InspectionPageClient.tsx 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  1. 'use client'
  2. import { type ComponentProps, type ComponentType, useMemo, useState, useTransition } from 'react'
  3. import { useRouter } from 'next/navigation'
  4. import Link from 'next/link'
  5. import { useFormatDate } from '@/lib/use-format-date'
  6. import {
  7. ConfirmConsequenceList,
  8. ConfirmFrame,
  9. ConfirmFrameAction,
  10. ConfirmFrameCancel,
  11. ConfirmFrameText,
  12. ConfirmSubjectList,
  13. useConfirm,
  14. } from '@/components/confirm-dialog'
  15. import { Button } from '@/components/ui/button'
  16. import { Badge } from '@/components/ui/badge'
  17. import {
  18. DropdownMenu,
  19. DropdownMenuContent,
  20. DropdownMenuItem,
  21. DropdownMenuSeparator,
  22. DropdownMenuTrigger,
  23. } from '@/components/ui/dropdown-menu'
  24. import {
  25. ChevronRight,
  26. ArrowLeft,
  27. CheckCircle2,
  28. Download,
  29. FileText,
  30. Loader2,
  31. MessageSquareText,
  32. MoreVertical,
  33. RotateCcw,
  34. Save,
  35. Settings2,
  36. Wrench,
  37. Send,
  38. Share2,
  39. Trash2,
  40. TriangleAlert,
  41. Eye,
  42. } from 'lucide-react'
  43. import { useTranslations } from 'next-intl'
  44. import { toast } from 'sonner'
  45. import {
  46. completeInspection,
  47. deleteInspection,
  48. reopenInspection,
  49. createQuoteFromInspection,
  50. } from '../Actions/inspectionActions'
  51. import { InspectionShareDialog } from './InspectionShareDialog'
  52. import { SendDocumentDialog } from '@/features/messaging/Components/SendDocumentDialog'
  53. import { sendInspectionEmail } from '@/features/email/Actions/emailActions'
  54. import { InspectionNotesCard } from './InspectionNotesCard'
  55. import { PdfPreviewDialog } from '@/components/pdf-preview-dialog'
  56. import { WorkOrderFromInspectionDialog } from './WorkOrderFromInspectionDialog'
  57. import { cn } from '@/lib/utils'
  58. import {
  59. InspectionFilesCard,
  60. type InspectionAttachmentData,
  61. type InspectionStatusReportData,
  62. } from './InspectionFilesCard'
  63. import { InspectionCertificateCard, type TechnicianOption } from './InspectionCertificateCard'
  64. import type { ConditionMarkData } from '@/features/condition-map/Lib/marks'
  65. import type { MarkType } from '@/features/condition-map/Lib/markTypes'
  66. import { InspectionItemRow, type InspectionItemData } from './InspectionItemRow'
  67. import { MediaLightbox, type LightboxImage } from './MediaLightbox'
  68. import { useServiceType } from '@/components/service-type-context'
  69. import { useSaveShortcut } from '@/hooks/use-save-shortcut'
  70. import {
  71. CONDITION_TOKENS,
  72. TEST_RESULT_TOKENS,
  73. countConditions,
  74. deriveTestResult,
  75. isDefect,
  76. worstCondition,
  77. type Condition,
  78. type SeverityScale,
  79. } from '../Lib/conditions'
  80. import { useConditionLabels } from '../Lib/useConditionLabels'
  81. import { findCompletionBlockers } from '../Lib/completion'
  82. export interface InspectionData {
  83. id: string
  84. status: string
  85. mileage: number | null
  86. notes: string | null
  87. publicToken: string | null
  88. completedAt: Date | null
  89. createdAt: Date
  90. organizationId: string
  91. severityScale: string | null
  92. country: string | null
  93. vehicleCategory: string | null
  94. nextTestDue: Date | null
  95. certificateNumber: string | null
  96. technicianId: string | null
  97. inspectorName: string | null
  98. testLocation: string | null
  99. vehicle: {
  100. id: string
  101. bodyType?: string | null
  102. make: string
  103. model: string
  104. year: number
  105. vin: string | null
  106. licensePlate: string | null
  107. mileage: number
  108. customer: {
  109. id: string
  110. name: string
  111. email: string | null
  112. phone: string | null
  113. telegramChatId?: string | null
  114. } | null
  115. }
  116. template: {
  117. id: string
  118. name: string
  119. severityScale?: string | null
  120. country?: string | null
  121. standard?: string | null
  122. }
  123. technician?: { id: string; name: string } | null
  124. items: InspectionItemData[]
  125. attachments?: InspectionAttachmentData[]
  126. quotes: {
  127. id: string
  128. quoteNumber: string | null
  129. status: string
  130. createdAt: Date
  131. user: { name: string }
  132. }[]
  133. quoteRequests: {
  134. id: string
  135. message: string | null
  136. selectedItemIds: string[]
  137. createdAt: Date
  138. }[]
  139. serviceRecords: {
  140. id: string
  141. title: string
  142. status: string
  143. invoiceNumber: string | null
  144. createdAt: Date
  145. }[]
  146. }
  147. const isVideo = (url: string) => /\.(mp4|webm|mov)$/i.test(url)
  148. /** Segmented bar showing how the checks are distributed across the grades. */
  149. function ProgressRail({
  150. counts,
  151. label,
  152. }: {
  153. counts: ReturnType<typeof countConditions>
  154. label: string
  155. }) {
  156. const segments = (
  157. [
  158. ['pass', counts.pass],
  159. ['attention', counts.attention],
  160. ['fail', counts.fail],
  161. ['dangerous', counts.dangerous],
  162. ['not_applicable', counts.notApplicable],
  163. ] as const
  164. )
  165. .map(([key, value]) => ({ key, value }))
  166. .filter((s) => s.value > 0)
  167. return (
  168. <div
  169. className="bg-muted flex h-2.5 w-full overflow-hidden rounded-full"
  170. role="img"
  171. aria-label={label}
  172. >
  173. {segments.map((segment) => (
  174. <div
  175. key={segment.key}
  176. className={CONDITION_TOKENS[segment.key].bar}
  177. style={{ width: `${(segment.value / Math.max(counts.total, 1)) * 100}%` }}
  178. />
  179. ))}
  180. </div>
  181. )
  182. }
  183. /**
  184. * The thin rule under a section header: how much of the section is graded,
  185. * in the grades' own colours, the rest left as the muted track.
  186. */
  187. function SectionRule({ counts }: { counts: ReturnType<typeof countConditions> }) {
  188. const segments = (
  189. [
  190. ['pass', counts.pass],
  191. ['attention', counts.attention],
  192. ['fail', counts.fail],
  193. ['dangerous', counts.dangerous],
  194. ['not_applicable', counts.notApplicable],
  195. ] as const
  196. ).filter(([, value]) => value > 0)
  197. return (
  198. <div className="bg-muted flex h-0.5 w-full overflow-hidden" aria-hidden="true">
  199. {segments.map(([key, value]) => (
  200. <div
  201. key={key}
  202. className={CONDITION_TOKENS[key].bar}
  203. style={{ width: `${(value / Math.max(counts.total, 1)) * 100}%` }}
  204. />
  205. ))}
  206. </div>
  207. )
  208. }
  209. function CountChip({
  210. condition,
  211. value,
  212. label,
  213. }: {
  214. condition: Condition
  215. value: number
  216. label: string
  217. }) {
  218. const token = CONDITION_TOKENS[condition]
  219. return (
  220. <div className="flex items-center gap-1.5">
  221. <span className={`h-2.5 w-2.5 shrink-0 rounded-full ${token.bar}`} aria-hidden="true" />
  222. <span className="text-xs">
  223. <span className="font-semibold">{value}</span>{' '}
  224. <span className="text-muted-foreground">{label}</span>
  225. </span>
  226. </div>
  227. )
  228. }
  229. export function InspectionPageClient({
  230. inspection,
  231. organizationId,
  232. smsEnabled = false,
  233. emailEnabled = false,
  234. telegramEnabled = false,
  235. statusReports = [],
  236. defectHistory = {},
  237. technicians = [],
  238. workshopAddress = '',
  239. conditionMarks = [],
  240. markTypes = [],
  241. }: {
  242. inspection: InspectionData
  243. /** Every mark on the vehicle's condition map, for a checklist that has one. */
  244. conditionMarks?: ConditionMarkData[]
  245. /** The workshop's kinds of mark, for the same checklist. */
  246. markTypes?: MarkType[]
  247. /** For the share links of the inspection's status reports. */
  248. organizationId: string
  249. smsEnabled?: boolean
  250. emailEnabled?: boolean
  251. telegramEnabled?: boolean
  252. /** Video reports sent to the customer from this inspection. */
  253. statusReports?: InspectionStatusReportData[]
  254. /** Wording this workshop has used before, keyed by check name. */
  255. defectHistory?: Record<string, { text: string; severity: string }[]>
  256. technicians?: TechnicianOption[]
  257. workshopAddress?: string
  258. }) {
  259. const t = useTranslations('inspections.page')
  260. const router = useRouter()
  261. const { formatDate } = useFormatDate()
  262. const serviceType = useServiceType()
  263. const [isPending, startTransition] = useTransition()
  264. const [showCompleteDialog, setShowCompleteDialog] = useState(false)
  265. const confirm = useConfirm()
  266. const [showShareDialog, setShowShareDialog] = useState(false)
  267. const [showSendDialog, setShowSendDialog] = useState(false)
  268. const [isCreatingQuote, setIsCreatingQuote] = useState(false)
  269. const [isCreatingWorkOrder, setIsCreatingWorkOrder] = useState(false)
  270. const [showWorkOrderDialog, setShowWorkOrderDialog] = useState(false)
  271. const [showPreview, setShowPreview] = useState(false)
  272. const [lightboxIndex, setLightboxIndex] = useState<number | null>(null)
  273. // The checklist saves each check as it is graded, which is only reassuring if
  274. // the page says so. Without this the technician has no way to tell a saved
  275. // inspection from one that silently failed halfway down a long Annex I sheet.
  276. const [savingIds, setSavingIds] = useState<Set<string>>(new Set())
  277. const [lastSavedAt, setLastSavedAt] = useState<Date | null>(null)
  278. const [saveFailed, setSaveFailed] = useState(false)
  279. // Grades and photo counts are mirrored here so the summary, the section nav
  280. // and the complete dialog react the moment a check is saved, instead of
  281. // waiting for a refresh. Photo counts matter as much as grades: a check that
  282. // requires evidence blocks completion until it has some.
  283. const [grades, setGrades] = useState<Record<string, Condition>>(() =>
  284. Object.fromEntries(inspection.items.map((i) => [i.id, i.condition as Condition]))
  285. )
  286. const [photoCounts, setPhotoCounts] = useState<Record<string, number>>(() =>
  287. Object.fromEntries(inspection.items.map((i) => [i.id, (i.imageUrls ?? []).length]))
  288. )
  289. const isCompleted = inspection.status === 'completed'
  290. // The snapshot wins; the template is the fallback for inspections that
  291. // predate it, and the migration pinned those templates to their old scale.
  292. const storedScale = inspection.severityScale ?? inspection.template.severityScale
  293. const scale: SeverityScale = storedScale === 'basic' ? 'basic' : 'eu'
  294. const country = inspection.country ?? inspection.template.country ?? null
  295. const {
  296. label: gradeLabel,
  297. graded,
  298. result: resultLabel,
  299. resultDetail,
  300. } = useConditionLabels(scale, country)
  301. const mileageLabel = serviceType === 'marine' ? t('engineHours') : t('odometer')
  302. const sections = useMemo(() => {
  303. const sorted = [...inspection.items].sort((a, b) => a.sortOrder - b.sortOrder)
  304. const order: string[] = []
  305. const grouped: Record<string, InspectionItemData[]> = {}
  306. for (const item of sorted) {
  307. if (!grouped[item.section]) {
  308. grouped[item.section] = []
  309. order.push(item.section)
  310. }
  311. grouped[item.section].push(item)
  312. }
  313. return order.map((name) => ({
  314. name,
  315. code: grouped[name][0]?.sectionCode ?? null,
  316. items: grouped[name],
  317. }))
  318. }, [inspection.items])
  319. const gradedItems = useMemo(
  320. () => inspection.items.map((i) => ({ condition: grades[i.id] ?? i.condition })),
  321. [inspection.items, grades]
  322. )
  323. const counts = useMemo(() => countConditions(gradedItems), [gradedItems])
  324. const result = useMemo(
  325. () => deriveTestResult(gradedItems, { requireAllInspected: !isCompleted }),
  326. [gradedItems, isCompleted]
  327. )
  328. const resultToken = TEST_RESULT_TOKENS[result]
  329. const images = useMemo<LightboxImage[]>(() => {
  330. const list: LightboxImage[] = []
  331. for (const item of inspection.items) {
  332. for (const url of item.imageUrls ?? []) {
  333. if (!isVideo(url)) list.push({ url, caption: item.name })
  334. }
  335. }
  336. return list
  337. }, [inspection.items])
  338. const defectItems = inspection.items.filter((i) => isDefect(grades[i.id] ?? i.condition))
  339. const blockers = useMemo(
  340. () =>
  341. findCompletionBlockers(
  342. inspection.items.map((item) => ({
  343. id: item.id,
  344. name: item.name,
  345. code: item.code,
  346. condition: grades[item.id] ?? item.condition,
  347. required: item.required,
  348. photoRequired: item.photoRequired,
  349. photoCount: photoCounts[item.id] ?? (item.imageUrls ?? []).length,
  350. }))
  351. ),
  352. [inspection.items, grades, photoCounts]
  353. )
  354. const pendingQuoteRequest = inspection.quoteRequests?.[0] ?? null
  355. // The checks the customer ticked, in checklist order; a check deleted since
  356. // the request is counted rather than shown.
  357. const requestedChecks = useMemo(() => {
  358. const wanted = new Set(pendingQuoteRequest?.selectedItemIds ?? [])
  359. return inspection.items.filter((item) => wanted.has(item.id))
  360. }, [inspection.items, pendingQuoteRequest])
  361. const missingRequestedChecks =
  362. (pendingQuoteRequest?.selectedItemIds.length ?? 0) - requestedChecks.length
  363. const requestedIds = useMemo(() => new Set(requestedChecks.map((i) => i.id)), [requestedChecks])
  364. const workOrder = inspection.serviceRecords?.[0] ?? null
  365. const notInspected = counts.total - counts.inspected
  366. const handleSaveState = (itemId: string, state: 'saving' | 'saved' | 'error') => {
  367. setSavingIds((prev) => {
  368. const next = new Set(prev)
  369. if (state === 'saving') next.add(itemId)
  370. else next.delete(itemId)
  371. return next
  372. })
  373. if (state === 'saved') {
  374. setLastSavedAt(new Date())
  375. setSaveFailed(false)
  376. }
  377. if (state === 'error') setSaveFailed(true)
  378. }
  379. /**
  380. * Fields commit on blur, so a note still being typed has not reached the
  381. * server yet. Taking focus off it is what actually saves; the button exists
  382. * because "it saves as you go" is not something a technician should have to
  383. * take on trust.
  384. */
  385. const handleSaveNow = () => {
  386. ;(document.activeElement as HTMLElement | null)?.blur()
  387. if (savingIds.size === 0 && !saveFailed) {
  388. toast.success(t('allSaved'))
  389. }
  390. }
  391. // The shortcut is pressed mid-sentence, so the field gets its focus back
  392. // once the blur has sent what was typed.
  393. useSaveShortcut(() => {
  394. const focused = document.activeElement as HTMLElement | null
  395. handleSaveNow()
  396. focused?.focus()
  397. }, !isCompleted)
  398. const openImage = (url: string) => {
  399. const index = images.findIndex((img) => img.url === url)
  400. setLightboxIndex(index >= 0 ? index : null)
  401. }
  402. /**
  403. * The quote is built on the server from what the database holds: the
  404. * inspection line, then every check that was not OK with the note as it
  405. * was saved, not as this page last saw it.
  406. */
  407. const handleCreateQuoteFromInspection = async () => {
  408. setIsCreatingQuote(true)
  409. // An action that cannot reach the server throws instead of answering, so
  410. // it is caught and reported the way a refusal is.
  411. const created = await createQuoteFromInspection(inspection.id).catch(() => null)
  412. if (created?.success && created.data) {
  413. router.push(`/quotes/${created.data.id}`)
  414. } else {
  415. toast.error(created?.error || t('quoteFailed'))
  416. setIsCreatingQuote(false)
  417. }
  418. }
  419. const handleComplete = () => {
  420. startTransition(async () => {
  421. const done = await completeInspection(inspection.id).catch(() => null)
  422. if (done?.success) {
  423. toast.success(t('completed'))
  424. setShowCompleteDialog(false)
  425. // A finished inspection is usually what the customer is waiting for.
  426. setShowSendDialog(true)
  427. router.refresh()
  428. } else {
  429. toast.error(done?.error || t('completeFailed'))
  430. }
  431. })
  432. }
  433. const handleReopen = async () => {
  434. const ok = await confirm({
  435. title: t('reopenTitle'),
  436. description: t('reopenBody'),
  437. consequences: inspection.publicToken ? [t('reopenShared')] : undefined,
  438. confirmLabel: t('reopen'),
  439. cancelLabel: t('cancel'),
  440. icon: RotateCcw,
  441. })
  442. if (!ok) return
  443. startTransition(async () => {
  444. const reopened = await reopenInspection(inspection.id).catch(() => null)
  445. if (reopened?.success) {
  446. toast.success(t('reopened'))
  447. router.refresh()
  448. } else {
  449. toast.error(reopened?.error || t('reopenFailed'))
  450. }
  451. })
  452. }
  453. const handleDelete = async () => {
  454. const ok = await confirm({
  455. title: t('deleteTitle'),
  456. description: t('deleteBody'),
  457. confirmLabel: t('delete'),
  458. cancelLabel: t('cancel'),
  459. icon: Trash2,
  460. destructive: true,
  461. })
  462. if (!ok) return
  463. startTransition(async () => {
  464. const removed = await deleteInspection(inspection.id).catch(() => null)
  465. if (removed?.success) {
  466. toast.success(t('deleted'))
  467. router.push('/inspections')
  468. } else {
  469. toast.error(removed?.error || t('deleteFailed'))
  470. }
  471. })
  472. }
  473. return (
  474. <div className="space-y-5">
  475. {/* Action bar */}
  476. <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">
  477. <div className="flex flex-wrap items-center justify-between gap-3">
  478. <div className="flex min-w-0 items-center gap-3">
  479. <Link
  480. href="/inspections"
  481. 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"
  482. >
  483. <ArrowLeft className="h-4 w-4" aria-hidden="true" />
  484. <span className="hidden sm:inline">{t('back')}</span>
  485. </Link>
  486. <div className="bg-border h-5 w-px" aria-hidden="true" />
  487. <div className="min-w-0">
  488. <h1 className="truncate text-base leading-tight font-semibold">
  489. {inspection.vehicle.year} {inspection.vehicle.make} {inspection.vehicle.model}
  490. </h1>
  491. <p className="text-muted-foreground truncate text-xs">
  492. {inspection.template.name} &middot; {formatDate(new Date(inspection.createdAt))}
  493. </p>
  494. </div>
  495. </div>
  496. <div className="flex items-center gap-2">
  497. <Badge
  498. variant="outline"
  499. className={
  500. isCompleted
  501. ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300'
  502. : 'border-blue-500/30 bg-blue-500/10 text-blue-700 dark:text-blue-300'
  503. }
  504. >
  505. {isCompleted ? t('statusCompleted') : t('statusInProgress')}
  506. </Badge>
  507. {!isCompleted && (
  508. <div className="mr-1 flex items-center gap-2">
  509. <p className="text-muted-foreground hidden text-xs sm:block" role="status">
  510. {savingIds.size > 0
  511. ? t('saving')
  512. : saveFailed
  513. ? t('saveFailed')
  514. : lastSavedAt
  515. ? t('savedAt', {
  516. time: lastSavedAt.toLocaleTimeString([], {
  517. hour: '2-digit',
  518. minute: '2-digit',
  519. }),
  520. })
  521. : t('savesAsYouGo')}
  522. </p>
  523. <BarButton
  524. variant="outline"
  525. icon={savingIds.size > 0 ? Loader2 : Save}
  526. spinning={savingIds.size > 0}
  527. label={t('save')}
  528. onClick={handleSaveNow}
  529. disabled={savingIds.size > 0}
  530. />
  531. </div>
  532. )}
  533. {isCompleted ? (
  534. <BarButton
  535. variant="outline"
  536. icon={RotateCcw}
  537. label={t('reopen')}
  538. onClick={handleReopen}
  539. />
  540. ) : (
  541. <BarButton
  542. icon={CheckCircle2}
  543. label={t('complete')}
  544. onClick={() => setShowCompleteDialog(true)}
  545. />
  546. )}
  547. {/* The certificate as the customer will get it, without leaving the page. */}
  548. <BarButton
  549. variant="outline"
  550. icon={Eye}
  551. label={t('preview')}
  552. onClick={() => setShowPreview(true)}
  553. data-testid="inspection-preview"
  554. />
  555. <BarButton
  556. variant="outline"
  557. icon={Send}
  558. label={t('send')}
  559. onClick={() => setShowSendDialog(true)}
  560. />
  561. <BarButton
  562. variant="outline"
  563. icon={Share2}
  564. label={t('share')}
  565. onClick={() => setShowShareDialog(true)}
  566. />
  567. <DropdownMenu>
  568. <DropdownMenuTrigger asChild>
  569. <Button
  570. variant="ghost"
  571. size="icon"
  572. className="h-9 w-9"
  573. aria-label={t('moreActions')}
  574. >
  575. <MoreVertical className="h-4 w-4" aria-hidden="true" />
  576. </Button>
  577. </DropdownMenuTrigger>
  578. <DropdownMenuContent align="end" className="min-w-52">
  579. <DropdownMenuItem
  580. onClick={() =>
  581. window.open(`/api/protected/inspections/${inspection.id}/pdf`, '_blank')
  582. }
  583. >
  584. <Download className="mr-2 h-4 w-4" aria-hidden="true" />
  585. {t('downloadCertificate')}
  586. </DropdownMenuItem>
  587. <DropdownMenuItem asChild>
  588. <Link href="/settings/templates?tab=inspections">
  589. <Settings2 className="mr-2 h-4 w-4" aria-hidden="true" />
  590. {t('manageTemplates')}
  591. </Link>
  592. </DropdownMenuItem>
  593. <DropdownMenuSeparator />
  594. <DropdownMenuItem className="text-destructive" onClick={handleDelete}>
  595. <Trash2 className="mr-2 h-4 w-4" aria-hidden="true" />
  596. {t('delete')}
  597. </DropdownMenuItem>
  598. </DropdownMenuContent>
  599. </DropdownMenu>
  600. </div>
  601. </div>
  602. </div>
  603. <div className="grid gap-5 lg:grid-cols-[1fr_19rem] lg:items-start">
  604. {/* Main column */}
  605. <main className="min-w-0 space-y-5">
  606. {/* Overall result */}
  607. <section
  608. aria-labelledby="inspection-result"
  609. className={`rounded-lg border p-4 ${resultToken.soft}`}
  610. >
  611. <h2 id="inspection-result" className="text-base font-semibold">
  612. {resultLabel(result)}
  613. </h2>
  614. <p className="mt-1 text-sm">{resultDetail(result)}</p>
  615. {result === 'incomplete' && notInspected > 0 && (
  616. <p className="mt-1 text-sm">
  617. {t('stillToGrade', { count: notInspected, total: counts.total })}
  618. </p>
  619. )}
  620. </section>
  621. {/* What the customer asked to have priced, from their link. Kept
  622. in view whether or not a quote exists yet: a second request can
  623. follow a first quote, and the desk must see both. */}
  624. {pendingQuoteRequest && (
  625. <section
  626. aria-labelledby="inspection-quote-request"
  627. data-testid="quote-request-card"
  628. className="rounded-lg border border-amber-500/40 bg-amber-500/5 p-4"
  629. >
  630. <div className="flex flex-wrap items-start justify-between gap-3">
  631. <div className="min-w-0">
  632. <h2
  633. id="inspection-quote-request"
  634. className="flex items-center gap-2 text-base font-semibold"
  635. >
  636. <MessageSquareText
  637. className="h-4 w-4 text-amber-700 dark:text-amber-300"
  638. aria-hidden="true"
  639. />
  640. {t('quoteRequestHeading')}
  641. </h2>
  642. <p className="text-muted-foreground mt-0.5 text-sm">
  643. {inspection.vehicle.customer?.name
  644. ? t('quoteRequestedBy', {
  645. name: inspection.vehicle.customer.name,
  646. date: formatDate(new Date(pendingQuoteRequest.createdAt)),
  647. })
  648. : t('quoteRequestedOn', {
  649. date: formatDate(new Date(pendingQuoteRequest.createdAt)),
  650. })}
  651. </p>
  652. </div>
  653. <Button
  654. size="sm"
  655. onClick={handleCreateQuoteFromInspection}
  656. disabled={isCreatingQuote}
  657. data-testid="quote-request-create"
  658. >
  659. {isCreatingQuote ? (
  660. <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
  661. ) : (
  662. <FileText className="h-4 w-4" aria-hidden="true" />
  663. )}
  664. {t('createQuoteFromRequest')}
  665. </Button>
  666. </div>
  667. {pendingQuoteRequest.message && (
  668. <blockquote className="mt-3 border-l-2 border-amber-500/50 pl-3 text-sm whitespace-pre-wrap">
  669. {pendingQuoteRequest.message}
  670. </blockquote>
  671. )}
  672. <ul className="mt-3 divide-y rounded-md border bg-background">
  673. {requestedChecks.map((item) => {
  674. const condition = (grades[item.id] ?? item.condition) as Condition
  675. return (
  676. <li
  677. key={item.id}
  678. className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 px-3 py-2 text-sm"
  679. >
  680. <span className="flex min-w-0 items-baseline gap-2">
  681. {item.code && (
  682. <span className="text-muted-foreground font-mono text-xs">
  683. {item.code}
  684. </span>
  685. )}
  686. <span className="font-medium">{item.name}</span>
  687. <span className="text-muted-foreground truncate text-xs">
  688. {item.section}
  689. </span>
  690. </span>
  691. <Badge variant="outline" className={CONDITION_TOKENS[condition].soft}>
  692. {graded(condition)}
  693. </Badge>
  694. </li>
  695. )
  696. })}
  697. </ul>
  698. {missingRequestedChecks > 0 && (
  699. <p className="text-muted-foreground mt-2 text-xs">
  700. {t('quoteRequestMissingChecks', { count: missingRequestedChecks })}
  701. </p>
  702. )}
  703. </section>
  704. )}
  705. <InspectionCertificateCard
  706. inspection={inspection}
  707. technicians={technicians}
  708. workshopAddress={workshopAddress}
  709. mileageLabel={mileageLabel}
  710. isCompleted={isCompleted}
  711. />
  712. {/* Checks: one card per section, drawn like a stamped page of the
  713. paper form. The name is set in the display face, the section
  714. code is printed large and faint at the right like a stamp, and
  715. a thin rule under the header shows how much is graded and in
  716. which grades. */}
  717. {sections.map((section, index) => {
  718. const sectionCounts = countConditions(
  719. section.items.map((i) => ({ condition: grades[i.id] ?? i.condition }))
  720. )
  721. const worst = worstCondition(section.items.map((i) => grades[i.id] ?? i.condition))
  722. const clean = sectionCounts.notInspected === 0 && !isDefect(worst)
  723. const rawCode = section.code ?? String(index + 1)
  724. const stamp = /^\d+$/.test(rawCode) ? rawCode.padStart(2, '0') : rawCode
  725. return (
  726. <section
  727. key={section.name}
  728. id={`section-${index}`}
  729. aria-labelledby={`section-${index}-heading`}
  730. className="bg-card scroll-mt-36 overflow-hidden rounded-lg border"
  731. >
  732. <header className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1 px-4 py-2">
  733. <h2
  734. id={`section-${index}-heading`}
  735. className="font-display min-w-0 truncate text-lg font-semibold tracking-wide uppercase"
  736. >
  737. {section.name}
  738. </h2>
  739. <div className="flex shrink-0 items-center gap-3">
  740. {isDefect(worst) && (
  741. <Badge variant="outline" className={CONDITION_TOKENS[worst].soft}>
  742. {graded(worst)}
  743. </Badge>
  744. )}
  745. <span className="text-muted-foreground text-xs tabular-nums">
  746. {t('graded', { graded: sectionCounts.inspected, total: sectionCounts.total })}
  747. </span>
  748. <span
  749. className={cn(
  750. 'font-display select-none text-3xl leading-none font-bold tracking-wide',
  751. clean
  752. ? 'text-emerald-600/45 dark:text-emerald-400/45'
  753. : 'text-foreground/15'
  754. )}
  755. aria-hidden="true"
  756. >
  757. {stamp}
  758. </span>
  759. </div>
  760. </header>
  761. <SectionRule counts={sectionCounts} />
  762. <ul className="space-y-2 p-3">
  763. {section.items.map((item) => (
  764. <InspectionItemRow
  765. key={item.id}
  766. item={item}
  767. inspectionId={inspection.id}
  768. inspectionOpenedAt={inspection.createdAt}
  769. scale={scale}
  770. country={country}
  771. standard={inspection.template.standard ?? null}
  772. isCompleted={isCompleted}
  773. history={defectHistory[item.name]}
  774. quoteRequested={requestedIds.has(item.id)}
  775. onOpenImage={openImage}
  776. onSaveState={handleSaveState}
  777. vehicle={{
  778. id: inspection.vehicle.id,
  779. bodyType: inspection.vehicle.bodyType ?? null,
  780. }}
  781. conditionMarks={conditionMarks}
  782. markTypes={markTypes}
  783. serviceType={serviceType}
  784. onChanged={(itemId, change) => {
  785. setGrades((prev) => ({ ...prev, [itemId]: change.condition }))
  786. setPhotoCounts((prev) => ({ ...prev, [itemId]: change.photoCount }))
  787. }}
  788. />
  789. ))}
  790. </ul>
  791. </section>
  792. )
  793. })}
  794. <InspectionFilesCard
  795. inspectionId={inspection.id}
  796. attachments={inspection.attachments ?? []}
  797. organizationId={organizationId}
  798. vehicleName={`${inspection.vehicle.year} ${inspection.vehicle.make} ${inspection.vehicle.model}`}
  799. customer={
  800. inspection.vehicle.customer
  801. ? {
  802. id: inspection.vehicle.customer.id,
  803. name: inspection.vehicle.customer.name,
  804. email: inspection.vehicle.customer.email,
  805. phone: inspection.vehicle.customer.phone,
  806. telegramChatId: inspection.vehicle.customer.telegramChatId ?? null,
  807. }
  808. : null
  809. }
  810. smsEnabled={smsEnabled}
  811. emailEnabled={emailEnabled}
  812. telegramEnabled={telegramEnabled}
  813. statusReports={statusReports}
  814. />
  815. </main>
  816. {/* Sidebar */}
  817. {/* Sticky, and no taller than what is left of the viewport under the
  818. action bar: a sidebar taller than the screen used to pin its top
  819. and hide its bottom until the checklist had scrolled all the way
  820. down. Scrolling over it now scrolls it, and the page after it. */}
  821. <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">
  822. {/* What happens with what was found: a job for the board, or a
  823. price for the customer first. Once one exists it is linked here. */}
  824. <section aria-labelledby="inspection-next-step" className="bg-card rounded-lg border p-4">
  825. <h2 id="inspection-next-step" className="text-sm font-semibold">
  826. {t('nextStep')}
  827. </h2>
  828. <div className="mt-3 space-y-2">
  829. {workOrder ? (
  830. <NextStepRow
  831. icon={Wrench}
  832. text={t('workOrderRaised', {
  833. number: workOrder.invoiceNumber ?? '',
  834. date: formatDate(new Date(workOrder.createdAt)),
  835. })}
  836. action={t('viewWorkOrder')}
  837. tone="done"
  838. onAction={() =>
  839. router.push(`/vehicles/${inspection.vehicle.id}/service/${workOrder.id}`)
  840. }
  841. testId="next-step-work-order"
  842. />
  843. ) : (
  844. <NextStepRow
  845. icon={Wrench}
  846. text={t('nextStepWorkOrderHint')}
  847. action={t('createWorkOrder')}
  848. busy={isCreatingWorkOrder}
  849. onAction={() => setShowWorkOrderDialog(true)}
  850. testId="next-step-work-order"
  851. />
  852. )}
  853. {inspection.quotes.length > 0 ? (
  854. <NextStepRow
  855. icon={FileText}
  856. text={t('quoteCreated', {
  857. name: inspection.quotes[0].user.name,
  858. date: formatDate(new Date(inspection.quotes[0].createdAt)),
  859. })}
  860. action={t('viewQuote')}
  861. tone="done"
  862. onAction={() => router.push(`/quotes/${inspection.quotes[0].id}`)}
  863. testId="next-step-quote"
  864. />
  865. ) : (
  866. <NextStepRow
  867. icon={pendingQuoteRequest ? MessageSquareText : FileText}
  868. tone={pendingQuoteRequest ? 'attention' : undefined}
  869. text={
  870. pendingQuoteRequest
  871. ? t('quoteRequested', { count: pendingQuoteRequest.selectedItemIds.length })
  872. : t('nextStepQuoteHint')
  873. }
  874. detail={pendingQuoteRequest?.message ?? undefined}
  875. action={t('createQuote')}
  876. busy={isCreatingQuote}
  877. onAction={handleCreateQuoteFromInspection}
  878. testId="next-step-quote"
  879. />
  880. )}
  881. </div>
  882. </section>
  883. <section aria-labelledby="inspection-progress" className="bg-card rounded-lg border p-4">
  884. <h2 id="inspection-progress" className="text-sm font-semibold">
  885. {t('progress')}
  886. </h2>
  887. <p className="mt-1 text-2xl font-semibold tabular-nums">
  888. {counts.inspected}
  889. <span className="text-muted-foreground text-base font-normal">/{counts.total}</span>
  890. </p>
  891. <p className="text-muted-foreground text-xs">{t('checksGraded')}</p>
  892. <div className="mt-3">
  893. <ProgressRail
  894. counts={counts}
  895. label={t('progressLabel', {
  896. graded: counts.inspected,
  897. total: counts.total,
  898. pass: counts.pass,
  899. attention: counts.attention,
  900. fail: counts.fail,
  901. dangerous: counts.dangerous,
  902. })}
  903. />
  904. </div>
  905. <div className="mt-3 grid gap-1.5">
  906. <CountChip condition="pass" value={counts.pass} label={gradeLabel('pass')} />
  907. <CountChip
  908. condition="attention"
  909. value={counts.attention}
  910. label={gradeLabel('attention')}
  911. />
  912. <CountChip condition="fail" value={counts.fail} label={gradeLabel('fail')} />
  913. {counts.notApplicable > 0 && (
  914. <CountChip
  915. condition="not_applicable"
  916. value={counts.notApplicable}
  917. label={gradeLabel('not_applicable')}
  918. />
  919. )}
  920. {scale === 'eu' && (
  921. <CountChip
  922. condition="dangerous"
  923. value={counts.dangerous}
  924. label={gradeLabel('dangerous')}
  925. />
  926. )}
  927. </div>
  928. </section>
  929. <InspectionNotesCard
  930. inspectionId={inspection.id}
  931. notes={inspection.notes}
  932. disabled={isCompleted}
  933. />
  934. <nav aria-labelledby="inspection-sections" className="bg-card rounded-lg border p-4">
  935. <h2 id="inspection-sections" className="text-sm font-semibold">
  936. {t('sections')}
  937. </h2>
  938. <ul className="mt-2 space-y-0.5">
  939. {sections.map((section, index) => {
  940. const sectionCounts = countConditions(
  941. section.items.map((i) => ({ condition: grades[i.id] ?? i.condition }))
  942. )
  943. const worst = worstCondition(section.items.map((i) => grades[i.id] ?? i.condition))
  944. return (
  945. <li key={section.name}>
  946. <a
  947. href={`#section-${index}`}
  948. 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"
  949. >
  950. <span
  951. className={`h-2 w-2 shrink-0 rounded-full ${CONDITION_TOKENS[worst].bar}`}
  952. aria-hidden="true"
  953. />
  954. <span className="min-w-0 flex-1 truncate">{section.name}</span>
  955. <span className="text-muted-foreground shrink-0 text-xs tabular-nums">
  956. {sectionCounts.inspected}/{sectionCounts.total}
  957. </span>
  958. </a>
  959. </li>
  960. )
  961. })}
  962. </ul>
  963. </nav>
  964. <section aria-labelledby="inspection-vehicle" className="bg-card rounded-lg border p-4">
  965. <h2 id="inspection-vehicle" className="text-sm font-semibold">
  966. {t('vehicle')}
  967. </h2>
  968. <dl className="mt-2 space-y-2 text-sm">
  969. <div>
  970. <dt className="text-muted-foreground text-xs">
  971. {serviceType === 'marine' ? t('vessel') : t('vehicle')}
  972. </dt>
  973. <dd>
  974. {inspection.vehicle.year} {inspection.vehicle.make} {inspection.vehicle.model}
  975. </dd>
  976. </div>
  977. {inspection.vehicle.vin && (
  978. <div>
  979. <dt className="text-muted-foreground text-xs">
  980. {serviceType === 'marine' ? 'HIN' : 'VIN'}
  981. </dt>
  982. <dd className="font-mono text-xs break-all">{inspection.vehicle.vin}</dd>
  983. </div>
  984. )}
  985. {inspection.vehicle.licensePlate && (
  986. <div>
  987. <dt className="text-muted-foreground text-xs">
  988. {serviceType === 'marine' ? t('registration') : t('plate')}
  989. </dt>
  990. <dd className="font-mono">{inspection.vehicle.licensePlate}</dd>
  991. </div>
  992. )}
  993. {inspection.vehicle.customer && (
  994. <div>
  995. <dt className="text-muted-foreground text-xs">{t('customer')}</dt>
  996. <dd>
  997. <Link
  998. href={`/customers/${inspection.vehicle.customer.id}`}
  999. className="hover:underline"
  1000. >
  1001. {inspection.vehicle.customer.name}
  1002. </Link>
  1003. </dd>
  1004. </div>
  1005. )}
  1006. </dl>
  1007. </section>
  1008. <section aria-labelledby="inspection-template" className="bg-card rounded-lg border p-4">
  1009. <div className="flex items-baseline justify-between gap-2">
  1010. <h2 id="inspection-template" className="text-sm font-semibold">
  1011. {t('template')}
  1012. </h2>
  1013. <a
  1014. href="https://torqvoice.com/docs/features/inspections"
  1015. target="_blank"
  1016. rel="noopener noreferrer"
  1017. 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"
  1018. >
  1019. {t('readMore')} →
  1020. </a>
  1021. </div>
  1022. <p className="mt-1 text-sm">{inspection.template.name}</p>
  1023. <p className="text-muted-foreground mt-1 text-xs">
  1024. {scale === 'eu' ? t('scaleEu') : t('scaleBasic')}
  1025. {country ? ` ${t('country', { code: country })}` : ''}
  1026. </p>
  1027. <Link
  1028. href="/settings/templates?tab=inspections"
  1029. 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"
  1030. >
  1031. <Settings2 className="h-3.5 w-3.5" aria-hidden="true" />
  1032. {t('manageInspectionTemplates')}
  1033. </Link>
  1034. </section>
  1035. </aside>
  1036. </div>
  1037. <PdfPreviewDialog
  1038. open={showPreview}
  1039. onOpenChange={setShowPreview}
  1040. url={`/api/protected/inspections/${inspection.id}/pdf`}
  1041. />
  1042. {/* Work order: a new job or an open one, and whether the defects come along */}
  1043. <WorkOrderFromInspectionDialog
  1044. open={showWorkOrderDialog}
  1045. onOpenChange={setShowWorkOrderDialog}
  1046. inspectionId={inspection.id}
  1047. defects={defectItems.map((item) => ({
  1048. id: item.id,
  1049. name: item.name,
  1050. condition: grades[item.id] ?? item.condition,
  1051. sortOrder: item.sortOrder,
  1052. }))}
  1053. onDone={(job) => {
  1054. setIsCreatingWorkOrder(true)
  1055. router.push(`/vehicles/${job.vehicleId}/service/${job.id}`)
  1056. }}
  1057. />
  1058. {/* Complete confirmation */}
  1059. <ConfirmFrame
  1060. open={showCompleteDialog}
  1061. onDismiss={() => setShowCompleteDialog(false)}
  1062. title={t('completeTitle')}
  1063. icon={CheckCircle2}
  1064. footer={
  1065. <>
  1066. <ConfirmFrameCancel>{t('cancel')}</ConfirmFrameCancel>
  1067. <ConfirmFrameAction
  1068. onClick={handleComplete}
  1069. disabled={isPending || blockers.length > 0}
  1070. >
  1071. {t('complete')}
  1072. </ConfirmFrameAction>
  1073. </>
  1074. }
  1075. >
  1076. <ConfirmFrameText>
  1077. <p>{t('completeBody', { result: resultLabel(deriveTestResult(gradedItems)) })}</p>
  1078. {blockers.length > 0 && (
  1079. <p className="text-destructive font-medium">
  1080. {t('completeBlocked', { count: blockers.length })}
  1081. </p>
  1082. )}
  1083. </ConfirmFrameText>
  1084. {/* What stands in the way, named, so the count is not taken on trust. */}
  1085. <ConfirmSubjectList
  1086. divided
  1087. rows={blockers.slice(0, 8).map((blocker) => ({
  1088. label: blocker.label,
  1089. detail:
  1090. blocker.reason === 'missing-grade'
  1091. ? t('blockerMissingGrade')
  1092. : t('blockerNeedsPhoto'),
  1093. }))}
  1094. more={Math.max(0, blockers.length - 8)}
  1095. />
  1096. <ConfirmConsequenceList
  1097. lines={[
  1098. ...(notInspected > 0
  1099. ? [{ text: t('completeUngraded', { count: notInspected }), emphasis: true }]
  1100. : []),
  1101. ...(counts.dangerous > 0
  1102. ? [
  1103. {
  1104. text: t('completeDangerous', { count: counts.dangerous }),
  1105. icon: TriangleAlert,
  1106. emphasis: true,
  1107. },
  1108. ]
  1109. : []),
  1110. ]}
  1111. />
  1112. </ConfirmFrame>
  1113. <InspectionShareDialog
  1114. open={showShareDialog}
  1115. onOpenChange={setShowShareDialog}
  1116. inspectionId={inspection.id}
  1117. organizationId={inspection.organizationId}
  1118. publicToken={inspection.publicToken}
  1119. />
  1120. <SendDocumentDialog
  1121. open={showSendDialog}
  1122. onOpenChange={setShowSendDialog}
  1123. kind="inspection"
  1124. documentId={inspection.id}
  1125. shareUrl={
  1126. inspection.publicToken
  1127. ? `${typeof window !== 'undefined' ? window.location.origin : ''}/share/inspection/${inspection.organizationId}/${inspection.publicToken}`
  1128. : null
  1129. }
  1130. customer={inspection.vehicle.customer}
  1131. sendEmail={(email, message, attachPdf) =>
  1132. sendInspectionEmail({
  1133. inspectionId: inspection.id,
  1134. recipientEmail: email,
  1135. message,
  1136. attachPdf,
  1137. })
  1138. }
  1139. onSent={() => router.refresh()}
  1140. />
  1141. <MediaLightbox
  1142. images={images}
  1143. index={lightboxIndex}
  1144. onClose={() => setLightboxIndex(null)}
  1145. onNavigate={setLightboxIndex}
  1146. />
  1147. </div>
  1148. )
  1149. }
  1150. /**
  1151. * One action in the bar. On a phone or a tablet the bar is icons, each with
  1152. * its name as the accessible label and tooltip; from a laptop up the label
  1153. * is drawn beside the icon. Same name either way, so tests and screen
  1154. * readers find "Complete" whatever the width.
  1155. */
  1156. function BarButton({
  1157. icon: Icon,
  1158. label,
  1159. spinning = false,
  1160. className,
  1161. ...props
  1162. }: Omit<ComponentProps<typeof Button>, 'children'> & {
  1163. icon: ComponentType<{ className?: string; 'aria-hidden'?: boolean | 'true' }>
  1164. label: string
  1165. spinning?: boolean
  1166. }) {
  1167. return (
  1168. <Button
  1169. size="sm"
  1170. aria-label={label}
  1171. title={label}
  1172. className={cn('px-2.5 lg:px-3', className)}
  1173. {...props}
  1174. >
  1175. <Icon className={cn('h-4 w-4 lg:mr-1', spinning && 'animate-spin')} aria-hidden="true" />
  1176. <span className="hidden lg:inline">{label}</span>
  1177. </Button>
  1178. )
  1179. }
  1180. /**
  1181. * One tile of the next-step card. The whole tile is the button: the action
  1182. * is its heading, the reason sits under it, and a chevron says it goes
  1183. * somewhere. Once the thing exists the tile turns green and reads as a link
  1184. * to it; a customer's pending quote request turns it amber.
  1185. */
  1186. function NextStepRow({
  1187. icon: Icon,
  1188. text,
  1189. detail,
  1190. action,
  1191. onAction,
  1192. busy = false,
  1193. tone,
  1194. testId,
  1195. }: {
  1196. icon: ComponentType<{ className?: string; 'aria-hidden'?: boolean | 'true' }>
  1197. text: string
  1198. detail?: string
  1199. action: string
  1200. onAction: () => void
  1201. busy?: boolean
  1202. tone?: 'done' | 'attention'
  1203. testId: string
  1204. }) {
  1205. const tile =
  1206. tone === 'done'
  1207. ? 'border-emerald-500/30 bg-emerald-500/5 hover:bg-emerald-500/10'
  1208. : tone === 'attention'
  1209. ? 'border-amber-500/40 bg-amber-500/5 hover:bg-amber-500/10'
  1210. : 'border-border bg-background hover:bg-muted/60'
  1211. const bubble =
  1212. tone === 'done'
  1213. ? 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-300'
  1214. : tone === 'attention'
  1215. ? 'bg-amber-500/15 text-amber-800 dark:text-amber-300'
  1216. : 'bg-primary/10 text-primary'
  1217. return (
  1218. <button
  1219. type="button"
  1220. disabled={busy}
  1221. onClick={onAction}
  1222. data-testid={testId}
  1223. className={cn(
  1224. 'group flex w-full cursor-pointer items-center gap-3 rounded-lg border p-3 text-left transition-colors',
  1225. 'focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none disabled:cursor-default disabled:opacity-70',
  1226. tile
  1227. )}
  1228. >
  1229. <span
  1230. className={cn('flex h-9 w-9 shrink-0 items-center justify-center rounded-full', bubble)}
  1231. aria-hidden="true"
  1232. >
  1233. {tone === 'done' ? <CheckCircle2 className="h-4 w-4" /> : <Icon className="h-4 w-4" />}
  1234. </span>
  1235. <span className="min-w-0 flex-1">
  1236. <span className="block text-sm font-medium">{action}</span>
  1237. <span className="text-muted-foreground block text-xs leading-snug">{text}</span>
  1238. {detail && (
  1239. <span className="text-muted-foreground mt-1 block truncate text-xs italic">
  1240. &ldquo;{detail}&rdquo;
  1241. </span>
  1242. )}
  1243. </span>
  1244. {busy ? (
  1245. <Loader2
  1246. className="text-muted-foreground h-4 w-4 shrink-0 animate-spin"
  1247. aria-hidden="true"
  1248. />
  1249. ) : (
  1250. <ChevronRight
  1251. className="text-muted-foreground h-4 w-4 shrink-0 transition-transform group-hover:translate-x-0.5"
  1252. aria-hidden="true"
  1253. />
  1254. )}
  1255. </button>
  1256. )
  1257. }