feat(ADM-018): completed feature

This commit is contained in:
chattie
2026-08-17 22:23:10 +02:00
parent cf1c69fc8b
commit d595b4871f
871 changed files with 47411 additions and 281 deletions

View File

@@ -0,0 +1,273 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import type { Order, OrderState } from '@/types';
import { ordersApi } from '@/lib/api-client';
const STATE_LABELS: Record<OrderState, string> = {
PENDING: 'Pendiente',
AWAITING_PAYMENT: 'Esperando pago',
PAID: 'Pagado',
PROCESSING: 'Procesando',
SHIPPED: 'Enviado',
DELIVERED: 'Entregado',
CANCELLED: 'Cancelado',
REFUNDED: 'Reembolsado',
PARTIALLY_REFUNDED: 'Reembolso parcial',
};
const STATE_COLORS: Record<OrderState, string> = {
PENDING: 'bg-amber-100 text-amber-800',
AWAITING_PAYMENT: 'bg-orange-100 text-orange-800',
PAID: 'bg-blue-100 text-blue-800',
PROCESSING: 'bg-indigo-100 text-indigo-800',
SHIPPED: 'bg-purple-100 text-purple-800',
DELIVERED: 'bg-green-100 text-green-800',
CANCELLED: 'bg-red-100 text-red-800',
REFUNDED: 'bg-purple-100 text-purple-800',
PARTIALLY_REFUNDED: 'bg-pink-100 text-pink-800',
};
const ALLOWED_TRANSITIONS: Record<OrderState, OrderState[]> = {
PENDING: ['AWAITING_PAYMENT', 'CANCELLED'],
AWAITING_PAYMENT: ['PAID', 'CANCELLED'],
PAID: ['PROCESSING', 'CANCELLED', 'REFUNDED'],
PROCESSING: ['SHIPPED', 'CANCELLED', 'REFUNDED'],
SHIPPED: ['DELIVERED', 'PARTIALLY_REFUNDED'],
DELIVERED: ['PARTIALLY_REFUNDED'],
CANCELLED: [],
REFUNDED: [],
PARTIALLY_REFUNDED: [],
};
const ACTION_LABELS: Record<OrderState, string> = {
AWAITING_PAYMENT: 'Marcar como Pagado',
PAID: 'Procesar pedido',
PROCESSING: 'Marcar como Enviado',
SHIPPED: 'Marcar como Entregado',
DELIVERED: 'Reembolso parcial',
CANCELLED: 'Cancelar pedido',
PENDING: 'Marcar como Pagado',
REFUNDED: 'Reembolsar',
PARTIALLY_REFUNDED: 'Reembolso parcial',
};
function formatPrice(cents: number) {
return `${(cents / 100).toFixed(2)}`;
}
export default function OrderDetailPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const [order, setOrder] = useState<Order | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [transitioning, setTransitioning] = useState(false);
const [showConfirm, setShowConfirm] = useState<OrderState | null>(null);
const [confirmReason, setConfirmReason] = useState('');
const load = useCallback(async () => {
setLoading(true);
setError('');
try {
const data = await ordersApi.get(id);
setOrder(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Error al cargar');
} finally {
setLoading(false);
}
}, [id]);
useEffect(() => { load(); }, [load]);
const handleTransition = async (nextState: OrderState) => {
setTransitioning(true);
try {
const updated = await ordersApi.transition(id, nextState);
setOrder(updated);
setShowConfirm(null);
setConfirmReason('');
} catch (err) {
alert(err instanceof Error ? err.message : 'Error al cambiar estado');
} finally {
setTransitioning(false);
}
};
if (loading) {
return (
<div className="p-8 flex items-center justify-center min-h-64">
<div className="text-gray-400">Cargando...</div>
</div>
);
}
if (error || !order) {
return (
<div className="p-8">
<p className="text-red-600">{error || 'Pedido no encontrado'}</p>
<button onClick={load} className="text-sm text-[#2D6A4F] hover:underline mt-2">
Reintentar
</button>
</div>
);
}
const currentState = order.state as OrderState;
const allowed = ALLOWED_TRANSITIONS[currentState] ?? [];
return (
<div className="p-8">
{/* Back */}
<Link href="/orders" className="inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 mb-6">
Volver a pedidos
</Link>
{/* Header */}
<div className="flex items-start justify-between mb-8">
<div>
<h1 className="text-2xl font-bold text-gray-900 font-mono">#{order.id.slice(0, 8)}</h1>
<p className="text-sm text-gray-500 mt-1">
{new Date(order.createdAt).toLocaleString('es-ES', {
dateStyle: 'long',
timeStyle: 'short',
})}
</p>
</div>
<span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium ${STATE_COLORS[currentState]}`}>
<span className="w-2 h-2 rounded-full bg-current" />
{STATE_LABELS[currentState]}
</span>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Main content */}
<div className="lg:col-span-2 space-y-6">
{/* Actions */}
{allowed.length > 0 && (
<div className="bg-white border border-gray-200 rounded-xl p-6">
<h2 className="font-bold text-gray-900 mb-4">Acciones</h2>
<div className="flex flex-wrap gap-2">
{allowed.map((next) => (
<button
key={next}
onClick={() => setShowConfirm(next)}
disabled={transitioning}
className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] disabled:opacity-50 text-white text-sm font-semibold rounded-xl transition-colors"
>
{ACTION_LABELS[next] ?? next}
</button>
))}
</div>
</div>
)}
{/* Order items */}
<div className="bg-white border border-gray-200 rounded-xl p-6">
<h2 className="font-bold text-gray-900 mb-4">Productos</h2>
<div className="space-y-3">
{order.items.map((item) => (
<div key={item.id} className="flex justify-between items-start py-2 border-b border-gray-50 last:border-0">
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-gray-900">{item.name}</p>
<p className="text-xs text-gray-400">
{item.quantity} × {formatPrice(item.unitPriceCents)}
{item.discountCents > 0 && ` (-${formatPrice(item.discountCents)})`}
</p>
</div>
<p className="text-sm font-bold text-gray-900 ml-4">
{formatPrice((item.unitPriceCents - item.discountCents) * item.quantity)}
</p>
</div>
))}
</div>
</div>
</div>
{/* Sidebar */}
<div className="space-y-6">
{/* Totals */}
<div className="bg-white border border-gray-200 rounded-xl p-6">
<h2 className="font-bold text-gray-900 mb-4">Resumen</h2>
<div className="space-y-2 text-sm">
<div className="flex justify-between">
<span className="text-gray-600">Subtotal</span>
<span className="font-medium">{formatPrice(order.subtotalCents)}</span>
</div>
{order.discountCents > 0 && (
<div className="flex justify-between">
<span className="text-gray-600">Descuento</span>
<span className="font-medium text-green-600">-{formatPrice(order.discountCents)}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-gray-600">IVA</span>
<span className="font-medium">{formatPrice(order.taxCents)}</span>
</div>
<div className="border-t border-gray-200 pt-2 mt-2 flex justify-between items-center">
<span className="font-bold text-gray-900">Total</span>
<span className="text-xl font-bold text-[#2D6A4F]">{formatPrice(order.totalCents)}</span>
</div>
</div>
</div>
{/* Timeline */}
<div className="bg-white border border-gray-200 rounded-xl p-6">
<h2 className="font-bold text-gray-900 mb-4">Historial</h2>
<div className="space-y-3">
<div className="flex gap-3">
<div className="w-2 h-2 rounded-full bg-[#2D6A4F] mt-1.5 flex-shrink-0" />
<div>
<p className="text-sm font-medium text-gray-900">{STATE_LABELS[currentState]}</p>
<p className="text-xs text-gray-400">
{new Date(order.createdAt).toLocaleString('es-ES')}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Confirmation Modal */}
{showConfirm && (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-2xl p-6 max-w-md w-full shadow-xl">
<h3 className="text-lg font-bold text-gray-900 mb-2">
Confirmar cambio de estado
</h3>
<p className="text-sm text-gray-600 mb-4">
¿{ACTION_LABELS[showConfirm] ?? showConfirm}?
</p>
{(showConfirm === 'CANCELLED' || showConfirm === 'REFUNDED') && (
<textarea
value={confirmReason}
onChange={(e) => setConfirmReason(e.target.value)}
placeholder="Motivo (opcional)"
rows={2}
className="w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none mb-4 resize-none"
/>
)}
<div className="flex gap-3 justify-end">
<button
onClick={() => { setShowConfirm(null); setConfirmReason(''); }}
className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors"
>
Cancelar
</button>
<button
onClick={() => handleTransition(showConfirm)}
disabled={transitioning}
className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] disabled:opacity-50 text-white text-sm font-semibold rounded-xl transition-colors"
>
{transitioning ? 'Guardando...' : 'Confirmar'}
</button>
</div>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,203 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import type { Order, OrderState } from '@/types';
import { ordersApi } from '@/lib/api-client';
const ORDER_STATES: OrderState[] = [
'PENDING',
'AWAITING_PAYMENT',
'PAID',
'PROCESSING',
'SHIPPED',
'DELIVERED',
'CANCELLED',
'REFUNDED',
'PARTIALLY_REFUNDED',
];
const STATE_LABELS: Record<OrderState, string> = {
PENDING: 'Pendiente',
AWAITING_PAYMENT: 'Esperando pago',
PAID: 'Pagado',
PROCESSING: 'Procesando',
SHIPPED: 'Enviado',
DELIVERED: 'Entregado',
CANCELLED: 'Cancelado',
REFUNDED: 'Reembolsado',
PARTIALLY_REFUNDED: 'Reembolso parcial',
};
const STATE_COLORS: Record<OrderState, string> = {
PENDING: 'bg-amber-100 text-amber-800',
AWAITING_PAYMENT: 'bg-orange-100 text-orange-800',
PAID: 'bg-blue-100 text-blue-800',
PROCESSING: 'bg-indigo-100 text-indigo-800',
SHIPPED: 'bg-purple-100 text-purple-800',
DELIVERED: 'bg-green-100 text-green-800',
CANCELLED: 'bg-red-100 text-red-800',
REFUNDED: 'bg-purple-100 text-purple-800',
PARTIALLY_REFUNDED: 'bg-pink-100 text-pink-800',
};
function formatPrice(cents: number) {
return `${(cents / 100).toFixed(2)}`;
}
function timeAgo(dateStr: string) {
const date = new Date(dateStr);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays === 0) return 'Hoy';
if (diffDays === 1) return 'Ayer';
if (diffDays < 30) return `Hace ${diffDays} días`;
return date.toLocaleDateString('es-ES', { day: 'numeric', month: 'short' });
}
export default function OrdersPage() {
const [orders, setOrders] = useState<Order[] | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [filterState, setFilterState] = useState('');
const [search, setSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
useEffect(() => {
const t = setTimeout(() => setDebouncedSearch(search), 400);
return () => clearTimeout(t);
}, [search]);
const load = useCallback(async () => {
setLoading(true);
setError('');
try {
const data = await ordersApi.list({
status: filterState || undefined,
q: debouncedSearch || undefined,
limit: 20,
});
setOrders(data.items);
} catch (err) {
setError(err instanceof Error ? err.message : 'Error al cargar');
} finally {
setLoading(false);
}
}, [filterState, debouncedSearch]);
useEffect(() => { load(); }, [load]);
return (
<div className="p-8">
{/* Header */}
<div className="mb-6">
<h1 className="text-2xl font-bold text-gray-900">Pedidos</h1>
<p className="text-sm text-gray-500 mt-0.5">{orders?.length ?? 0} pedidos</p>
</div>
{/* Filters */}
<div className="flex gap-3 mb-6 flex-wrap">
<div className="relative flex-1 max-w-xs">
<input
type="search"
placeholder="Buscar por ID o email..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full pl-9 pr-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] focus:border-transparent outline-none"
/>
<svg
className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<circle cx="11" cy="11" r="8" />
<path d="M21 21l-4.35-4.35" />
</svg>
</div>
<select
value={filterState}
onChange={(e) => setFilterState(e.target.value)}
className="px-3 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] focus:border-transparent outline-none bg-white"
>
<option value="">Todos los estados</option>
{ORDER_STATES.map((s) => (
<option key={s} value={s}>{STATE_LABELS[s]}</option>
))}
</select>
</div>
{/* Table */}
<div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
{loading ? (
<div className="p-8 text-center text-gray-400">
<div className="inline-block animate-spin h-5 w-5 border-2 border-gray-300 border-t-[#2D6A4F] rounded-full" />
<p className="mt-2 text-sm">Cargando...</p>
</div>
) : error ? (
<div className="p-8 text-center">
<p className="text-red-600 text-sm mb-3">{error}</p>
<button onClick={load} className="text-sm text-[#2D6A4F] hover:underline">
Reintentar
</button>
</div>
) : !orders || orders.length === 0 ? (
<div className="p-12 text-center">
<p className="text-4xl mb-3">🧾</p>
<p className="text-gray-500 text-sm">No hay pedidos</p>
</div>
) : (
<table className="w-full">
<thead>
<tr className="bg-gray-50 border-b border-gray-200">
{['ID', 'Fecha', 'Total', 'Estado'].map((h) => (
<th
key={h}
className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3"
>
{h}
</th>
))}
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{orders.map((o) => (
<tr key={o.id} className="hover:bg-gray-50 transition-colors">
<td className="px-4 py-3.5">
<Link
href={`/orders/${o.id}`}
className="text-sm font-mono text-[#2D6A4F] hover:underline"
>
{o.id.slice(0, 8)}...
</Link>
</td>
<td className="px-4 py-3">
<p className="text-sm text-gray-600">{timeAgo(o.createdAt)}</p>
<p className="text-xs text-gray-400">
{new Date(o.createdAt).toLocaleTimeString('es-ES', {
hour: '2-digit',
minute: '2-digit',
})}
</p>
</td>
<td className="px-4 py-3">
<p className="text-sm font-bold text-gray-900">{formatPrice(o.totalCents)}</p>
</td>
<td className="px-4 py-3">
<span
className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium ${STATE_COLORS[o.state]}`}
>
<span className="w-1.5 h-1.5 rounded-full bg-current" />
{STATE_LABELS[o.state]}
</span>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
);
}