feat: repair-POS integration, receipt formats, manager overrides, price adjustments

- Add thermal/full-page receipt format toggle (per-device, localStorage)
- Full-page receipt uses clean invoice layout matching repair PDF style
- Settings page reorganized into tabbed sections (Store, Locations, Modules, Receipt, POS Security, Advanced)
- Manager override system: configurable PIN prompt for void, refund, discount, cash in/out
- Discount threshold setting: require manager approval above X%
- Consumable product type: tracked for internal job costing, excluded from POS search, receipts, and customer-facing totals
- Repair line item dialog: product picker dropdown for parts/consumables from inventory
- Repair → POS checkout: load ready-for-pickup tickets into repair_payment transactions with proper tax categories (labor=service, parts=goods)
- Transaction completion auto-updates repair ticket status to picked_up
- POS Repairs dialog with Pickup and New Intake tabs, customer account lookup
- Inline price adjustment on cart items: % off, $ off, or set price with live preview
- Order-level discount button with same three input modes
- Backend: migration 0043 (consumable enum + is_consumable flag), createFromRepairTicket service, ready-for-pickup endpoint
- Fix: backend dev script uses --env-file for turbo compatibility

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
ryan
2026-04-05 01:32:28 +00:00
parent a48da03289
commit 95cf017b4b
32 changed files with 1507 additions and 199 deletions

View File

