Add repairs domain with tickets, line items, batches, and service templates

Full-stack implementation of instrument repair tracking: DB schema with
repair_ticket, repair_line_item, repair_batch, and repair_service_template
tables. Backend services and routes with pagination/search/sort. 20 API
tests covering CRUD, status workflow, line items, and batch operations.
Admin frontend with ticket list, detail with status progression, line item
management, batch list/detail with approval workflow, and new ticket form
with searchable account picker and intake photo uploads.
This commit is contained in:
Ryan Moon
2026-03-29 09:12:40 -05:00
parent 1d48f0befa
commit f17bbff02c
20 changed files with 2791 additions and 1 deletions

View File

@@ -0,0 +1,160 @@
import { createFileRoute, useParams, useNavigate } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { repairBatchDetailOptions, repairBatchMutations, repairBatchKeys, repairBatchTicketsOptions } from '@/api/repairs'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { ArrowLeft, Check, X } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth.store'
import type { RepairTicket } from '@/types/repair'
export const Route = createFileRoute('/_authenticated/repair-batches/$batchId')({
validateSearch: (search: Record<string, unknown>) => ({
page: Number(search.page) || 1,
limit: Number(search.limit) || 25,
q: (search.q as string) || undefined,
sort: (search.sort as string) || undefined,
order: (search.order as 'asc' | 'desc') || 'asc',
}),
component: RepairBatchDetailPage,
})
const ticketColumns: Column<RepairTicket>[] = [
{ key: 'ticket_number', header: 'Ticket #', sortable: true, render: (t) => <span className="font-mono text-sm">{t.ticketNumber}</span> },
{ key: 'customer_name', header: 'Instrument', render: (t) => <>{t.instrumentDescription ?? '-'}</> },
{ key: 'status', header: 'Status', sortable: true, render: (t) => <Badge variant="outline">{t.status.replace('_', ' ')}</Badge> },
{ key: 'problem', header: 'Problem', render: (t) => <span className="truncate max-w-[200px] block">{t.problemDescription}</span> },
]
function RepairBatchDetailPage() {
const { batchId } = useParams({ from: '/_authenticated/repair-batches/$batchId' })
const navigate = useNavigate()
const queryClient = useQueryClient()
const hasPermission = useAuthStore((s) => s.hasPermission)
const { params, setPage, setSort } = usePagination()
const { data: batch, isLoading } = useQuery(repairBatchDetailOptions(batchId))
const { data: ticketsData, isLoading: ticketsLoading } = useQuery(repairBatchTicketsOptions(batchId, params))
const approveMutation = useMutation({
mutationFn: () => repairBatchMutations.approve(batchId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairBatchKeys.detail(batchId) })
toast.success('Batch approved')
},
onError: (err) => toast.error(err.message),
})
const rejectMutation = useMutation({
mutationFn: () => repairBatchMutations.reject(batchId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairBatchKeys.detail(batchId) })
toast.success('Batch rejected')
},
onError: (err) => toast.error(err.message),
})
const statusMutation = useMutation({
mutationFn: (status: string) => repairBatchMutations.updateStatus(batchId, status),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairBatchKeys.detail(batchId) })
toast.success('Status updated')
},
onError: (err) => toast.error(err.message),
})
if (isLoading) {
return <div className="space-y-4"><Skeleton className="h-8 w-48" /><Skeleton className="h-64 w-full" /></div>
}
if (!batch) {
return <p className="text-muted-foreground">Batch not found</p>
}
function handleTicketClick(ticket: RepairTicket) {
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
}
return (
<div className="space-y-6 max-w-4xl">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div className="flex-1">
<h1 className="text-2xl font-bold">Batch #{batch.batchNumber}</h1>
<p className="text-sm text-muted-foreground">{batch.contactName ?? 'No contact'}</p>
</div>
<Badge variant="outline" className="text-sm px-3 py-1">{batch.status.replace('_', ' ')}</Badge>
<Badge variant={batch.approvalStatus === 'approved' ? 'default' : batch.approvalStatus === 'rejected' ? 'destructive' : 'secondary'} className="text-sm px-3 py-1">
{batch.approvalStatus}
</Badge>
</div>
{/* Actions */}
<div className="flex gap-2">
{hasPermission('repairs.admin') && batch.approvalStatus === 'pending' && (
<>
<Button onClick={() => approveMutation.mutate()} disabled={approveMutation.isPending}>
<Check className="mr-2 h-4 w-4" />Approve
</Button>
<Button variant="destructive" onClick={() => rejectMutation.mutate()} disabled={rejectMutation.isPending}>
<X className="mr-2 h-4 w-4" />Reject
</Button>
</>
)}
{hasPermission('repairs.edit') && batch.status === 'intake' && (
<Button variant="secondary" onClick={() => statusMutation.mutate('in_progress')}>Start Work</Button>
)}
{hasPermission('repairs.edit') && batch.status === 'in_progress' && (
<Button variant="secondary" onClick={() => statusMutation.mutate('completed')}>Mark Completed</Button>
)}
</div>
{/* Batch Info */}
<div className="grid grid-cols-2 gap-6">
<Card>
<CardHeader><CardTitle className="text-lg">Contact</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Name:</span> {batch.contactName ?? '-'}</div>
<div><span className="text-muted-foreground">Phone:</span> {batch.contactPhone ?? '-'}</div>
<div><span className="text-muted-foreground">Email:</span> {batch.contactEmail ?? '-'}</div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-lg">Details</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Instruments:</span> {batch.receivedCount}/{batch.instrumentCount}</div>
<div><span className="text-muted-foreground">Due:</span> {batch.dueDate ? new Date(batch.dueDate).toLocaleDateString() : '-'}</div>
<div><span className="text-muted-foreground">Estimated Total:</span> {batch.estimatedTotal ? `$${batch.estimatedTotal}` : '-'}</div>
{batch.notes && <div><span className="text-muted-foreground">Notes:</span> {batch.notes}</div>}
</CardContent>
</Card>
</div>
{/* Tickets in batch */}
<Card>
<CardHeader><CardTitle className="text-lg">Tickets ({ticketsData?.pagination.total ?? 0})</CardTitle></CardHeader>
<CardContent>
<DataTable
columns={ticketColumns}
data={ticketsData?.data ?? []}
loading={ticketsLoading}
page={params.page}
totalPages={ticketsData?.pagination.totalPages ?? 1}
total={ticketsData?.pagination.total ?? 0}
sort={params.sort}
order={params.order}
onPageChange={setPage}
onSort={setSort}
onRowClick={handleTicketClick}
/>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,121 @@
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { repairBatchListOptions } from '@/api/repairs'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Plus, Search } from 'lucide-react'
import { useAuthStore } from '@/stores/auth.store'
import type { RepairBatch } from '@/types/repair'
export const Route = createFileRoute('/_authenticated/repair-batches/')({
validateSearch: (search: Record<string, unknown>) => ({
page: Number(search.page) || 1,
limit: Number(search.limit) || 25,
q: (search.q as string) || undefined,
sort: (search.sort as string) || undefined,
order: (search.order as 'asc' | 'desc') || 'desc',
}),
component: RepairBatchesListPage,
})
const columns: Column<RepairBatch>[] = [
{
key: 'batch_number',
header: 'Batch #',
sortable: true,
render: (b) => <span className="font-mono text-sm">{b.batchNumber ?? '-'}</span>,
},
{
key: 'contact',
header: 'Contact',
render: (b) => <span className="font-medium">{b.contactName ?? '-'}</span>,
},
{
key: 'status',
header: 'Status',
sortable: true,
render: (b) => <Badge variant="outline">{b.status.replace('_', ' ')}</Badge>,
},
{
key: 'approval',
header: 'Approval',
render: (b) => {
const v = b.approvalStatus === 'approved' ? 'default' : b.approvalStatus === 'rejected' ? 'destructive' : 'secondary'
return <Badge variant={v}>{b.approvalStatus}</Badge>
},
},
{
key: 'instruments',
header: 'Instruments',
render: (b) => <>{b.receivedCount}/{b.instrumentCount}</>,
},
{
key: 'due_date',
header: 'Due',
sortable: true,
render: (b) => <>{b.dueDate ? new Date(b.dueDate).toLocaleDateString() : '-'}</>,
},
]
function RepairBatchesListPage() {
const navigate = useNavigate()
const hasPermission = useAuthStore((s) => s.hasPermission)
const { params, setPage, setSearch, setSort } = usePagination()
const [searchInput, setSearchInput] = useState(params.q ?? '')
const { data, isLoading } = useQuery(repairBatchListOptions(params))
function handleSearchSubmit(e: React.FormEvent) {
e.preventDefault()
setSearch(searchInput)
}
function handleRowClick(batch: RepairBatch) {
navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: {} as any })
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Repair Batches</h1>
{hasPermission('repairs.edit') && (
<Button onClick={() => navigate({ to: '/repair-batches/new' })}>
<Plus className="mr-2 h-4 w-4" />
New Batch
</Button>
)}
</div>
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search batches..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="pl-9"
/>
</div>
<Button type="submit" variant="secondary">Search</Button>
</form>
<DataTable
columns={columns}
data={data?.data ?? []}
loading={isLoading}
page={params.page}
totalPages={data?.pagination.totalPages ?? 1}
total={data?.pagination.total ?? 0}
sort={params.sort}
order={params.order}
onPageChange={setPage}
onSort={setSort}
onRowClick={handleRowClick}
/>
</div>
)
}

