feat(F-186): completed feature

This commit is contained in:
chattie
2026-08-22 22:08:09 +02:00
parent 63a305bdd4
commit a3f6edd325
30 changed files with 3603 additions and 624 deletions

View File

@@ -1,9 +1,13 @@
'use client';
import { useEffect, useState } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { api } from '@/lib/api-client';
interface PosStore { id: string; name: string; active: boolean }
interface PosStore {
id: string;
name: string;
active: boolean;
}
interface PosTerminal {
id: string;
storeId: string;
@@ -11,29 +15,106 @@ interface PosTerminal {
bindingCode: string | null;
boundAt: string | null;
status: string;
lastSeenAt: string | null;
settings?: { touchNavigationEnabled?: boolean; quickProductVariantIds?: Array<string | null> };
settings?: {
touchNavigationEnabled?: boolean;
quickProductVariantIds?: Array<string | null>;
lineDiscountsEnabled?: boolean;
};
}
interface CatalogOption { variantId: string; productId: string; name: string; sku: string; priceCents: number }
interface CatalogOption {
variantId: string;
name: string;
sku: string;
}
interface PaymentMethod {
id: string;
storeId: string;
code: string;
label: string;
kind: 'cash' | 'card' | 'other';
active: boolean;
sortOrder: number;
}
interface ReceiptSettings {
storeId: string;
name: string;
address: string;
taxId: string;
contactEmail: string;
contactPhone: string;
receiptHeader: string;
receiptFooter: string;
prefix: string;
nextNumber: number;
padding: number;
returnPolicy: string;
}
const emptyReceipt: ReceiptSettings = {
storeId: '',
name: '',
address: '',
taxId: '',
contactEmail: '',
contactPhone: '',
receiptHeader: '',
receiptFooter: '',
prefix: 'TPV',
nextNumber: 1,
padding: 6,
returnPolicy: 'Se admiten devoluciones durante 15 días con el ticket de compra.',
};
export default function PosAdminPage() {
const [stores, setStores] = useState<PosStore[]>([]);
const [terminals, setTerminals] = useState<PosTerminal[]>([]);
const [catalogOptions, setCatalogOptions] = useState<CatalogOption[]>([]);
const [storeId, setStoreId] = useState('');
const [name, setName] = useState('');
const [terminalName, setTerminalName] = useState('');
const [loading, setLoading] = useState(true);
const [creating, setCreating] = useState(false);
const [error, setError] = useState('');
const [newCode, setNewCode] = useState('');
const [copied, setCopied] = useState('');
const [catalogOptions, setCatalogOptions] = useState<CatalogOption[]>([]);
const [configuring, setConfiguring] = useState<PosTerminal | null>(null);
const [touchEnabled, setTouchEnabled] = useState(true);
const [quickSlots, setQuickSlots] = useState<Array<string | null>>([null, null, null, null]);
const [discountsEnabled, setDiscountsEnabled] = useState(true);
const [quickSlots, setQuickSlots] = useState<Array<string | null>>(
Array.from({ length: 8 }, () => null),
);
const [savingTouch, setSavingTouch] = useState(false);
const [touchMessage, setTouchMessage] = useState('');
const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([]);
const [newMethod, setNewMethod] = useState({
code: '',
label: '',
kind: 'other' as PaymentMethod['kind'],
});
const [savingMethod, setSavingMethod] = useState(false);
const [paymentMessage, setPaymentMessage] = useState('');
const [receipt, setReceipt] = useState<ReceiptSettings>(emptyReceipt);
const [savingReceipt, setSavingReceipt] = useState(false);
const [receiptMessage, setReceiptMessage] = useState('');
const load = async () => {
const loadStoreConfiguration = useCallback(async (selectedStoreId: string) => {
if (!selectedStoreId) return;
try {
const [methodData, receiptData] = await Promise.all([
api.get<{ items: PaymentMethod[] }>(
`/api/pos/admin/payment-methods?storeId=${encodeURIComponent(selectedStoreId)}`,
),
api.get<Partial<ReceiptSettings>>(
`/api/pos/admin/receipt-settings?storeId=${encodeURIComponent(selectedStoreId)}`,
),
]);
setPaymentMethods(methodData.items);
setReceipt({ ...emptyReceipt, ...receiptData, storeId: selectedStoreId });
} catch (err) {
setError(err instanceof Error ? err.message : 'No se pudo cargar la configuración de cobro');
}
}, []);
const load = useCallback(async () => {
setLoading(true);
setError('');
try {
@@ -45,15 +126,26 @@ export default function PosAdminPage() {
setStores(storeData.stores);
setTerminals(terminalData.terminals);
setCatalogOptions(catalogData.items);
setStoreId((current) => current || storeData.stores.find((store) => store.active)?.id || '');
const selected = storeId || storeData.stores.find((store) => store.active)?.id || '';
setStoreId(selected);
await loadStoreConfiguration(selected);
} catch (err) {
setError(err instanceof Error ? err.message : 'No se pudo cargar la configuración TPV');
} finally {
setLoading(false);
}
};
}, [loadStoreConfiguration, storeId]);
useEffect(() => { void load(); }, []);
useEffect(() => {
void load();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const changeStore = (nextStoreId: string) => {
setStoreId(nextStoreId);
setReceiptMessage('');
setPaymentMessage('');
void loadStoreConfiguration(nextStoreId);
};
const createTerminal = async (event: React.FormEvent) => {
event.preventDefault();
@@ -61,8 +153,11 @@ export default function PosAdminPage() {
setError('');
setNewCode('');
try {
const terminal = await api.post<PosTerminal>('/api/pos/admin/terminals', { storeId, name: name.trim() });
setName('');
const terminal = await api.post<PosTerminal>('/api/pos/admin/terminals', {
storeId,
name: terminalName.trim(),
});
setTerminalName('');
setNewCode(terminal.bindingCode ?? '');
await load();
} catch (err) {
@@ -75,8 +170,9 @@ export default function PosAdminPage() {
const openTouchConfig = (terminal: PosTerminal) => {
setConfiguring(terminal);
setTouchEnabled(terminal.settings?.touchNavigationEnabled !== false);
setDiscountsEnabled(terminal.settings?.lineDiscountsEnabled !== false);
const configured = terminal.settings?.quickProductVariantIds ?? [];
setQuickSlots([0, 1, 2, 3].map((slot) => configured[slot] ?? null));
setQuickSlots(Array.from({ length: 8 }, (_, slot) => configured[slot] ?? null));
setTouchMessage('');
};
@@ -87,9 +183,10 @@ export default function PosAdminPage() {
try {
await api.patch(`/api/pos/admin/terminals/${configuring.id}/touch-config`, {
touchNavigationEnabled: touchEnabled,
lineDiscountsEnabled: discountsEnabled,
quickProductVariantIds: quickSlots,
});
setTouchMessage('Configuración táctil guardada');
setTouchMessage('Configuración del terminal guardada');
await load();
} catch (err) {
setTouchMessage(err instanceof Error ? err.message : 'No se pudo guardar');
@@ -98,98 +195,458 @@ export default function PosAdminPage() {
}
};
const createPaymentMethod = async (event: React.FormEvent) => {
event.preventDefault();
setSavingMethod(true);
setPaymentMessage('');
try {
await api.post('/api/pos/admin/payment-methods', {
storeId,
code: newMethod.code.trim().toLowerCase(),
label: newMethod.label.trim(),
kind: newMethod.kind,
active: true,
sortOrder: paymentMethods.length,
});
setNewMethod({ code: '', label: '', kind: 'other' });
setPaymentMessage('Forma de pago creada');
await loadStoreConfiguration(storeId);
} catch (err) {
setPaymentMessage(err instanceof Error ? err.message : 'No se pudo crear la forma de pago');
} finally {
setSavingMethod(false);
}
};
const togglePaymentMethod = async (method: PaymentMethod) => {
setPaymentMessage('');
try {
await api.patch(`/api/pos/admin/payment-methods/${method.id}`, { active: !method.active });
setPaymentMessage(method.active ? 'Forma de pago desactivada' : 'Forma de pago activada');
await loadStoreConfiguration(storeId);
} catch (err) {
setPaymentMessage(err instanceof Error ? err.message : 'No se pudo actualizar');
}
};
const saveReceipt = async (event: React.FormEvent) => {
event.preventDefault();
setSavingReceipt(true);
setReceiptMessage('');
try {
await api.patch('/api/pos/admin/receipt-settings', receipt);
setReceiptMessage('Datos y numeración del ticket guardados');
await loadStoreConfiguration(storeId);
} catch (err) {
setReceiptMessage(err instanceof Error ? err.message : 'No se pudo guardar el ticket');
} finally {
setSavingReceipt(false);
}
};
const copyCode = async (code: string) => {
await navigator.clipboard.writeText(code);
setCopied(code);
setTimeout(() => setCopied(''), 2000);
window.setTimeout(() => setCopied(''), 2000);
};
return (
<div className="space-y-6">
<div>
<header>
<h1 className="text-2xl font-bold text-gray-900">TPV</h1>
<p className="mt-0.5 text-sm text-gray-500">Configura dispositivos y obtén el código para vincular cada caja.</p>
</div>
<p className="mt-0.5 text-sm text-gray-500">
Configura terminales táctiles, formas de pago y contenido fiscal del ticket.
</p>
</header>
<div className="grid gap-4 md:grid-cols-2">
<div className="rounded-xl border border-blue-200 bg-blue-50 p-5 text-sm text-blue-900">
<h2 className="font-bold">1. Vincular terminal</h2>
<p className="mt-1">Crea un terminal aquí y escribe su código de 8 caracteres en el navegador del TPV. Esto identifica qué caja física está vendiendo.</p>
</div>
<div className="rounded-xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-900">
<h2 className="font-bold">2. Abrir sesión de caja</h2>
<p className="mt-1">Después de vincular, el cajero indica el efectivo inicial en el propio TPV. La sesión representa el turno diario de caja.</p>
</div>
</div>
<label className="block max-w-md text-sm font-medium text-gray-700">
Tienda que estás configurando
<select
value={storeId}
onChange={(event) => changeStore(event.target.value)}
className="mt-1 w-full rounded-xl border border-gray-300 bg-white px-3 py-2.5"
>
{stores
.filter((store) => store.active)
.map((store) => (
<option key={store.id} value={store.id}>
{store.name}
</option>
))}
</select>
</label>
<form onSubmit={createTerminal} className="rounded-xl border border-gray-200 bg-white p-6">
<h2 className="mb-4 font-bold text-gray-900">Crear terminal</h2>
<div className="grid gap-4 md:grid-cols-[1fr_1fr_auto] md:items-end">
<label className="text-sm font-medium text-gray-700">
Tienda
<select value={storeId} onChange={(event) => setStoreId(event.target.value)} required className="mt-1 w-full rounded-xl border border-gray-300 bg-white px-3 py-2.5">
{stores.filter((store) => store.active).map((store) => <option key={store.id} value={store.id}>{store.name}</option>)}
</select>
</label>
<label className="text-sm font-medium text-gray-700">
<h2 className="mb-4 font-bold text-gray-900">Crear y vincular terminal</h2>
<div className="flex flex-wrap items-end gap-4">
<label className="min-w-64 flex-1 text-sm font-medium text-gray-700">
Nombre del terminal
<input value={name} onChange={(event) => setName(event.target.value)} required maxLength={100} placeholder="Caja principal" className="mt-1 w-full rounded-xl border border-gray-300 px-3 py-2.5" />
<input
value={terminalName}
onChange={(event) => setTerminalName(event.target.value)}
required
maxLength={100}
placeholder="Caja principal"
className="mt-1 w-full rounded-xl border border-gray-300 px-3 py-2.5"
/>
</label>
<button type="submit" disabled={creating || !storeId || !name.trim()} className="rounded-xl bg-[#2D6A4F] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50">
<button
disabled={creating || !storeId || !terminalName.trim()}
className="rounded-xl bg-[#2D6A4F] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
>
{creating ? 'Creando…' : 'Crear terminal'}
</button>
</div>
{newCode && <p className="mt-4 rounded-lg bg-green-50 p-3 text-sm text-green-800">Código creado: <strong className="font-mono text-lg tracking-widest">{newCode}</strong></p>}
{newCode && (
<p className="mt-4 rounded-lg bg-green-50 p-3 text-sm text-green-800">
Código: <strong className="font-mono text-lg tracking-widest">{newCode}</strong>
</p>
)}
{error && <p className="mt-4 text-sm text-red-600">{error}</p>}
</form>
<div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
<div className="border-b border-gray-200 px-6 py-4"><h2 className="font-bold text-gray-900">Terminales</h2></div>
{loading ? <p className="p-6 text-sm text-gray-500">Cargando</p> : terminals.length === 0 ? <p className="p-6 text-sm text-gray-500">No hay terminales.</p> : (
<section className="overflow-hidden rounded-xl border border-gray-200 bg-white">
<div className="border-b px-6 py-4">
<h2 className="font-bold">Terminales</h2>
</div>
{loading ? (
<p className="p-6 text-sm text-gray-500">Cargando</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="bg-gray-50 text-left text-xs uppercase text-gray-500"><tr><th className="px-4 py-3">Nombre</th><th className="px-4 py-3">Tienda</th><th className="px-4 py-3">Código</th><th className="px-4 py-3">Estado</th><th className="px-4 py-3">Vinculado</th><th className="px-4 py-3">Interfaz</th></tr></thead>
<tbody className="divide-y divide-gray-100">
{terminals.map((terminal) => {
const store = stores.find((item) => item.id === terminal.storeId);
return <tr key={terminal.id}><td className="px-4 py-3 font-medium">{terminal.name}</td><td className="px-4 py-3">{store?.name ?? terminal.storeId}</td><td className="px-4 py-3"><button type="button" onClick={() => terminal.bindingCode && void copyCode(terminal.bindingCode)} disabled={!terminal.bindingCode} className="rounded-lg bg-gray-100 px-3 py-1 font-mono tracking-wider hover:bg-gray-200 disabled:opacity-40">{copied === terminal.bindingCode ? 'Copiado' : terminal.bindingCode ?? '—'}</button></td><td className="px-4 py-3 capitalize">{terminal.status}</td><td className="px-4 py-3">{terminal.boundAt ? 'Sí' : 'No'}</td><td className="px-4 py-3"><button type="button" onClick={() => openTouchConfig(terminal)} className="rounded-lg border border-[#2D6A4F] px-3 py-1.5 text-xs font-semibold text-[#2D6A4F] hover:bg-green-50">Configurar táctil</button></td></tr>;
})}
<thead className="bg-gray-50 text-left text-xs uppercase text-gray-500">
<tr>
<th className="px-4 py-3">Nombre</th>
<th className="px-4 py-3">Código</th>
<th className="px-4 py-3">Estado</th>
<th className="px-4 py-3">Vinculado</th>
<th className="px-4 py-3">Configuración</th>
</tr>
</thead>
<tbody className="divide-y">
{terminals
.filter((terminal) => terminal.storeId === storeId)
.map((terminal) => (
<tr key={terminal.id}>
<td className="px-4 py-3 font-medium">{terminal.name}</td>
<td className="px-4 py-3">
<button
type="button"
onClick={() =>
terminal.bindingCode && void copyCode(terminal.bindingCode)
}
disabled={!terminal.bindingCode}
className="rounded-lg bg-gray-100 px-3 py-1 font-mono"
>
{copied === terminal.bindingCode
? 'Copiado'
: (terminal.bindingCode ?? '—')}
</button>
</td>
<td className="px-4 py-3">{terminal.status}</td>
<td className="px-4 py-3">{terminal.boundAt ? 'Sí' : 'No'}</td>
<td className="px-4 py-3">
<button
type="button"
onClick={() => openTouchConfig(terminal)}
className="rounded-lg border border-[#2D6A4F] px-3 py-1.5 text-xs font-semibold text-[#2D6A4F]"
>
Configurar terminal
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</section>
{configuring && (
<section className="rounded-xl border border-gray-200 bg-white p-6">
<div className="flex items-start justify-between gap-4">
<div className="flex justify-between">
<div>
<h2 className="font-bold text-gray-900">Interfaz táctil · {configuring.name}</h2>
<p className="mt-1 text-sm text-gray-500">Las categorías y subcategorías se administran en Categorías. Aquí activas su navegación en este terminal y eliges cuatro productos rápidos.</p>
<h2 className="font-bold">Interfaz táctil · {configuring.name}</h2>
<p className="mt-1 text-sm text-gray-500">
Elige hasta ocho productos rápidos y las funciones disponibles en esta caja.
</p>
</div>
<button type="button" onClick={() => setConfiguring(null)} className="text-gray-400 hover:text-gray-700" aria-label="Cerrar"></button>
<button type="button" onClick={() => setConfiguring(null)} aria-label="Cerrar">
</button>
</div>
<label className="mt-5 flex items-center gap-3 rounded-xl bg-gray-50 p-4 text-sm font-medium text-gray-800">
<input type="checkbox" checked={touchEnabled} onChange={(event) => setTouchEnabled(event.target.checked)} className="h-5 w-5 accent-[#2D6A4F]" />
Activar botones grandes categoría subcategoría producto
</label>
<div className="mt-5 grid gap-3 md:grid-cols-2">
<label className="flex items-center gap-3 rounded-xl bg-gray-50 p-4 text-sm font-medium">
<input
type="checkbox"
checked={touchEnabled}
onChange={(event) => setTouchEnabled(event.target.checked)}
className="h-5 w-5 accent-[#2D6A4F]"
/>{' '}
Navegación táctil por categorías
</label>
<label className="flex items-center gap-3 rounded-xl bg-gray-50 p-4 text-sm font-medium">
<input
type="checkbox"
checked={discountsEnabled}
onChange={(event) => setDiscountsEnabled(event.target.checked)}
className="h-5 w-5 accent-[#2D6A4F]"
/>{' '}
Permitir descuentos por línea
</label>
</div>
<p className="mt-2 text-xs text-gray-500">
Desactiva descuentos para terminales de autopago.
</p>
<div className="mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
{quickSlots.map((variantId, slot) => (
<label key={slot} className="text-sm font-medium text-gray-700">
Producto rápido {slot + 1}
<select value={variantId ?? ''} onChange={(event) => setQuickSlots((current) => current.map((value, index) => index === slot ? event.target.value || null : value))} className="mt-1 w-full rounded-xl border border-gray-300 bg-white px-3 py-2.5">
<select
value={variantId ?? ''}
onChange={(event) =>
setQuickSlots((current) =>
current.map((value, index) =>
index === slot ? event.target.value || null : value,
),
)
}
className="mt-1 w-full rounded-xl border bg-white px-3 py-2.5"
>
<option value="">Sin asignar</option>
{catalogOptions.map((product) => <option key={product.variantId} value={product.variantId}>{product.name} · {product.sku}</option>)}
{catalogOptions.map((product) => (
<option key={product.variantId} value={product.variantId}>
{product.name} · {product.sku}
</option>
))}
</select>
</label>
))}
</div>
<div className="mt-5 flex items-center gap-4">
<button type="button" onClick={() => void saveTouchConfig()} disabled={savingTouch} className="rounded-xl bg-[#2D6A4F] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50">{savingTouch ? 'Guardando…' : 'Guardar interfaz táctil'}</button>
{touchMessage && <p className={`text-sm ${touchMessage.includes('guardada') ? 'text-green-700' : 'text-red-600'}`}>{touchMessage}</p>}
<button
type="button"
onClick={() => void saveTouchConfig()}
disabled={savingTouch}
className="rounded-xl bg-[#2D6A4F] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
>
{savingTouch ? 'Guardando…' : 'Guardar terminal'}
</button>
{touchMessage && <p className="text-sm">{touchMessage}</p>}
</div>
</section>
)}
<section className="rounded-xl border border-gray-200 bg-white p-6">
<div>
<h2 className="font-bold">Formas de pago</h2>
<p className="mt-1 text-sm text-gray-500">
Crea Bizum, Stripe, Apple Pay u otro método. Tarjeta y otro se registran
manualmente; no activan una pasarela externa.
</p>
</div>
<div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
{paymentMethods.map((method) => (
<div
key={method.id}
className={`flex items-center justify-between rounded-xl border p-4 ${method.active ? 'border-green-200 bg-green-50' : 'border-gray-200 bg-gray-50 opacity-70'}`}
>
<div>
<strong className="block">{method.label}</strong>
<span className="text-xs text-gray-500">
{method.code} · {method.kind}
</span>
</div>
<button
type="button"
onClick={() => void togglePaymentMethod(method)}
className="rounded-lg border bg-white px-3 py-2 text-xs font-semibold"
>
{method.active ? 'Desactivar' : 'Activar'}
</button>
</div>
))}
</div>
<form
onSubmit={createPaymentMethod}
className="mt-5 grid gap-3 rounded-xl bg-gray-50 p-4 md:grid-cols-[1fr_1fr_1fr_auto] md:items-end"
>
<label className="text-sm font-medium">
Código
<input
value={newMethod.code}
onChange={(event) =>
setNewMethod({
...newMethod,
code: event.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, ''),
})
}
required
maxLength={32}
placeholder="bizum"
className="mt-1 w-full rounded-xl border px-3 py-2.5"
/>
</label>
<label className="text-sm font-medium">
Nombre visible
<input
value={newMethod.label}
onChange={(event) => setNewMethod({ ...newMethod, label: event.target.value })}
required
maxLength={64}
placeholder="Bizum"
className="mt-1 w-full rounded-xl border px-3 py-2.5"
/>
</label>
<label className="text-sm font-medium">
Tipo
<select
value={newMethod.kind}
onChange={(event) =>
setNewMethod({ ...newMethod, kind: event.target.value as PaymentMethod['kind'] })
}
className="mt-1 w-full rounded-xl border bg-white px-3 py-2.5"
>
<option value="cash">Efectivo</option>
<option value="card">Tarjeta</option>
<option value="other">Otro</option>
</select>
</label>
<button
disabled={savingMethod}
className="rounded-xl bg-[#2D6A4F] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
>
Añadir
</button>
</form>
{paymentMessage && <p className="mt-3 text-sm">{paymentMessage}</p>}
</section>
<form onSubmit={saveReceipt} className="rounded-xl border border-gray-200 bg-white p-6">
<div>
<h2 className="font-bold">Empresa, numeración y política del ticket</h2>
<p className="mt-1 text-sm text-gray-500">
Estos datos se congelan en cada ticket emitido.
</p>
</div>
<div className="mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
<Field
label="Razón social / nombre"
value={receipt.name}
onChange={(value) => setReceipt({ ...receipt, name: value })}
required
/>
<Field
label="NIF / CIF"
value={receipt.taxId}
onChange={(value) => setReceipt({ ...receipt, taxId: value })}
/>
<Field
label="Dirección"
value={receipt.address}
onChange={(value) => setReceipt({ ...receipt, address: value })}
/>
<Field
label="Email"
type="email"
value={receipt.contactEmail}
onChange={(value) => setReceipt({ ...receipt, contactEmail: value })}
/>
<Field
label="Teléfono"
value={receipt.contactPhone}
onChange={(value) => setReceipt({ ...receipt, contactPhone: value })}
/>
<Field
label="Cabecera"
value={receipt.receiptHeader}
onChange={(value) => setReceipt({ ...receipt, receiptHeader: value })}
/>
<Field
label="Pie"
value={receipt.receiptFooter}
onChange={(value) => setReceipt({ ...receipt, receiptFooter: value })}
/>
<Field
label="Prefijo de ticket"
value={receipt.prefix}
onChange={(value) =>
setReceipt({ ...receipt, prefix: value.toUpperCase().replace(/[^A-Z0-9_-]/g, '') })
}
required
/>
<Field
label="Próximo número"
type="number"
value={String(receipt.nextNumber)}
onChange={(value) => setReceipt({ ...receipt, nextNumber: Number(value) })}
required
min={1}
/>
<Field
label="Dígitos (relleno)"
type="number"
value={String(receipt.padding)}
onChange={(value) => setReceipt({ ...receipt, padding: Number(value) })}
required
min={1}
max={12}
/>
</div>
<label className="mt-4 block text-sm font-medium">
Política de devolución
<textarea
value={receipt.returnPolicy}
onChange={(event) => setReceipt({ ...receipt, returnPolicy: event.target.value })}
required
maxLength={2000}
rows={3}
className="mt-1 w-full rounded-xl border px-3 py-2.5"
/>
</label>
<div className="mt-5 flex items-center gap-4">
<button
disabled={savingReceipt}
className="rounded-xl bg-[#2D6A4F] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-50"
>
{savingReceipt ? 'Guardando…' : 'Guardar ticket'}
</button>
{receiptMessage && <p className="text-sm">{receiptMessage}</p>}
</div>
</form>
</div>
);
}
function Field({
label,
value,
onChange,
type = 'text',
required = false,
min,
max,
}: {
label: string;
value: string;
onChange: (value: string) => void;
type?: string;
required?: boolean;
min?: number;
max?: number;
}) {
return (
<label className="text-sm font-medium text-gray-700">
{label}
<input
type={type}
value={value}
onChange={(event) => onChange(event.target.value)}
required={required}
min={min}
max={max}
className="mt-1 w-full rounded-xl border border-gray-300 px-3 py-2.5"
/>
</label>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,95 @@
'use client';
import { useState } from 'react';
interface FreeItemModalProps {
onAdd: (item: { name: string; unitPriceCents: number }) => void;
onClose: () => void;
}
export default function FreeItemModal({ onAdd, onClose }: FreeItemModalProps) {
const [name, setName] = useState('');
const [price, setPrice] = useState('');
const [error, setError] = useState('');
const submit = (event: React.FormEvent) => {
event.preventDefault();
const normalized = price.trim().replace(',', '.');
const unitPriceCents = /^\d+(?:\.\d{1,2})?$/.test(normalized)
? Math.round(Number(normalized) * 100)
: 0;
if (!name.trim() || unitPriceCents <= 0) {
setError('Indica un nombre y un precio positivo');
return;
}
onAdd({ name: name.trim(), unitPriceCents });
};
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
role="dialog"
aria-modal="true"
aria-labelledby="free-item-title"
>
<form
onSubmit={submit}
className="w-full max-w-md space-y-5 rounded-2xl bg-white p-6 shadow-2xl"
>
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-sm font-semibold text-[#2D6A4F]">Sin producto de almacén</p>
<h2 id="free-item-title" className="text-2xl font-bold text-gray-900">
Artículo libre
</h2>
</div>
<button
type="button"
onClick={onClose}
className="min-h-12 min-w-12 rounded-xl bg-gray-100 text-xl"
aria-label="Cerrar"
>
</button>
</div>
<label className="block text-sm font-semibold text-gray-700">
Nombre o servicio
<input
value={name}
onChange={(event) => {
setName(event.target.value);
setError('');
}}
required
maxLength={200}
autoFocus
className="mt-1 min-h-12 w-full rounded-xl border-2 border-gray-200 px-4 outline-none focus:border-[#2D6A4F]"
placeholder="Ej. Asesoría nutricional"
/>
</label>
<label className="block text-sm font-semibold text-gray-700">
Precio ()
<input
value={price}
onChange={(event) => {
setPrice(event.target.value);
setError('');
}}
required
inputMode="decimal"
className="mt-1 min-h-12 w-full rounded-xl border-2 border-gray-200 px-4 text-xl font-bold outline-none focus:border-[#2D6A4F]"
placeholder="0,00"
/>
</label>
{error && (
<p className="text-sm font-medium text-red-600" aria-live="polite">
{error}
</p>
)}
<button className="min-h-14 w-full rounded-xl bg-[#2D6A4F] font-bold text-white">
Añadir al ticket
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,168 @@
'use client';
import { useMemo, useState } from 'react';
import { formatPrice } from '@/lib/money';
import type { PaymentAllocation, PaymentMethod } from '@/types/checkout';
interface PaymentModalProps {
method: PaymentMethod;
remainingCents: number;
onAdd: (allocation: PaymentAllocation) => void;
onClose: () => void;
}
export default function PaymentModal({
method,
remainingCents,
onAdd,
onClose,
}: PaymentModalProps) {
const [mode, setMode] = useState<'total' | 'partial'>('total');
const [amount, setAmount] = useState(centsToInput(remainingCents));
const [tendered, setTendered] = useState(centsToInput(remainingCents));
const [error, setError] = useState('');
const amountCents = useMemo(() => parseEuros(amount), [amount]);
const tenderedCents = useMemo(() => parseEuros(tendered), [tendered]);
const changeCents =
method.kind === 'cash' && tenderedCents >= amountCents ? tenderedCents - amountCents : 0;
const chooseMode = (next: 'total' | 'partial') => {
setMode(next);
setError('');
if (next === 'total') {
setAmount(centsToInput(remainingCents));
setTendered(centsToInput(remainingCents));
} else {
setAmount('');
setTendered('');
}
};
const add = () => {
if (amountCents <= 0 || amountCents > remainingCents) {
setError('El importe debe ser positivo y no superar lo pendiente');
return;
}
if (method.kind === 'cash' && tenderedCents < amountCents) {
setError('El efectivo entregado debe cubrir el importe aplicado');
return;
}
onAdd({
id: crypto.randomUUID(),
methodCode: method.code,
methodLabel: method.label,
kind: method.kind,
amountCents,
...(method.kind === 'cash' ? { tenderedCents } : {}),
changeCents,
});
};
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
role="dialog"
aria-modal="true"
aria-labelledby="payment-title"
>
<div className="w-full max-w-md space-y-5 rounded-2xl bg-white p-6 shadow-2xl">
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-sm font-semibold text-[#2D6A4F]">
Pendiente {formatPrice(remainingCents)}
</p>
<h2 id="payment-title" className="text-2xl font-bold text-gray-900">
{method.label}
</h2>
</div>
<button
type="button"
onClick={onClose}
className="min-h-12 min-w-12 rounded-xl bg-gray-100 text-xl"
aria-label="Cerrar pago"
>
</button>
</div>
<div className="grid grid-cols-2 gap-3">
<button
type="button"
onClick={() => chooseMode('total')}
className={`min-h-14 rounded-xl border-2 font-bold ${mode === 'total' ? 'border-[#2D6A4F] bg-green-50 text-[#2D6A4F]' : 'border-gray-200'}`}
>
Paga el total
</button>
<button
type="button"
onClick={() => chooseMode('partial')}
className={`min-h-14 rounded-xl border-2 font-bold ${mode === 'partial' ? 'border-[#2D6A4F] bg-green-50 text-[#2D6A4F]' : 'border-gray-200'}`}
>
Paga una parte
</button>
</div>
<label className="block text-sm font-semibold text-gray-700">
Importe que se aplica ()
<input
value={amount}
onChange={(event) => {
setAmount(event.target.value);
setError('');
}}
inputMode="decimal"
readOnly={mode === 'total'}
autoFocus={mode === 'partial'}
className="mt-1 w-full rounded-xl border-2 border-gray-200 px-4 py-3 text-2xl font-bold outline-none focus:border-[#2D6A4F] read-only:bg-gray-50"
aria-describedby="payment-error"
/>
</label>
{method.kind === 'cash' && (
<label className="block text-sm font-semibold text-gray-700">
Efectivo entregado ()
<input
value={tendered}
onChange={(event) => {
setTendered(event.target.value);
setError('');
}}
inputMode="decimal"
className="mt-1 w-full rounded-xl border-2 border-gray-200 px-4 py-3 text-2xl font-bold outline-none focus:border-[#2D6A4F]"
/>
</label>
)}
{method.kind === 'cash' && tenderedCents >= amountCents && amountCents > 0 && (
<div className="flex items-center justify-between rounded-xl bg-amber-50 p-4 text-amber-900">
<span className="font-semibold">A devolver</span>
<strong className="text-2xl">{formatPrice(changeCents)}</strong>
</div>
)}
{error && (
<p id="payment-error" className="text-sm font-medium text-red-600" aria-live="polite">
{error}
</p>
)}
<button
type="button"
onClick={add}
className="min-h-14 w-full rounded-xl bg-[#2D6A4F] px-5 font-bold text-white hover:bg-[#1B4332]"
>
Añadir pago
</button>
</div>
</div>
);
}
function parseEuros(value: string): number {
const normalized = value.trim().replace(',', '.');
if (!/^\d+(?:\.\d{0,2})?$/.test(normalized)) return 0;
return Math.round(Number(normalized) * 100);
}
function centsToInput(cents: number): string {
return (cents / 100).toFixed(2);
}

View File

@@ -0,0 +1,198 @@
'use client';
import { useState } from 'react';
import { posApi } from '@/lib/api-client';
import { formatPrice } from '@/lib/money';
import type { PosReceipt } from '@/types/checkout';
interface ReceiptModalProps {
receipt: PosReceipt;
initialEmail?: string;
onDelivered: () => void;
}
export default function ReceiptModal({
receipt,
initialEmail = '',
onDelivered,
}: ReceiptModalProps) {
const [email, setEmail] = useState(initialEmail);
const [sending, setSending] = useState(false);
const [error, setError] = useState('');
const printReceipt = () => {
window.print();
onDelivered();
};
const emailReceipt = async (event: React.FormEvent) => {
event.preventDefault();
setSending(true);
setError('');
try {
await posApi.emailReceipt(receipt.orderId, email.trim());
onDelivered();
} catch (err) {
setError(err instanceof Error ? err.message : 'No se pudo enviar el ticket');
} finally {
setSending(false);
}
};
return (
<div
className="fixed inset-0 z-[60] overflow-y-auto bg-black/50 p-4 print:static print:bg-white print:p-0"
role="dialog"
aria-modal="true"
aria-labelledby="receipt-title"
>
<div className="mx-auto w-full max-w-xl rounded-2xl bg-white p-6 shadow-2xl print:max-w-none print:rounded-none print:p-0 print:shadow-none">
<article className="space-y-4 text-sm text-gray-900">
<header className="border-b border-dashed border-gray-400 pb-4 text-center">
{receipt.header && <p className="font-semibold">{receipt.header}</p>}
<h2 id="receipt-title" className="text-2xl font-bold">
{receipt.company.name}
</h2>
{receipt.company.address && <p>{receipt.company.address}</p>}
{receipt.company.taxId && <p>NIF/CIF: {receipt.company.taxId}</p>}
{(receipt.company.phone || receipt.company.email) && (
<p>{[receipt.company.phone, receipt.company.email].filter(Boolean).join(' · ')}</p>
)}
</header>
<div className="grid grid-cols-2 gap-2 text-xs">
<p>
<strong>Ticket:</strong> {receipt.receiptNumber}
</p>
<p className="text-right">
<strong>Fecha:</strong> {new Date(receipt.issuedAt).toLocaleString('es-ES')}
</p>
<p>
<strong>Terminal:</strong> {receipt.terminal.name}
</p>
<p className="text-right">
<strong>Cajero:</strong> {receipt.cashier}
</p>
</div>
<table className="w-full border-collapse text-left">
<thead className="border-y border-dashed border-gray-400 text-xs uppercase">
<tr>
<th className="py-2">Artículo</th>
<th className="py-2 text-right">Cant.</th>
<th className="py-2 text-right">Subtotal</th>
</tr>
</thead>
<tbody>
{receipt.items.map((item, index) => (
<tr key={`${item.sku}-${index}`} className="border-b border-gray-100 align-top">
<td className="py-2">
<span className="font-medium">{item.name}</span>
<span className="block text-xs text-gray-500">
{formatPrice(item.unitPriceCents)}/ud{item.freeItem ? ' · libre' : ''}
</span>
{item.discountCents > 0 && (
<span className="block text-xs text-red-600">
Dto. {formatPrice(item.discountCents)}
</span>
)}
</td>
<td className="py-2 text-right">{item.quantity}</td>
<td className="py-2 text-right font-medium">{formatPrice(item.totalCents)}</td>
</tr>
))}
</tbody>
</table>
<div className="ml-auto w-full max-w-xs space-y-1">
<p className="flex justify-between">
<span>Subtotal</span>
<span>{formatPrice(receipt.subtotalCents)}</span>
</p>
{receipt.discountCents > 0 && (
<p className="flex justify-between text-red-600">
<span>Descuentos</span>
<span>{formatPrice(receipt.discountCents)}</span>
</p>
)}
<p className="flex justify-between">
<span>IVA</span>
<span>{formatPrice(receipt.taxCents)}</span>
</p>
<p className="flex justify-between border-t border-gray-900 pt-2 text-xl font-bold">
<span>Total</span>
<span>{formatPrice(receipt.totalCents)}</span>
</p>
</div>
<section className="border-y border-dashed border-gray-400 py-3">
<h3 className="mb-2 font-bold">Formas de pago</h3>
{receipt.payments.map((payment, index) => (
<div key={`${payment.methodCode}-${index}`} className="flex justify-between">
<span>{payment.methodLabel}</span>
<span>{formatPrice(payment.amountCents)}</span>
{payment.tenderedCents !== null && (
<span className="text-xs text-gray-500">
Entregado {formatPrice(payment.tenderedCents)}
</span>
)}
{payment.changeCents > 0 && (
<strong>Cambio {formatPrice(payment.changeCents)}</strong>
)}
</div>
))}
{receipt.changeCents > 0 && (
<p className="mt-2 flex justify-between rounded bg-amber-50 p-2 text-lg font-bold">
<span>Total a devolver</span>
<span>{formatPrice(receipt.changeCents)}</span>
</p>
)}
</section>
<footer className="space-y-2 text-center text-xs">
<p>{receipt.returnPolicy}</p>
{receipt.footer && <p className="font-semibold">{receipt.footer}</p>}
</footer>
</article>
<div className="mt-6 space-y-3 border-t pt-5 print:hidden">
<p className="text-center text-sm text-gray-600">
Imprime o envía el ticket para preparar la siguiente venta.
</p>
<button
type="button"
onClick={printReceipt}
className="min-h-14 w-full rounded-xl bg-[#2D6A4F] font-bold text-white"
>
🖨 Imprimir ticket
</button>
<form onSubmit={emailReceipt} className="flex gap-2">
<label className="sr-only" htmlFor="receipt-email">
Email del ticket
</label>
<input
id="receipt-email"
type="email"
required
value={email}
onChange={(event) => setEmail(event.target.value)}
placeholder="cliente@email.es"
className="min-h-14 min-w-0 flex-1 rounded-xl border-2 border-gray-200 px-4 outline-none focus:border-[#2D6A4F]"
/>
<button
disabled={sending}
className="min-h-14 rounded-xl bg-blue-600 px-5 font-bold text-white disabled:opacity-50"
>
{sending ? 'Enviando…' : '✉ Enviar'}
</button>
</form>
{error && (
<p className="text-sm font-medium text-red-600" aria-live="polite">
{error}
</p>
)}
</div>
</div>
</div>
);
}

View File

@@ -12,14 +12,14 @@ async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
},
});
if (!res.ok) {
const err = await res.json().catch(() => ({ message: res.statusText })) as {
const err = (await res.json().catch(() => ({ message: res.statusText }))) as {
message?: string;
error?: { message?: string; code?: string };
};
throw Object.assign(
new Error(err.error?.message ?? err.message ?? 'Request failed'),
{ status: res.status, code: err.error?.code },
);
throw Object.assign(new Error(err.error?.message ?? err.message ?? 'Request failed'), {
status: res.status,
code: err.error?.code,
});
}
return res.json() as Promise<T>;
}
@@ -41,11 +41,13 @@ export const posApi = {
method: 'POST',
body: JSON.stringify({ openingCashCents }),
}),
/** Load touch category navigation and four terminal quick products. */
/** Load touch category navigation and eight terminal quick products. */
touchCatalog: <T>() => apiFetch<T>('/pos/catalog/touch'),
/** List products by query. */
searchProducts: (q: string, storeId?: string, limit = 20) =>
apiFetch(`/pos/products/search?q=${encodeURIComponent(q)}&storeId=${storeId ?? ''}&limit=${limit}`),
apiFetch(
`/pos/products/search?q=${encodeURIComponent(q)}&storeId=${storeId ?? ''}&limit=${limit}`,
),
/** Get product by EAN. */
productByEan: (ean: string) => apiFetch(`/pos/products/by-ean/${encodeURIComponent(ean)}`),
/** Get product by SKU. */
@@ -55,10 +57,22 @@ export const posApi = {
/** Create an identity customer from the register. */
createCustomer: <T>(data: { email: string; displayName?: string; phone?: string }) =>
apiFetch<T>('/pos/customers', { method: 'POST', body: JSON.stringify(data) }),
/** Atomically confirm a fully allocated sale. */
createSale: <T>(data: unknown) =>
apiFetch<T>('/pos/sales', { method: 'POST', body: JSON.stringify(data) }),
/** Email the immutable generated receipt. */
emailReceipt: <T>(orderId: string, email: string) =>
apiFetch<T>(`/pos/sales/${encodeURIComponent(orderId)}/receipt/email`, {
method: 'POST',
body: JSON.stringify({ email }),
}),
};
export const authApi = {
login: (email: string, password: string) =>
apiFetch('/backoffice/auth/login', { method: 'POST', body: JSON.stringify({ email, password }) }),
apiFetch('/backoffice/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password }),
}),
logout: () => apiFetch('/backoffice/auth/logout', { method: 'POST' }),
};

View File

@@ -0,0 +1,72 @@
export interface PaymentMethod {
id: string;
code: string;
label: string;
kind: 'cash' | 'card' | 'other';
}
export interface PaymentAllocation {
id: string;
methodCode: string;
methodLabel: string;
kind: PaymentMethod['kind'];
amountCents: number;
tenderedCents?: number;
changeCents: number;
}
export interface ReceiptItem {
name: string;
sku: string;
quantity: number;
unitPriceCents: number;
subtotalCents: number;
discountCents: number;
taxCents: number;
totalCents: number;
freeItem: boolean;
}
export interface ReceiptPayment {
methodCode: string;
methodLabel: string;
kind: PaymentMethod['kind'];
amountCents: number;
tenderedCents: number | null;
changeCents: number;
}
export interface PosReceipt {
receiptNumber: string;
orderId: string;
issuedAt: string;
company: {
name: string;
address: string | null;
taxId: string | null;
email: string | null;
phone: string | null;
};
terminal: { id: string; name: string };
cashier: string;
sessionId: string;
customerEmail: string | null;
items: ReceiptItem[];
subtotalCents: number;
discountCents: number;
taxCents: number;
totalCents: number;
payments: ReceiptPayment[];
changeCents: number;
header: string | null;
returnPolicy: string;
footer: string | null;
}
export interface PosSaleResponse {
orderId: string;
receiptNumber: string;
totalCents: number;
changeCents: number;
receipt: PosReceipt;
}