Compare commits
5 Commits
feature/em
...
feature/st
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
37e9cc324f | ||
|
|
3b0daeae0c | ||
|
|
0411df57eb | ||
|
|
082e388799 | ||
| abe75fb1fd |
155
docs/frontend-testing-plan.md
Normal file
155
docs/frontend-testing-plan.md
Normal file
@@ -0,0 +1,155 @@
|
||||
# Frontend Testing Plan
|
||||
|
||||
## Overview
|
||||
|
||||
The admin frontend has grown significantly (station mode, POS, repairs intake, lessons). We need frontend testing to catch regressions and validate critical user flows.
|
||||
|
||||
## Recommended Stack
|
||||
|
||||
### Tier 1: Playwright (E2E)
|
||||
**Priority: High — implement first**
|
||||
|
||||
End-to-end browser tests that exercise the full app against a running backend. Catches integration issues, routing problems, and real user flow regressions.
|
||||
|
||||
- **Framework:** Playwright (`@playwright/test`)
|
||||
- **Runner:** `bun run test:e2e` (or `npx playwright test`)
|
||||
- **Location:** `packages/admin/e2e/`
|
||||
- **CI:** Runs in the `e2e` job alongside API tests (needs backend + DB + Valkey)
|
||||
|
||||
#### Critical flows to test first
|
||||
1. **Login flow** — email/password login, redirect to dashboard, logout
|
||||
2. **Forgot password** — submit email, see success message
|
||||
3. **Station PIN login** — navigate to /station, enter PIN, unlock, see tabs
|
||||
4. **Station tab switching** — POS → Repairs → Lessons, verify content renders
|
||||
5. **POS sale** — search product, add to cart, complete cash payment, see receipt
|
||||
6. **Repair intake** — new intake form, step through all steps, create ticket
|
||||
7. **Repair queue** — filter by status, select ticket, see detail
|
||||
8. **Session attendance** — open lessons tab, select session, mark attended
|
||||
9. **Profile PIN setup** — navigate to profile, security tab, set PIN
|
||||
10. **Auto-lock** — verify station locks after timeout
|
||||
|
||||
#### Setup
|
||||
```bash
|
||||
# Install
|
||||
bun add -d @playwright/test
|
||||
npx playwright install chromium
|
||||
|
||||
# Config: packages/admin/playwright.config.ts
|
||||
# - baseURL: http://localhost:5173 (dev) or build + serve
|
||||
# - webServer: start backend + frontend before tests
|
||||
# - Use test DB with known seed data
|
||||
```
|
||||
|
||||
#### Test structure
|
||||
```
|
||||
packages/admin/e2e/
|
||||
fixtures/
|
||||
auth.ts -- login helper, PIN login helper
|
||||
seed.ts -- API calls to seed test data (accounts, products, tickets)
|
||||
flows/
|
||||
login.spec.ts
|
||||
station-pos.spec.ts
|
||||
station-repairs.spec.ts
|
||||
station-lessons.spec.ts
|
||||
profile.spec.ts
|
||||
forgot-password.spec.ts
|
||||
```
|
||||
|
||||
#### Auth fixtures
|
||||
```ts
|
||||
// Reusable login that stores auth state
|
||||
async function loginAsAdmin(page) {
|
||||
await page.goto('/login')
|
||||
await page.fill('[type=email]', 'admin@test.com')
|
||||
await page.fill('[type=password]', 'TestPassword123!')
|
||||
await page.click('button[type=submit]')
|
||||
await page.waitForURL('**/accounts**')
|
||||
}
|
||||
|
||||
async function pinLogin(page, employeeNumber, pin) {
|
||||
await page.goto('/station')
|
||||
// Type PIN digits
|
||||
for (const digit of employeeNumber + pin) {
|
||||
await page.click(`button:has-text("${digit}")`)
|
||||
}
|
||||
await page.waitForSelector('[data-slot="tabs"]')
|
||||
}
|
||||
```
|
||||
|
||||
### Tier 2: Vitest + Testing Library (Component)
|
||||
**Priority: Medium — implement after E2E**
|
||||
|
||||
Fast unit/integration tests for component logic, state management, and utility functions. Doesn't need a running backend (mocks API calls).
|
||||
|
||||
- **Framework:** Vitest + `@testing-library/react`
|
||||
- **Runner:** `bun run test:unit` (in packages/admin)
|
||||
- **Location:** `packages/admin/__tests__/`
|
||||
|
||||
#### What to test
|
||||
- **Zustand stores:** `pos.store.ts`, `station.store.ts` — state transitions, lock/unlock, activity tracking
|
||||
- **Form validation:** intake form step validation, PIN input, password requirements
|
||||
- **Permission routing:** repairs-station permission check (desk vs tech), lessons-station (desk vs instructor)
|
||||
- **Utility functions:** time formatting, status color mapping, receipt format toggle
|
||||
- **Component rendering:** key components render without crashing with mock data
|
||||
|
||||
#### What NOT to test at component level
|
||||
- API integration (covered by E2E + API tests)
|
||||
- CSS/layout (covered by E2E visual checks)
|
||||
- Third-party component internals (shadcn, radix)
|
||||
|
||||
### Tier 3: Visual Regression (Optional)
|
||||
**Priority: Low — nice to have**
|
||||
|
||||
Screenshot comparison to catch unintended visual changes.
|
||||
|
||||
- **Tool:** Playwright's built-in screenshot comparison (`expect(page).toHaveScreenshot()`)
|
||||
- **Scope:** Key pages only (login, station POS, repair intake, profile)
|
||||
- **Storage:** Baseline screenshots committed to repo
|
||||
|
||||
## CI Integration
|
||||
|
||||
```yaml
|
||||
# Add to .gitea/workflows/ci.yml
|
||||
|
||||
frontend-unit:
|
||||
runs-on: ubuntu-latest
|
||||
needs: ci
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: curl -fsSL https://bun.sh/install | bash && echo "$HOME/.bun/bin" >> $GITHUB_PATH
|
||||
- run: bun install --frozen-lockfile
|
||||
- working-directory: packages/admin
|
||||
run: bun run test:unit
|
||||
|
||||
frontend-e2e:
|
||||
runs-on: ubuntu-latest
|
||||
needs: ci
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: curl -fsSL https://bun.sh/install | bash && echo "$HOME/.bun/bin" >> $GITHUB_PATH
|
||||
- run: bun install --frozen-lockfile
|
||||
- run: npx playwright install chromium --with-deps
|
||||
# Start services (postgres, valkey)
|
||||
# Run migrations + seed
|
||||
# Start backend + frontend
|
||||
# Run playwright tests
|
||||
```
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. **Set up Playwright** — config, install, first smoke test (login page loads)
|
||||
2. **Auth fixtures** — reusable login + PIN login helpers
|
||||
3. **Seed fixtures** — create test data via API (reuse API test patterns)
|
||||
4. **Login flow tests** — login, forgot password, redirect
|
||||
5. **Station flow tests** — PIN login, tab switching, POS sale
|
||||
6. **Repair flow tests** — intake form, queue, detail
|
||||
7. **Lesson flow tests** — attendance, schedule view
|
||||
8. **Set up Vitest** — config, first store test
|
||||
9. **Store tests** — POS store, station store
|
||||
10. **CI integration** — add to pipeline
|
||||
|
||||
## Estimated Effort
|
||||
|
||||
- Tier 1 (Playwright setup + 10 critical flows): ~1 session
|
||||
- Tier 2 (Vitest setup + store/component tests): ~1 session
|
||||
- CI integration: included in each tier
|
||||
@@ -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()
|
||||
|
||||
// Fetch lock timeout from config
|
||||
// Fetch lock timeout from config (standalone only)
|
||||
const { data: lockTimeoutStr } = useQuery({
|
||||
...configOptions('pos_lock_timeout'),
|
||||
enabled: !!token,
|
||||
enabled: !!token && !embedded,
|
||||
})
|
||||
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)
|
||||
|
||||
useEffect(() => {
|
||||
if (embedded) return
|
||||
if (locked || lockTimeoutMinutes === 0) {
|
||||
if (timerRef.current) clearInterval(timerRef.current)
|
||||
return
|
||||
@@ -69,26 +74,27 @@ export function POSRegister() {
|
||||
return () => {
|
||||
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(() => {
|
||||
if (!locked) touchActivity()
|
||||
}, [locked, touchActivity])
|
||||
if (!embedded && !locked) touchActivity()
|
||||
}, [embedded, locked, touchActivity])
|
||||
|
||||
// Fetch locations
|
||||
// Fetch locations (standalone only — station shell handles this when embedded)
|
||||
const { data: locationsData } = useQuery({
|
||||
...locationsOptions(),
|
||||
enabled: !!token,
|
||||
enabled: !!token && !embedded,
|
||||
})
|
||||
const locations = locationsData?.data ?? []
|
||||
|
||||
// Auto-select first location
|
||||
// Auto-select first location (standalone only)
|
||||
useEffect(() => {
|
||||
if (embedded) return
|
||||
if (!locationId && locations.length > 0) {
|
||||
setLocation(locations[0].id)
|
||||
}
|
||||
}, [locationId, locations, setLocation])
|
||||
}, [embedded, locationId, locations, setLocation])
|
||||
|
||||
// Fetch current drawer for selected location
|
||||
const { data: drawer } = useQuery({
|
||||
@@ -112,6 +118,20 @@ export function POSRegister() {
|
||||
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 (
|
||||
<div
|
||||
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.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as StationRouteImport } from './routes/station'
|
||||
import { Route as ResetPasswordRouteImport } from './routes/reset-password'
|
||||
import { Route as PosRouteImport } from './routes/pos'
|
||||
import { Route as 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 AuthenticatedLessonsScheduleInstructorsInstructorIdRouteImport } from './routes/_authenticated/lessons/schedule/instructors/$instructorId'
|
||||
|
||||
const StationRoute = StationRouteImport.update({
|
||||
id: '/station',
|
||||
path: '/station',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ResetPasswordRoute = ResetPasswordRouteImport.update({
|
||||
id: '/reset-password',
|
||||
path: '/reset-password',
|
||||
@@ -344,6 +350,7 @@ export interface FileRoutesByFullPath {
|
||||
'/login': typeof LoginRoute
|
||||
'/pos': typeof PosRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/station': typeof StationRoute
|
||||
'/help': typeof AuthenticatedHelpRoute
|
||||
'/profile': typeof AuthenticatedProfileRoute
|
||||
'/settings': typeof AuthenticatedSettingsRoute
|
||||
@@ -393,6 +400,7 @@ export interface FileRoutesByTo {
|
||||
'/login': typeof LoginRoute
|
||||
'/pos': typeof PosRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/station': typeof StationRoute
|
||||
'/help': typeof AuthenticatedHelpRoute
|
||||
'/profile': typeof AuthenticatedProfileRoute
|
||||
'/settings': typeof AuthenticatedSettingsRoute
|
||||
@@ -444,6 +452,7 @@ export interface FileRoutesById {
|
||||
'/login': typeof LoginRoute
|
||||
'/pos': typeof PosRoute
|
||||
'/reset-password': typeof ResetPasswordRoute
|
||||
'/station': typeof StationRoute
|
||||
'/_authenticated/help': typeof AuthenticatedHelpRoute
|
||||
'/_authenticated/profile': typeof AuthenticatedProfileRoute
|
||||
'/_authenticated/settings': typeof AuthenticatedSettingsRoute
|
||||
@@ -497,6 +506,7 @@ export interface FileRouteTypes {
|
||||
| '/login'
|
||||
| '/pos'
|
||||
| '/reset-password'
|
||||
| '/station'
|
||||
| '/help'
|
||||
| '/profile'
|
||||
| '/settings'
|
||||
@@ -546,6 +556,7 @@ export interface FileRouteTypes {
|
||||
| '/login'
|
||||
| '/pos'
|
||||
| '/reset-password'
|
||||
| '/station'
|
||||
| '/help'
|
||||
| '/profile'
|
||||
| '/settings'
|
||||
@@ -596,6 +607,7 @@ export interface FileRouteTypes {
|
||||
| '/login'
|
||||
| '/pos'
|
||||
| '/reset-password'
|
||||
| '/station'
|
||||
| '/_authenticated/help'
|
||||
| '/_authenticated/profile'
|
||||
| '/_authenticated/settings'
|
||||
@@ -648,10 +660,18 @@ export interface RootRouteChildren {
|
||||
LoginRoute: typeof LoginRoute
|
||||
PosRoute: typeof PosRoute
|
||||
ResetPasswordRoute: typeof ResetPasswordRoute
|
||||
StationRoute: typeof StationRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/station': {
|
||||
id: '/station'
|
||||
path: '/station'
|
||||
fullPath: '/station'
|
||||
preLoaderRoute: typeof StationRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/reset-password': {
|
||||
id: '/reset-password'
|
||||
path: '/reset-password'
|
||||
@@ -1133,6 +1153,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
LoginRoute: LoginRoute,
|
||||
PosRoute: PosRoute,
|
||||
ResetPasswordRoute: ResetPasswordRoute,
|
||||
StationRoute: StationRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
|
||||
@@ -239,7 +239,7 @@ function AuthenticatedLayout() {
|
||||
{isModuleEnabled('pos') && canViewPOS && (
|
||||
<div className="mb-2">
|
||||
<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"
|
||||
title={collapsed ? 'Point of Sale' : undefined}
|
||||
>
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { POSRegister } from '@/components/pos/pos-register'
|
||||
import { createFileRoute, redirect } from '@tanstack/react-router'
|
||||
|
||||
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 }),
|
||||
}))
|
||||
Reference in New Issue
Block a user