View File

@@ -0,0 +1,124 @@
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useQuery, useMutation } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { RepairBatchCreateSchema } from '@forte/shared/schemas'
import { repairBatchMutations } from '@/api/repairs'
import { accountListOptions } from '@/api/accounts'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ArrowLeft } from 'lucide-react'
import { toast } from 'sonner'
export const Route = createFileRoute('/_authenticated/repair-batches/new')({
component: NewRepairBatchPage,
})
function NewRepairBatchPage() {
const navigate = useNavigate()
const { data: accountsData } = useQuery(accountListOptions({ page: 1, limit: 100, order: 'asc', sort: 'name' }))
const {
register,
handleSubmit,
setValue,
formState: { errors },
} = useForm({
resolver: zodResolver(RepairBatchCreateSchema),
defaultValues: {
accountId: '',
contactName: '',
contactPhone: '',
contactEmail: '',
instrumentCount: 0,
notes: '',
},
})
const mutation = useMutation({
mutationFn: repairBatchMutations.create,
onSuccess: (batch) => {
toast.success('Repair batch created')
navigate({ to: '/repair-batches/$batchId', params: { batchId: batch.id }, search: {} as any })
},
onError: (err) => toast.error(err.message),
})
const accounts = accountsData?.data ?? []
return (
<div className="space-y-6 max-w-2xl">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
<ArrowLeft className="h-4 w-4" />
</Button>
<h1 className="text-2xl font-bold">New Repair Batch</h1>
</div>
<Card>
<CardHeader>
<CardTitle className="text-lg">Batch Details</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-4">
<div className="space-y-2">
<Label>Account (School) *</Label>
<Select onValueChange={(v) => setValue('accountId', v)}>
<SelectTrigger>
<SelectValue placeholder="Select account" />
</SelectTrigger>
<SelectContent>
{accounts.map((a: { id: string; name: string }) => (
<SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
))}
</SelectContent>
</Select>
{errors.accountId && <p className="text-sm text-destructive">{errors.accountId.message}</p>}
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Contact Name</Label>
<Input {...register('contactName')} />
</div>
<div className="space-y-2">
<Label>Contact Phone</Label>
<Input {...register('contactPhone')} />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Contact Email</Label>
<Input type="email" {...register('contactEmail')} />
</div>
<div className="space-y-2">
<Label>Instrument Count</Label>
<Input type="number" {...register('instrumentCount', { valueAsNumber: true })} />
</div>
</div>
<div className="space-y-2">
<Label>Notes</Label>
<Textarea {...register('notes')} rows={3} placeholder="e.g. Annual instrument checkup for band program" />
</div>
<div className="flex gap-2">
<Button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? 'Creating...' : 'Create Batch'}
</Button>
<Button variant="secondary" type="button" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
Cancel
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,284 @@
import { useState } from 'react'
import { createFileRoute, useParams, useNavigate } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { repairTicketDetailOptions, repairTicketMutations, repairTicketKeys, repairLineItemListOptions, repairLineItemMutations, repairLineItemKeys } from '@/api/repairs'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Skeleton } from '@/components/ui/skeleton'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { ArrowLeft, Plus, Trash2 } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth.store'
import type { RepairLineItem } from '@/types/repair'
export const Route = createFileRoute('/_authenticated/repairs/$ticketId')({
validateSearch: (search: Record<string, unknown>) => ({
page: Number(search.page) || 1,
limit: Number(search.limit) || 25,
q: (search.q as string) || undefined,
sort: (search.sort as string) || undefined,
order: (search.order as 'asc' | 'desc') || 'asc',
}),
component: RepairTicketDetailPage,
})
const STATUS_LABELS: Record<string, string> = {
intake: 'Intake',
diagnosing: 'Diagnosing',
pending_approval: 'Pending Approval',
approved: 'Approved',
in_progress: 'In Progress',
pending_parts: 'Pending Parts',
ready: 'Ready for Pickup',
picked_up: 'Picked Up',
delivered: 'Delivered',
cancelled: 'Cancelled',
}
const STATUS_FLOW = ['intake', 'diagnosing', 'pending_approval', 'approved', 'in_progress', 'ready', 'picked_up']
function RepairTicketDetailPage() {
const { ticketId } = useParams({ from: '/_authenticated/repairs/$ticketId' })
const navigate = useNavigate()
const queryClient = useQueryClient()
const hasPermission = useAuthStore((s) => s.hasPermission)
const [addItemOpen, setAddItemOpen] = useState(false)
const { params, setPage, setSort } = usePagination()
const { data: ticket, isLoading } = useQuery(repairTicketDetailOptions(ticketId))
const { data: lineItemsData, isLoading: itemsLoading } = useQuery(repairLineItemListOptions(ticketId, params))
const statusMutation = useMutation({
mutationFn: (status: string) => repairTicketMutations.updateStatus(ticketId, status),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairTicketKeys.detail(ticketId) })
toast.success('Status updated')
},
onError: (err) => toast.error(err.message),
})
const deleteItemMutation = useMutation({
mutationFn: repairLineItemMutations.delete,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairLineItemKeys.all(ticketId) })
toast.success('Line item removed')
},
onError: (err) => toast.error(err.message),
})
if (isLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-64 w-full" />
</div>
)
}
if (!ticket) {
return <p className="text-muted-foreground">Repair ticket not found</p>
}
const currentIdx = STATUS_FLOW.indexOf(ticket.status)
const nextStatus = currentIdx >= 0 && currentIdx < STATUS_FLOW.length - 1 ? STATUS_FLOW[currentIdx + 1] : null
const lineItemColumns: Column<RepairLineItem>[] = [
{
key: 'item_type',
header: 'Type',
sortable: true,
render: (i) => <Badge variant="outline">{i.itemType.replace('_', ' ')}</Badge>,
},
{ key: 'description', header: 'Description', render: (i) => <>{i.description}</> },
{ key: 'qty', header: 'Qty', render: (i) => <>{i.qty}</> },
{ key: 'unit_price', header: 'Unit Price', render: (i) => <>${i.unitPrice}</> },
{ key: 'total_price', header: 'Total', render: (i) => <span className="font-medium">${i.totalPrice}</span> },
{
key: 'actions',
header: '',
render: (i) => hasPermission('repairs.admin') ? (
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); deleteItemMutation.mutate(i.id) }}>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
) : null,
},
]
return (
<div className="space-y-6 max-w-4xl">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repairs', search: {} as any })}>
<ArrowLeft className="h-4 w-4" />
</Button>
<div className="flex-1">
<h1 className="text-2xl font-bold">Ticket #{ticket.ticketNumber}</h1>
<p className="text-sm text-muted-foreground">{ticket.customerName}</p>
</div>
<Badge variant={ticket.status === 'cancelled' ? 'destructive' : 'default'} className="text-sm px-3 py-1">
{STATUS_LABELS[ticket.status]}
</Badge>
</div>
{/* Status Actions */}
{hasPermission('repairs.edit') && ticket.status !== 'cancelled' && ticket.status !== 'picked_up' && ticket.status !== 'delivered' && (
<div className="flex gap-2">
{nextStatus && (
<Button onClick={() => statusMutation.mutate(nextStatus)} disabled={statusMutation.isPending}>
Move to {STATUS_LABELS[nextStatus]}
</Button>
)}
{ticket.status === 'in_progress' && (
<Button variant="secondary" onClick={() => statusMutation.mutate('pending_parts')} disabled={statusMutation.isPending}>
Pending Parts
</Button>
)}
{hasPermission('repairs.admin') && (
<Button variant="destructive" onClick={() => statusMutation.mutate('cancelled')} disabled={statusMutation.isPending}>
Cancel
</Button>
)}
</div>
)}
{/* Ticket Details */}
<div className="grid grid-cols-2 gap-6">
<Card>
<CardHeader><CardTitle className="text-lg">Customer</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Name:</span> {ticket.customerName}</div>
<div><span className="text-muted-foreground">Phone:</span> {ticket.customerPhone ?? '-'}</div>
<div><span className="text-muted-foreground">Account:</span> {ticket.accountId ?? 'Walk-in'}</div>
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-lg">Instrument</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Description:</span> {ticket.instrumentDescription ?? '-'}</div>
<div><span className="text-muted-foreground">Serial:</span> {ticket.serialNumber ?? '-'}</div>
<div><span className="text-muted-foreground">Condition:</span> {ticket.conditionIn ?? '-'}</div>
</CardContent>
</Card>
</div>
<Card>
<CardHeader><CardTitle className="text-lg">Problem & Notes</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
<div><span className="text-muted-foreground">Problem:</span> {ticket.problemDescription}</div>
{ticket.conditionInNotes && <div><span className="text-muted-foreground">Condition Notes:</span> {ticket.conditionInNotes}</div>}
{ticket.technicianNotes && <div><span className="text-muted-foreground">Tech Notes:</span> {ticket.technicianNotes}</div>}
<div className="flex gap-6 pt-2">
<div><span className="text-muted-foreground">Estimate:</span> {ticket.estimatedCost ? `$${ticket.estimatedCost}` : '-'}</div>
<div><span className="text-muted-foreground">Actual:</span> {ticket.actualCost ? `$${ticket.actualCost}` : '-'}</div>
<div><span className="text-muted-foreground">Promised:</span> {ticket.promisedDate ? new Date(ticket.promisedDate).toLocaleDateString() : '-'}</div>
</div>
</CardContent>
</Card>
{/* Line Items */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="text-lg">Line Items</CardTitle>
{hasPermission('repairs.edit') && (
<AddLineItemDialog ticketId={ticketId} open={addItemOpen} onOpenChange={setAddItemOpen} />
)}
</CardHeader>
<CardContent>
<DataTable
columns={lineItemColumns}
data={lineItemsData?.data ?? []}
loading={itemsLoading}
page={params.page}
totalPages={lineItemsData?.pagination.totalPages ?? 1}
total={lineItemsData?.pagination.total ?? 0}
sort={params.sort}
order={params.order}
onPageChange={setPage}
onSort={setSort}
/>
</CardContent>
</Card>
</div>
)
}
function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string; open: boolean; onOpenChange: (open: boolean) => void }) {
const queryClient = useQueryClient()
const [itemType, setItemType] = useState('labor')
const [description, setDescription] = useState('')
const [qty, setQty] = useState('1')
const [unitPrice, setUnitPrice] = useState('0')
const mutation = useMutation({
mutationFn: (data: Record<string, unknown>) => repairLineItemMutations.create(ticketId, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repairLineItemKeys.all(ticketId) })
toast.success('Line item added')
onOpenChange(false)
setDescription('')
setQty('1')
setUnitPrice('0')
},
onError: (err) => toast.error(err.message),
})
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
const q = parseFloat(qty) || 1
const up = parseFloat(unitPrice) || 0
mutation.mutate({
itemType,
description,
qty: q,
unitPrice: up,
totalPrice: q * up,
})
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogTrigger asChild>
<Button size="sm"><Plus className="mr-2 h-4 w-4" />Add Item</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader><DialogTitle>Add Line Item</DialogTitle></DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label>Type</Label>
<Select value={itemType} onValueChange={setItemType}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="labor">Labor</SelectItem>
<SelectItem value="part">Part</SelectItem>
<SelectItem value="flat_rate">Flat Rate</SelectItem>
<SelectItem value="misc">Misc</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Description *</Label>
<Input value={description} onChange={(e) => setDescription(e.target.value)} required />
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Qty</Label>
<Input type="number" step="0.001" value={qty} onChange={(e) => setQty(e.target.value)} />
</div>
<div className="space-y-2">
<Label>Unit Price</Label>
<Input type="number" step="0.01" value={unitPrice} onChange={(e) => setUnitPrice(e.target.value)} />
</div>
</div>
<Button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? 'Adding...' : 'Add'}
</Button>
</form>
</DialogContent>
</Dialog>
)
}

