JobDetailPopover.tsx 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. 'use client'
  2. import { useState, useEffect, useCallback } from 'react'
  3. import Link from 'next/link'
  4. import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
  5. import { Button } from '@/components/ui/button'
  6. import { Badge } from '@/components/ui/badge'
  7. import { Label } from '@/components/ui/label'
  8. import { Wrench, ClipboardCheck, ExternalLink, Trash2 } from 'lucide-react'
  9. import type { WorkBoardJob } from '../Actions/boardActions'
  10. import {
  11. addJobHelper,
  12. removeJobHelper,
  13. updateServiceTimes,
  14. updateInspectionTimes,
  15. } from '../Actions/boardActions'
  16. import { cn } from '@/lib/utils'
  17. import { useWorkBoardStore } from '../store/workboardStore'
  18. import { DurationPicker } from './DurationSlider'
  19. import { DateTimePicker } from '@/components/ui/datetime-picker'
  20. import { useDateSettings } from '@/components/date-settings-context'
  21. import { useTranslations } from 'next-intl'
  22. import { toast } from 'sonner'
  23. import { getJobDateRange } from '../utils/datetime'
  24. import { vehicleName } from '@/lib/vehicle-name'
  25. export function JobDetailPopover({
  26. job,
  27. open,
  28. onOpenChange,
  29. onRemove,
  30. }: {
  31. job: WorkBoardJob
  32. open: boolean
  33. onOpenChange: (open: boolean) => void
  34. onRemove: () => void
  35. }) {
  36. const t = useTranslations('workBoard.jobDetail')
  37. const tJob = useTranslations('workBoard.job')
  38. // The board's own clock: the workshop's, not the viewer's browser.
  39. const { timezone } = useDateSettings()
  40. const store = useWorkBoardStore()
  41. const liveJob = store.jobs.find((j) => j.id === job.id) ?? job
  42. const { start: initStart, end: initEnd } = getJobDateRange(liveJob)
  43. const [startDate, setStartDate] = useState<Date | undefined>(initStart ?? undefined)
  44. const [endDate, setEndDate] = useState<Date | undefined>(initEnd ?? undefined)
  45. useEffect(() => {
  46. const { start, end } = getJobDateRange(liveJob)
  47. setStartDate(start ?? undefined)
  48. setEndDate(end ?? undefined)
  49. }, [liveJob.id, liveJob.startDateTime, liveJob.endDateTime])
  50. const isServiceRecord = liveJob.type === 'serviceRecord'
  51. const detailUrl = isServiceRecord
  52. ? `/vehicles/${liveJob.vehicle?.id}/service/${liveJob.id}`
  53. : `/inspections/${liveJob.id}`
  54. const saveTimes = useCallback(
  55. async (start: Date | undefined, end: Date | undefined) => {
  56. if (!start || !end) return
  57. if (end <= start) {
  58. toast.error(t('endBeforeStart'))
  59. return
  60. }
  61. store.updateServiceTimes(job.id, start.toISOString(), end.toISOString())
  62. const action = isServiceRecord ? updateServiceTimes : updateInspectionTimes
  63. const res = await action({
  64. id: job.id,
  65. startDateTime: start,
  66. endDateTime: end,
  67. })
  68. if (!res.success) {
  69. const { start: origStart, end: origEnd } = getJobDateRange(job)
  70. if (origStart && origEnd) {
  71. store.updateServiceTimes(job.id, origStart.toISOString(), origEnd.toISOString())
  72. }
  73. toast.error(t('failedTimes'))
  74. }
  75. },
  76. [job, store, t, isServiceRecord]
  77. )
  78. // Everybody who could also be put on the job: the board's technicians,
  79. // less the one who has it.
  80. const others = store.technicians.filter(
  81. (tech) => tech.isActive && tech.id !== liveJob.technicianId
  82. )
  83. const technicianName = store.technicians.find((tech) => tech.id === liveJob.technicianId)?.name
  84. /** Put somebody on the job beside its technician, or take them off it. */
  85. const toggleHelper = async (technicianId: string) => {
  86. const before = liveJob
  87. const helping = before.helperIds.includes(technicianId)
  88. store.updateJob({
  89. ...before,
  90. helperIds: helping
  91. ? before.helperIds.filter((id) => id !== technicianId)
  92. : [...before.helperIds, technicianId],
  93. })
  94. const res = await (helping ? removeJobHelper : addJobHelper)({ id: before.id, technicianId })
  95. if (res.success && res.data) {
  96. store.updateJob(res.data)
  97. } else {
  98. store.updateJob(before)
  99. toast.error(t('failedHelper'))
  100. }
  101. }
  102. const handleDurationChange = (hours: number | null) => {
  103. if (hours && startDate) {
  104. const newEnd = new Date(startDate.getTime() + hours * 3600000)
  105. setEndDate(newEnd)
  106. saveTimes(startDate, newEnd)
  107. }
  108. }
  109. const currentHours =
  110. startDate && endDate ? Math.round((endDate.getTime() - startDate.getTime()) / 3600000) : null
  111. return (
  112. <Dialog open={open} onOpenChange={onOpenChange}>
  113. <DialogContent className="sm:max-w-sm" aria-describedby={undefined}>
  114. <DialogHeader>
  115. <DialogTitle className="flex items-center gap-2">
  116. {isServiceRecord ? (
  117. <Wrench className="h-4 w-4 shrink-0 text-blue-500" />
  118. ) : (
  119. <ClipboardCheck className="h-4 w-4 shrink-0 text-green-500" />
  120. )}
  121. {liveJob.title}
  122. </DialogTitle>
  123. </DialogHeader>
  124. <div className="space-y-3">
  125. {liveJob.vehicle && (
  126. <p className="text-sm text-muted-foreground">
  127. {vehicleName(liveJob.vehicle)}
  128. {liveJob.vehicle.licensePlate ? ` · ${liveJob.vehicle.licensePlate}` : ''}
  129. </p>
  130. )}
  131. {liveJob.status && (
  132. <Badge variant="secondary" className="capitalize">
  133. {liveJob.status.replace(/_/g, ' ')}
  134. </Badge>
  135. )}
  136. {/* Who else is on the job. A work order with a technician only: an
  137. inspection is one person's work, and nobody can help on a job
  138. that nobody has. */}
  139. {isServiceRecord && liveJob.technicianId && others.length > 0 && (
  140. <div className="space-y-1.5">
  141. {/* "Also" on a job needs saying who has it. */}
  142. {technicianName && (
  143. <p className="text-sm">
  144. <span className="text-muted-foreground">{tJob('technician')}: </span>
  145. <span className="font-medium">{technicianName}</span>
  146. </p>
  147. )}
  148. <Label className="text-xs">{t('alsoOnJob')}</Label>
  149. <div className="flex flex-wrap gap-1">
  150. {others.map((tech) => {
  151. const helping = liveJob.helperIds.includes(tech.id)
  152. return (
  153. <button
  154. key={tech.id}
  155. type="button"
  156. aria-pressed={helping}
  157. onClick={() => void toggleHelper(tech.id)}
  158. className={cn(
  159. 'cursor-pointer rounded-md border px-2.5 py-1 text-xs font-medium transition-colors',
  160. helping
  161. ? 'border-primary bg-primary text-primary-foreground'
  162. : 'border-border bg-background text-foreground hover:bg-muted'
  163. )}
  164. >
  165. {tech.name}
  166. </button>
  167. )
  168. })}
  169. </div>
  170. </div>
  171. )}
  172. <DurationPicker value={currentHours} onChange={handleDurationChange} />
  173. <div className="space-y-1.5">
  174. <Label className="text-xs">{t('startTime')}</Label>
  175. <DateTimePicker
  176. value={startDate}
  177. onChange={(d) => {
  178. setStartDate(d)
  179. const newEnd = d ? new Date(d.getTime() + 3600000) : endDate
  180. setEndDate(newEnd)
  181. saveTimes(d, newEnd)
  182. }}
  183. timeZone={timezone}
  184. granularity="minute"
  185. hourCycle={24}
  186. placeholder={t('startTime')}
  187. />
  188. </div>
  189. <div className="space-y-1.5">
  190. <Label className="text-xs">{t('endTime')}</Label>
  191. <DateTimePicker
  192. value={endDate}
  193. onChange={(d) => {
  194. setEndDate(d)
  195. saveTimes(startDate, d)
  196. }}
  197. timeZone={timezone}
  198. granularity="minute"
  199. hourCycle={24}
  200. placeholder={t('endTime')}
  201. />
  202. </div>
  203. <div className="flex gap-2">
  204. <Button asChild variant="outline" size="sm" className="flex-1">
  205. <Link href={detailUrl}>
  206. <ExternalLink className="mr-1.5 h-3.5 w-3.5" />
  207. {t('viewDetails')}
  208. </Link>
  209. </Button>
  210. <Button variant="destructive" size="sm" onClick={onRemove}>
  211. <Trash2 className="mr-1.5 h-3.5 w-3.5" />
  212. {t('remove')}
  213. </Button>
  214. </div>
  215. </div>
  216. </DialogContent>
  217. </Dialog>
  218. )
  219. }