feat(pos): add point of sale UI
- Add ProductGrid component with category filters and search - Add Cart component with quantity controls and totals - Add PaymentDialog with cash/card/transfer payment methods - Add CashRegisterStatus for opening/closing register - Add POS page with 70/30 layout (products/cart) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
199
apps/web/components/pos/cart.tsx
Normal file
199
apps/web/components/pos/cart.tsx
Normal file
@@ -0,0 +1,199 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { formatCurrency } from "@/lib/utils";
|
||||
|
||||
export interface CartItem {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
quantity: number;
|
||||
stock: number;
|
||||
trackStock: boolean;
|
||||
}
|
||||
|
||||
interface CartProps {
|
||||
items: CartItem[];
|
||||
onUpdateQuantity: (productId: string, quantity: number) => void;
|
||||
onRemoveItem: (productId: string) => void;
|
||||
onClearCart: () => void;
|
||||
onCheckout: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function Cart({
|
||||
items,
|
||||
onUpdateQuantity,
|
||||
onRemoveItem,
|
||||
onClearCart,
|
||||
onCheckout,
|
||||
disabled = false,
|
||||
}: CartProps) {
|
||||
const subtotal = items.reduce(
|
||||
(sum, item) => sum + item.price * item.quantity,
|
||||
0
|
||||
);
|
||||
|
||||
const handleIncrement = (item: CartItem) => {
|
||||
// Check stock if tracking
|
||||
if (item.trackStock && item.quantity >= item.stock) {
|
||||
return;
|
||||
}
|
||||
onUpdateQuantity(item.id, item.quantity + 1);
|
||||
};
|
||||
|
||||
const handleDecrement = (item: CartItem) => {
|
||||
if (item.quantity > 1) {
|
||||
onUpdateQuantity(item.id, item.quantity - 1);
|
||||
} else {
|
||||
onRemoveItem(item.id);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="h-full flex flex-col">
|
||||
<CardHeader className="border-b">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-lg">Carrito</CardTitle>
|
||||
{items.length > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onClearCart}
|
||||
disabled={disabled}
|
||||
className="text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
>
|
||||
Vaciar
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="flex-1 overflow-y-auto p-0">
|
||||
{items.length === 0 ? (
|
||||
<div className="flex items-center justify-center h-full text-primary-400 p-6">
|
||||
<div className="text-center">
|
||||
<div className="text-4xl mb-2">🛒</div>
|
||||
<p>El carrito esta vacio</p>
|
||||
<p className="text-sm mt-1">Selecciona productos para agregar</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y divide-primary-100">
|
||||
{items.map((item) => (
|
||||
<li key={item.id} className="p-4">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className="font-medium text-primary-800 text-sm truncate">
|
||||
{item.name}
|
||||
</h4>
|
||||
<p className="text-primary-500 text-xs mt-0.5">
|
||||
{formatCurrency(item.price)} c/u
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 text-red-400 hover:text-red-500 hover:bg-red-50 shrink-0"
|
||||
onClick={() => onRemoveItem(item.id)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="w-4 h-4"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M8.75 1A2.75 2.75 0 006 3.75v.443c-.795.077-1.584.176-2.365.298a.75.75 0 10.23 1.482l.149-.022.841 10.518A2.75 2.75 0 007.596 19h4.807a2.75 2.75 0 002.742-2.53l.841-10.519.149.023a.75.75 0 00.23-1.482A41.03 41.03 0 0014 4.193V3.75A2.75 2.75 0 0011.25 1h-2.5zM10 4c.84 0 1.673.025 2.5.075V3.75c0-.69-.56-1.25-1.25-1.25h-2.5c-.69 0-1.25.56-1.25 1.25v.325C8.327 4.025 9.16 4 10 4zM8.58 7.72a.75.75 0 00-1.5.06l.3 7.5a.75.75 0 101.5-.06l-.3-7.5zm4.34.06a.75.75 0 10-1.5-.06l-.3 7.5a.75.75 0 101.5.06l.3-7.5z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between mt-3">
|
||||
{/* Quantity Controls */}
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleDecrement(item)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="w-4 h-4"
|
||||
>
|
||||
<path d="M6.75 9.25a.75.75 0 000 1.5h6.5a.75.75 0 000-1.5h-6.5z" />
|
||||
</svg>
|
||||
</Button>
|
||||
<span className="w-10 text-center font-medium text-primary-800">
|
||||
{item.quantity}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => handleIncrement(item)}
|
||||
disabled={
|
||||
disabled ||
|
||||
(item.trackStock && item.quantity >= item.stock)
|
||||
}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="w-4 h-4"
|
||||
>
|
||||
<path d="M10.75 6.75a.75.75 0 00-1.5 0v2.5h-2.5a.75.75 0 000 1.5h2.5v2.5a.75.75 0 001.5 0v-2.5h2.5a.75.75 0 000-1.5h-2.5v-2.5z" />
|
||||
</svg>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Subtotal */}
|
||||
<span className="font-bold text-primary-800">
|
||||
{formatCurrency(item.price * item.quantity)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Stock Warning */}
|
||||
{item.trackStock && item.quantity >= item.stock && (
|
||||
<p className="text-xs text-amber-600 mt-2">
|
||||
Stock maximo alcanzado
|
||||
</p>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="flex-col gap-4 border-t p-4">
|
||||
{/* Total */}
|
||||
<div className="w-full flex items-center justify-between">
|
||||
<span className="text-lg font-medium text-primary-600">Total:</span>
|
||||
<span className="text-2xl font-bold text-primary-800">
|
||||
{formatCurrency(subtotal)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Checkout Button */}
|
||||
<Button
|
||||
className="w-full"
|
||||
size="lg"
|
||||
disabled={items.length === 0 || disabled}
|
||||
onClick={onCheckout}
|
||||
>
|
||||
Cobrar
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
431
apps/web/components/pos/cash-register-status.tsx
Normal file
431
apps/web/components/pos/cash-register-status.tsx
Normal file
@@ -0,0 +1,431 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { formatCurrency, cn } from "@/lib/utils";
|
||||
|
||||
interface CashRegister {
|
||||
id: string;
|
||||
openingAmount: number;
|
||||
closedAt: string | null;
|
||||
openedAt: string;
|
||||
site: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
user: {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
};
|
||||
_count: {
|
||||
sales: number;
|
||||
payments: number;
|
||||
};
|
||||
paymentBreakdown?: Record<string, number>;
|
||||
totalCashSales?: number;
|
||||
expectedAmount?: number;
|
||||
}
|
||||
|
||||
interface CashRegisterStatusProps {
|
||||
siteId: string;
|
||||
onRegisterStatusChange: (isOpen: boolean, registerId?: string) => void;
|
||||
}
|
||||
|
||||
export function CashRegisterStatus({
|
||||
siteId,
|
||||
onRegisterStatusChange,
|
||||
}: CashRegisterStatusProps) {
|
||||
const [register, setRegister] = useState<CashRegister | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showOpenDialog, setShowOpenDialog] = useState(false);
|
||||
const [showCloseDialog, setShowCloseDialog] = useState(false);
|
||||
const [openingAmount, setOpeningAmount] = useState<string>("0");
|
||||
const [closingAmount, setClosingAmount] = useState<string>("");
|
||||
const [closingNotes, setClosingNotes] = useState<string>("");
|
||||
const [actionLoading, setActionLoading] = useState(false);
|
||||
|
||||
// Fetch current register status
|
||||
const fetchRegisterStatus = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/cash-register?siteId=${siteId}&status=open`
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error("Error al verificar estado de caja");
|
||||
}
|
||||
const data = await response.json();
|
||||
setRegister(data);
|
||||
onRegisterStatusChange(!!data, data?.id);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||
onRegisterStatusChange(false);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [siteId, onRegisterStatusChange]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchRegisterStatus();
|
||||
}, [fetchRegisterStatus]);
|
||||
|
||||
const handleOpenRegister = async () => {
|
||||
setActionLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch("/api/cash-register", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
siteId,
|
||||
openingAmount: parseFloat(openingAmount) || 0,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Error al abrir caja");
|
||||
}
|
||||
|
||||
setShowOpenDialog(false);
|
||||
setOpeningAmount("0");
|
||||
await fetchRegisterStatus();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCloseRegister = async () => {
|
||||
if (!register) return;
|
||||
|
||||
setActionLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`/api/cash-register/${register.id}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
closingAmount: parseFloat(closingAmount) || 0,
|
||||
notes: closingNotes || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Error al cerrar caja");
|
||||
}
|
||||
|
||||
setShowCloseDialog(false);
|
||||
setClosingAmount("");
|
||||
setClosingNotes("");
|
||||
await fetchRegisterStatus();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Loading state
|
||||
if (loading) {
|
||||
return (
|
||||
<Card className="mb-4">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-primary"></div>
|
||||
<span className="text-primary-500">Verificando estado de caja...</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Open Register Dialog
|
||||
if (showOpenDialog) {
|
||||
return (
|
||||
<Card className="mb-4">
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold text-primary-800 mb-4">
|
||||
Abrir Caja
|
||||
</h3>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium text-primary-700 block mb-2">
|
||||
Monto inicial en caja
|
||||
</label>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="0.00"
|
||||
value={openingAmount}
|
||||
onChange={(e) => setOpeningAmount(e.target.value)}
|
||||
min={0}
|
||||
step={0.01}
|
||||
disabled={actionLoading}
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<div className="p-3 rounded-lg bg-red-50 text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
onClick={() => {
|
||||
setShowOpenDialog(false);
|
||||
setError(null);
|
||||
}}
|
||||
disabled={actionLoading}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
className="flex-1"
|
||||
onClick={handleOpenRegister}
|
||||
disabled={actionLoading}
|
||||
>
|
||||
{actionLoading ? "Abriendo..." : "Abrir Caja"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Close Register Dialog
|
||||
if (showCloseDialog && register) {
|
||||
const expectedAmount = register.expectedAmount || 0;
|
||||
const closingValue = parseFloat(closingAmount) || 0;
|
||||
const difference = closingValue - expectedAmount;
|
||||
|
||||
return (
|
||||
<Card className="mb-4">
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-semibold text-primary-800 mb-4">
|
||||
Cerrar Caja
|
||||
</h3>
|
||||
<div className="space-y-4">
|
||||
{/* Expected Amount */}
|
||||
<div className="p-3 bg-primary-50 rounded-lg">
|
||||
<p className="text-sm text-primary-500">Monto esperado en caja</p>
|
||||
<p className="text-xl font-bold text-primary-800">
|
||||
{formatCurrency(expectedAmount)}
|
||||
</p>
|
||||
<p className="text-xs text-primary-400 mt-1">
|
||||
Apertura: {formatCurrency(Number(register.openingAmount))} + Ventas efectivo:{" "}
|
||||
{formatCurrency(register.totalCashSales || 0)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Closing Amount Input */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-primary-700 block mb-2">
|
||||
Monto real en caja
|
||||
</label>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="0.00"
|
||||
value={closingAmount}
|
||||
onChange={(e) => setClosingAmount(e.target.value)}
|
||||
min={0}
|
||||
step={0.01}
|
||||
disabled={actionLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Difference Display */}
|
||||
{closingAmount && (
|
||||
<div
|
||||
className={cn(
|
||||
"p-3 rounded-lg text-center",
|
||||
difference === 0
|
||||
? "bg-green-50"
|
||||
: difference > 0
|
||||
? "bg-blue-50"
|
||||
: "bg-red-50"
|
||||
)}
|
||||
>
|
||||
<p
|
||||
className={cn(
|
||||
"text-sm",
|
||||
difference === 0
|
||||
? "text-green-600"
|
||||
: difference > 0
|
||||
? "text-blue-600"
|
||||
: "text-red-600"
|
||||
)}
|
||||
>
|
||||
{difference === 0
|
||||
? "Cuadre perfecto"
|
||||
: difference > 0
|
||||
? "Sobrante"
|
||||
: "Faltante"}
|
||||
</p>
|
||||
<p
|
||||
className={cn(
|
||||
"text-xl font-bold",
|
||||
difference === 0
|
||||
? "text-green-700"
|
||||
: difference > 0
|
||||
? "text-blue-700"
|
||||
: "text-red-700"
|
||||
)}
|
||||
>
|
||||
{formatCurrency(Math.abs(difference))}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Notes */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-primary-700 block mb-2">
|
||||
Notas (opcional)
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Observaciones del cierre"
|
||||
value={closingNotes}
|
||||
onChange={(e) => setClosingNotes(e.target.value)}
|
||||
disabled={actionLoading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 rounded-lg bg-red-50 text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
onClick={() => {
|
||||
setShowCloseDialog(false);
|
||||
setError(null);
|
||||
}}
|
||||
disabled={actionLoading}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
className="flex-1"
|
||||
onClick={handleCloseRegister}
|
||||
disabled={actionLoading || !closingAmount}
|
||||
>
|
||||
{actionLoading ? "Cerrando..." : "Cerrar Caja"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Register is closed
|
||||
if (!register) {
|
||||
return (
|
||||
<Card className="mb-4 border-amber-300 bg-amber-50">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 rounded-full bg-amber-500"></div>
|
||||
<div>
|
||||
<p className="font-medium text-amber-800">Caja Cerrada</p>
|
||||
<p className="text-sm text-amber-600">
|
||||
Abre la caja para comenzar a vender
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={() => setShowOpenDialog(true)}>Abrir Caja</Button>
|
||||
</div>
|
||||
{error && (
|
||||
<div className="mt-3 p-3 rounded-lg bg-red-50 text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Register is open
|
||||
return (
|
||||
<Card className="mb-4 border-green-300 bg-green-50">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-3 h-3 rounded-full bg-green-500 animate-pulse"></div>
|
||||
<div>
|
||||
<p className="font-medium text-green-800">Caja Abierta</p>
|
||||
<p className="text-sm text-green-600">
|
||||
Por {register.user.firstName} {register.user.lastName}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Current Totals */}
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="text-right">
|
||||
<p className="text-xs text-green-600">Ventas hoy</p>
|
||||
<p className="font-semibold text-green-800">
|
||||
{register._count.sales}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-xs text-green-600">Efectivo esperado</p>
|
||||
<p className="font-semibold text-green-800">
|
||||
{formatCurrency(register.expectedAmount || 0)}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => setShowCloseDialog(true)}>
|
||||
Cerrar Caja
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment Breakdown */}
|
||||
{register.paymentBreakdown &&
|
||||
Object.keys(register.paymentBreakdown).length > 0 && (
|
||||
<div className="mt-3 pt-3 border-t border-green-200 flex gap-4">
|
||||
{register.paymentBreakdown.CASH !== undefined && (
|
||||
<span className="text-sm text-green-700">
|
||||
Efectivo: {formatCurrency(register.paymentBreakdown.CASH)}
|
||||
</span>
|
||||
)}
|
||||
{register.paymentBreakdown.CARD !== undefined && (
|
||||
<span className="text-sm text-green-700">
|
||||
Tarjeta: {formatCurrency(register.paymentBreakdown.CARD)}
|
||||
</span>
|
||||
)}
|
||||
{register.paymentBreakdown.TRANSFER !== undefined && (
|
||||
<span className="text-sm text-green-700">
|
||||
Transferencia:{" "}
|
||||
{formatCurrency(register.paymentBreakdown.TRANSFER)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="mt-3 p-3 rounded-lg bg-red-50 text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
5
apps/web/components/pos/index.ts
Normal file
5
apps/web/components/pos/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export { ProductGrid } from "./product-grid";
|
||||
export { Cart } from "./cart";
|
||||
export type { CartItem } from "./cart";
|
||||
export { PaymentDialog } from "./payment-dialog";
|
||||
export { CashRegisterStatus } from "./cash-register-status";
|
||||
277
apps/web/components/pos/payment-dialog.tsx
Normal file
277
apps/web/components/pos/payment-dialog.tsx
Normal file
@@ -0,0 +1,277 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { formatCurrency, cn } from "@/lib/utils";
|
||||
import { CartItem } from "./cart";
|
||||
|
||||
type PaymentMethod = "CASH" | "CARD" | "TRANSFER";
|
||||
|
||||
interface PaymentDialogProps {
|
||||
items: CartItem[];
|
||||
total: number;
|
||||
siteId: string;
|
||||
onClose: () => void;
|
||||
onPaymentComplete: (saleId: string) => void;
|
||||
}
|
||||
|
||||
const paymentMethods: { value: PaymentMethod; label: string; icon: string }[] = [
|
||||
{ value: "CASH", label: "Efectivo", icon: "💵" },
|
||||
{ value: "TRANSFER", label: "Transferencia", icon: "🏦" },
|
||||
{ value: "CARD", label: "Terminal", icon: "💳" },
|
||||
];
|
||||
|
||||
export function PaymentDialog({
|
||||
items,
|
||||
total,
|
||||
siteId,
|
||||
onClose,
|
||||
onPaymentComplete,
|
||||
}: PaymentDialogProps) {
|
||||
const [selectedMethod, setSelectedMethod] = useState<PaymentMethod>("CASH");
|
||||
const [cashReceived, setCashReceived] = useState<string>("");
|
||||
const [reference, setReference] = useState<string>("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const cashReceivedAmount = parseFloat(cashReceived) || 0;
|
||||
const change = cashReceivedAmount - total;
|
||||
const canPay =
|
||||
selectedMethod !== "CASH" || cashReceivedAmount >= total;
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!canPay) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const saleData = {
|
||||
siteId,
|
||||
items: items.map((item) => ({
|
||||
productId: item.id,
|
||||
quantity: item.quantity,
|
||||
price: item.price,
|
||||
})),
|
||||
payments: [
|
||||
{
|
||||
amount: total,
|
||||
method: selectedMethod,
|
||||
reference: reference || undefined,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const response = await fetch("/api/sales", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(saleData),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Error al procesar la venta");
|
||||
}
|
||||
|
||||
const sale = await response.json();
|
||||
onPaymentComplete(sale.id);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleQuickCash = (amount: number) => {
|
||||
setCashReceived(amount.toString());
|
||||
};
|
||||
|
||||
// Generate quick cash options based on total
|
||||
const quickCashOptions = [
|
||||
Math.ceil(total / 10) * 10,
|
||||
Math.ceil(total / 50) * 50,
|
||||
Math.ceil(total / 100) * 100,
|
||||
Math.ceil(total / 500) * 500,
|
||||
].filter((value, index, self) =>
|
||||
value >= total && self.indexOf(value) === index
|
||||
).slice(0, 4);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="border-b">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>Procesar Pago</CardTitle>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
className="w-5 h-5"
|
||||
>
|
||||
<path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" />
|
||||
</svg>
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="p-6 space-y-6">
|
||||
{/* Total Display */}
|
||||
<div className="text-center p-4 bg-primary-50 rounded-lg">
|
||||
<p className="text-sm text-primary-500 mb-1">Total a pagar</p>
|
||||
<p className="text-3xl font-bold text-primary-800">
|
||||
{formatCurrency(total)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Payment Method Selection */}
|
||||
<div>
|
||||
<p className="text-sm font-medium text-primary-700 mb-3">
|
||||
Metodo de pago
|
||||
</p>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{paymentMethods.map((method) => (
|
||||
<button
|
||||
key={method.value}
|
||||
className={cn(
|
||||
"p-3 rounded-lg border-2 text-center transition-all",
|
||||
selectedMethod === method.value
|
||||
? "border-primary bg-primary-50"
|
||||
: "border-primary-200 hover:border-primary-300"
|
||||
)}
|
||||
onClick={() => setSelectedMethod(method.value)}
|
||||
disabled={loading}
|
||||
>
|
||||
<span className="text-2xl block mb-1">{method.icon}</span>
|
||||
<span className="text-sm font-medium text-primary-700">
|
||||
{method.label}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Cash Payment Options */}
|
||||
{selectedMethod === "CASH" && (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium text-primary-700 block mb-2">
|
||||
Monto recibido
|
||||
</label>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="0.00"
|
||||
value={cashReceived}
|
||||
onChange={(e) => setCashReceived(e.target.value)}
|
||||
className="text-lg font-medium"
|
||||
min={0}
|
||||
step={0.01}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Quick Cash Buttons */}
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{quickCashOptions.map((amount) => (
|
||||
<Button
|
||||
key={amount}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleQuickCash(amount)}
|
||||
disabled={loading}
|
||||
>
|
||||
{formatCurrency(amount)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Change Display */}
|
||||
{cashReceivedAmount > 0 && (
|
||||
<div
|
||||
className={cn(
|
||||
"p-3 rounded-lg text-center",
|
||||
change >= 0 ? "bg-green-50" : "bg-red-50"
|
||||
)}
|
||||
>
|
||||
<p
|
||||
className={cn(
|
||||
"text-sm mb-1",
|
||||
change >= 0 ? "text-green-600" : "text-red-600"
|
||||
)}
|
||||
>
|
||||
{change >= 0 ? "Cambio" : "Falta"}
|
||||
</p>
|
||||
<p
|
||||
className={cn(
|
||||
"text-2xl font-bold",
|
||||
change >= 0 ? "text-green-700" : "text-red-700"
|
||||
)}
|
||||
>
|
||||
{formatCurrency(Math.abs(change))}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Transfer Reference */}
|
||||
{(selectedMethod === "TRANSFER" || selectedMethod === "CARD") && (
|
||||
<div>
|
||||
<label className="text-sm font-medium text-primary-700 block mb-2">
|
||||
Referencia (opcional)
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Numero de referencia o autorizacion"
|
||||
value={reference}
|
||||
onChange={(e) => setReference(e.target.value)}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="p-3 rounded-lg bg-red-50 text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="border-t p-4 gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
className="flex-1"
|
||||
onClick={handleSubmit}
|
||||
disabled={!canPay || loading}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
|
||||
Procesando...
|
||||
</>
|
||||
) : (
|
||||
"Confirmar Pago"
|
||||
)}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
260
apps/web/components/pos/product-grid.tsx
Normal file
260
apps/web/components/pos/product-grid.tsx
Normal file
@@ -0,0 +1,260 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { formatCurrency, cn } from "@/lib/utils";
|
||||
|
||||
interface Category {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
_count: {
|
||||
products: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface Product {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
sku: string | null;
|
||||
price: number;
|
||||
stock: number;
|
||||
minStock: number;
|
||||
trackStock: boolean;
|
||||
image: string | null;
|
||||
lowStock: boolean;
|
||||
category: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface ProductGridProps {
|
||||
siteId: string;
|
||||
onAddToCart: (product: Product) => void;
|
||||
}
|
||||
|
||||
export function ProductGrid({ siteId, onAddToCart }: ProductGridProps) {
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Fetch categories
|
||||
useEffect(() => {
|
||||
async function fetchCategories() {
|
||||
try {
|
||||
const response = await fetch("/api/products/categories");
|
||||
if (!response.ok) {
|
||||
throw new Error("Error al cargar categorias");
|
||||
}
|
||||
const data = await response.json();
|
||||
setCategories(data);
|
||||
} catch (err) {
|
||||
console.error("Error fetching categories:", err);
|
||||
}
|
||||
}
|
||||
|
||||
fetchCategories();
|
||||
}, []);
|
||||
|
||||
// Fetch products
|
||||
useEffect(() => {
|
||||
async function fetchProducts() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const params = new URLSearchParams({ siteId, isActive: "true" });
|
||||
if (selectedCategory) {
|
||||
params.append("categoryId", selectedCategory);
|
||||
}
|
||||
if (searchQuery) {
|
||||
params.append("search", searchQuery);
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/products?${params.toString()}`);
|
||||
if (!response.ok) {
|
||||
throw new Error("Error al cargar productos");
|
||||
}
|
||||
const data = await response.json();
|
||||
setProducts(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error desconocido");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Debounce search
|
||||
const timeoutId = setTimeout(fetchProducts, searchQuery ? 300 : 0);
|
||||
return () => clearTimeout(timeoutId);
|
||||
}, [siteId, selectedCategory, searchQuery]);
|
||||
|
||||
// Filter products based on category and search
|
||||
const filteredProducts = useMemo(() => {
|
||||
return products;
|
||||
}, [products]);
|
||||
|
||||
const handleProductClick = (product: Product) => {
|
||||
if (product.trackStock && product.stock <= 0) {
|
||||
return; // Cannot add out of stock products
|
||||
}
|
||||
onAddToCart(product);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
{/* Search Input */}
|
||||
<div className="mb-4">
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Buscar productos..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Category Tabs */}
|
||||
<div className="flex gap-2 mb-4 overflow-x-auto pb-2">
|
||||
<Button
|
||||
variant={selectedCategory === null ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setSelectedCategory(null)}
|
||||
>
|
||||
Todos
|
||||
</Button>
|
||||
{categories.map((category) => (
|
||||
<Button
|
||||
key={category.id}
|
||||
variant={selectedCategory === category.id ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setSelectedCategory(category.id)}
|
||||
className="whitespace-nowrap"
|
||||
>
|
||||
{category.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Loading State */}
|
||||
{loading && (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
|
||||
<p className="text-primary-500">Cargando productos...</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error State */}
|
||||
{error && !loading && (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center text-red-500">
|
||||
<p>{error}</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mt-2"
|
||||
onClick={() => setSearchQuery("")}
|
||||
>
|
||||
Reintentar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Empty State */}
|
||||
{!loading && !error && filteredProducts.length === 0 && (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<div className="text-center text-primary-500">
|
||||
<p>No se encontraron productos</p>
|
||||
{searchQuery && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mt-2"
|
||||
onClick={() => setSearchQuery("")}
|
||||
>
|
||||
Limpiar busqueda
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Product Grid */}
|
||||
{!loading && !error && filteredProducts.length > 0 && (
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
|
||||
{filteredProducts.map((product) => {
|
||||
const isOutOfStock = product.trackStock && product.stock <= 0;
|
||||
const isLowStock = product.lowStock;
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={product.id}
|
||||
className={cn(
|
||||
"p-4 cursor-pointer transition-all hover:shadow-md",
|
||||
isOutOfStock && "opacity-50 cursor-not-allowed bg-gray-100",
|
||||
isLowStock && !isOutOfStock && "border-amber-400 border-2"
|
||||
)}
|
||||
onClick={() => handleProductClick(product)}
|
||||
>
|
||||
{/* Product Image Placeholder */}
|
||||
{product.image ? (
|
||||
<div className="w-full h-24 mb-3 rounded-md overflow-hidden">
|
||||
<img
|
||||
src={product.image}
|
||||
alt={product.name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="w-full h-24 mb-3 bg-primary-100 rounded-md flex items-center justify-center">
|
||||
<span className="text-3xl text-primary-300">
|
||||
{product.name.charAt(0).toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Product Info */}
|
||||
<h3 className="font-medium text-primary-800 text-sm truncate">
|
||||
{product.name}
|
||||
</h3>
|
||||
<p className="text-primary-600 font-bold mt-1">
|
||||
{formatCurrency(product.price)}
|
||||
</p>
|
||||
|
||||
{/* Stock Indicator */}
|
||||
{product.trackStock && (
|
||||
<div className="mt-2">
|
||||
{isOutOfStock ? (
|
||||
<span className="text-xs text-red-500 font-medium">
|
||||
Agotado
|
||||
</span>
|
||||
) : isLowStock ? (
|
||||
<span className="text-xs text-amber-600 font-medium">
|
||||
Stock bajo: {product.stock}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-primary-400">
|
||||
Stock: {product.stock}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user