Compare commits
7 Commits
feature/em
...
feature/ac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4738f4a3f | ||
|
|
b9798f2c8c | ||
| 5f4a12b9c4 | |||
|
|
3b0daeae0c | ||
|
|
0411df57eb | ||
|
|
082e388799 | ||
| abe75fb1fd |
@@ -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}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
// 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 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'
|
||||||
@@ -59,6 +60,11 @@ 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({
|
const ResetPasswordRoute = ResetPasswordRouteImport.update({
|
||||||
id: '/reset-password',
|
id: '/reset-password',
|
||||||
path: '/reset-password',
|
path: '/reset-password',
|
||||||
@@ -344,6 +350,7 @@ export interface FileRoutesByFullPath {
|
|||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/pos': typeof PosRoute
|
'/pos': typeof PosRoute
|
||||||
'/reset-password': typeof ResetPasswordRoute
|
'/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
|
||||||
@@ -393,6 +400,7 @@ export interface FileRoutesByTo {
|
|||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/pos': typeof PosRoute
|
'/pos': typeof PosRoute
|
||||||
'/reset-password': typeof ResetPasswordRoute
|
'/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
|
||||||
@@ -444,6 +452,7 @@ export interface FileRoutesById {
|
|||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
'/pos': typeof PosRoute
|
'/pos': typeof PosRoute
|
||||||
'/reset-password': typeof ResetPasswordRoute
|
'/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
|
||||||
@@ -497,6 +506,7 @@ export interface FileRouteTypes {
|
|||||||
| '/login'
|
| '/login'
|
||||||
| '/pos'
|
| '/pos'
|
||||||
| '/reset-password'
|
| '/reset-password'
|
||||||
|
| '/station'
|
||||||
| '/help'
|
| '/help'
|
||||||
| '/profile'
|
| '/profile'
|
||||||
| '/settings'
|
| '/settings'
|
||||||
@@ -546,6 +556,7 @@ export interface FileRouteTypes {
|
|||||||
| '/login'
|
| '/login'
|
||||||
| '/pos'
|
| '/pos'
|
||||||
| '/reset-password'
|
| '/reset-password'
|
||||||
|
| '/station'
|
||||||
| '/help'
|
| '/help'
|
||||||
| '/profile'
|
| '/profile'
|
||||||
| '/settings'
|
| '/settings'
|
||||||
@@ -596,6 +607,7 @@ export interface FileRouteTypes {
|
|||||||
| '/login'
|
| '/login'
|
||||||
| '/pos'
|
| '/pos'
|
||||||
| '/reset-password'
|
| '/reset-password'
|
||||||
|
| '/station'
|
||||||
| '/_authenticated/help'
|
| '/_authenticated/help'
|
||||||
| '/_authenticated/profile'
|
| '/_authenticated/profile'
|
||||||
| '/_authenticated/settings'
|
| '/_authenticated/settings'
|
||||||
@@ -648,10 +660,18 @@ export interface RootRouteChildren {
|
|||||||
LoginRoute: typeof LoginRoute
|
LoginRoute: typeof LoginRoute
|
||||||
PosRoute: typeof PosRoute
|
PosRoute: typeof PosRoute
|
||||||
ResetPasswordRoute: typeof ResetPasswordRoute
|
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': {
|
'/reset-password': {
|
||||||
id: '/reset-password'
|
id: '/reset-password'
|
||||||
path: '/reset-password'
|
path: '/reset-password'
|
||||||
@@ -1133,6 +1153,7 @@ const rootRouteChildren: RootRouteChildren = {
|
|||||||
LoginRoute: LoginRoute,
|
LoginRoute: LoginRoute,
|
||||||
PosRoute: PosRoute,
|
PosRoute: PosRoute,
|
||||||
ResetPasswordRoute: ResetPasswordRoute,
|
ResetPasswordRoute: ResetPasswordRoute,
|
||||||
|
StationRoute: StationRoute,
|
||||||
}
|
}
|
||||||
export const routeTree = rootRouteImport
|
export const routeTree = rootRouteImport
|
||||||
._addFileChildren(rootRouteChildren)
|
._addFileChildren(rootRouteChildren)
|
||||||
|
|||||||
@@ -239,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}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -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>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|||||||
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 }),
|
||||||
|
}))
|
||||||
202
packages/backend/api-tests/suites/accounting.ts
Normal file
202
packages/backend/api-tests/suites/accounting.ts
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
import { suite } from '../lib/context.js'
|
||||||
|
|
||||||
|
suite('Accounting', { tags: ['accounting'] }, (t) => {
|
||||||
|
// ─── Invoices: CRUD ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('creates a manual invoice', { tags: ['invoices', 'create'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Invoice Test Acct', billingMode: 'consolidated' })
|
||||||
|
const res = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [
|
||||||
|
{ description: 'Service A', qty: 2, unitPrice: 50, taxRate: 0.0825 },
|
||||||
|
{ description: 'Service B', qty: 1, unitPrice: 100 },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
t.assert.status(res, 201)
|
||||||
|
t.assert.ok(res.data.invoiceNumber)
|
||||||
|
t.assert.equal(res.data.status, 'draft')
|
||||||
|
t.assert.ok(parseFloat(res.data.total) > 0)
|
||||||
|
t.assert.equal(res.data.balance, res.data.total)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('rejects invoice without line items', { tags: ['invoices', 'validation'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Empty Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const res = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [],
|
||||||
|
})
|
||||||
|
t.assert.status(res, 400)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('lists invoices with pagination', { tags: ['invoices', 'list'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/invoices', { page: 1, limit: 25 })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.data)
|
||||||
|
t.assert.ok(res.data.pagination)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('gets invoice detail with line items', { tags: ['invoices', 'detail'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Detail Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Widget', qty: 3, unitPrice: 25 }],
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await t.api.get(`/v1/invoices/${inv.data.id}`)
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.lineItems)
|
||||||
|
t.assert.equal(res.data.lineItems.length, 1)
|
||||||
|
t.assert.ok(res.data.payments)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('returns 404 for missing invoice', { tags: ['invoices', 'detail'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/invoices/00000000-0000-0000-0000-000000000000')
|
||||||
|
t.assert.status(res, 404)
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── Invoice Workflow ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('sends a draft invoice', { tags: ['invoices', 'workflow'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Send Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Send Test', qty: 1, unitPrice: 100 }],
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.equal(res.data.status, 'sent')
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('applies payment to invoice', { tags: ['invoices', 'payment'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Payment Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Pay Test', qty: 1, unitPrice: 200 }],
|
||||||
|
})
|
||||||
|
await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
|
||||||
|
// Partial payment
|
||||||
|
const res1 = await t.api.post(`/v1/invoices/${inv.data.id}/apply-payment`, { amount: 100 })
|
||||||
|
t.assert.status(res1, 200)
|
||||||
|
t.assert.ok(res1.data.id)
|
||||||
|
|
||||||
|
// Check invoice updated
|
||||||
|
const detail = await t.api.get(`/v1/invoices/${inv.data.id}`)
|
||||||
|
t.assert.equal(detail.data.status, 'partial')
|
||||||
|
t.assert.equal(detail.data.amountPaid, '100.00')
|
||||||
|
t.assert.equal(detail.data.balance, '100.00')
|
||||||
|
|
||||||
|
// Full payment
|
||||||
|
const res2 = await t.api.post(`/v1/invoices/${inv.data.id}/apply-payment`, { amount: 100 })
|
||||||
|
t.assert.status(res2, 200)
|
||||||
|
|
||||||
|
const final = await t.api.get(`/v1/invoices/${inv.data.id}`)
|
||||||
|
t.assert.equal(final.data.status, 'paid')
|
||||||
|
t.assert.equal(final.data.balance, '0.00')
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('rejects overpayment', { tags: ['invoices', 'payment', 'validation'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Overpay Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Small Item', qty: 1, unitPrice: 50 }],
|
||||||
|
})
|
||||||
|
await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/invoices/${inv.data.id}/apply-payment`, { amount: 100 })
|
||||||
|
t.assert.status(res, 400)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('voids an invoice', { tags: ['invoices', 'void'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Void Invoice Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Void Test', qty: 1, unitPrice: 75 }],
|
||||||
|
})
|
||||||
|
await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/invoices/${inv.data.id}/void`, { reason: 'Customer changed mind' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.equal(res.data.status, 'void')
|
||||||
|
t.assert.equal(res.data.balance, '0')
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('writes off a bad debt', { tags: ['invoices', 'write-off'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'WriteOff Acct', billingMode: 'consolidated' })
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Bad Debt Item', qty: 1, unitPrice: 300 }],
|
||||||
|
})
|
||||||
|
await t.api.post(`/v1/invoices/${inv.data.id}/send`)
|
||||||
|
|
||||||
|
const res = await t.api.post(`/v1/invoices/${inv.data.id}/write-off`, { reason: 'Uncollectable' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.equal(res.data.status, 'written_off')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── Account Balance ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('tracks account balance on invoice send', { tags: ['balance'] }, async () => {
|
||||||
|
const acct = await t.api.post('/v1/accounts', { name: 'Balance Track Acct', billingMode: 'consolidated' })
|
||||||
|
|
||||||
|
// Create and send invoice (which triggers AR balance update via service)
|
||||||
|
const inv = await t.api.post('/v1/invoices', {
|
||||||
|
accountId: acct.data.id,
|
||||||
|
issueDate: '2026-04-06',
|
||||||
|
dueDate: '2026-05-06',
|
||||||
|
lineItems: [{ description: 'Balance Test', qty: 1, unitPrice: 150 }],
|
||||||
|
})
|
||||||
|
|
||||||
|
const balRes = await t.api.get(`/v1/accounts/${acct.data.id}/balance`)
|
||||||
|
t.assert.status(balRes, 200)
|
||||||
|
t.assert.ok(balRes.data.accountId)
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── CSV Export ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('exports invoices as CSV', { tags: ['export'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/invoices/export')
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
// CSV response should have headers
|
||||||
|
const text = typeof res.data === 'string' ? res.data : JSON.stringify(res.data)
|
||||||
|
t.assert.contains(text, 'Invoice Number')
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── AR Aging ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('returns AR aging report', { tags: ['reports'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/invoices/aging')
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.current !== undefined)
|
||||||
|
t.assert.ok(res.data.days30 !== undefined)
|
||||||
|
t.assert.ok(res.data.days60 !== undefined)
|
||||||
|
t.assert.ok(res.data.days90plus !== undefined)
|
||||||
|
t.assert.ok(res.data.total !== undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
// ─── Outstanding Accounts ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
t.test('lists outstanding accounts', { tags: ['balance'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/accounts/outstanding', { page: 1, limit: 25 })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.data)
|
||||||
|
t.assert.ok(res.data.pagination)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -4,3 +4,4 @@ export * from './schema/accounts.js'
|
|||||||
export * from './schema/inventory.js'
|
export * from './schema/inventory.js'
|
||||||
export * from './schema/pos.js'
|
export * from './schema/pos.js'
|
||||||
export * from './schema/settings.js'
|
export * from './schema/settings.js'
|
||||||
|
export * from './schema/accounting.js'
|
||||||
|
|||||||
189
packages/backend/src/db/migrations/0047_accounting.sql
Normal file
189
packages/backend/src/db/migrations/0047_accounting.sql
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
-- Accounting module tables
|
||||||
|
|
||||||
|
-- Enums
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE invoice_status AS ENUM ('draft','sent','paid','partial','overdue','void','written_off');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE account_type AS ENUM ('asset','liability','revenue','contra_revenue','cogs','expense');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE normal_balance AS ENUM ('debit','credit');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE journal_line_type AS ENUM ('debit','credit');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE billing_run_status AS ENUM ('pending','running','completed','failed');
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
|
||||||
|
|
||||||
|
-- Core: Invoice
|
||||||
|
CREATE TABLE IF NOT EXISTS "invoice" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"invoice_number" varchar(50) UNIQUE NOT NULL,
|
||||||
|
"account_id" uuid NOT NULL REFERENCES "account"("id"),
|
||||||
|
"location_id" uuid REFERENCES "location"("id"),
|
||||||
|
"status" invoice_status NOT NULL DEFAULT 'draft',
|
||||||
|
"issue_date" date NOT NULL DEFAULT CURRENT_DATE,
|
||||||
|
"due_date" date NOT NULL DEFAULT CURRENT_DATE,
|
||||||
|
"source_type" varchar(50),
|
||||||
|
"source_id" uuid,
|
||||||
|
"subtotal" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"discount_total" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"tax_total" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"total" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"amount_paid" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"balance" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"refund_of_invoice_id" uuid REFERENCES "invoice"("id"),
|
||||||
|
"notes" text,
|
||||||
|
"created_by" uuid REFERENCES "user"("id"),
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"updated_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "invoice_account_id" ON "invoice" ("account_id");
|
||||||
|
CREATE INDEX IF NOT EXISTS "invoice_status" ON "invoice" ("status");
|
||||||
|
CREATE INDEX IF NOT EXISTS "invoice_source" ON "invoice" ("source_type", "source_id");
|
||||||
|
|
||||||
|
-- Core: Invoice Line Item
|
||||||
|
CREATE TABLE IF NOT EXISTS "invoice_line_item" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"invoice_id" uuid NOT NULL REFERENCES "invoice"("id") ON DELETE CASCADE,
|
||||||
|
"description" varchar(255) NOT NULL,
|
||||||
|
"qty" integer NOT NULL DEFAULT 1,
|
||||||
|
"unit_price" numeric(10,2) NOT NULL,
|
||||||
|
"discount_amount" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"tax_rate" numeric(5,4) NOT NULL DEFAULT 0,
|
||||||
|
"tax_amount" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"line_total" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"account_code_id" uuid,
|
||||||
|
"source_type" varchar(50),
|
||||||
|
"source_id" uuid,
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "invoice_line_item_invoice_id" ON "invoice_line_item" ("invoice_id");
|
||||||
|
|
||||||
|
-- Core: Payment Application
|
||||||
|
CREATE TABLE IF NOT EXISTS "payment_application" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"invoice_id" uuid NOT NULL REFERENCES "invoice"("id"),
|
||||||
|
"transaction_id" uuid REFERENCES "transaction"("id"),
|
||||||
|
"amount" numeric(10,2) NOT NULL,
|
||||||
|
"applied_at" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"applied_by" uuid NOT NULL REFERENCES "user"("id"),
|
||||||
|
"notes" text,
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "payment_application_invoice_id" ON "payment_application" ("invoice_id");
|
||||||
|
|
||||||
|
-- Core: Account Balance (materialized AR)
|
||||||
|
CREATE TABLE IF NOT EXISTS "account_balance" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"account_id" uuid NOT NULL UNIQUE REFERENCES "account"("id"),
|
||||||
|
"current_balance" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"last_invoice_date" date,
|
||||||
|
"last_payment_date" date,
|
||||||
|
"updated_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Accounting module: Chart of Accounts
|
||||||
|
CREATE TABLE IF NOT EXISTS "account_code" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"code" varchar(10) UNIQUE NOT NULL,
|
||||||
|
"name" varchar(255) NOT NULL,
|
||||||
|
"account_type" account_type NOT NULL,
|
||||||
|
"normal_balance" normal_balance NOT NULL,
|
||||||
|
"is_system" boolean NOT NULL DEFAULT true,
|
||||||
|
"is_active" boolean NOT NULL DEFAULT true,
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now(),
|
||||||
|
"updated_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Accounting module: Journal Entry
|
||||||
|
CREATE TABLE IF NOT EXISTS "journal_entry" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"entry_number" varchar(20) UNIQUE NOT NULL,
|
||||||
|
"entry_date" date NOT NULL DEFAULT CURRENT_DATE,
|
||||||
|
"entry_type" varchar(50) NOT NULL,
|
||||||
|
"source_type" varchar(50),
|
||||||
|
"source_id" uuid,
|
||||||
|
"description" text NOT NULL,
|
||||||
|
"total_debits" numeric(10,2) NOT NULL,
|
||||||
|
"total_credits" numeric(10,2) NOT NULL,
|
||||||
|
"is_void" boolean NOT NULL DEFAULT false,
|
||||||
|
"void_reason" text,
|
||||||
|
"voided_by" uuid REFERENCES "user"("id"),
|
||||||
|
"voided_at" timestamptz,
|
||||||
|
"reversal_of_id" uuid REFERENCES "journal_entry"("id"),
|
||||||
|
"created_by" uuid NOT NULL REFERENCES "user"("id"),
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "journal_entry_date" ON "journal_entry" ("entry_date");
|
||||||
|
CREATE INDEX IF NOT EXISTS "journal_entry_type" ON "journal_entry" ("entry_type");
|
||||||
|
|
||||||
|
-- Accounting module: Journal Entry Line
|
||||||
|
CREATE TABLE IF NOT EXISTS "journal_entry_line" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"journal_entry_id" uuid NOT NULL REFERENCES "journal_entry"("id") ON DELETE CASCADE,
|
||||||
|
"account_code_id" uuid NOT NULL REFERENCES "account_code"("id"),
|
||||||
|
"line_type" journal_line_type NOT NULL,
|
||||||
|
"amount" numeric(10,2) NOT NULL,
|
||||||
|
"description" text,
|
||||||
|
"entity_type" varchar(50),
|
||||||
|
"entity_id" uuid,
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS "journal_entry_line_entry_id" ON "journal_entry_line" ("journal_entry_id");
|
||||||
|
CREATE INDEX IF NOT EXISTS "journal_entry_line_account" ON "journal_entry_line" ("account_code_id");
|
||||||
|
|
||||||
|
-- Lessons module: Billing Run
|
||||||
|
CREATE TABLE IF NOT EXISTS "billing_run" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
"run_date" date NOT NULL,
|
||||||
|
"status" billing_run_status NOT NULL DEFAULT 'pending',
|
||||||
|
"enrollments_processed" integer NOT NULL DEFAULT 0,
|
||||||
|
"invoices_generated" integer NOT NULL DEFAULT 0,
|
||||||
|
"total_amount" numeric(10,2) NOT NULL DEFAULT 0,
|
||||||
|
"errors" jsonb,
|
||||||
|
"started_at" timestamptz,
|
||||||
|
"completed_at" timestamptz,
|
||||||
|
"created_by" uuid REFERENCES "user"("id"),
|
||||||
|
"created_at" timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Add nextBillingDate to enrollment
|
||||||
|
ALTER TABLE "enrollment" ADD COLUMN IF NOT EXISTS "next_billing_date" date;
|
||||||
|
|
||||||
|
-- Add accounting to module_config
|
||||||
|
INSERT INTO "module_config" ("slug", "name", "description", "licensed", "enabled")
|
||||||
|
VALUES ('accounting', 'Accounting', 'Chart of accounts, journal entries, and financial reports', true, false)
|
||||||
|
ON CONFLICT ("slug") DO NOTHING;
|
||||||
|
|
||||||
|
-- Seed chart of accounts
|
||||||
|
INSERT INTO "account_code" ("code", "name", "account_type", "normal_balance", "is_system") VALUES
|
||||||
|
('1000', 'Cash - Register Drawer', 'asset', 'debit', true),
|
||||||
|
('1100', 'Accounts Receivable', 'asset', 'debit', true),
|
||||||
|
('1200', 'Payment Clearing', 'asset', 'debit', true),
|
||||||
|
('1300', 'Inventory - Sale Stock', 'asset', 'debit', true),
|
||||||
|
('1320', 'Inventory - Parts & Supplies', 'asset', 'debit', true),
|
||||||
|
('2000', 'Sales Tax Payable', 'liability', 'credit', true),
|
||||||
|
('2110', 'Deferred Revenue - Lessons', 'liability', 'credit', true),
|
||||||
|
('4000', 'Sales Revenue', 'revenue', 'credit', true),
|
||||||
|
('4200', 'Lesson Revenue', 'revenue', 'credit', true),
|
||||||
|
('4300', 'Repair Revenue - Labor', 'revenue', 'credit', true),
|
||||||
|
('4310', 'Repair Revenue - Parts', 'revenue', 'credit', true),
|
||||||
|
('4900', 'Sales Discounts', 'contra_revenue', 'debit', true),
|
||||||
|
('4910', 'Sales Returns & Refunds', 'contra_revenue', 'debit', true),
|
||||||
|
('5000', 'Cost of Goods Sold', 'cogs', 'debit', true),
|
||||||
|
('5100', 'Repair Parts Cost', 'cogs', 'debit', true),
|
||||||
|
('6000', 'Cash Over / Short', 'expense', 'debit', true),
|
||||||
|
('6200', 'Bad Debt Expense', 'expense', 'debit', true)
|
||||||
|
ON CONFLICT ("code") DO NOTHING;
|
||||||
@@ -330,6 +330,13 @@
|
|||||||
"when": 1775860000000,
|
"when": 1775860000000,
|
||||||
"tag": "0046_auto-employee-number",
|
"tag": "0046_auto-employee-number",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 47,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1775950000000,
|
||||||
|
"tag": "0047_accounting",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
147
packages/backend/src/db/schema/accounting.ts
Normal file
147
packages/backend/src/db/schema/accounting.ts
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
import { pgTable, uuid, varchar, text, numeric, integer, boolean, date, timestamp, jsonb, pgEnum } from 'drizzle-orm/pg-core'
|
||||||
|
import { accounts } from './accounts.js'
|
||||||
|
import { locations } from './stores.js'
|
||||||
|
import { users } from './users.js'
|
||||||
|
import { transactions } from './pos.js'
|
||||||
|
|
||||||
|
// Enums
|
||||||
|
export const invoiceStatusEnum = pgEnum('invoice_status', ['draft', 'sent', 'paid', 'partial', 'overdue', 'void', 'written_off'])
|
||||||
|
export const accountTypeEnum = pgEnum('account_type', ['asset', 'liability', 'revenue', 'contra_revenue', 'cogs', 'expense'])
|
||||||
|
export const normalBalanceEnum = pgEnum('normal_balance', ['debit', 'credit'])
|
||||||
|
export const journalLineTypeEnum = pgEnum('journal_line_type', ['debit', 'credit'])
|
||||||
|
export const billingRunStatusEnum = pgEnum('billing_run_status', ['pending', 'running', 'completed', 'failed'])
|
||||||
|
|
||||||
|
// Core: Invoice
|
||||||
|
export const invoices = pgTable('invoice', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
invoiceNumber: varchar('invoice_number', { length: 50 }).notNull().unique(),
|
||||||
|
accountId: uuid('account_id').notNull().references(() => accounts.id),
|
||||||
|
locationId: uuid('location_id').references(() => locations.id),
|
||||||
|
status: invoiceStatusEnum('status').notNull().default('draft'),
|
||||||
|
issueDate: date('issue_date').notNull().defaultNow(),
|
||||||
|
dueDate: date('due_date').notNull().defaultNow(),
|
||||||
|
sourceType: varchar('source_type', { length: 50 }),
|
||||||
|
sourceId: uuid('source_id'),
|
||||||
|
subtotal: numeric('subtotal', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
discountTotal: numeric('discount_total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
taxTotal: numeric('tax_total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
total: numeric('total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
amountPaid: numeric('amount_paid', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
balance: numeric('balance', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
refundOfInvoiceId: uuid('refund_of_invoice_id'),
|
||||||
|
notes: text('notes'),
|
||||||
|
createdBy: uuid('created_by').references(() => users.id),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Core: Invoice Line Item
|
||||||
|
export const invoiceLineItems = pgTable('invoice_line_item', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
invoiceId: uuid('invoice_id').notNull().references(() => invoices.id, { onDelete: 'cascade' }),
|
||||||
|
description: varchar('description', { length: 255 }).notNull(),
|
||||||
|
qty: integer('qty').notNull().default(1),
|
||||||
|
unitPrice: numeric('unit_price', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
discountAmount: numeric('discount_amount', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
taxRate: numeric('tax_rate', { precision: 5, scale: 4 }).notNull().default('0'),
|
||||||
|
taxAmount: numeric('tax_amount', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
lineTotal: numeric('line_total', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
accountCodeId: uuid('account_code_id'),
|
||||||
|
sourceType: varchar('source_type', { length: 50 }),
|
||||||
|
sourceId: uuid('source_id'),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Core: Payment Application
|
||||||
|
export const paymentApplications = pgTable('payment_application', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
invoiceId: uuid('invoice_id').notNull().references(() => invoices.id),
|
||||||
|
transactionId: uuid('transaction_id').references(() => transactions.id),
|
||||||
|
amount: numeric('amount', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
appliedAt: timestamp('applied_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
appliedBy: uuid('applied_by').notNull().references(() => users.id),
|
||||||
|
notes: text('notes'),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Core: Account Balance (materialized AR)
|
||||||
|
export const accountBalances = pgTable('account_balance', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
accountId: uuid('account_id').notNull().unique().references(() => accounts.id),
|
||||||
|
currentBalance: numeric('current_balance', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
lastInvoiceDate: date('last_invoice_date'),
|
||||||
|
lastPaymentDate: date('last_payment_date'),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Accounting module: Chart of Accounts
|
||||||
|
export const accountCodes = pgTable('account_code', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
code: varchar('code', { length: 10 }).notNull().unique(),
|
||||||
|
name: varchar('name', { length: 255 }).notNull(),
|
||||||
|
accountType: accountTypeEnum('account_type').notNull(),
|
||||||
|
normalBalance: normalBalanceEnum('normal_balance').notNull(),
|
||||||
|
isSystem: boolean('is_system').notNull().default(true),
|
||||||
|
isActive: boolean('is_active').notNull().default(true),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Accounting module: Journal Entry
|
||||||
|
export const journalEntries = pgTable('journal_entry', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
entryNumber: varchar('entry_number', { length: 20 }).notNull().unique(),
|
||||||
|
entryDate: date('entry_date').notNull().defaultNow(),
|
||||||
|
entryType: varchar('entry_type', { length: 50 }).notNull(),
|
||||||
|
sourceType: varchar('source_type', { length: 50 }),
|
||||||
|
sourceId: uuid('source_id'),
|
||||||
|
description: text('description').notNull(),
|
||||||
|
totalDebits: numeric('total_debits', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
totalCredits: numeric('total_credits', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
isVoid: boolean('is_void').notNull().default(false),
|
||||||
|
voidReason: text('void_reason'),
|
||||||
|
voidedBy: uuid('voided_by').references(() => users.id),
|
||||||
|
voidedAt: timestamp('voided_at', { withTimezone: true }),
|
||||||
|
reversalOfId: uuid('reversal_of_id'),
|
||||||
|
createdBy: uuid('created_by').notNull().references(() => users.id),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Accounting module: Journal Entry Line
|
||||||
|
export const journalEntryLines = pgTable('journal_entry_line', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
journalEntryId: uuid('journal_entry_id').notNull().references(() => journalEntries.id, { onDelete: 'cascade' }),
|
||||||
|
accountCodeId: uuid('account_code_id').notNull().references(() => accountCodes.id),
|
||||||
|
lineType: journalLineTypeEnum('line_type').notNull(),
|
||||||
|
amount: numeric('amount', { precision: 10, scale: 2 }).notNull(),
|
||||||
|
description: text('description'),
|
||||||
|
entityType: varchar('entity_type', { length: 50 }),
|
||||||
|
entityId: uuid('entity_id'),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Lessons module: Billing Run
|
||||||
|
export const billingRuns = pgTable('billing_run', {
|
||||||
|
id: uuid('id').primaryKey().defaultRandom(),
|
||||||
|
runDate: date('run_date').notNull(),
|
||||||
|
status: billingRunStatusEnum('status').notNull().default('pending'),
|
||||||
|
enrollmentsProcessed: integer('enrollments_processed').notNull().default(0),
|
||||||
|
invoicesGenerated: integer('invoices_generated').notNull().default(0),
|
||||||
|
totalAmount: numeric('total_amount', { precision: 10, scale: 2 }).notNull().default('0'),
|
||||||
|
errors: jsonb('errors'),
|
||||||
|
startedAt: timestamp('started_at', { withTimezone: true }),
|
||||||
|
completedAt: timestamp('completed_at', { withTimezone: true }),
|
||||||
|
createdBy: uuid('created_by').references(() => users.id),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
})
|
||||||
|
|
||||||
|
// Type exports
|
||||||
|
export type Invoice = typeof invoices.$inferSelect
|
||||||
|
export type InvoiceInsert = typeof invoices.$inferInsert
|
||||||
|
export type InvoiceLineItem = typeof invoiceLineItems.$inferSelect
|
||||||
|
export type PaymentApplication = typeof paymentApplications.$inferSelect
|
||||||
|
export type AccountBalance = typeof accountBalances.$inferSelect
|
||||||
|
export type AccountCode = typeof accountCodes.$inferSelect
|
||||||
|
export type JournalEntry = typeof journalEntries.$inferSelect
|
||||||
|
export type JournalEntryLine = typeof journalEntryLines.$inferSelect
|
||||||
|
export type BillingRun = typeof billingRuns.$inferSelect
|
||||||
@@ -33,6 +33,7 @@ import { vaultRoutes } from './routes/v1/vault.js'
|
|||||||
import { webdavRoutes } from './routes/webdav/index.js'
|
import { webdavRoutes } from './routes/webdav/index.js'
|
||||||
import { moduleRoutes } from './routes/v1/modules.js'
|
import { moduleRoutes } from './routes/v1/modules.js'
|
||||||
import { configRoutes } from './routes/v1/config.js'
|
import { configRoutes } from './routes/v1/config.js'
|
||||||
|
import { invoiceRoutes } from './routes/v1/invoices.js'
|
||||||
import { RbacService } from './services/rbac.service.js'
|
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'
|
||||||
@@ -202,6 +203,7 @@ export async function buildApp() {
|
|||||||
await app.register(storeRoutes, { prefix: '/v1' })
|
await app.register(storeRoutes, { prefix: '/v1' })
|
||||||
await app.register(moduleRoutes, { prefix: '/v1' })
|
await app.register(moduleRoutes, { prefix: '/v1' })
|
||||||
await app.register(configRoutes, { prefix: '/v1' })
|
await app.register(configRoutes, { prefix: '/v1' })
|
||||||
|
await app.register(invoiceRoutes, { prefix: '/v1' })
|
||||||
await app.register(lookupRoutes, { prefix: '/v1' })
|
await app.register(lookupRoutes, { prefix: '/v1' })
|
||||||
|
|
||||||
// Module-gated routes
|
// Module-gated routes
|
||||||
|
|||||||
130
packages/backend/src/routes/v1/invoices.ts
Normal file
130
packages/backend/src/routes/v1/invoices.ts
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
import type { FastifyPluginAsync } from 'fastify'
|
||||||
|
import {
|
||||||
|
PaginationSchema,
|
||||||
|
InvoiceCreateSchema,
|
||||||
|
PaymentApplicationSchema,
|
||||||
|
InvoiceVoidSchema,
|
||||||
|
InvoiceWriteOffSchema,
|
||||||
|
} from '@lunarfront/shared/schemas'
|
||||||
|
import { InvoiceService } from '../../services/invoice.service.js'
|
||||||
|
import { AccountBalanceService } from '../../services/account-balance.service.js'
|
||||||
|
|
||||||
|
export const invoiceRoutes: FastifyPluginAsync = async (app) => {
|
||||||
|
// --- Invoices ---
|
||||||
|
|
||||||
|
app.get('/invoices', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const query = request.query as Record<string, string | undefined>
|
||||||
|
const params = PaginationSchema.parse(query)
|
||||||
|
const filters = {
|
||||||
|
accountId: query.accountId,
|
||||||
|
status: query.status,
|
||||||
|
dateFrom: query.dateFrom,
|
||||||
|
dateTo: query.dateTo,
|
||||||
|
}
|
||||||
|
const result = await InvoiceService.list(app.db, params, filters)
|
||||||
|
return reply.send(result)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/invoices/:id', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const invoice = await InvoiceService.getById(app.db, id)
|
||||||
|
if (!invoice) return reply.status(404).send({ error: { message: 'Invoice not found', statusCode: 404 } })
|
||||||
|
return reply.send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices', { preHandler: [app.authenticate, app.requirePermission('accounting.edit')] }, async (request, reply) => {
|
||||||
|
const parsed = InvoiceCreateSchema.safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
|
}
|
||||||
|
const invoice = await InvoiceService.create(app.db, parsed.data, request.user.id)
|
||||||
|
request.log.info({ invoiceId: invoice.id, invoiceNumber: invoice.invoiceNumber }, 'Invoice created')
|
||||||
|
return reply.status(201).send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices/:id/send', { preHandler: [app.authenticate, app.requirePermission('accounting.edit')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const invoice = await InvoiceService.send(app.db, id)
|
||||||
|
request.log.info({ invoiceId: id }, 'Invoice sent')
|
||||||
|
return reply.send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices/:id/apply-payment', { preHandler: [app.authenticate, app.requirePermission('accounting.edit')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const parsed = PaymentApplicationSchema.safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
|
}
|
||||||
|
const application = await InvoiceService.applyPayment(app.db, id, parsed.data, request.user.id)
|
||||||
|
request.log.info({ invoiceId: id, amount: parsed.data.amount }, 'Payment applied')
|
||||||
|
return reply.send(application)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices/:id/void', { preHandler: [app.authenticate, app.requirePermission('accounting.admin')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const parsed = InvoiceVoidSchema.safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
|
}
|
||||||
|
const invoice = await InvoiceService.void(app.db, id, parsed.data.reason, request.user.id)
|
||||||
|
request.log.info({ invoiceId: id, reason: parsed.data.reason }, 'Invoice voided')
|
||||||
|
return reply.send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/invoices/:id/write-off', { preHandler: [app.authenticate, app.requirePermission('accounting.admin')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const parsed = InvoiceWriteOffSchema.safeParse(request.body)
|
||||||
|
if (!parsed.success) {
|
||||||
|
return reply.status(400).send({ error: { message: 'Validation failed', details: parsed.error.flatten(), statusCode: 400 } })
|
||||||
|
}
|
||||||
|
const invoice = await InvoiceService.writeOff(app.db, id, parsed.data.reason, request.user.id)
|
||||||
|
request.log.info({ invoiceId: id, reason: parsed.data.reason }, 'Invoice written off')
|
||||||
|
return reply.send(invoice)
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- Account Invoices & Balance ---
|
||||||
|
|
||||||
|
app.get('/accounts/:id/invoices', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const query = request.query as Record<string, string | undefined>
|
||||||
|
const params = PaginationSchema.parse(query)
|
||||||
|
const result = await InvoiceService.listByAccount(app.db, id, params)
|
||||||
|
return reply.send(result)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.get('/accounts/:id/balance', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string }
|
||||||
|
const balance = await AccountBalanceService.getBalance(app.db, id)
|
||||||
|
return reply.send(balance)
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- Export ---
|
||||||
|
|
||||||
|
app.get('/invoices/export', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const query = request.query as Record<string, string | undefined>
|
||||||
|
const csv = await InvoiceService.exportCSV(app.db, {
|
||||||
|
dateFrom: query.dateFrom,
|
||||||
|
dateTo: query.dateTo,
|
||||||
|
})
|
||||||
|
return reply
|
||||||
|
.header('Content-Type', 'text/csv')
|
||||||
|
.header('Content-Disposition', `attachment; filename="invoices-${new Date().toISOString().slice(0, 10)}.csv"`)
|
||||||
|
.send(csv)
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- AR Aging ---
|
||||||
|
|
||||||
|
app.get('/invoices/aging', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const report = await InvoiceService.getAgingReport(app.db)
|
||||||
|
return reply.send(report)
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- Outstanding Accounts ---
|
||||||
|
|
||||||
|
app.get('/accounts/outstanding', { preHandler: [app.authenticate, app.requirePermission('accounting.view')] }, async (request, reply) => {
|
||||||
|
const query = request.query as Record<string, string | undefined>
|
||||||
|
const params = PaginationSchema.parse(query)
|
||||||
|
const result = await AccountBalanceService.getOutstandingAccounts(app.db, params)
|
||||||
|
return reply.send(result)
|
||||||
|
})
|
||||||
|
}
|
||||||
93
packages/backend/src/services/account-balance.service.ts
Normal file
93
packages/backend/src/services/account-balance.service.ts
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import { eq, desc, gt, count } from 'drizzle-orm'
|
||||||
|
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
||||||
|
import { accountBalances } from '../db/schema/accounting.js'
|
||||||
|
import { accounts } from '../db/schema/accounts.js'
|
||||||
|
import type { PaginationInput } from '@lunarfront/shared/schemas'
|
||||||
|
|
||||||
|
export const AccountBalanceService = {
|
||||||
|
async getBalance(db: PostgresJsDatabase<any>, accountId: string) {
|
||||||
|
const [existing] = await db.select().from(accountBalances).where(eq(accountBalances.accountId, accountId)).limit(1)
|
||||||
|
if (existing) return existing
|
||||||
|
|
||||||
|
// Create balance record if it doesn't exist
|
||||||
|
const [created] = await db.insert(accountBalances).values({ accountId }).returning()
|
||||||
|
return created
|
||||||
|
},
|
||||||
|
|
||||||
|
async adjustBalance(
|
||||||
|
db: PostgresJsDatabase<any>,
|
||||||
|
accountId: string,
|
||||||
|
adjustment: number,
|
||||||
|
reason: 'invoice' | 'payment' | 'void' | 'write_off',
|
||||||
|
) {
|
||||||
|
const balance = await this.getBalance(db, accountId)
|
||||||
|
const newBalance = parseFloat(balance.currentBalance) + adjustment
|
||||||
|
|
||||||
|
const updates: Record<string, unknown> = {
|
||||||
|
currentBalance: newBalance.toFixed(2),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reason === 'invoice' && adjustment > 0) {
|
||||||
|
updates.lastInvoiceDate = new Date().toISOString().slice(0, 10)
|
||||||
|
}
|
||||||
|
if (reason === 'payment' && adjustment < 0) {
|
||||||
|
updates.lastPaymentDate = new Date().toISOString().slice(0, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.update(accountBalances).set(updates).where(eq(accountBalances.accountId, accountId))
|
||||||
|
},
|
||||||
|
|
||||||
|
async getOutstandingAccounts(db: PostgresJsDatabase<any>, params: PaginationInput) {
|
||||||
|
const where = gt(accountBalances.currentBalance, '0')
|
||||||
|
const offset = ((params.page ?? 1) - 1) * (params.limit ?? 25)
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
db.select({
|
||||||
|
accountId: accountBalances.accountId,
|
||||||
|
currentBalance: accountBalances.currentBalance,
|
||||||
|
lastInvoiceDate: accountBalances.lastInvoiceDate,
|
||||||
|
lastPaymentDate: accountBalances.lastPaymentDate,
|
||||||
|
accountName: accounts.name,
|
||||||
|
accountEmail: accounts.email,
|
||||||
|
})
|
||||||
|
.from(accountBalances)
|
||||||
|
.innerJoin(accounts, eq(accountBalances.accountId, accounts.id))
|
||||||
|
.where(where)
|
||||||
|
.orderBy(desc(accountBalances.currentBalance))
|
||||||
|
.limit(params.limit ?? 25)
|
||||||
|
.offset(offset),
|
||||||
|
db.select({ total: count() })
|
||||||
|
.from(accountBalances)
|
||||||
|
.where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
pagination: {
|
||||||
|
page: params.page ?? 1,
|
||||||
|
limit: params.limit ?? 25,
|
||||||
|
total,
|
||||||
|
totalPages: Math.ceil(total / (params.limit ?? 25)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async recalculateFromInvoices(db: PostgresJsDatabase<any>, accountId: string) {
|
||||||
|
// Safety valve: recalculate balance from all invoices
|
||||||
|
const { invoices } = await import('../db/schema/accounting.js')
|
||||||
|
const rows = await db
|
||||||
|
.select({ balance: invoices.balance, status: invoices.status })
|
||||||
|
.from(invoices)
|
||||||
|
.where(eq(invoices.accountId, accountId))
|
||||||
|
|
||||||
|
const totalOutstanding = rows
|
||||||
|
.filter(r => ['sent', 'partial', 'overdue'].includes(r.status))
|
||||||
|
.reduce((sum, r) => sum + parseFloat(r.balance), 0)
|
||||||
|
|
||||||
|
await db.update(accountBalances).set({
|
||||||
|
currentBalance: totalOutstanding.toFixed(2),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}).where(eq(accountBalances.accountId, accountId))
|
||||||
|
},
|
||||||
|
}
|
||||||
499
packages/backend/src/services/invoice.service.ts
Normal file
499
packages/backend/src/services/invoice.service.ts
Normal file
@@ -0,0 +1,499 @@
|
|||||||
|
import { eq, and, count, sql, type Column, lte, inArray } from 'drizzle-orm'
|
||||||
|
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
||||||
|
import { invoices, invoiceLineItems, paymentApplications } from '../db/schema/accounting.js'
|
||||||
|
import { transactions, transactionLineItems } from '../db/schema/pos.js'
|
||||||
|
import { repairTickets, repairLineItems } from '../db/schema/repairs.js'
|
||||||
|
import { accounts } from '../db/schema/accounts.js'
|
||||||
|
import { NotFoundError, ValidationError } from '../lib/errors.js'
|
||||||
|
import { AccountBalanceService } from './account-balance.service.js'
|
||||||
|
import type { InvoiceCreateInput, PaginationInput } from '@lunarfront/shared/schemas'
|
||||||
|
import { buildSearchCondition } from '../utils/pagination.js'
|
||||||
|
|
||||||
|
function generateInvoiceNumber(): string {
|
||||||
|
const date = new Date()
|
||||||
|
const dateStr = date.toISOString().slice(0, 10).replace(/-/g, '')
|
||||||
|
const seq = String(Math.floor(Math.random() * 9999) + 1).padStart(4, '0')
|
||||||
|
return `INV-${dateStr}-${seq}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const InvoiceService = {
|
||||||
|
async create(db: PostgresJsDatabase<any>, input: InvoiceCreateInput, createdBy: string) {
|
||||||
|
const invoiceNumber = generateInvoiceNumber()
|
||||||
|
|
||||||
|
// Calculate totals from line items
|
||||||
|
let subtotal = 0
|
||||||
|
let discountTotal = 0
|
||||||
|
let taxTotal = 0
|
||||||
|
|
||||||
|
const lineItemValues = input.lineItems.map((item) => {
|
||||||
|
const lineSubtotal = item.qty * item.unitPrice
|
||||||
|
const lineDiscount = item.discountAmount ?? 0
|
||||||
|
const lineTaxable = lineSubtotal - lineDiscount
|
||||||
|
const lineTax = parseFloat((lineTaxable * (item.taxRate ?? 0)).toFixed(2))
|
||||||
|
const lineTotal = parseFloat((lineTaxable + lineTax).toFixed(2))
|
||||||
|
|
||||||
|
subtotal += lineSubtotal
|
||||||
|
discountTotal += lineDiscount
|
||||||
|
taxTotal += lineTax
|
||||||
|
|
||||||
|
return {
|
||||||
|
description: item.description,
|
||||||
|
qty: item.qty,
|
||||||
|
unitPrice: item.unitPrice.toFixed(2),
|
||||||
|
discountAmount: lineDiscount.toFixed(2),
|
||||||
|
taxRate: (item.taxRate ?? 0).toFixed(4),
|
||||||
|
taxAmount: lineTax.toFixed(2),
|
||||||
|
lineTotal: lineTotal.toFixed(2),
|
||||||
|
accountCodeId: item.accountCodeId ?? null,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const total = parseFloat((subtotal - discountTotal + taxTotal).toFixed(2))
|
||||||
|
|
||||||
|
const [invoice] = await db.insert(invoices).values({
|
||||||
|
invoiceNumber,
|
||||||
|
accountId: input.accountId,
|
||||||
|
locationId: input.locationId ?? null,
|
||||||
|
status: 'draft',
|
||||||
|
issueDate: input.issueDate,
|
||||||
|
dueDate: input.dueDate,
|
||||||
|
subtotal: subtotal.toFixed(2),
|
||||||
|
discountTotal: discountTotal.toFixed(2),
|
||||||
|
taxTotal: taxTotal.toFixed(2),
|
||||||
|
total: total.toFixed(2),
|
||||||
|
balance: total.toFixed(2),
|
||||||
|
notes: input.notes ?? null,
|
||||||
|
createdBy,
|
||||||
|
}).returning()
|
||||||
|
|
||||||
|
// Insert line items
|
||||||
|
for (const item of lineItemValues) {
|
||||||
|
await db.insert(invoiceLineItems).values({
|
||||||
|
invoiceId: invoice.id,
|
||||||
|
...item,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
},
|
||||||
|
|
||||||
|
async createFromTransaction(db: PostgresJsDatabase<any>, transactionId: string, createdBy: string) {
|
||||||
|
const [txn] = await db.select().from(transactions).where(eq(transactions.id, transactionId)).limit(1)
|
||||||
|
if (!txn) throw new NotFoundError('Transaction')
|
||||||
|
if (!txn.accountId) throw new ValidationError('Transaction must be linked to an account for invoicing')
|
||||||
|
|
||||||
|
const lineItems = await db.select().from(transactionLineItems).where(eq(transactionLineItems.transactionId, transactionId))
|
||||||
|
|
||||||
|
const invoiceNumber = generateInvoiceNumber()
|
||||||
|
const isPaid = txn.paymentMethod !== 'account_charge'
|
||||||
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
|
|
||||||
|
const [invoice] = await db.insert(invoices).values({
|
||||||
|
invoiceNumber,
|
||||||
|
accountId: txn.accountId,
|
||||||
|
locationId: txn.locationId ?? null,
|
||||||
|
status: isPaid ? 'paid' : 'sent',
|
||||||
|
issueDate: today,
|
||||||
|
dueDate: today, // Immediate for POS, could add net-30 logic later
|
||||||
|
sourceType: 'transaction',
|
||||||
|
sourceId: transactionId,
|
||||||
|
subtotal: txn.subtotal,
|
||||||
|
discountTotal: txn.discountTotal,
|
||||||
|
taxTotal: txn.taxTotal,
|
||||||
|
total: txn.total,
|
||||||
|
amountPaid: isPaid ? txn.total : '0',
|
||||||
|
balance: isPaid ? '0' : txn.total,
|
||||||
|
createdBy,
|
||||||
|
}).returning()
|
||||||
|
|
||||||
|
// Copy line items
|
||||||
|
for (const item of lineItems) {
|
||||||
|
await db.insert(invoiceLineItems).values({
|
||||||
|
invoiceId: invoice.id,
|
||||||
|
description: item.description,
|
||||||
|
qty: item.qty,
|
||||||
|
unitPrice: item.unitPrice,
|
||||||
|
discountAmount: item.discountAmount ?? '0',
|
||||||
|
taxRate: item.taxRate ?? '0',
|
||||||
|
taxAmount: item.taxAmount ?? '0',
|
||||||
|
lineTotal: item.lineTotal ?? '0',
|
||||||
|
sourceType: 'transaction_line_item',
|
||||||
|
sourceId: item.id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// If paid, record the payment application
|
||||||
|
if (isPaid) {
|
||||||
|
await db.insert(paymentApplications).values({
|
||||||
|
invoiceId: invoice.id,
|
||||||
|
transactionId,
|
||||||
|
amount: txn.total,
|
||||||
|
appliedBy: createdBy,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// If account_charge, update AR balance
|
||||||
|
if (!isPaid) {
|
||||||
|
await AccountBalanceService.adjustBalance(db, txn.accountId, parseFloat(txn.total), 'invoice')
|
||||||
|
}
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
},
|
||||||
|
|
||||||
|
async createFromRepairTicket(db: PostgresJsDatabase<any>, ticketId: string, createdBy: string) {
|
||||||
|
const [ticket] = await db.select().from(repairTickets).where(eq(repairTickets.id, ticketId)).limit(1)
|
||||||
|
if (!ticket) throw new NotFoundError('Repair ticket')
|
||||||
|
if (!ticket.accountId) throw new ValidationError('Repair ticket must be linked to an account for invoicing')
|
||||||
|
|
||||||
|
const lineItemRows = await db.select().from(repairLineItems)
|
||||||
|
.where(and(eq(repairLineItems.repairTicketId, ticketId), sql`${repairLineItems.itemType} != 'consumable'`))
|
||||||
|
|
||||||
|
if (lineItemRows.length === 0) return null // No billable items
|
||||||
|
|
||||||
|
const invoiceNumber = generateInvoiceNumber()
|
||||||
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
|
|
||||||
|
let subtotal = 0
|
||||||
|
for (const item of lineItemRows) {
|
||||||
|
subtotal += parseFloat(item.totalPrice)
|
||||||
|
}
|
||||||
|
|
||||||
|
const [invoice] = await db.insert(invoices).values({
|
||||||
|
invoiceNumber,
|
||||||
|
accountId: ticket.accountId,
|
||||||
|
status: 'sent',
|
||||||
|
issueDate: today,
|
||||||
|
dueDate: today,
|
||||||
|
sourceType: 'repair_ticket',
|
||||||
|
sourceId: ticketId,
|
||||||
|
subtotal: subtotal.toFixed(2),
|
||||||
|
total: subtotal.toFixed(2),
|
||||||
|
balance: subtotal.toFixed(2),
|
||||||
|
createdBy,
|
||||||
|
}).returning()
|
||||||
|
|
||||||
|
for (const item of lineItemRows) {
|
||||||
|
await db.insert(invoiceLineItems).values({
|
||||||
|
invoiceId: invoice.id,
|
||||||
|
description: item.description,
|
||||||
|
qty: parseInt(item.qty as any) || 1,
|
||||||
|
unitPrice: item.unitPrice,
|
||||||
|
lineTotal: item.totalPrice,
|
||||||
|
sourceType: 'repair_line_item',
|
||||||
|
sourceId: item.id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update AR balance
|
||||||
|
await AccountBalanceService.adjustBalance(db, ticket.accountId, subtotal, 'invoice')
|
||||||
|
|
||||||
|
return invoice
|
||||||
|
},
|
||||||
|
|
||||||
|
async applyPayment(
|
||||||
|
db: PostgresJsDatabase<any>,
|
||||||
|
invoiceId: string,
|
||||||
|
input: { transactionId?: string; amount: number },
|
||||||
|
appliedBy: string,
|
||||||
|
) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, invoiceId)).limit(1)
|
||||||
|
if (!invoice) throw new NotFoundError('Invoice')
|
||||||
|
|
||||||
|
if (['void', 'written_off', 'paid'].includes(invoice.status)) {
|
||||||
|
throw new ValidationError(`Cannot apply payment to ${invoice.status} invoice`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentBalance = parseFloat(invoice.balance)
|
||||||
|
if (input.amount > currentBalance) {
|
||||||
|
throw new ValidationError(`Payment amount $${input.amount} exceeds invoice balance $${currentBalance}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record payment application
|
||||||
|
const [application] = await db.insert(paymentApplications).values({
|
||||||
|
invoiceId,
|
||||||
|
transactionId: input.transactionId ?? null,
|
||||||
|
amount: input.amount.toFixed(2),
|
||||||
|
appliedBy,
|
||||||
|
}).returning()
|
||||||
|
|
||||||
|
// Update invoice
|
||||||
|
const newAmountPaid = parseFloat(invoice.amountPaid) + input.amount
|
||||||
|
const newBalance = parseFloat(invoice.total) - newAmountPaid
|
||||||
|
const newStatus = newBalance <= 0 ? 'paid' : 'partial'
|
||||||
|
|
||||||
|
await db.update(invoices).set({
|
||||||
|
amountPaid: newAmountPaid.toFixed(2),
|
||||||
|
balance: newBalance.toFixed(2),
|
||||||
|
status: newStatus,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}).where(eq(invoices.id, invoiceId))
|
||||||
|
|
||||||
|
// Update AR balance
|
||||||
|
await AccountBalanceService.adjustBalance(db, invoice.accountId, -input.amount, 'payment')
|
||||||
|
|
||||||
|
return application
|
||||||
|
},
|
||||||
|
|
||||||
|
async applyPaymentToOldestInvoices(
|
||||||
|
db: PostgresJsDatabase<any>,
|
||||||
|
accountId: string,
|
||||||
|
amount: number,
|
||||||
|
transactionId: string,
|
||||||
|
appliedBy: string,
|
||||||
|
) {
|
||||||
|
// FIFO: apply payment to oldest outstanding invoices
|
||||||
|
const outstanding = await db.select().from(invoices)
|
||||||
|
.where(and(
|
||||||
|
eq(invoices.accountId, accountId),
|
||||||
|
inArray(invoices.status, ['sent', 'partial', 'overdue']),
|
||||||
|
))
|
||||||
|
.orderBy(invoices.issueDate)
|
||||||
|
|
||||||
|
let remaining = amount
|
||||||
|
const applications = []
|
||||||
|
|
||||||
|
for (const inv of outstanding) {
|
||||||
|
if (remaining <= 0) break
|
||||||
|
const invBalance = parseFloat(inv.balance)
|
||||||
|
const applied = Math.min(remaining, invBalance)
|
||||||
|
|
||||||
|
const app = await this.applyPayment(db, inv.id, { transactionId, amount: applied }, appliedBy)
|
||||||
|
applications.push(app)
|
||||||
|
remaining -= applied
|
||||||
|
}
|
||||||
|
|
||||||
|
return { applications, amountApplied: amount - remaining, remaining }
|
||||||
|
},
|
||||||
|
|
||||||
|
async void(db: PostgresJsDatabase<any>, invoiceId: string, reason: string, _voidedBy: string) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, invoiceId)).limit(1)
|
||||||
|
if (!invoice) throw new NotFoundError('Invoice')
|
||||||
|
|
||||||
|
if (invoice.status === 'void') throw new ValidationError('Invoice is already void')
|
||||||
|
|
||||||
|
const balance = parseFloat(invoice.balance)
|
||||||
|
|
||||||
|
await db.update(invoices).set({
|
||||||
|
status: 'void',
|
||||||
|
balance: '0',
|
||||||
|
notes: `${invoice.notes ? invoice.notes + '\n' : ''}Voided: ${reason}`,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}).where(eq(invoices.id, invoiceId))
|
||||||
|
|
||||||
|
// If there was an outstanding balance, adjust AR
|
||||||
|
if (balance > 0) {
|
||||||
|
await AccountBalanceService.adjustBalance(db, invoice.accountId, -balance, 'void')
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...invoice, status: 'void' as const, balance: '0' }
|
||||||
|
},
|
||||||
|
|
||||||
|
async writeOff(db: PostgresJsDatabase<any>, invoiceId: string, reason: string, _writtenOffBy: string) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, invoiceId)).limit(1)
|
||||||
|
if (!invoice) throw new NotFoundError('Invoice')
|
||||||
|
|
||||||
|
const balance = parseFloat(invoice.balance)
|
||||||
|
if (balance <= 0) throw new ValidationError('No balance to write off')
|
||||||
|
|
||||||
|
await db.update(invoices).set({
|
||||||
|
status: 'written_off',
|
||||||
|
balance: '0',
|
||||||
|
notes: `${invoice.notes ? invoice.notes + '\n' : ''}Written off: ${reason}`,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
}).where(eq(invoices.id, invoiceId))
|
||||||
|
|
||||||
|
await AccountBalanceService.adjustBalance(db, invoice.accountId, -balance, 'write_off')
|
||||||
|
|
||||||
|
return { ...invoice, status: 'written_off' as const, balance: '0' }
|
||||||
|
},
|
||||||
|
|
||||||
|
async send(db: PostgresJsDatabase<any>, invoiceId: string) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, invoiceId)).limit(1)
|
||||||
|
if (!invoice) throw new NotFoundError('Invoice')
|
||||||
|
|
||||||
|
if (invoice.status !== 'draft') throw new ValidationError('Only draft invoices can be sent')
|
||||||
|
|
||||||
|
const [updated] = await db.update(invoices).set({ status: 'sent', updatedAt: new Date() })
|
||||||
|
.where(eq(invoices.id, invoiceId)).returning()
|
||||||
|
return updated
|
||||||
|
},
|
||||||
|
|
||||||
|
async getById(db: PostgresJsDatabase<any>, id: string) {
|
||||||
|
const [invoice] = await db.select().from(invoices).where(eq(invoices.id, id)).limit(1)
|
||||||
|
if (!invoice) return null
|
||||||
|
|
||||||
|
const lineItemRows = await db.select().from(invoiceLineItems).where(eq(invoiceLineItems.invoiceId, id))
|
||||||
|
const payments = await db.select().from(paymentApplications).where(eq(paymentApplications.invoiceId, id))
|
||||||
|
|
||||||
|
return { ...invoice, lineItems: lineItemRows, payments }
|
||||||
|
},
|
||||||
|
|
||||||
|
async list(db: PostgresJsDatabase<any>, params: PaginationInput, filters?: {
|
||||||
|
accountId?: string
|
||||||
|
status?: string
|
||||||
|
dateFrom?: string
|
||||||
|
dateTo?: string
|
||||||
|
}) {
|
||||||
|
const conditions = []
|
||||||
|
if (filters?.accountId) conditions.push(eq(invoices.accountId, filters.accountId))
|
||||||
|
if (filters?.status) conditions.push(eq(invoices.status, filters.status as any))
|
||||||
|
if (filters?.dateFrom) conditions.push(sql`${invoices.issueDate} >= ${filters.dateFrom}`)
|
||||||
|
if (filters?.dateTo) conditions.push(sql`${invoices.issueDate} <= ${filters.dateTo}`)
|
||||||
|
|
||||||
|
const searchCondition = params.q
|
||||||
|
? buildSearchCondition(params.q, [invoices.invoiceNumber])
|
||||||
|
: undefined
|
||||||
|
if (searchCondition) conditions.push(searchCondition)
|
||||||
|
|
||||||
|
const where = conditions.length > 0 ? and(...conditions) : undefined
|
||||||
|
const offset = ((params.page ?? 1) - 1) * (params.limit ?? 25)
|
||||||
|
|
||||||
|
const sortableColumns: Record<string, Column> = {
|
||||||
|
invoice_number: invoices.invoiceNumber,
|
||||||
|
issue_date: invoices.issueDate,
|
||||||
|
due_date: invoices.dueDate,
|
||||||
|
total: invoices.total,
|
||||||
|
balance: invoices.balance,
|
||||||
|
status: invoices.status,
|
||||||
|
created_at: invoices.createdAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortColumn = sortableColumns[params.sort ?? 'created_at'] ?? invoices.createdAt
|
||||||
|
const orderFn = params.order === 'asc' ? sql`${sortColumn} ASC` : sql`${sortColumn} DESC`
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
db.select({
|
||||||
|
id: invoices.id,
|
||||||
|
invoiceNumber: invoices.invoiceNumber,
|
||||||
|
accountId: invoices.accountId,
|
||||||
|
status: invoices.status,
|
||||||
|
issueDate: invoices.issueDate,
|
||||||
|
dueDate: invoices.dueDate,
|
||||||
|
total: invoices.total,
|
||||||
|
amountPaid: invoices.amountPaid,
|
||||||
|
balance: invoices.balance,
|
||||||
|
sourceType: invoices.sourceType,
|
||||||
|
createdAt: invoices.createdAt,
|
||||||
|
accountName: accounts.name,
|
||||||
|
})
|
||||||
|
.from(invoices)
|
||||||
|
.leftJoin(accounts, eq(invoices.accountId, accounts.id))
|
||||||
|
.where(where)
|
||||||
|
.orderBy(orderFn)
|
||||||
|
.limit(params.limit ?? 25)
|
||||||
|
.offset(offset),
|
||||||
|
db.select({ total: count() }).from(invoices).where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
return {
|
||||||
|
data,
|
||||||
|
pagination: {
|
||||||
|
page: params.page ?? 1,
|
||||||
|
limit: params.limit ?? 25,
|
||||||
|
total,
|
||||||
|
totalPages: Math.ceil(total / (params.limit ?? 25)),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async listByAccount(db: PostgresJsDatabase<any>, accountId: string, params: PaginationInput) {
|
||||||
|
return this.list(db, params, { accountId })
|
||||||
|
},
|
||||||
|
|
||||||
|
async markOverdueInvoices(db: PostgresJsDatabase<any>) {
|
||||||
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
|
await db.update(invoices).set({ status: 'overdue', updatedAt: new Date() })
|
||||||
|
.where(and(
|
||||||
|
inArray(invoices.status, ['sent', 'partial']),
|
||||||
|
lte(invoices.dueDate, today),
|
||||||
|
))
|
||||||
|
},
|
||||||
|
|
||||||
|
async getAgingReport(db: PostgresJsDatabase<any>) {
|
||||||
|
const today = new Date()
|
||||||
|
const d30 = new Date(today); d30.setDate(d30.getDate() - 30)
|
||||||
|
const d60 = new Date(today); d60.setDate(d60.getDate() - 60)
|
||||||
|
const d90 = new Date(today); d90.setDate(d90.getDate() - 90)
|
||||||
|
|
||||||
|
const outstanding = await db.select({
|
||||||
|
id: invoices.id,
|
||||||
|
invoiceNumber: invoices.invoiceNumber,
|
||||||
|
accountId: invoices.accountId,
|
||||||
|
accountName: accounts.name,
|
||||||
|
dueDate: invoices.dueDate,
|
||||||
|
total: invoices.total,
|
||||||
|
balance: invoices.balance,
|
||||||
|
})
|
||||||
|
.from(invoices)
|
||||||
|
.leftJoin(accounts, eq(invoices.accountId, accounts.id))
|
||||||
|
.where(and(
|
||||||
|
inArray(invoices.status, ['sent', 'partial', 'overdue']),
|
||||||
|
sql`${invoices.balance}::numeric > 0`,
|
||||||
|
))
|
||||||
|
|
||||||
|
let current = 0, days30 = 0, days60 = 0, days90plus = 0
|
||||||
|
|
||||||
|
for (const inv of outstanding) {
|
||||||
|
const balance = parseFloat(inv.balance!)
|
||||||
|
const dueDate = new Date(inv.dueDate!)
|
||||||
|
if (dueDate >= today) current += balance
|
||||||
|
else if (dueDate >= d30) days30 += balance
|
||||||
|
else if (dueDate >= d60) days60 += balance
|
||||||
|
else days90plus += balance
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
current: current.toFixed(2),
|
||||||
|
days30: days30.toFixed(2),
|
||||||
|
days60: days60.toFixed(2),
|
||||||
|
days90plus: days90plus.toFixed(2),
|
||||||
|
total: (current + days30 + days60 + days90plus).toFixed(2),
|
||||||
|
invoiceCount: outstanding.length,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async exportCSV(db: PostgresJsDatabase<any>, filters?: { dateFrom?: string; dateTo?: string }) {
|
||||||
|
const conditions = []
|
||||||
|
if (filters?.dateFrom) conditions.push(sql`${invoices.issueDate} >= ${filters.dateFrom}`)
|
||||||
|
if (filters?.dateTo) conditions.push(sql`${invoices.issueDate} <= ${filters.dateTo}`)
|
||||||
|
const where = conditions.length > 0 ? and(...conditions) : undefined
|
||||||
|
|
||||||
|
const rows = await db.select({
|
||||||
|
invoiceNumber: invoices.invoiceNumber,
|
||||||
|
accountName: accounts.name,
|
||||||
|
issueDate: invoices.issueDate,
|
||||||
|
dueDate: invoices.dueDate,
|
||||||
|
status: invoices.status,
|
||||||
|
subtotal: invoices.subtotal,
|
||||||
|
discountTotal: invoices.discountTotal,
|
||||||
|
taxTotal: invoices.taxTotal,
|
||||||
|
total: invoices.total,
|
||||||
|
amountPaid: invoices.amountPaid,
|
||||||
|
balance: invoices.balance,
|
||||||
|
})
|
||||||
|
.from(invoices)
|
||||||
|
.leftJoin(accounts, eq(invoices.accountId, accounts.id))
|
||||||
|
.where(where)
|
||||||
|
.orderBy(invoices.issueDate)
|
||||||
|
|
||||||
|
const headers = ['Invoice Number', 'Customer', 'Issue Date', 'Due Date', 'Status', 'Subtotal', 'Discount', 'Tax', 'Total', 'Paid', 'Balance']
|
||||||
|
const csvRows = [
|
||||||
|
headers.join(','),
|
||||||
|
...rows.map(r => [
|
||||||
|
r.invoiceNumber,
|
||||||
|
`"${(r.accountName ?? '').replace(/"/g, '""')}"`,
|
||||||
|
r.issueDate,
|
||||||
|
r.dueDate,
|
||||||
|
r.status,
|
||||||
|
r.subtotal,
|
||||||
|
r.discountTotal,
|
||||||
|
r.taxTotal,
|
||||||
|
r.total,
|
||||||
|
r.amountPaid,
|
||||||
|
r.balance,
|
||||||
|
].join(',')),
|
||||||
|
]
|
||||||
|
|
||||||
|
return csvRows.join('\n')
|
||||||
|
},
|
||||||
|
}
|
||||||
83
packages/shared/src/schemas/accounting.schema.ts
Normal file
83
packages/shared/src/schemas/accounting.schema.ts
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
// Enums
|
||||||
|
export const AccountType = z.enum(['asset', 'liability', 'revenue', 'contra_revenue', 'cogs', 'expense'])
|
||||||
|
export type AccountType = z.infer<typeof AccountType>
|
||||||
|
|
||||||
|
export const InvoiceStatus = z.enum(['draft', 'sent', 'paid', 'partial', 'overdue', 'void', 'written_off'])
|
||||||
|
export type InvoiceStatus = z.infer<typeof InvoiceStatus>
|
||||||
|
|
||||||
|
export const JournalLineType = z.enum(['debit', 'credit'])
|
||||||
|
export type JournalLineType = z.infer<typeof JournalLineType>
|
||||||
|
|
||||||
|
export const BillingRunStatus = z.enum(['pending', 'running', 'completed', 'failed'])
|
||||||
|
export type BillingRunStatus = z.infer<typeof BillingRunStatus>
|
||||||
|
|
||||||
|
// Invoice
|
||||||
|
export const InvoiceLineItemInput = z.object({
|
||||||
|
description: z.string().min(1).max(255),
|
||||||
|
qty: z.coerce.number().int().min(1).default(1),
|
||||||
|
unitPrice: z.coerce.number().min(0),
|
||||||
|
discountAmount: z.coerce.number().min(0).default(0),
|
||||||
|
taxRate: z.coerce.number().min(0).default(0),
|
||||||
|
accountCodeId: z.string().uuid().optional(),
|
||||||
|
})
|
||||||
|
export type InvoiceLineItemInput = z.infer<typeof InvoiceLineItemInput>
|
||||||
|
|
||||||
|
export const InvoiceCreateSchema = z.object({
|
||||||
|
accountId: z.string().uuid(),
|
||||||
|
locationId: z.string().uuid().optional(),
|
||||||
|
issueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
dueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
notes: z.string().optional(),
|
||||||
|
lineItems: z.array(InvoiceLineItemInput).min(1),
|
||||||
|
})
|
||||||
|
export type InvoiceCreateInput = z.infer<typeof InvoiceCreateSchema>
|
||||||
|
|
||||||
|
export const PaymentApplicationSchema = z.object({
|
||||||
|
transactionId: z.string().uuid().optional(),
|
||||||
|
amount: z.coerce.number().min(0.01),
|
||||||
|
notes: z.string().optional(),
|
||||||
|
})
|
||||||
|
export type PaymentApplicationInput = z.infer<typeof PaymentApplicationSchema>
|
||||||
|
|
||||||
|
export const InvoiceVoidSchema = z.object({
|
||||||
|
reason: z.string().min(1),
|
||||||
|
})
|
||||||
|
export type InvoiceVoidInput = z.infer<typeof InvoiceVoidSchema>
|
||||||
|
|
||||||
|
export const InvoiceWriteOffSchema = z.object({
|
||||||
|
reason: z.string().min(1),
|
||||||
|
})
|
||||||
|
export type InvoiceWriteOffInput = z.infer<typeof InvoiceWriteOffSchema>
|
||||||
|
|
||||||
|
// Journal Entry
|
||||||
|
export const JournalEntryVoidSchema = z.object({
|
||||||
|
reason: z.string().min(1),
|
||||||
|
})
|
||||||
|
export type JournalEntryVoidInput = z.infer<typeof JournalEntryVoidSchema>
|
||||||
|
|
||||||
|
// Billing
|
||||||
|
export const BillingRunSchema = z.object({
|
||||||
|
runDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||||
|
})
|
||||||
|
export type BillingRunInput = z.infer<typeof BillingRunSchema>
|
||||||
|
|
||||||
|
export const BillEnrollmentSchema = z.object({
|
||||||
|
periodStart: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
periodEnd: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
})
|
||||||
|
export type BillEnrollmentInput = z.infer<typeof BillEnrollmentSchema>
|
||||||
|
|
||||||
|
// Report filters
|
||||||
|
export const DateRangeFilterSchema = z.object({
|
||||||
|
dateFrom: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||||
|
dateTo: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||||
|
})
|
||||||
|
export type DateRangeFilter = z.infer<typeof DateRangeFilterSchema>
|
||||||
|
|
||||||
|
export const StatementFilterSchema = z.object({
|
||||||
|
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||||
|
})
|
||||||
|
export type StatementFilter = z.infer<typeof StatementFilterSchema>
|
||||||
@@ -200,3 +200,31 @@ export type {
|
|||||||
|
|
||||||
export { LogLevel, AppConfigUpdateSchema } from './config.schema.js'
|
export { LogLevel, AppConfigUpdateSchema } from './config.schema.js'
|
||||||
export type { AppConfigUpdateInput } from './config.schema.js'
|
export type { AppConfigUpdateInput } from './config.schema.js'
|
||||||
|
|
||||||
|
export {
|
||||||
|
AccountType,
|
||||||
|
InvoiceStatus,
|
||||||
|
JournalLineType,
|
||||||
|
BillingRunStatus,
|
||||||
|
InvoiceLineItemInput,
|
||||||
|
InvoiceCreateSchema,
|
||||||
|
PaymentApplicationSchema,
|
||||||
|
InvoiceVoidSchema,
|
||||||
|
InvoiceWriteOffSchema,
|
||||||
|
JournalEntryVoidSchema,
|
||||||
|
BillingRunSchema,
|
||||||
|
BillEnrollmentSchema,
|
||||||
|
DateRangeFilterSchema,
|
||||||
|
StatementFilterSchema,
|
||||||
|
} from './accounting.schema.js'
|
||||||
|
export type {
|
||||||
|
InvoiceCreateInput,
|
||||||
|
PaymentApplicationInput,
|
||||||
|
InvoiceVoidInput,
|
||||||
|
InvoiceWriteOffInput,
|
||||||
|
JournalEntryVoidInput,
|
||||||
|
BillingRunInput,
|
||||||
|
BillEnrollmentInput,
|
||||||
|
DateRangeFilter,
|
||||||
|
StatementFilter,
|
||||||
|
} from './accounting.schema.js'
|
||||||
|
|||||||
Reference in New Issue
Block a user