| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240 |
- 'use client'
- import { useState, useEffect, useCallback } from 'react'
- import Link from 'next/link'
- import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
- import { Button } from '@/components/ui/button'
- import { Badge } from '@/components/ui/badge'
- import { Label } from '@/components/ui/label'
- import { Wrench, ClipboardCheck, ExternalLink, Trash2 } from 'lucide-react'
- import type { WorkBoardJob } from '../Actions/boardActions'
- import {
- addJobHelper,
- removeJobHelper,
- updateServiceTimes,
- updateInspectionTimes,
- } from '../Actions/boardActions'
- import { cn } from '@/lib/utils'
- import { useWorkBoardStore } from '../store/workboardStore'
- import { DurationPicker } from './DurationSlider'
- import { DateTimePicker } from '@/components/ui/datetime-picker'
- import { useDateSettings } from '@/components/date-settings-context'
- import { useTranslations } from 'next-intl'
- import { toast } from 'sonner'
- import { getJobDateRange } from '../utils/datetime'
- import { vehicleName } from '@/lib/vehicle-name'
- export function JobDetailPopover({
- job,
- open,
- onOpenChange,
- onRemove,
- }: {
- job: WorkBoardJob
- open: boolean
- onOpenChange: (open: boolean) => void
- onRemove: () => void
- }) {
- const t = useTranslations('workBoard.jobDetail')
- const tJob = useTranslations('workBoard.job')
- // The board's own clock: the workshop's, not the viewer's browser.
- const { timezone } = useDateSettings()
- const store = useWorkBoardStore()
- const liveJob = store.jobs.find((j) => j.id === job.id) ?? job
- const { start: initStart, end: initEnd } = getJobDateRange(liveJob)
- const [startDate, setStartDate] = useState<Date | undefined>(initStart ?? undefined)
- const [endDate, setEndDate] = useState<Date | undefined>(initEnd ?? undefined)
- useEffect(() => {
- const { start, end } = getJobDateRange(liveJob)
- setStartDate(start ?? undefined)
- setEndDate(end ?? undefined)
- }, [liveJob.id, liveJob.startDateTime, liveJob.endDateTime])
- const isServiceRecord = liveJob.type === 'serviceRecord'
- const detailUrl = isServiceRecord
- ? `/vehicles/${liveJob.vehicle?.id}/service/${liveJob.id}`
- : `/inspections/${liveJob.id}`
- const saveTimes = useCallback(
- async (start: Date | undefined, end: Date | undefined) => {
- if (!start || !end) return
- if (end <= start) {
- toast.error(t('endBeforeStart'))
- return
- }
- store.updateServiceTimes(job.id, start.toISOString(), end.toISOString())
- const action = isServiceRecord ? updateServiceTimes : updateInspectionTimes
- const res = await action({
- id: job.id,
- startDateTime: start,
- endDateTime: end,
- })
- if (!res.success) {
- const { start: origStart, end: origEnd } = getJobDateRange(job)
- if (origStart && origEnd) {
- store.updateServiceTimes(job.id, origStart.toISOString(), origEnd.toISOString())
- }
- toast.error(t('failedTimes'))
- }
- },
- [job, store, t, isServiceRecord]
- )
- // Everybody who could also be put on the job: the board's technicians,
- // less the one who has it.
- const others = store.technicians.filter(
- (tech) => tech.isActive && tech.id !== liveJob.technicianId
- )
- const technicianName = store.technicians.find((tech) => tech.id === liveJob.technicianId)?.name
- /** Put somebody on the job beside its technician, or take them off it. */
- const toggleHelper = async (technicianId: string) => {
- const before = liveJob
- const helping = before.helperIds.includes(technicianId)
- store.updateJob({
- ...before,
- helperIds: helping
- ? before.helperIds.filter((id) => id !== technicianId)
- : [...before.helperIds, technicianId],
- })
- const res = await (helping ? removeJobHelper : addJobHelper)({ id: before.id, technicianId })
- if (res.success && res.data) {
- store.updateJob(res.data)
- } else {
- store.updateJob(before)
- toast.error(t('failedHelper'))
- }
- }
- const handleDurationChange = (hours: number | null) => {
- if (hours && startDate) {
- const newEnd = new Date(startDate.getTime() + hours * 3600000)
- setEndDate(newEnd)
- saveTimes(startDate, newEnd)
- }
- }
- const currentHours =
- startDate && endDate ? Math.round((endDate.getTime() - startDate.getTime()) / 3600000) : null
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-sm" aria-describedby={undefined}>
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2">
- {isServiceRecord ? (
- <Wrench className="h-4 w-4 shrink-0 text-blue-500" />
- ) : (
- <ClipboardCheck className="h-4 w-4 shrink-0 text-green-500" />
- )}
- {liveJob.title}
- </DialogTitle>
- </DialogHeader>
- <div className="space-y-3">
- {liveJob.vehicle && (
- <p className="text-sm text-muted-foreground">
- {vehicleName(liveJob.vehicle)}
- {liveJob.vehicle.licensePlate ? ` · ${liveJob.vehicle.licensePlate}` : ''}
- </p>
- )}
- {liveJob.status && (
- <Badge variant="secondary" className="capitalize">
- {liveJob.status.replace(/_/g, ' ')}
- </Badge>
- )}
- {/* Who else is on the job. A work order with a technician only: an
- inspection is one person's work, and nobody can help on a job
- that nobody has. */}
- {isServiceRecord && liveJob.technicianId && others.length > 0 && (
- <div className="space-y-1.5">
- {/* "Also" on a job needs saying who has it. */}
- {technicianName && (
- <p className="text-sm">
- <span className="text-muted-foreground">{tJob('technician')}: </span>
- <span className="font-medium">{technicianName}</span>
- </p>
- )}
- <Label className="text-xs">{t('alsoOnJob')}</Label>
- <div className="flex flex-wrap gap-1">
- {others.map((tech) => {
- const helping = liveJob.helperIds.includes(tech.id)
- return (
- <button
- key={tech.id}
- type="button"
- aria-pressed={helping}
- onClick={() => void toggleHelper(tech.id)}
- className={cn(
- 'cursor-pointer rounded-md border px-2.5 py-1 text-xs font-medium transition-colors',
- helping
- ? 'border-primary bg-primary text-primary-foreground'
- : 'border-border bg-background text-foreground hover:bg-muted'
- )}
- >
- {tech.name}
- </button>
- )
- })}
- </div>
- </div>
- )}
- <DurationPicker value={currentHours} onChange={handleDurationChange} />
- <div className="space-y-1.5">
- <Label className="text-xs">{t('startTime')}</Label>
- <DateTimePicker
- value={startDate}
- onChange={(d) => {
- setStartDate(d)
- const newEnd = d ? new Date(d.getTime() + 3600000) : endDate
- setEndDate(newEnd)
- saveTimes(d, newEnd)
- }}
- timeZone={timezone}
- granularity="minute"
- hourCycle={24}
- placeholder={t('startTime')}
- />
- </div>
- <div className="space-y-1.5">
- <Label className="text-xs">{t('endTime')}</Label>
- <DateTimePicker
- value={endDate}
- onChange={(d) => {
- setEndDate(d)
- saveTimes(startDate, d)
- }}
- timeZone={timezone}
- granularity="minute"
- hourCycle={24}
- placeholder={t('endTime')}
- />
- </div>
- <div className="flex gap-2">
- <Button asChild variant="outline" size="sm" className="flex-1">
- <Link href={detailUrl}>
- <ExternalLink className="mr-1.5 h-3.5 w-3.5" />
- {t('viewDetails')}
- </Link>
- </Button>
- <Button variant="destructive" size="sm" onClick={onRemove}>
- <Trash2 className="mr-1.5 h-3.5 w-3.5" />
- {t('remove')}
- </Button>
- </div>
- </div>
- </DialogContent>
- </Dialog>
- )
- }
|