| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301 |
- 'use client'
- import { type ComponentProps, type ComponentType, useMemo, useState, useTransition } from 'react'
- import { useRouter } from 'next/navigation'
- import Link from 'next/link'
- import { useFormatDate } from '@/lib/use-format-date'
- import {
- ConfirmConsequenceList,
- ConfirmFrame,
- ConfirmFrameAction,
- ConfirmFrameCancel,
- ConfirmFrameText,
- ConfirmSubjectList,
- useConfirm,
- } from '@/components/confirm-dialog'
- import { Button } from '@/components/ui/button'
- import { Badge } from '@/components/ui/badge'
- import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
- } from '@/components/ui/dropdown-menu'
- import {
- ChevronRight,
- ArrowLeft,
- CheckCircle2,
- Download,
- FileText,
- Loader2,
- MessageSquareText,
- MoreVertical,
- RotateCcw,
- Save,
- Settings2,
- Wrench,
- Send,
- Share2,
- Trash2,
- TriangleAlert,
- Eye,
- } from 'lucide-react'
- import { useTranslations } from 'next-intl'
- import { toast } from 'sonner'
- import {
- completeInspection,
- deleteInspection,
- reopenInspection,
- createQuoteFromInspection,
- } from '../Actions/inspectionActions'
- import { InspectionShareDialog } from './InspectionShareDialog'
- import { SendDocumentDialog } from '@/features/messaging/Components/SendDocumentDialog'
- import { sendInspectionEmail } from '@/features/email/Actions/emailActions'
- import { InspectionNotesCard } from './InspectionNotesCard'
- import { PdfPreviewDialog } from '@/components/pdf-preview-dialog'
- import { WorkOrderFromInspectionDialog } from './WorkOrderFromInspectionDialog'
- import { cn } from '@/lib/utils'
- import {
- InspectionFilesCard,
- type InspectionAttachmentData,
- type InspectionStatusReportData,
- } from './InspectionFilesCard'
- import { InspectionCertificateCard, type TechnicianOption } from './InspectionCertificateCard'
- import type { ConditionMarkData } from '@/features/condition-map/Lib/marks'
- import type { MarkType } from '@/features/condition-map/Lib/markTypes'
- import { InspectionItemRow, type InspectionItemData } from './InspectionItemRow'
- import { MediaLightbox, type LightboxImage } from './MediaLightbox'
- import { useServiceType } from '@/components/service-type-context'
- import { useSaveShortcut } from '@/hooks/use-save-shortcut'
- import {
- CONDITION_TOKENS,
- TEST_RESULT_TOKENS,
- countConditions,
- deriveTestResult,
- isDefect,
- worstCondition,
- type Condition,
- type SeverityScale,
- } from '../Lib/conditions'
- import { useConditionLabels } from '../Lib/useConditionLabels'
- import { findCompletionBlockers } from '../Lib/completion'
- export interface InspectionData {
- id: string
- status: string
- mileage: number | null
- notes: string | null
- publicToken: string | null
- completedAt: Date | null
- createdAt: Date
- organizationId: string
- severityScale: string | null
- country: string | null
- vehicleCategory: string | null
- nextTestDue: Date | null
- certificateNumber: string | null
- technicianId: string | null
- inspectorName: string | null
- testLocation: string | null
- vehicle: {
- id: string
- bodyType?: string | null
- make: string
- model: string
- year: number
- vin: string | null
- licensePlate: string | null
- mileage: number
- customer: {
- id: string
- name: string
- email: string | null
- phone: string | null
- telegramChatId?: string | null
- } | null
- }
- template: {
- id: string
- name: string
- severityScale?: string | null
- country?: string | null
- standard?: string | null
- }
- technician?: { id: string; name: string } | null
- items: InspectionItemData[]
- attachments?: InspectionAttachmentData[]
- quotes: {
- id: string
- quoteNumber: string | null
- status: string
- createdAt: Date
- user: { name: string }
- }[]
- quoteRequests: {
- id: string
- message: string | null
- selectedItemIds: string[]
- createdAt: Date
- }[]
- serviceRecords: {
- id: string
- title: string
- status: string
- invoiceNumber: string | null
- createdAt: Date
- }[]
- }
- const isVideo = (url: string) => /\.(mp4|webm|mov)$/i.test(url)
- /** Segmented bar showing how the checks are distributed across the grades. */
- function ProgressRail({
- counts,
- label,
- }: {
- counts: ReturnType<typeof countConditions>
- label: string
- }) {
- const segments = (
- [
- ['pass', counts.pass],
- ['attention', counts.attention],
- ['fail', counts.fail],
- ['dangerous', counts.dangerous],
- ['not_applicable', counts.notApplicable],
- ] as const
- )
- .map(([key, value]) => ({ key, value }))
- .filter((s) => s.value > 0)
- return (
- <div
- className="bg-muted flex h-2.5 w-full overflow-hidden rounded-full"
- role="img"
- aria-label={label}
- >
- {segments.map((segment) => (
- <div
- key={segment.key}
- className={CONDITION_TOKENS[segment.key].bar}
- style={{ width: `${(segment.value / Math.max(counts.total, 1)) * 100}%` }}
- />
- ))}
- </div>
- )
- }
- /**
- * The thin rule under a section header: how much of the section is graded,
- * in the grades' own colours, the rest left as the muted track.
- */
- function SectionRule({ counts }: { counts: ReturnType<typeof countConditions> }) {
- const segments = (
- [
- ['pass', counts.pass],
- ['attention', counts.attention],
- ['fail', counts.fail],
- ['dangerous', counts.dangerous],
- ['not_applicable', counts.notApplicable],
- ] as const
- ).filter(([, value]) => value > 0)
- return (
- <div className="bg-muted flex h-0.5 w-full overflow-hidden" aria-hidden="true">
- {segments.map(([key, value]) => (
- <div
- key={key}
- className={CONDITION_TOKENS[key].bar}
- style={{ width: `${(value / Math.max(counts.total, 1)) * 100}%` }}
- />
- ))}
- </div>
- )
- }
- function CountChip({
- condition,
- value,
- label,
- }: {
- condition: Condition
- value: number
- label: string
- }) {
- const token = CONDITION_TOKENS[condition]
- return (
- <div className="flex items-center gap-1.5">
- <span className={`h-2.5 w-2.5 shrink-0 rounded-full ${token.bar}`} aria-hidden="true" />
- <span className="text-xs">
- <span className="font-semibold">{value}</span>{' '}
- <span className="text-muted-foreground">{label}</span>
- </span>
- </div>
- )
- }
- export function InspectionPageClient({
- inspection,
- organizationId,
- smsEnabled = false,
- emailEnabled = false,
- telegramEnabled = false,
- statusReports = [],
- defectHistory = {},
- technicians = [],
- workshopAddress = '',
- conditionMarks = [],
- markTypes = [],
- }: {
- inspection: InspectionData
- /** Every mark on the vehicle's condition map, for a checklist that has one. */
- conditionMarks?: ConditionMarkData[]
- /** The workshop's kinds of mark, for the same checklist. */
- markTypes?: MarkType[]
- /** For the share links of the inspection's status reports. */
- organizationId: string
- smsEnabled?: boolean
- emailEnabled?: boolean
- telegramEnabled?: boolean
- /** Video reports sent to the customer from this inspection. */
- statusReports?: InspectionStatusReportData[]
- /** Wording this workshop has used before, keyed by check name. */
- defectHistory?: Record<string, { text: string; severity: string }[]>
- technicians?: TechnicianOption[]
- workshopAddress?: string
- }) {
- const t = useTranslations('inspections.page')
- const router = useRouter()
- const { formatDate } = useFormatDate()
- const serviceType = useServiceType()
- const [isPending, startTransition] = useTransition()
- const [showCompleteDialog, setShowCompleteDialog] = useState(false)
- const confirm = useConfirm()
- const [showShareDialog, setShowShareDialog] = useState(false)
- const [showSendDialog, setShowSendDialog] = useState(false)
- const [isCreatingQuote, setIsCreatingQuote] = useState(false)
- const [isCreatingWorkOrder, setIsCreatingWorkOrder] = useState(false)
- const [showWorkOrderDialog, setShowWorkOrderDialog] = useState(false)
- const [showPreview, setShowPreview] = useState(false)
- const [lightboxIndex, setLightboxIndex] = useState<number | null>(null)
- // The checklist saves each check as it is graded, which is only reassuring if
- // the page says so. Without this the technician has no way to tell a saved
- // inspection from one that silently failed halfway down a long Annex I sheet.
- const [savingIds, setSavingIds] = useState<Set<string>>(new Set())
- const [lastSavedAt, setLastSavedAt] = useState<Date | null>(null)
- const [saveFailed, setSaveFailed] = useState(false)
- // Grades and photo counts are mirrored here so the summary, the section nav
- // and the complete dialog react the moment a check is saved, instead of
- // waiting for a refresh. Photo counts matter as much as grades: a check that
- // requires evidence blocks completion until it has some.
- const [grades, setGrades] = useState<Record<string, Condition>>(() =>
- Object.fromEntries(inspection.items.map((i) => [i.id, i.condition as Condition]))
- )
- const [photoCounts, setPhotoCounts] = useState<Record<string, number>>(() =>
- Object.fromEntries(inspection.items.map((i) => [i.id, (i.imageUrls ?? []).length]))
- )
- const isCompleted = inspection.status === 'completed'
- // The snapshot wins; the template is the fallback for inspections that
- // predate it, and the migration pinned those templates to their old scale.
- const storedScale = inspection.severityScale ?? inspection.template.severityScale
- const scale: SeverityScale = storedScale === 'basic' ? 'basic' : 'eu'
- const country = inspection.country ?? inspection.template.country ?? null
- const {
- label: gradeLabel,
- graded,
- result: resultLabel,
- resultDetail,
- } = useConditionLabels(scale, country)
- const mileageLabel = serviceType === 'marine' ? t('engineHours') : t('odometer')
- const sections = useMemo(() => {
- const sorted = [...inspection.items].sort((a, b) => a.sortOrder - b.sortOrder)
- const order: string[] = []
- const grouped: Record<string, InspectionItemData[]> = {}
- for (const item of sorted) {
- if (!grouped[item.section]) {
- grouped[item.section] = []
- order.push(item.section)
- }
- grouped[item.section].push(item)
- }
- return order.map((name) => ({
- name,
- code: grouped[name][0]?.sectionCode ?? null,
- items: grouped[name],
- }))
- }, [inspection.items])
- const gradedItems = useMemo(
- () => inspection.items.map((i) => ({ condition: grades[i.id] ?? i.condition })),
- [inspection.items, grades]
- )
- const counts = useMemo(() => countConditions(gradedItems), [gradedItems])
- const result = useMemo(
- () => deriveTestResult(gradedItems, { requireAllInspected: !isCompleted }),
- [gradedItems, isCompleted]
- )
- const resultToken = TEST_RESULT_TOKENS[result]
- const images = useMemo<LightboxImage[]>(() => {
- const list: LightboxImage[] = []
- for (const item of inspection.items) {
- for (const url of item.imageUrls ?? []) {
- if (!isVideo(url)) list.push({ url, caption: item.name })
- }
- }
- return list
- }, [inspection.items])
- const defectItems = inspection.items.filter((i) => isDefect(grades[i.id] ?? i.condition))
- const blockers = useMemo(
- () =>
- findCompletionBlockers(
- inspection.items.map((item) => ({
- id: item.id,
- name: item.name,
- code: item.code,
- condition: grades[item.id] ?? item.condition,
- required: item.required,
- photoRequired: item.photoRequired,
- photoCount: photoCounts[item.id] ?? (item.imageUrls ?? []).length,
- }))
- ),
- [inspection.items, grades, photoCounts]
- )
- const pendingQuoteRequest = inspection.quoteRequests?.[0] ?? null
- // The checks the customer ticked, in checklist order; a check deleted since
- // the request is counted rather than shown.
- const requestedChecks = useMemo(() => {
- const wanted = new Set(pendingQuoteRequest?.selectedItemIds ?? [])
- return inspection.items.filter((item) => wanted.has(item.id))
- }, [inspection.items, pendingQuoteRequest])
- const missingRequestedChecks =
- (pendingQuoteRequest?.selectedItemIds.length ?? 0) - requestedChecks.length
- const requestedIds = useMemo(() => new Set(requestedChecks.map((i) => i.id)), [requestedChecks])
- const workOrder = inspection.serviceRecords?.[0] ?? null
- const notInspected = counts.total - counts.inspected
- const handleSaveState = (itemId: string, state: 'saving' | 'saved' | 'error') => {
- setSavingIds((prev) => {
- const next = new Set(prev)
- if (state === 'saving') next.add(itemId)
- else next.delete(itemId)
- return next
- })
- if (state === 'saved') {
- setLastSavedAt(new Date())
- setSaveFailed(false)
- }
- if (state === 'error') setSaveFailed(true)
- }
- /**
- * Fields commit on blur, so a note still being typed has not reached the
- * server yet. Taking focus off it is what actually saves; the button exists
- * because "it saves as you go" is not something a technician should have to
- * take on trust.
- */
- const handleSaveNow = () => {
- ;(document.activeElement as HTMLElement | null)?.blur()
- if (savingIds.size === 0 && !saveFailed) {
- toast.success(t('allSaved'))
- }
- }
- // The shortcut is pressed mid-sentence, so the field gets its focus back
- // once the blur has sent what was typed.
- useSaveShortcut(() => {
- const focused = document.activeElement as HTMLElement | null
- handleSaveNow()
- focused?.focus()
- }, !isCompleted)
- const openImage = (url: string) => {
- const index = images.findIndex((img) => img.url === url)
- setLightboxIndex(index >= 0 ? index : null)
- }
- /**
- * The quote is built on the server from what the database holds: the
- * inspection line, then every check that was not OK with the note as it
- * was saved, not as this page last saw it.
- */
- const handleCreateQuoteFromInspection = async () => {
- setIsCreatingQuote(true)
- // An action that cannot reach the server throws instead of answering, so
- // it is caught and reported the way a refusal is.
- const created = await createQuoteFromInspection(inspection.id).catch(() => null)
- if (created?.success && created.data) {
- router.push(`/quotes/${created.data.id}`)
- } else {
- toast.error(created?.error || t('quoteFailed'))
- setIsCreatingQuote(false)
- }
- }
- const handleComplete = () => {
- startTransition(async () => {
- const done = await completeInspection(inspection.id).catch(() => null)
- if (done?.success) {
- toast.success(t('completed'))
- setShowCompleteDialog(false)
- // A finished inspection is usually what the customer is waiting for.
- setShowSendDialog(true)
- router.refresh()
- } else {
- toast.error(done?.error || t('completeFailed'))
- }
- })
- }
- const handleReopen = async () => {
- const ok = await confirm({
- title: t('reopenTitle'),
- description: t('reopenBody'),
- consequences: inspection.publicToken ? [t('reopenShared')] : undefined,
- confirmLabel: t('reopen'),
- cancelLabel: t('cancel'),
- icon: RotateCcw,
- })
- if (!ok) return
- startTransition(async () => {
- const reopened = await reopenInspection(inspection.id).catch(() => null)
- if (reopened?.success) {
- toast.success(t('reopened'))
- router.refresh()
- } else {
- toast.error(reopened?.error || t('reopenFailed'))
- }
- })
- }
- const handleDelete = async () => {
- const ok = await confirm({
- title: t('deleteTitle'),
- description: t('deleteBody'),
- confirmLabel: t('delete'),
- cancelLabel: t('cancel'),
- icon: Trash2,
- destructive: true,
- })
- if (!ok) return
- startTransition(async () => {
- const removed = await deleteInspection(inspection.id).catch(() => null)
- if (removed?.success) {
- toast.success(t('deleted'))
- router.push('/inspections')
- } else {
- toast.error(removed?.error || t('deleteFailed'))
- }
- })
- }
- return (
- <div className="space-y-5">
- {/* Action bar */}
- <div className="bg-background/95 supports-[backdrop-filter]:bg-background/80 sticky top-16 z-20 -mx-4 border-b px-4 py-3 backdrop-blur">
- <div className="flex flex-wrap items-center justify-between gap-3">
- <div className="flex min-w-0 items-center gap-3">
- <Link
- href="/inspections"
- className="text-muted-foreground hover:text-foreground focus-visible:ring-ring inline-flex h-9 items-center gap-1.5 rounded-md text-sm transition-colors focus-visible:ring-2 focus-visible:outline-none"
- >
- <ArrowLeft className="h-4 w-4" aria-hidden="true" />
- <span className="hidden sm:inline">{t('back')}</span>
- </Link>
- <div className="bg-border h-5 w-px" aria-hidden="true" />
- <div className="min-w-0">
- <h1 className="truncate text-base leading-tight font-semibold">
- {inspection.vehicle.year} {inspection.vehicle.make} {inspection.vehicle.model}
- </h1>
- <p className="text-muted-foreground truncate text-xs">
- {inspection.template.name} · {formatDate(new Date(inspection.createdAt))}
- </p>
- </div>
- </div>
- <div className="flex items-center gap-2">
- <Badge
- variant="outline"
- className={
- isCompleted
- ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300'
- : 'border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300'
- }
- >
- {isCompleted ? t('statusCompleted') : t('statusInProgress')}
- </Badge>
- {!isCompleted && (
- <div className="mr-1 flex items-center gap-2">
- <p className="text-muted-foreground hidden text-xs sm:block" role="status">
- {savingIds.size > 0
- ? t('saving')
- : saveFailed
- ? t('saveFailed')
- : lastSavedAt
- ? t('savedAt', {
- time: lastSavedAt.toLocaleTimeString([], {
- hour: '2-digit',
- minute: '2-digit',
- }),
- })
- : t('savesAsYouGo')}
- </p>
- <BarButton
- variant="outline"
- icon={savingIds.size > 0 ? Loader2 : Save}
- spinning={savingIds.size > 0}
- label={t('save')}
- onClick={handleSaveNow}
- disabled={savingIds.size > 0}
- />
- </div>
- )}
- {isCompleted ? (
- <BarButton
- variant="outline"
- icon={RotateCcw}
- label={t('reopen')}
- onClick={handleReopen}
- />
- ) : (
- <BarButton
- icon={CheckCircle2}
- label={t('complete')}
- onClick={() => setShowCompleteDialog(true)}
- />
- )}
- {/* The certificate as the customer will get it, without leaving the page. */}
- <BarButton
- variant="outline"
- icon={Eye}
- label={t('preview')}
- onClick={() => setShowPreview(true)}
- data-testid="inspection-preview"
- />
- <BarButton
- variant="outline"
- icon={Send}
- label={t('send')}
- onClick={() => setShowSendDialog(true)}
- />
- <BarButton
- variant="outline"
- icon={Share2}
- label={t('share')}
- onClick={() => setShowShareDialog(true)}
- />
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- className="h-9 w-9"
- aria-label={t('moreActions')}
- >
- <MoreVertical className="h-4 w-4" aria-hidden="true" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="min-w-52">
- <DropdownMenuItem
- onClick={() =>
- window.open(`/api/protected/inspections/${inspection.id}/pdf`, '_blank')
- }
- >
- <Download className="mr-2 h-4 w-4" aria-hidden="true" />
- {t('downloadCertificate')}
- </DropdownMenuItem>
- <DropdownMenuItem asChild>
- <Link href="/settings/templates?tab=inspections">
- <Settings2 className="mr-2 h-4 w-4" aria-hidden="true" />
- {t('manageTemplates')}
- </Link>
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem className="text-destructive" onClick={handleDelete}>
- <Trash2 className="mr-2 h-4 w-4" aria-hidden="true" />
- {t('delete')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- </div>
- <div className="grid gap-5 lg:grid-cols-[1fr_19rem] lg:items-start">
- {/* Main column */}
- <main className="min-w-0 space-y-5">
- {/* Overall result */}
- <section
- aria-labelledby="inspection-result"
- className={`rounded-lg border p-4 ${resultToken.soft}`}
- >
- <h2 id="inspection-result" className="text-base font-semibold">
- {resultLabel(result)}
- </h2>
- <p className="mt-1 text-sm">{resultDetail(result)}</p>
- {result === 'incomplete' && notInspected > 0 && (
- <p className="mt-1 text-sm">
- {t('stillToGrade', { count: notInspected, total: counts.total })}
- </p>
- )}
- </section>
- {/* What the customer asked to have priced, from their link. Kept
- in view whether or not a quote exists yet: a second request can
- follow a first quote, and the desk must see both. */}
- {pendingQuoteRequest && (
- <section
- aria-labelledby="inspection-quote-request"
- data-testid="quote-request-card"
- className="rounded-lg border border-amber-500/40 bg-amber-500/5 p-4"
- >
- <div className="flex flex-wrap items-start justify-between gap-3">
- <div className="min-w-0">
- <h2
- id="inspection-quote-request"
- className="flex items-center gap-2 text-base font-semibold"
- >
- <MessageSquareText
- className="h-4 w-4 text-amber-700 dark:text-amber-300"
- aria-hidden="true"
- />
- {t('quoteRequestHeading')}
- </h2>
- <p className="text-muted-foreground mt-0.5 text-sm">
- {inspection.vehicle.customer?.name
- ? t('quoteRequestedBy', {
- name: inspection.vehicle.customer.name,
- date: formatDate(new Date(pendingQuoteRequest.createdAt)),
- })
- : t('quoteRequestedOn', {
- date: formatDate(new Date(pendingQuoteRequest.createdAt)),
- })}
- </p>
- </div>
- <Button
- size="sm"
- onClick={handleCreateQuoteFromInspection}
- disabled={isCreatingQuote}
- data-testid="quote-request-create"
- >
- {isCreatingQuote ? (
- <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
- ) : (
- <FileText className="h-4 w-4" aria-hidden="true" />
- )}
- {t('createQuoteFromRequest')}
- </Button>
- </div>
- {pendingQuoteRequest.message && (
- <blockquote className="mt-3 border-l-2 border-amber-500/50 pl-3 text-sm whitespace-pre-wrap">
- {pendingQuoteRequest.message}
- </blockquote>
- )}
- <ul className="mt-3 divide-y rounded-md border bg-background">
- {requestedChecks.map((item) => {
- const condition = (grades[item.id] ?? item.condition) as Condition
- return (
- <li
- key={item.id}
- className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 px-3 py-2 text-sm"
- >
- <span className="flex min-w-0 items-baseline gap-2">
- {item.code && (
- <span className="text-muted-foreground font-mono text-xs">
- {item.code}
- </span>
- )}
- <span className="font-medium">{item.name}</span>
- <span className="text-muted-foreground truncate text-xs">
- {item.section}
- </span>
- </span>
- <Badge variant="outline" className={CONDITION_TOKENS[condition].soft}>
- {graded(condition)}
- </Badge>
- </li>
- )
- })}
- </ul>
- {missingRequestedChecks > 0 && (
- <p className="text-muted-foreground mt-2 text-xs">
- {t('quoteRequestMissingChecks', { count: missingRequestedChecks })}
- </p>
- )}
- </section>
- )}
- <InspectionCertificateCard
- inspection={inspection}
- technicians={technicians}
- workshopAddress={workshopAddress}
- mileageLabel={mileageLabel}
- isCompleted={isCompleted}
- />
- {/* Checks: one card per section, drawn like a stamped page of the
- paper form. The name is set in the display face, the section
- code is printed large and faint at the right like a stamp, and
- a thin rule under the header shows how much is graded and in
- which grades. */}
- {sections.map((section, index) => {
- const sectionCounts = countConditions(
- section.items.map((i) => ({ condition: grades[i.id] ?? i.condition }))
- )
- const worst = worstCondition(section.items.map((i) => grades[i.id] ?? i.condition))
- const clean = sectionCounts.notInspected === 0 && !isDefect(worst)
- const rawCode = section.code ?? String(index + 1)
- const stamp = /^\d+$/.test(rawCode) ? rawCode.padStart(2, '0') : rawCode
- return (
- <section
- key={section.name}
- id={`section-${index}`}
- aria-labelledby={`section-${index}-heading`}
- className="bg-card scroll-mt-36 overflow-hidden rounded-lg border"
- >
- <header className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 px-4 py-2">
- <h2
- id={`section-${index}-heading`}
- className="font-display min-w-0 truncate text-lg font-semibold tracking-wide uppercase"
- >
- {section.name}
- </h2>
- <div className="flex shrink-0 items-center gap-3">
- {isDefect(worst) && (
- <Badge variant="outline" className={CONDITION_TOKENS[worst].soft}>
- {graded(worst)}
- </Badge>
- )}
- <span className="text-muted-foreground text-xs tabular-nums">
- {t('graded', { graded: sectionCounts.inspected, total: sectionCounts.total })}
- </span>
- <span
- className={cn(
- 'font-display select-none text-3xl leading-none font-bold tracking-wide',
- clean
- ? 'text-emerald-600/45 dark:text-emerald-400/45'
- : 'text-foreground/15'
- )}
- aria-hidden="true"
- >
- {stamp}
- </span>
- </div>
- </header>
- <SectionRule counts={sectionCounts} />
- <ul className="space-y-2 p-3">
- {section.items.map((item) => (
- <InspectionItemRow
- key={item.id}
- item={item}
- inspectionId={inspection.id}
- inspectionOpenedAt={inspection.createdAt}
- scale={scale}
- country={country}
- standard={inspection.template.standard ?? null}
- isCompleted={isCompleted}
- history={defectHistory[item.name]}
- quoteRequested={requestedIds.has(item.id)}
- onOpenImage={openImage}
- onSaveState={handleSaveState}
- vehicle={{
- id: inspection.vehicle.id,
- bodyType: inspection.vehicle.bodyType ?? null,
- }}
- conditionMarks={conditionMarks}
- markTypes={markTypes}
- serviceType={serviceType}
- onChanged={(itemId, change) => {
- setGrades((prev) => ({ ...prev, [itemId]: change.condition }))
- setPhotoCounts((prev) => ({ ...prev, [itemId]: change.photoCount }))
- }}
- />
- ))}
- </ul>
- </section>
- )
- })}
- <InspectionFilesCard
- inspectionId={inspection.id}
- attachments={inspection.attachments ?? []}
- organizationId={organizationId}
- vehicleName={`${inspection.vehicle.year} ${inspection.vehicle.make} ${inspection.vehicle.model}`}
- customer={
- inspection.vehicle.customer
- ? {
- id: inspection.vehicle.customer.id,
- name: inspection.vehicle.customer.name,
- email: inspection.vehicle.customer.email,
- phone: inspection.vehicle.customer.phone,
- telegramChatId: inspection.vehicle.customer.telegramChatId ?? null,
- }
- : null
- }
- smsEnabled={smsEnabled}
- emailEnabled={emailEnabled}
- telegramEnabled={telegramEnabled}
- statusReports={statusReports}
- />
- </main>
- {/* Sidebar */}
- {/* Sticky, and no taller than what is left of the viewport under the
- action bar: a sidebar taller than the screen used to pin its top
- and hide its bottom until the checklist had scrolled all the way
- down. Scrolling over it now scrolls it, and the page after it. */}
- <aside className="space-y-4 lg:sticky lg:top-36 lg:max-h-[calc(100vh-10rem)] lg:overflow-y-auto lg:overscroll-y-contain lg:pr-1">
- {/* What happens with what was found: a job for the board, or a
- price for the customer first. Once one exists it is linked here. */}
- <section aria-labelledby="inspection-next-step" className="bg-card rounded-lg border p-4">
- <h2 id="inspection-next-step" className="text-sm font-semibold">
- {t('nextStep')}
- </h2>
- <div className="mt-3 space-y-2">
- {workOrder ? (
- <NextStepRow
- icon={Wrench}
- text={t('workOrderRaised', {
- number: workOrder.invoiceNumber ?? '',
- date: formatDate(new Date(workOrder.createdAt)),
- })}
- action={t('viewWorkOrder')}
- tone="done"
- onAction={() =>
- router.push(`/vehicles/${inspection.vehicle.id}/service/${workOrder.id}`)
- }
- testId="next-step-work-order"
- />
- ) : (
- <NextStepRow
- icon={Wrench}
- text={t('nextStepWorkOrderHint')}
- action={t('createWorkOrder')}
- busy={isCreatingWorkOrder}
- onAction={() => setShowWorkOrderDialog(true)}
- testId="next-step-work-order"
- />
- )}
- {inspection.quotes.length > 0 ? (
- <NextStepRow
- icon={FileText}
- text={t('quoteCreated', {
- name: inspection.quotes[0].user.name,
- date: formatDate(new Date(inspection.quotes[0].createdAt)),
- })}
- action={t('viewQuote')}
- tone="done"
- onAction={() => router.push(`/quotes/${inspection.quotes[0].id}`)}
- testId="next-step-quote"
- />
- ) : (
- <NextStepRow
- icon={pendingQuoteRequest ? MessageSquareText : FileText}
- tone={pendingQuoteRequest ? 'attention' : undefined}
- text={
- pendingQuoteRequest
- ? t('quoteRequested', { count: pendingQuoteRequest.selectedItemIds.length })
- : t('nextStepQuoteHint')
- }
- detail={pendingQuoteRequest?.message ?? undefined}
- action={t('createQuote')}
- busy={isCreatingQuote}
- onAction={handleCreateQuoteFromInspection}
- testId="next-step-quote"
- />
- )}
- </div>
- </section>
- <section aria-labelledby="inspection-progress" className="bg-card rounded-lg border p-4">
- <h2 id="inspection-progress" className="text-sm font-semibold">
- {t('progress')}
- </h2>
- <p className="mt-1 text-2xl font-semibold tabular-nums">
- {counts.inspected}
- <span className="text-muted-foreground text-base font-normal">/{counts.total}</span>
- </p>
- <p className="text-muted-foreground text-xs">{t('checksGraded')}</p>
- <div className="mt-3">
- <ProgressRail
- counts={counts}
- label={t('progressLabel', {
- graded: counts.inspected,
- total: counts.total,
- pass: counts.pass,
- attention: counts.attention,
- fail: counts.fail,
- dangerous: counts.dangerous,
- })}
- />
- </div>
- <div className="mt-3 grid gap-1.5">
- <CountChip condition="pass" value={counts.pass} label={gradeLabel('pass')} />
- <CountChip
- condition="attention"
- value={counts.attention}
- label={gradeLabel('attention')}
- />
- <CountChip condition="fail" value={counts.fail} label={gradeLabel('fail')} />
- {counts.notApplicable > 0 && (
- <CountChip
- condition="not_applicable"
- value={counts.notApplicable}
- label={gradeLabel('not_applicable')}
- />
- )}
- {scale === 'eu' && (
- <CountChip
- condition="dangerous"
- value={counts.dangerous}
- label={gradeLabel('dangerous')}
- />
- )}
- </div>
- </section>
- <InspectionNotesCard
- inspectionId={inspection.id}
- notes={inspection.notes}
- disabled={isCompleted}
- />
- <nav aria-labelledby="inspection-sections" className="bg-card rounded-lg border p-4">
- <h2 id="inspection-sections" className="text-sm font-semibold">
- {t('sections')}
- </h2>
- <ul className="mt-2 space-y-0.5">
- {sections.map((section, index) => {
- const sectionCounts = countConditions(
- section.items.map((i) => ({ condition: grades[i.id] ?? i.condition }))
- )
- const worst = worstCondition(section.items.map((i) => grades[i.id] ?? i.condition))
- return (
- <li key={section.name}>
- <a
- href={`#section-${index}`}
- className="hover:bg-muted focus-visible:ring-ring flex items-center gap-2 rounded-md px-2 py-2 text-sm focus-visible:ring-2 focus-visible:outline-none"
- >
- <span
- className={`h-2 w-2 shrink-0 rounded-full ${CONDITION_TOKENS[worst].bar}`}
- aria-hidden="true"
- />
- <span className="min-w-0 flex-1 truncate">{section.name}</span>
- <span className="text-muted-foreground shrink-0 text-xs tabular-nums">
- {sectionCounts.inspected}/{sectionCounts.total}
- </span>
- </a>
- </li>
- )
- })}
- </ul>
- </nav>
- <section aria-labelledby="inspection-vehicle" className="bg-card rounded-lg border p-4">
- <h2 id="inspection-vehicle" className="text-sm font-semibold">
- {t('vehicle')}
- </h2>
- <dl className="mt-2 space-y-2 text-sm">
- <div>
- <dt className="text-muted-foreground text-xs">
- {serviceType === 'marine' ? t('vessel') : t('vehicle')}
- </dt>
- <dd>
- {inspection.vehicle.year} {inspection.vehicle.make} {inspection.vehicle.model}
- </dd>
- </div>
- {inspection.vehicle.vin && (
- <div>
- <dt className="text-muted-foreground text-xs">
- {serviceType === 'marine' ? 'HIN' : 'VIN'}
- </dt>
- <dd className="font-mono text-xs break-all">{inspection.vehicle.vin}</dd>
- </div>
- )}
- {inspection.vehicle.licensePlate && (
- <div>
- <dt className="text-muted-foreground text-xs">
- {serviceType === 'marine' ? t('registration') : t('plate')}
- </dt>
- <dd className="font-mono">{inspection.vehicle.licensePlate}</dd>
- </div>
- )}
- {inspection.vehicle.customer && (
- <div>
- <dt className="text-muted-foreground text-xs">{t('customer')}</dt>
- <dd>
- <Link
- href={`/customers/${inspection.vehicle.customer.id}`}
- className="hover:underline"
- >
- {inspection.vehicle.customer.name}
- </Link>
- </dd>
- </div>
- )}
- </dl>
- </section>
- <section aria-labelledby="inspection-template" className="bg-card rounded-lg border p-4">
- <div className="flex items-baseline justify-between gap-2">
- <h2 id="inspection-template" className="text-sm font-semibold">
- {t('template')}
- </h2>
- <a
- href="https://torqvoice.com/docs/features/inspections"
- target="_blank"
- rel="noopener noreferrer"
- className="text-muted-foreground hover:text-foreground focus-visible:ring-ring shrink-0 rounded text-[11px] transition-colors focus-visible:ring-2 focus-visible:outline-none"
- >
- {t('readMore')} →
- </a>
- </div>
- <p className="mt-1 text-sm">{inspection.template.name}</p>
- <p className="text-muted-foreground mt-1 text-xs">
- {scale === 'eu' ? t('scaleEu') : t('scaleBasic')}
- {country ? ` ${t('country', { code: country })}` : ''}
- </p>
- <Link
- href="/settings/templates?tab=inspections"
- className="text-primary focus-visible:ring-ring mt-3 inline-flex items-center gap-1.5 rounded-md text-sm hover:underline focus-visible:ring-2 focus-visible:outline-none"
- >
- <Settings2 className="h-3.5 w-3.5" aria-hidden="true" />
- {t('manageInspectionTemplates')}
- </Link>
- </section>
- </aside>
- </div>
- <PdfPreviewDialog
- open={showPreview}
- onOpenChange={setShowPreview}
- url={`/api/protected/inspections/${inspection.id}/pdf`}
- />
- {/* Work order: a new job or an open one, and whether the defects come along */}
- <WorkOrderFromInspectionDialog
- open={showWorkOrderDialog}
- onOpenChange={setShowWorkOrderDialog}
- inspectionId={inspection.id}
- defects={defectItems.map((item) => ({
- id: item.id,
- name: item.name,
- condition: grades[item.id] ?? item.condition,
- sortOrder: item.sortOrder,
- }))}
- onDone={(job) => {
- setIsCreatingWorkOrder(true)
- router.push(`/vehicles/${job.vehicleId}/service/${job.id}`)
- }}
- />
- {/* Complete confirmation */}
- <ConfirmFrame
- open={showCompleteDialog}
- onDismiss={() => setShowCompleteDialog(false)}
- title={t('completeTitle')}
- icon={CheckCircle2}
- footer={
- <>
- <ConfirmFrameCancel>{t('cancel')}</ConfirmFrameCancel>
- <ConfirmFrameAction
- onClick={handleComplete}
- disabled={isPending || blockers.length > 0}
- >
- {t('complete')}
- </ConfirmFrameAction>
- </>
- }
- >
- <ConfirmFrameText>
- <p>{t('completeBody', { result: resultLabel(deriveTestResult(gradedItems)) })}</p>
- {blockers.length > 0 && (
- <p className="text-destructive font-medium">
- {t('completeBlocked', { count: blockers.length })}
- </p>
- )}
- </ConfirmFrameText>
- {/* What stands in the way, named, so the count is not taken on trust. */}
- <ConfirmSubjectList
- divided
- rows={blockers.slice(0, 8).map((blocker) => ({
- label: blocker.label,
- detail:
- blocker.reason === 'missing-grade'
- ? t('blockerMissingGrade')
- : t('blockerNeedsPhoto'),
- }))}
- more={Math.max(0, blockers.length - 8)}
- />
- <ConfirmConsequenceList
- lines={[
- ...(notInspected > 0
- ? [{ text: t('completeUngraded', { count: notInspected }), emphasis: true }]
- : []),
- ...(counts.dangerous > 0
- ? [
- {
- text: t('completeDangerous', { count: counts.dangerous }),
- icon: TriangleAlert,
- emphasis: true,
- },
- ]
- : []),
- ]}
- />
- </ConfirmFrame>
- <InspectionShareDialog
- open={showShareDialog}
- onOpenChange={setShowShareDialog}
- inspectionId={inspection.id}
- organizationId={inspection.organizationId}
- publicToken={inspection.publicToken}
- />
- <SendDocumentDialog
- open={showSendDialog}
- onOpenChange={setShowSendDialog}
- kind="inspection"
- documentId={inspection.id}
- shareUrl={
- inspection.publicToken
- ? `${typeof window !== 'undefined' ? window.location.origin : ''}/share/inspection/${inspection.organizationId}/${inspection.publicToken}`
- : null
- }
- customer={inspection.vehicle.customer}
- sendEmail={(email, message, attachPdf) =>
- sendInspectionEmail({
- inspectionId: inspection.id,
- recipientEmail: email,
- message,
- attachPdf,
- })
- }
- onSent={() => router.refresh()}
- />
- <MediaLightbox
- images={images}
- index={lightboxIndex}
- onClose={() => setLightboxIndex(null)}
- onNavigate={setLightboxIndex}
- />
- </div>
- )
- }
- /**
- * One action in the bar. On a phone or a tablet the bar is icons, each with
- * its name as the accessible label and tooltip; from a laptop up the label
- * is drawn beside the icon. Same name either way, so tests and screen
- * readers find "Complete" whatever the width.
- */
- function BarButton({
- icon: Icon,
- label,
- spinning = false,
- className,
- ...props
- }: Omit<ComponentProps<typeof Button>, 'children'> & {
- icon: ComponentType<{ className?: string; 'aria-hidden'?: boolean | 'true' }>
- label: string
- spinning?: boolean
- }) {
- return (
- <Button
- size="sm"
- aria-label={label}
- title={label}
- className={cn('px-2.5 lg:px-3', className)}
- {...props}
- >
- <Icon className={cn('h-4 w-4 lg:mr-1', spinning && 'animate-spin')} aria-hidden="true" />
- <span className="hidden lg:inline">{label}</span>
- </Button>
- )
- }
- /**
- * One tile of the next-step card. The whole tile is the button: the action
- * is its heading, the reason sits under it, and a chevron says it goes
- * somewhere. Once the thing exists the tile turns green and reads as a link
- * to it; a customer's pending quote request turns it amber.
- */
- function NextStepRow({
- icon: Icon,
- text,
- detail,
- action,
- onAction,
- busy = false,
- tone,
- testId,
- }: {
- icon: ComponentType<{ className?: string; 'aria-hidden'?: boolean | 'true' }>
- text: string
- detail?: string
- action: string
- onAction: () => void
- busy?: boolean
- tone?: 'done' | 'attention'
- testId: string
- }) {
- const tile =
- tone === 'done'
- ? 'border-emerald-500/30 bg-emerald-500/5 hover:bg-emerald-500/10'
- : tone === 'attention'
- ? 'border-amber-500/40 bg-amber-500/5 hover:bg-amber-500/10'
- : 'border-border bg-background hover:bg-muted/60'
- const bubble =
- tone === 'done'
- ? 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-300'
- : tone === 'attention'
- ? 'bg-amber-500/15 text-amber-800 dark:text-amber-300'
- : 'bg-primary/10 text-primary'
- return (
- <button
- type="button"
- disabled={busy}
- onClick={onAction}
- data-testid={testId}
- className={cn(
- 'group flex w-full cursor-pointer items-center gap-3 rounded-lg border p-3 text-left transition-colors',
- 'focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none disabled:cursor-default disabled:opacity-70',
- tile
- )}
- >
- <span
- className={cn('flex h-9 w-9 shrink-0 items-center justify-center rounded-full', bubble)}
- aria-hidden="true"
- >
- {tone === 'done' ? <CheckCircle2 className="h-4 w-4" /> : <Icon className="h-4 w-4" />}
- </span>
- <span className="min-w-0 flex-1">
- <span className="block text-sm font-medium">{action}</span>
- <span className="text-muted-foreground block text-xs leading-snug">{text}</span>
- {detail && (
- <span className="text-muted-foreground mt-1 block truncate text-xs italic">
- “{detail}”
- </span>
- )}
- </span>
- {busy ? (
- <Loader2
- className="text-muted-foreground h-4 w-4 shrink-0 animate-spin"
- aria-hidden="true"
- />
- ) : (
- <ChevronRight
- className="text-muted-foreground h-4 w-4 shrink-0 transition-transform group-hover:translate-x-0.5"
- aria-hidden="true"
- />
- )}
- </button>
- )
- }
|