@@ -136,7 +136,7 @@ export function currentDrawerOptions(locationId: string | null) {
export function productSearchOptions(search: string) {
return queryOptions({
queryKey: posKeys.products(search),
queryFn: () => api.get<{ data: Product[]; pagination: { page: number; limit: number; total: number; totalPages: number } }>('/v1/products', { q: search, limit: 24, isActive: true }),
queryFn: () => api.get<{ data: Product[]; pagination: { page: number; limit: number; total: number; totalPages: number } }>('/v1/products', { q: search, limit: 24, isActive: true, isConsumable: false }),
enabled: search.length >= 1,
})
}
@@ -183,4 +183,7 @@ export const posMutations = {
getAdjustments: (drawerId: string) =>
api.get<{ data: DrawerAdjustment[] }>(`/v1/drawer/${drawerId}/adjustments`),
createFromRepair: (ticketId: string, locationId?: string) =>
api.post<Transaction>(`/v1/transactions/from-repair/${ticketId}`, { locationId }),
}

View File

@@ -34,6 +34,7 @@ export function ProductForm({ defaultValues, onSubmit, loading }: Props) {
isSerialized: defaultValues?.isSerialized ?? false,
isRental: defaultValues?.isRental ?? false,
isDualUseRepair: defaultValues?.isDualUseRepair ?? false,
isConsumable: defaultValues?.isConsumable ?? false,
isActive: defaultValues?.isActive ?? true,
},
})
@@ -42,6 +43,7 @@ export function ProductForm({ defaultValues, onSubmit, loading }: Props) {
const isRental = watch('isRental')
const isSerialized = watch('isSerialized')
const isDualUseRepair = watch('isDualUseRepair')
const isConsumable = watch('isConsumable')
const isActive = watch('isActive')
function handleFormSubmit(data: Record<string, unknown>) {
@@ -61,6 +63,7 @@ export function ProductForm({ defaultValues, onSubmit, loading }: Props) {
isSerialized: data.isSerialized,
isRental: data.isRental,
isDualUseRepair: data.isDualUseRepair,
isConsumable: data.isConsumable,
isActive: data.isActive,
})
}
@@ -158,6 +161,10 @@ export function ProductForm({ defaultValues, onSubmit, loading }: Props) {
<input type="checkbox" checked={isDualUseRepair} onChange={(e) => setValue('isDualUseRepair', e.target.checked)} className="h-4 w-4" />
Available as Repair Line Item
</label>
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input type="checkbox" checked={isConsumable} onChange={(e) => setValue('isConsumable', e.target.checked)} className="h-4 w-4" />
Consumable (internal use, not sold at POS)
</label>
<label className="flex items-center gap-2 text-sm cursor-pointer">
<input type="checkbox" checked={isActive} onChange={(e) => setValue('isActive', e.target.checked)} className="h-4 w-4" />
Active

View File

@@ -3,11 +3,16 @@ import { usePOSStore } from '@/stores/pos.store'
import { posMutations, posKeys, type Transaction } from '@/api/pos'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import { X, Banknote, CreditCard, FileText, Ban, UserRound } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { X, Banknote, CreditCard, FileText, Ban, UserRound, Tag } from 'lucide-react'
import { toast } from 'sonner'
import { useState } from 'react'
import { POSPaymentDialog } from './pos-payment-dialog'
import { POSCustomerDialog } from './pos-customer-dialog'
import { ManagerOverrideDialog, requiresOverride, requiresDiscountOverride } from './pos-manager-override'
import type { TransactionLineItem } from '@/api/pos'
interface POSCartPanelProps {
transaction: Transaction | null
@@ -18,6 +23,10 @@ export function POSCartPanel({ transaction }: POSCartPanelProps) {
const { currentTransactionId, setTransaction, accountName, accountPhone, accountEmail } = usePOSStore()
const [paymentMethod, setPaymentMethod] = useState<string | null>(null)
const [customerOpen, setCustomerOpen] = useState(false)
const [overrideOpen, setOverrideOpen] = useState(false)
const [priceItemId, setPriceItemId] = useState<string | null>(null)
const [pendingDiscount, setPendingDiscount] = useState<{ lineItemId: string; amount: number; reason: string } | null>(null)
const [discountOverrideOpen, setDiscountOverrideOpen] = useState(false)
const lineItems = transaction?.lineItems ?? []
const drawerSessionId = usePOSStore((s) => s.drawerSessionId)
@@ -32,6 +41,17 @@ export function POSCartPanel({ transaction }: POSCartPanelProps) {
onError: (err) => toast.error(err.message),
})
const discountMutation = useMutation({
mutationFn: (data: { lineItemId: string; amount: number; reason: string }) =>
posMutations.applyDiscount(currentTransactionId!, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: posKeys.transaction(currentTransactionId!) })
setPriceItemId(null)
toast.success('Price adjusted')
},
onError: (err) => toast.error(err.message),
})
const voidMutation = useMutation({
mutationFn: () => posMutations.void(currentTransactionId!),
onSuccess: () => {
@@ -93,33 +113,61 @@ export function POSCartPanel({ transaction }: POSCartPanelProps) {
</div>
) : (
<div className="divide-y divide-border">
{lineItems.map((item) => (
<div key={item.id} className="flex items-center gap-2 px-3 py-2.5 group">
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{item.description}</p>
<p className="text-xs text-muted-foreground">
{item.qty} x ${parseFloat(item.unitPrice).toFixed(2)}
{parseFloat(item.taxAmount) > 0 && (
<span className="ml-2">tax ${parseFloat(item.taxAmount).toFixed(2)}</span>
)}
</p>
{lineItems.map((item) => {
const unitPrice = parseFloat(item.unitPrice)
const discount = parseFloat(item.discountAmount)
const hasDiscount = discount > 0
const listTotal = unitPrice * item.qty
const discountPct = listTotal > 0 ? Math.round((discount / listTotal) * 100) : 0
return (
<div key={item.id} className="flex items-center gap-2 px-3 py-2.5 group">
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{item.description}</p>
<div className="text-xs text-muted-foreground flex items-center gap-2">
<span>{item.qty} x ${unitPrice.toFixed(2)}</span>
{hasDiscount && (
<span className="text-green-600">-${discount.toFixed(2)} ({discountPct}%)</span>
)}
{parseFloat(item.taxAmount) > 0 && (
<span>tax ${parseFloat(item.taxAmount).toFixed(2)}</span>
)}
</div>
</div>
<span className="text-sm font-medium tabular-nums">
${parseFloat(item.lineTotal).toFixed(2)}
</span>
{isPending && (
<div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 shrink-0">
<PriceAdjuster
item={item}
open={priceItemId === item.id}
onOpenChange={(o) => setPriceItemId(o ? item.id : null)}
onApply={(amount, reason) => {
const pct = listTotal > 0 ? (amount / listTotal) * 100 : 0
if (requiresDiscountOverride(pct)) {
setPendingDiscount({ lineItemId: item.id, amount, reason })
setDiscountOverrideOpen(true)
} else {
discountMutation.mutate({ lineItemId: item.id, amount, reason })
}
}}
isPending={discountMutation.isPending}
/>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => removeItemMutation.mutate(item.id)}
disabled={removeItemMutation.isPending}
>
<X className="h-4 w-4 text-destructive" />
</Button>
</div>
)}
</div>
<span className="text-sm font-medium tabular-nums">
${parseFloat(item.lineTotal).toFixed(2)}
</span>
{isPending && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 opacity-0 group-hover:opacity-100 shrink-0"
onClick={() => removeItemMutation.mutate(item.id)}
disabled={removeItemMutation.isPending}
>
<X className="h-4 w-4 text-destructive" />
</Button>
)}
</div>
))}
)
})}
</div>
)}
</div>
@@ -148,6 +196,25 @@ export function POSCartPanel({ transaction }: POSCartPanelProps) {
</div>
</div>
{/* Order discount button */}
{hasItems && isPending && (
<div className="px-3 pb-1">
<OrderDiscountButton
subtotal={subtotal}
onApply={(amount, reason) => {
const pct = subtotal > 0 ? (amount / subtotal) * 100 : 0
if (requiresDiscountOverride(pct)) {
setPendingDiscount({ lineItemId: lineItems[0].id, amount, reason })
setDiscountOverrideOpen(true)
} else {
discountMutation.mutate({ lineItemId: lineItems[0].id, amount, reason })
}
}}
isPending={discountMutation.isPending}
/>
</div>
)}
{/* Payment buttons */}
<div className="p-3 space-y-2">
{!drawerOpen && hasItems && (
@@ -183,7 +250,13 @@ export function POSCartPanel({ transaction }: POSCartPanelProps) {
variant="destructive"
className="h-12 text-sm gap-2"
disabled={!hasItems || !isPending}
onClick={() => voidMutation.mutate()}
onClick={() => {
if (requiresOverride('void_transaction')) {
setOverrideOpen(true)
} else {
voidMutation.mutate()
}
}}
>
<Ban className="h-4 w-4" />
Void
@@ -205,6 +278,220 @@ export function POSCartPanel({ transaction }: POSCartPanelProps) {
{/* Customer dialog */}
<POSCustomerDialog open={customerOpen} onOpenChange={setCustomerOpen} />
{/* Manager override for void */}
<ManagerOverrideDialog
open={overrideOpen}
onOpenChange={setOverrideOpen}
action="Void transaction"
onAuthorized={() => voidMutation.mutate()}
/>
{/* Manager override for discount */}
<ManagerOverrideDialog
open={discountOverrideOpen}
onOpenChange={setDiscountOverrideOpen}
action="Price adjustment"
onAuthorized={() => {
if (pendingDiscount) {
discountMutation.mutate(pendingDiscount)
setPendingDiscount(null)
}
}}
/>
</div>
)
}
// --- Order Discount Button ---
function OrderDiscountButton({ subtotal, onApply, isPending }: {
subtotal: number
onApply: (amount: number, reason: string) => void
isPending: boolean
}) {
const [open, setOpen] = useState(false)
const [mode, setMode] = useState<AdjustMode>('percent')
const [value, setValue] = useState('')
function calculate() {
const v = parseFloat(value) || 0
if (mode === 'amount_off') return Math.min(v, subtotal)
if (mode === 'set_price') return Math.max(0, subtotal - v)
return Math.round(subtotal * (v / 100) * 100) / 100
}
const discountAmount = calculate()
function handleApply() {
if (discountAmount <= 0) return
const reason = mode === 'percent' ? `${parseFloat(value)}% order discount` : mode === 'set_price' ? `Order total set to $${parseFloat(value).toFixed(2)}` : `$${parseFloat(value).toFixed(2)} order discount`
onApply(discountAmount, reason)
setValue('')
setOpen(false)
}
return (
<Popover open={open} onOpenChange={(o) => { setOpen(o); if (!o) setValue('') }}>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="w-full gap-2 text-xs h-8">
<Tag className="h-3 w-3" />Order Discount
</Button>
</PopoverTrigger>
<PopoverContent className="w-64 p-3" side="top" align="center">
<div className="space-y-3">
<div className="text-xs text-muted-foreground">
Subtotal: <span className="font-medium text-foreground">${subtotal.toFixed(2)}</span>
</div>
<div className="flex rounded-md border overflow-hidden text-xs">
{([
{ key: 'percent' as const, label: '% Off' },
{ key: 'amount_off' as const, label: '$ Off' },
{ key: 'set_price' as const, label: 'Set Total' },
]).map((m) => (
<button
key={m.key}
type="button"
className={`flex-1 py-1.5 transition-colors ${mode === m.key ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}
onClick={() => { setMode(m.key); setValue('') }}
>
{m.label}
</button>
))}
</div>
<Input
type="number"
step="0.01"
min="0"
placeholder={mode === 'percent' ? 'e.g. 10' : '0.00'}
value={value}
onChange={(e) => setValue(e.target.value)}
className="h-9"
autoFocus
onKeyDown={(e) => { if (e.key === 'Enter') handleApply() }}
/>
{value && discountAmount > 0 && (
<div className="text-xs flex justify-between font-medium">
<span className="text-green-600">-${discountAmount.toFixed(2)}</span>
<span>New total: ${(subtotal - discountAmount).toFixed(2)}</span>
</div>
)}
<Button size="sm" className="w-full" onClick={handleApply} disabled={isPending || discountAmount <= 0}>
{isPending ? 'Applying...' : 'Apply Discount'}
</Button>
</div>
</PopoverContent>
</Popover>
)
}
// --- Price Adjuster Popover ---
type AdjustMode = 'amount_off' | 'set_price' | 'percent'
function PriceAdjuster({ item, open, onOpenChange, onApply, isPending }: {
item: TransactionLineItem
open: boolean
onOpenChange: (open: boolean) => void
onApply: (amount: number, reason: string) => void
isPending: boolean
}) {
const [mode, setMode] = useState<AdjustMode>('percent')
const [value, setValue] = useState('')
const unitPrice = parseFloat(item.unitPrice)
const listTotal = unitPrice * item.qty
function calculate(): { discountAmount: number; salePrice: number; pct: number } {
const v = parseFloat(value) || 0
if (mode === 'amount_off') {
const d = Math.min(v, listTotal)
return { discountAmount: d, salePrice: listTotal - d, pct: listTotal > 0 ? (d / listTotal) * 100 : 0 }
}
if (mode === 'set_price') {
const d = Math.max(0, listTotal - v)
return { discountAmount: d, salePrice: v, pct: listTotal > 0 ? (d / listTotal) * 100 : 0 }
}
// percent
const d = Math.round(listTotal * (v / 100) * 100) / 100
return { discountAmount: d, salePrice: listTotal - d, pct: v }
}
const calc = calculate()
function handleApply() {
if (calc.discountAmount <= 0) return
const reason = mode === 'percent' ? `${parseFloat(value)}% off` : mode === 'set_price' ? `Price set to $${parseFloat(value).toFixed(2)}` : `$${parseFloat(value).toFixed(2)} off`
onApply(calc.discountAmount, reason)
setValue('')
}
return (
<Popover open={open} onOpenChange={(o) => { onOpenChange(o); if (!o) setValue('') }}>
<PopoverTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8">
<Tag className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-64 p-3" side="left" align="start">
<div className="space-y-3">
<div className="text-xs text-muted-foreground">
List: <span className="font-medium text-foreground">${listTotal.toFixed(2)}</span>
</div>
{/* Mode tabs */}
<div className="flex rounded-md border overflow-hidden text-xs">
{([
{ key: 'percent' as const, label: '% Off' },
{ key: 'amount_off' as const, label: '$ Off' },
{ key: 'set_price' as const, label: 'Set Price' },
]).map((m) => (
<button
key={m.key}
type="button"
className={`flex-1 py-1.5 transition-colors ${mode === m.key ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'}`}
onClick={() => { setMode(m.key); setValue('') }}
>
{m.label}
</button>
))}
</div>
<Input
type="number"
step="0.01"
min="0"
placeholder={mode === 'percent' ? 'e.g. 10' : '0.00'}
value={value}
onChange={(e) => setValue(e.target.value)}
className="h-9"
autoFocus
onKeyDown={(e) => { if (e.key === 'Enter') handleApply() }}
/>
{value && parseFloat(value) > 0 && (
<div className="text-xs space-y-0.5">
<div className="flex justify-between">
<span className="text-muted-foreground">Discount</span>
<span className="text-green-600">-${calc.discountAmount.toFixed(2)} ({calc.pct.toFixed(0)}%)</span>
</div>
<div className="flex justify-between font-medium">
<span>Sale Price</span>
<span>${calc.salePrice.toFixed(2)}</span>
</div>
</div>
)}
<Button
size="sm"
className="w-full"
onClick={handleApply}
disabled={isPending || !value || calc.discountAmount <= 0}
>
{isPending ? 'Applying...' : 'Apply'}
</Button>
</div>
</PopoverContent>
</Popover>
)
}

View File

@@ -10,6 +10,7 @@ import { Separator } from '@/components/ui/separator'
import { Badge } from '@/components/ui/badge'
import { ArrowDownToLine, ArrowUpFromLine } from 'lucide-react'
import { toast } from 'sonner'
import { ManagerOverrideDialog, requiresOverride } from './pos-manager-override'
interface POSDrawerDialogProps {
open: boolean
@@ -28,6 +29,8 @@ export function POSDrawerDialog({ open, onOpenChange, drawer }: POSDrawerDialogP
const [adjustView, setAdjustView] = useState<'cash_in' | 'cash_out' | null>(null)
const [adjAmount, setAdjAmount] = useState('')
const [adjReason, setAdjReason] = useState('')
const [overrideOpen, setOverrideOpen] = useState(false)
const [pendingAdjustView, setPendingAdjustView] = useState<'cash_in' | 'cash_out' | null>(null)
// Fetch adjustments for open drawer
const { data: adjData } = useQuery({
@@ -93,6 +96,7 @@ export function POSDrawerDialog({ open, onOpenChange, drawer }: POSDrawerDialogP
if (adjustView && isOpen) {
const isCashIn = adjustView === 'cash_in'
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-sm">
<DialogHeader>
@@ -136,10 +140,12 @@ export function POSDrawerDialog({ open, onOpenChange, drawer }: POSDrawerDialogP
</div>
</DialogContent>
</Dialog>
</>
)
}
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-sm">
<DialogHeader>
@@ -164,7 +170,14 @@ export function POSDrawerDialog({ open, onOpenChange, drawer }: POSDrawerDialogP
<Button
variant="outline"
className="h-11 gap-2"
onClick={() => setAdjustView('cash_in')}
onClick={() => {
if (requiresOverride('cash_in_out')) {
setPendingAdjustView('cash_in')
setOverrideOpen(true)
} else {
setAdjustView('cash_in')
}
}}
>
<ArrowDownToLine className="h-4 w-4 text-green-600" />
Cash In
@@ -172,7 +185,14 @@ export function POSDrawerDialog({ open, onOpenChange, drawer }: POSDrawerDialogP
<Button
variant="outline"
className="h-11 gap-2"
onClick={() => setAdjustView('cash_out')}
onClick={() => {
if (requiresOverride('cash_in_out')) {
setPendingAdjustView('cash_out')
setOverrideOpen(true)
} else {
setAdjustView('cash_out')
}
}}
>
<ArrowUpFromLine className="h-4 w-4 text-red-600" />
Cash Out
@@ -260,5 +280,16 @@ export function POSDrawerDialog({ open, onOpenChange, drawer }: POSDrawerDialogP
)}
</DialogContent>
</Dialog>
<ManagerOverrideDialog
open={overrideOpen}
onOpenChange={setOverrideOpen}
action={pendingAdjustView === 'cash_in' ? 'Cash In' : 'Cash Out'}
onAuthorized={() => {
if (pendingAdjustView) setAdjustView(pendingAdjustView)
setPendingAdjustView(null)
}}
/>
</>
)
}

View File

@@ -10,6 +10,7 @@ import { Skeleton } from '@/components/ui/skeleton'
import { Search, ScanBarcode, Wrench, PenLine, ClipboardList } from 'lucide-react'
import { toast } from 'sonner'
import { POSTransactionsDialog } from './pos-transactions-dialog'
import { POSRepairDialog } from './pos-repair-dialog'
interface POSItemPanelProps {
transaction: Transaction | null
@@ -21,6 +22,7 @@ export function POSItemPanel({ transaction: _transaction }: POSItemPanelProps) {
const [search, setSearch] = useState('')
const [customOpen, setCustomOpen] = useState(false)
const [txnDialogOpen, setTxnDialogOpen] = useState(false)
const [repairOpen, setRepairOpen] = useState(false)
const [customDesc, setCustomDesc] = useState('')
const [customPrice, setCustomPrice] = useState('')
const [customQty, setCustomQty] = useState('1')
@@ -200,7 +202,7 @@ export function POSItemPanel({ transaction: _transaction }: POSItemPanelProps) {
<Button
variant="outline"
className="flex-1 h-11 text-sm gap-2"
disabled
onClick={() => setRepairOpen(true)}
>
<Wrench className="h-4 w-4" />
Repairs
@@ -277,6 +279,7 @@ export function POSItemPanel({ transaction: _transaction }: POSItemPanelProps) {
{/* Transactions dialog */}
<POSTransactionsDialog open={txnDialogOpen} onOpenChange={setTxnDialogOpen} />
<POSRepairDialog open={repairOpen} onOpenChange={setRepairOpen} />
</div>
)
}

View File

@@ -0,0 +1,199 @@
import { useState, useCallback, useEffect, useRef } from 'react'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { api } from '@/lib/api-client'
import { Delete, ShieldCheck } from 'lucide-react'
interface ManagerOverrideDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
action: string
onAuthorized: () => void
}
interface PinUser {
id: string
role: string
firstName: string
lastName: string
}
export function ManagerOverrideDialog({ open, onOpenChange, action, onAuthorized }: ManagerOverrideDialogProps) {
const [code, setCode] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (open) {
setCode('')
setError('')
containerRef.current?.focus()
}
}, [open])
const handleDigit = useCallback((digit: string) => {
setError('')
setCode((p) => (p.length >= 10 ? p : p + digit))
}, [])
const handleBackspace = useCallback(() => {
setError('')
setCode((p) => p.slice(0, -1))
}, [])
const handleClear = useCallback(() => {
setError('')
setCode('')
}, [])
const handleSubmit = useCallback(async (submitCode: string) => {
if (submitCode.length < 8) {
setError('Enter manager employee # + PIN')
return
}
setLoading(true)
setError('')
try {
const res = await api.post<{ user: PinUser; token: string }>('/v1/auth/pin-login', { code: submitCode })
if (res.user.role === 'admin' || res.user.role === 'manager') {
onAuthorized()
onOpenChange(false)
} else {
setError('Manager or admin access required')
setCode('')
}
} catch {
setError('Invalid code')
setCode('')
} finally {
setLoading(false)
}
}, [onAuthorized, onOpenChange])
useEffect(() => {
if (code.length === 8) {
handleSubmit(code)
}
}, [code, handleSubmit])
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key >= '0' && e.key <= '9') handleDigit(e.key)
else if (e.key === 'Backspace') handleBackspace()
else if (e.key === 'Enter' && code.length >= 8) handleSubmit(code)
else if (e.key === 'Escape') handleClear()
}, [handleDigit, handleBackspace, handleSubmit, handleClear, code])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-xs">
<div
ref={containerRef}
onKeyDown={handleKeyDown}
tabIndex={0}
className="outline-none space-y-4"
>
<div className="text-center space-y-1">
<ShieldCheck className="h-8 w-8 mx-auto text-amber-500" />
<DialogTitle className="text-base">Manager Override</DialogTitle>
<p className="text-xs text-muted-foreground">{action}</p>
</div>
{/* Code dots */}
<div className="flex justify-center items-center gap-2">
<div className="flex gap-1.5">
{Array.from({ length: 4 }).map((_, i) => (
<div
key={`e${i}`}
className={`w-3 h-3 rounded-full border-2 ${
i < Math.min(code.length, 4) ? 'bg-foreground border-foreground' : 'border-muted-foreground/30'
}`}
/>
))}
</div>
<span className="text-muted-foreground/40">-</span>
<div className="flex gap-1.5">
{Array.from({ length: 4 }).map((_, i) => (
<div
key={`p${i}`}
className={`w-3 h-3 rounded-full border-2 ${
i < Math.max(0, code.length - 4) ? 'bg-foreground border-foreground' : 'border-muted-foreground/30'
}`}
/>
))}
</div>
</div>
{error && <p className="text-xs text-destructive text-center">{error}</p>}
{/* Numpad */}
<div className="grid grid-cols-3 gap-1.5">
{['1', '2', '3', '4', '5', '6', '7', '8', '9'].map((d) => (
<Button key={d} variant="outline" className="h-12 text-lg font-medium" onClick={() => handleDigit(d)} disabled={loading}>
{d}
</Button>
))}
<Button variant="outline" className="h-12 text-xs" onClick={handleClear} disabled={loading}>Clear</Button>
<Button variant="outline" className="h-12 text-lg font-medium" onClick={() => handleDigit('0')} disabled={loading}>0</Button>
<Button variant="outline" className="h-12" onClick={handleBackspace} disabled={loading}>
<Delete className="h-4 w-4" />
</Button>
</div>
{loading && <p className="text-xs text-muted-foreground text-center">Verifying...</p>}
</div>
</DialogContent>
</Dialog>
)
}
// --- Config types & helpers ---
export const OVERRIDE_ACTIONS = [
{ key: 'void_transaction', label: 'Void Transaction', description: 'Cancel an in-progress sale' },
{ key: 'refund', label: 'Refund', description: 'Process a return or refund' },
{ key: 'manual_discount', label: 'Manual Discount', description: 'Apply a discount not from a preset' },
{ key: 'price_override', label: 'Price Override', description: 'Change an item price at the register' },
{ key: 'no_sale_drawer', label: 'No-Sale Drawer Open', description: 'Open the drawer without a transaction' },
{ key: 'cash_in_out', label: 'Cash In / Cash Out', description: 'Add or remove cash from the drawer' },
] as const
export type OverrideAction = typeof OVERRIDE_ACTIONS[number]['key']
const STORAGE_KEY = 'pos_manager_overrides'
export function getRequiredOverrides(): Set<OverrideAction> {
try {
const stored = localStorage.getItem(STORAGE_KEY)
if (!stored) return new Set()
return new Set(JSON.parse(stored) as OverrideAction[])
} catch {
return new Set()
}
}
export function setRequiredOverrides(actions: Set<OverrideAction>) {
localStorage.setItem(STORAGE_KEY, JSON.stringify([...actions]))
}
export function requiresOverride(action: OverrideAction): boolean {
return getRequiredOverrides().has(action)
}
// Discount threshold — discounts above this percentage require manager override
const DISCOUNT_THRESHOLD_KEY = 'pos_discount_threshold_pct'
export function getDiscountThreshold(): number {
const stored = localStorage.getItem(DISCOUNT_THRESHOLD_KEY)
return stored ? parseInt(stored, 10) : 0 // 0 = disabled
}
export function setDiscountThreshold(pct: number) {
localStorage.setItem(DISCOUNT_THRESHOLD_KEY, String(pct))
}
export function requiresDiscountOverride(discountPct: number): boolean {
const threshold = getDiscountThreshold()
if (threshold <= 0) return requiresOverride('manual_discount')
return discountPct >= threshold
}

View File

@@ -71,6 +71,7 @@ export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transactio
queryFn: () => api.get<{ data: AppConfigEntry[] }>('/v1/config'),
enabled: !!result?.id,
})
const receiptFormat = usePOSStore((s) => s.receiptFormat)
const receiptConfig = {
header: configData?.data?.find((c) => c.key === 'receipt_header')?.value || undefined,
footer: configData?.data?.find((c) => c.key === 'receipt_footer')?.value || undefined,
@@ -98,11 +99,11 @@ export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transactio
if (showReceipt && receiptData) {
return (
<Dialog open={open} onOpenChange={() => { setShowReceipt(false); handleDone() }}>
<DialogContent className="max-w-sm max-h-[90vh] overflow-y-auto print:max-w-none print:max-h-none print:overflow-visible print:shadow-none print:border-none">
<DialogContent className={`${receiptFormat === 'full' ? 'max-w-2xl' : 'max-w-sm'} max-h-[90vh] overflow-y-auto print:max-w-none print:max-h-none print:overflow-visible print:shadow-none print:border-none`}>
<div className="flex justify-between items-center mb-2">
<Button variant="ghost" size="sm" onClick={() => setShowReceipt(false)}>Back</Button>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => downloadReceiptPDF(result.transactionNumber)} className="gap-2">
<Button variant="outline" size="sm" onClick={() => downloadReceiptPDF(result.transactionNumber, receiptFormat)} className="gap-2">
Save PDF
</Button>
<Button size="sm" onClick={printReceipt} className="gap-2">
@@ -111,7 +112,7 @@ export function POSPaymentDialog({ open, onOpenChange, paymentMethod, transactio
</div>
</div>
<div id="pos-receipt-print">
<POSReceipt data={receiptData} config={receiptConfig} />
<POSReceipt data={receiptData} size={receiptFormat} config={receiptConfig} />
</div>
</DialogContent>
</Dialog>

View File

@@ -100,23 +100,28 @@ function useStoreLogo(companyId?: string) {
}
export function POSReceipt({ data, size = 'thermal', footerText, config }: POSReceiptProps) {
const barcodeRef = useRef<SVGSVGElement>(null)
const { transaction: txn, company, location } = data
const isThermal = size === 'thermal'
if (!isThermal) {
return <FullPageReceipt data={data} config={config} footerText={footerText} />
}
return <ThermalReceipt data={data} config={config} footerText={footerText} />
}
function ThermalReceipt({ data, config, footerText }: { data: POSReceiptProps['data']; config?: ReceiptConfig; footerText?: string }) {
const barcodeRef = useRef<SVGSVGElement>(null)
const { transaction: txn, company, location } = data
const logoSrc = useStoreLogo()
useEffect(() => {
if (barcodeRef.current) {
JsBarcode(barcodeRef.current, txn.transactionNumber, {
format: 'CODE128',
width: isThermal ? 1.5 : 2,
height: isThermal ? 40 : 50,
displayValue: true,
fontSize: isThermal ? 10 : 12,
margin: 4,
format: 'CODE128', width: 1.5, height: 40, displayValue: true, fontSize: 10, margin: 4,
})
}
}, [txn.transactionNumber, isThermal])
}, [txn.transactionNumber])
const date = new Date(txn.completedAt ?? txn.createdAt)
const subtotal = parseFloat(txn.subtotal)
@@ -143,16 +148,14 @@ export function POSReceipt({ data, size = 'thermal', footerText, config }: POSRe
return (
<div style={{
background: '#fff', color: '#000', fontFamily: 'monospace',
width: isThermal ? 260 : '100%', maxWidth: isThermal ? 260 : 480,
fontSize: isThermal ? 10 : 14, lineHeight: isThermal ? '1.3' : '1.6',
margin: '0 auto',
width: 260, maxWidth: 260, fontSize: 10, lineHeight: '1.3', margin: '0 auto',
}}>
{/* Store header */}
<div style={{ ...s.section, ...s.center }}>
{logoSrc ? (
<img src={logoSrc} alt={company.name} style={{ display: 'block', margin: '0 auto 4px', maxHeight: isThermal ? 48 : 64, maxWidth: isThermal ? 200 : 280, objectFit: 'contain' }} />
<img src={logoSrc} alt={company.name} style={{ display: 'block', margin: '0 auto 4px', maxHeight: 48, maxWidth: 200, objectFit: 'contain' }} />
) : (
<div style={{ ...s.bold, fontSize: isThermal ? 14 : 18 }}>{company.name}</div>
<div style={{ ...s.bold, fontSize: 14 }}>{company.name}</div>
)}
{location.name !== company.name && <div style={s.gray}>{location.name}</div>}
{addr?.street && <div>{addr.street}</div>}
@@ -205,7 +208,7 @@ export function POSReceipt({ data, size = 'thermal', footerText, config }: POSRe
{rounding !== 0 && (
<div style={{ ...s.row, ...s.gray }}><span>Rounding</span><span style={s.nums}>{rounding > 0 ? '+' : ''}{rounding.toFixed(2)}</span></div>
)}
<div style={{ ...s.row, ...s.bold, fontSize: isThermal ? 14 : 16, paddingTop: 4 }}>
<div style={{ ...s.row, ...s.bold, fontSize: 14, paddingTop: 4 }}>
<span>TOTAL</span><span style={s.nums}>${total.toFixed(2)}</span>
</div>
</div>
@@ -240,6 +243,152 @@ export function POSReceipt({ data, size = 'thermal', footerText, config }: POSRe
)
}
function FullPageReceipt({ data, config, footerText }: { data: POSReceiptProps['data']; config?: ReceiptConfig; footerText?: string }) {
const barcodeRef = useRef<SVGSVGElement>(null)
const { transaction: txn, company, location } = data
const logoSrc = useStoreLogo()
useEffect(() => {
if (barcodeRef.current) {
JsBarcode(barcodeRef.current, txn.transactionNumber, {
format: 'CODE128', width: 2, height: 50, displayValue: true, fontSize: 12, margin: 4,
})
}
}, [txn.transactionNumber])
const date = new Date(txn.completedAt ?? txn.createdAt)
const subtotal = parseFloat(txn.subtotal)
const discountTotal = parseFloat(txn.discountTotal)
const taxTotal = parseFloat(txn.taxTotal)
const total = parseFloat(txn.total)
const rounding = parseFloat(txn.roundingAdjustment)
const tendered = txn.amountTendered ? parseFloat(txn.amountTendered) : null
const change = txn.changeGiven ? parseFloat(txn.changeGiven) : null
const addr = location.address ?? company.address
const phone = location.phone ?? company.phone
const email = location.email ?? company.email
const f = (n: number) => `$${n.toFixed(2)}`
return (
<div style={{
background: '#fff', color: '#000', fontFamily: 'Helvetica, Arial, sans-serif',
width: '100%', maxWidth: 600, margin: '0 auto', fontSize: 13, lineHeight: '1.5',
}}>
{/* Header — company left, transaction right */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', paddingBottom: 16 }}>
<div>
{logoSrc ? (
<img src={logoSrc} alt={company.name} style={{ maxHeight: 56, maxWidth: 200, objectFit: 'contain', marginBottom: 4 }} />
) : (
<div style={{ fontSize: 20, fontWeight: 'bold' }}>{company.name}</div>
)}
{location.name !== company.name && <div style={{ color: '#555', fontSize: 12 }}>{location.name}</div>}
{addr?.street && <div style={{ fontSize: 12 }}>{addr.street}</div>}
{(addr?.city || addr?.state || addr?.zip) && (
<div style={{ fontSize: 12 }}>{[addr?.city, addr?.state].filter(Boolean).join(', ')} {addr?.zip}</div>
)}
{phone && <div style={{ fontSize: 12 }}>{phone}</div>}
{email && <div style={{ fontSize: 12 }}>{email}</div>}
{config?.header && <div style={{ fontSize: 12, color: '#555', marginTop: 2 }}>{config.header}</div>}
</div>
<div style={{ textAlign: 'right' }}>
<div style={{ fontSize: 16, fontWeight: 'bold' }}>{txn.transactionNumber}</div>
<div style={{ fontSize: 12, color: '#555', textTransform: 'capitalize' }}>{txn.transactionType.replace('_', ' ')}</div>
<div style={{ fontSize: 12, color: '#555' }}>{date.toLocaleDateString()}</div>
<div style={{ fontSize: 12, color: '#555' }}>{date.toLocaleTimeString()}</div>
</div>
</div>
{/* Divider */}
<div style={{ borderBottom: '1px solid #ddd', marginBottom: 16 }} />
{/* Line items table */}
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ background: '#f5f5f5' }}>
<th style={{ textAlign: 'left', padding: '6px 8px', fontWeight: 600, fontSize: 11, textTransform: 'uppercase', color: '#555' }}>Item</th>
<th style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 600, fontSize: 11, textTransform: 'uppercase', color: '#555', width: 50 }}>Qty</th>
<th style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 600, fontSize: 11, textTransform: 'uppercase', color: '#555', width: 80 }}>Price</th>
<th style={{ textAlign: 'right', padding: '6px 8px', fontWeight: 600, fontSize: 11, textTransform: 'uppercase', color: '#555', width: 80 }}>Total</th>
</tr>
</thead>
<tbody>
{txn.lineItems.map((item, i) => (
<tr key={i} style={{ borderBottom: '1px solid #eee' }}>
<td style={{ padding: '6px 8px' }}>
{item.description}
{parseFloat(item.discountAmount ?? '0') > 0 && (
<div style={{ fontSize: 11, color: '#999' }}>Discount: -{f(parseFloat(item.discountAmount!))}</div>
)}
</td>
<td style={{ padding: '6px 8px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{item.qty}</td>
<td style={{ padding: '6px 8px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{f(parseFloat(item.unitPrice))}</td>
<td style={{ padding: '6px 8px', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{f(parseFloat(item.lineTotal))}</td>
</tr>
))}
</tbody>
</table>
{/* Totals — right aligned */}
<div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12 }}>
<div style={{ width: 220 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0' }}>
<span>Subtotal</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(subtotal)}</span>
</div>
{discountTotal > 0 && (
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0', color: '#555' }}>
<span>Discount</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>-{f(discountTotal)}</span>
</div>
)}
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0' }}>
<span>Tax</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(taxTotal)}</span>
</div>
{rounding !== 0 && (
<div style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0', color: '#888', fontSize: 12 }}>
<span>Rounding</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{rounding > 0 ? '+' : ''}{rounding.toFixed(2)}</span>
</div>
)}
<div style={{ borderTop: '1px solid #ddd', marginTop: 4, paddingTop: 6, display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', fontSize: 16 }}>
<span>Total</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(total)}</span>
</div>
</div>
</div>
{/* Payment info */}
<div style={{ marginTop: 16, padding: '12px 0', borderTop: '1px solid #ddd' }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span>Payment Method</span>
<span style={{ textTransform: 'capitalize', fontWeight: 500 }}>{txn.paymentMethod?.replace('_', ' ') ?? 'N/A'}</span>
</div>
{tendered !== null && (
<div style={{ display: 'flex', justifyContent: 'space-between', color: '#555', fontSize: 12, marginTop: 2 }}>
<span>Tendered</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(tendered)}</span>
</div>
)}
{change !== null && change > 0 && (
<div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 'bold', marginTop: 2 }}>
<span>Change</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{f(change)}</span>
</div>
)}
</div>
{/* Barcode */}
<div style={{ display: 'flex', justifyContent: 'center', padding: '16px 0' }}>
<svg ref={barcodeRef} />
</div>
{/* Footer */}
<div style={{ borderTop: '1px solid #eee', paddingTop: 12, textAlign: 'center', fontSize: 11, color: '#999' }}>
{(config?.footer || footerText) && <div>{config?.footer || footerText}</div>}
{config?.returnPolicy && <div style={{ marginTop: 4 }}>{config.returnPolicy}</div>}
{config?.social && <div style={{ marginTop: 4 }}>{config.social}</div>}
</div>
</div>
)
}
export function printReceipt() {
const el = document.getElementById('pos-receipt-print')
if (!el) return
@@ -269,23 +418,36 @@ export function printReceipt() {
}, 300)
}
export async function downloadReceiptPDF(txnNumber?: string) {
export async function downloadReceiptPDF(txnNumber?: string, format: 'thermal' | 'full' = 'thermal') {
const el = document.getElementById('pos-receipt-print')
if (!el) return
// Calculate height from actual content
const heightPx = el.scrollHeight + 16 // 16px padding
const heightMm = Math.ceil(heightPx * 0.265) + 8 // px to mm + margin
const html2pdf = (await import('html2pdf.js')).default
html2pdf()
.set({
margin: [2, 2, 2, 2],
filename: `receipt-${txnNumber ?? 'unknown'}.pdf`,
image: { type: 'jpeg', quality: 0.95 },
html2canvas: { scale: 2, useCORS: true, width: 280 },
jsPDF: { unit: 'mm', format: [72, heightMm], orientation: 'portrait' },
})
.from(el)
.save()
if (format === 'full') {
html2pdf()
.set({
margin: [10, 10, 10, 10],
filename: `receipt-${txnNumber ?? 'unknown'}.pdf`,
image: { type: 'jpeg', quality: 0.95 },
html2canvas: { scale: 2, useCORS: true },
jsPDF: { unit: 'mm', format: 'letter', orientation: 'portrait' },
})
.from(el)
.save()
} else {
// Thermal — dynamic height based on content
const heightPx = el.scrollHeight + 16
const heightMm = Math.ceil(heightPx * 0.265) + 8
html2pdf()
.set({
margin: [2, 2, 2, 2],
filename: `receipt-${txnNumber ?? 'unknown'}.pdf`,
image: { type: 'jpeg', quality: 0.95 },
html2canvas: { scale: 2, useCORS: true, width: 280 },
jsPDF: { unit: 'mm', format: [72, heightMm], orientation: 'portrait' },
})
.from(el)
.save()
}
}

View File

@@ -0,0 +1,263 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { usePOSStore } from '@/stores/pos.store'
import { api } from '@/lib/api-client'
import { posMutations, posKeys } from '@/api/pos'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Search, Wrench, Plus } from 'lucide-react'
import { toast } from 'sonner'
interface Account {
id: string
name: string
email: string | null
phone: string | null
accountNumber: string | null
}
interface RepairTicketSummary {
id: string
ticketNumber: string | null
customerName: string
customerPhone: string | null
itemDescription: string | null
estimatedCost: string | null
status: string
}
interface POSRepairDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
}
export function POSRepairDialog({ open, onOpenChange }: POSRepairDialogProps) {
const queryClient = useQueryClient()
const { locationId, setTransaction, setAccount } = usePOSStore()
const [search, setSearch] = useState('')
const [tab, setTab] = useState('pickup')
// --- Pickup tab ---
const { data, isLoading } = useQuery({
queryKey: ['pos', 'repair-tickets-ready', search],
queryFn: () => api.get<{ data: RepairTicketSummary[] }>('/v1/repair-tickets/ready', { q: search || undefined, limit: 20 }),
enabled: open && tab === 'pickup',
})
const tickets = data?.data ?? []
const pickupMutation = useMutation({
mutationFn: (ticketId: string) => posMutations.createFromRepair(ticketId, locationId ?? undefined),
onSuccess: (txn) => {
setTransaction(txn.id)
if (txn.accountId) {
const ticket = tickets.find((t) => t.id === pickupMutation.variables)
if (ticket) setAccount(txn.accountId, ticket.customerName, ticket.customerPhone)
}
queryClient.invalidateQueries({ queryKey: posKeys.transaction(txn.id) })
toast.success(`Repair payment loaded — ${txn.transactionNumber}`)
close()
},
onError: (err) => toast.error(err.message),
})
// --- New intake tab ---
const [customerName, setCustomerName] = useState('')
const [customerPhone, setCustomerPhone] = useState('')
const [itemDescription, setItemDescription] = useState('')
const [problemDescription, setProblemDescription] = useState('')
const [estimatedCost, setEstimatedCost] = useState('')
const [accountId, setAccountId] = useState<string | null>(null)
const [customerSearch, setCustomerSearch] = useState('')
const [showCustomers, setShowCustomers] = useState(false)
const { data: customerData } = useQuery({
queryKey: ['pos', 'accounts', customerSearch],
queryFn: () => api.get<{ data: Account[] }>('/v1/accounts', { q: customerSearch, limit: 10 }),
enabled: customerSearch.length >= 2 && tab === 'intake',
})
const customerResults = customerData?.data ?? []
function selectCustomer(account: Account) {
setAccountId(account.id)
setCustomerName(account.name)
setCustomerPhone(account.phone ?? '')
setCustomerSearch('')
setShowCustomers(false)
}
function clearCustomer() {
setAccountId(null)
setCustomerName('')
setCustomerPhone('')
}
const intakeMutation = useMutation({
mutationFn: (data: Record<string, unknown>) =>
api.post<{ id: string; ticketNumber: string }>('/v1/repair-tickets', data),
onSuccess: (ticket) => {
toast.success(`Repair ticket #${ticket.ticketNumber} created`)
close()
},
onError: (err) => toast.error(err.message),
})
function handleIntakeSubmit(e: React.FormEvent) {
e.preventDefault()
intakeMutation.mutate({
customerName,
customerPhone: customerPhone || undefined,
accountId: accountId ?? undefined,
itemDescription: itemDescription || undefined,
problemDescription,
estimatedCost: estimatedCost ? parseFloat(estimatedCost) : undefined,
locationId: locationId ?? undefined,
})
}
function close() {
onOpenChange(false)
setSearch('')
setCustomerName('')
setCustomerPhone('')
setItemDescription('')
setProblemDescription('')
setEstimatedCost('')
setAccountId(null)
setCustomerSearch('')
setShowCustomers(false)
}
return (
<Dialog open={open} onOpenChange={(o) => { if (!o) close(); else onOpenChange(true) }}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wrench className="h-5 w-5" />Repairs
</DialogTitle>
</DialogHeader>
<Tabs value={tab} onValueChange={setTab}>
<TabsList className="w-full">
<TabsTrigger value="pickup" className="flex-1">Pickup</TabsTrigger>
<TabsTrigger value="intake" className="flex-1">New Intake</TabsTrigger>
</TabsList>
<TabsContent value="pickup" className="mt-3 space-y-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search by ticket #, name, or phone..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-9"
autoFocus={tab === 'pickup'}
/>
</div>
<div className="max-h-64 overflow-y-auto space-y-1">
{isLoading ? (
<p className="text-sm text-muted-foreground text-center py-4">Loading...</p>
) : tickets.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">
{search ? 'No ready tickets found' : 'No tickets ready for pickup'}
</p>
) : (
tickets.map((ticket) => (
<button
key={ticket.id}
type="button"
className="w-full text-left rounded-md border p-3 hover:bg-accent transition-colors"
onClick={() => pickupMutation.mutate(ticket.id)}
disabled={pickupMutation.isPending}
>
<div className="flex items-center justify-between">
<span className="font-medium text-sm">#{ticket.ticketNumber}</span>
<Badge variant="outline" className="text-xs">Ready</Badge>
</div>
<div className="text-sm mt-0.5">{ticket.customerName}</div>
{ticket.itemDescription && (
<div className="text-xs text-muted-foreground mt-0.5 truncate">{ticket.itemDescription}</div>
)}
{ticket.estimatedCost && (
<div className="text-xs text-muted-foreground mt-0.5">Est: ${ticket.estimatedCost}</div>
)}
</button>
))
)}
</div>
</TabsContent>
<TabsContent value="intake" className="mt-3">
<form onSubmit={handleIntakeSubmit} className="space-y-3">
{/* Customer lookup */}
<div className="relative space-y-1">
<Label className="text-xs">Customer Lookup</Label>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
<Input
placeholder="Search by name, phone, or email..."
value={customerSearch}
onChange={(e) => { setCustomerSearch(e.target.value); setShowCustomers(true) }}
onFocus={() => customerSearch.length >= 2 && setShowCustomers(true)}
className="pl-9 h-8 text-sm"
/>
</div>
{accountId && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Badge variant="secondary" className="text-[10px]">Linked</Badge>
<span>{customerName}</span>
<button type="button" className="underline text-destructive ml-1" onClick={clearCustomer}>clear</button>
</div>
)}
{showCustomers && customerSearch.length >= 2 && (
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-40 overflow-auto">
{customerResults.length === 0 ? (
<div className="p-2 text-xs text-muted-foreground">No accounts found</div>
) : customerResults.map((a) => (
<button key={a.id} type="button" className="w-full text-left px-3 py-2 text-sm hover:bg-accent" onClick={() => selectCustomer(a)}>
<div className="font-medium">{a.name}</div>
<div className="text-xs text-muted-foreground">{[a.phone, a.email].filter(Boolean).join(' · ')}</div>
</button>
))}
</div>
)}
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label className="text-xs">Customer Name *</Label>
<Input value={customerName} onChange={(e) => setCustomerName(e.target.value)} required />
</div>
<div className="space-y-1">
<Label className="text-xs">Phone</Label>
<Input value={customerPhone} onChange={(e) => setCustomerPhone(e.target.value)} />
</div>
</div>
<div className="space-y-1">
<Label className="text-xs">Item Description</Label>
<Input value={itemDescription} onChange={(e) => setItemDescription(e.target.value)} placeholder="e.g. Violin, iPhone 12, Trek bicycle" />
</div>
<div className="space-y-1">
<Label className="text-xs">Problem *</Label>
<Textarea value={problemDescription} onChange={(e) => setProblemDescription(e.target.value)} rows={2} placeholder="What needs to be fixed?" required />
</div>
<div className="space-y-1">
<Label className="text-xs">Estimated Cost</Label>
<Input type="number" step="0.01" min="0" value={estimatedCost} onChange={(e) => setEstimatedCost(e.target.value)} placeholder="0.00" />
</div>
<Button type="submit" className="w-full gap-2" disabled={intakeMutation.isPending}>
<Plus className="h-4 w-4" />
{intakeMutation.isPending ? 'Creating...' : 'Create Repair Ticket'}
</Button>
</form>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
)
}

View File

@@ -3,7 +3,7 @@ import { usePOSStore } from '@/stores/pos.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 } from 'lucide-react'
import { ArrowLeft, Lock, DollarSign, Receipt, FileText } from 'lucide-react'
import type { DrawerSession } from '@/api/pos'
import { useState } from 'react'
import { POSDrawerDialog } from './pos-drawer-dialog'
@@ -18,9 +18,12 @@ interface POSTopBarProps {
export function POSTopBar({ locations, locationId, onLocationChange, drawer }: POSTopBarProps) {
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 [drawerDialogOpen, setDrawerDialogOpen] = useState(false)
const drawerOpen = drawer?.status === 'open'
const isThermal = receiptFormat === 'thermal'
return (
<>
@@ -46,6 +49,17 @@ export function POSTopBar({ locations, locationId, onLocationChange, drawer }: P
) : locations.length === 1 ? (
<span className="text-sm font-medium">{locations[0].name}</span>
) : null}
<Button
variant="ghost"
size="sm"
className="h-8 gap-1.5 text-xs text-muted-foreground hover:text-foreground"
onClick={() => setReceiptFormat(isThermal ? 'full' : 'thermal')}
title={isThermal ? 'Receipt: Thermal — click to switch to Full Page' : 'Receipt: Full Page — click to switch to Thermal'}
>
{isThermal ? <Receipt className="h-3.5 w-3.5" /> : <FileText className="h-3.5 w-3.5" />}
<span className="hidden sm:inline">{isThermal ? 'Thermal' : 'Full Page'}</span>
</Button>
</div>
{/* Center: drawer status */}

View File

@@ -2,6 +2,7 @@ import { 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 { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
@@ -57,6 +58,7 @@ export function POSTransactionsDialog({ open, onOpenChange }: POSTransactionsDia
queryFn: () => api.get<{ data: AppConfigEntry[] }>('/v1/config'),
enabled: !!receiptTxnId,
})
const receiptFormat = usePOSStore((s) => s.receiptFormat)
const receiptConfig = {
header: configData?.data?.find((c) => c.key === 'receipt_header')?.value || undefined,
footer: configData?.data?.find((c) => c.key === 'receipt_footer')?.value || undefined,
@@ -68,11 +70,11 @@ export function POSTransactionsDialog({ open, onOpenChange }: POSTransactionsDia
if (receiptTxnId && receiptData) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-sm max-h-[90vh] overflow-y-auto">
<DialogContent className={`${receiptFormat === 'full' ? 'max-w-2xl' : 'max-w-sm'} max-h-[90vh] overflow-y-auto`}>
<div className="flex justify-between items-center mb-2">
<Button variant="ghost" size="sm" onClick={() => setReceiptTxnId(null)}>Back</Button>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => downloadReceiptPDF(receiptData.transaction.transactionNumber)}>
<Button variant="outline" size="sm" onClick={() => downloadReceiptPDF(receiptData.transaction.transactionNumber, receiptFormat)}>
Save PDF
</Button>
<Button size="sm" onClick={printReceipt} className="gap-2">
@@ -81,7 +83,7 @@ export function POSTransactionsDialog({ open, onOpenChange }: POSTransactionsDia
</div>
</div>
<div id="pos-receipt-print">
<POSReceipt data={receiptData} config={receiptConfig} />
<POSReceipt data={receiptData} size={receiptFormat} config={receiptConfig} />
</div>
</DialogContent>
</Dialog>

View File

@@ -85,8 +85,9 @@ export function generateRepairPdf({ ticket, lineItems, notes, includeNotes, comp
doc.text(dateInfo, 14, y)
y += 8
// Line items table
if (lineItems.length > 0) {
// Line items table (exclude consumables — internal only)
const billableItems = lineItems.filter((i) => i.itemType !== 'consumable')
if (billableItems.length > 0) {
doc.setDrawColor(200)
doc.line(14, y, 196, y)
y += 6
@@ -109,7 +110,7 @@ export function generateRepairPdf({ ticket, lineItems, notes, includeNotes, comp
// Table rows
doc.setFont('helvetica', 'normal')
for (const item of lineItems) {
for (const item of billableItems) {
if (y > 270) { doc.addPage(); y = 20 }
doc.text(item.itemType.replace('_', ' '), 16, y)
const descLines = doc.splitTextToSize(item.description, 85)
@@ -127,7 +128,7 @@ export function generateRepairPdf({ ticket, lineItems, notes, includeNotes, comp
y += 5
doc.setFont('helvetica', 'bold')
doc.setFontSize(10)
const total = lineItems.reduce((sum, i) => sum + parseFloat(i.totalPrice), 0)
const total = billableItems.reduce((sum, i) => sum + parseFloat(i.totalPrice), 0)
doc.text('Total:', 155, y, { align: 'right' })
doc.text(`$${total.toFixed(2)}`, 190, y, { align: 'right' })
y += 4

View File

@@ -0,0 +1,46 @@
import * as React from "react"
import { Popover as PopoverPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

View File

@@ -6,6 +6,7 @@ import {
repairLineItemListOptions, repairLineItemMutations, repairLineItemKeys,
repairServiceTemplateListOptions,
} from '@/api/repairs'
import { api } from '@/lib/api-client'
import { usePagination } from '@/hooks/use-pagination'
import { StatusProgress } from '@/components/repairs/status-progress'
import { TicketPhotos } from '@/components/repairs/ticket-photos'
@@ -157,7 +158,12 @@ function RepairTicketDetailPage() {
}
const lineItemColumns: Column<RepairLineItem>[] = [
{ key: 'item_type', header: 'Type', sortable: true, render: (i) => <Badge variant="outline">{i.itemType.replace('_', ' ')}</Badge> },
{ key: 'item_type', header: 'Type', sortable: true, render: (i) => (
<div className="flex items-center gap-1">
<Badge variant="outline">{i.itemType.replace('_', ' ')}</Badge>
{i.itemType === 'consumable' && <Badge variant="secondary" className="text-[10px]">Internal</Badge>}
</div>
) },
{ key: 'description', header: 'Description', render: (i) => <>{i.description}</> },
{ key: 'qty', header: 'Qty', render: (i) => <>{i.qty}</> },
{ key: 'unit_price', header: 'Unit Price', render: (i) => <>${i.unitPrice}</> },
@@ -391,11 +397,27 @@ function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string;
const [qty, setQty] = useState('1')
const [unitPrice, setUnitPrice] = useState('0')
const [cost, setCost] = useState('')
const [productId, setProductId] = useState<string | null>(null)
const [productSearch, setProductSearch] = useState('')
const [showProducts, setShowProducts] = useState(false)
const showProductPicker = itemType === 'part' || itemType === 'consumable'
const { data: templatesData } = useQuery(
repairServiceTemplateListOptions({ page: 1, limit: 20, q: templateSearch || undefined, order: 'asc', sort: 'name' }),
)
const { data: productsData } = useQuery({
queryKey: ['products', 'repair-picker', productSearch, itemType],
queryFn: () => {
const params: Record<string, string> = { q: productSearch, limit: '10', isActive: 'true' }
if (itemType === 'consumable') params.isConsumable = 'true'
else params.isDualUseRepair = 'true'
return api.get<{ data: { id: string; name: string; sku: string | null; price: string | null; brand: string | null }[] }>('/v1/products', params)
},
enabled: showProductPicker && productSearch.length >= 1,
})
const mutation = useMutation({
mutationFn: (data: Record<string, unknown>) => repairLineItemMutations.create(ticketId, data),
onSuccess: () => {
@@ -408,7 +430,7 @@ function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string;
})
function resetForm() {
setDescription(''); setQty('1'); setUnitPrice('0'); setCost(''); setItemType('labor'); setTemplateSearch(''); setShowTemplates(false)
setDescription(''); setQty('1'); setUnitPrice('0'); setCost(''); setItemType('labor'); setTemplateSearch(''); setShowTemplates(false); setProductId(null); setProductSearch(''); setShowProducts(false)
}
function selectTemplate(template: { name: string; itemCategory: string | null; size: string | null; itemType: string; defaultPrice: string; defaultCost: string | null }) {
@@ -416,15 +438,24 @@ function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string;
setDescription(desc); setItemType(template.itemType); setUnitPrice(template.defaultPrice); setCost(template.defaultCost ?? ''); setShowTemplates(false); setTemplateSearch('')
}
function selectProduct(product: { id: string; name: string; price: string | null; brand: string | null }) {
setProductId(product.id)
setDescription(product.brand ? `${product.brand} ${product.name}` : product.name)
setUnitPrice(product.price ?? '0')
setProductSearch('')
setShowProducts(false)
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
const q = parseFloat(qty) || 1
const up = parseFloat(unitPrice) || 0
const c = cost ? parseFloat(cost) : undefined
mutation.mutate({ itemType, description, qty: q, unitPrice: up, totalPrice: q * up, cost: c })
mutation.mutate({ itemType, description, qty: q, unitPrice: up, totalPrice: q * up, cost: c, productId: productId ?? undefined })
}
const templates = templatesData?.data ?? []
const products = productsData?.data ?? []
return (
<Dialog open={open} onOpenChange={(o) => { onOpenChange(o); if (!o) resetForm() }}>
@@ -454,8 +485,38 @@ function AddLineItemDialog({ ticketId, open, onOpenChange }: { ticketId: string;
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label>Type</Label>
<Select value={itemType} onValueChange={setItemType}><SelectTrigger><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>
<Select value={itemType} onValueChange={(v) => { setItemType(v); setProductId(null); setProductSearch(''); setShowProducts(false) }}><SelectTrigger><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><SelectItem value="consumable">Consumable (internal)</SelectItem></SelectContent></Select>
</div>
{showProductPicker && (
<div className="relative space-y-2">
<Label>Search Inventory</Label>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder={itemType === 'consumable' ? 'Search consumables...' : 'Search parts...'}
value={productSearch}
onChange={(e) => { setProductSearch(e.target.value); setShowProducts(true) }}
onFocus={() => productSearch && setShowProducts(true)}
className="pl-9"
/>
</div>
{productId && (
<div className="text-xs text-muted-foreground flex items-center gap-1">
Linked to product <button type="button" className="underline text-destructive" onClick={() => setProductId(null)}>clear</button>
</div>
)}
{showProducts && productSearch.length >= 1 && (
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-48 overflow-auto">
{products.length === 0 ? <div className="p-3 text-sm text-muted-foreground">No products found</div> : products.map((p) => (
<button key={p.id} type="button" className="w-full text-left px-3 py-2 text-sm hover:bg-accent flex justify-between" onClick={() => selectProduct(p)}>
<span>{p.brand ? `${p.brand} ` : ''}{p.name}{p.sku ? ` (${p.sku})` : ''}</span>
{p.price && <span className="text-muted-foreground">${p.price}</span>}
</button>
))}
</div>
)}
</div>
)}
<div className="space-y-2"><Label>Description *</Label><Input value={description} onChange={(e) => setDescription(e.target.value)} required /></div>
<div className="grid grid-cols-3 gap-4">
<div className="space-y-2"><Label>Qty</Label><Input type="number" step="0.001" value={qty} onChange={(e) => setQty(e.target.value)} /></div>

View File

@@ -16,7 +16,8 @@ import { Switch } from '@/components/ui/switch'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { moduleListOptions, moduleMutations, moduleKeys } from '@/api/modules'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Save, Plus, Trash2, MapPin, Building, ImageIcon, Blocks, Lock, Settings2, Receipt } from 'lucide-react'
import { Save, Plus, Trash2, MapPin, Building, ImageIcon, Blocks, Lock, Settings2, Receipt, ShieldCheck } from 'lucide-react'
import { OVERRIDE_ACTIONS, getRequiredOverrides, setRequiredOverrides, getDiscountThreshold, setDiscountThreshold, type OverrideAction } from '@/components/pos/pos-manager-override'
import { toast } from 'sonner'
interface StoreSettings {
@@ -119,142 +120,149 @@ function SettingsPage() {
<div className="space-y-6 max-w-3xl">
<h1 className="text-2xl font-bold">Settings</h1>
<Tabs defaultValue="general">
<Tabs defaultValue="store">
<TabsList>
<TabsTrigger value="general">General</TabsTrigger>
<TabsTrigger value="store">Store</TabsTrigger>
<TabsTrigger value="locations">Locations</TabsTrigger>
<TabsTrigger value="modules">Modules</TabsTrigger>
<TabsTrigger value="receipt">Receipt</TabsTrigger>
<TabsTrigger value="pos">POS Security</TabsTrigger>
<TabsTrigger value="advanced">Advanced</TabsTrigger>
</TabsList>
<TabsContent value="general" className="space-y-6 mt-4">
{/* Store Info */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="text-lg flex items-center gap-2">
<Building className="h-5 w-5" />Store Information
</CardTitle>
{!editing && <Button variant="outline" size="sm" onClick={startEdit}>Edit</Button>}
{editing && (
<div className="flex gap-2">
<Button size="sm" onClick={saveEdit} disabled={updateMutation.isPending}>
<Save className="mr-1 h-3 w-3" />{updateMutation.isPending ? 'Saving...' : 'Save'}
</Button>
<Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Cancel</Button>
</div>
)}
</CardHeader>
<CardContent className="space-y-6">
{/* Logo upload */}
<div>
<LogoUpload entityId={store.id} category="logo" label="Store Logo" description="Used on PDFs, sidebar, and login screen" />
</div>
{editing ? (
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Store Name *</Label>
<Input value={fields.name} onChange={(e) => setFields((p) => ({ ...p, name: e.target.value }))} />
</div>
<div className="space-y-2">
<Label>Timezone</Label>
<Input value={fields.timezone} onChange={(e) => setFields((p) => ({ ...p, timezone: e.target.value }))} placeholder="America/Chicago" />
<TabsContent value="store" className="mt-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="text-lg flex items-center gap-2">
<Building className="h-5 w-5" />Store Information
</CardTitle>
{!editing && <Button variant="outline" size="sm" onClick={startEdit}>Edit</Button>}
{editing && (
<div className="flex gap-2">
<Button size="sm" onClick={saveEdit} disabled={updateMutation.isPending}>
<Save className="mr-1 h-3 w-3" />{updateMutation.isPending ? 'Saving...' : 'Save'}
</Button>
<Button variant="ghost" size="sm" onClick={() => setEditing(false)}>Cancel</Button>
</div>
)}
</CardHeader>
<CardContent className="space-y-6">
<div>
<LogoUpload entityId={store.id} category="logo" label="Store Logo" description="Used on PDFs, sidebar, and login screen" />
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Phone</Label>
<Input value={fields.phone} onChange={(e) => setFields((p) => ({ ...p, phone: e.target.value }))} />
</div>
<div className="space-y-2">
<Label>Email</Label>
<Input value={fields.email} onChange={(e) => setFields((p) => ({ ...p, email: e.target.value }))} />
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Street</Label>
<Input value={fields.street} onChange={(e) => setFields((p) => ({ ...p, street: e.target.value }))} />
</div>
<div className="grid grid-cols-3 gap-2">
<div className="space-y-2">
<Label>City</Label>
<Input value={fields.city} onChange={(e) => setFields((p) => ({ ...p, city: e.target.value }))} />
{editing ? (
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Store Name *</Label>
<Input value={fields.name} onChange={(e) => setFields((p) => ({ ...p, name: e.target.value }))} />
</div>
<div className="space-y-2">
<Label>Timezone</Label>
<Input value={fields.timezone} onChange={(e) => setFields((p) => ({ ...p, timezone: e.target.value }))} placeholder="America/Chicago" />
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Phone</Label>
<Input value={fields.phone} onChange={(e) => setFields((p) => ({ ...p, phone: e.target.value }))} />
</div>
<div className="space-y-2">
<Label>Email</Label>
<Input value={fields.email} onChange={(e) => setFields((p) => ({ ...p, email: e.target.value }))} />
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Street</Label>
<Input value={fields.street} onChange={(e) => setFields((p) => ({ ...p, street: e.target.value }))} />
</div>
<div className="grid grid-cols-3 gap-2">
<div className="space-y-2">
<Label>City</Label>
<Input value={fields.city} onChange={(e) => setFields((p) => ({ ...p, city: e.target.value }))} />
</div>
<div className="space-y-2">
<Label>State</Label>
<Input value={fields.state} onChange={(e) => setFields((p) => ({ ...p, state: e.target.value }))} />
</div>
<div className="space-y-2">
<Label>ZIP</Label>
<Input value={fields.zip} onChange={(e) => setFields((p) => ({ ...p, zip: e.target.value }))} />
</div>
</div>
</div>
<div className="space-y-2">
<Label>State</Label>
<Input value={fields.state} onChange={(e) => setFields((p) => ({ ...p, state: e.target.value }))} />
</div>
<div className="space-y-2">
<Label>ZIP</Label>
<Input value={fields.zip} onChange={(e) => setFields((p) => ({ ...p, zip: e.target.value }))} />
<Label>Notes</Label>
<Textarea value={fields.notes} onChange={(e) => setFields((p) => ({ ...p, notes: e.target.value }))} rows={2} />
</div>
</div>
</div>
<div className="space-y-2">
<Label>Notes</Label>
<Textarea value={fields.notes} onChange={(e) => setFields((p) => ({ ...p, notes: e.target.value }))} rows={2} />
</div>
</div>
) : (
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2 text-sm">
<div className="text-lg font-semibold">{store.name}</div>
<div><span className="text-muted-foreground">Phone:</span> {store.phone ?? '-'}</div>
<div><span className="text-muted-foreground">Email:</span> {store.email ?? '-'}</div>
<div><span className="text-muted-foreground">Timezone:</span> {store.timezone}</div>
) : (
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2 text-sm">
<div className="text-lg font-semibold">{store.name}</div>
<div><span className="text-muted-foreground">Phone:</span> {store.phone ?? '-'}</div>
<div><span className="text-muted-foreground">Email:</span> {store.email ?? '-'}</div>
<div><span className="text-muted-foreground">Timezone:</span> {store.timezone}</div>
</div>
<div className="space-y-2 text-sm">
{store.address && (store.address.street || store.address.city) ? (
<>
<div className="font-medium flex items-center gap-1"><MapPin className="h-3 w-3" />Address</div>
{store.address.street && <div>{store.address.street}</div>}
<div>{[store.address.city, store.address.state, store.address.zip].filter(Boolean).join(', ')}</div>
</>
) : (
<div className="text-muted-foreground">No address set</div>
)}
{store.notes && <div className="mt-2"><span className="text-muted-foreground">Notes:</span> {store.notes}</div>}
</div>
</div>
</div>
<div className="space-y-2 text-sm">
{store.address && (store.address.street || store.address.city) ? (
<>
<div className="font-medium flex items-center gap-1"><MapPin className="h-3 w-3" />Address</div>
{store.address.street && <div>{store.address.street}</div>}
<div>{[store.address.city, store.address.state, store.address.zip].filter(Boolean).join(', ')}</div>
</>
) : (
<div className="text-muted-foreground">No address set</div>
)}
{store.notes && <div className="mt-2"><span className="text-muted-foreground">Notes:</span> {store.notes}</div>}
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="locations" className="mt-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="text-lg flex items-center gap-2">
<MapPin className="h-5 w-5" />Locations
</CardTitle>
<AddLocationDialog open={addLocationOpen} onOpenChange={setAddLocationOpen} />
</CardHeader>
<CardContent>
{locations.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">No locations yet add your first store location</p>
) : (
<div className="space-y-3">
{locations.map((loc) => (
<LocationCard key={loc.id} location={loc} />
))}
</div>
</div>
</div>
)}
</CardContent>
</Card>
{/* Locations */}
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="text-lg flex items-center gap-2">
<MapPin className="h-5 w-5" />Locations
</CardTitle>
<AddLocationDialog open={addLocationOpen} onOpenChange={setAddLocationOpen} />
</CardHeader>
<CardContent>
{locations.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-4">No locations yet add your first store location</p>
) : (
<div className="space-y-3">
{locations.map((loc) => (
<LocationCard key={loc.id} location={loc} />
))}
</div>
)}
</CardContent>
</Card>
{/* Modules */}
<ModulesCard />
{/* App Configuration */}
<AppConfigCard />
)}
</CardContent>
</Card>
</TabsContent>
<TabsContent value="modules" className="mt-4">
<ModulesCard />
</TabsContent>
<TabsContent value="receipt" className="mt-4">
<ReceiptSettingsCard />
</TabsContent>
<TabsContent value="pos" className="mt-4">
<ManagerOverridesCard />
</TabsContent>
<TabsContent value="advanced" className="mt-4">
<AppConfigCard />
</TabsContent>
</Tabs>
</div>
)
@@ -492,6 +500,74 @@ function ReceiptSettingsCard() {
)
}
function ManagerOverridesCard() {
const [overrides, setOverrides] = useState<Set<OverrideAction>>(() => getRequiredOverrides())
const [threshold, setThreshold] = useState(() => getDiscountThreshold())
function toggle(action: OverrideAction) {
setOverrides((prev) => {
const next = new Set(prev)
if (next.has(action)) next.delete(action)
else next.add(action)
setRequiredOverrides(next)
return next
})
}
return (
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<ShieldCheck className="h-5 w-5" />Manager Overrides
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4">
When enabled, these actions will require a manager or admin to enter their PIN before proceeding. This setting is stored per device.
</p>
<div className="space-y-2">
{OVERRIDE_ACTIONS.map((action) => (
<div key={action.key} className="flex items-center justify-between p-3 rounded-md border">
<div className="min-w-0">
<span className="font-medium text-sm">{action.label}</span>
<p className="text-xs text-muted-foreground mt-0.5">{action.description}</p>
</div>
<Switch
checked={overrides.has(action.key)}
onCheckedChange={() => toggle(action.key)}
/>
</div>
))}
</div>
<div className="mt-4 p-3 rounded-md border">
<div className="flex items-center justify-between">
<div className="min-w-0">
<span className="font-medium text-sm">Discount Threshold</span>
<p className="text-xs text-muted-foreground mt-0.5">Require manager approval for discounts at or above this percentage. Set to 0 to disable.</p>
</div>
<div className="flex items-center gap-1">
<Input
type="number"
min="0"
max="100"
className="w-20 h-8 text-sm text-right"
value={threshold}
onChange={(e) => {
const v = parseInt(e.target.value) || 0
setThreshold(v)
setDiscountThreshold(v)
}}
/>
<span className="text-sm text-muted-foreground">%</span>
</div>
</div>
</div>
</CardContent>
</Card>
)
}
function LocationCard({ location }: { location: Location }) {
const queryClient = useQueryClient()
const [editing, setEditing] = useState(false)

View File

@@ -8,6 +8,8 @@ interface POSUser {
role: string
}
type ReceiptFormat = 'thermal' | 'full'
interface POSState {
currentTransactionId: string | null
locationId: string | null
@@ -20,6 +22,7 @@ interface POSState {
accountName: string | null
accountPhone: string | null
accountEmail: string | null
receiptFormat: ReceiptFormat
setTransaction: (id: string | null) => void
setLocation: (id: string) => void
setDrawerSession: (id: string | null) => void
@@ -28,9 +31,17 @@ interface POSState {
touchActivity: () => void
setAccount: (id: string, name: string, phone?: string | null, email?: string | null) => void
clearAccount: () => void
setReceiptFormat: (format: ReceiptFormat) => void
reset: () => void
}
const RECEIPT_FORMAT_KEY = 'pos_receipt_format'
function getStoredReceiptFormat(): ReceiptFormat {
const stored = localStorage.getItem(RECEIPT_FORMAT_KEY)
return stored === 'full' ? 'full' : 'thermal'
}
export const usePOSStore = create<POSState>((set) => ({
currentTransactionId: null,
locationId: null,
@@ -43,6 +54,7 @@ export const usePOSStore = create<POSState>((set) => ({
accountName: null,
accountPhone: null,
accountEmail: null,
receiptFormat: getStoredReceiptFormat(),
setTransaction: (id) => set({ currentTransactionId: id }),
setLocation: (id) => set({ locationId: id }),
setDrawerSession: (id) => set({ drawerSessionId: id }),
@@ -51,5 +63,6 @@ export const usePOSStore = create<POSState>((set) => ({
touchActivity: () => set({ lastActivity: Date.now() }),
setAccount: (id, name, phone, email) => set({ accountId: id, accountName: name, accountPhone: phone ?? null, accountEmail: email ?? null }),
clearAccount: () => set({ accountId: null, accountName: null, accountPhone: null, accountEmail: null }),
setReceiptFormat: (format) => { localStorage.setItem(RECEIPT_FORMAT_KEY, format); set({ receiptFormat: format }) },
reset: () => set({ currentTransactionId: null, accountId: null, accountName: null, accountPhone: null, accountEmail: null }),
}))

View File

@@ -44,6 +44,7 @@ export interface Product {
isSerialized: boolean
isRental: boolean
isDualUseRepair: boolean
isConsumable: boolean
price: string | null
minPrice: string | null
rentalRateMonthly: string | null

View File

@@ -28,7 +28,7 @@ export interface RepairTicket {
export interface RepairLineItem {
id: string
repairTicketId: string
itemType: 'labor' | 'part' | 'flat_rate' | 'misc'
itemType: 'labor' | 'part' | 'flat_rate' | 'misc' | 'consumable'
description: string
productId: string | null
qty: string
@@ -82,7 +82,7 @@ export interface RepairServiceTemplate {
itemCategory: string | null
size: string | null
description: string | null
itemType: 'labor' | 'part' | 'flat_rate' | 'misc'
itemType: 'labor' | 'part' | 'flat_rate' | 'misc' | 'consumable'
defaultPrice: string
defaultCost: string | null
sortOrder: number

View File

@@ -4,7 +4,7 @@
"private": true,
"type": "module",
"scripts": {
"dev": "bun --watch run src/main.ts",
"dev": "bun --env-file=../../.env --watch run src/main.ts",
"start": "bun run src/main.ts",
"test": "bun test || true",
"test:watch": "bun test --watch",

View File

@@ -0,0 +1,5 @@
-- Add 'consumable' to repair_line_item_type enum
ALTER TYPE repair_line_item_type ADD VALUE IF NOT EXISTS 'consumable';
-- Add is_consumable flag to product table
ALTER TABLE product ADD COLUMN IF NOT EXISTS is_consumable boolean NOT NULL DEFAULT false;

View File

@@ -309,6 +309,13 @@
"when": 1775590000000,
"tag": "0042_user-pin",
"breakpoints": true
},
{
"idx": 43,
"version": "7",
"when": 1775680000000,
"tag": "0043_repair-pos-consumable",
"breakpoints": true
}
]
}

View File

@@ -57,6 +57,7 @@ export const products = pgTable('product', {
isSerialized: boolean('is_serialized').notNull().default(false),
isRental: boolean('is_rental').notNull().default(false),
isDualUseRepair: boolean('is_dual_use_repair').notNull().default(false),
isConsumable: boolean('is_consumable').notNull().default(false),
taxCategory: taxCategoryEnum('tax_category').notNull().default('goods'),
price: numeric('price', { precision: 10, scale: 2 }),
minPrice: numeric('min_price', { precision: 10, scale: 2 }),

View File

@@ -36,6 +36,7 @@ export const repairLineItemTypeEnum = pgEnum('repair_line_item_type', [
'part',
'flat_rate',
'misc',
'consumable',
])
export const repairConditionInEnum = pgEnum('repair_condition_in', [

View File

@@ -41,6 +41,7 @@ export const productRoutes: FastifyPluginAsync = async (app) => {
isSerialized: q.isSerialized === 'true' ? true : q.isSerialized === 'false' ? false : undefined,
isRental: q.isRental === 'true' ? true : q.isRental === 'false' ? false : undefined,
isDualUseRepair: q.isDualUseRepair === 'true' ? true : q.isDualUseRepair === 'false' ? false : undefined,
isConsumable: q.isConsumable === 'true' ? true : q.isConsumable === 'false' ? false : undefined,
lowStock: q.lowStock === 'true',
}
const result = await ProductService.list(app.db, params, filters)

View File

@@ -27,6 +27,13 @@ export const repairRoutes: FastifyPluginAsync = async (app) => {
return reply.status(201).send(ticket)
})
app.get('/repair-tickets/ready', { preHandler: [app.authenticate, app.requirePermission('pos.view')] }, async (request, reply) => {
const query = request.query as Record<string, string | undefined>
const params = PaginationSchema.parse(query)
const result = await RepairTicketService.listReadyForPickup(app.db, params)
return reply.send(result)
})
app.get('/repair-tickets', { preHandler: [app.authenticate, app.requirePermission('repairs.view')] }, async (request, reply) => {
const query = request.query as Record<string, string | undefined>
const params = PaginationSchema.parse(query)

View File

@@ -19,6 +19,14 @@ export const transactionRoutes: FastifyPluginAsync = async (app) => {
return reply.status(201).send(txn)
})
app.post('/transactions/from-repair/:ticketId', { preHandler: [app.authenticate, app.requirePermission('pos.edit')] }, async (request, reply) => {
const { ticketId } = request.params as { ticketId: string }
const body = request.body as { locationId?: string } | undefined
const txn = await TransactionService.createFromRepairTicket(app.db, ticketId, body?.locationId, request.user.id)
request.log.info({ transactionId: txn?.id, ticketId, userId: request.user.id }, 'Repair payment transaction created')
return reply.status(201).send(txn)
})
app.get('/transactions', { preHandler: [app.authenticate, app.requirePermission('pos.view')] }, async (request, reply) => {
const query = request.query as Record<string, string | undefined>
const params = PaginationSchema.parse(query)

View File

@@ -49,6 +49,7 @@ export const ProductService = {
isSerialized?: boolean
isRental?: boolean
isDualUseRepair?: boolean
isConsumable?: boolean
lowStock?: boolean
}) {
const conditions = [eq(products.isActive, filters?.isActive ?? true)]
@@ -68,6 +69,9 @@ export const ProductService = {
if (filters?.isDualUseRepair !== undefined) {
conditions.push(eq(products.isDualUseRepair, filters.isDualUseRepair))
}
if (filters?.isConsumable !== undefined) {
conditions.push(eq(products.isConsumable, filters.isConsumable))
}
if (filters?.lowStock) {
// qty_on_hand <= qty_reorder_point (and reorder point is set) OR qty_on_hand = 0
conditions.push(

View File

@@ -174,6 +174,25 @@ export const RepairTicketService = {
return paginatedResponse(data, total, params.page, params.limit)
},
async listReadyForPickup(db: PostgresJsDatabase<any>, params: PaginationInput) {
const baseWhere = eq(repairTickets.status, 'ready')
const searchCondition = params.q
? buildSearchCondition(params.q, [repairTickets.ticketNumber, repairTickets.customerName, repairTickets.customerPhone])
: undefined
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
let query = db.select().from(repairTickets).where(where).$dynamic()
query = withSort(query, params.sort, params.order, { ticket_number: repairTickets.ticketNumber, customer_name: repairTickets.customerName, created_at: repairTickets.createdAt }, repairTickets.createdAt)
query = withPagination(query, params.page, params.limit)
const [data, [{ total }]] = await Promise.all([
query,
db.select({ total: count() }).from(repairTickets).where(where),
])
return paginatedResponse(data, total, params.page, params.limit)
},
async update(db: PostgresJsDatabase<any>, id: string, input: RepairTicketUpdateInput) {
const values: Record<string, unknown> = { ...input, updatedAt: new Date() }
if (input.estimatedCost !== undefined) values.estimatedCost = input.estimatedCost.toString()

View File

@@ -63,6 +63,8 @@ export const TaxService = {
switch (itemType) {
case 'labor':
return 'service'
case 'consumable':
return 'exempt'
case 'part':
case 'flat_rate':
case 'misc':

View File

@@ -8,6 +8,7 @@ import {
drawerSessions,
} from '../db/schema/pos.js'
import { products, inventoryUnits } from '../db/schema/inventory.js'
import { repairTickets, repairLineItems } from '../db/schema/repairs.js'
import { companies, locations } from '../db/schema/stores.js'
import { NotFoundError, ValidationError, ConflictError } from '../lib/errors.js'
import { TaxService } from './tax.service.js'
@@ -47,6 +48,78 @@ export const TransactionService = {
return txn
},
async createFromRepairTicket(db: PostgresJsDatabase<any>, ticketId: string, locationId: string | undefined, processedBy: string) {
// Fetch ticket
const [ticket] = await db
.select()
.from(repairTickets)
.where(eq(repairTickets.id, ticketId))
.limit(1)
if (!ticket) throw new NotFoundError('Repair ticket')
if (!['ready', 'approved', 'in_progress'].includes(ticket.status)) {
throw new ValidationError('Ticket must be in ready, approved, or in_progress status to check out')
}
// Check for existing pending repair_payment for this ticket
const [existing] = await db
.select({ id: transactions.id })
.from(transactions)
.where(and(
eq(transactions.repairTicketId, ticketId),
eq(transactions.status, 'pending'),
))
.limit(1)
if (existing) throw new ConflictError('A pending transaction already exists for this ticket')
// Fetch non-consumable line items
const items = await db
.select()
.from(repairLineItems)
.where(eq(repairLineItems.repairTicketId, ticketId))
const billableItems = items.filter((i) => i.itemType !== 'consumable')
if (billableItems.length === 0) throw new ValidationError('No billable line items on this ticket')
// Create transaction
const txn = await this.create(db, {
transactionType: 'repair_payment',
locationId: locationId ?? ticket.locationId ?? undefined,
accountId: ticket.accountId ?? undefined,
repairTicketId: ticketId,
}, processedBy)
// Add each billable line item
for (const item of billableItems) {
const taxCategory = TaxService.repairItemTypeToTaxCategory(item.itemType)
let taxRate = 0
const txnLocationId = locationId ?? ticket.locationId
if (txnLocationId) {
taxRate = await TaxService.getRateForLocation(db, txnLocationId, taxCategory)
}
const unitPrice = parseFloat(item.unitPrice)
const qty = Math.round(parseFloat(item.qty))
const lineSubtotal = unitPrice * qty
const taxAmount = TaxService.calculateTax(lineSubtotal, taxRate)
const lineTotal = lineSubtotal + taxAmount
await db.insert(transactionLineItems).values({
transactionId: txn.id,
productId: item.productId,
description: item.description,
qty,
unitPrice: unitPrice.toString(),
taxRate: taxRate.toString(),
taxAmount: taxAmount.toString(),
lineTotal: lineTotal.toString(),
})
}
await this.recalculateTotals(db, txn.id)
return this.getById(db, txn.id)
},
async addLineItem(db: PostgresJsDatabase<any>, transactionId: string, input: TransactionLineItemCreateInput) {
const txn = await this.getById(db, transactionId)
if (!txn) throw new NotFoundError('Transaction')
@@ -309,6 +382,15 @@ export const TransactionService = {
})
.where(eq(transactions.id, transactionId))
.returning()
// If this is a repair payment, update ticket status to picked_up
if (completed.transactionType === 'repair_payment' && completed.repairTicketId) {
await db
.update(repairTickets)
.set({ status: 'picked_up', completedDate: new Date(), updatedAt: new Date() })
.where(eq(repairTickets.id, completed.repairTicketId))
}
return completed
},

View File

@@ -61,6 +61,7 @@ export const ProductCreateSchema = z.object({
isSerialized: z.boolean().default(false),
isRental: z.boolean().default(false),
isDualUseRepair: z.boolean().default(false),
isConsumable: z.boolean().default(false),
price: z.number().min(0).optional(),
minPrice: z.number().min(0).optional(),
rentalRateMonthly: z.number().min(0).optional(),

View File

@@ -13,7 +13,7 @@ export const RepairTicketStatus = z.enum([
])
export type RepairTicketStatus = z.infer<typeof RepairTicketStatus>
export const RepairLineItemType = z.enum(['labor', 'part', 'flat_rate', 'misc'])
export const RepairLineItemType = z.enum(['labor', 'part', 'flat_rate', 'misc', 'consumable'])
export type RepairLineItemType = z.infer<typeof RepairLineItemType>
export const RepairConditionIn = z.enum(['excellent', 'good', 'fair', 'poor'])