fixed some bugs
This commit is contained in:
@@ -20,7 +20,6 @@ interface CartItemCardProps {
|
||||
onUpdate?: () => void;
|
||||
}
|
||||
|
||||
// Session Storage Key
|
||||
const PENDING_CART_UPDATES_KEY = "pendingCartUpdates";
|
||||
|
||||
interface PendingUpdate {
|
||||
@@ -32,39 +31,33 @@ interface PendingUpdate {
|
||||
export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
const t = useTranslations();
|
||||
|
||||
// Local UI State (Instant feedback)
|
||||
const [localQuantity, setLocalQuantity] = useState(item.quantity);
|
||||
|
||||
// Sync State
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
const [syncError, setSyncError] = useState(false);
|
||||
|
||||
// Stock limit modal
|
||||
const [showStockModal, setShowStockModal] = useState(false);
|
||||
|
||||
// Refs
|
||||
const debounceTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
|
||||
const isRequestInFlightRef = useRef(false);
|
||||
const pendingQuantityRef = useRef<number | null>(null);
|
||||
const retryCountRef = useRef(0);
|
||||
const retryTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
|
||||
const isInitializedRef = useRef(false);
|
||||
|
||||
// Function refs to solve circular dependency
|
||||
const syncToServerRef = useRef<((quantity: number) => void) | null>(null);
|
||||
const retrySyncRef = useRef<((quantity: number) => void) | null>(null);
|
||||
|
||||
const { mutate: updateQuantity } = useUpdateCartItemQuantity();
|
||||
const { mutate: removeItem, isPending: isRemoving } = useRemoveFromCart();
|
||||
|
||||
// Get available stock
|
||||
const availableStock = item.product.stock || 0;
|
||||
|
||||
// Initialize from server state
|
||||
useEffect(() => {
|
||||
setLocalQuantity(item.quantity);
|
||||
if (!isInitializedRef.current) {
|
||||
isInitializedRef.current = true;
|
||||
}
|
||||
}, [item.quantity]);
|
||||
|
||||
// Save to sessionStorage
|
||||
const savePendingUpdate = useCallback(
|
||||
(quantity: number) => {
|
||||
try {
|
||||
@@ -90,7 +83,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
[item.product_id],
|
||||
);
|
||||
|
||||
// Remove from sessionStorage
|
||||
const clearPendingUpdate = useCallback(() => {
|
||||
try {
|
||||
const stored = sessionStorage.getItem(PENDING_CART_UPDATES_KEY);
|
||||
@@ -112,7 +104,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
}
|
||||
}, [item.product_id]);
|
||||
|
||||
// Exponential backoff retry
|
||||
const retrySync = useCallback((quantity: number) => {
|
||||
const maxRetries = 4;
|
||||
const retryCount = retryCountRef.current;
|
||||
@@ -123,7 +114,7 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delay = Math.min(1000 * Math.pow(2, retryCount), 16000); // Max 16s
|
||||
const delay = Math.min(1000 * Math.pow(2, retryCount), 16000);
|
||||
retryCountRef.current++;
|
||||
|
||||
retryTimerRef.current = setTimeout(() => {
|
||||
@@ -131,19 +122,15 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
}, delay);
|
||||
}, []);
|
||||
|
||||
// Update ref
|
||||
retrySyncRef.current = retrySync;
|
||||
|
||||
// Sync to server
|
||||
const syncToServer = useCallback(
|
||||
(quantity: number) => {
|
||||
// If already syncing, queue this update
|
||||
if (isRequestInFlightRef.current) {
|
||||
pendingQuantityRef.current = quantity;
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark as syncing
|
||||
isRequestInFlightRef.current = true;
|
||||
setIsSyncing(true);
|
||||
setSyncError(false);
|
||||
@@ -157,7 +144,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
clearPendingUpdate();
|
||||
onUpdate?.();
|
||||
|
||||
// Process queued update if any
|
||||
if (pendingQuantityRef.current !== null) {
|
||||
const nextQuantity = pendingQuantityRef.current;
|
||||
pendingQuantityRef.current = null;
|
||||
@@ -181,7 +167,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
clearPendingUpdate();
|
||||
onUpdate?.();
|
||||
|
||||
// Process queued update if any
|
||||
if (pendingQuantityRef.current !== null) {
|
||||
const nextQuantity = pendingQuantityRef.current;
|
||||
pendingQuantityRef.current = null;
|
||||
@@ -192,7 +177,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
console.error("Update failed:", error);
|
||||
isRequestInFlightRef.current = false;
|
||||
|
||||
// Rollback on error after retries exhausted
|
||||
if (retryCountRef.current >= 3) {
|
||||
setLocalQuantity(item.quantity);
|
||||
clearPendingUpdate();
|
||||
@@ -214,55 +198,29 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
],
|
||||
);
|
||||
|
||||
// Update ref
|
||||
syncToServerRef.current = syncToServer;
|
||||
|
||||
// Load pending updates from sessionStorage on mount
|
||||
useEffect(() => {
|
||||
const loadPendingUpdates = () => {
|
||||
try {
|
||||
const stored = sessionStorage.getItem(PENDING_CART_UPDATES_KEY);
|
||||
if (stored) {
|
||||
const pending: Record<number, PendingUpdate> = JSON.parse(stored);
|
||||
const productPending = pending[item.product_id];
|
||||
if (!isInitializedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (productPending && productPending.quantity !== item.quantity) {
|
||||
// Apply pending update
|
||||
setLocalQuantity(productPending.quantity);
|
||||
pendingQuantityRef.current = productPending.quantity;
|
||||
retryCountRef.current = productPending.retryCount;
|
||||
|
||||
// Trigger sync after a short delay
|
||||
setTimeout(
|
||||
() => syncToServerRef.current?.(productPending.quantity),
|
||||
500,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load pending updates:", error);
|
||||
}
|
||||
};
|
||||
|
||||
loadPendingUpdates();
|
||||
}, [item.product_id, item.quantity]);
|
||||
|
||||
// Debounced sync
|
||||
useEffect(() => {
|
||||
// Clear existing timers
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
|
||||
// If local quantity matches server, no sync needed
|
||||
if (localQuantity === item.quantity) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Save to sessionStorage immediately
|
||||
if (localQuantity <= 0 && item.quantity > 0) {
|
||||
// Delete operation
|
||||
} else if (localQuantity <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
savePendingUpdate(localQuantity);
|
||||
|
||||
// Debounce the API call
|
||||
debounceTimerRef.current = setTimeout(() => {
|
||||
syncToServerRef.current?.(localQuantity);
|
||||
}, 800);
|
||||
@@ -274,7 +232,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
};
|
||||
}, [localQuantity, item.quantity, savePendingUpdate]);
|
||||
|
||||
// Cleanup
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
|
||||
@@ -286,13 +243,11 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
// Check stock limit
|
||||
if (localQuantity >= availableStock) {
|
||||
setShowStockModal(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Optimistic update (instant UI feedback)
|
||||
setLocalQuantity((prev) => prev + 1);
|
||||
};
|
||||
|
||||
@@ -305,7 +260,6 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Optimistic update (instant UI feedback)
|
||||
setLocalQuantity((prev) => prev - 1);
|
||||
};
|
||||
|
||||
@@ -323,49 +277,70 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card className="p-4 shadow-none border">
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<Card className="p-6 shadow-sm border border-gray-200 rounded-2xl hover:shadow-md transition-shadow duration-200">
|
||||
<div className="flex flex-col sm:flex-row gap-6">
|
||||
{/* Product Image & Info */}
|
||||
<div className="flex gap-4 flex-1">
|
||||
<div className="relative w-[88px] h-[117px] rounded-xl border overflow-hidden shrink-0">
|
||||
<div className="relative w-[100px] h-[133px] rounded-xl border border-gray-200 overflow-hidden shrink-0 bg-gray-50">
|
||||
<Image
|
||||
src={getImageSrc()}
|
||||
alt={item.product.name}
|
||||
fill
|
||||
className="object-contain"
|
||||
className="object-contain p-2"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<h3 className="font-semibold text-base">{item.product.name}</h3>
|
||||
<h3 className="font-bold text-base text-gray-900 line-clamp-2">
|
||||
{item.product.name}
|
||||
</h3>
|
||||
{/* <p className="text-sm text-gray-500 font-medium">
|
||||
{item.seller?.name || "Store"}
|
||||
</p> */}
|
||||
|
||||
{/* {availableStock <= 5 && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="h-2 w-2 rounded-full bg-amber-500 animate-pulse" />
|
||||
<p className="text-xs text-amber-600 font-semibold">
|
||||
{t("only_left", { count: availableStock })}
|
||||
</p>
|
||||
</div>
|
||||
)} */}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleDelete}
|
||||
disabled={isRemoving}
|
||||
className="w-fit cursor-pointer p-0 h-auto hover:bg-transparent hover:text-red-500"
|
||||
className="w-fit cursor-pointer p-0 h-auto hover:bg-transparent text-gray-600 hover:text-red-500 transition-colors group"
|
||||
>
|
||||
<Trash2 className="h-5 w-5" />
|
||||
<Trash2 className="h-5 w-5 group-hover:scale-110 transition-transform" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between">
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold">
|
||||
{/* Price & Quantity */}
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-6 justify-between">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-gray-600">
|
||||
{t("unit_price")}{" "}
|
||||
<span className="text-primary">{item.price_formatted}</span>
|
||||
<span className="text-gray-900 font-bold">
|
||||
{item.price_formatted}
|
||||
</span>
|
||||
</p>
|
||||
|
||||
{item.discount_formatted &&
|
||||
item.discount_formatted !== "0 TMT" && (
|
||||
<p className="text-sm font-semibold">
|
||||
<p className="text-sm font-medium text-emerald-600">
|
||||
{t("discount")} {item.discount_formatted}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-semibold">
|
||||
<span className="text-sm font-medium text-gray-600">
|
||||
{t("total_price")}
|
||||
</span>
|
||||
<span className="bg-green-500 text-white px-3 py-1 rounded-lg font-semibold text-base">
|
||||
<span className="bg-emerald-500 text-white px-4 py-1.5 rounded-[10px] font-bold text-base shadow-sm">
|
||||
{(
|
||||
parseFloat(item.product.price_amount || "0") * localQuantity
|
||||
).toFixed(2)}{" "}
|
||||
@@ -374,23 +349,31 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Quantity Controls */}
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleQuantityDecrease}
|
||||
className={` cursor-pointer rounded-lg bg-blue-50 ${
|
||||
isSyncing ? "opacity-70" : ""
|
||||
disabled={isSyncing}
|
||||
className={`cursor-pointer rounded-[10px] h-10 w-10 border-2 border-gray-200 hover:border-gray-900 hover:bg-gray-50 transition-all duration-200 ${
|
||||
isSyncing ? "opacity-50" : ""
|
||||
}`}
|
||||
>
|
||||
<Minus className="h-4 w-4" />
|
||||
<Minus className="h-4 w-4 text-gray-700" />
|
||||
</Button>
|
||||
|
||||
<div className="w-12 text-center font-semibold relative">
|
||||
{localQuantity}
|
||||
<div className="min-w-[48px] text-center font-bold text-lg relative">
|
||||
{isSyncing ? (
|
||||
<div className="flex items-center justify-center">
|
||||
<div className="w-4 h-4 border-2 border-gray-300 border-t-gray-900 rounded-full animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
localQuantity
|
||||
)}
|
||||
{syncError && (
|
||||
<span
|
||||
className="absolute -top-1 -right-3 h-2 w-2 bg-red-500 rounded-full"
|
||||
className="absolute -top-1 -right-2 h-2.5 w-2.5 bg-red-500 rounded-full border-2 border-white shadow-sm"
|
||||
title="Sync error"
|
||||
/>
|
||||
)}
|
||||
@@ -400,16 +383,16 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleQuantityIncrease}
|
||||
// disabled={localQuantity >= availableStock}
|
||||
className={`rounded-lg cursor-pointer bg-blue-50 ${
|
||||
isSyncing ? "opacity-70" : ""
|
||||
} ${
|
||||
disabled={isSyncing || localQuantity >= availableStock}
|
||||
className={`rounded-[10px] h-10 w-10 cursor-pointer border-2 transition-all duration-200 ${
|
||||
localQuantity >= availableStock
|
||||
? "opacity-50 cursor-not-allowed"
|
||||
: ""
|
||||
}`}
|
||||
? "opacity-30 cursor-not-allowed border-gray-200"
|
||||
: "border-gray-900 bg-gray-900 hover:bg-gray-800"
|
||||
} ${isSyncing ? "opacity-50" : ""}`}
|
||||
>
|
||||
<Plus className="h-4 w-4 text-[#007AFF]" />
|
||||
<Plus
|
||||
className={`h-4 w-4 ${localQuantity >= availableStock ? "text-gray-400" : "text-white"}`}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -418,27 +401,27 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
|
||||
{/* Stock Limit Modal */}
|
||||
<Dialog open={showStockModal} onOpenChange={setShowStockModal}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogContent className="sm:max-w-md rounded-3xl border-gray-200">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center justify-center mb-4">
|
||||
<div className="rounded-full bg-orange-100 p-3">
|
||||
<AlertTriangle className="h-6 w-6 text-orange-600" />
|
||||
<div className="rounded-full bg-amber-100 p-4">
|
||||
<AlertTriangle className="h-7 w-7 text-amber-600" />
|
||||
</div>
|
||||
</div>
|
||||
<DialogTitle className="text-center text-xl">
|
||||
<DialogTitle className="text-center text-2xl font-bold text-gray-900">
|
||||
{t("stock_limit_title")}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-center text-base pt-2">
|
||||
<DialogDescription className="text-center text-base pt-3 text-gray-600 leading-relaxed">
|
||||
{t("stock_limit_message", {
|
||||
product: item.product.name,
|
||||
stock: availableStock,
|
||||
})}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex justify-center mt-4">
|
||||
<div className="flex justify-center mt-6">
|
||||
<Button
|
||||
onClick={() => setShowStockModal(false)}
|
||||
className="w-full rounded-lg cursor-pointer"
|
||||
className="w-full h-12 rounded-2xl cursor-pointer bg-gray-900 hover:bg-gray-800 font-semibold shadow-md"
|
||||
>
|
||||
{t("understood")}
|
||||
</Button>
|
||||
|
||||
Reference in New Issue
Block a user