feat: atualizar fluxo OT, dashboard, transacoes e PDFs
This commit is contained in:
@@ -1,8 +1,418 @@
|
||||
export default function DashboardPage() {
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { useQueries, useQuery } from '@tanstack/react-query'
|
||||
import { apiFetch } from '@/lib/api'
|
||||
import type { Client, Expense, Invoice, Staff, WorkOrder, WorkOrderDetail } from '@/lib/types'
|
||||
|
||||
const STATUS_LABEL: Record<WorkOrder['status'], string> = {
|
||||
quote: 'Orçamento',
|
||||
open: 'Aberta',
|
||||
in_progress: 'Em Curso',
|
||||
completed: 'Concluída',
|
||||
invoiced: 'Faturada',
|
||||
cancelled: 'Cancelada',
|
||||
}
|
||||
|
||||
const STATUS_ORDER: WorkOrder['status'][] = ['quote', 'open', 'in_progress', 'completed', 'invoiced', 'cancelled']
|
||||
type PeriodKey = 'month' | '30d' | '90d' | 'year'
|
||||
|
||||
const PERIOD_OPTIONS: { key: PeriodKey; label: string }[] = [
|
||||
{ key: 'month', label: 'Mês atual' },
|
||||
{ key: '30d', label: '30 dias' },
|
||||
{ key: '90d', label: '90 dias' },
|
||||
{ key: 'year', label: '12 meses' },
|
||||
]
|
||||
|
||||
function currency(v: number) {
|
||||
return new Intl.NumberFormat('pt-PT', { style: 'currency', currency: 'EUR' }).format(v)
|
||||
}
|
||||
|
||||
function monthKey(d: Date) {
|
||||
return `${d.getFullYear()}-${d.getMonth()}`
|
||||
}
|
||||
|
||||
function getPeriodStart(period: PeriodKey, now = new Date()) {
|
||||
const start = new Date(now)
|
||||
if (period === 'month') {
|
||||
start.setDate(1)
|
||||
start.setHours(0, 0, 0, 0)
|
||||
return start
|
||||
}
|
||||
if (period === '30d') {
|
||||
start.setDate(now.getDate() - 30)
|
||||
return start
|
||||
}
|
||||
if (period === '90d') {
|
||||
start.setDate(now.getDate() - 90)
|
||||
return start
|
||||
}
|
||||
start.setMonth(now.getMonth() - 12)
|
||||
return start
|
||||
}
|
||||
|
||||
function DashboardCard({
|
||||
title,
|
||||
value,
|
||||
subtitle,
|
||||
}: {
|
||||
title: string
|
||||
value: string
|
||||
subtitle: string
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
|
||||
<p className="text-gray-500 mt-1 text-sm">Bem-vindo ao TechXCar — implementado no Plano 5</p>
|
||||
</div>
|
||||
<article className="rounded-2xl border border-slate-700/70 bg-slate-900/65 p-4 transition-colors hover:border-slate-500/80">
|
||||
<p className="text-[11px] uppercase tracking-[0.14em] text-slate-400">{title}</p>
|
||||
<p className="mt-2 text-2xl font-semibold text-white [font-family:'Space_Grotesk',ui-sans-serif,sans-serif]">
|
||||
{value}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-slate-400">{subtitle}</p>
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const [period, setPeriod] = useState<PeriodKey>('month')
|
||||
|
||||
const workOrdersQ = useQuery<WorkOrder[]>({
|
||||
queryKey: ['work-orders'],
|
||||
queryFn: () => apiFetch<WorkOrder[]>('/work-orders'),
|
||||
})
|
||||
|
||||
const invoicesQ = useQuery<Invoice[]>({
|
||||
queryKey: ['invoices'],
|
||||
queryFn: () => apiFetch<Invoice[]>('/invoices'),
|
||||
})
|
||||
|
||||
const expensesQ = useQuery<Expense[]>({
|
||||
queryKey: ['expenses'],
|
||||
queryFn: () => apiFetch<Expense[]>('/expenses'),
|
||||
})
|
||||
|
||||
const staffQ = useQuery<Staff[]>({
|
||||
queryKey: ['staff'],
|
||||
queryFn: () => apiFetch<Staff[]>('/staff'),
|
||||
})
|
||||
|
||||
const clientsQ = useQuery<Client[]>({
|
||||
queryKey: ['clients'],
|
||||
queryFn: () => apiFetch<Client[]>('/clients'),
|
||||
})
|
||||
|
||||
const workOrders = workOrdersQ.data ?? []
|
||||
const invoices = invoicesQ.data ?? []
|
||||
const expenses = expensesQ.data ?? []
|
||||
const staff = staffQ.data ?? []
|
||||
const clients = clientsQ.data ?? []
|
||||
const invoiceDocs = invoices.filter((doc) => doc.type === 'invoice')
|
||||
|
||||
const invoiceTotalsQ = useQueries({
|
||||
queries: invoiceDocs.map((doc) => ({
|
||||
queryKey: ['work-order-detail', doc.work_order_id, 'dashboard-total'],
|
||||
queryFn: () => apiFetch<WorkOrderDetail>(`/work-orders/${doc.work_order_id}`),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
})),
|
||||
})
|
||||
|
||||
const isLoading = [workOrdersQ, invoicesQ, expensesQ, staffQ, clientsQ].some((q) => q.isLoading)
|
||||
const hasError = [workOrdersQ, invoicesQ, expensesQ, staffQ, clientsQ].some((q) => q.isError)
|
||||
const entriesLoading = invoiceTotalsQ.some((q) => q.isLoading)
|
||||
const entriesError = invoiceTotalsQ.some((q) => q.isError)
|
||||
|
||||
const workOrderTotals = useMemo(() => {
|
||||
const totals: Record<string, number> = {}
|
||||
for (let i = 0; i < invoiceDocs.length; i++) {
|
||||
const q = invoiceTotalsQ[i]
|
||||
const doc = invoiceDocs[i]
|
||||
if (!q?.data || !doc) continue
|
||||
const items = q.data.items.reduce((sum, item) => sum + item.total, 0)
|
||||
const hours = q.data.staff_hours.reduce((sum, h) => sum + h.total, 0)
|
||||
totals[doc.work_order_id] = items + hours
|
||||
}
|
||||
return totals
|
||||
}, [invoiceDocs, invoiceTotalsQ])
|
||||
|
||||
const metrics = useMemo(() => {
|
||||
const now = new Date()
|
||||
const periodStart = getPeriodStart(period, now)
|
||||
|
||||
const workOrdersPeriod = workOrders.filter((wo) => new Date(wo.created_at) >= periodStart)
|
||||
const invoicesPeriod = invoices.filter((inv) => new Date(inv.issued_at) >= periodStart)
|
||||
const expensesPeriod = expenses.filter((exp) => new Date(exp.date) >= periodStart)
|
||||
const invoicesMonth = invoices.filter((inv) => monthKey(new Date(inv.issued_at)) === monthKey(now))
|
||||
const expensesMonth = expenses.filter((exp) => monthKey(new Date(exp.date)) === monthKey(now))
|
||||
|
||||
const byStatus = Object.fromEntries(STATUS_ORDER.map((s) => [s, 0])) as Record<WorkOrder['status'], number>
|
||||
for (const wo of workOrdersPeriod) byStatus[wo.status] += 1
|
||||
|
||||
const activeOrders = byStatus.quote + byStatus.open + byStatus.in_progress
|
||||
const periodExpenses = expensesPeriod.reduce((sum, e) => sum + e.amount, 0)
|
||||
const monthExpenses = expensesMonth.reduce((sum, e) => sum + e.amount, 0)
|
||||
const monthDocs = invoicesMonth.length
|
||||
const activeStaff = staff.filter((s) => s.active).length
|
||||
const periodEntries = invoicesPeriod
|
||||
.filter((inv) => inv.type === 'invoice')
|
||||
.reduce((sum, inv) => sum + (workOrderTotals[inv.work_order_id] ?? 0), 0)
|
||||
const monthEntries = invoicesMonth
|
||||
.filter((inv) => inv.type === 'invoice')
|
||||
.reduce((sum, inv) => sum + (workOrderTotals[inv.work_order_id] ?? 0), 0)
|
||||
|
||||
const recentOrders = [...workOrdersPeriod]
|
||||
.sort((a, b) => +new Date(b.updated_at) - +new Date(a.updated_at))
|
||||
.slice(0, 6)
|
||||
|
||||
const recentDocs = [...invoicesPeriod]
|
||||
.sort((a, b) => +new Date(b.issued_at) - +new Date(a.issued_at))
|
||||
.slice(0, 6)
|
||||
|
||||
return {
|
||||
byStatus,
|
||||
activeOrders,
|
||||
periodExpenses,
|
||||
periodEntries,
|
||||
monthEntries,
|
||||
monthExpenses,
|
||||
monthDocs,
|
||||
activeStaff,
|
||||
recentOrders,
|
||||
recentDocs,
|
||||
periodOrdersCount: workOrdersPeriod.length,
|
||||
periodDocsCount: invoicesPeriod.length,
|
||||
}
|
||||
}, [period, workOrders, invoices, expenses, staff, workOrderTotals])
|
||||
|
||||
const entriesVsExpensesMax = Math.max(metrics.periodEntries, metrics.periodExpenses, 1)
|
||||
const entriesBarWidth = (metrics.periodEntries / entriesVsExpensesMax) * 100
|
||||
const expensesBarWidth = (metrics.periodExpenses / entriesVsExpensesMax) * 100
|
||||
|
||||
return (
|
||||
<section className="space-y-6 [font-family:'Sora',ui-sans-serif,sans-serif]">
|
||||
<header className="relative overflow-hidden rounded-2xl border border-slate-700/60 bg-gradient-to-br from-slate-900 via-slate-900 to-sky-950/35 p-6">
|
||||
<div className="absolute -right-16 -top-16 h-44 w-44 rounded-full bg-cyan-600/10 blur-2xl" />
|
||||
<div className="absolute -left-12 bottom-0 h-32 w-32 rounded-full bg-amber-500/10 blur-2xl" />
|
||||
<p className="text-xs uppercase tracking-[0.2em] text-slate-400">Painel Operacional</p>
|
||||
<h1 className="mt-1 text-3xl font-semibold text-white [font-family:'Space_Grotesk',ui-sans-serif,sans-serif]">
|
||||
Dashboard da Oficina
|
||||
</h1>
|
||||
<p className="mt-2 max-w-2xl text-sm text-slate-300">
|
||||
Visão rápida do trabalho em curso, faturação e despesas para apoiar as decisões do dia.
|
||||
</p>
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
{PERIOD_OPTIONS.map((opt) => (
|
||||
<button
|
||||
key={opt.key}
|
||||
onClick={() => setPeriod(opt.key)}
|
||||
className={`rounded-md border px-3 py-1.5 text-xs transition-colors ${
|
||||
period === opt.key
|
||||
? 'border-cyan-400/80 bg-cyan-500/20 text-cyan-100'
|
||||
: 'border-slate-700 bg-slate-900/80 text-slate-300 hover:border-slate-500 hover:text-white'
|
||||
}`}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{isLoading && (
|
||||
<p className="rounded-xl border border-slate-700 bg-slate-900/60 px-4 py-3 text-sm text-slate-300">
|
||||
A carregar métricas do dashboard...
|
||||
</p>
|
||||
)}
|
||||
|
||||
{hasError && !isLoading && (
|
||||
<p className="rounded-xl border border-red-900/80 bg-red-950/40 px-4 py-3 text-sm text-red-200">
|
||||
Alguns dados não foram carregados. As métricas visíveis podem estar incompletas.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
|
||||
<DashboardCard
|
||||
title="OTs Ativas"
|
||||
value={String(metrics.activeOrders)}
|
||||
subtitle={`No período (${metrics.periodOrdersCount} OTs)`}
|
||||
/>
|
||||
<DashboardCard
|
||||
title="Clientes"
|
||||
value={String(clients.length)}
|
||||
subtitle="Base total de clientes"
|
||||
/>
|
||||
<DashboardCard
|
||||
title="Técnicos Ativos"
|
||||
value={`${metrics.activeStaff}/${staff.length}`}
|
||||
subtitle="Recursos disponíveis"
|
||||
/>
|
||||
<DashboardCard
|
||||
title="Despesas do Período"
|
||||
value={currency(metrics.periodExpenses)}
|
||||
subtitle="Somatório no filtro selecionado"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<article className="rounded-2xl border border-slate-700/70 bg-slate-900/65 p-5">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="text-base font-semibold text-white">Entradas Recebidas vs Despesas</h2>
|
||||
<span className="text-xs text-slate-400">
|
||||
{PERIOD_OPTIONS.find((p) => p.key === period)?.label}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="rounded-lg border border-emerald-800/60 bg-emerald-950/20 p-3">
|
||||
<p className="text-xs uppercase tracking-wide text-emerald-300">Entradas (faturas)</p>
|
||||
<p className="mt-1 text-2xl font-semibold text-white">{currency(metrics.periodEntries)}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-rose-800/60 bg-rose-950/20 p-3">
|
||||
<p className="text-xs uppercase tracking-wide text-rose-300">Despesas</p>
|
||||
<p className="mt-1 text-2xl font-semibold text-white">{currency(metrics.periodExpenses)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 space-y-3">
|
||||
<div>
|
||||
<div className="mb-1 flex justify-between text-xs">
|
||||
<span className="text-slate-300">Entradas recebidas</span>
|
||||
<span className="font-mono text-emerald-300">{currency(metrics.periodEntries)}</span>
|
||||
</div>
|
||||
<div className="h-3 rounded-full bg-slate-800">
|
||||
<div className="h-3 rounded-full bg-gradient-to-r from-emerald-500 to-teal-400" style={{ width: `${entriesBarWidth}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-1 flex justify-between text-xs">
|
||||
<span className="text-slate-300">Despesas registadas</span>
|
||||
<span className="font-mono text-rose-300">{currency(metrics.periodExpenses)}</span>
|
||||
</div>
|
||||
<div className="h-3 rounded-full bg-slate-800">
|
||||
<div className="h-3 rounded-full bg-gradient-to-r from-rose-500 to-orange-400" style={{ width: `${expensesBarWidth}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-4 text-sm text-slate-300">
|
||||
Saldo estimado: <span className={metrics.periodEntries - metrics.periodExpenses >= 0 ? 'text-emerald-300' : 'text-rose-300'}>
|
||||
{currency(metrics.periodEntries - metrics.periodExpenses)}
|
||||
</span>
|
||||
</p>
|
||||
{(entriesLoading || entriesError) && (
|
||||
<p className="mt-2 text-xs text-slate-400">
|
||||
{entriesLoading ? 'A calcular totais de entradas...' : 'Algumas entradas não puderam ser calculadas.'}
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
|
||||
<div className="grid items-stretch gap-4 xl:grid-cols-2">
|
||||
<article className="h-full rounded-2xl border border-slate-700/70 bg-slate-900/65 p-5">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="text-base font-semibold text-white">Fluxo das Ordens de Trabalho</h2>
|
||||
<Link to="/app/work-orders" className="text-xs text-cyan-300 hover:text-cyan-200">
|
||||
Ver todas
|
||||
</Link>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{STATUS_ORDER.map((status) => {
|
||||
const count = metrics.byStatus[status]
|
||||
const total = Math.max(metrics.periodOrdersCount, 1)
|
||||
const width = Math.max((count / total) * 100, count > 0 ? 6 : 0)
|
||||
return (
|
||||
<div key={status}>
|
||||
<div className="mb-1 flex justify-between text-xs">
|
||||
<span className="text-slate-300">{STATUS_LABEL[status]}</span>
|
||||
<span className="font-mono text-slate-400">{count}</span>
|
||||
</div>
|
||||
<div className="h-2 rounded-full bg-slate-800">
|
||||
<div className="h-2 rounded-full bg-gradient-to-r from-cyan-500 to-emerald-500" style={{ width: `${width}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article className="h-full rounded-2xl border border-slate-700/70 bg-slate-900/65 p-5">
|
||||
<h2 className="text-base font-semibold text-white">Faturação e Prioridades</h2>
|
||||
<div className="mt-4 space-y-3 text-sm">
|
||||
<div className="rounded-lg border border-slate-700 bg-slate-900/70 px-3 py-2">
|
||||
<p className="text-slate-400">Documentos emitidos no período</p>
|
||||
<p className="text-xl font-semibold text-white">{metrics.periodDocsCount}</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-amber-800/70 bg-amber-950/30 px-3 py-2 text-amber-100">
|
||||
<p className="text-xs uppercase tracking-wide">Ação recomendada</p>
|
||||
<p className="mt-1">
|
||||
{metrics.byStatus.completed > 0
|
||||
? `${metrics.byStatus.completed} OT(s) concluída(s) pronta(s) para faturar.`
|
||||
: 'Sem OTs concluídas pendentes de faturação.'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-cyan-900/70 bg-cyan-950/25 px-3 py-2 text-cyan-100">
|
||||
<p className="text-xs uppercase tracking-wide">Em orçamento</p>
|
||||
<p className="mt-1">
|
||||
{metrics.byStatus.quote > 0
|
||||
? `${metrics.byStatus.quote} OT(s) em orçamento aguardam aprovação.`
|
||||
: 'Não existem OTs pendentes em orçamento.'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-lg border border-slate-700 bg-slate-900/70 px-3 py-2">
|
||||
<p className="text-slate-400">Contexto mensal</p>
|
||||
<p className="text-slate-200 mt-1 text-xs">
|
||||
Entradas no mês: {currency(metrics.monthEntries)} | Despesas no mês: {currency(metrics.monthExpenses)} | Documentos: {metrics.monthDocs}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
<article className="rounded-2xl border border-slate-700/70 bg-slate-900/65 p-5">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h2 className="text-base font-semibold text-white">Atividade Recente de OTs</h2>
|
||||
<Link to="/app/work-orders" className="text-xs text-cyan-300 hover:text-cyan-200">
|
||||
Abrir OTs
|
||||
</Link>
|
||||
</div>
|
||||
{metrics.recentOrders.length === 0 ? (
|
||||
<p className="text-sm text-slate-400">Ainda não existem ordens de trabalho.</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-slate-800">
|
||||
{metrics.recentOrders.map((wo) => (
|
||||
<li key={wo.id} className="flex items-center justify-between py-2">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">OT #{wo.number}</p>
|
||||
<p className="text-xs text-slate-400">{STATUS_LABEL[wo.status]}</p>
|
||||
</div>
|
||||
<span className="text-xs text-slate-500">
|
||||
{new Intl.DateTimeFormat('pt-PT', { dateStyle: 'short', timeStyle: 'short' }).format(new Date(wo.updated_at))}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</article>
|
||||
|
||||
<article className="rounded-2xl border border-slate-700/70 bg-slate-900/65 p-5">
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<h2 className="text-base font-semibold text-white">Documentos Recentes</h2>
|
||||
<Link to="/app/invoices" className="text-xs text-cyan-300 hover:text-cyan-200">
|
||||
Abrir Faturação
|
||||
</Link>
|
||||
</div>
|
||||
{metrics.recentDocs.length === 0 ? (
|
||||
<p className="text-sm text-slate-400">Sem documentos emitidos.</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-slate-800">
|
||||
{metrics.recentDocs.map((doc) => (
|
||||
<li key={doc.id} className="flex items-center justify-between py-2">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">
|
||||
{doc.type === 'invoice' ? 'Fatura' : 'Orçamento'} #{doc.number}
|
||||
</p>
|
||||
<p className="text-xs text-slate-400 font-mono">OT {doc.work_order_id.slice(0, 8)}...</p>
|
||||
</div>
|
||||
<span className="text-xs text-slate-500">
|
||||
{new Intl.DateTimeFormat('pt-PT', { dateStyle: 'short' }).format(new Date(doc.issued_at))}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user