View File

@@ -0,0 +1,153 @@
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { repairTicketListOptions } from '@/api/repairs'
import { usePagination } from '@/hooks/use-pagination'
import { DataTable, type Column } from '@/components/shared/data-table'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Plus, Search } from 'lucide-react'
import { useAuthStore } from '@/stores/auth.store'
import type { RepairTicket } from '@/types/repair'
export const Route = createFileRoute('/_authenticated/repairs/')({
validateSearch: (search: Record<string, unknown>) => ({
page: Number(search.page) || 1,
limit: Number(search.limit) || 25,
q: (search.q as string) || undefined,
sort: (search.sort as string) || undefined,
order: (search.order as 'asc' | 'desc') || 'desc',
}),
component: RepairsListPage,
})
function statusBadge(status: string) {
const variants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
intake: 'outline',
diagnosing: 'secondary',
pending_approval: 'secondary',
approved: 'default',
in_progress: 'default',
pending_parts: 'secondary',
ready: 'default',
picked_up: 'outline',
delivered: 'outline',
cancelled: 'destructive',
}
const labels: Record<string, string> = {
intake: 'Intake',
diagnosing: 'Diagnosing',
pending_approval: 'Pending Approval',
approved: 'Approved',
in_progress: 'In Progress',
pending_parts: 'Pending Parts',
ready: 'Ready',
picked_up: 'Picked Up',
delivered: 'Delivered',
cancelled: 'Cancelled',
}
return <Badge variant={variants[status] ?? 'outline'}>{labels[status] ?? status}</Badge>
}
const columns: Column<RepairTicket>[] = [
{
key: 'ticket_number',
header: 'Ticket #',
sortable: true,
render: (t) => <span className="font-mono text-sm">{t.ticketNumber ?? '-'}</span>,
},
{
key: 'customer_name',
header: 'Customer',
sortable: true,
render: (t) => <span className="font-medium">{t.customerName}</span>,
},
{
key: 'instrument',
header: 'Instrument',
render: (t) => <>{t.instrumentDescription ?? '-'}</>,
},
{
key: 'status',
header: 'Status',
sortable: true,
render: (t) => statusBadge(t.status),
},
{
key: 'intake_date',
header: 'Intake',
sortable: true,
render: (t) => <>{new Date(t.intakeDate).toLocaleDateString()}</>,
},
{
key: 'promised_date',
header: 'Promised',
sortable: true,
render: (t) => <>{t.promisedDate ? new Date(t.promisedDate).toLocaleDateString() : '-'}</>,
},
{
key: 'estimated_cost',
header: 'Estimate',
render: (t) => <>{t.estimatedCost ? `$${t.estimatedCost}` : '-'}</>,
},
]
function RepairsListPage() {
const navigate = useNavigate()
const hasPermission = useAuthStore((s) => s.hasPermission)
const { params, setPage, setSearch, setSort } = usePagination()
const [searchInput, setSearchInput] = useState(params.q ?? '')
const { data, isLoading } = useQuery(repairTicketListOptions(params))
function handleSearchSubmit(e: React.FormEvent) {
e.preventDefault()
setSearch(searchInput)
}
function handleRowClick(ticket: RepairTicket) {
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Repairs</h1>
{hasPermission('repairs.edit') && (
<Button onClick={() => navigate({ to: '/repairs/new' })}>
<Plus className="mr-2 h-4 w-4" />
New Repair
</Button>
)}
</div>
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search repairs..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="pl-9"
/>
</div>
<Button type="submit" variant="secondary">Search</Button>
</form>
<DataTable
columns={columns}
data={data?.data ?? []}
loading={isLoading}
page={params.page}
totalPages={data?.pagination.totalPages ?? 1}
total={data?.pagination.total ?? 0}
sort={params.sort}
order={params.order}
onPageChange={setPage}
onSort={setSort}
onRowClick={handleRowClick}
/>
</div>
)
}

