Contect with order api
This commit is contained in:
@@ -329,15 +329,13 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
<p className="text-sm font-semibold">
|
||||
{t("unit_price")} <span className="text-primary">{item.price_formatted}</span>
|
||||
</p>
|
||||
<p className="text-sm font-semibold">
|
||||
{t("extra_price")} {item.sub_total_formatted}
|
||||
</p>
|
||||
|
||||
{item.discount_formatted && item.discount_formatted !== "0 TMT" && (
|
||||
<p className="text-sm font-semibold">{t("discount")} {item.discount_formatted}</p>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-semibold">{t("total_price")}</span>
|
||||
<span className="bg-green-500 text-white px-3 py-1 rounded-xl font-semibold text-base">
|
||||
<span className="bg-green-500 text-white px-3 py-1 rounded-lg font-semibold text-base">
|
||||
{(parseFloat(item.product.price_amount || "0") * localQuantity).toFixed(2)} TMT
|
||||
</span>
|
||||
</div>
|
||||
@@ -348,7 +346,7 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleQuantityDecrease}
|
||||
className={`rounded-xl bg-blue-50 ${isSyncing ? 'opacity-70' : ''}`}
|
||||
className={` cursor-pointerrounded-xl bg-blue-50 ${isSyncing ? 'opacity-70' : ''}`}
|
||||
>
|
||||
<Minus className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -368,11 +366,11 @@ export default function CartItemCard({ item, onUpdate }: CartItemCardProps) {
|
||||
size="icon"
|
||||
onClick={handleQuantityIncrease}
|
||||
disabled={localQuantity >= availableStock}
|
||||
className={`rounded-xl bg-blue-50 ${isSyncing ? 'opacity-70' : ''} ${
|
||||
className={`rounded-xl cursor-pointer bg-blue-50 ${isSyncing ? 'opacity-70' : ''} ${
|
||||
localQuantity >= availableStock ? 'opacity-50 cursor-not-allowed' : ''
|
||||
}`}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
<Plus className="h-4 w-4 text-[#007AFF]" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
import DeliveryTypeSelector from "./DeliveryTypeSelector";
|
||||
import { useTranslations } from "next-intl";
|
||||
import type { DeliveryType, PaymentType, Province } from "@/lib/types/api";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
interface OrderBillingItem {
|
||||
title: string;
|
||||
@@ -42,6 +43,8 @@ interface OrderSummaryProps {
|
||||
regionGroups: Record<string, Province[]>;
|
||||
availableRegions: string[];
|
||||
paymentTypes: PaymentType[];
|
||||
phone: string;
|
||||
onPhoneChange: (phone: string) => void;
|
||||
onPaymentTypeChange: (type: PaymentType) => void;
|
||||
onDeliveryTypeChange: (type: DeliveryType) => void;
|
||||
onRegionChange: (regionCode: string) => void;
|
||||
@@ -61,6 +64,7 @@ export default function OrderSummary({
|
||||
regionGroups,
|
||||
availableRegions,
|
||||
paymentTypes,
|
||||
phone, onPhoneChange,
|
||||
onPaymentTypeChange,
|
||||
onDeliveryTypeChange,
|
||||
onRegionChange,
|
||||
@@ -74,7 +78,7 @@ export default function OrderSummary({
|
||||
const provincesForSelectedRegion = selectedRegion
|
||||
? regionGroups[selectedRegion] || []
|
||||
: [];
|
||||
const isFormValid = selectedRegion && selectedProvince && paymentType;
|
||||
const isFormValid = selectedRegion && selectedProvince && paymentType && phone;
|
||||
|
||||
return (
|
||||
<Card className="w-full md:w-[380px] p-6 rounded-xl h-fit sticky top-20">
|
||||
@@ -167,6 +171,17 @@ export default function OrderSummary({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Phone Number */}
|
||||
<div className="mb-6">
|
||||
<Label className="text-lg font-semibold mb-3 block">{t("phone")}</Label>
|
||||
<Input
|
||||
type="tel"
|
||||
value={phone}
|
||||
onChange={(e) => onPhoneChange(e.target.value)}
|
||||
placeholder={t("phone")}
|
||||
className="rounded-xl"
|
||||
/>
|
||||
</div>
|
||||
{/* Note */}
|
||||
<div className="mb-6">
|
||||
<Label className="text-lg font-semibold mb-3 block">{t("note")}</Label>
|
||||
|
||||
@@ -224,7 +224,7 @@ export function useCreateOrder() {
|
||||
return useMutation({
|
||||
mutationFn: async (payload: {
|
||||
customer_name?: string
|
||||
customer_phone?: string
|
||||
customer_phone: string
|
||||
customer_address: string
|
||||
shipping_method: string
|
||||
payment_type_id: number
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
useCategoryFilters,
|
||||
useFilteredCategoryProducts,
|
||||
} from "@/features/category/hooks/useCategories";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import type { Category, Product } from "@/lib/types/api";
|
||||
|
||||
@@ -232,50 +232,14 @@ export default function CategoryPageClient({
|
||||
[]
|
||||
);
|
||||
|
||||
const renderBreadcrumbs = useCallback(() => {
|
||||
if (!categoriesData || !selectedCategory) return null;
|
||||
|
||||
const breadcrumbs: Category[] = [];
|
||||
let currentCategory = selectedCategory;
|
||||
let parentId = currentCategory.parent_id;
|
||||
|
||||
breadcrumbs.unshift(currentCategory);
|
||||
|
||||
while (parentId) {
|
||||
const parentCategory = findCategoryById(categoriesData, parentId);
|
||||
if (parentCategory) {
|
||||
breadcrumbs.unshift(parentCategory);
|
||||
parentId = parentCategory.parent_id;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 mb-4 text-sm">
|
||||
{breadcrumbs.map((category, index) => (
|
||||
<div key={category.id} className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() =>
|
||||
router.push(`/${locale}/category/${category.slug}`)
|
||||
}
|
||||
className="hover:text-primary transition-colors"
|
||||
>
|
||||
{category.name}
|
||||
</button>
|
||||
{index < breadcrumbs.length - 1 && <span>/</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}, [categoriesData, selectedCategory, findCategoryById, locale, router]);
|
||||
|
||||
|
||||
const FiltersContent = useCallback(
|
||||
() => (
|
||||
<div className="space-y-6">
|
||||
{filtersData?.categories && filtersData.categories.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-3">{t("categories")}</h3>
|
||||
<h3 className="text-lg font-semibold mb-3">{t("category")}</h3>
|
||||
<div className="space-y-2">
|
||||
{filtersData.categories.map((category) => (
|
||||
<label
|
||||
@@ -388,21 +352,20 @@ export default function CategoryPageClient({
|
||||
productsData?.pagination?.total || sortedProducts.length || 0;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{renderBreadcrumbs()}
|
||||
<h2 className="text-3xl font-bold">{selectedCategory.name}</h2>
|
||||
<p className="text-gray-600">
|
||||
{t("total")}: {totalItems} {t("products")}
|
||||
</p>
|
||||
<div className="flex flex-col mx-auto max-w-[1504px]
|
||||
px-2 md:px-4 lg:px-6 pb-12
|
||||
">
|
||||
<h2 className="p-4 text-3xl font-bold pb-6 rounded-lg mb-0 bg-white">{selectedCategory.name}</h2>
|
||||
|
||||
|
||||
<div className="flex gap-4">
|
||||
<div className="hidden sm:block w-[280px] flex-shrink-0 border-r pr-4">
|
||||
<ScrollArea className="h-[calc(100vh-200px)]">
|
||||
<div className="flex gap-4 bg-white rounded-lg">
|
||||
<div className="hidden sm:block w-[280px] shrink-0 border-r px-4 ">
|
||||
<ScrollArea className="h-[calc(100vh-200px)] ">
|
||||
<FiltersContent />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
<div className="flex-1 bg-white rounded-lg">
|
||||
{sortedProducts.length > 0 ? (
|
||||
<InfiniteScroll
|
||||
dataLength={sortedProducts.length}
|
||||
@@ -416,7 +379,7 @@ export default function CategoryPageClient({
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
<div className="bg-white rounded-lg grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
|
||||
{sortedProducts.map((product) => (
|
||||
<ProductCard
|
||||
key={product.id}
|
||||
@@ -429,8 +392,8 @@ export default function CategoryPageClient({
|
||||
}
|
||||
struct_price_text={`${product.price_amount} TMT`}
|
||||
images={[product.media?.[0]?.images_400x400]}
|
||||
is_favorite={false}
|
||||
/>
|
||||
|
||||
button={true} />
|
||||
))}
|
||||
</div>
|
||||
</InfiniteScroll>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useState, MouseEvent, useEffect, useRef } from "react";
|
||||
import { Heart } from "lucide-react";
|
||||
import { useState, MouseEvent, useEffect, useRef, useCallback } from "react";
|
||||
import { Heart, ShoppingCart, Loader2, Plus, Minus } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Carousel,
|
||||
@@ -13,8 +13,14 @@ import {
|
||||
} from "@/components/ui/carousel";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useToggleFavorite, useIsFavorite } from "@/lib/hooks";
|
||||
|
||||
import {
|
||||
useAddToCart,
|
||||
useUpdateCartItemQuantity,
|
||||
useCart,
|
||||
} from "@/features/cart/hooks/useCart";
|
||||
import { useTranslations } from "next-intl";
|
||||
type ProductCardProps = {
|
||||
id: number;
|
||||
name: string;
|
||||
@@ -27,6 +33,8 @@ type ProductCardProps = {
|
||||
price_color?: string;
|
||||
height?: number;
|
||||
width?: number;
|
||||
button?: boolean;
|
||||
stock?: number;
|
||||
};
|
||||
|
||||
export default function ProductCard({
|
||||
@@ -41,19 +49,35 @@ export default function ProductCard({
|
||||
price_color = "#005bff",
|
||||
height = 360,
|
||||
width = 280,
|
||||
button = false,
|
||||
stock,
|
||||
}: ProductCardProps) {
|
||||
const { isFavorite, isLoading: isFavoriteLoading } = useIsFavorite(id);
|
||||
const { mutate: toggleFavorite, isPending } = useToggleFavorite();
|
||||
const { mutate: toggleFavorite, isPending: isFavoriteToggling } =
|
||||
useToggleFavorite();
|
||||
const addToCartMutation = useAddToCart();
|
||||
const updateCartMutation = useUpdateCartItemQuantity();
|
||||
const { data: cartData, refetch: refetchCart } = useCart();
|
||||
|
||||
const [api, setApi] = useState<CarouselApi>();
|
||||
const [current, setCurrent] = useState(0);
|
||||
const [localQuantity, setLocalQuantity] = useState(1);
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
|
||||
const autoplayRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const debounceTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
|
||||
const isRequestInFlightRef = useRef(false);
|
||||
const pendingQuantityRef = useRef<number | null>(null);
|
||||
|
||||
const hasMultipleImages = images.length > 1;
|
||||
|
||||
const cartItem = cartData?.data?.find((item: any) => item.product?.id === id);
|
||||
const isInCart = !!cartItem;
|
||||
const isOutOfStock = stock !== undefined && stock === 0;
|
||||
const availableStock = stock || 999;
|
||||
const t = useTranslations();
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
|
||||
setCurrent(api.selectedScrollSnap());
|
||||
api.on("select", () => {
|
||||
setCurrent(api.selectedScrollSnap());
|
||||
@@ -73,37 +97,158 @@ export default function ProductCard({
|
||||
}, 3000);
|
||||
};
|
||||
|
||||
const stopAutoplay = () => {
|
||||
startAutoplay();
|
||||
return () => {
|
||||
if (autoplayRef.current) {
|
||||
clearInterval(autoplayRef.current);
|
||||
autoplayRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
startAutoplay();
|
||||
return () => stopAutoplay();
|
||||
}, [api, hasMultipleImages]);
|
||||
|
||||
const handleFavorite = (e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
// Sync localQuantity with cart
|
||||
useEffect(() => {
|
||||
if (cartItem?.product_quantity) {
|
||||
setLocalQuantity(cartItem.product_quantity);
|
||||
} else {
|
||||
setLocalQuantity(1);
|
||||
}
|
||||
}, [cartItem]);
|
||||
|
||||
toggleFavorite(
|
||||
{ productId: id, isFavorite },
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
toast.success(
|
||||
data.wasAdded
|
||||
? "Товар добавлен в избранное"
|
||||
: "Товар удален из избранного"
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Ошибка. Попробуйте снова");
|
||||
},
|
||||
const syncToServer = useCallback(
|
||||
async (quantity: number) => {
|
||||
if (isRequestInFlightRef.current) {
|
||||
pendingQuantityRef.current = quantity;
|
||||
return;
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
isRequestInFlightRef.current = true;
|
||||
setIsSyncing(true);
|
||||
|
||||
try {
|
||||
await updateCartMutation.mutateAsync({
|
||||
productId: id,
|
||||
quantity: quantity,
|
||||
});
|
||||
|
||||
isRequestInFlightRef.current = false;
|
||||
setIsSyncing(false);
|
||||
await refetchCart();
|
||||
|
||||
if (pendingQuantityRef.current !== null) {
|
||||
const nextQuantity = pendingQuantityRef.current;
|
||||
pendingQuantityRef.current = null;
|
||||
setTimeout(() => syncToServer(nextQuantity), 100);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Sync failed:", error);
|
||||
isRequestInFlightRef.current = false;
|
||||
setIsSyncing(false);
|
||||
setLocalQuantity(cartItem?.product_quantity || 1);
|
||||
}
|
||||
},
|
||||
[id, updateCartMutation, cartItem, refetchCart]
|
||||
);
|
||||
|
||||
// Debounced sync
|
||||
useEffect(() => {
|
||||
if (!isInCart) return;
|
||||
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
|
||||
if (localQuantity === (cartItem?.product_quantity || 1)) {
|
||||
return;
|
||||
}
|
||||
|
||||
debounceTimerRef.current = setTimeout(() => {
|
||||
syncToServer(localQuantity);
|
||||
}, 800);
|
||||
|
||||
return () => {
|
||||
if (debounceTimerRef.current) {
|
||||
clearTimeout(debounceTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, [localQuantity, isInCart, cartItem, syncToServer]);
|
||||
|
||||
const handleFavorite = useCallback(
|
||||
(e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
toggleFavorite(
|
||||
{ productId: id, isFavorite },
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
toast.success(
|
||||
data.wasAdded ? "Added to favorites" : "Removed from favorites"
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Error. Try again");
|
||||
},
|
||||
}
|
||||
);
|
||||
},
|
||||
[id, isFavorite, toggleFavorite]
|
||||
);
|
||||
|
||||
const handleAddToCart = useCallback(
|
||||
async (e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
setIsSyncing(true);
|
||||
|
||||
try {
|
||||
await addToCartMutation.mutateAsync({
|
||||
productId: id,
|
||||
quantity: localQuantity,
|
||||
});
|
||||
|
||||
await refetchCart();
|
||||
setIsSyncing(false);
|
||||
|
||||
toast.success("Added to cart", {
|
||||
description: `${name} has been added to your cart`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Add to cart error:", error);
|
||||
setIsSyncing(false);
|
||||
toast.error("Failed to add to cart");
|
||||
}
|
||||
},
|
||||
[id, name, localQuantity, addToCartMutation, refetchCart]
|
||||
);
|
||||
|
||||
const handleQuantityIncrease = useCallback(
|
||||
(e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
if (localQuantity >= availableStock) {
|
||||
toast.error("Stock limit reached", {
|
||||
description: `Only ${availableStock} items available`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setLocalQuantity((prev) => prev + 1);
|
||||
},
|
||||
[localQuantity, availableStock]
|
||||
);
|
||||
|
||||
const handleQuantityDecrease = useCallback(
|
||||
(e: MouseEvent<HTMLButtonElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
if (localQuantity <= 1) return;
|
||||
setLocalQuantity((prev) => prev - 1);
|
||||
},
|
||||
[localQuantity]
|
||||
);
|
||||
|
||||
const handleCardClick = (e: MouseEvent<HTMLAnchorElement>) => {
|
||||
const target = e.target as HTMLElement;
|
||||
@@ -172,10 +317,10 @@ export default function ProductCard({
|
||||
)}
|
||||
</Carousel>
|
||||
|
||||
{/* Favorite button - show skeleton while loading favorites */}
|
||||
{/* Favorite button */}
|
||||
<button
|
||||
onClick={handleFavorite}
|
||||
disabled={isPending || isFavoriteLoading}
|
||||
disabled={isFavoriteToggling || isFavoriteLoading}
|
||||
className="absolute top-3 right-3 z-10 rounded-full bg-white/80 p-2 hover:bg-white transition-all disabled:opacity-50"
|
||||
>
|
||||
{isFavoriteLoading ? (
|
||||
@@ -215,6 +360,15 @@ export default function ProductCard({
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Out of Stock Overlay */}
|
||||
{isOutOfStock && (
|
||||
<div className="absolute inset-0 bg-black/50 flex items-center justify-center z-10">
|
||||
<Badge variant="secondary" className="text-sm font-bold">
|
||||
Out of Stock
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<CardContent className="p-0 space-y-1">
|
||||
@@ -228,6 +382,59 @@ export default function ProductCard({
|
||||
{name}
|
||||
</p>
|
||||
</CardContent>
|
||||
|
||||
{/* Cart controls - show on hover if button enabled */}
|
||||
{button && !isOutOfStock && (
|
||||
<div className=" px-1">
|
||||
{!isInCart ? (
|
||||
<Button
|
||||
onClick={handleAddToCart}
|
||||
disabled={isSyncing}
|
||||
className="w-full rounded-lg gap-2 bg-[#005bff] hover:bg-[#0041c4] cursor-pointer"
|
||||
size="sm"
|
||||
>
|
||||
{isSyncing ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Adding...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ShoppingCart className="h-4 w-4" />
|
||||
{t("checkout")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleQuantityDecrease}
|
||||
disabled={isSyncing || localQuantity <= 1}
|
||||
className="rounded-lg cursor-pointer h-9 w-9 shrink-0"
|
||||
>
|
||||
<Minus className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex-1 text-center font-semibold text-sm border rounded-lg h-9 flex items-center justify-center bg-white relative">
|
||||
{localQuantity}
|
||||
{isSyncing && (
|
||||
<Loader2 className="h-3 w-3 animate-spin absolute -top-1 -right-1 text-blue-500" />
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleQuantityIncrease}
|
||||
disabled={localQuantity >= availableStock || isSyncing}
|
||||
className="rounded-lg cursor-pointer h-9 w-9 shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4 text-[#005bff]" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</a>
|
||||
);
|
||||
|
||||
@@ -101,6 +101,7 @@ export default function CollectionSection({ collection, locale }: Props) {
|
||||
price_color="#0059ff"
|
||||
height={360}
|
||||
width={250}
|
||||
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -15,6 +15,15 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Package,
|
||||
Calendar,
|
||||
MapPin,
|
||||
CreditCard,
|
||||
ShoppingBag,
|
||||
} from "lucide-react";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { useOrders, useCancelOrder } from "@/lib/hooks";
|
||||
import { useTranslations } from "next-intl";
|
||||
@@ -27,11 +36,25 @@ interface OrdersPageClientProps {
|
||||
export default function OrdersPageClient({ locale }: OrdersPageClientProps) {
|
||||
const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false);
|
||||
const [orderToCancel, setOrderToCancel] = useState<Order | null>(null);
|
||||
const [expandedOrders, setExpandedOrders] = useState<Set<number>>(new Set());
|
||||
const { toast } = useToast();
|
||||
const t = useTranslations();
|
||||
|
||||
const { data: orders, isLoading, isError, error } = useOrders();
|
||||
const { mutate: cancelOrder, isPending: isCancellingOrder } = useCancelOrder();
|
||||
const { data: orders, isLoading, isError } = useOrders();
|
||||
const { mutate: cancelOrder, isPending: isCancellingOrder } =
|
||||
useCancelOrder();
|
||||
|
||||
const toggleOrderExpand = useCallback((orderId: number) => {
|
||||
setExpandedOrders((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(orderId)) {
|
||||
newSet.delete(orderId);
|
||||
} else {
|
||||
newSet.add(orderId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleCancelOrder = useCallback((order: Order) => {
|
||||
setOrderToCancel(order);
|
||||
@@ -62,72 +85,101 @@ export default function OrdersPageClient({ locale }: OrdersPageClientProps) {
|
||||
|
||||
const getStatusBadge = useCallback((status: string) => {
|
||||
const lowerStatus = status.toLowerCase();
|
||||
|
||||
if (lowerStatus.includes("ожидается") || lowerStatus.includes("pending") || lowerStatus.includes("garaşlama")) {
|
||||
return <Badge variant="outline">{status}</Badge>;
|
||||
|
||||
if (
|
||||
lowerStatus.includes("ожидается") ||
|
||||
lowerStatus.includes("pending") ||
|
||||
lowerStatus.includes("garaşlama")
|
||||
) {
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-yellow-50 text-yellow-700 border-yellow-300"
|
||||
>
|
||||
{status}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (lowerStatus.includes("обработка") || lowerStatus.includes("processing") || lowerStatus.includes("işlenýär")) {
|
||||
return <Badge variant="secondary">{status}</Badge>;
|
||||
if (
|
||||
lowerStatus.includes("обработка") ||
|
||||
lowerStatus.includes("processing") ||
|
||||
lowerStatus.includes("işlenýär")
|
||||
) {
|
||||
return (
|
||||
<Badge variant="secondary" className="bg-blue-50 text-blue-700">
|
||||
{status}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (lowerStatus.includes("отправлен") || lowerStatus.includes("shipped") || lowerStatus.includes("iberildi")) {
|
||||
return <Badge>{status}</Badge>;
|
||||
if (
|
||||
lowerStatus.includes("отправлен") ||
|
||||
lowerStatus.includes("shipped") ||
|
||||
lowerStatus.includes("iberildi")
|
||||
) {
|
||||
return <Badge className="bg-purple-500">{status}</Badge>;
|
||||
}
|
||||
if (lowerStatus.includes("доставлен") || lowerStatus.includes("delivered") || lowerStatus.includes("eltildi")) {
|
||||
if (
|
||||
lowerStatus.includes("доставлен") ||
|
||||
lowerStatus.includes("delivered") ||
|
||||
lowerStatus.includes("eltildi")
|
||||
) {
|
||||
return <Badge className="bg-green-600">{status}</Badge>;
|
||||
}
|
||||
if (lowerStatus.includes("отменен") || lowerStatus.includes("cancelled") || lowerStatus.includes("ýatyryldy")) {
|
||||
if (
|
||||
lowerStatus.includes("отменен") ||
|
||||
lowerStatus.includes("cancelled") ||
|
||||
lowerStatus.includes("ýatyryldy")
|
||||
) {
|
||||
return <Badge variant="destructive">{status}</Badge>;
|
||||
}
|
||||
|
||||
|
||||
return <Badge>{status}</Badge>;
|
||||
}, []);
|
||||
|
||||
const isActiveOrder = useCallback((status: string) => {
|
||||
const lower = status.toLowerCase();
|
||||
return lower.includes("ожидается") || lower.includes("обработка") || lower.includes("отправлен") ||
|
||||
lower.includes("pending") || lower.includes("processing") || lower.includes("shipped") ||
|
||||
lower.includes("garaşlama") || lower.includes("işlenýär") || lower.includes("iberildi");
|
||||
return (
|
||||
lower.includes("ожидается") ||
|
||||
lower.includes("обработка") ||
|
||||
lower.includes("отправлен") ||
|
||||
lower.includes("pending") ||
|
||||
lower.includes("processing") ||
|
||||
lower.includes("shipped") ||
|
||||
lower.includes("garaşylýar") ||
|
||||
lower.includes("işlenýär") ||
|
||||
lower.includes("iberildi")
|
||||
);
|
||||
}, []);
|
||||
|
||||
const activeOrders = useMemo(() => orders?.filter((o) => isActiveOrder(o.status)) || [], [orders, isActiveOrder]);
|
||||
const completedOrders = useMemo(() => orders?.filter((o) => !isActiveOrder(o.status)) || [], [orders, isActiveOrder]);
|
||||
const activeOrders = useMemo(
|
||||
() => orders?.filter((o) => isActiveOrder(o.status)) || [],
|
||||
[orders, isActiveOrder]
|
||||
);
|
||||
const completedOrders = useMemo(
|
||||
() => orders?.filter((o) => !isActiveOrder(o.status)) || [],
|
||||
[orders, isActiveOrder]
|
||||
);
|
||||
|
||||
const calculateTotal = useCallback((order: Order) => {
|
||||
return order.orderItems.reduce((sum, item) => {
|
||||
return sum + (parseFloat(item.unit_price_amount) * item.quantity);
|
||||
return sum + parseFloat(item.unit_price_amount) * item.quantity;
|
||||
}, 0);
|
||||
}, []);
|
||||
|
||||
const loadingSkeleton = useMemo(() => (
|
||||
<div className="container mx-auto p-4 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t("my_orders")}</h1>
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-10 w-40" />
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-64 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
), [t]);
|
||||
|
||||
if (isLoading) {
|
||||
return loadingSkeleton;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<div className="container mx-auto p-4 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t("my_orders")}</h1>
|
||||
<div className="bg-red-50 p-4 rounded-lg border border-red-200">
|
||||
<p className="text-red-600">{t("load_orders_error")}</p>
|
||||
<div className="space-y-4">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-32 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!orders || orders.length === 0) {
|
||||
if (isError || !orders || orders.length === 0) {
|
||||
return (
|
||||
<div className="container mx-auto p-4 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t("my_orders")}</h1>
|
||||
@@ -158,16 +210,19 @@ export default function OrdersPageClient({ locale }: OrdersPageClientProps) {
|
||||
<p className="text-xl text-gray-400">{t("no_active_orders")}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div className="space-y-4">
|
||||
{activeOrders.map((order) => (
|
||||
<OrderCard
|
||||
<CompactOrderCard
|
||||
key={order.id}
|
||||
order={order}
|
||||
isExpanded={expandedOrders.has(order.id)}
|
||||
onToggle={() => toggleOrderExpand(order.id)}
|
||||
onCancel={handleCancelOrder}
|
||||
isCancelling={isCancellingOrder}
|
||||
getStatusBadge={getStatusBadge}
|
||||
calculateTotal={calculateTotal}
|
||||
showCancelButton
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -177,19 +232,24 @@ export default function OrdersPageClient({ locale }: OrdersPageClientProps) {
|
||||
<TabsContent value="completed">
|
||||
{completedOrders.length === 0 ? (
|
||||
<div className="flex items-center justify-center min-h-[40vh]">
|
||||
<p className="text-xl text-gray-400">{t("no_completed_orders")}</p>
|
||||
<p className="text-xl text-gray-400">
|
||||
{t("no_completed_orders")}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div className="space-y-4">
|
||||
{completedOrders.map((order) => (
|
||||
<OrderCard
|
||||
<CompactOrderCard
|
||||
key={order.id}
|
||||
order={order}
|
||||
isExpanded={expandedOrders.has(order.id)}
|
||||
onToggle={() => toggleOrderExpand(order.id)}
|
||||
onCancel={handleCancelOrder}
|
||||
isCancelling={isCancellingOrder}
|
||||
getStatusBadge={getStatusBadge}
|
||||
calculateTotal={calculateTotal}
|
||||
showCancelButton={false}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -213,7 +273,11 @@ export default function OrdersPageClient({ locale }: OrdersPageClientProps) {
|
||||
>
|
||||
{t("keep_order")}
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={confirmCancelOrder} disabled={isCancellingOrder}>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={confirmCancelOrder}
|
||||
disabled={isCancellingOrder}
|
||||
>
|
||||
{isCancellingOrder ? t("cancelling") : t("cancel_order")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
@@ -223,92 +287,190 @@ export default function OrdersPageClient({ locale }: OrdersPageClientProps) {
|
||||
);
|
||||
}
|
||||
|
||||
interface OrderCardProps {
|
||||
interface CompactOrderCardProps {
|
||||
order: Order;
|
||||
isExpanded: boolean;
|
||||
onToggle: () => void;
|
||||
onCancel: (order: Order) => void;
|
||||
isCancelling: boolean;
|
||||
getStatusBadge: (status: string) => React.ReactNode;
|
||||
calculateTotal: (order: Order) => number;
|
||||
showCancelButton: boolean;
|
||||
t: any;
|
||||
}
|
||||
|
||||
function OrderCard({
|
||||
function CompactOrderCard({
|
||||
order,
|
||||
isExpanded,
|
||||
onToggle,
|
||||
onCancel,
|
||||
isCancelling,
|
||||
getStatusBadge,
|
||||
calculateTotal,
|
||||
showCancelButton,
|
||||
}: OrderCardProps) {
|
||||
const t = useTranslations();
|
||||
t,
|
||||
}: CompactOrderCardProps) {
|
||||
const total = useMemo(() => calculateTotal(order), [calculateTotal, order]);
|
||||
const itemCount = order.orderItems.length;
|
||||
|
||||
return (
|
||||
<Card className="p-4 flex flex-col justify-between">
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-3">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("order_number")}{order.id}
|
||||
</h3>
|
||||
{getStatusBadge(order.status)}
|
||||
</div>
|
||||
|
||||
<div className="mb-3 space-y-1 text-sm">
|
||||
<p className="text-gray-600">
|
||||
<span className="font-medium">{t("delivery_time")}:</span> {order.delivery_time}
|
||||
</p>
|
||||
<p className="text-gray-600">
|
||||
<span className="font-medium">{t("delivery_date")}:</span>{" "}
|
||||
{new Date(order.delivery_at).toLocaleDateString()}
|
||||
</p>
|
||||
<p className="text-gray-600">
|
||||
<span className="font-medium">{t("address")}:</span> {order.customer_address}
|
||||
</p>
|
||||
<p className="text-gray-600">
|
||||
<span className="font-medium">{t("payment_method")}:</span> {order.payment_type}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 mb-3 max-h-48 overflow-y-auto">
|
||||
{order.orderItems.map((item, index) => (
|
||||
<div key={index} className="flex items-start gap-3">
|
||||
<Image
|
||||
src={item.product.images_400x400 || item.product.thumbnail}
|
||||
alt={item.product.name}
|
||||
width={50}
|
||||
height={50}
|
||||
className="rounded object-cover"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium line-clamp-2">{item.product.name}</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t("product_quantity")}: {item.quantity} × {item.unit_price_amount} TMT
|
||||
<Card className="overflow-hidden transition-all hover:shadow-md">
|
||||
{/* Compact Header - Always Visible */}
|
||||
<div
|
||||
className="p-4 mx-4 rounded-lg cursor-pointer bg-linear-to-r from-white to-gray-50 hover:from-gray-50 hover:to-gray-100 transition-colors"
|
||||
onClick={onToggle}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Package className="h-5 w-5 text-gray-500" />
|
||||
<div>
|
||||
<h3 className="font-semibold text-lg">
|
||||
{t("order_number")} {order.id}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{itemCount} {itemCount === 1 ? t("product") : t("products")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-3">
|
||||
<div className="flex justify-between font-semibold">
|
||||
<span>{t("total_price")}</span>
|
||||
<span>{total.toFixed(2)} TMT</span>
|
||||
<div className="flex items-center gap-4">
|
||||
{getStatusBadge(order.status)}
|
||||
<div className="text-right">
|
||||
<p className="font-bold text-lg text-green-600">
|
||||
{total.toFixed(2)} TMT
|
||||
</p>
|
||||
</div>
|
||||
{isExpanded ? (
|
||||
<ChevronUp className="h-5 w-5 text-gray-400" />
|
||||
) : (
|
||||
<ChevronDown className="h-5 w-5 text-gray-400" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showCancelButton && (
|
||||
<div className="mt-4">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => onCancel(order)}
|
||||
disabled={isCancelling}
|
||||
className="w-full"
|
||||
>
|
||||
{t("cancel_order")}
|
||||
</Button>
|
||||
{/* Expandable Details */}
|
||||
{isExpanded && (
|
||||
<div className="border-t bg-white">
|
||||
{/* Order Info Grid */}
|
||||
<div className="p-4 grid grid-cols-1 md:grid-cols-2 gap-4 bg-gray-50">
|
||||
<div className="flex items-start gap-3">
|
||||
<Calendar className="h-5 w-5 text-blue-500 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-700">
|
||||
{t("delivery_date")}
|
||||
</p>
|
||||
<p className="text-sm text-gray-900">
|
||||
{new Date(order.delivery_at).toLocaleDateString()} •{" "}
|
||||
{order.delivery_time}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3">
|
||||
<MapPin className="h-5 w-5 text-red-500 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-700">
|
||||
{t("address")}
|
||||
</p>
|
||||
<p className="text-sm text-gray-900">
|
||||
{order.customer_address}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3">
|
||||
<CreditCard className="h-5 w-5 text-green-500 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-700">
|
||||
{t("payment_method")}
|
||||
</p>
|
||||
<p className="text-sm text-gray-900">{order.payment_type}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-3">
|
||||
<ShoppingBag className="h-5 w-5 text-purple-500 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-700">
|
||||
{t("shipping_method")}
|
||||
</p>
|
||||
<p className="text-sm text-gray-900">{order.shipping_method}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Products List */}
|
||||
<div className="p-4">
|
||||
<h4 className="font-semibold mb-3 text-gray-700">
|
||||
{t("products")}:
|
||||
</h4>
|
||||
<div className="space-y-3 max-h-96 overflow-y-auto">
|
||||
{order.orderItems.map((item, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-4 p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
|
||||
>
|
||||
<div className="relative w-16 h-16 flex-shrink-0 rounded-md overflow-hidden bg-white border">
|
||||
<Image
|
||||
src={
|
||||
item.product.images_400x400 || item.product.thumbnail
|
||||
}
|
||||
alt={item.product.name}
|
||||
fill
|
||||
className="object-contain p-1"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-sm line-clamp-2">
|
||||
{item.product.name}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
{item.quantity} × {item.unit_price_amount} TMT
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-semibold text-sm">
|
||||
{(
|
||||
parseFloat(item.unit_price_amount) * item.quantity
|
||||
).toFixed(2)}{" "}
|
||||
TMT
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer with Total and Actions */}
|
||||
<div className="border-t p-4 bg-gray-50">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<span className="text-base font-semibold text-gray-700">
|
||||
{t("total_price")}:
|
||||
</span>
|
||||
<span className="text-xl font-bold text-green-600">
|
||||
{total.toFixed(2)} TMT
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{showCancelButton && (
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onCancel(order);
|
||||
}}
|
||||
disabled={isCancelling}
|
||||
className="w-full"
|
||||
>
|
||||
{t("cancel_order")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,7 +506,7 @@ export default function ProductPageContent({ slug }: ProductDetailProps) {
|
||||
</div>
|
||||
|
||||
<div className="lg:w-[380px] space-y-4">
|
||||
<Card className="p-6 rounded-xl shadow-lg sticky top-4">
|
||||
<Card className="p-6 rounded-xl ">
|
||||
<div className="flex justify-between items-start mb-6">
|
||||
<span className="text-lg text-gray-500">{t("price")}:</span>
|
||||
<div className="flex flex-col items-end">
|
||||
|
||||
Reference in New Issue
Block a user