feat(F-106): completed feature
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import type { Order, OrderState } from '@/types';
|
||||
import { ordersApi } from '@/lib/api-client';
|
||||
import type { Order, OrderState, Product } from '@/types';
|
||||
import { ordersApi, productsApi } from '@/lib/api-client';
|
||||
|
||||
const STATE_LABELS: Record<OrderState, string> = {
|
||||
PENDING: 'Pendiente',
|
||||
@@ -53,19 +53,39 @@ const ACTION_LABELS: Record<OrderState, string> = {
|
||||
PARTIALLY_REFUNDED: 'Reembolso parcial',
|
||||
};
|
||||
|
||||
interface DraftItem {
|
||||
variantId: string;
|
||||
productId: string;
|
||||
sku: string;
|
||||
name: string;
|
||||
quantity: number;
|
||||
}
|
||||
|
||||
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 [trackingInput, setTrackingInput] = useState('');
|
||||
const [notification, setNotification] = useState<{ ok: boolean; message: string } | null>(null);
|
||||
|
||||
// Edición de artículos
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draftItems, setDraftItems] = useState<DraftItem[]>([]);
|
||||
const [savingItems, setSavingItems] = useState(false);
|
||||
const [itemsError, setItemsError] = useState('');
|
||||
const [productQuery, setProductQuery] = useState('');
|
||||
const [searchResults, setSearchResults] = useState<Product[]>([]);
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [addingProductId, setAddingProductId] = useState<string | null>(null);
|
||||
const [addingVariants, setAddingVariants] = useState<{ id: string; sku: string }[]>([]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
@@ -83,12 +103,22 @@ export default function OrderDetailPage() {
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleTransition = async (nextState: OrderState) => {
|
||||
if (nextState === 'SHIPPED' && !trackingInput.trim()) return;
|
||||
setTransitioning(true);
|
||||
try {
|
||||
const updated = await ordersApi.transition(id, nextState);
|
||||
const updated = await ordersApi.transition(id, nextState, trackingInput);
|
||||
setOrder(updated);
|
||||
setShowConfirm(null);
|
||||
setConfirmReason('');
|
||||
setTrackingInput('');
|
||||
if (updated.notified) {
|
||||
setNotification({ ok: true, message: 'Cliente notificado por email.' });
|
||||
} else {
|
||||
setNotification({
|
||||
ok: false,
|
||||
message: updated.notificationError || 'No se pudo notificar al cliente por email.',
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Error al cambiar estado');
|
||||
} finally {
|
||||
@@ -96,6 +126,108 @@ export default function OrderDetailPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const startEditing = () => {
|
||||
if (!order) return;
|
||||
setDraftItems(
|
||||
order.items.map((item) => ({
|
||||
variantId: item.variantId,
|
||||
productId: item.productId,
|
||||
sku: item.sku,
|
||||
name: item.name,
|
||||
quantity: item.quantity,
|
||||
})),
|
||||
);
|
||||
setItemsError('');
|
||||
setEditing(true);
|
||||
};
|
||||
|
||||
const updateDraftQuantity = (variantId: string, quantity: number) => {
|
||||
setDraftItems((prev) =>
|
||||
prev.map((item) =>
|
||||
item.variantId === variantId
|
||||
? { ...item, quantity: Math.max(1, Math.min(999, quantity || 1)) }
|
||||
: item,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const removeDraftItem = (variantId: string) => {
|
||||
setDraftItems((prev) => prev.filter((item) => item.variantId !== variantId));
|
||||
};
|
||||
|
||||
const searchProducts = useCallback(async (query: string) => {
|
||||
setProductQuery(query);
|
||||
if (query.trim().length < 2) {
|
||||
setSearchResults([]);
|
||||
return;
|
||||
}
|
||||
setSearching(true);
|
||||
try {
|
||||
const result = await productsApi.list({ q: query.trim(), limit: 8 });
|
||||
setSearchResults(result.items ?? []);
|
||||
} catch {
|
||||
setSearchResults([]);
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const pickProductForAdd = async (product: Product) => {
|
||||
setAddingProductId(product.id);
|
||||
setAddingVariants([]);
|
||||
try {
|
||||
const result = await productsApi.getVariants(product.id);
|
||||
const variants = (result.items ?? []).map((variant) => ({ id: variant.id, sku: variant.sku }));
|
||||
if (variants.length === 1) {
|
||||
addDraftItem(variants[0].id, product.id, variants[0].sku, product.name);
|
||||
setAddingProductId(null);
|
||||
} else {
|
||||
setAddingVariants(variants);
|
||||
}
|
||||
} catch (err) {
|
||||
setItemsError(err instanceof Error ? err.message : 'Error al cargar variantes');
|
||||
setAddingProductId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const addDraftItem = (variantId: string, productId: string, sku: string, name: string) => {
|
||||
setDraftItems((prev) => {
|
||||
const existing = prev.find((item) => item.variantId === variantId);
|
||||
if (existing) {
|
||||
return prev.map((item) =>
|
||||
item.variantId === variantId ? { ...item, quantity: Math.min(999, item.quantity + 1) } : item,
|
||||
);
|
||||
}
|
||||
return [...prev, { variantId, productId, sku, name, quantity: 1 }];
|
||||
});
|
||||
setSearchResults([]);
|
||||
setProductQuery('');
|
||||
setAddingProductId(null);
|
||||
setAddingVariants([]);
|
||||
setItemsError('');
|
||||
};
|
||||
|
||||
const saveItems = async () => {
|
||||
if (draftItems.length === 0) {
|
||||
setItemsError('El pedido debe tener al menos un artículo');
|
||||
return;
|
||||
}
|
||||
setSavingItems(true);
|
||||
setItemsError('');
|
||||
try {
|
||||
const updated = await ordersApi.editItems(
|
||||
id,
|
||||
draftItems.map((item) => ({ variantId: item.variantId, quantity: item.quantity })),
|
||||
);
|
||||
setOrder(updated);
|
||||
setEditing(false);
|
||||
} catch (err) {
|
||||
setItemsError(err instanceof Error ? err.message : 'Error al guardar artículos');
|
||||
} finally {
|
||||
setSavingItems(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-64">
|
||||
@@ -117,6 +249,7 @@ export default function OrderDetailPage() {
|
||||
|
||||
const currentState = order.state as OrderState;
|
||||
const allowed = ALLOWED_TRANSITIONS[currentState] ?? [];
|
||||
const itemsEditable = currentState !== 'CANCELLED' && currentState !== 'REFUNDED';
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -142,6 +275,20 @@ export default function OrderDetailPage() {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Notification result */}
|
||||
{notification && (
|
||||
<div
|
||||
className={`flex items-center justify-between px-4 py-3 rounded-xl text-sm border ${
|
||||
notification.ok
|
||||
? 'bg-green-50 border-green-200 text-green-800'
|
||||
: 'bg-amber-50 border-amber-200 text-amber-800'
|
||||
}`}
|
||||
>
|
||||
<span>{notification.message}</span>
|
||||
<button onClick={() => setNotification(null)} className="ml-4 font-bold opacity-60 hover:opacity-100">✕</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Main content */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
@@ -153,7 +300,7 @@ export default function OrderDetailPage() {
|
||||
{allowed.map((next) => (
|
||||
<button
|
||||
key={next}
|
||||
onClick={() => setShowConfirm(next)}
|
||||
onClick={() => { setShowConfirm(next); setNotification(null); }}
|
||||
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"
|
||||
>
|
||||
@@ -166,23 +313,135 @@ export default function OrderDetailPage() {
|
||||
|
||||
{/* 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)})`}
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="font-bold text-gray-900">Productos</h2>
|
||||
{itemsEditable && !editing && (
|
||||
<button
|
||||
onClick={startEditing}
|
||||
className="px-3 py-1.5 text-sm font-semibold text-[#2D6A4F] border border-[#2D6A4F] rounded-lg hover:bg-[#2D6A4F]/5 transition-colors"
|
||||
>
|
||||
✏️ Editar artículos
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!editing ? (
|
||||
<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>
|
||||
<p className="text-sm font-bold text-gray-900 ml-4">
|
||||
{formatPrice((item.unitPriceCents - item.discountCents) * item.quantity)}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-3">
|
||||
{draftItems.map((item) => (
|
||||
<div key={item.variantId} className="flex items-center gap-3 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 truncate">{item.name}</p>
|
||||
<p className="text-xs text-gray-400 font-mono">{item.sku}</p>
|
||||
</div>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={999}
|
||||
value={item.quantity}
|
||||
onChange={(e) => updateDraftQuantity(item.variantId, Number(e.target.value))}
|
||||
className="w-20 px-2 py-1.5 border border-gray-300 rounded-lg text-sm text-right focus:ring-2 focus:ring-[#2D6A4F] outline-none"
|
||||
/>
|
||||
<button
|
||||
onClick={() => removeDraftItem(item.variantId)}
|
||||
disabled={draftItems.length === 1}
|
||||
title="Quitar artículo"
|
||||
className="p-1.5 text-red-500 hover:bg-red-50 rounded-lg disabled:opacity-30 disabled:cursor-not-allowed"
|
||||
>
|
||||
🗑️
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{draftItems.length === 0 && (
|
||||
<p className="text-sm text-gray-400 py-2">Sin artículos. Añade al menos uno.</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Add product */}
|
||||
<div className="border-t border-gray-100 pt-4">
|
||||
<label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">Añadir producto</label>
|
||||
<input
|
||||
type="search"
|
||||
value={productQuery}
|
||||
onChange={(e) => { searchProducts(e.target.value); }}
|
||||
placeholder="Buscar por nombre o SKU (mín. 2 caracteres)…"
|
||||
className="mt-1 w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
|
||||
/>
|
||||
{searching && <p className="text-xs text-gray-400 mt-2">Buscando…</p>}
|
||||
{!searching && searchResults.length > 0 && (
|
||||
<ul className="mt-2 border border-gray-200 rounded-xl divide-y divide-gray-100 max-h-56 overflow-auto">
|
||||
{searchResults.map((product) => (
|
||||
<li key={product.id}>
|
||||
{addingProductId === product.id && addingVariants.length > 0 ? (
|
||||
<div className="px-3 py-2">
|
||||
<p className="text-sm font-medium text-gray-900">{product.name}</p>
|
||||
<div className="flex flex-wrap gap-2 mt-1">
|
||||
{addingVariants.map((variant) => (
|
||||
<button
|
||||
key={variant.id}
|
||||
onClick={() => addDraftItem(variant.id, product.id, variant.sku, product.name)}
|
||||
className="px-2 py-1 text-xs font-mono bg-gray-100 hover:bg-[#2D6A4F] hover:text-white rounded-lg transition-colors"
|
||||
>
|
||||
{variant.sku}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => { pickProductForAdd(product); }}
|
||||
disabled={addingProductId !== null}
|
||||
className="w-full text-left px-3 py-2 text-sm text-gray-800 hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
{product.name}
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{itemsError && <p className="text-sm text-red-600">{itemsError}</p>}
|
||||
|
||||
<div className="flex gap-3 justify-end border-t border-gray-100 pt-4">
|
||||
<button
|
||||
onClick={() => { setEditing(false); setItemsError(''); }}
|
||||
disabled={savingItems}
|
||||
className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
onClick={saveItems}
|
||||
disabled={savingItems || draftItems.length === 0}
|
||||
className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] disabled:opacity-50 text-white text-sm font-semibold rounded-xl transition-colors"
|
||||
>
|
||||
{savingItems ? 'Guardando…' : 'Guardar artículos'}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-400">
|
||||
Los precios e IVA se recalculan con las tarifas vigentes al guardar.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -211,6 +470,12 @@ export default function OrderDetailPage() {
|
||||
<span className="text-xl font-bold text-[#2D6A4F]">{formatPrice(order.totalCents)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{order.trackingNumber && (
|
||||
<div className="mt-4 border-t border-gray-100 pt-3">
|
||||
<p className="text-xs font-semibold text-gray-500 uppercase tracking-wide">Seguimiento</p>
|
||||
<p className="text-sm font-mono text-gray-900 mt-1">{order.trackingNumber}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Timeline */}
|
||||
@@ -239,8 +504,23 @@ export default function OrderDetailPage() {
|
||||
Confirmar cambio de estado
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600 mb-4">
|
||||
¿{ACTION_LABELS[showConfirm] ?? showConfirm}?
|
||||
¿{ACTION_LABELS[showConfirm] ?? showConfirm}? Se notificará al cliente por email.
|
||||
</p>
|
||||
{showConfirm === 'SHIPPED' && (
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Número de seguimiento <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={trackingInput}
|
||||
onChange={(e) => setTrackingInput(e.target.value)}
|
||||
placeholder="p. ej. PQ123456789ES"
|
||||
maxLength={120}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{(showConfirm === 'CANCELLED' || showConfirm === 'REFUNDED') && (
|
||||
<textarea
|
||||
value={confirmReason}
|
||||
@@ -252,14 +532,14 @@ export default function OrderDetailPage() {
|
||||
)}
|
||||
<div className="flex gap-3 justify-end">
|
||||
<button
|
||||
onClick={() => { setShowConfirm(null); setConfirmReason(''); }}
|
||||
onClick={() => { setShowConfirm(null); setConfirmReason(''); setTrackingInput(''); }}
|
||||
className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleTransition(showConfirm)}
|
||||
disabled={transitioning}
|
||||
disabled={transitioning || (showConfirm === 'SHIPPED' && !trackingInput.trim())}
|
||||
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'}
|
||||
|
||||
@@ -106,8 +106,13 @@ export const ordersApi = {
|
||||
).then((data) => (Array.isArray(data) ? { items: data, total: data.length } : data));
|
||||
},
|
||||
get: (id: string) => api.get<import('@/types').Order>(`/api/orders/${id}`),
|
||||
transition: (id: string, state: string) =>
|
||||
api.post<import('@/types').Order>(`/api/orders/${id}/transitions`, { state }),
|
||||
transition: (id: string, state: string, trackingNumber?: string) =>
|
||||
api.post<import('@/types').Order & { notified?: boolean; notificationError?: string }>(
|
||||
`/api/orders/${id}/transitions`,
|
||||
trackingNumber?.trim() ? { state, trackingNumber: trackingNumber.trim() } : { state },
|
||||
),
|
||||
editItems: (id: string, items: { variantId: string; quantity: number }[]) =>
|
||||
api.put<import('@/types').Order>(`/api/orders/${id}/items`, { items }),
|
||||
};
|
||||
|
||||
// ── Customers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -108,6 +108,7 @@ export interface Order {
|
||||
discountCents: number;
|
||||
taxCents: number;
|
||||
totalCents: number;
|
||||
trackingNumber?: string | null;
|
||||
idempotencyKey: string | null;
|
||||
items: OrderItem[];
|
||||
createdAt: string;
|
||||
|
||||
Reference in New Issue
Block a user