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:
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
199
packages/admin/src/components/pos/pos-manager-override.tsx
Normal file
199
packages/admin/src/components/pos/pos-manager-override.tsx
Normal 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
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
263
packages/admin/src/components/pos/pos-repair-dialog.tsx
Normal file
263
packages/admin/src/components/pos/pos-repair-dialog.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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 */}
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user