Improve repair batches: account search, add repair button, batch PDF

Batch create form now uses searchable account picker (same as ticket
intake) instead of a dropdown. Batch detail shows + Add Repair button
that creates a ticket pre-linked to the batch. Repair count and total
estimate auto-calculated from linked tickets. Batch PDF generates a
summary with all repairs, statuses, estimates, and grand total. Added
Mark Delivered button for completed batches. New repair form shows
batch badge when linked from a batch.
This commit is contained in:
Ryan Moon
2026-03-29 13:38:25 -05:00
parent 916eb29895
commit f7e78bec84
4 changed files with 307 additions and 63 deletions

View File

@@ -1,21 +1,22 @@
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 { repairBatchDetailOptions, repairBatchMutations, repairBatchKeys, repairBatchTicketsOptions, repairLineItemListOptions } 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 { ArrowLeft, Check, X, Plus, FileText, Download } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth.store'
import jsPDF from 'jspdf'
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,
limit: Number(search.limit) || 100,
q: (search.q as string) || undefined,
sort: (search.sort as string) || undefined,
order: (search.order as 'asc' | 'desc') || 'asc',
@@ -23,11 +24,23 @@ export const Route = createFileRoute('/_authenticated/repair-batches/$batchId')(
component: RepairBatchDetailPage,
})
const STATUS_LABELS: Record<string, string> = {
new: 'New', in_transit: 'In Transit', 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',
}
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: 'instrument', header: 'Instrument', render: (t) => <>{t.instrumentDescription ?? '-'}</> },
{ key: 'problem', header: 'Problem', render: (t) => <span className="truncate max-w-[200px] block">{t.problemDescription}</span> },
{ key: 'status', header: 'Status', sortable: true, render: (t) => <Badge variant="outline">{STATUS_LABELS[t.status] ?? t.status}</Badge> },
{
key: 'estimated_cost',
header: 'Estimate',
render: (t) => <>{t.estimatedCost ? `$${t.estimatedCost}` : '-'}</>,
},
]
function RepairBatchDetailPage() {
@@ -35,6 +48,7 @@ function RepairBatchDetailPage() {
const navigate = useNavigate()
const queryClient = useQueryClient()
const hasPermission = useAuthStore((s) => s.hasPermission)
const token = useAuthStore((s) => s.token)
const { params, setPage, setSort } = usePagination()
const { data: batch, isLoading } = useQuery(repairBatchDetailOptions(batchId))
@@ -75,12 +89,148 @@ function RepairBatchDetailPage() {
return <p className="text-muted-foreground">Batch not found</p>
}
const tickets = ticketsData?.data ?? []
const repairCount = ticketsData?.pagination.total ?? 0
const totalEstimate = tickets.reduce((sum, t) => sum + (t.estimatedCost ? parseFloat(t.estimatedCost) : 0), 0)
const totalActual = tickets.reduce((sum, t) => sum + (t.actualCost ? parseFloat(t.actualCost) : 0), 0)
function handleTicketClick(ticket: RepairTicket) {
navigate({ to: '/repairs/$ticketId', params: { ticketId: ticket.id }, search: {} as any })
}
function handleAddRepair() {
// Navigate to new repair with batch pre-linked
navigate({ to: '/repairs/new', search: { batchId, batchName: batch!.batchNumber ?? '' } as any })
}
async function generateBatchPdf() {
if (!batch) return
const doc = new jsPDF()
let y = 20
doc.setFontSize(18)
doc.setFont('helvetica', 'bold')
doc.text('Forte Music', 14, y)
y += 8
doc.setFontSize(12)
doc.setFont('helvetica', 'normal')
doc.text('Repair Batch Summary', 14, y)
doc.setFontSize(14)
doc.setFont('helvetica', 'bold')
doc.text(`Batch #${batch.batchNumber ?? ''}`, 196, 20, { align: 'right' })
doc.setFontSize(10)
doc.setFont('helvetica', 'normal')
doc.text(STATUS_LABELS[batch.status] ?? batch.status, 196, 28, { align: 'right' })
y += 12
doc.setDrawColor(200)
doc.line(14, y, 196, y)
y += 8
// Contact info
doc.setFontSize(10)
doc.setFont('helvetica', 'bold')
doc.text('Contact', 14, y)
y += 5
doc.setFont('helvetica', 'normal')
if (batch.contactName) { doc.text(batch.contactName, 14, y); y += 5 }
if (batch.contactPhone) { doc.text(batch.contactPhone, 14, y); y += 5 }
if (batch.contactEmail) { doc.text(batch.contactEmail, 14, y); y += 5 }
y += 3
// Summary
doc.setFont('helvetica', 'bold')
doc.text(`Repairs: ${repairCount}`, 14, y)
if (batch.dueDate) doc.text(`Due: ${new Date(batch.dueDate).toLocaleDateString()}`, 100, y)
y += 8
if (batch.notes) {
doc.setFont('helvetica', 'normal')
doc.setFontSize(9)
const noteLines = doc.splitTextToSize(batch.notes, 180)
doc.text(noteLines, 14, y)
y += noteLines.length * 4 + 4
}
// Repairs table
doc.setDrawColor(200)
doc.line(14, y, 196, y)
y += 6
doc.setFontSize(10)
doc.setFont('helvetica', 'bold')
doc.text('Repairs', 14, y)
y += 6
// Table header
doc.setFontSize(8)
doc.setFillColor(245, 245, 245)
doc.rect(14, y - 3, 182, 6, 'F')
doc.text('Ticket #', 16, y)
doc.text('Instrument', 40, y)
doc.text('Problem', 100, y)
doc.text('Status', 155, y)
doc.text('Estimate', 190, y, { align: 'right' })
y += 5
doc.setFont('helvetica', 'normal')
for (const ticket of tickets) {
if (y > 270) { doc.addPage(); y = 20 }
doc.text(ticket.ticketNumber ?? '-', 16, y)
doc.text((ticket.instrumentDescription ?? '-').slice(0, 30), 40, y)
doc.text(ticket.problemDescription.slice(0, 28), 100, y)
doc.text(STATUS_LABELS[ticket.status] ?? ticket.status, 155, y)
doc.text(ticket.estimatedCost ? `$${ticket.estimatedCost}` : '-', 190, y, { align: 'right' })
y += 5
}
// Totals
y += 3
doc.setDrawColor(200)
doc.line(140, y, 196, y)
y += 5
doc.setFont('helvetica', 'bold')
doc.setFontSize(10)
doc.text('Estimated Total:', 155, y, { align: 'right' })
doc.text(`$${totalEstimate.toFixed(2)}`, 190, y, { align: 'right' })
y += 5
if (totalActual > 0) {
doc.text('Actual Total:', 155, y, { align: 'right' })
doc.text(`$${totalActual.toFixed(2)}`, 190, y, { align: 'right' })
y += 5
}
// Footer
y = 280
doc.setFontSize(8)
doc.setFont('helvetica', 'normal')
doc.setTextColor(150)
doc.text(`Generated ${new Date().toLocaleString()} — Batch #${batch.batchNumber}`, 105, y, { align: 'center' })
const filename = `repair-batch-${batch.batchNumber}.pdf`
doc.save(filename)
// Upload to batch documents
const blob = doc.output('blob')
const formData = new FormData()
formData.append('file', new File([blob], filename, { type: 'application/pdf' }))
formData.append('entityType', 'repair_ticket')
formData.append('entityId', batchId)
formData.append('category', 'document')
try {
await fetch('/v1/files', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: formData,
})
} catch { /* non-critical */ }
toast.success('Batch PDF downloaded')
}
return (
<div className="space-y-6 max-w-4xl">
<div className="space-y-6 max-w-5xl">
<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" />
@@ -89,14 +239,17 @@ function RepairBatchDetailPage() {
<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>
<Button variant="outline" size="sm" onClick={generateBatchPdf}>
<FileText className="mr-2 h-4 w-4" />PDF
</Button>
<Badge variant="outline" className="text-sm px-3 py-1">{STATUS_LABELS[batch.status] ?? batch.status}</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">
<div className="flex gap-2 flex-wrap">
{hasPermission('repairs.admin') && batch.approvalStatus === 'pending' && (
<>
<Button onClick={() => approveMutation.mutate()} disabled={approveMutation.isPending}>
@@ -113,10 +266,13 @@ function RepairBatchDetailPage() {
{hasPermission('repairs.edit') && batch.status === 'in_progress' && (
<Button variant="secondary" onClick={() => statusMutation.mutate('completed')}>Mark Completed</Button>
)}
{hasPermission('repairs.edit') && batch.status === 'completed' && (
<Button variant="secondary" onClick={() => statusMutation.mutate('delivered')}>Mark Delivered</Button>
)}
</div>
{/* Batch Info */}
<div className="grid grid-cols-2 gap-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<Card>
<CardHeader><CardTitle className="text-lg">Contact</CardTitle></CardHeader>
<CardContent className="space-y-2 text-sm">
@@ -126,11 +282,12 @@ function RepairBatchDetailPage() {
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-lg">Details</CardTitle></CardHeader>
<CardHeader><CardTitle className="text-lg">Summary</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">Repairs:</span> <span className="font-semibold">{repairCount}</span></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>
<div><span className="text-muted-foreground">Estimated Total:</span> <span className="font-semibold">${totalEstimate.toFixed(2)}</span></div>
{totalActual > 0 && <div><span className="text-muted-foreground">Actual Total:</span> <span className="font-semibold">${totalActual.toFixed(2)}</span></div>}
{batch.notes && <div><span className="text-muted-foreground">Notes:</span> {batch.notes}</div>}
</CardContent>
</Card>
@@ -138,15 +295,22 @@ function RepairBatchDetailPage() {
{/* Tickets in batch */}
<Card>
<CardHeader><CardTitle className="text-lg">Tickets ({ticketsData?.pagination.total ?? 0})</CardTitle></CardHeader>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="text-lg">Repairs ({repairCount})</CardTitle>
{hasPermission('repairs.edit') && (
<Button size="sm" onClick={handleAddRepair}>
<Plus className="mr-2 h-4 w-4" />Add Repair
</Button>
)}
</CardHeader>
<CardContent>
<DataTable
columns={ticketColumns}
data={ticketsData?.data ?? []}
data={tickets}
loading={ticketsLoading}
page={params.page}
totalPages={ticketsData?.pagination.totalPages ?? 1}
total={ticketsData?.pagination.total ?? 0}
total={repairCount}
sort={params.sort}
order={params.order}
onPageChange={setPage}

View File

@@ -1,4 +1,5 @@
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useState } 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'
@@ -9,10 +10,10 @@ 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 { ArrowLeft, Search, Plus, X } from 'lucide-react'
import { toast } from 'sonner'
import type { Account } from '@/types/account'
export const Route = createFileRoute('/_authenticated/repair-batches/new')({
component: NewRepairBatchPage,
@@ -21,7 +22,13 @@ export const Route = createFileRoute('/_authenticated/repair-batches/new')({
function NewRepairBatchPage() {
const navigate = useNavigate()
const { data: accountsData } = useQuery(accountListOptions({ page: 1, limit: 100, order: 'asc', sort: 'name' }))
const [accountSearch, setAccountSearch] = useState('')
const [selectedAccount, setSelectedAccount] = useState<Account | null>(null)
const [showAccountDropdown, setShowAccountDropdown] = useState(false)
const { data: accountsData } = useQuery(
accountListOptions({ page: 1, limit: 20, q: accountSearch || undefined, order: 'asc', sort: 'name' }),
)
const {
register,
@@ -35,7 +42,6 @@ function NewRepairBatchPage() {
contactName: '',
contactPhone: '',
contactEmail: '',
instrumentCount: 0,
notes: '',
},
})
@@ -49,10 +55,28 @@ function NewRepairBatchPage() {
onError: (err) => toast.error(err.message),
})
function selectAccount(account: Account) {
setSelectedAccount(account)
setShowAccountDropdown(false)
setAccountSearch('')
setValue('accountId', account.id)
if (account.phone) setValue('contactPhone', account.phone)
if (account.email) setValue('contactEmail', account.email)
setValue('contactName', account.name)
}
function clearAccount() {
setSelectedAccount(null)
setValue('accountId', '')
setValue('contactName', '')
setValue('contactPhone', '')
setValue('contactEmail', '')
}
const accounts = accountsData?.data ?? []
return (
<div className="space-y-6 max-w-2xl">
<div className="space-y-6 max-w-3xl">
<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" />
@@ -60,28 +84,72 @@ function NewRepairBatchPage() {
<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>}
<form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-lg">Account</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">
{!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 by name, email, or phone..."
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.email && <span className="text-muted-foreground ml-2">{a.email}</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>
)}
{errors.accountId && <p className="text-sm text-destructive mt-1">{errors.accountId.message}</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>
)}
</CardContent>
</Card>
<div className="grid grid-cols-2 gap-4">
<Card>
<CardHeader>
<CardTitle className="text-lg">Contact & Details</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>Contact Name</Label>
<Input {...register('contactName')} />
@@ -92,33 +160,27 @@ function NewRepairBatchPage() {
</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 className="space-y-2">
<Label>Contact Email</Label>
<Input type="email" {...register('contactEmail')} />
</div>
<div className="space-y-2">
<Label>Notes</Label>
<Textarea {...register('notes')} rows={3} placeholder="e.g. Annual instrument checkup for band program" />
<Textarea {...register('notes')} rows={3} placeholder="e.g. Annual instrument checkup, multiple guitars needing setups" />
</div>
</CardContent>
</Card>
<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 className="flex gap-2">
<Button type="submit" disabled={mutation.isPending} size="lg">
{mutation.isPending ? 'Creating...' : 'Create Batch'}
</Button>
<Button variant="secondary" type="button" size="lg" onClick={() => navigate({ to: '/repair-batches', search: {} as any })}>
Cancel
</Button>
</div>
</form>
</div>
)
}

View File

@@ -137,7 +137,7 @@ function RepairsListPage() {
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Repairs</h1>
{hasPermission('repairs.edit') && (
<Button onClick={() => navigate({ to: '/repairs/new' })}>
<Button onClick={() => navigate({ to: '/repairs/new', search: {} as any })}>
<Plus className="mr-2 h-4 w-4" />
New Repair
</Button>

View File

@@ -29,12 +29,19 @@ interface PendingLineItem {
}
export const Route = createFileRoute('/_authenticated/repairs/new')({
validateSearch: (search: Record<string, unknown>) => ({
batchId: (search.batchId as string) || undefined,
batchName: (search.batchName as string) || undefined,
}),
component: NewRepairPage,
})
function NewRepairPage() {
const navigate = useNavigate()
const token = useAuthStore((s) => s.token)
const search = Route.useSearch()
const linkedBatchId = search.batchId
const linkedBatchName = search.batchName
// Account search
const [accountSearch, setAccountSearch] = useState('')
@@ -95,6 +102,10 @@ function NewRepairPage() {
if (lineItems.length > 0) {
data.estimatedCost = estimatedTotal
}
// Link to batch if coming from a batch
if (linkedBatchId) {
data.repairBatchId = linkedBatchId
}
const ticket = await repairTicketMutations.create(data)
@@ -201,6 +212,13 @@ function NewRepairPage() {
<h1 className="text-2xl font-bold">New Repair Ticket</h1>
</div>
{linkedBatchId && (
<div className="flex items-center gap-2 px-3 py-2 rounded-md border bg-muted/30 text-sm">
<Badge variant="outline">Batch #{linkedBatchName}</Badge>
<span className="text-muted-foreground">This repair will be linked to the batch</span>
</div>
)}
<form onSubmit={handleSubmit((data) => mutation.mutate(data))} className="space-y-6">
{/* Customer Section */}
<Card>