Compare commits
17 Commits
a1dc4b0e47
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 5f4a12b9c4 | |||
|
|
3b0daeae0c | ||
|
|
0411df57eb | ||
|
|
082e388799 | ||
| abe75fb1fd | |||
|
|
45fd6d34eb | ||
| 30233b430f | |||
|
|
924a28e201 | ||
|
|
2cd646ddea | ||
|
|
3f9e125412 | ||
| 7bca854058 | |||
|
|
96d2a966d7 | ||
|
|
666ae8d59b | ||
| 67f1e4a26a | |||
|
|
613784a1cc | ||
| ea9aceec46 | |||
|
|
bc8613bbbc |
@@ -93,18 +93,14 @@ spec:
|
|||||||
secretKeyRef:
|
secretKeyRef:
|
||||||
name: lunarfront-secrets
|
name: lunarfront-secrets
|
||||||
key: business-name
|
key: business-name
|
||||||
|
- name: APP_URL
|
||||||
|
value: "https://{{ .Values.ingress.host }}"
|
||||||
- name: INITIAL_USER_EMAIL
|
- name: INITIAL_USER_EMAIL
|
||||||
valueFrom:
|
valueFrom:
|
||||||
secretKeyRef:
|
secretKeyRef:
|
||||||
name: lunarfront-secrets
|
name: lunarfront-secrets
|
||||||
key: initial-user-email
|
key: initial-user-email
|
||||||
optional: true
|
optional: true
|
||||||
- name: INITIAL_USER_PASSWORD
|
|
||||||
valueFrom:
|
|
||||||
secretKeyRef:
|
|
||||||
name: lunarfront-secrets
|
|
||||||
key: initial-user-password
|
|
||||||
optional: true
|
|
||||||
- name: INITIAL_USER_FIRST_NAME
|
- name: INITIAL_USER_FIRST_NAME
|
||||||
valueFrom:
|
valueFrom:
|
||||||
secretKeyRef:
|
secretKeyRef:
|
||||||
|
|||||||
@@ -14,3 +14,11 @@ interface LoginResponse {
|
|||||||
export async function login(email: string, password: string): Promise<LoginResponse> {
|
export async function login(email: string, password: string): Promise<LoginResponse> {
|
||||||
return api.post<LoginResponse>('/v1/auth/login', { email, password })
|
return api.post<LoginResponse>('/v1/auth/login', { email, password })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function forgotPassword(email: string): Promise<{ message: string }> {
|
||||||
|
return api.post<{ message: string }>('/v1/auth/forgot-password', { email })
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resetPassword(token: string, newPassword: string): Promise<{ message: string }> {
|
||||||
|
return api.post<{ message: string }>('/v1/auth/reset-password', { token, newPassword })
|
||||||
|
}
|
||||||
|
|||||||
@@ -84,6 +84,7 @@ export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transactio
|
|||||||
queryKey: ['pos', 'receipt', result?.id],
|
queryKey: ['pos', 'receipt', result?.id],
|
||||||
queryFn: () => api.get<{
|
queryFn: () => api.get<{
|
||||||
transaction: Transaction & { lineItems: { description: string; qty: number; unitPrice: string; taxAmount: string; lineTotal: string; discountAmount: string }[] }
|
transaction: Transaction & { lineItems: { description: string; qty: number; unitPrice: string; taxAmount: string; lineTotal: string; discountAmount: string }[] }
|
||||||
|
customerEmail: string | null
|
||||||
company: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
|
company: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
|
||||||
location: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
|
location: { name: string; phone: string | null; email: string | null; address: { street?: string; city?: string; state?: string; zip?: string } | null }
|
||||||
}>(`/v1/transactions/${result!.id}/receipt`),
|
}>(`/v1/transactions/${result!.id}/receipt`),
|
||||||
@@ -91,6 +92,19 @@ export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transactio
|
|||||||
})
|
})
|
||||||
|
|
||||||
const [showReceipt, setShowReceipt] = useState(false)
|
const [showReceipt, setShowReceipt] = useState(false)
|
||||||
|
const [emailMode, setEmailMode] = useState(false)
|
||||||
|
const [emailAddress, setEmailAddress] = useState('')
|
||||||
|
const [emailSent, setEmailSent] = useState(false)
|
||||||
|
|
||||||
|
const emailReceiptMutation = useMutation({
|
||||||
|
mutationFn: () => api.post<{ message: string }>(`/v1/transactions/${result!.id}/email-receipt`, { email: emailAddress }),
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Receipt emailed')
|
||||||
|
setEmailMode(false)
|
||||||
|
setEmailSent(true)
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
if (completed && result) {
|
if (completed && result) {
|
||||||
const changeGiven = parseFloat(result.changeGiven ?? '0')
|
const changeGiven = parseFloat(result.changeGiven ?? '0')
|
||||||
@@ -140,14 +154,47 @@ export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transactio
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="w-full grid grid-cols-2 gap-2">
|
{emailMode ? (
|
||||||
<Button variant="outline" className="h-11 gap-2" onClick={() => setShowReceipt(true)}>
|
<div className="w-full space-y-2">
|
||||||
<Printer className="h-4 w-4" />Receipt
|
<Label className="text-xs text-muted-foreground">Email receipt to:</Label>
|
||||||
</Button>
|
<div className="flex gap-2">
|
||||||
<Button variant="outline" className="h-11 gap-2" disabled>
|
<Input
|
||||||
<Mail className="h-4 w-4" />Email
|
type="email"
|
||||||
</Button>
|
value={emailAddress}
|
||||||
</div>
|
onChange={(e) => setEmailAddress(e.target.value)}
|
||||||
|
placeholder="customer@example.com"
|
||||||
|
className="h-9"
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
className="h-9 px-4"
|
||||||
|
onClick={() => emailReceiptMutation.mutate()}
|
||||||
|
disabled={!emailAddress || emailReceiptMutation.isPending}
|
||||||
|
>
|
||||||
|
{emailReceiptMutation.isPending ? 'Sending...' : 'Send'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="sm" className="text-xs" onClick={() => setEmailMode(false)}>Cancel</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="w-full grid grid-cols-2 gap-2">
|
||||||
|
<Button variant="outline" className="h-11 gap-2" onClick={() => setShowReceipt(true)}>
|
||||||
|
<Printer className="h-4 w-4" />Receipt
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="h-11 gap-2"
|
||||||
|
onClick={() => {
|
||||||
|
setEmailAddress(receiptData?.customerEmail ?? '')
|
||||||
|
setEmailMode(true)
|
||||||
|
}}
|
||||||
|
disabled={emailSent}
|
||||||
|
>
|
||||||
|
<Mail className="h-4 w-4" />{emailSent ? 'Sent' : 'Email'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<Button className="w-full h-12 text-base" onClick={handleDone}>
|
<Button className="w-full h-12 text-base" onClick={handleDone}>
|
||||||
New Sale
|
New Sale
|
||||||
|
|||||||
@@ -40,20 +40,25 @@ function configOptions(key: string) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function POSRegister() {
|
interface POSRegisterProps {
|
||||||
|
embedded?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function POSRegister({ embedded }: POSRegisterProps = {}) {
|
||||||
const { locationId, setLocation, currentTransactionId, setDrawerSession, locked, lock, touchActivity, token } = usePOSStore()
|
const { locationId, setLocation, currentTransactionId, setDrawerSession, locked, lock, touchActivity, token } = usePOSStore()
|
||||||
|
|
||||||
// Fetch lock timeout from config
|
// Fetch lock timeout from config (standalone only)
|
||||||
const { data: lockTimeoutStr } = useQuery({
|
const { data: lockTimeoutStr } = useQuery({
|
||||||
...configOptions('pos_lock_timeout'),
|
...configOptions('pos_lock_timeout'),
|
||||||
enabled: !!token,
|
enabled: !!token && !embedded,
|
||||||
})
|
})
|
||||||
const lockTimeoutMinutes = parseInt(lockTimeoutStr ?? '15') || 15
|
const lockTimeoutMinutes = parseInt(lockTimeoutStr ?? '15') || 15
|
||||||
|
|
||||||
// Auto-lock timer
|
// Auto-lock timer (standalone only — station shell handles this when embedded)
|
||||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (embedded) return
|
||||||
if (locked || lockTimeoutMinutes === 0) {
|
if (locked || lockTimeoutMinutes === 0) {
|
||||||
if (timerRef.current) clearInterval(timerRef.current)
|
if (timerRef.current) clearInterval(timerRef.current)
|
||||||
return
|
return
|
||||||
@@ -69,26 +74,27 @@ export function POSRegister() {
|
|||||||
return () => {
|
return () => {
|
||||||
if (timerRef.current) clearInterval(timerRef.current)
|
if (timerRef.current) clearInterval(timerRef.current)
|
||||||
}
|
}
|
||||||
}, [locked, lockTimeoutMinutes, lock])
|
}, [embedded, locked, lockTimeoutMinutes, lock])
|
||||||
|
|
||||||
// Track activity on any interaction
|
// Track activity (standalone only)
|
||||||
const handleActivity = useCallback(() => {
|
const handleActivity = useCallback(() => {
|
||||||
if (!locked) touchActivity()
|
if (!embedded && !locked) touchActivity()
|
||||||
}, [locked, touchActivity])
|
}, [embedded, locked, touchActivity])
|
||||||
|
|
||||||
// Fetch locations
|
// Fetch locations (standalone only — station shell handles this when embedded)
|
||||||
const { data: locationsData } = useQuery({
|
const { data: locationsData } = useQuery({
|
||||||
...locationsOptions(),
|
...locationsOptions(),
|
||||||
enabled: !!token,
|
enabled: !!token && !embedded,
|
||||||
})
|
})
|
||||||
const locations = locationsData?.data ?? []
|
const locations = locationsData?.data ?? []
|
||||||
|
|
||||||
// Auto-select first location
|
// Auto-select first location (standalone only)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (embedded) return
|
||||||
if (!locationId && locations.length > 0) {
|
if (!locationId && locations.length > 0) {
|
||||||
setLocation(locations[0].id)
|
setLocation(locations[0].id)
|
||||||
}
|
}
|
||||||
}, [locationId, locations, setLocation])
|
}, [embedded, locationId, locations, setLocation])
|
||||||
|
|
||||||
// Fetch current drawer for selected location
|
// Fetch current drawer for selected location
|
||||||
const { data: drawer } = useQuery({
|
const { data: drawer } = useQuery({
|
||||||
@@ -112,6 +118,20 @@ export function POSRegister() {
|
|||||||
enabled: !!currentTransactionId && !!token,
|
enabled: !!currentTransactionId && !!token,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Embedded mode: just the content panels, no wrapper/lock/topbar
|
||||||
|
if (embedded) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-1 h-full min-h-0">
|
||||||
|
<div className="w-[60%] border-r border-border overflow-hidden">
|
||||||
|
<POSItemPanel transaction={transaction ?? null} />
|
||||||
|
</div>
|
||||||
|
<div className="w-[40%] overflow-hidden">
|
||||||
|
<POSCartPanel transaction={transaction ?? null} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="relative flex flex-col h-full"
|
className="relative flex flex-col h-full"
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { CalendarDays, Calendar } from 'lucide-react'
|
||||||
|
import { LessonsTodayOverview } from './lessons-today-overview'
|
||||||
|
import { LessonsScheduleView } from './lessons-schedule-view'
|
||||||
|
|
||||||
|
interface LessonsDeskViewProps {
|
||||||
|
canEdit: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LessonsDeskView({ canEdit }: LessonsDeskViewProps) {
|
||||||
|
const [subView, setSubView] = useState<'today' | 'schedule'>('today')
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Sub-view toggle */}
|
||||||
|
<div className="flex items-center gap-1 px-3 py-2 border-b border-border shrink-0 bg-card/50">
|
||||||
|
<Button
|
||||||
|
variant={subView === 'today' ? 'default' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
className="h-8 gap-1.5"
|
||||||
|
onClick={() => setSubView('today')}
|
||||||
|
>
|
||||||
|
<CalendarDays className="h-3.5 w-3.5" />
|
||||||
|
Today
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={subView === 'schedule' ? 'default' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
className="h-8 gap-1.5"
|
||||||
|
onClick={() => setSubView('schedule')}
|
||||||
|
>
|
||||||
|
<Calendar className="h-3.5 w-3.5" />
|
||||||
|
Schedule
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex-1 min-h-0 overflow-hidden">
|
||||||
|
{subView === 'today' && <LessonsTodayOverview canEdit={canEdit} />}
|
||||||
|
{subView === 'schedule' && <LessonsScheduleView />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { usePOSStore } from '@/stores/pos.store'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { CalendarDays, CalendarRange } from 'lucide-react'
|
||||||
|
import { LessonsTodayOverview } from './lessons-today-overview'
|
||||||
|
import { LessonsWeekView } from './lessons-week-view'
|
||||||
|
|
||||||
|
interface LessonsInstructorViewProps {
|
||||||
|
canEdit: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LessonsInstructorView({ canEdit }: LessonsInstructorViewProps) {
|
||||||
|
const [subView, setSubView] = useState<'today' | 'week'>('today')
|
||||||
|
const cashier = usePOSStore((s) => s.cashier)
|
||||||
|
|
||||||
|
// TODO: Map cashier user ID to instructor ID
|
||||||
|
// For now, the instructor view shows the same data as desk view
|
||||||
|
// but filtered by the logged-in user's instructor record
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Sub-view toggle */}
|
||||||
|
<div className="flex items-center gap-1 px-3 py-2 border-b border-border shrink-0 bg-card/50">
|
||||||
|
<Button
|
||||||
|
variant={subView === 'today' ? 'default' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
className="h-8 gap-1.5"
|
||||||
|
onClick={() => setSubView('today')}
|
||||||
|
>
|
||||||
|
<CalendarDays className="h-3.5 w-3.5" />
|
||||||
|
My Sessions
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={subView === 'week' ? 'default' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
className="h-8 gap-1.5"
|
||||||
|
onClick={() => setSubView('week')}
|
||||||
|
>
|
||||||
|
<CalendarRange className="h-3.5 w-3.5" />
|
||||||
|
Week
|
||||||
|
</Button>
|
||||||
|
{cashier && (
|
||||||
|
<span className="text-xs text-muted-foreground ml-auto">
|
||||||
|
{cashier.firstName} {cashier.lastName}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex-1 min-h-0 overflow-hidden">
|
||||||
|
{subView === 'today' && <LessonsTodayOverview canEdit={canEdit} />}
|
||||||
|
{subView === 'week' && <LessonsWeekView canEdit={canEdit} />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { instructorListOptions, scheduleSlotListOptions } from '@/api/lessons'
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import type { ScheduleSlot, Instructor } from '@/types/lesson'
|
||||||
|
|
||||||
|
const DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
|
||||||
|
const HOURS = Array.from({ length: 14 }, (_, i) => i + 7) // 7 AM to 8 PM
|
||||||
|
|
||||||
|
export function LessonsScheduleView() {
|
||||||
|
const [selectedInstructorId, setSelectedInstructorId] = useState<string>('all')
|
||||||
|
|
||||||
|
const { data: instructorsData } = useQuery({
|
||||||
|
...instructorListOptions({ page: 1, limit: 100, q: undefined, sort: 'name', order: 'asc' }),
|
||||||
|
})
|
||||||
|
const instructors = (instructorsData?.data ?? []).filter((i: Instructor) => i.isActive !== false)
|
||||||
|
|
||||||
|
const { data: slotsData } = useQuery({
|
||||||
|
...scheduleSlotListOptions(
|
||||||
|
{ page: 1, limit: 500, q: undefined, sort: undefined, order: 'asc' },
|
||||||
|
selectedInstructorId !== 'all' ? { instructorId: selectedInstructorId } : undefined,
|
||||||
|
),
|
||||||
|
})
|
||||||
|
const slots = slotsData?.data ?? []
|
||||||
|
|
||||||
|
// Group slots by day
|
||||||
|
function getSlotsForDay(dayOfWeek: number) {
|
||||||
|
return slots.filter((s: ScheduleSlot) => s.dayOfWeek === dayOfWeek)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(time: string) {
|
||||||
|
const [h, m] = time.split(':').map(Number)
|
||||||
|
const ampm = h >= 12 ? 'PM' : 'AM'
|
||||||
|
const hour = h > 12 ? h - 12 : h === 0 ? 12 : h
|
||||||
|
return `${hour}:${m.toString().padStart(2, '0')} ${ampm}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Controls */}
|
||||||
|
<div className="flex items-center gap-3 px-3 py-2 border-b border-border shrink-0 bg-card/50">
|
||||||
|
<span className="text-sm font-medium">Weekly Schedule</span>
|
||||||
|
<Select value={selectedInstructorId} onValueChange={setSelectedInstructorId}>
|
||||||
|
<SelectTrigger className="h-8 w-48">
|
||||||
|
<SelectValue placeholder="All Instructors" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">All Instructors</SelectItem>
|
||||||
|
{instructors.map((inst: Instructor) => (
|
||||||
|
<SelectItem key={inst.id} value={inst.id}>{inst.displayName}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Badge variant="outline" className="text-xs">{slots.length} slots</Badge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Weekly grid */}
|
||||||
|
<div className="flex-1 overflow-auto">
|
||||||
|
<div className="grid grid-cols-8 min-w-[800px]">
|
||||||
|
{/* Header row */}
|
||||||
|
<div className="sticky top-0 bg-card border-b border-r border-border p-2 text-xs font-medium text-muted-foreground z-10" />
|
||||||
|
{DAYS.map((day) => (
|
||||||
|
<div key={day} className="sticky top-0 bg-card border-b border-border p-2 text-xs font-medium text-center z-10">
|
||||||
|
{day.slice(0, 3)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Time rows */}
|
||||||
|
{HOURS.map((hour) => (
|
||||||
|
<>
|
||||||
|
<div key={`h-${hour}`} className="border-r border-b border-border p-1 text-xs text-muted-foreground text-right pr-2">
|
||||||
|
{hour > 12 ? hour - 12 : hour}{hour >= 12 ? 'p' : 'a'}
|
||||||
|
</div>
|
||||||
|
{DAYS.map((_, dayIdx) => {
|
||||||
|
const daySlots = getSlotsForDay(dayIdx).filter((s: ScheduleSlot) => {
|
||||||
|
const slotHour = parseInt(s.startTime.split(':')[0])
|
||||||
|
return slotHour === hour
|
||||||
|
})
|
||||||
|
return (
|
||||||
|
<div key={`${hour}-${dayIdx}`} className="border-b border-border min-h-[48px] p-0.5">
|
||||||
|
{daySlots.map((slot: ScheduleSlot) => {
|
||||||
|
const instructor = instructors.find((i: Instructor) => i.id === slot.instructorId)
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={slot.id}
|
||||||
|
className="bg-primary/10 border border-primary/20 rounded px-1.5 py-0.5 text-xs mb-0.5"
|
||||||
|
>
|
||||||
|
<div className="font-medium truncate">{formatTime(slot.startTime)}</div>
|
||||||
|
{instructor && <div className="text-muted-foreground truncate">{instructor.displayName}</div>}
|
||||||
|
<Badge variant="outline" className="text-[9px] h-4">Open</Badge>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { LessonsDeskView } from './lessons-desk-view'
|
||||||
|
import { LessonsInstructorView } from './lessons-instructor-view'
|
||||||
|
|
||||||
|
interface LessonsStationProps {
|
||||||
|
permissions: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LessonsStation({ permissions }: LessonsStationProps) {
|
||||||
|
const canEdit = permissions.includes('lessons.edit') || permissions.includes('lessons.admin')
|
||||||
|
|
||||||
|
// Front desk (admin/edit) gets desk view with full overview
|
||||||
|
// Instructor (view only) gets focused instructor view
|
||||||
|
if (canEdit) {
|
||||||
|
return <LessonsDeskView canEdit={canEdit} />
|
||||||
|
}
|
||||||
|
|
||||||
|
return <LessonsInstructorView canEdit={false} />
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { sessionListOptions } from '@/api/lessons'
|
||||||
|
import type { LessonSession } from '@/types/lesson'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { SessionDetailPanel } from './session-detail-panel'
|
||||||
|
import { CheckCircle, Clock, XCircle, AlertCircle } from 'lucide-react'
|
||||||
|
|
||||||
|
const STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof CheckCircle }> = {
|
||||||
|
scheduled: { label: 'Scheduled', color: 'bg-blue-500/10 text-blue-500', icon: Clock },
|
||||||
|
attended: { label: 'Attended', color: 'bg-green-500/10 text-green-500', icon: CheckCircle },
|
||||||
|
missed: { label: 'Missed', color: 'bg-red-500/10 text-red-500', icon: XCircle },
|
||||||
|
makeup: { label: 'Makeup', color: 'bg-purple-500/10 text-purple-500', icon: Clock },
|
||||||
|
cancelled: { label: 'Cancelled', color: 'bg-muted text-muted-foreground', icon: XCircle },
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LessonsTodayOverviewProps {
|
||||||
|
canEdit: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LessonsTodayOverview({ canEdit }: LessonsTodayOverviewProps) {
|
||||||
|
const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null)
|
||||||
|
const [groupBy, setGroupBy] = useState<'time' | 'instructor'>('time')
|
||||||
|
|
||||||
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
|
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
...sessionListOptions({
|
||||||
|
page: 1,
|
||||||
|
limit: 100,
|
||||||
|
sort: 'scheduled_time',
|
||||||
|
order: 'asc',
|
||||||
|
scheduledDateFrom: today,
|
||||||
|
scheduledDateTo: today,
|
||||||
|
}),
|
||||||
|
staleTime: 30_000,
|
||||||
|
refetchInterval: 60_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const sessions = data?.data ?? []
|
||||||
|
|
||||||
|
// Check if a session is upcoming (within next 30 min)
|
||||||
|
function isUpcoming(session: LessonSession) {
|
||||||
|
if (session.status !== 'scheduled') return false
|
||||||
|
const now = new Date()
|
||||||
|
const [hours, minutes] = session.scheduledTime.split(':').map(Number)
|
||||||
|
const sessionTime = new Date(session.scheduledDate + 'T00:00:00')
|
||||||
|
sessionTime.setHours(hours, minutes)
|
||||||
|
const diff = sessionTime.getTime() - now.getTime()
|
||||||
|
return diff > 0 && diff <= 30 * 60_000
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if overdue (scheduled, past time)
|
||||||
|
function isOverdue(session: LessonSession) {
|
||||||
|
if (session.status !== 'scheduled') return false
|
||||||
|
const now = new Date()
|
||||||
|
const [hours, minutes] = session.scheduledTime.split(':').map(Number)
|
||||||
|
const sessionTime = new Date(session.scheduledDate + 'T00:00:00')
|
||||||
|
sessionTime.setHours(hours, minutes)
|
||||||
|
return sessionTime.getTime() < now.getTime()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group by instructor
|
||||||
|
const byInstructor = sessions.reduce((acc, s) => {
|
||||||
|
const name = s.instructorName ?? 'Unassigned'
|
||||||
|
if (!acc[name]) acc[name] = []
|
||||||
|
acc[name].push(s)
|
||||||
|
return acc
|
||||||
|
}, {} as Record<string, LessonSession[]>)
|
||||||
|
|
||||||
|
// Status counts
|
||||||
|
const scheduled = sessions.filter(s => s.status === 'scheduled').length
|
||||||
|
const attended = sessions.filter(s => s.status === 'attended').length
|
||||||
|
const missed = sessions.filter(s => s.status === 'missed').length
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Summary bar */}
|
||||||
|
<div className="flex items-center gap-3 px-3 py-2 border-b border-border shrink-0 bg-card/50">
|
||||||
|
<span className="text-sm font-medium">Today</span>
|
||||||
|
<Badge variant="outline" className="text-xs">{sessions.length} sessions</Badge>
|
||||||
|
{scheduled > 0 && <Badge variant="outline" className="text-xs bg-blue-500/10 text-blue-500">{scheduled} scheduled</Badge>}
|
||||||
|
{attended > 0 && <Badge variant="outline" className="text-xs bg-green-500/10 text-green-500">{attended} attended</Badge>}
|
||||||
|
{missed > 0 && <Badge variant="outline" className="text-xs bg-red-500/10 text-red-500">{missed} missed</Badge>}
|
||||||
|
<div className="flex-1" />
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<Button variant={groupBy === 'time' ? 'default' : 'ghost'} size="sm" className="h-7 text-xs" onClick={() => setGroupBy('time')}>By Time</Button>
|
||||||
|
<Button variant={groupBy === 'instructor' ? 'default' : 'ghost'} size="sm" className="h-7 text-xs" onClick={() => setGroupBy('instructor')}>By Instructor</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Split view */}
|
||||||
|
<div className="flex flex-1 min-h-0">
|
||||||
|
{/* Session list */}
|
||||||
|
<div className="w-[40%] border-r border-border overflow-y-auto">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="p-3 space-y-2">
|
||||||
|
{Array.from({ length: 5 }).map((_, i) => (
|
||||||
|
<div key={i} className="h-14 bg-muted animate-pulse rounded-lg" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : sessions.length === 0 ? (
|
||||||
|
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||||
|
<p className="text-sm">No sessions today</p>
|
||||||
|
</div>
|
||||||
|
) : groupBy === 'time' ? (
|
||||||
|
<div className="px-2 py-2 space-y-1">
|
||||||
|
{sessions.map((session) => (
|
||||||
|
<SessionRow
|
||||||
|
key={session.id}
|
||||||
|
session={session}
|
||||||
|
selected={selectedSessionId === session.id}
|
||||||
|
upcoming={isUpcoming(session)}
|
||||||
|
overdue={isOverdue(session)}
|
||||||
|
onClick={() => setSelectedSessionId(session.id)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="px-2 py-2 space-y-3">
|
||||||
|
{Object.entries(byInstructor).map(([instructor, instructorSessions]) => (
|
||||||
|
<div key={instructor}>
|
||||||
|
<p className="text-xs font-semibold text-muted-foreground px-2 mb-1">{instructor}</p>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{instructorSessions.map((session) => (
|
||||||
|
<SessionRow
|
||||||
|
key={session.id}
|
||||||
|
session={session}
|
||||||
|
selected={selectedSessionId === session.id}
|
||||||
|
upcoming={isUpcoming(session)}
|
||||||
|
overdue={isOverdue(session)}
|
||||||
|
onClick={() => setSelectedSessionId(session.id)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Detail panel */}
|
||||||
|
<div className="w-[60%] overflow-hidden">
|
||||||
|
<SessionDetailPanel sessionId={selectedSessionId} canEdit={canEdit} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SessionRow({ session, selected, upcoming, overdue, onClick }: {
|
||||||
|
session: LessonSession
|
||||||
|
selected: boolean
|
||||||
|
upcoming: boolean
|
||||||
|
overdue: boolean
|
||||||
|
onClick: () => void
|
||||||
|
}) {
|
||||||
|
const cfg = STATUS_CONFIG[session.status] ?? { label: session.status, color: '', icon: Clock }
|
||||||
|
const StatusIcon = cfg.icon
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
className={`w-full text-left p-3 rounded-lg transition-colors ${
|
||||||
|
selected ? 'bg-primary/10 border border-primary/20' :
|
||||||
|
upcoming ? 'bg-yellow-500/5 border border-yellow-500/20 hover:bg-yellow-500/10' :
|
||||||
|
overdue ? 'bg-red-500/5 border border-red-500/20 hover:bg-red-500/10' :
|
||||||
|
'hover:bg-muted border border-transparent'
|
||||||
|
}`}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between mb-0.5">
|
||||||
|
<span className="text-sm font-medium">{session.scheduledTime}</span>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{overdue && <AlertCircle className="h-3.5 w-3.5 text-red-500" />}
|
||||||
|
<Badge variant="outline" className={`text-[10px] ${cfg.color}`}>
|
||||||
|
<StatusIcon className="h-2.5 w-2.5 mr-0.5" />
|
||||||
|
{cfg.label}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-sm">{session.memberName ?? 'Unknown'}</div>
|
||||||
|
<div className="flex items-center justify-between text-xs text-muted-foreground mt-0.5">
|
||||||
|
<span>{session.lessonTypeName ?? 'Lesson'}</span>
|
||||||
|
<span>{session.instructorName ?? ''}</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { sessionListOptions } from '@/api/lessons'
|
||||||
|
import type { LessonSession } from '@/types/lesson'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Dialog, DialogContent } from '@/components/ui/dialog'
|
||||||
|
import { SessionDetailPanel } from './session-detail-panel'
|
||||||
|
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||||
|
|
||||||
|
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||||
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
|
scheduled: 'bg-blue-500/15 border-blue-500/30 text-blue-700 dark:text-blue-300',
|
||||||
|
attended: 'bg-green-500/15 border-green-500/30 text-green-700 dark:text-green-300',
|
||||||
|
missed: 'bg-red-500/15 border-red-500/30 text-red-700 dark:text-red-300',
|
||||||
|
makeup: 'bg-purple-500/15 border-purple-500/30 text-purple-700 dark:text-purple-300',
|
||||||
|
cancelled: 'bg-muted border-border text-muted-foreground',
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LessonsWeekViewProps {
|
||||||
|
canEdit: boolean
|
||||||
|
instructorId?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LessonsWeekView({ canEdit, instructorId }: LessonsWeekViewProps) {
|
||||||
|
const [weekOffset, setWeekOffset] = useState(0)
|
||||||
|
const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null)
|
||||||
|
|
||||||
|
// Get week start (Monday) and end (Sunday)
|
||||||
|
const now = new Date()
|
||||||
|
const monday = new Date(now)
|
||||||
|
monday.setDate(now.getDate() - ((now.getDay() + 6) % 7) + weekOffset * 7)
|
||||||
|
monday.setHours(0, 0, 0, 0)
|
||||||
|
const sunday = new Date(monday)
|
||||||
|
sunday.setDate(monday.getDate() + 6)
|
||||||
|
|
||||||
|
const weekStart = monday.toISOString().slice(0, 10)
|
||||||
|
const weekEnd = sunday.toISOString().slice(0, 10)
|
||||||
|
|
||||||
|
const { data } = useQuery({
|
||||||
|
...sessionListOptions({
|
||||||
|
page: 1,
|
||||||
|
limit: 200,
|
||||||
|
sort: 'scheduled_time',
|
||||||
|
order: 'asc',
|
||||||
|
scheduledDateFrom: weekStart,
|
||||||
|
scheduledDateTo: weekEnd,
|
||||||
|
...(instructorId ? { instructorId } : {}),
|
||||||
|
}),
|
||||||
|
staleTime: 30_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const sessions = data?.data ?? []
|
||||||
|
|
||||||
|
// Group sessions by date
|
||||||
|
const byDate = new Map<string, LessonSession[]>()
|
||||||
|
for (const s of sessions) {
|
||||||
|
const existing = byDate.get(s.scheduledDate) ?? []
|
||||||
|
existing.push(s)
|
||||||
|
byDate.set(s.scheduledDate, existing)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate week dates
|
||||||
|
const weekDates = Array.from({ length: 7 }, (_, i) => {
|
||||||
|
const d = new Date(monday)
|
||||||
|
d.setDate(monday.getDate() + i)
|
||||||
|
return d.toISOString().slice(0, 10)
|
||||||
|
})
|
||||||
|
|
||||||
|
const todayStr = new Date().toISOString().slice(0, 10)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Week navigation */}
|
||||||
|
<div className="flex items-center justify-between px-3 py-2 border-b border-border shrink-0 bg-card/50">
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setWeekOffset(weekOffset - 1)}>
|
||||||
|
<ChevronLeft className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
<div className="text-sm font-medium">
|
||||||
|
{monday.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} — {sunday.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
{weekOffset !== 0 && (
|
||||||
|
<Button variant="ghost" size="sm" className="h-8 text-xs" onClick={() => setWeekOffset(0)}>Today</Button>
|
||||||
|
)}
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => setWeekOffset(weekOffset + 1)}>
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Calendar grid */}
|
||||||
|
<div className="flex-1 overflow-auto">
|
||||||
|
<div className="grid grid-cols-7 min-h-full">
|
||||||
|
{weekDates.map((dateStr, i) => {
|
||||||
|
const daySessions = byDate.get(dateStr) ?? []
|
||||||
|
const isToday = dateStr === todayStr
|
||||||
|
const dayDate = new Date(dateStr + 'T00:00:00')
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={dateStr} className={`border-r border-border ${i === 6 ? 'border-r-0' : ''}`}>
|
||||||
|
{/* Day header */}
|
||||||
|
<div className={`sticky top-0 z-10 p-2 border-b border-border text-center ${isToday ? 'bg-primary/5' : 'bg-card'}`}>
|
||||||
|
<div className="text-xs text-muted-foreground">{DAYS[dayDate.getDay()]}</div>
|
||||||
|
<div className={`text-sm font-medium ${isToday ? 'text-primary' : ''}`}>
|
||||||
|
{dayDate.getDate()}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Sessions */}
|
||||||
|
<div className="p-1 space-y-1">
|
||||||
|
{daySessions.map((session) => (
|
||||||
|
<button
|
||||||
|
key={session.id}
|
||||||
|
className={`w-full text-left p-2 rounded border text-xs transition-colors hover:opacity-80 ${STATUS_COLORS[session.status] ?? ''}`}
|
||||||
|
onClick={() => setSelectedSessionId(session.id)}
|
||||||
|
>
|
||||||
|
<div className="font-medium">{session.scheduledTime}</div>
|
||||||
|
<div className="truncate">{session.memberName ?? 'Unknown'}</div>
|
||||||
|
<div className="truncate text-muted-foreground">{session.lessonTypeName ?? ''}</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{daySessions.length === 0 && (
|
||||||
|
<div className="text-xs text-muted-foreground text-center py-4 opacity-30">—</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Session detail dialog */}
|
||||||
|
<Dialog open={!!selectedSessionId} onOpenChange={(open) => { if (!open) setSelectedSessionId(null) }}>
|
||||||
|
<DialogContent className="max-w-lg max-h-[80vh] overflow-hidden p-0">
|
||||||
|
<SessionDetailPanel sessionId={selectedSessionId} canEdit={canEdit} />
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { sessionDetailOptions, sessionKeys, sessionMutations, sessionPlanItemsOptions } from '@/api/lessons'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { CheckCircle, XCircle, Clock, GraduationCap } from 'lucide-react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
const STATUS_CONFIG: Record<string, { label: string; color: string }> = {
|
||||||
|
scheduled: { label: 'Scheduled', color: 'bg-blue-500/10 text-blue-500' },
|
||||||
|
attended: { label: 'Attended', color: 'bg-green-500/10 text-green-500' },
|
||||||
|
missed: { label: 'Missed', color: 'bg-red-500/10 text-red-500' },
|
||||||
|
makeup: { label: 'Makeup', color: 'bg-purple-500/10 text-purple-500' },
|
||||||
|
cancelled: { label: 'Cancelled', color: 'bg-muted text-muted-foreground' },
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SessionDetailPanelProps {
|
||||||
|
sessionId: string | null
|
||||||
|
canEdit: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SessionDetailPanel({ sessionId, canEdit }: SessionDetailPanelProps) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [notes, setNotes] = useState('')
|
||||||
|
const [notesLoaded, setNotesLoaded] = useState(false)
|
||||||
|
|
||||||
|
const { data: session, isLoading } = useQuery({
|
||||||
|
...sessionDetailOptions(sessionId ?? ''),
|
||||||
|
enabled: !!sessionId,
|
||||||
|
})
|
||||||
|
|
||||||
|
const { data: planItems } = useQuery({
|
||||||
|
...sessionPlanItemsOptions(sessionId ?? ''),
|
||||||
|
enabled: !!sessionId,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Sync notes from session data
|
||||||
|
if (session && !notesLoaded) {
|
||||||
|
setNotes(session.instructorNotes ?? '')
|
||||||
|
setNotesLoaded(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusMutation = useMutation({
|
||||||
|
mutationFn: (status: string) => sessionMutations.updateStatus(sessionId!, status),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: sessionKeys.detail(sessionId!) })
|
||||||
|
queryClient.invalidateQueries({ queryKey: sessionKeys.all })
|
||||||
|
toast.success('Attendance recorded')
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
const notesMutation = useMutation({
|
||||||
|
mutationFn: () => sessionMutations.updateNotes(sessionId!, { instructorNotes: notes }),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: sessionKeys.detail(sessionId!) })
|
||||||
|
toast.success('Notes saved')
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!sessionId) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||||
|
<div className="text-center space-y-2">
|
||||||
|
<GraduationCap className="h-10 w-10 mx-auto opacity-20" />
|
||||||
|
<p className="text-sm">Select a session</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading || !session) {
|
||||||
|
return (
|
||||||
|
<div className="p-4 space-y-4">
|
||||||
|
<div className="h-8 bg-muted animate-pulse rounded" />
|
||||||
|
<div className="h-20 bg-muted animate-pulse rounded" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = STATUS_CONFIG[session.status] ?? { label: session.status, color: '' }
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full overflow-hidden">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="p-4 border-b border-border shrink-0">
|
||||||
|
<div className="flex items-center justify-between mb-2">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg font-semibold">{session.memberName ?? 'Unknown Student'}</h3>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{session.lessonTypeName ?? 'Lesson'} — {session.instructorName ?? 'No instructor'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Badge variant="outline" className={status.color}>{status.label}</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4 text-sm text-muted-foreground">
|
||||||
|
<span>{new Date(session.scheduledDate + 'T00:00:00').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}</span>
|
||||||
|
<span>{session.scheduledTime}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Attendance buttons */}
|
||||||
|
{canEdit && session.status === 'scheduled' && (
|
||||||
|
<div className="flex gap-2 p-3 border-b border-border shrink-0 bg-muted/30">
|
||||||
|
<Button
|
||||||
|
className="flex-1 h-12 gap-2 bg-green-600 hover:bg-green-700"
|
||||||
|
onClick={() => statusMutation.mutate('attended')}
|
||||||
|
disabled={statusMutation.isPending}
|
||||||
|
>
|
||||||
|
<CheckCircle className="h-5 w-5" />
|
||||||
|
Attended
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="flex-1 h-12 gap-2 text-red-500 border-red-500/30 hover:bg-red-500/10"
|
||||||
|
onClick={() => statusMutation.mutate('missed')}
|
||||||
|
disabled={statusMutation.isPending}
|
||||||
|
>
|
||||||
|
<XCircle className="h-5 w-5" />
|
||||||
|
Missed
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="flex-1 h-12 gap-2"
|
||||||
|
onClick={() => statusMutation.mutate('cancelled')}
|
||||||
|
disabled={statusMutation.isPending}
|
||||||
|
>
|
||||||
|
<Clock className="h-5 w-5" />
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex-1 overflow-y-auto p-4 space-y-4">
|
||||||
|
{/* Plan items */}
|
||||||
|
{planItems && planItems.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs text-muted-foreground">Lesson Plan Items</Label>
|
||||||
|
<div className="mt-2 space-y-1">
|
||||||
|
{planItems.map((item) => (
|
||||||
|
<div key={item.id} className="flex items-center gap-2 py-1 text-sm">
|
||||||
|
<div className="h-4 w-4 rounded border border-border" />
|
||||||
|
<span>{item.lessonPlanItemId}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Notes */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label className="text-xs text-muted-foreground">Instructor Notes</Label>
|
||||||
|
<Textarea
|
||||||
|
value={notes}
|
||||||
|
onChange={(e) => setNotes(e.target.value)}
|
||||||
|
placeholder="Session notes, observations, homework..."
|
||||||
|
rows={4}
|
||||||
|
disabled={!canEdit}
|
||||||
|
/>
|
||||||
|
{canEdit && (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
onClick={() => notesMutation.mutate()}
|
||||||
|
disabled={notesMutation.isPending || notes === (session.instructorNotes ?? '')}
|
||||||
|
>
|
||||||
|
{notesMutation.isPending ? 'Saving...' : 'Save Notes'}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Previous notes */}
|
||||||
|
{session.homeworkAssigned && (
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs text-muted-foreground">Homework Assigned</Label>
|
||||||
|
<p className="text-sm mt-1">{session.homeworkAssigned}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{session.nextLessonGoals && (
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs text-muted-foreground">Next Lesson Goals</Label>
|
||||||
|
<p className="text-sm mt-1">{session.nextLessonGoals}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{session.topicsCovered && session.topicsCovered.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<Label className="text-xs text-muted-foreground">Topics Covered</Label>
|
||||||
|
<div className="flex gap-1.5 flex-wrap mt-1">
|
||||||
|
{session.topicsCovered.map((topic, i) => (
|
||||||
|
<Badge key={i} variant="outline" className="text-xs">{topic}</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { RepairStatusBar } from './repair-status-bar'
|
||||||
|
import { RepairQueuePanel } from './repair-queue-panel'
|
||||||
|
import { RepairDetailPanel } from './repair-detail-panel'
|
||||||
|
import { RepairIntakeForm } from './repair-intake-form'
|
||||||
|
|
||||||
|
interface RepairDeskViewProps {
|
||||||
|
canEdit: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RepairDeskView({ canEdit }: RepairDeskViewProps) {
|
||||||
|
const [selectedTicketId, setSelectedTicketId] = useState<string | null>(null)
|
||||||
|
const [intakeMode, setIntakeMode] = useState(false)
|
||||||
|
const [statusFilter, setStatusFilter] = useState<string[] | null>(null)
|
||||||
|
const [activeFilterLabel, setActiveFilterLabel] = useState<string | null>(null)
|
||||||
|
|
||||||
|
function handleFilterChange(statuses: string[] | null) {
|
||||||
|
setStatusFilter(statuses)
|
||||||
|
// Track which group label is active for the status bar highlight
|
||||||
|
if (!statuses) {
|
||||||
|
setActiveFilterLabel(null)
|
||||||
|
} else {
|
||||||
|
// Map statuses back to group label
|
||||||
|
const groups: Record<string, string> = {
|
||||||
|
new: 'New', in_transit: 'New', intake: 'New',
|
||||||
|
diagnosing: 'Diagnosing', pending_approval: 'Diagnosing',
|
||||||
|
approved: 'In Progress', in_progress: 'In Progress', pending_parts: 'In Progress',
|
||||||
|
ready: 'Ready',
|
||||||
|
}
|
||||||
|
setActiveFilterLabel(groups[statuses[0]] ?? null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (intakeMode) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
<RepairIntakeForm
|
||||||
|
onComplete={(ticketId) => {
|
||||||
|
setIntakeMode(false)
|
||||||
|
setSelectedTicketId(ticketId)
|
||||||
|
}}
|
||||||
|
onCancel={() => setIntakeMode(false)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
<RepairStatusBar activeFilter={activeFilterLabel} onFilterChange={handleFilterChange} />
|
||||||
|
<div className="flex flex-1 min-h-0">
|
||||||
|
<div className="w-[35%] border-r border-border overflow-hidden">
|
||||||
|
<RepairQueuePanel
|
||||||
|
selectedTicketId={selectedTicketId}
|
||||||
|
onSelectTicket={setSelectedTicketId}
|
||||||
|
onNewIntake={() => setIntakeMode(true)}
|
||||||
|
statusFilter={statusFilter}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="w-[65%] overflow-hidden">
|
||||||
|
<RepairDetailPanel ticketId={selectedTicketId} canEdit={canEdit} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import {
|
||||||
|
repairTicketDetailOptions, repairTicketKeys, repairTicketMutations,
|
||||||
|
repairLineItemListOptions,
|
||||||
|
} from '@/api/repairs'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { StatusProgress } from '@/components/repairs/status-progress'
|
||||||
|
import { TicketNotes } from '@/components/repairs/ticket-notes'
|
||||||
|
import { TicketPhotos } from '@/components/repairs/ticket-photos'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
import { Mail, ChevronRight, Wrench } from 'lucide-react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
const STATUS_FLOW = ['new', 'intake', 'diagnosing', 'pending_approval', 'approved', 'in_progress', 'ready', 'picked_up']
|
||||||
|
|
||||||
|
interface RepairDetailPanelProps {
|
||||||
|
ticketId: string | null
|
||||||
|
canEdit: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RepairDetailPanel({ ticketId, canEdit }: RepairDetailPanelProps) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [activeSection, setActiveSection] = useState<'details' | 'notes' | 'photos'>('details')
|
||||||
|
|
||||||
|
const { data: ticket, isLoading } = useQuery({
|
||||||
|
...repairTicketDetailOptions(ticketId ?? ''),
|
||||||
|
enabled: !!ticketId,
|
||||||
|
})
|
||||||
|
|
||||||
|
const { data: lineItemsData } = useQuery({
|
||||||
|
...repairLineItemListOptions(ticketId ?? '', { page: 1, limit: 100, q: undefined, sort: undefined, order: 'asc' }),
|
||||||
|
enabled: !!ticketId,
|
||||||
|
})
|
||||||
|
|
||||||
|
const statusMutation = useMutation({
|
||||||
|
mutationFn: (status: string) => repairTicketMutations.updateStatus(ticketId!, status),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: repairTicketKeys.detail(ticketId!) })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repair-tickets', 'station-all'] })
|
||||||
|
toast.success('Status updated')
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
const emailEstimateMutation = useMutation({
|
||||||
|
mutationFn: (email: string) => api.post(`/v1/repair-tickets/${ticketId}/email-estimate`, { email }),
|
||||||
|
onSuccess: () => toast.success('Estimate emailed'),
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!ticketId) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||||
|
<div className="text-center space-y-2">
|
||||||
|
<Wrench className="h-10 w-10 mx-auto opacity-20" />
|
||||||
|
<p className="text-sm">Select a ticket from the queue</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading || !ticket) {
|
||||||
|
return (
|
||||||
|
<div className="p-4 space-y-4">
|
||||||
|
<div className="h-8 bg-muted animate-pulse rounded" />
|
||||||
|
<div className="h-20 bg-muted animate-pulse rounded" />
|
||||||
|
<div className="h-40 bg-muted animate-pulse rounded" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const lineItems = lineItemsData?.data ?? []
|
||||||
|
const currentIdx = STATUS_FLOW.indexOf(ticket.status)
|
||||||
|
const nextStatus = currentIdx >= 0 && currentIdx < STATUS_FLOW.length - 1 ? STATUS_FLOW[currentIdx + 1] : null
|
||||||
|
const isTerminal = ['picked_up', 'delivered', 'cancelled'].includes(ticket.status)
|
||||||
|
|
||||||
|
function handleStatusClick(status: string) {
|
||||||
|
if (canEdit && !isTerminal) statusMutation.mutate(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleEmailEstimate() {
|
||||||
|
const email = (ticket as any).customerEmail
|
||||||
|
if (email) {
|
||||||
|
emailEstimateMutation.mutate(email)
|
||||||
|
} else {
|
||||||
|
toast.error('No customer email on file')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full overflow-hidden">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="p-3 border-b border-border shrink-0">
|
||||||
|
<div className="flex items-center justify-between mb-2">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg font-semibold">#{ticket.ticketNumber}</h3>
|
||||||
|
<p className="text-sm text-muted-foreground">{ticket.customerName}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button variant="outline" size="sm" className="gap-1.5" onClick={handleEmailEstimate}>
|
||||||
|
<Mail className="h-3.5 w-3.5" />
|
||||||
|
<span className="hidden lg:inline">Email Estimate</span>
|
||||||
|
</Button>
|
||||||
|
{canEdit && nextStatus && !isTerminal && (
|
||||||
|
<Button size="sm" className="gap-1.5" onClick={() => statusMutation.mutate(nextStatus)}>
|
||||||
|
Next <ChevronRight className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<StatusProgress
|
||||||
|
currentStatus={ticket.status}
|
||||||
|
onStatusClick={canEdit && !isTerminal ? handleStatusClick : undefined}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Section toggle */}
|
||||||
|
<div className="flex gap-1 px-3 py-2 border-b border-border shrink-0 bg-muted/30">
|
||||||
|
{(['details', 'notes', 'photos'] as const).map((s) => (
|
||||||
|
<Button
|
||||||
|
key={s}
|
||||||
|
variant={activeSection === s ? 'default' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
className="h-7 text-xs capitalize"
|
||||||
|
onClick={() => setActiveSection(s)}
|
||||||
|
>
|
||||||
|
{s}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex-1 overflow-y-auto p-3">
|
||||||
|
{activeSection === 'details' && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Item info */}
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm"><span className="text-muted-foreground">Item:</span> {ticket.itemDescription ?? 'N/A'}</p>
|
||||||
|
{ticket.serialNumber && <p className="text-sm"><span className="text-muted-foreground">S/N:</span> {ticket.serialNumber}</p>}
|
||||||
|
{ticket.conditionIn && <p className="text-sm"><span className="text-muted-foreground">Condition:</span> {ticket.conditionIn}</p>}
|
||||||
|
{ticket.conditionInNotes && <p className="text-sm text-muted-foreground">{ticket.conditionInNotes}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
{/* Problem */}
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-medium text-muted-foreground mb-1">Problem</p>
|
||||||
|
<p className="text-sm">{ticket.problemDescription}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Dates */}
|
||||||
|
<div className="flex gap-4">
|
||||||
|
{ticket.promisedDate && (
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Promised</p>
|
||||||
|
<p className="text-sm font-medium">{new Date(ticket.promisedDate).toLocaleDateString()}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{ticket.estimatedCost && (
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Estimate</p>
|
||||||
|
<p className="text-sm font-medium">${ticket.estimatedCost}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{ticket.actualCost && (
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-muted-foreground">Actual</p>
|
||||||
|
<p className="text-sm font-medium">${ticket.actualCost}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Line items */}
|
||||||
|
{lineItems.length > 0 && (
|
||||||
|
<>
|
||||||
|
<Separator />
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-medium text-muted-foreground mb-2">Line Items</p>
|
||||||
|
<div className="space-y-1">
|
||||||
|
{lineItems.map((item) => (
|
||||||
|
<div key={item.id} className="flex items-center justify-between text-sm py-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">{item.itemType}</Badge>
|
||||||
|
<span>{item.description}</span>
|
||||||
|
</div>
|
||||||
|
<span className="font-medium">${item.totalPrice}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<Separator />
|
||||||
|
<div className="flex justify-between text-sm font-semibold pt-1">
|
||||||
|
<span>Total</span>
|
||||||
|
<span>${lineItems.reduce((sum, i) => sum + parseFloat(i.totalPrice), 0).toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeSection === 'notes' && ticketId && (
|
||||||
|
<TicketNotes ticketId={ticketId} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeSection === 'photos' && ticketId && (
|
||||||
|
<TicketPhotos ticketId={ticketId} currentStatus={ticket.status} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { repairTicketMutations, repairLineItemMutations, repairServiceTemplateListOptions } from '@/api/repairs'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { ArrowLeft, ArrowRight, Plus, Trash2, Check, Search } from 'lucide-react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
import type { RepairServiceTemplate } from '@/types/repair'
|
||||||
|
import type { PaginatedResponse } from '@lunarfront/shared/schemas'
|
||||||
|
|
||||||
|
interface RepairIntakeFormProps {
|
||||||
|
onComplete: (ticketId: string) => void
|
||||||
|
onCancel: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LineItemDraft {
|
||||||
|
id: string
|
||||||
|
itemType: string
|
||||||
|
description: string
|
||||||
|
qty: number
|
||||||
|
unitPrice: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const STEPS = ['Customer', 'Item', 'Problem & Estimate', 'Review']
|
||||||
|
const CONDITIONS = [
|
||||||
|
{ value: 'excellent', label: 'Excellent' },
|
||||||
|
{ value: 'good', label: 'Good' },
|
||||||
|
{ value: 'fair', label: 'Fair' },
|
||||||
|
{ value: 'poor', label: 'Poor' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function RepairIntakeForm({ onComplete, onCancel }: RepairIntakeFormProps) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [step, setStep] = useState(0)
|
||||||
|
|
||||||
|
// Customer
|
||||||
|
const [customerName, setCustomerName] = useState('')
|
||||||
|
const [customerPhone, setCustomerPhone] = useState('')
|
||||||
|
const [customerEmail, setCustomerEmail] = useState('')
|
||||||
|
const [accountId, setAccountId] = useState<string | null>(null)
|
||||||
|
|
||||||
|
// Account search
|
||||||
|
const [accountSearch, setAccountSearch] = useState('')
|
||||||
|
const { data: accountResults } = useQuery({
|
||||||
|
queryKey: ['accounts', 'search', accountSearch],
|
||||||
|
queryFn: () => api.get<PaginatedResponse<{ id: string; name: string; email: string | null; phone: string | null }>>('/v1/accounts', { page: 1, limit: 10, q: accountSearch }),
|
||||||
|
enabled: accountSearch.length >= 2,
|
||||||
|
staleTime: 10_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Item
|
||||||
|
const [itemDescription, setItemDescription] = useState('')
|
||||||
|
const [serialNumber, setSerialNumber] = useState('')
|
||||||
|
const [conditionIn, setConditionIn] = useState('')
|
||||||
|
const [conditionInNotes, setConditionInNotes] = useState('')
|
||||||
|
|
||||||
|
// Problem & Estimate
|
||||||
|
const [problemDescription, setProblemDescription] = useState('')
|
||||||
|
const [estimatedCost, setEstimatedCost] = useState('')
|
||||||
|
const [promisedDate, setPromisedDate] = useState('')
|
||||||
|
const [lineItems, setLineItems] = useState<LineItemDraft[]>([])
|
||||||
|
|
||||||
|
// Templates for quick-add
|
||||||
|
const { data: templatesData } = useQuery({
|
||||||
|
...repairServiceTemplateListOptions({ page: 1, limit: 100, q: undefined, sort: 'sort_order', order: 'asc' }),
|
||||||
|
})
|
||||||
|
const templates = templatesData?.data ?? []
|
||||||
|
|
||||||
|
function addLineItem(template?: RepairServiceTemplate) {
|
||||||
|
setLineItems([...lineItems, {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
itemType: template?.itemType ?? 'labor',
|
||||||
|
description: template?.description ?? template?.name ?? '',
|
||||||
|
qty: 1,
|
||||||
|
unitPrice: parseFloat(template?.defaultPrice ?? '0'),
|
||||||
|
}])
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeLineItem(id: string) {
|
||||||
|
setLineItems(lineItems.filter(i => i.id !== id))
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateLineItem(id: string, field: string, value: string | number) {
|
||||||
|
setLineItems(lineItems.map(i => i.id === id ? { ...i, [field]: value } : i))
|
||||||
|
}
|
||||||
|
|
||||||
|
const lineItemTotal = lineItems.reduce((sum, i) => sum + i.qty * i.unitPrice, 0)
|
||||||
|
|
||||||
|
const createMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
const ticket = await repairTicketMutations.create({
|
||||||
|
customerName,
|
||||||
|
customerPhone: customerPhone || undefined,
|
||||||
|
accountId: accountId || undefined,
|
||||||
|
itemDescription: itemDescription || undefined,
|
||||||
|
serialNumber: serialNumber || undefined,
|
||||||
|
conditionIn: conditionIn || undefined,
|
||||||
|
conditionInNotes: conditionInNotes || undefined,
|
||||||
|
problemDescription,
|
||||||
|
estimatedCost: estimatedCost ? parseFloat(estimatedCost) : undefined,
|
||||||
|
promisedDate: promisedDate || undefined,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Create line items
|
||||||
|
for (const item of lineItems) {
|
||||||
|
await repairLineItemMutations.create(ticket.id, {
|
||||||
|
itemType: item.itemType,
|
||||||
|
description: item.description,
|
||||||
|
qty: item.qty,
|
||||||
|
unitPrice: item.unitPrice,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return ticket
|
||||||
|
},
|
||||||
|
onSuccess: (ticket) => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repair-tickets'] })
|
||||||
|
toast.success(`Ticket #${ticket.ticketNumber} created`)
|
||||||
|
onComplete(ticket.id)
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
function selectAccount(acct: { id: string; name: string; email: string | null; phone: string | null }) {
|
||||||
|
setAccountId(acct.id)
|
||||||
|
setCustomerName(acct.name)
|
||||||
|
if (acct.phone) setCustomerPhone(acct.phone)
|
||||||
|
if (acct.email) setCustomerEmail(acct.email)
|
||||||
|
setAccountSearch('')
|
||||||
|
}
|
||||||
|
|
||||||
|
function canProceed() {
|
||||||
|
if (step === 0) return customerName.trim().length > 0
|
||||||
|
if (step === 1) return true
|
||||||
|
if (step === 2) return problemDescription.trim().length > 0
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Step indicator */}
|
||||||
|
<div className="flex items-center gap-2 px-4 py-3 border-b border-border shrink-0">
|
||||||
|
<Button variant="ghost" size="sm" onClick={onCancel}>
|
||||||
|
<ArrowLeft className="h-4 w-4 mr-1" />Cancel
|
||||||
|
</Button>
|
||||||
|
<div className="flex-1" />
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{STEPS.map((s, i) => (
|
||||||
|
<div key={s} className="flex items-center gap-1">
|
||||||
|
<div className={`h-7 px-3 rounded-full text-xs flex items-center font-medium ${
|
||||||
|
i === step ? 'bg-primary text-primary-foreground' :
|
||||||
|
i < step ? 'bg-primary/20 text-primary' : 'bg-muted text-muted-foreground'
|
||||||
|
}`}>
|
||||||
|
{i < step ? <Check className="h-3 w-3" /> : i + 1}
|
||||||
|
<span className="ml-1.5 hidden md:inline">{s}</span>
|
||||||
|
</div>
|
||||||
|
{i < STEPS.length - 1 && <div className="w-4 h-px bg-border" />}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Step content */}
|
||||||
|
<div className="flex-1 overflow-y-auto p-4 max-w-2xl mx-auto w-full">
|
||||||
|
{step === 0 && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-semibold">Customer</h3>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Search existing accounts</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
placeholder="Search by name..."
|
||||||
|
value={accountSearch}
|
||||||
|
onChange={(e) => setAccountSearch(e.target.value)}
|
||||||
|
className="pl-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{accountSearch.length >= 2 && accountResults?.data && accountResults.data.length > 0 && (
|
||||||
|
<div className="border rounded-md max-h-40 overflow-y-auto">
|
||||||
|
{accountResults.data.map((acct) => (
|
||||||
|
<button
|
||||||
|
key={acct.id}
|
||||||
|
className="w-full text-left px-3 py-2 text-sm hover:bg-muted transition-colors"
|
||||||
|
onClick={() => selectAccount(acct)}
|
||||||
|
>
|
||||||
|
<span className="font-medium">{acct.name}</span>
|
||||||
|
{acct.phone && <span className="text-muted-foreground ml-2">{acct.phone}</span>}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Separator />
|
||||||
|
<p className="text-sm text-muted-foreground">Or enter walk-in customer info:</p>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Name *</Label>
|
||||||
|
<Input value={customerName} onChange={(e) => setCustomerName(e.target.value)} placeholder="Customer name" />
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Phone</Label>
|
||||||
|
<Input value={customerPhone} onChange={(e) => setCustomerPhone(e.target.value)} placeholder="555-1234" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Email</Label>
|
||||||
|
<Input type="email" value={customerEmail} onChange={(e) => setCustomerEmail(e.target.value)} placeholder="email@example.com" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === 1 && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-semibold">Item Details</h3>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Item Description</Label>
|
||||||
|
<Input value={itemDescription} onChange={(e) => setItemDescription(e.target.value)} placeholder="e.g. Fender Stratocaster, iPhone 15, etc." />
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Serial Number</Label>
|
||||||
|
<Input value={serialNumber} onChange={(e) => setSerialNumber(e.target.value)} placeholder="Optional" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Condition</Label>
|
||||||
|
<Select value={conditionIn} onValueChange={setConditionIn}>
|
||||||
|
<SelectTrigger><SelectValue placeholder="Select condition" /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{CONDITIONS.map(c => <SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>)}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Condition Notes</Label>
|
||||||
|
<Textarea value={conditionInNotes} onChange={(e) => setConditionInNotes(e.target.value)} placeholder="Describe any existing damage, scratches, etc." rows={3} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === 2 && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-semibold">Problem & Estimate</h3>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Problem Description *</Label>
|
||||||
|
<Textarea value={problemDescription} onChange={(e) => setProblemDescription(e.target.value)} placeholder="Describe what needs to be repaired..." rows={3} />
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Estimated Cost</Label>
|
||||||
|
<Input type="number" step="0.01" value={estimatedCost} onChange={(e) => setEstimatedCost(e.target.value)} placeholder="0.00" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Promised Date</Label>
|
||||||
|
<Input type="date" value={promisedDate} onChange={(e) => setPromisedDate(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label>Line Items</Label>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => addLineItem()}>
|
||||||
|
<Plus className="h-3.5 w-3.5 mr-1" />Add Item
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Template quick-add */}
|
||||||
|
{templates.length > 0 && (
|
||||||
|
<div className="flex gap-1.5 flex-wrap">
|
||||||
|
{templates.slice(0, 10).map(t => (
|
||||||
|
<Button key={t.id} variant="outline" size="sm" className="h-7 text-xs" onClick={() => addLineItem(t)}>
|
||||||
|
{t.name} — ${t.defaultPrice}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{lineItems.map((item) => (
|
||||||
|
<div key={item.id} className="flex items-end gap-2">
|
||||||
|
<div className="w-24 space-y-1">
|
||||||
|
<Label className="text-xs">Type</Label>
|
||||||
|
<Select value={item.itemType} onValueChange={(v) => updateLineItem(item.id, 'itemType', v)}>
|
||||||
|
<SelectTrigger className="h-8 text-xs"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="labor">Labor</SelectItem>
|
||||||
|
<SelectItem value="part">Part</SelectItem>
|
||||||
|
<SelectItem value="flat_rate">Flat Rate</SelectItem>
|
||||||
|
<SelectItem value="misc">Misc</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 space-y-1">
|
||||||
|
<Label className="text-xs">Description</Label>
|
||||||
|
<Input className="h-8 text-sm" value={item.description} onChange={(e) => updateLineItem(item.id, 'description', e.target.value)} />
|
||||||
|
</div>
|
||||||
|
<div className="w-16 space-y-1">
|
||||||
|
<Label className="text-xs">Qty</Label>
|
||||||
|
<Input className="h-8 text-sm" type="number" min={1} value={item.qty} onChange={(e) => updateLineItem(item.id, 'qty', parseInt(e.target.value) || 1)} />
|
||||||
|
</div>
|
||||||
|
<div className="w-24 space-y-1">
|
||||||
|
<Label className="text-xs">Price</Label>
|
||||||
|
<Input className="h-8 text-sm" type="number" step="0.01" value={item.unitPrice} onChange={(e) => updateLineItem(item.id, 'unitPrice', parseFloat(e.target.value) || 0)} />
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={() => removeLineItem(item.id)}>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{lineItems.length > 0 && (
|
||||||
|
<div className="text-right text-sm font-semibold">
|
||||||
|
Line Item Total: ${lineItemTotal.toFixed(2)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === 3 && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-lg font-semibold">Review</h3>
|
||||||
|
<div className="space-y-3 text-sm">
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground text-xs">Customer</p>
|
||||||
|
<p className="font-medium">{customerName}</p>
|
||||||
|
{customerPhone && <p className="text-muted-foreground">{customerPhone}</p>}
|
||||||
|
</div>
|
||||||
|
{itemDescription && (
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground text-xs">Item</p>
|
||||||
|
<p>{itemDescription}{serialNumber ? ` (S/N: ${serialNumber})` : ''}</p>
|
||||||
|
{conditionIn && <Badge variant="outline" className="text-xs mt-1">{conditionIn}</Badge>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground text-xs">Problem</p>
|
||||||
|
<p>{problemDescription}</p>
|
||||||
|
</div>
|
||||||
|
{(estimatedCost || promisedDate) && (
|
||||||
|
<div className="flex gap-6">
|
||||||
|
{estimatedCost && <div><p className="text-muted-foreground text-xs">Estimate</p><p className="font-medium">${estimatedCost}</p></div>}
|
||||||
|
{promisedDate && <div><p className="text-muted-foreground text-xs">Promised</p><p>{new Date(promisedDate + 'T00:00:00').toLocaleDateString()}</p></div>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{lineItems.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<p className="text-muted-foreground text-xs mb-1">Line Items</p>
|
||||||
|
{lineItems.map(i => (
|
||||||
|
<div key={i.id} className="flex justify-between py-0.5">
|
||||||
|
<span>{i.description} x{i.qty}</span>
|
||||||
|
<span className="font-medium">${(i.qty * i.unitPrice).toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<Separator className="my-1" />
|
||||||
|
<div className="flex justify-between font-semibold">
|
||||||
|
<span>Total</span>
|
||||||
|
<span>${lineItemTotal.toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Navigation */}
|
||||||
|
<div className="flex items-center justify-between p-4 border-t border-border shrink-0">
|
||||||
|
<Button variant="outline" onClick={() => step > 0 ? setStep(step - 1) : onCancel()}>
|
||||||
|
<ArrowLeft className="h-4 w-4 mr-1" />
|
||||||
|
{step === 0 ? 'Cancel' : 'Back'}
|
||||||
|
</Button>
|
||||||
|
{step < STEPS.length - 1 ? (
|
||||||
|
<Button onClick={() => setStep(step + 1)} disabled={!canProceed()}>
|
||||||
|
Next <ArrowRight className="h-4 w-4 ml-1" />
|
||||||
|
</Button>
|
||||||
|
) : (
|
||||||
|
<Button onClick={() => createMutation.mutate()} disabled={createMutation.isPending}>
|
||||||
|
{createMutation.isPending ? 'Creating...' : 'Create Ticket'}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import type { RepairTicket } from '@/types/repair'
|
||||||
|
import type { PaginatedResponse } from '@lunarfront/shared/schemas'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Plus, Search } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
|
new: 'bg-blue-500/10 text-blue-500',
|
||||||
|
in_transit: 'bg-blue-500/10 text-blue-500',
|
||||||
|
intake: 'bg-blue-500/10 text-blue-500',
|
||||||
|
diagnosing: 'bg-yellow-500/10 text-yellow-500',
|
||||||
|
pending_approval: 'bg-yellow-500/10 text-yellow-500',
|
||||||
|
approved: 'bg-orange-500/10 text-orange-500',
|
||||||
|
in_progress: 'bg-orange-500/10 text-orange-500',
|
||||||
|
pending_parts: 'bg-orange-500/10 text-orange-500',
|
||||||
|
ready: 'bg-green-500/10 text-green-500',
|
||||||
|
picked_up: 'bg-muted text-muted-foreground',
|
||||||
|
delivered: 'bg-muted text-muted-foreground',
|
||||||
|
cancelled: 'bg-destructive/10 text-destructive',
|
||||||
|
}
|
||||||
|
|
||||||
|
const STATUS_LABELS: Record<string, string> = {
|
||||||
|
new: 'New',
|
||||||
|
in_transit: 'In Transit',
|
||||||
|
intake: 'Intake',
|
||||||
|
diagnosing: 'Diagnosing',
|
||||||
|
pending_approval: 'Pending Approval',
|
||||||
|
approved: 'Approved',
|
||||||
|
in_progress: 'In Progress',
|
||||||
|
pending_parts: 'Pending Parts',
|
||||||
|
ready: 'Ready',
|
||||||
|
picked_up: 'Picked Up',
|
||||||
|
delivered: 'Delivered',
|
||||||
|
cancelled: 'Cancelled',
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RepairQueuePanelProps {
|
||||||
|
selectedTicketId: string | null
|
||||||
|
onSelectTicket: (id: string) => void
|
||||||
|
onNewIntake: () => void
|
||||||
|
statusFilter: string[] | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RepairQueuePanel({ selectedTicketId, onSelectTicket, onNewIntake, statusFilter }: RepairQueuePanelProps) {
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey: ['repair-tickets', 'station-queue', search, statusFilter],
|
||||||
|
queryFn: () => api.get<PaginatedResponse<RepairTicket>>('/v1/repair-tickets', {
|
||||||
|
page: 1,
|
||||||
|
limit: 100,
|
||||||
|
q: search || undefined,
|
||||||
|
sort: 'created_at',
|
||||||
|
order: 'desc',
|
||||||
|
...(statusFilter ? { status: statusFilter.join(',') } : {}),
|
||||||
|
}),
|
||||||
|
staleTime: 30_000,
|
||||||
|
refetchInterval: 30_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const tickets = data?.data ?? []
|
||||||
|
|
||||||
|
function timeAgo(dateStr: string) {
|
||||||
|
const diff = Date.now() - new Date(dateStr).getTime()
|
||||||
|
const hours = Math.floor(diff / 3600000)
|
||||||
|
if (hours < 1) return 'Just now'
|
||||||
|
if (hours < 24) return `${hours}h ago`
|
||||||
|
const days = Math.floor(hours / 24)
|
||||||
|
return `${days}d ago`
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
<div className="p-3 space-y-2 shrink-0">
|
||||||
|
<Button className="w-full h-11 gap-2" onClick={onNewIntake}>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
New Intake
|
||||||
|
</Button>
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
placeholder="Search tickets..."
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
|
className="pl-9 h-9"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="p-3 space-y-2">
|
||||||
|
{Array.from({ length: 5 }).map((_, i) => (
|
||||||
|
<div key={i} className="h-16 bg-muted animate-pulse rounded-lg" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : tickets.length === 0 ? (
|
||||||
|
<div className="p-6 text-center text-muted-foreground text-sm">
|
||||||
|
No tickets found
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="px-2 pb-2 space-y-1">
|
||||||
|
{tickets.map((ticket) => (
|
||||||
|
<button
|
||||||
|
key={ticket.id}
|
||||||
|
className={`w-full text-left p-3 rounded-lg transition-colors ${
|
||||||
|
selectedTicketId === ticket.id
|
||||||
|
? 'bg-primary/10 border border-primary/20'
|
||||||
|
: 'hover:bg-muted border border-transparent'
|
||||||
|
}`}
|
||||||
|
onClick={() => onSelectTicket(ticket.id)}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between mb-1">
|
||||||
|
<span className="text-sm font-medium">#{ticket.ticketNumber}</span>
|
||||||
|
<Badge variant="outline" className={`text-[10px] ${STATUS_COLORS[ticket.status] ?? ''}`}>
|
||||||
|
{STATUS_LABELS[ticket.status] ?? ticket.status}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-foreground truncate">{ticket.customerName}</div>
|
||||||
|
<div className="flex items-center justify-between mt-1">
|
||||||
|
<span className="text-xs text-muted-foreground truncate">{ticket.itemDescription ?? 'No item'}</span>
|
||||||
|
<span className="text-xs text-muted-foreground shrink-0 ml-2">{timeAgo(ticket.createdAt)}</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import type { RepairTicket } from '@/types/repair'
|
||||||
|
import type { PaginatedResponse } from '@lunarfront/shared/schemas'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
|
||||||
|
const STATUS_GROUPS = [
|
||||||
|
{ label: 'New', statuses: ['new', 'in_transit', 'intake'], color: 'bg-blue-500/10 text-blue-500 border-blue-500/20' },
|
||||||
|
{ label: 'Diagnosing', statuses: ['diagnosing', 'pending_approval'], color: 'bg-yellow-500/10 text-yellow-500 border-yellow-500/20' },
|
||||||
|
{ label: 'In Progress', statuses: ['approved', 'in_progress', 'pending_parts'], color: 'bg-orange-500/10 text-orange-500 border-orange-500/20' },
|
||||||
|
{ label: 'Ready', statuses: ['ready'], color: 'bg-green-500/10 text-green-500 border-green-500/20' },
|
||||||
|
]
|
||||||
|
|
||||||
|
interface RepairStatusBarProps {
|
||||||
|
activeFilter: string | null
|
||||||
|
onFilterChange: (statuses: string[] | null) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RepairStatusBar({ activeFilter, onFilterChange }: RepairStatusBarProps) {
|
||||||
|
// Fetch all non-terminal tickets for counts
|
||||||
|
const { data } = useQuery({
|
||||||
|
queryKey: ['repair-tickets', 'station-counts'],
|
||||||
|
queryFn: () => api.get<PaginatedResponse<RepairTicket>>('/v1/repair-tickets', { page: 1, limit: 1, q: undefined, sort: undefined, order: 'asc' }),
|
||||||
|
staleTime: 30_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
// We need per-status counts — fetch a larger list for counting
|
||||||
|
const { data: allData } = useQuery({
|
||||||
|
queryKey: ['repair-tickets', 'station-all'],
|
||||||
|
queryFn: () => api.get<PaginatedResponse<RepairTicket>>('/v1/repair-tickets', { page: 1, limit: 500, q: undefined, sort: undefined, order: 'asc' }),
|
||||||
|
staleTime: 30_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const tickets = allData?.data ?? []
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2 px-3 py-2 border-b border-border bg-card/50 shrink-0">
|
||||||
|
<button
|
||||||
|
className={`text-xs px-2 py-1 rounded-md transition-colors ${!activeFilter ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'}`}
|
||||||
|
onClick={() => onFilterChange(null)}
|
||||||
|
>
|
||||||
|
All ({data?.pagination?.total ?? tickets.length})
|
||||||
|
</button>
|
||||||
|
{STATUS_GROUPS.map((group) => {
|
||||||
|
const count = tickets.filter(t => group.statuses.includes(t.status)).length
|
||||||
|
const isActive = activeFilter === group.label
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={group.label}
|
||||||
|
className={`flex items-center gap-1.5 text-xs px-2 py-1 rounded-md transition-colors ${isActive ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'}`}
|
||||||
|
onClick={() => onFilterChange(isActive ? null : group.statuses)}
|
||||||
|
>
|
||||||
|
{group.label}
|
||||||
|
{count > 0 && (
|
||||||
|
<Badge variant="outline" className={`text-[10px] h-4 px-1 ${group.color}`}>
|
||||||
|
{count}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { usePOSStore } from '@/stores/pos.store'
|
||||||
|
import type { RepairTicket } from '@/types/repair'
|
||||||
|
import type { PaginatedResponse } from '@lunarfront/shared/schemas'
|
||||||
|
import { RepairWorkbench } from './repair-workbench'
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Wrench } from 'lucide-react'
|
||||||
|
|
||||||
|
const STATUS_LABELS: Record<string, string> = {
|
||||||
|
new: 'New', intake: 'Intake', diagnosing: 'Diagnosing',
|
||||||
|
pending_approval: 'Pending', approved: 'Approved',
|
||||||
|
in_progress: 'In Progress', pending_parts: 'Parts',
|
||||||
|
ready: 'Ready',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RepairTechView() {
|
||||||
|
const cashier = usePOSStore((s) => s.cashier)
|
||||||
|
const [selectedTicketId, setSelectedTicketId] = useState<string | null>(null)
|
||||||
|
|
||||||
|
// Fetch tickets assigned to current user (active statuses only)
|
||||||
|
const { data } = useQuery({
|
||||||
|
queryKey: ['repair-tickets', 'tech-assigned', cashier?.id],
|
||||||
|
queryFn: () => api.get<PaginatedResponse<RepairTicket>>('/v1/repair-tickets', {
|
||||||
|
page: 1,
|
||||||
|
limit: 50,
|
||||||
|
sort: 'created_at',
|
||||||
|
order: 'asc',
|
||||||
|
q: undefined,
|
||||||
|
// Filter to active statuses — the API will return all if no status filter, we filter client-side
|
||||||
|
}),
|
||||||
|
enabled: !!cashier?.id,
|
||||||
|
staleTime: 15_000,
|
||||||
|
refetchInterval: 30_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Filter to tickets assigned to this technician in active statuses
|
||||||
|
const activeStatuses = ['diagnosing', 'pending_approval', 'approved', 'in_progress', 'pending_parts', 'ready']
|
||||||
|
const myTickets = (data?.data ?? []).filter(t =>
|
||||||
|
t.assignedTechnicianId === cashier?.id && activeStatuses.includes(t.status)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Auto-select first ticket
|
||||||
|
if (!selectedTicketId && myTickets.length > 0) {
|
||||||
|
setSelectedTicketId(myTickets[0].id)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (myTickets.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||||
|
<div className="text-center space-y-2">
|
||||||
|
<Wrench className="h-12 w-12 mx-auto opacity-20" />
|
||||||
|
<p className="text-lg font-medium">No assigned tickets</p>
|
||||||
|
<p className="text-sm">Tickets assigned to you will appear here</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Ticket selector */}
|
||||||
|
{myTickets.length > 1 && (
|
||||||
|
<div className="flex items-center gap-2 px-4 py-2 border-b border-border shrink-0 bg-muted/30">
|
||||||
|
<span className="text-sm text-muted-foreground">Ticket:</span>
|
||||||
|
<Select value={selectedTicketId ?? ''} onValueChange={setSelectedTicketId}>
|
||||||
|
<SelectTrigger className="h-8 w-72">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{myTickets.map(t => (
|
||||||
|
<SelectItem key={t.id} value={t.id}>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
#{t.ticketNumber} — {t.customerName}
|
||||||
|
<Badge variant="outline" className="text-[10px]">{STATUS_LABELS[t.status] ?? t.status}</Badge>
|
||||||
|
</span>
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<span className="text-xs text-muted-foreground">{myTickets.length} active</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Workbench */}
|
||||||
|
<div className="flex-1 min-h-0 overflow-hidden">
|
||||||
|
{selectedTicketId && <RepairWorkbench ticketId={selectedTicketId} />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,323 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import {
|
||||||
|
repairTicketDetailOptions, repairTicketKeys, repairTicketMutations,
|
||||||
|
repairLineItemListOptions, repairLineItemMutations,
|
||||||
|
repairServiceTemplateListOptions,
|
||||||
|
repairNoteListOptions, repairNoteMutations,
|
||||||
|
} from '@/api/repairs'
|
||||||
|
import { StatusProgress } from '@/components/repairs/status-progress'
|
||||||
|
import { TicketPhotos } from '@/components/repairs/ticket-photos'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
import { ChevronRight, Plus, Camera, MessageSquare, Wrench, Trash2 } from 'lucide-react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
const STATUS_FLOW = ['new', 'intake', 'diagnosing', 'pending_approval', 'approved', 'in_progress', 'ready', 'picked_up']
|
||||||
|
|
||||||
|
interface RepairWorkbenchProps {
|
||||||
|
ticketId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RepairWorkbench({ ticketId }: RepairWorkbenchProps) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [activeSection, setActiveSection] = useState<'work' | 'parts' | 'photos' | 'notes'>('work')
|
||||||
|
const [newNote, setNewNote] = useState('')
|
||||||
|
|
||||||
|
// Add line item state
|
||||||
|
const [addingItem, setAddingItem] = useState(false)
|
||||||
|
const [newItemType, setNewItemType] = useState('part')
|
||||||
|
const [newItemDesc, setNewItemDesc] = useState('')
|
||||||
|
const [newItemQty, setNewItemQty] = useState('1')
|
||||||
|
const [newItemPrice, setNewItemPrice] = useState('')
|
||||||
|
|
||||||
|
const { data: ticket } = useQuery({
|
||||||
|
...repairTicketDetailOptions(ticketId),
|
||||||
|
staleTime: 15_000,
|
||||||
|
})
|
||||||
|
|
||||||
|
const { data: lineItemsData } = useQuery({
|
||||||
|
...repairLineItemListOptions(ticketId, { page: 1, limit: 100, q: undefined, sort: undefined, order: 'asc' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
const { data: notesData } = useQuery(repairNoteListOptions(ticketId))
|
||||||
|
|
||||||
|
const { data: templatesData } = useQuery({
|
||||||
|
...repairServiceTemplateListOptions({ page: 1, limit: 50, q: undefined, sort: 'sort_order', order: 'asc' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
const statusMutation = useMutation({
|
||||||
|
mutationFn: (status: string) => repairTicketMutations.updateStatus(ticketId, status),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: repairTicketKeys.detail(ticketId) })
|
||||||
|
toast.success('Status updated')
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
const addNoteMutation = useMutation({
|
||||||
|
mutationFn: () => repairNoteMutations.create(ticketId, { content: newNote, visibility: 'internal' }),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repair-tickets', ticketId, 'notes'] })
|
||||||
|
setNewNote('')
|
||||||
|
toast.success('Note added')
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
const addLineItemMutation = useMutation({
|
||||||
|
mutationFn: () => repairLineItemMutations.create(ticketId, {
|
||||||
|
itemType: newItemType,
|
||||||
|
description: newItemDesc,
|
||||||
|
qty: parseInt(newItemQty) || 1,
|
||||||
|
unitPrice: parseFloat(newItemPrice) || 0,
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repair-tickets', ticketId, 'line-items'] })
|
||||||
|
setAddingItem(false)
|
||||||
|
setNewItemDesc('')
|
||||||
|
setNewItemPrice('')
|
||||||
|
toast.success('Item added')
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
const deleteLineItemMutation = useMutation({
|
||||||
|
mutationFn: (id: string) => repairLineItemMutations.delete(id),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repair-tickets', ticketId, 'line-items'] })
|
||||||
|
toast.success('Item removed')
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!ticket) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center h-full">
|
||||||
|
<div className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const lineItems = lineItemsData?.data ?? []
|
||||||
|
const notes = notesData?.data ?? []
|
||||||
|
const templates = templatesData?.data ?? []
|
||||||
|
const currentIdx = STATUS_FLOW.indexOf(ticket.status)
|
||||||
|
const nextStatus = currentIdx >= 0 && currentIdx < STATUS_FLOW.length - 1 ? STATUS_FLOW[currentIdx + 1] : null
|
||||||
|
const isTerminal = ['picked_up', 'delivered', 'cancelled'].includes(ticket.status)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="p-4 border-b border-border shrink-0 space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl font-bold">#{ticket.ticketNumber}</h2>
|
||||||
|
<p className="text-sm text-muted-foreground">{ticket.customerName} — {ticket.itemDescription ?? 'No item'}</p>
|
||||||
|
</div>
|
||||||
|
{nextStatus && !isTerminal && (
|
||||||
|
<Button size="lg" className="h-12 gap-2 text-base" onClick={() => statusMutation.mutate(nextStatus)}>
|
||||||
|
Next Step <ChevronRight className="h-5 w-5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<StatusProgress currentStatus={ticket.status} onStatusClick={(s) => !isTerminal && statusMutation.mutate(s)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Section toggle */}
|
||||||
|
<div className="flex gap-1 px-4 py-2 border-b border-border shrink-0 bg-muted/30">
|
||||||
|
{[
|
||||||
|
{ key: 'work' as const, icon: Wrench, label: 'Work' },
|
||||||
|
{ key: 'parts' as const, icon: Plus, label: 'Parts' },
|
||||||
|
{ key: 'photos' as const, icon: Camera, label: 'Photos' },
|
||||||
|
{ key: 'notes' as const, icon: MessageSquare, label: `Notes (${notes.length})` },
|
||||||
|
].map((s) => (
|
||||||
|
<Button
|
||||||
|
key={s.key}
|
||||||
|
variant={activeSection === s.key ? 'default' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
className="h-9 gap-1.5"
|
||||||
|
onClick={() => setActiveSection(s.key)}
|
||||||
|
>
|
||||||
|
<s.icon className="h-3.5 w-3.5" />
|
||||||
|
{s.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex-1 overflow-y-auto p-4">
|
||||||
|
{activeSection === 'work' && (
|
||||||
|
<div className="space-y-4 max-w-2xl">
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-medium text-muted-foreground mb-1">Problem Description</p>
|
||||||
|
<p className="text-sm">{ticket.problemDescription}</p>
|
||||||
|
</div>
|
||||||
|
{ticket.conditionIn && (
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-medium text-muted-foreground mb-1">Condition at Intake</p>
|
||||||
|
<Badge variant="outline">{ticket.conditionIn}</Badge>
|
||||||
|
{ticket.conditionInNotes && <p className="text-sm text-muted-foreground mt-1">{ticket.conditionInNotes}</p>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{ticket.technicianNotes && (
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-medium text-muted-foreground mb-1">Technician Notes</p>
|
||||||
|
<p className="text-sm">{ticket.technicianNotes}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<Separator />
|
||||||
|
<div className="flex gap-4">
|
||||||
|
{ticket.estimatedCost && <div><p className="text-xs text-muted-foreground">Estimate</p><p className="text-lg font-bold">${ticket.estimatedCost}</p></div>}
|
||||||
|
{ticket.actualCost && <div><p className="text-xs text-muted-foreground">Actual</p><p className="text-lg font-bold">${ticket.actualCost}</p></div>}
|
||||||
|
{ticket.promisedDate && <div><p className="text-xs text-muted-foreground">Promised</p><p className="text-lg font-bold">{new Date(ticket.promisedDate).toLocaleDateString()}</p></div>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeSection === 'parts' && (
|
||||||
|
<div className="space-y-4 max-w-2xl">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h3 className="font-medium">Line Items</h3>
|
||||||
|
<Button size="sm" onClick={() => setAddingItem(true)}>
|
||||||
|
<Plus className="h-3.5 w-3.5 mr-1" />Add
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Template quick-add */}
|
||||||
|
{templates.length > 0 && (
|
||||||
|
<div className="flex gap-1.5 flex-wrap">
|
||||||
|
{templates.slice(0, 8).map(t => (
|
||||||
|
<Button
|
||||||
|
key={t.id}
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 text-xs"
|
||||||
|
onClick={async () => {
|
||||||
|
await repairLineItemMutations.create(ticketId, {
|
||||||
|
itemType: t.itemType,
|
||||||
|
description: t.description ?? t.name,
|
||||||
|
qty: 1,
|
||||||
|
unitPrice: parseFloat(t.defaultPrice),
|
||||||
|
})
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['repair-tickets', ticketId, 'line-items'] })
|
||||||
|
toast.success(`Added ${t.name}`)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t.name}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{addingItem && (
|
||||||
|
<div className="flex items-end gap-2 p-3 border rounded-lg bg-muted/30">
|
||||||
|
<div className="w-24 space-y-1">
|
||||||
|
<Label className="text-xs">Type</Label>
|
||||||
|
<Select value={newItemType} onValueChange={setNewItemType}>
|
||||||
|
<SelectTrigger className="h-8 text-xs"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="labor">Labor</SelectItem>
|
||||||
|
<SelectItem value="part">Part</SelectItem>
|
||||||
|
<SelectItem value="flat_rate">Flat Rate</SelectItem>
|
||||||
|
<SelectItem value="misc">Misc</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 space-y-1">
|
||||||
|
<Label className="text-xs">Description</Label>
|
||||||
|
<Input className="h-8" value={newItemDesc} onChange={(e) => setNewItemDesc(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
<div className="w-16 space-y-1">
|
||||||
|
<Label className="text-xs">Qty</Label>
|
||||||
|
<Input className="h-8" type="number" value={newItemQty} onChange={(e) => setNewItemQty(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
<div className="w-24 space-y-1">
|
||||||
|
<Label className="text-xs">Price</Label>
|
||||||
|
<Input className="h-8" type="number" step="0.01" value={newItemPrice} onChange={(e) => setNewItemPrice(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
<Button size="sm" className="h-8" onClick={() => addLineItemMutation.mutate()} disabled={!newItemDesc}>Add</Button>
|
||||||
|
<Button variant="ghost" size="sm" className="h-8" onClick={() => setAddingItem(false)}>Cancel</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-1">
|
||||||
|
{lineItems.map((item) => (
|
||||||
|
<div key={item.id} className="flex items-center justify-between py-2 px-3 rounded hover:bg-muted/50">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Badge variant="outline" className="text-[10px] h-5">{item.itemType}</Badge>
|
||||||
|
<span className="text-sm">{item.description}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">x{item.qty}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-medium">${item.totalPrice}</span>
|
||||||
|
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => deleteLineItemMutation.mutate(item.id)}>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{lineItems.length > 0 && (
|
||||||
|
<>
|
||||||
|
<Separator />
|
||||||
|
<div className="flex justify-between px-3 py-2 font-semibold">
|
||||||
|
<span>Total</span>
|
||||||
|
<span>${lineItems.reduce((s, i) => s + parseFloat(i.totalPrice), 0).toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{lineItems.length === 0 && !addingItem && (
|
||||||
|
<p className="text-sm text-muted-foreground text-center py-4">No line items yet</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeSection === 'photos' && (
|
||||||
|
<TicketPhotos ticketId={ticketId} currentStatus={ticket.status} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeSection === 'notes' && (
|
||||||
|
<div className="space-y-4 max-w-2xl">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Textarea
|
||||||
|
value={newNote}
|
||||||
|
onChange={(e) => setNewNote(e.target.value)}
|
||||||
|
placeholder="Add a note..."
|
||||||
|
rows={2}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
className="shrink-0"
|
||||||
|
onClick={() => addNoteMutation.mutate()}
|
||||||
|
disabled={!newNote.trim() || addNoteMutation.isPending}
|
||||||
|
>
|
||||||
|
Add
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-3">
|
||||||
|
{notes.map((note) => (
|
||||||
|
<div key={note.id} className="border rounded-lg p-3">
|
||||||
|
<div className="flex items-center justify-between mb-1">
|
||||||
|
<span className="text-sm font-medium">{note.authorName}</span>
|
||||||
|
<span className="text-xs text-muted-foreground">{new Date(note.createdAt).toLocaleString()}</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm">{note.content}</p>
|
||||||
|
{note.visibility === 'internal' && <Badge variant="outline" className="text-[10px] mt-1">Internal</Badge>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{notes.length === 0 && (
|
||||||
|
<p className="text-sm text-muted-foreground text-center py-4">No notes yet</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { RepairDeskView } from './repair-desk-view'
|
||||||
|
import { RepairTechView } from './repair-tech-view'
|
||||||
|
|
||||||
|
interface RepairsStationProps {
|
||||||
|
permissions: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RepairsStation({ permissions }: RepairsStationProps) {
|
||||||
|
const canEdit = permissions.includes('repairs.edit')
|
||||||
|
|
||||||
|
// Front desk (can edit/intake) gets the desk view with queue + intake
|
||||||
|
// Technician (view only) gets the focused workbench
|
||||||
|
if (canEdit) {
|
||||||
|
return <RepairDeskView canEdit={canEdit} />
|
||||||
|
}
|
||||||
|
|
||||||
|
return <RepairTechView />
|
||||||
|
}
|
||||||
177
packages/admin/src/components/station/station-shell.tsx
Normal file
177
packages/admin/src/components/station/station-shell.tsx
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
import { useEffect, useRef, useCallback, useState } from 'react'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { queryOptions } from '@tanstack/react-query'
|
||||||
|
import { api } from '@/lib/api-client'
|
||||||
|
import { usePOSStore } from '@/stores/pos.store'
|
||||||
|
import { useStationStore } from '@/stores/station.store'
|
||||||
|
import { moduleListOptions } from '@/api/modules'
|
||||||
|
import { currentDrawerOptions } from '@/api/pos'
|
||||||
|
import { POSRegister } from '@/components/pos/pos-register'
|
||||||
|
import { POSLockScreen } from '@/components/pos/pos-lock-screen'
|
||||||
|
import { StationTopBar } from './station-top-bar'
|
||||||
|
import { RepairsStation } from '@/components/station-repairs/repairs-station'
|
||||||
|
import { LessonsStation } from '@/components/station-lessons/lessons-station'
|
||||||
|
|
||||||
|
interface Location {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AppConfigEntry {
|
||||||
|
key: string
|
||||||
|
value: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
function locationsOptions() {
|
||||||
|
return queryOptions({
|
||||||
|
queryKey: ['locations'],
|
||||||
|
queryFn: () => api.get<{ data: Location[] }>('/v1/locations'),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function configOptions(key: string) {
|
||||||
|
return queryOptions({
|
||||||
|
queryKey: ['config', key],
|
||||||
|
queryFn: async (): Promise<string | null> => {
|
||||||
|
try {
|
||||||
|
const entry = await api.get<AppConfigEntry>(`/v1/config/${key}`)
|
||||||
|
return entry.value
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StationShell() {
|
||||||
|
const { locationId, setLocation, locked, lock, touchActivity, token, setDrawerSession } = usePOSStore()
|
||||||
|
const { activeTab, setActiveTab } = useStationStore()
|
||||||
|
|
||||||
|
// Fetch lock timeout from config
|
||||||
|
const { data: lockTimeoutStr } = useQuery({
|
||||||
|
...configOptions('pos_lock_timeout'),
|
||||||
|
enabled: !!token,
|
||||||
|
})
|
||||||
|
const lockTimeoutMinutes = parseInt(lockTimeoutStr ?? '15') || 15
|
||||||
|
|
||||||
|
// Auto-lock timer
|
||||||
|
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (locked || lockTimeoutMinutes === 0) {
|
||||||
|
if (timerRef.current) clearInterval(timerRef.current)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
timerRef.current = setInterval(() => {
|
||||||
|
const { lastActivity, locked: isLocked } = usePOSStore.getState()
|
||||||
|
if (!isLocked && Date.now() - lastActivity > lockTimeoutMinutes * 60_000) {
|
||||||
|
lock()
|
||||||
|
}
|
||||||
|
}, 30_000)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (timerRef.current) clearInterval(timerRef.current)
|
||||||
|
}
|
||||||
|
}, [locked, lockTimeoutMinutes, lock])
|
||||||
|
|
||||||
|
// Track activity
|
||||||
|
const handleActivity = useCallback(() => {
|
||||||
|
if (!locked) touchActivity()
|
||||||
|
}, [locked, touchActivity])
|
||||||
|
|
||||||
|
// Fetch locations
|
||||||
|
const { data: locationsData } = useQuery({
|
||||||
|
...locationsOptions(),
|
||||||
|
enabled: !!token,
|
||||||
|
})
|
||||||
|
const locations = locationsData?.data ?? []
|
||||||
|
|
||||||
|
// Auto-select first location
|
||||||
|
useEffect(() => {
|
||||||
|
if (!locationId && locations.length > 0) {
|
||||||
|
setLocation(locations[0].id)
|
||||||
|
}
|
||||||
|
}, [locationId, locations, setLocation])
|
||||||
|
|
||||||
|
// Fetch enabled modules
|
||||||
|
const { data: modulesData } = useQuery({
|
||||||
|
...moduleListOptions(),
|
||||||
|
enabled: !!token,
|
||||||
|
})
|
||||||
|
const enabledModules = new Set(
|
||||||
|
(modulesData?.data ?? []).filter((m) => m.enabled && m.licensed).map((m) => m.slug),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Fetch permissions for current user
|
||||||
|
const [permissions, setPermissions] = useState<string[]>([])
|
||||||
|
const { data: permData } = useQuery({
|
||||||
|
queryKey: ['me', 'permissions'],
|
||||||
|
queryFn: () => api.get<{ permissions: string[] }>('/v1/me/permissions'),
|
||||||
|
enabled: !!token,
|
||||||
|
})
|
||||||
|
useEffect(() => {
|
||||||
|
if (permData?.permissions) setPermissions(permData.permissions)
|
||||||
|
}, [permData])
|
||||||
|
|
||||||
|
// Auto-select first available tab based on permissions + modules
|
||||||
|
useEffect(() => {
|
||||||
|
if (!token || !permData) return
|
||||||
|
const perms = permData.permissions ?? []
|
||||||
|
const tabs = [
|
||||||
|
{ key: 'pos' as const, perm: 'pos.view', mod: 'pos' },
|
||||||
|
{ key: 'repairs' as const, perm: 'repairs.view', mod: 'repairs' },
|
||||||
|
{ key: 'lessons' as const, perm: 'lessons.view', mod: 'lessons' },
|
||||||
|
]
|
||||||
|
const available = tabs.filter(t => perms.includes(t.perm) && enabledModules.has(t.mod))
|
||||||
|
if (available.length > 0 && !available.find(t => t.key === activeTab)) {
|
||||||
|
setActiveTab(available[0].key)
|
||||||
|
}
|
||||||
|
}, [token, permData, enabledModules, activeTab, setActiveTab])
|
||||||
|
|
||||||
|
// Fetch drawer for POS tab (needed in top bar)
|
||||||
|
const { data: drawer } = useQuery({
|
||||||
|
...currentDrawerOptions(locationId),
|
||||||
|
retry: false,
|
||||||
|
enabled: !!locationId && !!token,
|
||||||
|
})
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (drawer?.id && drawer.status === 'open') {
|
||||||
|
setDrawerSession(drawer.id)
|
||||||
|
} else {
|
||||||
|
setDrawerSession(null)
|
||||||
|
}
|
||||||
|
}, [drawer, setDrawerSession])
|
||||||
|
|
||||||
|
const hasPermission = (perm: string) => permissions.includes(perm)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="relative flex flex-col h-full"
|
||||||
|
onPointerDown={handleActivity}
|
||||||
|
onKeyDown={handleActivity}
|
||||||
|
>
|
||||||
|
{locked && <POSLockScreen />}
|
||||||
|
<StationTopBar
|
||||||
|
locations={locations}
|
||||||
|
locationId={locationId}
|
||||||
|
onLocationChange={setLocation}
|
||||||
|
drawer={drawer ?? null}
|
||||||
|
permissions={permissions}
|
||||||
|
enabledModules={enabledModules}
|
||||||
|
/>
|
||||||
|
<div className="flex-1 min-h-0 overflow-hidden">
|
||||||
|
{activeTab === 'pos' && enabledModules.has('pos') && hasPermission('pos.view') && (
|
||||||
|
<POSRegister embedded />
|
||||||
|
)}
|
||||||
|
{activeTab === 'repairs' && enabledModules.has('repairs') && hasPermission('repairs.view') && (
|
||||||
|
<RepairsStation permissions={permissions} />
|
||||||
|
)}
|
||||||
|
{activeTab === 'lessons' && enabledModules.has('lessons') && hasPermission('lessons.view') && (
|
||||||
|
<LessonsStation permissions={permissions} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
127
packages/admin/src/components/station/station-top-bar.tsx
Normal file
127
packages/admin/src/components/station/station-top-bar.tsx
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import { usePOSStore } from '@/stores/pos.store'
|
||||||
|
import { useStationStore } from '@/stores/station.store'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
|
import { ArrowLeft, Lock, DollarSign, Receipt, FileText, ShoppingCart, Wrench, GraduationCap } from 'lucide-react'
|
||||||
|
import type { DrawerSession } from '@/api/pos'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { POSDrawerDialog } from '@/components/pos/pos-drawer-dialog'
|
||||||
|
|
||||||
|
type StationTab = 'pos' | 'repairs' | 'lessons'
|
||||||
|
|
||||||
|
const TAB_CONFIG: { key: StationTab; label: string; icon: typeof ShoppingCart; permission: string; module: string }[] = [
|
||||||
|
{ key: 'pos', label: 'POS', icon: ShoppingCart, permission: 'pos.view', module: 'pos' },
|
||||||
|
{ key: 'repairs', label: 'Repairs', icon: Wrench, permission: 'repairs.view', module: 'repairs' },
|
||||||
|
{ key: 'lessons', label: 'Lessons', icon: GraduationCap, permission: 'lessons.view', module: 'lessons' },
|
||||||
|
]
|
||||||
|
|
||||||
|
interface StationTopBarProps {
|
||||||
|
locations: { id: string; name: string }[]
|
||||||
|
locationId: string | null
|
||||||
|
onLocationChange: (id: string) => void
|
||||||
|
drawer: DrawerSession | null
|
||||||
|
permissions: string[]
|
||||||
|
enabledModules: Set<string>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StationTopBar({ locations, locationId, onLocationChange, drawer, permissions, enabledModules }: StationTopBarProps) {
|
||||||
|
const cashier = usePOSStore((s) => s.cashier)
|
||||||
|
const lockFn = usePOSStore((s) => s.lock)
|
||||||
|
const receiptFormat = usePOSStore((s) => s.receiptFormat)
|
||||||
|
const setReceiptFormat = usePOSStore((s) => s.setReceiptFormat)
|
||||||
|
const { activeTab, setActiveTab } = useStationStore()
|
||||||
|
const [drawerDialogOpen, setDrawerDialogOpen] = useState(false)
|
||||||
|
|
||||||
|
const drawerOpen = drawer?.status === 'open'
|
||||||
|
const isThermal = receiptFormat === 'thermal'
|
||||||
|
|
||||||
|
const hasPermission = (perm: string) => permissions.includes(perm)
|
||||||
|
const visibleTabs = TAB_CONFIG.filter(t => hasPermission(t.permission) && enabledModules.has(t.module))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div className="h-12 border-b border-border bg-card flex items-center px-3 shrink-0 gap-2">
|
||||||
|
{/* Left: back link */}
|
||||||
|
<Link to="/login" className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground mr-2">
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
<span className="hidden sm:inline">Admin</span>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex items-center gap-1 bg-muted rounded-lg p-0.5">
|
||||||
|
{visibleTabs.map((tab) => (
|
||||||
|
<Button
|
||||||
|
key={tab.key}
|
||||||
|
variant={activeTab === tab.key ? 'default' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
className={`h-8 gap-1.5 text-xs ${activeTab === tab.key ? '' : 'text-muted-foreground hover:text-foreground'}`}
|
||||||
|
onClick={() => setActiveTab(tab.key)}
|
||||||
|
>
|
||||||
|
<tab.icon className="h-3.5 w-3.5" />
|
||||||
|
{tab.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Spacer */}
|
||||||
|
<div className="flex-1" />
|
||||||
|
|
||||||
|
{/* Location */}
|
||||||
|
{locations.length > 1 ? (
|
||||||
|
<Select value={locationId ?? ''} onValueChange={onLocationChange}>
|
||||||
|
<SelectTrigger className="h-8 w-40 text-sm">
|
||||||
|
<SelectValue placeholder="Location" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{locations.map((loc) => (
|
||||||
|
<SelectItem key={loc.id} value={loc.id}>{loc.name}</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
) : locations.length === 1 ? (
|
||||||
|
<span className="text-sm text-muted-foreground">{locations[0].name}</span>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{/* POS-specific controls */}
|
||||||
|
{activeTab === 'pos' && (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 gap-1.5 text-xs text-muted-foreground"
|
||||||
|
onClick={() => setReceiptFormat(isThermal ? 'full' : 'thermal')}
|
||||||
|
title={isThermal ? 'Thermal' : 'Full Page'}
|
||||||
|
>
|
||||||
|
{isThermal ? <Receipt className="h-3.5 w-3.5" /> : <FileText className="h-3.5 w-3.5" />}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button variant="ghost" size="sm" className="gap-1.5" onClick={() => setDrawerDialogOpen(true)}>
|
||||||
|
<DollarSign className="h-4 w-4" />
|
||||||
|
{drawerOpen ? (
|
||||||
|
<Badge variant="default" className="text-xs">Open</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant="outline" className="text-xs">Closed</Badge>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Cashier + Lock */}
|
||||||
|
{cashier && (
|
||||||
|
<span className="text-sm text-muted-foreground">{cashier.firstName}</span>
|
||||||
|
)}
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={lockFn} title="Lock Station">
|
||||||
|
<Lock className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<POSDrawerDialog
|
||||||
|
open={drawerDialogOpen}
|
||||||
|
onOpenChange={setDrawerDialogOpen}
|
||||||
|
drawer={drawer}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
66
packages/admin/src/components/ui/alert.tsx
Normal file
66
packages/admin/src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const alertVariants = cva(
|
||||||
|
"relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-card text-card-foreground",
|
||||||
|
destructive:
|
||||||
|
"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function Alert({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert"
|
||||||
|
role="alert"
|
||||||
|
className={cn(alertVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-title"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-description"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Alert, AlertTitle, AlertDescription }
|
||||||
@@ -9,6 +9,8 @@
|
|||||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||||
|
|
||||||
import { Route as rootRouteImport } from './routes/__root'
|
import { Route as rootRouteImport } from './routes/__root'
|
||||||
|
import { Route as StationRouteImport } from './routes/station'
|
||||||
|
import { Route as ResetPasswordRouteImport } from './routes/reset-password'
|
||||||
import { Route as PosRouteImport } from './routes/pos'
|
import { Route as PosRouteImport } from './routes/pos'
|
||||||
import { Route as LoginRouteImport } from './routes/login'
|
import { Route as LoginRouteImport } from './routes/login'
|
||||||
import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
|
import { Route as AuthenticatedRouteImport } from './routes/_authenticated'
|
||||||
@@ -58,6 +60,16 @@ import { Route as AuthenticatedAccountsAccountIdMembersRouteImport } from './rou
|
|||||||
import { Route as AuthenticatedAccountsAccountIdEnrollmentsRouteImport } from './routes/_authenticated/accounts/$accountId/enrollments'
|
import { Route as AuthenticatedAccountsAccountIdEnrollmentsRouteImport } from './routes/_authenticated/accounts/$accountId/enrollments'
|
||||||
import { Route as AuthenticatedLessonsScheduleInstructorsInstructorIdRouteImport } from './routes/_authenticated/lessons/schedule/instructors/$instructorId'
|
import { Route as AuthenticatedLessonsScheduleInstructorsInstructorIdRouteImport } from './routes/_authenticated/lessons/schedule/instructors/$instructorId'
|
||||||
|
|
||||||
|
const StationRoute = StationRouteImport.update({
|
||||||
|
id: '/station',
|
||||||
|
path: '/station',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
|
const ResetPasswordRoute = ResetPasswordRouteImport.update({
|
||||||
|
id: '/reset-password',
|
||||||
|
path: '/reset-password',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
const PosRoute = PosRouteImport.update({
|
const PosRoute = PosRouteImport.update({
|
||||||
id: '/pos',
|
id: '/pos',
|
||||||
path: '/pos',
|
path: '/pos',
|
||||||
@@ -337,6 +349,8 @@ export interface FileRoutesByFullPath {
|
|||||||
'/': typeof AuthenticatedIndexRoute
|
'/': typeof AuthenticatedIndexRoute
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/pos': typeof PosRoute
|
'/pos': typeof PosRoute
|
||||||
|
'/reset-password': typeof ResetPasswordRoute
|
||||||
|
'/station': typeof StationRoute
|
||||||
'/help': typeof AuthenticatedHelpRoute
|
'/help': typeof AuthenticatedHelpRoute
|
||||||
'/profile': typeof AuthenticatedProfileRoute
|
'/profile': typeof AuthenticatedProfileRoute
|
||||||
'/settings': typeof AuthenticatedSettingsRoute
|
'/settings': typeof AuthenticatedSettingsRoute
|
||||||
@@ -385,6 +399,8 @@ export interface FileRoutesByFullPath {
|
|||||||
export interface FileRoutesByTo {
|
export interface FileRoutesByTo {
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/pos': typeof PosRoute
|
'/pos': typeof PosRoute
|
||||||
|
'/reset-password': typeof ResetPasswordRoute
|
||||||
|
'/station': typeof StationRoute
|
||||||
'/help': typeof AuthenticatedHelpRoute
|
'/help': typeof AuthenticatedHelpRoute
|
||||||
'/profile': typeof AuthenticatedProfileRoute
|
'/profile': typeof AuthenticatedProfileRoute
|
||||||
'/settings': typeof AuthenticatedSettingsRoute
|
'/settings': typeof AuthenticatedSettingsRoute
|
||||||
@@ -435,6 +451,8 @@ export interface FileRoutesById {
|
|||||||
'/_authenticated': typeof AuthenticatedRouteWithChildren
|
'/_authenticated': typeof AuthenticatedRouteWithChildren
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/pos': typeof PosRoute
|
'/pos': typeof PosRoute
|
||||||
|
'/reset-password': typeof ResetPasswordRoute
|
||||||
|
'/station': typeof StationRoute
|
||||||
'/_authenticated/help': typeof AuthenticatedHelpRoute
|
'/_authenticated/help': typeof AuthenticatedHelpRoute
|
||||||
'/_authenticated/profile': typeof AuthenticatedProfileRoute
|
'/_authenticated/profile': typeof AuthenticatedProfileRoute
|
||||||
'/_authenticated/settings': typeof AuthenticatedSettingsRoute
|
'/_authenticated/settings': typeof AuthenticatedSettingsRoute
|
||||||
@@ -487,6 +505,8 @@ export interface FileRouteTypes {
|
|||||||
| '/'
|
| '/'
|
||||||
| '/login'
|
| '/login'
|
||||||
| '/pos'
|
| '/pos'
|
||||||
|
| '/reset-password'
|
||||||
|
| '/station'
|
||||||
| '/help'
|
| '/help'
|
||||||
| '/profile'
|
| '/profile'
|
||||||
| '/settings'
|
| '/settings'
|
||||||
@@ -535,6 +555,8 @@ export interface FileRouteTypes {
|
|||||||
to:
|
to:
|
||||||
| '/login'
|
| '/login'
|
||||||
| '/pos'
|
| '/pos'
|
||||||
|
| '/reset-password'
|
||||||
|
| '/station'
|
||||||
| '/help'
|
| '/help'
|
||||||
| '/profile'
|
| '/profile'
|
||||||
| '/settings'
|
| '/settings'
|
||||||
@@ -584,6 +606,8 @@ export interface FileRouteTypes {
|
|||||||
| '/_authenticated'
|
| '/_authenticated'
|
||||||
| '/login'
|
| '/login'
|
||||||
| '/pos'
|
| '/pos'
|
||||||
|
| '/reset-password'
|
||||||
|
| '/station'
|
||||||
| '/_authenticated/help'
|
| '/_authenticated/help'
|
||||||
| '/_authenticated/profile'
|
| '/_authenticated/profile'
|
||||||
| '/_authenticated/settings'
|
| '/_authenticated/settings'
|
||||||
@@ -635,10 +659,26 @@ export interface RootRouteChildren {
|
|||||||
AuthenticatedRoute: typeof AuthenticatedRouteWithChildren
|
AuthenticatedRoute: typeof AuthenticatedRouteWithChildren
|
||||||
LoginRoute: typeof LoginRoute
|
LoginRoute: typeof LoginRoute
|
||||||
PosRoute: typeof PosRoute
|
PosRoute: typeof PosRoute
|
||||||
|
ResetPasswordRoute: typeof ResetPasswordRoute
|
||||||
|
StationRoute: typeof StationRoute
|
||||||
}
|
}
|
||||||
|
|
||||||
declare module '@tanstack/react-router' {
|
declare module '@tanstack/react-router' {
|
||||||
interface FileRoutesByPath {
|
interface FileRoutesByPath {
|
||||||
|
'/station': {
|
||||||
|
id: '/station'
|
||||||
|
path: '/station'
|
||||||
|
fullPath: '/station'
|
||||||
|
preLoaderRoute: typeof StationRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
|
'/reset-password': {
|
||||||
|
id: '/reset-password'
|
||||||
|
path: '/reset-password'
|
||||||
|
fullPath: '/reset-password'
|
||||||
|
preLoaderRoute: typeof ResetPasswordRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
'/pos': {
|
'/pos': {
|
||||||
id: '/pos'
|
id: '/pos'
|
||||||
path: '/pos'
|
path: '/pos'
|
||||||
@@ -1112,6 +1152,8 @@ const rootRouteChildren: RootRouteChildren = {
|
|||||||
AuthenticatedRoute: AuthenticatedRouteWithChildren,
|
AuthenticatedRoute: AuthenticatedRouteWithChildren,
|
||||||
LoginRoute: LoginRoute,
|
LoginRoute: LoginRoute,
|
||||||
PosRoute: PosRoute,
|
PosRoute: PosRoute,
|
||||||
|
ResetPasswordRoute: ResetPasswordRoute,
|
||||||
|
StationRoute: StationRoute,
|
||||||
}
|
}
|
||||||
export const routeTree = rootRouteImport
|
export const routeTree = rootRouteImport
|
||||||
._addFileChildren(rootRouteChildren)
|
._addFileChildren(rootRouteChildren)
|
||||||
|
|||||||
@@ -1,11 +1,29 @@
|
|||||||
import { createRootRoute, Outlet } from '@tanstack/react-router'
|
import { createRootRoute, Outlet } from '@tanstack/react-router'
|
||||||
import { Toaster } from 'sonner'
|
import { Toaster } from 'sonner'
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
|
||||||
export const Route = createRootRoute({
|
export const Route = createRootRoute({
|
||||||
component: RootLayout,
|
component: RootLayout,
|
||||||
})
|
})
|
||||||
|
|
||||||
function RootLayout() {
|
function RootLayout() {
|
||||||
|
useEffect(() => {
|
||||||
|
fetch('/v1/store/branding')
|
||||||
|
.then((r) => r.ok ? r.json() : null)
|
||||||
|
.then((data: { name: string | null; hasLogo: boolean } | null) => {
|
||||||
|
if (!data) return
|
||||||
|
if (data.name) document.title = data.name
|
||||||
|
if (data.hasLogo) {
|
||||||
|
const link = document.querySelector<HTMLLinkElement>('link[rel="icon"]')
|
||||||
|
?? document.createElement('link')
|
||||||
|
link.rel = 'icon'
|
||||||
|
link.href = '/v1/store/logo'
|
||||||
|
document.head.appendChild(link)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Outlet />
|
<Outlet />
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { createFileRoute, Outlet, Link, redirect, useRouter } from '@tanstack/react-router'
|
import { createFileRoute, Outlet, Link, redirect, useRouter } from '@tanstack/react-router'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query'
|
||||||
import { queryOptions } from '@tanstack/react-query'
|
import { queryOptions } from '@tanstack/react-query'
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { api } from '@/lib/api-client'
|
import { api } from '@/lib/api-client'
|
||||||
@@ -9,6 +9,9 @@ import { moduleListOptions } from '@/api/modules'
|
|||||||
import { Avatar } from '@/components/shared/avatar-upload'
|
import { Avatar } from '@/components/shared/avatar-upload'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User, Wrench, Package, ClipboardList, FolderOpen, KeyRound, Settings, PanelLeftClose, PanelLeft, CalendarDays, GraduationCap, CalendarRange, BookOpen, BookMarked, Package2, Tag, Truck, ShoppingCart } from 'lucide-react'
|
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User, Wrench, Package, ClipboardList, FolderOpen, KeyRound, Settings, PanelLeftClose, PanelLeft, CalendarDays, GraduationCap, CalendarRange, BookOpen, BookMarked, Package2, Tag, Truck, ShoppingCart } from 'lucide-react'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated')({
|
export const Route = createFileRoute('/_authenticated')({
|
||||||
beforeLoad: () => {
|
beforeLoad: () => {
|
||||||
@@ -104,6 +107,58 @@ function NavGroup({ label, children, collapsed }: { label: string; children: Rea
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function SetPinModal() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [pin, setPin] = useState('')
|
||||||
|
const [confirmPin, setConfirmPin] = useState('')
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
const setPinMutation = useMutation({
|
||||||
|
mutationFn: () => api.post('/v1/auth/set-pin', { pin }),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
|
||||||
|
toast.success('PIN set successfully')
|
||||||
|
},
|
||||||
|
onError: (err) => setError(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
if (pin.length < 4 || pin.length > 6) { setError('PIN must be 4-6 digits'); return }
|
||||||
|
if (!/^\d+$/.test(pin)) { setError('PIN must be digits only'); return }
|
||||||
|
if (pin !== confirmPin) { setError('PINs do not match'); return }
|
||||||
|
setPinMutation.mutate()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
|
||||||
|
<div className="w-full max-w-sm rounded-xl border bg-card p-6 shadow-xl">
|
||||||
|
<h2 className="text-lg font-semibold mb-1">Set your POS PIN</h2>
|
||||||
|
<p className="text-sm text-muted-foreground mb-4">
|
||||||
|
A PIN is required to use the Point of Sale. Choose a 4-6 digit PIN you'll use to unlock the terminal.
|
||||||
|
</p>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>PIN</Label>
|
||||||
|
<Input type="password" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value)} placeholder="****" autoFocus />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Confirm PIN</Label>
|
||||||
|
<Input type="password" inputMode="numeric" maxLength={6} value={confirmPin} onChange={(e) => setConfirmPin(e.target.value)} placeholder="****" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||||
|
<Button type="submit" className="w-full" disabled={setPinMutation.isPending}>
|
||||||
|
{setPinMutation.isPending ? 'Setting...' : 'Set PIN'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function AuthenticatedLayout() {
|
function AuthenticatedLayout() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const user = useAuthStore((s) => s.user)
|
const user = useAuthStore((s) => s.user)
|
||||||
@@ -112,6 +167,13 @@ function AuthenticatedLayout() {
|
|||||||
const setPermissions = useAuthStore((s) => s.setPermissions)
|
const setPermissions = useAuthStore((s) => s.setPermissions)
|
||||||
const permissionsLoaded = useAuthStore((s) => s.permissionsLoaded)
|
const permissionsLoaded = useAuthStore((s) => s.permissionsLoaded)
|
||||||
|
|
||||||
|
// Fetch profile for PIN warning
|
||||||
|
const { data: profile } = useQuery(queryOptions({
|
||||||
|
queryKey: ['auth', 'me'],
|
||||||
|
queryFn: () => api.get<{ hasPin: boolean }>('/v1/auth/me'),
|
||||||
|
enabled: !!useAuthStore.getState().token,
|
||||||
|
}))
|
||||||
|
|
||||||
// Fetch permissions on mount
|
// Fetch permissions on mount
|
||||||
const { data: permData } = useQuery({
|
const { data: permData } = useQuery({
|
||||||
...myPermissionsOptions(),
|
...myPermissionsOptions(),
|
||||||
@@ -177,7 +239,7 @@ function AuthenticatedLayout() {
|
|||||||
{isModuleEnabled('pos') && canViewPOS && (
|
{isModuleEnabled('pos') && canViewPOS && (
|
||||||
<div className="mb-2">
|
<div className="mb-2">
|
||||||
<button
|
<button
|
||||||
onClick={() => { logout(); router.navigate({ to: '/pos' }) }}
|
onClick={() => { logout(); router.navigate({ to: '/station' }) }}
|
||||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent w-full"
|
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent w-full"
|
||||||
title={collapsed ? 'Point of Sale' : undefined}
|
title={collapsed ? 'Point of Sale' : undefined}
|
||||||
>
|
>
|
||||||
@@ -263,6 +325,7 @@ function AuthenticatedLayout() {
|
|||||||
</div>
|
</div>
|
||||||
</nav>
|
</nav>
|
||||||
<main className="flex-1 p-6 min-h-screen">
|
<main className="flex-1 p-6 min-h-screen">
|
||||||
|
{profile && !profile.hasPin && <SetPinModal />}
|
||||||
<Outlet />
|
<Outlet />
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -11,10 +11,22 @@ import { Input } from '@/components/ui/input'
|
|||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
import { Separator } from '@/components/ui/separator'
|
import { Separator } from '@/components/ui/separator'
|
||||||
|
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||||
import { Sun, Moon, Monitor } from 'lucide-react'
|
import { Sun, Moon, Monitor } from 'lucide-react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
import { AvatarUpload } from '@/components/shared/avatar-upload'
|
import { AvatarUpload } from '@/components/shared/avatar-upload'
|
||||||
|
|
||||||
|
interface Profile {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
firstName: string
|
||||||
|
lastName: string
|
||||||
|
role: string
|
||||||
|
employeeNumber: string | null
|
||||||
|
hasPin: boolean
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/profile')({
|
export const Route = createFileRoute('/_authenticated/profile')({
|
||||||
component: ProfilePage,
|
component: ProfilePage,
|
||||||
})
|
})
|
||||||
@@ -22,21 +34,56 @@ export const Route = createFileRoute('/_authenticated/profile')({
|
|||||||
function profileOptions() {
|
function profileOptions() {
|
||||||
return queryOptions({
|
return queryOptions({
|
||||||
queryKey: ['auth', 'me'],
|
queryKey: ['auth', 'me'],
|
||||||
queryFn: () => api.get<{ id: string; email: string; firstName: string; lastName: string }>('/v1/auth/me'),
|
queryFn: () => api.get<Profile>('/v1/auth/me'),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function ProfilePage() {
|
function ProfilePage() {
|
||||||
|
const { tab } = Route.useSearch() as { tab?: string }
|
||||||
|
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const setAuth = useAuthStore((s) => s.setAuth)
|
const setAuth = useAuthStore((s) => s.setAuth)
|
||||||
const storeUser = useAuthStore((s) => s.user)
|
const storeUser = useAuthStore((s) => s.user)
|
||||||
const storeToken = useAuthStore((s) => s.token)
|
const storeToken = useAuthStore((s) => s.token)
|
||||||
const { mode, colorTheme, setMode, setColorTheme } = useThemeStore()
|
|
||||||
|
|
||||||
const { data: profile } = useQuery(profileOptions())
|
const { data: profile } = useQuery(profileOptions())
|
||||||
|
|
||||||
const [firstName, setFirstName] = useState('')
|
return (
|
||||||
const [lastName, setLastName] = useState('')
|
<div className="space-y-6 max-w-2xl">
|
||||||
|
<h1 className="text-2xl font-bold">Profile</h1>
|
||||||
|
|
||||||
|
<Tabs defaultValue={tab === 'security' || tab === 'appearance' ? tab : 'account'}>
|
||||||
|
<TabsList>
|
||||||
|
<TabsTrigger value="account">Account</TabsTrigger>
|
||||||
|
<TabsTrigger value="security">Security</TabsTrigger>
|
||||||
|
<TabsTrigger value="appearance">Appearance</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
|
||||||
|
<TabsContent value="account">
|
||||||
|
<AccountTab profile={profile} queryClient={queryClient} setAuth={setAuth} storeUser={storeUser} storeToken={storeToken} />
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="security">
|
||||||
|
<SecurityTab profile={profile} queryClient={queryClient} />
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value="appearance">
|
||||||
|
<AppearanceTab />
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccountTab({ profile, queryClient, setAuth, storeUser, storeToken }: {
|
||||||
|
profile: Profile | undefined
|
||||||
|
queryClient: ReturnType<typeof useQueryClient>
|
||||||
|
setAuth: (token: string, user: any) => void
|
||||||
|
storeUser: any
|
||||||
|
storeToken: string | null
|
||||||
|
}) {
|
||||||
|
const [firstName, setFirstName] = useState(profile?.firstName ?? '')
|
||||||
|
const [lastName, setLastName] = useState(profile?.lastName ?? '')
|
||||||
const [nameLoaded, setNameLoaded] = useState(false)
|
const [nameLoaded, setNameLoaded] = useState(false)
|
||||||
|
|
||||||
if (profile && !nameLoaded) {
|
if (profile && !nameLoaded) {
|
||||||
@@ -45,12 +92,8 @@ function ProfilePage() {
|
|||||||
setNameLoaded(true)
|
setNameLoaded(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
const [currentPassword, setCurrentPassword] = useState('')
|
|
||||||
const [newPassword, setNewPassword] = useState('')
|
|
||||||
const [confirmPassword, setConfirmPassword] = useState('')
|
|
||||||
|
|
||||||
const updateProfileMutation = useMutation({
|
const updateProfileMutation = useMutation({
|
||||||
mutationFn: (data: Record<string, unknown>) => api.patch<{ id: string; email: string; firstName: string; lastName: string }>('/v1/auth/me', data),
|
mutationFn: (data: Record<string, unknown>) => api.patch<Profile>('/v1/auth/me', data),
|
||||||
onSuccess: (updated) => {
|
onSuccess: (updated) => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
|
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
|
||||||
if (storeToken && storeUser) {
|
if (storeToken && storeUser) {
|
||||||
@@ -61,6 +104,59 @@ function ProfilePage() {
|
|||||||
onError: (err) => toast.error(err.message),
|
onError: (err) => toast.error(err.message),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-lg">Account</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{profile?.id && (
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<AvatarUpload entityType="user" entityId={profile.id} size="lg" />
|
||||||
|
<div>
|
||||||
|
<p className="font-medium">{profile.firstName} {profile.lastName}</p>
|
||||||
|
<p className="text-sm text-muted-foreground">{profile.email}</p>
|
||||||
|
{profile.employeeNumber && (
|
||||||
|
<p className="text-xs text-muted-foreground">Employee #{profile.employeeNumber}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Email</Label>
|
||||||
|
<Input value={profile?.email ?? ''} disabled className="opacity-60" />
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>First Name</Label>
|
||||||
|
<Input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Last Name</Label>
|
||||||
|
<Input value={lastName} onChange={(e) => setLastName(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
onClick={() => updateProfileMutation.mutate({ firstName, lastName })}
|
||||||
|
disabled={updateProfileMutation.isPending}
|
||||||
|
>
|
||||||
|
{updateProfileMutation.isPending ? 'Saving...' : 'Save'}
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SecurityTab({ profile, queryClient }: {
|
||||||
|
profile: Profile | undefined
|
||||||
|
queryClient: ReturnType<typeof useQueryClient>
|
||||||
|
}) {
|
||||||
|
const [currentPassword, setCurrentPassword] = useState('')
|
||||||
|
const [newPassword, setNewPassword] = useState('')
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState('')
|
||||||
|
const [pin, setPin] = useState('')
|
||||||
|
const [confirmPin, setConfirmPin] = useState('')
|
||||||
|
|
||||||
const changePasswordMutation = useMutation({
|
const changePasswordMutation = useMutation({
|
||||||
mutationFn: () => api.post('/v1/auth/change-password', { currentPassword, newPassword }),
|
mutationFn: () => api.post('/v1/auth/change-password', { currentPassword, newPassword }),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
@@ -72,6 +168,26 @@ function ProfilePage() {
|
|||||||
onError: (err) => toast.error(err.message),
|
onError: (err) => toast.error(err.message),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const setPinMutation = useMutation({
|
||||||
|
mutationFn: () => api.post('/v1/auth/set-pin', { pin }),
|
||||||
|
onSuccess: () => {
|
||||||
|
setPin('')
|
||||||
|
setConfirmPin('')
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
|
||||||
|
toast.success('PIN set')
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
|
const removePinMutation = useMutation({
|
||||||
|
mutationFn: () => api.del('/v1/auth/pin'),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['auth', 'me'] })
|
||||||
|
toast.success('PIN removed')
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
function handlePasswordChange() {
|
function handlePasswordChange() {
|
||||||
if (newPassword.length < 12) {
|
if (newPassword.length < 12) {
|
||||||
toast.error('Password must be at least 12 characters')
|
toast.error('Password must be at least 12 characters')
|
||||||
@@ -84,47 +200,24 @@ function ProfilePage() {
|
|||||||
changePasswordMutation.mutate()
|
changePasswordMutation.mutate()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleSetPin() {
|
||||||
|
if (pin.length < 4 || pin.length > 6) {
|
||||||
|
toast.error('PIN must be 4-6 digits')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!/^\d+$/.test(pin)) {
|
||||||
|
toast.error('PIN must be digits only')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (pin !== confirmPin) {
|
||||||
|
toast.error('PINs do not match')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setPinMutation.mutate()
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6 max-w-2xl">
|
<div className="space-y-6">
|
||||||
<h1 className="text-2xl font-bold">Profile</h1>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle className="text-lg">Account</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-4">
|
|
||||||
{profile?.id && (
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<AvatarUpload entityType="user" entityId={profile.id} size="lg" />
|
|
||||||
<div>
|
|
||||||
<p className="font-medium">{profile.firstName} {profile.lastName}</p>
|
|
||||||
<p className="text-sm text-muted-foreground">{profile.email}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Email</Label>
|
|
||||||
<Input value={profile?.email ?? ''} disabled className="opacity-60" />
|
|
||||||
</div>
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>First Name</Label>
|
|
||||||
<Input value={firstName} onChange={(e) => setFirstName(e.target.value)} />
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Last Name</Label>
|
|
||||||
<Input value={lastName} onChange={(e) => setLastName(e.target.value)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={() => updateProfileMutation.mutate({ firstName, lastName })}
|
|
||||||
disabled={updateProfileMutation.isPending}
|
|
||||||
>
|
|
||||||
{updateProfileMutation.isPending ? 'Saving...' : 'Save'}
|
|
||||||
</Button>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-lg">Change Password</CardTitle>
|
<CardTitle className="text-lg">Change Password</CardTitle>
|
||||||
@@ -150,53 +243,113 @@ function ProfilePage() {
|
|||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-lg">Appearance</CardTitle>
|
<CardTitle className="text-lg">POS PIN</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<div className="space-y-2">
|
{profile?.employeeNumber && (
|
||||||
<Label>Mode</Label>
|
<p className="text-sm text-muted-foreground">
|
||||||
<div className="flex gap-2">
|
Your employee number is <span className="font-mono font-medium text-foreground">{profile.employeeNumber}</span>.
|
||||||
{[
|
To unlock the POS, enter your employee number followed by your PIN.
|
||||||
{ value: 'light' as const, icon: Sun, label: 'Light' },
|
</p>
|
||||||
{ value: 'dark' as const, icon: Moon, label: 'Dark' },
|
)}
|
||||||
{ value: 'system' as const, icon: Monitor, label: 'System' },
|
{profile?.hasPin ? (
|
||||||
].map((m) => (
|
<>
|
||||||
<Button
|
<p className="text-sm text-muted-foreground">You have a PIN set. You can change or remove it below.</p>
|
||||||
key={m.value}
|
<div className="grid grid-cols-2 gap-4">
|
||||||
variant={mode === m.value ? 'default' : 'secondary'}
|
<div className="space-y-2">
|
||||||
size="sm"
|
<Label>New PIN (4-6 digits)</Label>
|
||||||
onClick={() => setMode(m.value)}
|
<Input type="password" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value)} placeholder="****" />
|
||||||
>
|
</div>
|
||||||
<m.icon className="mr-2 h-4 w-4" />
|
<div className="space-y-2">
|
||||||
{m.label}
|
<Label>Confirm PIN</Label>
|
||||||
|
<Input type="password" inputMode="numeric" maxLength={6} value={confirmPin} onChange={(e) => setConfirmPin(e.target.value)} placeholder="****" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button onClick={handleSetPin} disabled={setPinMutation.isPending}>
|
||||||
|
{setPinMutation.isPending ? 'Saving...' : 'Change PIN'}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
<Button variant="outline" onClick={() => removePinMutation.mutate()} disabled={removePinMutation.isPending}>
|
||||||
</div>
|
{removePinMutation.isPending ? 'Removing...' : 'Remove PIN'}
|
||||||
</div>
|
|
||||||
|
|
||||||
<Separator />
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label>Color Theme</Label>
|
|
||||||
<div className="flex gap-2 flex-wrap">
|
|
||||||
{themes.map((t) => (
|
|
||||||
<Button
|
|
||||||
key={t.name}
|
|
||||||
variant={colorTheme === t.name ? 'default' : 'secondary'}
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setColorTheme(t.name)}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className="mr-2 h-3 w-3 rounded-full border inline-block"
|
|
||||||
style={{ backgroundColor: `hsl(${t.light.primary})` }}
|
|
||||||
/>
|
|
||||||
{t.label}
|
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
</div>
|
||||||
</div>
|
</>
|
||||||
</div>
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="text-sm text-muted-foreground">Set a PIN to unlock the Point of Sale terminal.</p>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>PIN (4-6 digits)</Label>
|
||||||
|
<Input type="password" inputMode="numeric" maxLength={6} value={pin} onChange={(e) => setPin(e.target.value)} placeholder="****" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Confirm PIN</Label>
|
||||||
|
<Input type="password" inputMode="numeric" maxLength={6} value={confirmPin} onChange={(e) => setConfirmPin(e.target.value)} placeholder="****" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button onClick={handleSetPin} disabled={setPinMutation.isPending}>
|
||||||
|
{setPinMutation.isPending ? 'Saving...' : 'Set PIN'}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function AppearanceTab() {
|
||||||
|
const { mode, colorTheme, setMode, setColorTheme } = useThemeStore()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-lg">Appearance</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Mode</Label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{[
|
||||||
|
{ value: 'light' as const, icon: Sun, label: 'Light' },
|
||||||
|
{ value: 'dark' as const, icon: Moon, label: 'Dark' },
|
||||||
|
{ value: 'system' as const, icon: Monitor, label: 'System' },
|
||||||
|
].map((m) => (
|
||||||
|
<Button
|
||||||
|
key={m.value}
|
||||||
|
variant={mode === m.value ? 'default' : 'secondary'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setMode(m.value)}
|
||||||
|
>
|
||||||
|
<m.icon className="mr-2 h-4 w-4" />
|
||||||
|
{m.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Separator />
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Color Theme</Label>
|
||||||
|
<div className="flex gap-2 flex-wrap">
|
||||||
|
{themes.map((t) => (
|
||||||
|
<Button
|
||||||
|
key={t.name}
|
||||||
|
variant={colorTheme === t.name ? 'default' : 'secondary'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setColorTheme(t.name)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="mr-2 h-3 w-3 rounded-full border inline-block"
|
||||||
|
style={{ backgroundColor: `hsl(${t.light.primary})` }}
|
||||||
|
/>
|
||||||
|
{t.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
|||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||||
import { ArrowLeft, Plus, Trash2, RotateCcw, Save, Search } from 'lucide-react'
|
import { ArrowLeft, Plus, Trash2, RotateCcw, Save, Search, Mail } from 'lucide-react'
|
||||||
import { PdfModal } from '@/components/repairs/pdf-modal'
|
import { PdfModal } from '@/components/repairs/pdf-modal'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
import { useAuthStore } from '@/stores/auth.store'
|
import { useAuthStore } from '@/stores/auth.store'
|
||||||
@@ -78,6 +78,17 @@ function RepairTicketDetailPage() {
|
|||||||
const { data: lineItemsData, isLoading: itemsLoading } = useQuery(repairLineItemListOptions(ticketId, params))
|
const { data: lineItemsData, isLoading: itemsLoading } = useQuery(repairLineItemListOptions(ticketId, params))
|
||||||
|
|
||||||
const [editFields, setEditFields] = useState<Record<string, string>>({})
|
const [editFields, setEditFields] = useState<Record<string, string>>({})
|
||||||
|
const [emailEstimateOpen, setEmailEstimateOpen] = useState(false)
|
||||||
|
const [estimateEmail, setEstimateEmail] = useState('')
|
||||||
|
|
||||||
|
const emailEstimateMutation = useMutation({
|
||||||
|
mutationFn: () => api.post<{ message: string }>(`/v1/repair-tickets/${ticketId}/email-estimate`, { email: estimateEmail }),
|
||||||
|
onSuccess: () => {
|
||||||
|
toast.success('Estimate emailed')
|
||||||
|
setEmailEstimateOpen(false)
|
||||||
|
},
|
||||||
|
onError: (err) => toast.error(err.message),
|
||||||
|
})
|
||||||
|
|
||||||
const statusMutation = useMutation({
|
const statusMutation = useMutation({
|
||||||
mutationFn: (status: string) => repairTicketMutations.updateStatus(ticketId, status),
|
mutationFn: (status: string) => repairTicketMutations.updateStatus(ticketId, status),
|
||||||
@@ -188,6 +199,37 @@ function RepairTicketDetailPage() {
|
|||||||
<h1 className="text-2xl font-bold">Ticket #{ticket.ticketNumber}</h1>
|
<h1 className="text-2xl font-bold">Ticket #{ticket.ticketNumber}</h1>
|
||||||
<p className="text-sm text-muted-foreground">{ticket.customerName} — {ticket.itemDescription ?? 'No item description'}</p>
|
<p className="text-sm text-muted-foreground">{ticket.customerName} — {ticket.itemDescription ?? 'No item description'}</p>
|
||||||
</div>
|
</div>
|
||||||
|
<Dialog open={emailEstimateOpen} onOpenChange={setEmailEstimateOpen}>
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button variant="outline" size="sm" className="gap-2" onClick={() => setEstimateEmail((ticket as any).customerEmail ?? '')}>
|
||||||
|
<Mail className="h-4 w-4" />Email Estimate
|
||||||
|
</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
<DialogContent className="max-w-sm">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Email Estimate</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label>Send to</Label>
|
||||||
|
<Input
|
||||||
|
type="email"
|
||||||
|
value={estimateEmail}
|
||||||
|
onChange={(e) => setEstimateEmail(e.target.value)}
|
||||||
|
placeholder="customer@example.com"
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
className="w-full"
|
||||||
|
onClick={() => emailEstimateMutation.mutate()}
|
||||||
|
disabled={!estimateEmail || emailEstimateMutation.isPending}
|
||||||
|
>
|
||||||
|
{emailEstimateMutation.isPending ? 'Sending...' : 'Send Estimate'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
<PdfModal ticket={ticket} lineItems={lineItemsData?.data ?? []} ticketId={ticketId} />
|
<PdfModal ticket={ticket} lineItems={lineItemsData?.data ?? []} ticketId={ticketId} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useState, useEffect } from 'react'
|
import { useState, useEffect } from 'react'
|
||||||
import { createFileRoute, useRouter, redirect } from '@tanstack/react-router'
|
import { createFileRoute, useRouter, redirect } from '@tanstack/react-router'
|
||||||
import { useAuthStore } from '@/stores/auth.store'
|
import { useAuthStore } from '@/stores/auth.store'
|
||||||
import { login } from '@/api/auth'
|
import { login, forgotPassword } from '@/api/auth'
|
||||||
|
|
||||||
interface Branding {
|
interface Branding {
|
||||||
name: string | null
|
name: string | null
|
||||||
@@ -26,6 +26,8 @@ function LoginPage() {
|
|||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [branding, setBranding] = useState<Branding | null>(null)
|
const [branding, setBranding] = useState<Branding | null>(null)
|
||||||
|
const [forgotMode, setForgotMode] = useState(false)
|
||||||
|
const [forgotSent, setForgotSent] = useState(false)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetch('/v1/store/branding')
|
fetch('/v1/store/branding')
|
||||||
@@ -72,42 +74,117 @@ function LoginPage() {
|
|||||||
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
|
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
{forgotMode ? (
|
||||||
<div className="space-y-2">
|
forgotSent ? (
|
||||||
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
|
<div className="text-center space-y-4">
|
||||||
<input
|
<p className="text-sm" style={{ color: '#b0bec5' }}>If an account exists with that email, you will receive a password reset link.</p>
|
||||||
type="email"
|
<button
|
||||||
placeholder="you@example.com"
|
onClick={() => { setForgotMode(false); setForgotSent(false); setError('') }}
|
||||||
value={email}
|
className="text-xs"
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
style={{ color: '#6b7a8d' }}
|
||||||
required
|
>
|
||||||
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
Back to sign in
|
||||||
/>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
) : (
|
||||||
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Password</label>
|
<form onSubmit={async (e) => {
|
||||||
<input
|
e.preventDefault()
|
||||||
type="password"
|
setError('')
|
||||||
value={password}
|
setLoading(true)
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
try {
|
||||||
required
|
await forgotPassword(email)
|
||||||
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
setForgotSent(true)
|
||||||
/>
|
} catch (err) {
|
||||||
</div>
|
setError(err instanceof Error ? err.message : 'Something went wrong')
|
||||||
{error && (
|
} finally {
|
||||||
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
|
setLoading(false)
|
||||||
)}
|
}
|
||||||
<button
|
}} className="space-y-4">
|
||||||
type="submit"
|
<p className="text-sm" style={{ color: '#b0bec5' }}>Enter your email and we'll send you a reset link.</p>
|
||||||
disabled={loading}
|
<div className="space-y-2">
|
||||||
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
|
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
|
||||||
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
|
<input
|
||||||
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
|
type="email"
|
||||||
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
|
placeholder="you@example.com"
|
||||||
>
|
value={email}
|
||||||
{loading ? 'Signing in...' : 'Sign in'}
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
</button>
|
required
|
||||||
</form>
|
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && (
|
||||||
|
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
|
||||||
|
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||||
|
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
|
||||||
|
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
|
||||||
|
>
|
||||||
|
{loading ? 'Sending...' : 'Send reset link'}
|
||||||
|
</button>
|
||||||
|
<div className="text-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => { setForgotMode(false); setError('') }}
|
||||||
|
className="text-xs"
|
||||||
|
style={{ color: '#6b7a8d' }}
|
||||||
|
>
|
||||||
|
Back to sign in
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Email</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
placeholder="you@example.com"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && (
|
||||||
|
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
|
||||||
|
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||||
|
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
|
||||||
|
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
|
||||||
|
>
|
||||||
|
{loading ? 'Signing in...' : 'Sign in'}
|
||||||
|
</button>
|
||||||
|
<div className="text-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => { setForgotMode(true); setError('') }}
|
||||||
|
className="text-xs"
|
||||||
|
style={{ color: '#6b7a8d' }}
|
||||||
|
>
|
||||||
|
Forgot password?
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,14 +1,7 @@
|
|||||||
import { createFileRoute } from '@tanstack/react-router'
|
import { createFileRoute, redirect } from '@tanstack/react-router'
|
||||||
import { POSRegister } from '@/components/pos/pos-register'
|
|
||||||
|
|
||||||
export const Route = createFileRoute('/pos')({
|
export const Route = createFileRoute('/pos')({
|
||||||
component: POSPage,
|
beforeLoad: () => {
|
||||||
|
throw redirect({ to: '/station' })
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
function POSPage() {
|
|
||||||
return (
|
|
||||||
<div className="h-screen w-screen overflow-hidden bg-background text-foreground">
|
|
||||||
<POSRegister />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
154
packages/admin/src/routes/reset-password.tsx
Normal file
154
packages/admin/src/routes/reset-password.tsx
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||||
|
import { resetPassword } from '@/api/auth'
|
||||||
|
|
||||||
|
interface Branding {
|
||||||
|
name: string | null
|
||||||
|
hasLogo: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/reset-password')({
|
||||||
|
component: ResetPasswordPage,
|
||||||
|
})
|
||||||
|
|
||||||
|
function ResetPasswordPage() {
|
||||||
|
const { token } = Route.useSearch() as { token?: string }
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState('')
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [success, setSuccess] = useState(false)
|
||||||
|
const [branding, setBranding] = useState<Branding | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch('/v1/store/branding')
|
||||||
|
.then((r) => r.ok ? r.json() : null)
|
||||||
|
.then((data) => { if (data) setBranding(data) })
|
||||||
|
.catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
setError('Missing reset token. Please use the link from your email.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (password !== confirmPassword) {
|
||||||
|
setError('Passwords do not match')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (password.length < 12) {
|
||||||
|
setError('Password must be at least 12 characters')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true)
|
||||||
|
try {
|
||||||
|
await resetPassword(token, password)
|
||||||
|
setSuccess(true)
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Reset failed. The link may have expired.')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="flex min-h-screen items-center justify-center"
|
||||||
|
style={{ background: 'linear-gradient(135deg, #0f1724 0%, #142038 100%)' }}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="w-full max-w-sm rounded-xl border p-8 shadow-2xl"
|
||||||
|
style={{ backgroundColor: '#131c2e', borderColor: '#1e2d45' }}
|
||||||
|
>
|
||||||
|
<div className="text-center mb-8">
|
||||||
|
{branding?.hasLogo ? (
|
||||||
|
<img src="/v1/store/logo" alt={branding.name ?? 'Store'} className="max-h-14 max-w-[220px] object-contain mx-auto" />
|
||||||
|
) : (
|
||||||
|
<h1 className="text-3xl font-bold" style={{ color: '#d8dfe9' }}>{branding?.name ?? 'LunarFront'}</h1>
|
||||||
|
)}
|
||||||
|
{branding?.name ? (
|
||||||
|
<p className="text-[10px] mt-2" style={{ color: '#4a5568' }}>Powered by <span style={{ color: '#6b7a8d' }}>LunarFront</span></p>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm mt-1" style={{ color: '#6b7a8d' }}>Small Business Management</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{success ? (
|
||||||
|
<div className="text-center space-y-4">
|
||||||
|
<p style={{ color: '#81c784' }}>Password reset successfully.</p>
|
||||||
|
<Link
|
||||||
|
to="/login"
|
||||||
|
className="inline-block h-9 rounded-md border px-4 py-2 text-sm font-medium transition-colors"
|
||||||
|
style={{ color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||||
|
>
|
||||||
|
Sign in
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : !token ? (
|
||||||
|
<div className="text-center space-y-4">
|
||||||
|
<p style={{ color: '#e57373' }}>Invalid reset link. Please request a new one.</p>
|
||||||
|
<Link
|
||||||
|
to="/login"
|
||||||
|
className="inline-block h-9 rounded-md border px-4 py-2 text-sm font-medium transition-colors"
|
||||||
|
style={{ color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||||
|
>
|
||||||
|
Back to sign in
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<h2 className="text-lg font-semibold text-center mb-4" style={{ color: '#d8dfe9' }}>Set new password</h2>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>New password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
minLength={12}
|
||||||
|
placeholder="At least 12 characters"
|
||||||
|
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium" style={{ color: '#b0bec5' }}>Confirm password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
className="h-9 w-full rounded-md border px-3 py-1 text-sm outline-none login-input"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error && (
|
||||||
|
<p className="text-sm" style={{ color: '#e57373' }}>{error}</p>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="h-9 w-full rounded-md border text-sm font-medium transition-colors disabled:opacity-50"
|
||||||
|
style={{ backgroundColor: 'transparent', color: '#d0d8e0', borderColor: '#3a4a62' }}
|
||||||
|
onMouseEnter={(e) => { (e.target as HTMLElement).style.backgroundColor = '#1e2d45' }}
|
||||||
|
onMouseLeave={(e) => { (e.target as HTMLElement).style.backgroundColor = 'transparent' }}
|
||||||
|
>
|
||||||
|
{loading ? 'Resetting...' : 'Reset password'}
|
||||||
|
</button>
|
||||||
|
<div className="text-center">
|
||||||
|
<Link to="/login" className="text-xs" style={{ color: '#6b7a8d' }}>
|
||||||
|
Back to sign in
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
14
packages/admin/src/routes/station.tsx
Normal file
14
packages/admin/src/routes/station.tsx
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import { StationShell } from '@/components/station/station-shell'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/station')({
|
||||||
|
component: StationPage,
|
||||||
|
})
|
||||||
|
|
||||||
|
function StationPage() {
|
||||||
|
return (
|
||||||
|
<div className="h-screen w-screen overflow-hidden bg-background text-foreground">
|
||||||
|
<StationShell />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
13
packages/admin/src/stores/station.store.ts
Normal file
13
packages/admin/src/stores/station.store.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { create } from 'zustand'
|
||||||
|
|
||||||
|
type StationTab = 'pos' | 'repairs' | 'lessons'
|
||||||
|
|
||||||
|
interface StationState {
|
||||||
|
activeTab: StationTab
|
||||||
|
setActiveTab: (tab: StationTab) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useStationStore = create<StationState>((set) => ({
|
||||||
|
activeTab: 'pos',
|
||||||
|
setActiveTab: (tab) => set({ activeTab: tab }),
|
||||||
|
}))
|
||||||
144
packages/backend/__tests__/utils/email-templates.test.ts
Normal file
144
packages/backend/__tests__/utils/email-templates.test.ts
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
import { describe, it, expect } from 'bun:test'
|
||||||
|
import {
|
||||||
|
renderReceiptEmailHtml,
|
||||||
|
renderReceiptEmailText,
|
||||||
|
renderEstimateEmailHtml,
|
||||||
|
renderEstimateEmailText,
|
||||||
|
} from '../../src/utils/email-templates.js'
|
||||||
|
|
||||||
|
const mockReceipt = {
|
||||||
|
transaction: {
|
||||||
|
transactionNumber: 'TXN-20260405-001',
|
||||||
|
subtotal: '100.00',
|
||||||
|
discountTotal: '10.00',
|
||||||
|
taxTotal: '7.43',
|
||||||
|
total: '97.43',
|
||||||
|
paymentMethod: 'cash',
|
||||||
|
amountTendered: '100.00',
|
||||||
|
changeGiven: '2.57',
|
||||||
|
roundingAdjustment: null,
|
||||||
|
completedAt: '2026-04-05T12:00:00Z',
|
||||||
|
lineItems: [
|
||||||
|
{ description: 'Guitar Strings', qty: 2, unitPrice: '12.99', taxAmount: '2.14', lineTotal: '25.98', discountAmount: null },
|
||||||
|
{ description: 'Tuner', qty: 1, unitPrice: '74.02', taxAmount: '5.29', lineTotal: '74.02', discountAmount: null },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
company: { name: 'Test Store', phone: '555-1234', email: 'store@test.com', address: { street: '123 Main St', city: 'Austin', state: 'TX', zip: '78701' } },
|
||||||
|
location: null,
|
||||||
|
}
|
||||||
|
|
||||||
|
const mockTicket = {
|
||||||
|
ticketNumber: 'RPR-001',
|
||||||
|
customerName: 'Jane Doe',
|
||||||
|
customerPhone: '555-5678',
|
||||||
|
itemDescription: 'Acoustic Guitar',
|
||||||
|
serialNumber: 'AG-12345',
|
||||||
|
problemDescription: 'Cracked neck joint',
|
||||||
|
estimatedCost: '250.00',
|
||||||
|
promisedDate: '2026-04-12',
|
||||||
|
status: 'pending_approval',
|
||||||
|
}
|
||||||
|
|
||||||
|
const mockLineItems = [
|
||||||
|
{ itemType: 'labor', description: 'Neck repair', qty: 1, unitPrice: '150.00', totalPrice: '150.00' },
|
||||||
|
{ itemType: 'part', description: 'Wood glue & clamps', qty: 1, unitPrice: '25.00', totalPrice: '25.00' },
|
||||||
|
{ itemType: 'flat_rate', description: 'Setup & restring', qty: 1, unitPrice: '75.00', totalPrice: '75.00' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const mockCompany = { name: 'Test Store', phone: '555-1234', email: 'store@test.com', address: null }
|
||||||
|
|
||||||
|
describe('renderReceiptEmailHtml', () => {
|
||||||
|
it('renders HTML with transaction details', () => {
|
||||||
|
const html = renderReceiptEmailHtml(mockReceipt as any)
|
||||||
|
expect(html).toContain('TXN-20260405-001')
|
||||||
|
expect(html).toContain('Test Store')
|
||||||
|
expect(html).toContain('Guitar Strings')
|
||||||
|
expect(html).toContain('Tuner')
|
||||||
|
expect(html).toContain('$97.43')
|
||||||
|
expect(html).toContain('$100.00')
|
||||||
|
expect(html).toContain('Powered by LunarFront')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('includes discount when present', () => {
|
||||||
|
const html = renderReceiptEmailHtml(mockReceipt as any)
|
||||||
|
expect(html).toContain('Discount')
|
||||||
|
expect(html).toContain('$10.00')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('includes payment details for cash', () => {
|
||||||
|
const html = renderReceiptEmailHtml(mockReceipt as any)
|
||||||
|
expect(html).toContain('Cash')
|
||||||
|
expect(html).toContain('$2.57')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('includes receipt config when provided', () => {
|
||||||
|
const config = { receipt_footer: 'Thank you!', receipt_return_policy: '30-day returns' }
|
||||||
|
const html = renderReceiptEmailHtml(mockReceipt as any, config)
|
||||||
|
expect(html).toContain('Thank you!')
|
||||||
|
expect(html).toContain('30-day returns')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('includes company address', () => {
|
||||||
|
const html = renderReceiptEmailHtml(mockReceipt as any)
|
||||||
|
expect(html).toContain('123 Main St')
|
||||||
|
expect(html).toContain('Austin')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('renderReceiptEmailText', () => {
|
||||||
|
it('renders plain text with transaction details', () => {
|
||||||
|
const text = renderReceiptEmailText(mockReceipt as any)
|
||||||
|
expect(text).toContain('TXN-20260405-001')
|
||||||
|
expect(text).toContain('Guitar Strings')
|
||||||
|
expect(text).toContain('Total: $97.43')
|
||||||
|
expect(text).toContain('Cash')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('renderEstimateEmailHtml', () => {
|
||||||
|
it('renders HTML with ticket details', () => {
|
||||||
|
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||||
|
expect(html).toContain('RPR-001')
|
||||||
|
expect(html).toContain('Jane Doe')
|
||||||
|
expect(html).toContain('Acoustic Guitar')
|
||||||
|
expect(html).toContain('AG-12345')
|
||||||
|
expect(html).toContain('Cracked neck joint')
|
||||||
|
expect(html).toContain('$250.00')
|
||||||
|
expect(html).toContain('Powered by LunarFront')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders line items with types', () => {
|
||||||
|
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||||
|
expect(html).toContain('Labor')
|
||||||
|
expect(html).toContain('Neck repair')
|
||||||
|
expect(html).toContain('Part')
|
||||||
|
expect(html).toContain('Flat Rate')
|
||||||
|
expect(html).toContain('Setup & restring')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('includes promised date', () => {
|
||||||
|
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||||
|
expect(html).toContain('Estimated completion')
|
||||||
|
expect(html).toContain('Apr')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('renders without line items using estimatedCost', () => {
|
||||||
|
const html = renderEstimateEmailHtml(mockTicket as any, [], mockCompany as any)
|
||||||
|
expect(html).toContain('$250.00')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('includes company phone', () => {
|
||||||
|
const html = renderEstimateEmailHtml(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||||
|
expect(html).toContain('555-1234')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('renderEstimateEmailText', () => {
|
||||||
|
it('renders plain text with ticket details', () => {
|
||||||
|
const text = renderEstimateEmailText(mockTicket as any, mockLineItems as any, mockCompany as any)
|
||||||
|
expect(text).toContain('RPR-001')
|
||||||
|
expect(text).toContain('Jane Doe')
|
||||||
|
expect(text).toContain('Neck repair')
|
||||||
|
expect(text).toContain('$250.00')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -114,6 +114,10 @@ async function setupDatabase() {
|
|||||||
await testSql`INSERT INTO module_config (slug, name, description, licensed, enabled) VALUES (${m.slug}, ${m.name}, ${m.description}, true, ${m.enabled}) ON CONFLICT (slug) DO NOTHING`
|
await testSql`INSERT INTO module_config (slug, name, description, licensed, enabled) VALUES (${m.slug}, ${m.name}, ${m.description}, true, ${m.enabled}) ON CONFLICT (slug) DO NOTHING`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Seed test email provider so email endpoints work without real provider
|
||||||
|
await testSql`INSERT INTO app_settings (key, value, is_encrypted) VALUES ('email.provider', 'test', false) ON CONFLICT (key) DO NOTHING`
|
||||||
|
await testSql`INSERT INTO app_settings (key, value, is_encrypted) VALUES ('email.from_address', 'Test Store <noreply@test.com>', false) ON CONFLICT (key) DO NOTHING`
|
||||||
|
|
||||||
await testSql.end()
|
await testSql.end()
|
||||||
console.log(' Database ready')
|
console.log(' Database ready')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1051,4 +1051,48 @@ suite('POS', { tags: ['pos'] }, (t) => {
|
|||||||
// Cleanup
|
// Cleanup
|
||||||
await t.api.post(`/v1/drawer/${drawer.data.id}/close`, { closingBalance: 100 })
|
await t.api.post(`/v1/drawer/${drawer.data.id}/close`, { closingBalance: 100 })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ─── Email Receipt ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('emails a receipt for a completed transaction', { tags: ['transactions', 'email'] }, async () => {
|
||||||
|
// Create and complete a transaction
|
||||||
|
const txn = await t.api.post('/v1/transactions', { transactionType: 'sale', locationId: LOCATION_ID })
|
||||||
|
await t.api.post(`/v1/transactions/${txn.data.id}/line-items`, { description: 'Email Test Item', qty: 1, unitPrice: 25 })
|
||||||
|
await t.api.post(`/v1/transactions/${txn.data.id}/complete`, { paymentMethod: 'card_present' })
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/transactions/${txn.data.id}/email-receipt`, { email: 'customer@test.com' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.equal(res.data.message, 'Receipt sent')
|
||||||
|
t.assert.equal(res.data.sentTo, 'customer@test.com')
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('rejects email receipt with invalid email', { tags: ['transactions', 'email', 'validation'] }, async () => {
|
||||||
|
const txn = await t.api.post('/v1/transactions', { transactionType: 'sale', locationId: LOCATION_ID })
|
||||||
|
await t.api.post(`/v1/transactions/${txn.data.id}/line-items`, { description: 'Bad Email Item', qty: 1, unitPrice: 10 })
|
||||||
|
await t.api.post(`/v1/transactions/${txn.data.id}/complete`, { paymentMethod: 'card_present' })
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/transactions/${txn.data.id}/email-receipt`, { email: 'not-an-email' })
|
||||||
|
t.assert.status(res, 400)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('rejects email receipt with missing body', { tags: ['transactions', 'email', 'validation'] }, async () => {
|
||||||
|
const txn = await t.api.post('/v1/transactions', { transactionType: 'sale', locationId: LOCATION_ID })
|
||||||
|
await t.api.post(`/v1/transactions/${txn.data.id}/line-items`, { description: 'No Body Item', qty: 1, unitPrice: 10 })
|
||||||
|
await t.api.post(`/v1/transactions/${txn.data.id}/complete`, { paymentMethod: 'card_present' })
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/transactions/${txn.data.id}/email-receipt`, {})
|
||||||
|
t.assert.status(res, 400)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('receipt response includes customerEmail', { tags: ['transactions', 'email'] }, async () => {
|
||||||
|
// Create account with email
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Email Customer', email: 'acct@test.com', billingMode: 'consolidated' })
|
||||||
|
const txn = await t.api.post('/v1/transactions', { transactionType: 'sale', locationId: LOCATION_ID, accountId: acct.data.id })
|
||||||
|
await t.api.post(`/v1/transactions/${txn.data.id}/line-items`, { description: 'Account Item', qty: 1, unitPrice: 50 })
|
||||||
|
await t.api.post(`/v1/transactions/${txn.data.id}/complete`, { paymentMethod: 'card_present' })
|
||||||
|
|
||||||
|
const receipt = await t.api.get(`/v1/transactions/${txn.data.id}/receipt`)
|
||||||
|
t.assert.status(receipt, 200)
|
||||||
|
t.assert.equal(receipt.data.customerEmail, 'acct@test.com')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -510,4 +510,55 @@ suite('Repairs', { tags: ['repairs'] }, (t) => {
|
|||||||
const fileRes = await fetch(`${t.baseUrl}${signedRes.data.url}`)
|
const fileRes = await fetch(`${t.baseUrl}${signedRes.data.url}`)
|
||||||
t.assert.equal(fileRes.status, 200)
|
t.assert.equal(fileRes.status, 200)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ─── Email Estimate ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('emails a repair estimate', { tags: ['tickets', 'email'] }, async () => {
|
||||||
|
const ticket = await t.api.post('/v1/repair-tickets', {
|
||||||
|
customerName: 'Email Estimate Customer',
|
||||||
|
itemDescription: 'Broken Laptop',
|
||||||
|
problemDescription: 'Won\'t power on',
|
||||||
|
conditionIn: 'poor',
|
||||||
|
estimatedCost: 200,
|
||||||
|
})
|
||||||
|
await t.api.post(`/v1/repair-tickets/${ticket.data.id}/line-items`, {
|
||||||
|
itemType: 'labor',
|
||||||
|
description: 'Diagnostic fee',
|
||||||
|
qty: 1,
|
||||||
|
unitPrice: 50,
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/email-estimate`, { email: 'customer@test.com' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.equal(res.data.message, 'Estimate sent')
|
||||||
|
t.assert.equal(res.data.sentTo, 'customer@test.com')
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('rejects estimate email with invalid email', { tags: ['tickets', 'email', 'validation'] }, async () => {
|
||||||
|
const ticket = await t.api.post('/v1/repair-tickets', {
|
||||||
|
customerName: 'Bad Email Customer',
|
||||||
|
problemDescription: 'Test',
|
||||||
|
conditionIn: 'good',
|
||||||
|
})
|
||||||
|
const res = await t.api.post(`/v1/repair-tickets/${ticket.data.id}/email-estimate`, { email: 'bad' })
|
||||||
|
t.assert.status(res, 400)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('returns 404 for estimate email on nonexistent ticket', { tags: ['tickets', 'email', 'validation'] }, async () => {
|
||||||
|
const res = await t.api.post('/v1/repair-tickets/00000000-0000-0000-0000-000000000000/email-estimate', { email: 'test@test.com' })
|
||||||
|
t.assert.status(res, 404)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('ticket detail includes customerEmail from account', { tags: ['tickets', 'email'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Repair Email Acct', email: 'repair@test.com', billingMode: 'consolidated' })
|
||||||
|
const ticket = await t.api.post('/v1/repair-tickets', {
|
||||||
|
customerName: 'Repair Email Acct',
|
||||||
|
accountId: acct.data.id,
|
||||||
|
problemDescription: 'Email test',
|
||||||
|
conditionIn: 'good',
|
||||||
|
})
|
||||||
|
const detail = await t.api.get(`/v1/repair-tickets/${ticket.data.id}`)
|
||||||
|
t.assert.status(detail, 200)
|
||||||
|
t.assert.equal(detail.data.customerEmail, 'repair@test.com')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
-- Auto-assign employee_number on user insert if not provided
|
||||||
|
CREATE OR REPLACE FUNCTION assign_employee_number()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
DECLARE next_num INT;
|
||||||
|
BEGIN
|
||||||
|
IF NEW.employee_number IS NULL OR NEW.employee_number = '' THEN
|
||||||
|
SELECT COALESCE(MAX(employee_number::int), 1000) + 1
|
||||||
|
INTO next_num
|
||||||
|
FROM "user"
|
||||||
|
WHERE employee_number ~ '^\d+$';
|
||||||
|
NEW.employee_number := next_num::text;
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS trg_assign_employee_number ON "user";
|
||||||
|
CREATE TRIGGER trg_assign_employee_number
|
||||||
|
BEFORE INSERT ON "user"
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION assign_employee_number();
|
||||||
|
|
||||||
|
-- Backfill any users missing an employee number
|
||||||
|
DO $$ DECLARE r RECORD; num INT;
|
||||||
|
BEGIN
|
||||||
|
SELECT COALESCE(MAX(employee_number::int), 1000) INTO num FROM "user" WHERE employee_number ~ '^\d+$';
|
||||||
|
FOR r IN (SELECT id FROM "user" WHERE employee_number IS NULL OR employee_number = '' ORDER BY created_at) LOOP
|
||||||
|
num := num + 1;
|
||||||
|
UPDATE "user" SET employee_number = num::text WHERE id = r.id;
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
@@ -323,6 +323,13 @@
|
|||||||
"when": 1775770000000,
|
"when": 1775770000000,
|
||||||
"tag": "0045_registers-reports",
|
"tag": "0045_registers-reports",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 46,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1775860000000,
|
||||||
|
"tag": "0046_auto-employee-number",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -37,23 +37,66 @@ import { RbacService } from './services/rbac.service.js'
|
|||||||
import { ModuleService } from './services/module.service.js'
|
import { ModuleService } from './services/module.service.js'
|
||||||
import { AppConfigService } from './services/config.service.js'
|
import { AppConfigService } from './services/config.service.js'
|
||||||
import { SettingsService } from './services/settings.service.js'
|
import { SettingsService } from './services/settings.service.js'
|
||||||
|
import { eq } from 'drizzle-orm'
|
||||||
import { users } from './db/schema/users.js'
|
import { users } from './db/schema/users.js'
|
||||||
import { companies } from './db/schema/stores.js'
|
import { companies } from './db/schema/stores.js'
|
||||||
|
import { roles, userRoles } from './db/schema/rbac.js'
|
||||||
|
import { EmailService } from './services/email.service.js'
|
||||||
import bcrypt from 'bcryptjs'
|
import bcrypt from 'bcryptjs'
|
||||||
|
|
||||||
async function seedInitialUser(app: Awaited<ReturnType<typeof buildApp>>) {
|
async function seedInitialUser(app: Awaited<ReturnType<typeof buildApp>>) {
|
||||||
const email = process.env.INITIAL_USER_EMAIL
|
const email = process.env.INITIAL_USER_EMAIL
|
||||||
const password = process.env.INITIAL_USER_PASSWORD
|
|
||||||
const firstName = process.env.INITIAL_USER_FIRST_NAME
|
const firstName = process.env.INITIAL_USER_FIRST_NAME
|
||||||
const lastName = process.env.INITIAL_USER_LAST_NAME
|
const lastName = process.env.INITIAL_USER_LAST_NAME
|
||||||
if (!email || !password || !firstName || !lastName) return
|
if (!email || !firstName || !lastName) return
|
||||||
|
|
||||||
const existing = await app.db.select({ id: users.id }).from(users).limit(1)
|
const existing = await app.db.select({ id: users.id }).from(users).limit(1)
|
||||||
if (existing.length > 0) return
|
if (existing.length > 0) return
|
||||||
|
|
||||||
const passwordHash = await bcrypt.hash(password, 10)
|
// Create user with a random password — they'll set their real one via the welcome email
|
||||||
await app.db.insert(users).values({ email, passwordHash, firstName, lastName, role: 'admin' })
|
const tempPassword = crypto.randomUUID()
|
||||||
|
const passwordHash = await bcrypt.hash(tempPassword, 10)
|
||||||
|
const [user] = await app.db.insert(users).values({ email, passwordHash, firstName, lastName, role: 'admin' }).returning({ id: users.id })
|
||||||
|
|
||||||
|
// Assign the Admin RBAC role
|
||||||
|
const [adminRole] = await app.db.select({ id: roles.id }).from(roles).where(eq(roles.name, 'Admin')).limit(1)
|
||||||
|
if (adminRole) {
|
||||||
|
await app.db.insert(userRoles).values({ userId: user.id, roleId: adminRole.id })
|
||||||
|
}
|
||||||
|
|
||||||
app.log.info({ email }, 'Initial admin user created')
|
app.log.info({ email }, 'Initial admin user created')
|
||||||
|
|
||||||
|
// Send welcome email with password setup link
|
||||||
|
try {
|
||||||
|
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '4h' })
|
||||||
|
const appUrl = process.env.APP_URL ?? `https://${process.env.HOSTNAME ?? 'localhost'}`
|
||||||
|
const resetLink = `${appUrl}/reset-password?token=${resetToken}`
|
||||||
|
|
||||||
|
const [store] = await app.db.select({ name: companies.name }).from(companies).limit(1)
|
||||||
|
const storeName = store?.name ?? process.env.BUSINESS_NAME ?? 'LunarFront'
|
||||||
|
|
||||||
|
await EmailService.send(app.db, {
|
||||||
|
to: email,
|
||||||
|
subject: `Welcome to ${storeName} — Set your password`,
|
||||||
|
html: `
|
||||||
|
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
|
||||||
|
<h2 style="color: #1a1a2e; margin-bottom: 8px;">${storeName}</h2>
|
||||||
|
<p style="color: #555; margin-bottom: 24px;">Hi ${firstName},</p>
|
||||||
|
<p style="color: #555;">Your account has been created. Click the button below to set your password and get started:</p>
|
||||||
|
<div style="text-align: center; margin: 32px 0;">
|
||||||
|
<a href="${resetLink}" style="background-color: #1a1a2e; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500;">Set Your Password</a>
|
||||||
|
</div>
|
||||||
|
<p style="color: #888; font-size: 13px;">This link expires in 4 hours. If it expires, you can request a new one from the login page.</p>
|
||||||
|
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
|
||||||
|
<p style="color: #aaa; font-size: 11px;">Powered by LunarFront</p>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
text: `Hi ${firstName}, welcome to ${storeName}! Set your password here: ${resetLink} — This link expires in 4 hours.`,
|
||||||
|
})
|
||||||
|
app.log.info({ email }, 'Welcome email sent to initial user')
|
||||||
|
} catch (err) {
|
||||||
|
app.log.error({ email, error: (err as Error).message }, 'Failed to send welcome email — user can use forgot password')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function seedEmailSettings(app: Awaited<ReturnType<typeof buildApp>>) {
|
async function seedEmailSettings(app: Awaited<ReturnType<typeof buildApp>>) {
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import type { FastifyPluginAsync } from 'fastify'
|
import type { FastifyPluginAsync } from 'fastify'
|
||||||
import { eq } from 'drizzle-orm'
|
import { eq } from 'drizzle-orm'
|
||||||
import bcrypt from 'bcryptjs'
|
import bcrypt from 'bcryptjs'
|
||||||
import { RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema } from '@lunarfront/shared/schemas'
|
import { RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema, ForgotPasswordSchema, ResetPasswordSchema } from '@lunarfront/shared/schemas'
|
||||||
import { users } from '../../db/schema/users.js'
|
import { users } from '../../db/schema/users.js'
|
||||||
|
import { companies } from '../../db/schema/stores.js'
|
||||||
|
import { EmailService } from '../../services/email.service.js'
|
||||||
|
|
||||||
const SALT_ROUNDS = 10
|
const SALT_ROUNDS = 10
|
||||||
|
|
||||||
@@ -151,24 +153,22 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
const [user] = await app.db.select({ id: users.id, email: users.email }).from(users).where(eq(users.id, userId)).limit(1)
|
const [user] = await app.db.select({ id: users.id, email: users.email }).from(users).where(eq(users.id, userId)).limit(1)
|
||||||
if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
|
if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
|
||||||
|
|
||||||
// Generate a signed reset token that expires in 1 hour
|
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '4h' })
|
||||||
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '1h' })
|
|
||||||
const resetLink = `${process.env.APP_URL ?? 'http://localhost:5173'}/reset-password?token=${resetToken}`
|
const resetLink = `${process.env.APP_URL ?? 'http://localhost:5173'}/reset-password?token=${resetToken}`
|
||||||
|
|
||||||
request.log.info({ userId, generatedBy: request.user.id }, 'Password reset link generated')
|
request.log.info({ userId, generatedBy: request.user.id }, 'Password reset link generated')
|
||||||
return reply.send({ resetLink, expiresIn: '1 hour' })
|
return reply.send({ resetLink, expiresIn: '4 hours' })
|
||||||
})
|
})
|
||||||
|
|
||||||
// Reset password with token
|
// Reset password with token
|
||||||
app.post('/auth/reset-password', async (request, reply) => {
|
app.post('/auth/reset-password', async (request, reply) => {
|
||||||
const { token, newPassword } = request.body as { token?: string; newPassword?: string }
|
const parsed = ResetPasswordSchema.safeParse(request.body)
|
||||||
if (!token || !newPassword) {
|
if (!parsed.success) {
|
||||||
return reply.status(400).send({ error: { message: 'token and newPassword are required', statusCode: 400 } })
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
}
|
|
||||||
if (newPassword.length < 12) {
|
|
||||||
return reply.status(400).send({ error: { message: 'Password must be at least 12 characters', statusCode: 400 } })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { token, newPassword } = parsed.data
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const payload = app.jwt.verify<{ userId: string; purpose: string }>(token)
|
const payload = app.jwt.verify<{ userId: string; purpose: string }>(token)
|
||||||
if (payload.purpose !== 'password-reset') {
|
if (payload.purpose !== 'password-reset') {
|
||||||
@@ -185,6 +185,86 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Forgot password / resend welcome — public, always returns success (no user enumeration)
|
||||||
|
// Pass ?type=welcome for welcome emails, defaults to reset
|
||||||
|
app.post('/auth/forgot-password', rateLimitConfig, async (request, reply) => {
|
||||||
|
const parsed = ForgotPasswordSchema.safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { email } = parsed.data
|
||||||
|
const isWelcome = (request.query as { type?: string }).type === 'welcome'
|
||||||
|
|
||||||
|
// Rate limit per email — max 3 emails per hour
|
||||||
|
const emailKey = `pwd-reset:${email.toLowerCase()}`
|
||||||
|
const count = await app.redis.incr(emailKey)
|
||||||
|
if (count === 1) await app.redis.expire(emailKey, 3600)
|
||||||
|
if (count > 3) {
|
||||||
|
return reply.send({ message: 'If an account exists with that email, you will receive an email.' })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Always return success — don't reveal whether the email exists
|
||||||
|
const [user] = await app.db.select({ id: users.id, firstName: users.firstName }).from(users).where(eq(users.email, email)).limit(1)
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
try {
|
||||||
|
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '4h' })
|
||||||
|
const appUrl = process.env.APP_URL ?? 'http://localhost:5173'
|
||||||
|
const resetLink = `${appUrl}/reset-password?token=${resetToken}`
|
||||||
|
|
||||||
|
const [store] = await app.db.select({ name: companies.name }).from(companies).limit(1)
|
||||||
|
const storeName = store?.name ?? 'LunarFront'
|
||||||
|
|
||||||
|
if (isWelcome) {
|
||||||
|
await EmailService.send(app.db, {
|
||||||
|
to: email,
|
||||||
|
subject: `Welcome to ${storeName} — Set your password`,
|
||||||
|
html: `
|
||||||
|
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
|
||||||
|
<h2 style="color: #1a1a2e; margin-bottom: 8px;">${storeName}</h2>
|
||||||
|
<p style="color: #555; margin-bottom: 24px;">Hi ${user.firstName},</p>
|
||||||
|
<p style="color: #555;">Your account has been created. Click the button below to set your password and get started:</p>
|
||||||
|
<div style="text-align: center; margin: 32px 0;">
|
||||||
|
<a href="${resetLink}" style="background-color: #1a1a2e; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500;">Set Your Password</a>
|
||||||
|
</div>
|
||||||
|
<p style="color: #888; font-size: 13px;">This link expires in 4 hours. If it expires, you can request a new one from the login page.</p>
|
||||||
|
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
|
||||||
|
<p style="color: #aaa; font-size: 11px;">Powered by LunarFront</p>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
text: `Hi ${user.firstName}, welcome to ${storeName}! Set your password here: ${resetLink} — This link expires in 4 hours.`,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
await EmailService.send(app.db, {
|
||||||
|
to: email,
|
||||||
|
subject: `Reset your password — ${storeName}`,
|
||||||
|
html: `
|
||||||
|
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
|
||||||
|
<h2 style="color: #1a1a2e; margin-bottom: 8px;">${storeName}</h2>
|
||||||
|
<p style="color: #555; margin-bottom: 24px;">Hi ${user.firstName},</p>
|
||||||
|
<p style="color: #555;">We received a request to reset your password. Click the button below to choose a new one:</p>
|
||||||
|
<div style="text-align: center; margin: 32px 0;">
|
||||||
|
<a href="${resetLink}" style="background-color: #1a1a2e; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 500;">Reset Password</a>
|
||||||
|
</div>
|
||||||
|
<p style="color: #888; font-size: 13px;">This link expires in 4 hours. If you didn't request this, you can safely ignore this email.</p>
|
||||||
|
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
|
||||||
|
<p style="color: #aaa; font-size: 11px;">Powered by LunarFront</p>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
text: `Hi ${user.firstName}, reset your password here: ${resetLink} — This link expires in 4 hours.`,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
request.log.info({ userId: user.id, type: isWelcome ? 'welcome' : 'reset' }, 'Password email sent')
|
||||||
|
} catch (err) {
|
||||||
|
request.log.error({ email, error: (err as Error).message }, 'Failed to send password email')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.send({ message: 'If an account exists with that email, you will receive a password reset link.' })
|
||||||
|
})
|
||||||
|
|
||||||
// Get current user profile
|
// Get current user profile
|
||||||
app.get('/auth/me', { preHandler: [app.authenticate] }, async (request, reply) => {
|
app.get('/auth/me', { preHandler: [app.authenticate] }, async (request, reply) => {
|
||||||
const [user] = await app.db
|
const [user] = await app.db
|
||||||
@@ -194,6 +274,8 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
firstName: users.firstName,
|
firstName: users.firstName,
|
||||||
lastName: users.lastName,
|
lastName: users.lastName,
|
||||||
role: users.role,
|
role: users.role,
|
||||||
|
employeeNumber: users.employeeNumber,
|
||||||
|
pinHash: users.pinHash,
|
||||||
createdAt: users.createdAt,
|
createdAt: users.createdAt,
|
||||||
})
|
})
|
||||||
.from(users)
|
.from(users)
|
||||||
@@ -201,7 +283,16 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
.limit(1)
|
.limit(1)
|
||||||
|
|
||||||
if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
|
if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
|
||||||
return reply.send(user)
|
return reply.send({
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
firstName: user.firstName,
|
||||||
|
lastName: user.lastName,
|
||||||
|
role: user.role,
|
||||||
|
employeeNumber: user.employeeNumber,
|
||||||
|
hasPin: !!user.pinHash,
|
||||||
|
createdAt: user.createdAt,
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
// Update current user profile
|
// Update current user profile
|
||||||
|
|||||||
@@ -13,7 +13,13 @@ import {
|
|||||||
RepairServiceTemplateCreateSchema,
|
RepairServiceTemplateCreateSchema,
|
||||||
RepairServiceTemplateUpdateSchema,
|
RepairServiceTemplateUpdateSchema,
|
||||||
} from '@lunarfront/shared/schemas'
|
} from '@lunarfront/shared/schemas'
|
||||||
|
import { eq } from 'drizzle-orm'
|
||||||
|
import { z } from 'zod'
|
||||||
import { RepairTicketService, RepairLineItemService, RepairBatchService, RepairNoteService, RepairServiceTemplateService } from '../../services/repair.service.js'
|
import { RepairTicketService, RepairLineItemService, RepairBatchService, RepairNoteService, RepairServiceTemplateService } from '../../services/repair.service.js'
|
||||||
|
import { accounts } from '../../db/schema/accounts.js'
|
||||||
|
import { companies } from '../../db/schema/stores.js'
|
||||||
|
import { EmailService } from '../../services/email.service.js'
|
||||||
|
import { renderEstimateEmailHtml, renderEstimateEmailText } from '../../utils/email-templates.js'
|
||||||
|
|
||||||
export const repairRoutes: FastifyPluginAsync = async (app) => {
|
export const repairRoutes: FastifyPluginAsync = async (app) => {
|
||||||
// --- Repair Tickets ---
|
// --- Repair Tickets ---
|
||||||
@@ -59,7 +65,14 @@ export const repairRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
const { id } = request.params as { id: string }
|
const { id } = request.params as { id: string }
|
||||||
const ticket = await RepairTicketService.getById(app.db, id)
|
const ticket = await RepairTicketService.getById(app.db, id)
|
||||||
if (!ticket) return reply.status(404).send({ error: { message: 'Repair ticket not found', statusCode: 404 } })
|
if (!ticket) return reply.status(404).send({ error: { message: 'Repair ticket not found', statusCode: 404 } })
|
||||||
return reply.send(ticket)
|
|
||||||
|
let customerEmail: string | null = null
|
||||||
|
if (ticket.accountId) {
|
||||||
|
const [acct] = await app.db.select({ email: accounts.email }).from(accounts).where(eq(accounts.id, ticket.accountId)).limit(1)
|
||||||
|
customerEmail = acct?.email ?? null
|
||||||
|
}
|
||||||
|
|
||||||
|
return reply.send({ ...ticket, customerEmail })
|
||||||
})
|
})
|
||||||
|
|
||||||
app.patch('/repair-tickets/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
|
app.patch('/repair-tickets/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.edit')] }, async (request, reply) => {
|
||||||
@@ -84,6 +97,42 @@ export const repairRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
return reply.send(ticket)
|
return reply.send(ticket)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
app.post('/repair-tickets/:id/email-estimate', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const parsed = z.object({ email: z.string().email() }).safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Valid email is required', statusCode: 400 } })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rate limit: max 5 emails per ticket per hour
|
||||||
|
const rateKey = `email-estimate:${id}`
|
||||||
|
const count = await app.redis.incr(rateKey)
|
||||||
|
if (count === 1) await app.redis.expire(rateKey, 3600)
|
||||||
|
if (count > 5) {
|
||||||
|
return reply.status(429).send({ error: { message: 'Too many emails for this estimate. Try again later.', statusCode: 429 } })
|
||||||
|
}
|
||||||
|
|
||||||
|
const ticket = await RepairTicketService.getById(app.db, id)
|
||||||
|
if (!ticket) return reply.status(404).send({ error: { message: 'Repair ticket not found', statusCode: 404 } })
|
||||||
|
|
||||||
|
const lineItemsResult = await RepairLineItemService.listByTicket(app.db, id, { page: 1, limit: 500 })
|
||||||
|
const [company] = await app.db.select().from(companies).limit(1)
|
||||||
|
if (!company) return reply.status(500).send({ error: { message: 'Store not configured', statusCode: 500 } })
|
||||||
|
|
||||||
|
const html = renderEstimateEmailHtml(ticket as any, lineItemsResult.data as any[], { name: company.name, phone: company.phone, email: company.email, address: company.address as any })
|
||||||
|
const text = renderEstimateEmailText(ticket as any, lineItemsResult.data as any[], { name: company.name, phone: company.phone, email: company.email, address: company.address as any })
|
||||||
|
|
||||||
|
await EmailService.send(app.db, {
|
||||||
|
to: parsed.data.email,
|
||||||
|
subject: `Repair Estimate — Ticket #${ticket.ticketNumber}`,
|
||||||
|
html,
|
||||||
|
text,
|
||||||
|
})
|
||||||
|
|
||||||
|
request.log.info({ ticketId: id, email: parsed.data.email, userId: request.user.id }, 'Estimate email sent')
|
||||||
|
return reply.send({ message: 'Estimate sent', sentTo: parsed.data.email })
|
||||||
|
})
|
||||||
|
|
||||||
app.delete('/repair-tickets/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.admin')] }, async (request, reply) => {
|
app.delete('/repair-tickets/:id', { preHandler: [app.authenticate, app.requirePermission('repairs.admin')] }, async (request, reply) => {
|
||||||
const { id } = request.params as { id: string }
|
const { id } = request.params as { id: string }
|
||||||
const ticket = await RepairTicketService.delete(app.db, id)
|
const ticket = await RepairTicketService.delete(app.db, id)
|
||||||
|
|||||||
@@ -7,7 +7,11 @@ import {
|
|||||||
ApplyDiscountSchema,
|
ApplyDiscountSchema,
|
||||||
CompleteTransactionSchema,
|
CompleteTransactionSchema,
|
||||||
} from '@lunarfront/shared/schemas'
|
} from '@lunarfront/shared/schemas'
|
||||||
|
import { inArray } from 'drizzle-orm'
|
||||||
import { TransactionService } from '../../services/transaction.service.js'
|
import { TransactionService } from '../../services/transaction.service.js'
|
||||||
|
import { appConfig } from '../../db/schema/stores.js'
|
||||||
|
import { EmailService } from '../../services/email.service.js'
|
||||||
|
import { renderReceiptEmailHtml, renderReceiptEmailText } from '../../utils/email-templates.js'
|
||||||
|
|
||||||
const FromRepairBodySchema = z.object({
|
const FromRepairBodySchema = z.object({
|
||||||
locationId: z.string().uuid().optional(),
|
locationId: z.string().uuid().optional(),
|
||||||
@@ -64,6 +68,45 @@ export const transactionRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
return reply.send(receipt)
|
return reply.send(receipt)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
app.post('/transactions/:id/email-receipt', { preHandler: [app.authenticate, app.requirePermission('pos.view')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const parsed = z.object({ email: z.string().email() }).safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Valid email is required', statusCode: 400 } })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rate limit: max 5 emails per transaction per hour
|
||||||
|
const rateKey = `email-receipt:${id}`
|
||||||
|
const count = await app.redis.incr(rateKey)
|
||||||
|
if (count === 1) await app.redis.expire(rateKey, 3600)
|
||||||
|
if (count > 5) {
|
||||||
|
return reply.status(429).send({ error: { message: 'Too many emails for this receipt. Try again later.', statusCode: 429 } })
|
||||||
|
}
|
||||||
|
|
||||||
|
const receipt = await TransactionService.getReceipt(app.db, id)
|
||||||
|
const storeName = receipt.company?.name ?? 'Store'
|
||||||
|
|
||||||
|
// Fetch receipt config
|
||||||
|
const configRows = await app.db.select({ key: appConfig.key, value: appConfig.value })
|
||||||
|
.from(appConfig)
|
||||||
|
.where(inArray(appConfig.key, ['receipt_header', 'receipt_footer', 'receipt_return_policy', 'receipt_social']))
|
||||||
|
const config: Record<string, string> = {}
|
||||||
|
for (const row of configRows) if (row.value) config[row.key] = row.value
|
||||||
|
|
||||||
|
const html = renderReceiptEmailHtml(receipt as any, config)
|
||||||
|
const text = renderReceiptEmailText(receipt as any, config)
|
||||||
|
|
||||||
|
await EmailService.send(app.db, {
|
||||||
|
to: parsed.data.email,
|
||||||
|
subject: `Your receipt from ${storeName} — ${receipt.transaction.transactionNumber}`,
|
||||||
|
html,
|
||||||
|
text,
|
||||||
|
})
|
||||||
|
|
||||||
|
request.log.info({ transactionId: id, email: parsed.data.email, userId: request.user.id }, 'Receipt email sent')
|
||||||
|
return reply.send({ message: 'Receipt sent', sentTo: parsed.data.email })
|
||||||
|
})
|
||||||
|
|
||||||
app.post('/transactions/:id/line-items', { preHandler: [app.authenticate, app.requirePermission('pos.edit')] }, async (request, reply) => {
|
app.post('/transactions/:id/line-items', { preHandler: [app.authenticate, app.requirePermission('pos.edit')] }, async (request, reply) => {
|
||||||
const { id } = request.params as { id: string }
|
const { id } = request.params as { id: string }
|
||||||
const parsed = TransactionLineItemCreateSchema.safeParse(request.body)
|
const parsed = TransactionLineItemCreateSchema.safeParse(request.body)
|
||||||
|
|||||||
51
packages/backend/src/scripts/reset-password.ts
Normal file
51
packages/backend/src/scripts/reset-password.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
#!/usr/bin/env bun
|
||||||
|
/**
|
||||||
|
* Force-reset a user's password from the command line.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* bun run packages/backend/src/scripts/reset-password.ts <email> <new-password>
|
||||||
|
*
|
||||||
|
* From a customer pod:
|
||||||
|
* kubectl exec -n customer-tvs deploy/customer-tvs-backend -- \
|
||||||
|
* bun run src/scripts/reset-password.ts user@example.com NewPassword123!
|
||||||
|
*/
|
||||||
|
import postgres from 'postgres'
|
||||||
|
import { drizzle } from 'drizzle-orm/postgres-js'
|
||||||
|
import { eq } from 'drizzle-orm'
|
||||||
|
import bcrypt from 'bcryptjs'
|
||||||
|
import { users } from '../db/schema/users.js'
|
||||||
|
|
||||||
|
const [email, newPassword] = process.argv.slice(2)
|
||||||
|
|
||||||
|
if (!email || !newPassword) {
|
||||||
|
console.error('Usage: bun run reset-password.ts <email> <new-password>')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newPassword.length < 12) {
|
||||||
|
console.error('Error: Password must be at least 12 characters')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const databaseUrl = process.env.DATABASE_URL
|
||||||
|
if (!databaseUrl) {
|
||||||
|
console.error('Error: DATABASE_URL is not set')
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const sql = postgres(databaseUrl)
|
||||||
|
const db = drizzle(sql)
|
||||||
|
|
||||||
|
const [user] = await db.select({ id: users.id, email: users.email }).from(users).where(eq(users.email, email)).limit(1)
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
console.error(`Error: No user found with email "${email}"`)
|
||||||
|
await sql.end()
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
const hash = await bcrypt.hash(newPassword, 10)
|
||||||
|
await db.update(users).set({ passwordHash: hash, updatedAt: new Date() }).where(eq(users.id, user.id))
|
||||||
|
|
||||||
|
console.log(`Password reset for ${email} (user ${user.id})`)
|
||||||
|
await sql.end()
|
||||||
@@ -87,6 +87,21 @@ class SmtpProvider implements EmailProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class TestProvider implements EmailProvider {
|
||||||
|
static lastEmail: SendOpts | null = null
|
||||||
|
static emails: SendOpts[] = []
|
||||||
|
|
||||||
|
async send(opts: SendOpts): Promise<void> {
|
||||||
|
TestProvider.lastEmail = opts
|
||||||
|
TestProvider.emails.push(opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
static reset() {
|
||||||
|
TestProvider.lastEmail = null
|
||||||
|
TestProvider.emails = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const EmailService = {
|
export const EmailService = {
|
||||||
async send(db: PostgresJsDatabase<any>, opts: SendOpts): Promise<void> {
|
async send(db: PostgresJsDatabase<any>, opts: SendOpts): Promise<void> {
|
||||||
const provider = await SettingsService.get(db, 'email.provider')
|
const provider = await SettingsService.get(db, 'email.provider')
|
||||||
@@ -99,8 +114,14 @@ export const EmailService = {
|
|||||||
return new SendGridProvider(db).send(opts)
|
return new SendGridProvider(db).send(opts)
|
||||||
case 'smtp':
|
case 'smtp':
|
||||||
return new SmtpProvider().send(opts)
|
return new SmtpProvider().send(opts)
|
||||||
|
case 'test':
|
||||||
|
return new TestProvider().send(opts)
|
||||||
default:
|
default:
|
||||||
throw new Error('Email provider not configured. Set email.provider in app_settings.')
|
throw new Error('Email provider not configured. Set email.provider in app_settings.')
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getTestEmails: () => TestProvider.emails,
|
||||||
|
getLastTestEmail: () => TestProvider.lastEmail,
|
||||||
|
resetTestEmails: () => TestProvider.reset(),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
import { products, inventoryUnits } from '../db/schema/inventory.js'
|
import { products, inventoryUnits } from '../db/schema/inventory.js'
|
||||||
import { repairTickets, repairLineItems } from '../db/schema/repairs.js'
|
import { repairTickets, repairLineItems } from '../db/schema/repairs.js'
|
||||||
import { companies, locations } from '../db/schema/stores.js'
|
import { companies, locations } from '../db/schema/stores.js'
|
||||||
|
import { accounts } from '../db/schema/accounts.js'
|
||||||
import { NotFoundError, ValidationError, ConflictError } from '../lib/errors.js'
|
import { NotFoundError, ValidationError, ConflictError } from '../lib/errors.js'
|
||||||
import { TaxService } from './tax.service.js'
|
import { TaxService } from './tax.service.js'
|
||||||
import type {
|
import type {
|
||||||
@@ -473,8 +474,16 @@ export const TransactionService = {
|
|||||||
location = loc ?? null
|
location = loc ?? null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Resolve customer email from linked account
|
||||||
|
let customerEmail: string | null = null
|
||||||
|
if (txn.accountId) {
|
||||||
|
const [acct] = await db.select({ email: accounts.email }).from(accounts).where(eq(accounts.id, txn.accountId)).limit(1)
|
||||||
|
customerEmail = acct?.email ?? null
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
transaction: txn,
|
transaction: txn,
|
||||||
|
customerEmail,
|
||||||
company: company
|
company: company
|
||||||
? {
|
? {
|
||||||
name: company.name,
|
name: company.name,
|
||||||
|
|||||||
319
packages/backend/src/utils/email-templates.ts
Normal file
319
packages/backend/src/utils/email-templates.ts
Normal file
@@ -0,0 +1,319 @@
|
|||||||
|
/**
|
||||||
|
* Server-side HTML email template renderers for receipts and repair estimates.
|
||||||
|
* Uses inline CSS for email-client compatibility.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface Address {
|
||||||
|
street?: string
|
||||||
|
city?: string
|
||||||
|
state?: string
|
||||||
|
zip?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CompanyInfo {
|
||||||
|
name: string
|
||||||
|
phone?: string | null
|
||||||
|
email?: string | null
|
||||||
|
address?: Address | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ReceiptLineItem {
|
||||||
|
description: string
|
||||||
|
qty: number
|
||||||
|
unitPrice: string
|
||||||
|
taxAmount: string
|
||||||
|
lineTotal: string
|
||||||
|
discountAmount?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ReceiptTransaction {
|
||||||
|
transactionNumber: string
|
||||||
|
subtotal: string
|
||||||
|
discountTotal: string
|
||||||
|
taxTotal: string
|
||||||
|
total: string
|
||||||
|
paymentMethod: string | null
|
||||||
|
amountTendered: string | null
|
||||||
|
changeGiven: string | null
|
||||||
|
roundingAdjustment: string | null
|
||||||
|
completedAt: string | null
|
||||||
|
lineItems: ReceiptLineItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ReceiptConfig {
|
||||||
|
receipt_header?: string
|
||||||
|
receipt_footer?: string
|
||||||
|
receipt_return_policy?: string
|
||||||
|
receipt_social?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ReceiptData {
|
||||||
|
transaction: ReceiptTransaction
|
||||||
|
company: CompanyInfo | null
|
||||||
|
location: CompanyInfo | null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RepairLineItem {
|
||||||
|
itemType: string
|
||||||
|
description: string
|
||||||
|
qty: number
|
||||||
|
unitPrice: string
|
||||||
|
totalPrice: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RepairTicket {
|
||||||
|
ticketNumber: string
|
||||||
|
customerName: string
|
||||||
|
customerPhone?: string | null
|
||||||
|
itemDescription?: string | null
|
||||||
|
serialNumber?: string | null
|
||||||
|
problemDescription?: string | null
|
||||||
|
estimatedCost?: string | null
|
||||||
|
promisedDate?: string | null
|
||||||
|
status: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Shared layout ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function wrapEmailLayout(storeName: string, bodyHtml: string): string {
|
||||||
|
return `
|
||||||
|
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px; color: #333;">
|
||||||
|
<h2 style="color: #1a1a2e; margin: 0 0 24px 0; font-size: 20px;">${esc(storeName)}</h2>
|
||||||
|
${bodyHtml}
|
||||||
|
<hr style="border: none; border-top: 1px solid #eee; margin: 32px 0;" />
|
||||||
|
<p style="color: #aaa; font-size: 11px; margin: 0;">Powered by LunarFront</p>
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
|
||||||
|
function esc(s: string): string {
|
||||||
|
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatAddress(addr?: Address | null): string {
|
||||||
|
if (!addr) return ''
|
||||||
|
const parts = [addr.street, [addr.city, addr.state].filter(Boolean).join(', '), addr.zip].filter(Boolean)
|
||||||
|
return parts.join('<br />')
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(dateStr: string | null): string {
|
||||||
|
if (!dateStr) return ''
|
||||||
|
const d = new Date(dateStr)
|
||||||
|
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' })
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateOnly(dateStr: string | null): string {
|
||||||
|
if (!dateStr) return ''
|
||||||
|
const d = new Date(dateStr)
|
||||||
|
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAYMENT_LABELS: Record<string, string> = {
|
||||||
|
cash: 'Cash',
|
||||||
|
card_present: 'Card',
|
||||||
|
card_keyed: 'Card (Keyed)',
|
||||||
|
check: 'Check',
|
||||||
|
store_credit: 'Store Credit',
|
||||||
|
other: 'Other',
|
||||||
|
}
|
||||||
|
|
||||||
|
const TYPE_LABELS: Record<string, string> = {
|
||||||
|
labor: 'Labor',
|
||||||
|
part: 'Part',
|
||||||
|
flat_rate: 'Flat Rate',
|
||||||
|
misc: 'Misc',
|
||||||
|
consumable: 'Consumable',
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Receipt email ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function renderReceiptEmailHtml(data: ReceiptData, config?: ReceiptConfig): string {
|
||||||
|
const txn = data.transaction
|
||||||
|
const storeName = data.company?.name ?? 'Store'
|
||||||
|
|
||||||
|
let companyBlock = ''
|
||||||
|
if (data.company) {
|
||||||
|
const addr = formatAddress(data.company.address)
|
||||||
|
companyBlock = `
|
||||||
|
<div style="font-size: 13px; color: #666; margin-bottom: 16px;">
|
||||||
|
${addr ? `<div>${addr}</div>` : ''}
|
||||||
|
${data.company.phone ? `<div>${esc(data.company.phone)}</div>` : ''}
|
||||||
|
</div>
|
||||||
|
`
|
||||||
|
}
|
||||||
|
|
||||||
|
const headerText = config?.receipt_header ? `<p style="font-size: 13px; color: #555; margin: 0 0 16px 0;">${esc(config.receipt_header)}</p>` : ''
|
||||||
|
|
||||||
|
const lineRows = txn.lineItems.map(item => `
|
||||||
|
<tr>
|
||||||
|
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px;">${esc(item.description)}</td>
|
||||||
|
<td style="padding: 6px 8px; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: center;">${item.qty}</td>
|
||||||
|
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: right;">$${item.unitPrice}</td>
|
||||||
|
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: right;">$${item.lineTotal}</td>
|
||||||
|
</tr>
|
||||||
|
`).join('')
|
||||||
|
|
||||||
|
const discountRow = parseFloat(txn.discountTotal) > 0
|
||||||
|
? `<tr><td style="padding: 4px 0; font-size: 13px;">Discount</td><td style="padding: 4px 0; font-size: 13px; text-align: right; color: #e57373;">-$${txn.discountTotal}</td></tr>`
|
||||||
|
: ''
|
||||||
|
|
||||||
|
const roundingRow = txn.roundingAdjustment && parseFloat(txn.roundingAdjustment) !== 0
|
||||||
|
? `<tr><td style="padding: 4px 0; font-size: 13px;">Rounding</td><td style="padding: 4px 0; font-size: 13px; text-align: right;">$${txn.roundingAdjustment}</td></tr>`
|
||||||
|
: ''
|
||||||
|
|
||||||
|
const paymentBlock = txn.paymentMethod ? `
|
||||||
|
<div style="margin-top: 16px; font-size: 13px; color: #666;">
|
||||||
|
<div>Paid by: ${PAYMENT_LABELS[txn.paymentMethod] ?? txn.paymentMethod}</div>
|
||||||
|
${txn.amountTendered && txn.paymentMethod === 'cash' ? `<div>Tendered: $${txn.amountTendered}</div>` : ''}
|
||||||
|
${txn.changeGiven && parseFloat(txn.changeGiven) > 0 ? `<div>Change: $${txn.changeGiven}</div>` : ''}
|
||||||
|
</div>
|
||||||
|
` : ''
|
||||||
|
|
||||||
|
const footerText = config?.receipt_footer ? `<p style="font-size: 12px; color: #888; margin: 16px 0 0 0; text-align: center;">${esc(config.receipt_footer)}</p>` : ''
|
||||||
|
const policyText = config?.receipt_return_policy ? `<p style="font-size: 11px; color: #999; margin: 8px 0 0 0; text-align: center;">${esc(config.receipt_return_policy)}</p>` : ''
|
||||||
|
const socialText = config?.receipt_social ? `<p style="font-size: 11px; color: #999; margin: 4px 0 0 0; text-align: center;">${esc(config.receipt_social)}</p>` : ''
|
||||||
|
|
||||||
|
const body = `
|
||||||
|
${companyBlock}
|
||||||
|
${headerText}
|
||||||
|
<div style="background: #f9f9f9; border-radius: 8px; padding: 16px; margin-bottom: 16px;">
|
||||||
|
<div style="font-size: 13px; color: #666;">
|
||||||
|
<strong style="color: #333;">Receipt #${esc(txn.transactionNumber)}</strong><br />
|
||||||
|
${formatDate(txn.completedAt)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<table style="width: 100%; border-collapse: collapse; margin-bottom: 16px;">
|
||||||
|
<thead>
|
||||||
|
<tr style="border-bottom: 2px solid #eee;">
|
||||||
|
<th style="padding: 6px 0; font-size: 12px; text-align: left; color: #888; font-weight: 600;">Item</th>
|
||||||
|
<th style="padding: 6px 8px; font-size: 12px; text-align: center; color: #888; font-weight: 600;">Qty</th>
|
||||||
|
<th style="padding: 6px 0; font-size: 12px; text-align: right; color: #888; font-weight: 600;">Price</th>
|
||||||
|
<th style="padding: 6px 0; font-size: 12px; text-align: right; color: #888; font-weight: 600;">Total</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
${lineRows}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<table style="width: 50%; margin-left: auto; border-collapse: collapse;">
|
||||||
|
<tr><td style="padding: 4px 0; font-size: 13px;">Subtotal</td><td style="padding: 4px 0; font-size: 13px; text-align: right;">$${txn.subtotal}</td></tr>
|
||||||
|
${discountRow}
|
||||||
|
<tr><td style="padding: 4px 0; font-size: 13px;">Tax</td><td style="padding: 4px 0; font-size: 13px; text-align: right;">$${txn.taxTotal}</td></tr>
|
||||||
|
${roundingRow}
|
||||||
|
<tr style="border-top: 2px solid #333;"><td style="padding: 8px 0; font-size: 15px; font-weight: 700;">Total</td><td style="padding: 8px 0; font-size: 15px; font-weight: 700; text-align: right;">$${txn.total}</td></tr>
|
||||||
|
</table>
|
||||||
|
${paymentBlock}
|
||||||
|
${footerText}
|
||||||
|
${policyText}
|
||||||
|
${socialText}
|
||||||
|
`
|
||||||
|
|
||||||
|
return wrapEmailLayout(storeName, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderReceiptEmailText(data: ReceiptData, config?: ReceiptConfig): string {
|
||||||
|
const txn = data.transaction
|
||||||
|
const storeName = data.company?.name ?? 'Store'
|
||||||
|
const lines = [
|
||||||
|
storeName,
|
||||||
|
`Receipt #${txn.transactionNumber}`,
|
||||||
|
formatDate(txn.completedAt),
|
||||||
|
'',
|
||||||
|
...txn.lineItems.map(i => `${i.description} x${i.qty} — $${i.lineTotal}`),
|
||||||
|
'',
|
||||||
|
`Subtotal: $${txn.subtotal}`,
|
||||||
|
...(parseFloat(txn.discountTotal) > 0 ? [`Discount: -$${txn.discountTotal}`] : []),
|
||||||
|
`Tax: $${txn.taxTotal}`,
|
||||||
|
`Total: $${txn.total}`,
|
||||||
|
'',
|
||||||
|
...(txn.paymentMethod ? [`Paid by: ${PAYMENT_LABELS[txn.paymentMethod] ?? txn.paymentMethod}`] : []),
|
||||||
|
...(config?.receipt_footer ? ['', config.receipt_footer] : []),
|
||||||
|
]
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Repair estimate email ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function renderEstimateEmailHtml(ticket: RepairTicket, lineItems: RepairLineItem[], company: CompanyInfo): string {
|
||||||
|
const storeName = company.name
|
||||||
|
|
||||||
|
const lineRows = lineItems.map(item => `
|
||||||
|
<tr>
|
||||||
|
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px;">${TYPE_LABELS[item.itemType] ?? item.itemType}</td>
|
||||||
|
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px;">${esc(item.description)}</td>
|
||||||
|
<td style="padding: 6px 8px; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: center;">${item.qty}</td>
|
||||||
|
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: right;">$${item.unitPrice}</td>
|
||||||
|
<td style="padding: 6px 0; border-bottom: 1px solid #f0f0f0; font-size: 13px; text-align: right;">$${item.totalPrice}</td>
|
||||||
|
</tr>
|
||||||
|
`).join('')
|
||||||
|
|
||||||
|
const estimatedTotal = ticket.estimatedCost
|
||||||
|
? `<tr style="border-top: 2px solid #333;"><td colspan="4" style="padding: 8px 0; font-size: 15px; font-weight: 700;">Estimated Total</td><td style="padding: 8px 0; font-size: 15px; font-weight: 700; text-align: right;">$${ticket.estimatedCost}</td></tr>`
|
||||||
|
: ''
|
||||||
|
|
||||||
|
const lineItemTotal = lineItems.reduce((sum, i) => sum + parseFloat(i.totalPrice), 0).toFixed(2)
|
||||||
|
const lineItemTotalRow = !ticket.estimatedCost && lineItems.length > 0
|
||||||
|
? `<tr style="border-top: 2px solid #333;"><td colspan="4" style="padding: 8px 0; font-size: 15px; font-weight: 700;">Estimated Total</td><td style="padding: 8px 0; font-size: 15px; font-weight: 700; text-align: right;">$${lineItemTotal}</td></tr>`
|
||||||
|
: ''
|
||||||
|
|
||||||
|
const body = `
|
||||||
|
<div style="background: #f9f9f9; border-radius: 8px; padding: 16px; margin-bottom: 16px;">
|
||||||
|
<div style="font-size: 13px; color: #666;">
|
||||||
|
<strong style="color: #333;">Repair Estimate — Ticket #${esc(ticket.ticketNumber)}</strong><br />
|
||||||
|
${esc(ticket.customerName)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-bottom: 16px; font-size: 13px; color: #555;">
|
||||||
|
${ticket.itemDescription ? `<div><strong>Item:</strong> ${esc(ticket.itemDescription)}${ticket.serialNumber ? ` (S/N: ${esc(ticket.serialNumber)})` : ''}</div>` : ''}
|
||||||
|
${ticket.problemDescription ? `<div style="margin-top: 4px;"><strong>Issue:</strong> ${esc(ticket.problemDescription)}</div>` : ''}
|
||||||
|
${ticket.promisedDate ? `<div style="margin-top: 4px;"><strong>Estimated completion:</strong> ${formatDateOnly(ticket.promisedDate)}</div>` : ''}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
${lineItems.length > 0 ? `
|
||||||
|
<table style="width: 100%; border-collapse: collapse; margin-bottom: 16px;">
|
||||||
|
<thead>
|
||||||
|
<tr style="border-bottom: 2px solid #eee;">
|
||||||
|
<th style="padding: 6px 0; font-size: 12px; text-align: left; color: #888; font-weight: 600;">Type</th>
|
||||||
|
<th style="padding: 6px 0; font-size: 12px; text-align: left; color: #888; font-weight: 600;">Description</th>
|
||||||
|
<th style="padding: 6px 8px; font-size: 12px; text-align: center; color: #888; font-weight: 600;">Qty</th>
|
||||||
|
<th style="padding: 6px 0; font-size: 12px; text-align: right; color: #888; font-weight: 600;">Price</th>
|
||||||
|
<th style="padding: 6px 0; font-size: 12px; text-align: right; color: #888; font-weight: 600;">Total</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
${lineRows}
|
||||||
|
${estimatedTotal}
|
||||||
|
${lineItemTotalRow}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
` : `
|
||||||
|
${ticket.estimatedCost ? `<div style="font-size: 15px; font-weight: 700; margin-bottom: 16px;">Estimated Cost: $${ticket.estimatedCost}</div>` : ''}
|
||||||
|
`}
|
||||||
|
|
||||||
|
<p style="font-size: 12px; color: #888;">This is an estimate and the final cost may vary. Please contact us with any questions.</p>
|
||||||
|
${company.phone ? `<p style="font-size: 12px; color: #888; margin-top: 4px;">Phone: ${esc(company.phone)}</p>` : ''}
|
||||||
|
`
|
||||||
|
|
||||||
|
return wrapEmailLayout(storeName, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function renderEstimateEmailText(ticket: RepairTicket, lineItems: RepairLineItem[], company: CompanyInfo): string {
|
||||||
|
const lines = [
|
||||||
|
company.name,
|
||||||
|
`Repair Estimate — Ticket #${ticket.ticketNumber}`,
|
||||||
|
`Customer: ${ticket.customerName}`,
|
||||||
|
'',
|
||||||
|
...(ticket.itemDescription ? [`Item: ${ticket.itemDescription}${ticket.serialNumber ? ` (S/N: ${ticket.serialNumber})` : ''}`] : []),
|
||||||
|
...(ticket.problemDescription ? [`Issue: ${ticket.problemDescription}`] : []),
|
||||||
|
...(ticket.promisedDate ? [`Estimated completion: ${formatDateOnly(ticket.promisedDate)}`] : []),
|
||||||
|
'',
|
||||||
|
...lineItems.map(i => `${TYPE_LABELS[i.itemType] ?? i.itemType}: ${i.description} x${i.qty} — $${i.totalPrice}`),
|
||||||
|
'',
|
||||||
|
...(ticket.estimatedCost ? [`Estimated Total: $${ticket.estimatedCost}`] : []),
|
||||||
|
'',
|
||||||
|
'This is an estimate and the final cost may vary.',
|
||||||
|
...(company.phone ? [`Phone: ${company.phone}`] : []),
|
||||||
|
]
|
||||||
|
return lines.join('\n')
|
||||||
|
}
|
||||||
@@ -27,3 +27,14 @@ export const SetPinSchema = z.object({
|
|||||||
pin: z.string().min(4).max(6).regex(/^\d+$/, 'PIN must be digits only'),
|
pin: z.string().min(4).max(6).regex(/^\d+$/, 'PIN must be digits only'),
|
||||||
})
|
})
|
||||||
export type SetPinInput = z.infer<typeof SetPinSchema>
|
export type SetPinInput = z.infer<typeof SetPinSchema>
|
||||||
|
|
||||||
|
export const ForgotPasswordSchema = z.object({
|
||||||
|
email: z.string().email(),
|
||||||
|
})
|
||||||
|
export type ForgotPasswordInput = z.infer<typeof ForgotPasswordSchema>
|
||||||
|
|
||||||
|
export const ResetPasswordSchema = z.object({
|
||||||
|
token: z.string().min(1),
|
||||||
|
newPassword: z.string().min(12, 'Password must be at least 12 characters').max(128),
|
||||||
|
})
|
||||||
|
export type ResetPasswordInput = z.infer<typeof ResetPasswordSchema>
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
export { PaginationSchema } from './pagination.schema.js'
|
export { PaginationSchema } from './pagination.schema.js'
|
||||||
export type { PaginationInput, PaginatedResponse } from './pagination.schema.js'
|
export type { PaginationInput, PaginatedResponse } from './pagination.schema.js'
|
||||||
|
|
||||||
export { UserRole, RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema } from './auth.schema.js'
|
export { UserRole, RegisterSchema, LoginSchema, PinLoginSchema, SetPinSchema, ForgotPasswordSchema, ResetPasswordSchema } from './auth.schema.js'
|
||||||
export type { RegisterInput, LoginInput, PinLoginInput, SetPinInput } from './auth.schema.js'
|
export type { RegisterInput, LoginInput, PinLoginInput, SetPinInput, ForgotPasswordInput, ResetPasswordInput } from './auth.schema.js'
|
||||||
|
|
||||||
export {
|
export {
|
||||||
BillingMode,
|
BillingMode,
|
||||||
|
|||||||
Reference in New Issue
Block a user