View File

@@ -0,0 +1,314 @@
import { useState, useRef } from 'react'
import { createFileRoute, useNavigate, Link } from '@tanstack/react-router'
import { useQuery, useMutation } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { RepairTicketCreateSchema } from '@forte/shared/schemas'
import { repairTicketMutations } from '@/api/repairs'
import { accountListOptions } from '@/api/accounts'
import { useAuthStore } from '@/stores/auth.store'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ArrowLeft, Search, Plus, Upload, X, ImageIcon } from 'lucide-react'
import { toast } from 'sonner'
import type { Account } from '@/types/account'
export const Route = createFileRoute('/_authenticated/repairs/new')({
component: NewRepairPage,
})
function NewRepairPage() {
const navigate = useNavigate()
const token = useAuthStore((s) => s.token)
// Account search
const [accountSearch, setAccountSearch] = useState('')
const [selectedAccount, setSelectedAccount] = useState<Account | null>(null)
const [showAccountDropdown, setShowAccountDropdown] = useState(false)
// Photos
const [photos, setPhotos] = useState<File[]>([])
const photoInputRef = useRef<HTMLInputElement>(null)
const { data: accountsData } = useQuery(
accountListOptions({ page: 1, limit: 20, q: accountSearch || undefined, order: 'asc', sort: 'name' }),
)
const {
register,
handleSubmit,
setValue,
watch,
formState: { errors },
} = useForm({
resolver: zodResolver(RepairTicketCreateSchema),
defaultValues: {
customerName: '',
customerPhone: '',
instrumentDescription: '',
serialNumber: '',
problemDescription: '',
conditionIn: undefined,
estimatedCost: undefined,
accountId: undefined,
},
})
const mutation = useMutation({
mutationFn: async (data: Record<string, unknown>) => {
const ticket = await repairTicketMutations.create(data)
// Upload photos after ticket creation
for (const photo of photos) {
const formData = new FormData()
formData.append('file', photo)
formData.append('entityType', 'repair_ticket')
formData.append('entityId', ticket.id)
formData.append('category', 'intake')
await fetch('/v1/files', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: formData,
})
}
return ticket
},
onSuccess: (ticket) => {
toast.success('Repair ticket created')
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
},
onError: (err) => toast.error(err.message),
})
function selectAccount(account: Account) {
setSelectedAccount(account)
setShowAccountDropdown(false)
setAccountSearch('')
setValue('accountId', account.id)
setValue('customerName', account.name)
setValue('customerPhone', account.phone ?? '')
}
function clearAccount() {
setSelectedAccount(null)
setValue('accountId', undefined)
setValue('customerName', '')
setValue('customerPhone', '')
}
function addPhotos(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files ?? [])
setPhotos((prev) => [...prev, ...files])
e.target.value = ''
}
function removePhoto(index: number) {
setPhotos((prev) => prev.filter((_, i) => i !== index))
}
const accounts = accountsData?.data ?? []
return (
<div className="space-y-6 max-w-4xl">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/repairs', search: {} as any })}>
<ArrowLeft className="h-4 w-4" />
</Button>
<h1 className="text-2xl font-bold">New Repair Ticket</h1>
</div>
<form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-6">
{/* Customer Section */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-lg">Customer</CardTitle>
<Link to="/accounts/new" className="text-sm text-primary hover:underline flex items-center gap-1">
<Plus className="h-3 w-3" />
New Account
</Link>
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* Account search */}
{!selectedAccount ? (
<div className="relative">
<Label>Search Account</Label>
<div className="relative mt-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Type to search accounts..."
value={accountSearch}
onChange={(e) => {
setAccountSearch(e.target.value)
setShowAccountDropdown(true)
}}
onFocus={() => setShowAccountDropdown(true)}
className="pl-9"
/>
</div>
{showAccountDropdown && accountSearch.length > 0 && (
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-60 overflow-auto">
{accounts.length === 0 ? (
<div className="p-3 text-sm text-muted-foreground">No accounts found</div>
) : (
accounts.map((a) => (
<button
key={a.id}
type="button"
className="w-full text-left px-3 py-2 text-sm hover:bg-accent flex items-center justify-between"
onClick={() => selectAccount(a)}
>
<div>
<span className="font-medium">{a.name}</span>
{a.phone && <span className="text-muted-foreground ml-2">{a.phone}</span>}
</div>
{a.accountNumber && <span className="text-xs text-muted-foreground font-mono">#{a.accountNumber}</span>}
</button>
))
)}
</div>
)}
<p className="text-xs text-muted-foreground mt-1">Or fill in customer details manually below for walk-ins</p>
</div>
) : (
<div className="flex items-center justify-between p-3 rounded-md border bg-muted/30">
<div>
<p className="font-medium">{selectedAccount.name}</p>
<div className="flex gap-4 text-sm text-muted-foreground">
{selectedAccount.phone && <span>{selectedAccount.phone}</span>}
{selectedAccount.email && <span>{selectedAccount.email}</span>}
{selectedAccount.accountNumber && <span className="font-mono">#{selectedAccount.accountNumber}</span>}
</div>
</div>
<Button type="button" variant="ghost" size="sm" onClick={clearAccount}>
<X className="h-4 w-4" />
</Button>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Customer Name *</Label>
<Input {...register('customerName')} />
{errors.customerName && <p className="text-sm text-destructive">{errors.customerName.message}</p>}
</div>
<div className="space-y-2">
<Label>Phone</Label>
<Input {...register('customerPhone')} />
</div>
</div>
</CardContent>
</Card>
{/* Instrument Section */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Instrument</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Instrument Description</Label>
<Input {...register('instrumentDescription')} placeholder="e.g. Yamaha Trumpet YTR-2330" />
</div>
<div className="space-y-2">
<Label>Serial Number</Label>
<Input {...register('serialNumber')} />
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Condition at Intake</Label>
<Select onValueChange={(v) => setValue('conditionIn', v as any)}>
<SelectTrigger>
<SelectValue placeholder="Select condition" />
</SelectTrigger>
<SelectContent>
<SelectItem value="excellent">Excellent</SelectItem>
<SelectItem value="good">Good</SelectItem>
<SelectItem value="fair">Fair</SelectItem>
<SelectItem value="poor">Poor</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Estimated Cost</Label>
<Input type="number" step="0.01" {...register('estimatedCost', { valueAsNumber: true })} />
</div>
</div>
<div className="space-y-2">
<Label>Problem Description *</Label>
<Textarea {...register('problemDescription')} rows={3} placeholder="Describe the issue..." />
{errors.problemDescription && <p className="text-sm text-destructive">{errors.problemDescription.message}</p>}
</div>
</CardContent>
</Card>
{/* Photos Section */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Intake Photos</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">Optional document instrument condition at intake</p>
<div className="flex flex-wrap gap-3">
{photos.map((photo, i) => (
<div key={i} className="relative group">
<img
src={URL.createObjectURL(photo)}
alt={`Intake photo ${i + 1}`}
className="h-24 w-24 object-cover rounded-md border"
/>
<button
type="button"
className="absolute -top-2 -right-2 h-5 w-5 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
onClick={() => removePhoto(i)}
>
<X className="h-3 w-3" />
</button>
</div>
))}
<button
type="button"
className="h-24 w-24 rounded-md border-2 border-dashed border-muted-foreground/30 flex flex-col items-center justify-center text-muted-foreground hover:border-primary hover:text-primary transition-colors"
onClick={() => photoInputRef.current?.click()}
>
<ImageIcon className="h-6 w-6 mb-1" />
<span className="text-xs">Add Photo</span>
</button>
</div>
<input
ref={photoInputRef}
type="file"
accept="image/jpeg,image/png,image/webp"
multiple
className="hidden"
onChange={addPhotos}
/>
</CardContent>
</Card>
{/* Submit */}
<div className="flex gap-2">
<Button type="submit" disabled={mutation.isPending} size="lg">
{mutation.isPending ? 'Creating...' : 'Create Ticket'}
</Button>
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/repairs', search: {} as any })}>
Cancel
</Button>
</div>
</form>
</div>
)
}