Contect with order api
This commit is contained in:
@@ -18,11 +18,12 @@ import type { DeliveryType, PaymentType } from "@/lib/types/api";
|
||||
export default function CartPage() {
|
||||
const [isClient, setIsClient] = useState(false);
|
||||
const [paymentType, setPaymentType] = useState<PaymentType | null>(null);
|
||||
const [deliveryType, setDeliveryType] = useState<DeliveryType>("SELECTED_DELIVERY");
|
||||
const [deliveryType, setDeliveryType] =
|
||||
useState<DeliveryType>("SELECTED_DELIVERY");
|
||||
const [selectedRegion, setSelectedRegion] = useState<string>("");
|
||||
const [selectedProvince, setSelectedProvince] = useState<number | null>(null);
|
||||
const [note, setNote] = useState<string>("");
|
||||
|
||||
const [phone, setPhone] = useState<string>("");
|
||||
const router = useRouter();
|
||||
const t = useTranslations();
|
||||
|
||||
@@ -48,7 +49,10 @@ export default function CartPage() {
|
||||
}, {} as Record<string, typeof provinces>);
|
||||
}, [provinces]);
|
||||
|
||||
const availableRegions = useMemo(() => Object.keys(regionGroups), [regionGroups]);
|
||||
const availableRegions = useMemo(
|
||||
() => Object.keys(regionGroups),
|
||||
[regionGroups]
|
||||
);
|
||||
|
||||
// Memoize items grouped by seller
|
||||
const itemsBySeller = useMemo(() => {
|
||||
@@ -86,7 +90,9 @@ export default function CartPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedProvinceData = provinces.find((p) => p.id === selectedProvince);
|
||||
const selectedProvinceData = provinces.find(
|
||||
(p) => p.id === selectedProvince
|
||||
);
|
||||
if (!selectedProvinceData) return;
|
||||
|
||||
const orderData = userStore.getOrderData();
|
||||
@@ -99,7 +105,7 @@ export default function CartPage() {
|
||||
createOrder(
|
||||
{
|
||||
customer_name: orderData.customer_name,
|
||||
customer_phone: orderData.customer_phone,
|
||||
customer_phone: phone,
|
||||
customer_address: selectedProvinceData.name,
|
||||
shipping_method: deliveryType === "PICK_UP" ? "pickup" : "standart",
|
||||
payment_type_id: paymentType.id,
|
||||
@@ -141,12 +147,15 @@ export default function CartPage() {
|
||||
<div className="flex flex-col md:flex-row gap-6">
|
||||
<div className="flex-1">
|
||||
<Card className="p-6 rounded-xl">
|
||||
{Object.entries(itemsBySeller).map(([sellerId, { seller, items }]) => (
|
||||
{Object.entries(itemsBySeller).map(
|
||||
([sellerId, { seller, items }]) => (
|
||||
<div key={sellerId} className="mb-6">
|
||||
<p className="text-base font-semibold mb-3">{seller.name}</p>
|
||||
<div className="space-y-4">
|
||||
{items.map((item) => {
|
||||
const price = parseFloat(item.product.price_amount || "0");
|
||||
const price = parseFloat(
|
||||
item.product.price_amount || "0"
|
||||
);
|
||||
const quantity = item.product_quantity;
|
||||
const total = price * quantity;
|
||||
|
||||
@@ -182,7 +191,8 @@ export default function CartPage() {
|
||||
<Separator className="mt-4" />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -217,6 +227,8 @@ export default function CartPage() {
|
||||
onNoteChange={setNote}
|
||||
onCompleteOrder={handleCompleteOrder}
|
||||
isLoading={isCreatingOrder}
|
||||
phone={phone}
|
||||
onPhoneChange={setPhone}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,76 +1,17 @@
|
||||
"use client";
|
||||
import {
|
||||
useFavorites,
|
||||
useAddToCart,
|
||||
useRemoveFromFavorites,
|
||||
} from "@/lib/hooks";
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { Heart, ShoppingCart } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
import { useFavorites } from "@/lib/hooks";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { useTranslations } from "next-intl";
|
||||
import ProductCard from "@/features/home/components/ProductCard";
|
||||
import type { Favorite } from "@/lib/types/api";
|
||||
|
||||
export default function FavoritesPage() {
|
||||
const [isHovered, setIsHovered] = useState<number | null>(null);
|
||||
const { toast } = useToast();
|
||||
const t = useTranslations();
|
||||
|
||||
const { data: favorites, isLoading, isError } = useFavorites();
|
||||
const { mutate: removeFromFavorites, isPending: isRemoving } =
|
||||
useRemoveFromFavorites();
|
||||
const { mutate: addToCart, isPending: isAddingToCart } = useAddToCart();
|
||||
|
||||
const handleRemoveFromFavorites = useCallback(
|
||||
(productId: number) => {
|
||||
removeFromFavorites(productId, {
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: t("removed_from_favorites"),
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toast({
|
||||
title: t("error"),
|
||||
description: error.message,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
},
|
||||
[removeFromFavorites, toast, t]
|
||||
);
|
||||
|
||||
const handleAddToCart = useCallback(
|
||||
(productId: number) => {
|
||||
addToCart(
|
||||
{ productId },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast({
|
||||
title: t("added_to_cart"),
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toast({
|
||||
title: t("error"),
|
||||
description: error.message,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
}
|
||||
);
|
||||
},
|
||||
[addToCart, toast, t]
|
||||
);
|
||||
|
||||
const loadingSkeleton = useMemo(
|
||||
() => (
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t("favorite_products")}</h1>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
|
||||
@@ -79,17 +20,12 @@ export default function FavoritesPage() {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
[t]
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
return loadingSkeleton;
|
||||
}
|
||||
|
||||
if (isError || !favorites || favorites.length === 0) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 min-h-screen">
|
||||
<div className="container mx-auto px-6 py-8 bg-white">
|
||||
<h1 className="text-3xl font-bold mb-6">{t("favorite_products")}</h1>
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<p className="text-2xl text-gray-400">{t("empty_favorites")}</p>
|
||||
@@ -99,145 +35,48 @@ export default function FavoritesPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t("favorite_products")}</h1>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
|
||||
{favorites.map((favorite: Favorite) => (
|
||||
<ProductCard
|
||||
key={favorite.product.id}
|
||||
productId={favorite.product.id}
|
||||
product={favorite.product}
|
||||
onRemove={() => handleRemoveFromFavorites(favorite.product.id)}
|
||||
onAddToCart={() => handleAddToCart(favorite.product.id)}
|
||||
onHover={setIsHovered}
|
||||
isHovered={isHovered === favorite.product.id}
|
||||
isRemoving={isRemoving}
|
||||
isAddingToCart={isAddingToCart}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
<div className="container mx-auto px-6
|
||||
md:px-4 lg:px-6 pb-12 space-y-8 max-w-[1504px]
|
||||
">
|
||||
<h1 className="bg-white text-3xl p-4 font-bold mb-0 pb-6">{t("favorite_products")}</h1>
|
||||
<div className="bg-white grid grid-cols-2 sm:grid-cols-3 rounded-lg md:grid-cols-4 lg:grid-cols-5 gap-3 p-4">
|
||||
{favorites.map((favorite: Favorite) => {
|
||||
const product = favorite.product;
|
||||
|
||||
interface Product {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
price_amount: string;
|
||||
old_price_amount?: string | null;
|
||||
media: Array<{
|
||||
thumbnail: string;
|
||||
images_400x400: string;
|
||||
images_720x720: string;
|
||||
images_800x800: string;
|
||||
images_1200x1200: string;
|
||||
}>;
|
||||
stock: number;
|
||||
}
|
||||
const allImages = product.media
|
||||
?.map(
|
||||
(media) =>
|
||||
media.images_800x800 ||
|
||||
media.images_720x720 ||
|
||||
media.images_400x400 ||
|
||||
media.thumbnail
|
||||
)
|
||||
.filter(Boolean) || ["/placeholder-product.jpg"];
|
||||
|
||||
interface ProductCardProps {
|
||||
productId: number;
|
||||
product: Product;
|
||||
onRemove: () => void;
|
||||
onAddToCart: () => void;
|
||||
onHover: (id: number | null) => void;
|
||||
isHovered: boolean;
|
||||
isRemoving: boolean;
|
||||
isAddingToCart: boolean;
|
||||
}
|
||||
|
||||
function ProductCard({
|
||||
productId,
|
||||
product,
|
||||
onRemove,
|
||||
onAddToCart,
|
||||
onHover,
|
||||
isHovered,
|
||||
isRemoving,
|
||||
isAddingToCart,
|
||||
}: ProductCardProps) {
|
||||
const t = useTranslations();
|
||||
|
||||
if (!product) return null;
|
||||
|
||||
const imageUrl =
|
||||
product.media?.[0]?.images_800x800 ||
|
||||
product.media?.[0]?.thumbnail ||
|
||||
"/placeholder.svg";
|
||||
|
||||
const price = `${parseFloat(product.price_amount).toFixed(2)} TMT`;
|
||||
const oldPrice = product.old_price_amount
|
||||
? `${parseFloat(product.old_price_amount).toFixed(2)} TMT`
|
||||
: null;
|
||||
const formattedPrice = product.price_amount
|
||||
? `${parseFloat(product.price_amount).toFixed(2)} TMT`
|
||||
: "Price not available";
|
||||
|
||||
return (
|
||||
<Card
|
||||
className="group overflow-hidden rounded-xl transition-shadow hover:shadow-lg relative border-none"
|
||||
onMouseEnter={() => onHover(productId)}
|
||||
onMouseLeave={() => onHover(null)}
|
||||
>
|
||||
<Link href={`/product/${productId || product.slug}`} className="block">
|
||||
<div className="relative aspect-square bg-gray-50">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onRemove();
|
||||
}}
|
||||
disabled={isRemoving}
|
||||
className="absolute top-2 right-2 z-10 bg-white rounded-full p-2 shadow-md hover:scale-110 transition-transform disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Heart className="h-5 w-5 fill-red-500 text-red-500" />
|
||||
</button>
|
||||
|
||||
<Image
|
||||
src={imageUrl}
|
||||
alt={product.name}
|
||||
fill
|
||||
sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, (max-width: 1024px) 25vw, 20vw"
|
||||
className="object-contain p-4 group-hover:scale-105 transition-transform"
|
||||
priority={false}
|
||||
<ProductCard
|
||||
key={product.id}
|
||||
id={product.id}
|
||||
name={product.name}
|
||||
price={
|
||||
product.price_amount ? parseFloat(product.price_amount) : null
|
||||
}
|
||||
struct_price_text={formattedPrice}
|
||||
images={allImages}
|
||||
labels={[]}
|
||||
price_color="#0059ff"
|
||||
height={360}
|
||||
width={250}
|
||||
button={true}
|
||||
stock={product.stock}
|
||||
/>
|
||||
|
||||
{product.stock === 0 && (
|
||||
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
|
||||
<Badge variant="secondary" className="text-sm">
|
||||
{t("out_of_stock")}
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-3">
|
||||
<h3 className="font-medium text-sm line-clamp-2 mb-2 min-h-[40px]">
|
||||
{product.name}
|
||||
</h3>
|
||||
<div className="space-y-1">
|
||||
{oldPrice && (
|
||||
<p className="text-sm text-gray-400 line-through">{oldPrice}</p>
|
||||
)}
|
||||
<p className="text-lg font-bold text-blue-600">{price}</p>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
{isHovered && product.stock > 0 && (
|
||||
<div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-white via-white to-transparent">
|
||||
<Button
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
onAddToCart();
|
||||
}}
|
||||
disabled={isAddingToCart}
|
||||
className="w-full rounded-xl gap-2"
|
||||
size="sm"
|
||||
>
|
||||
<ShoppingCart className="h-4 w-4" />
|
||||
{t("add_to_cart")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,65 +1,74 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import type React from "react"
|
||||
import { useState } from "react"
|
||||
import { Upload } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { useOpenStore } from "@/lib/hooks"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import type React from "react";
|
||||
import { useState } from "react";
|
||||
import { Upload } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { useOpenStore } from "@/lib/hooks";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
|
||||
interface OpenStorePageProps {
|
||||
locale?: string
|
||||
locale?: string;
|
||||
translations?: {
|
||||
title: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
email: string
|
||||
phone: string
|
||||
uploadPatent: string
|
||||
submit: string
|
||||
selectedFile: string
|
||||
firstNameRequired: string
|
||||
lastNameRequired: string
|
||||
emailInvalid: string
|
||||
phoneInvalid: string
|
||||
fileRequired: string
|
||||
fileSizeError: string
|
||||
fileTypeError: string
|
||||
}
|
||||
title: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
uploadPatent: string;
|
||||
submit: string;
|
||||
selectedFile: string;
|
||||
firstNameRequired: string;
|
||||
lastNameRequired: string;
|
||||
emailInvalid: string;
|
||||
phoneInvalid: string;
|
||||
fileRequired: string;
|
||||
fileSizeError: string;
|
||||
fileTypeError: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface FormData {
|
||||
firstName: string
|
||||
lastName: string
|
||||
email: string
|
||||
phone: string
|
||||
file: File | null
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
file: File | null;
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
firstName?: string
|
||||
lastName?: string
|
||||
email?: string
|
||||
phone?: string
|
||||
file?: string
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
phone?: string;
|
||||
file?: string;
|
||||
}
|
||||
|
||||
export default function OpenStorePage({ locale = "ru", translations }: OpenStorePageProps) {
|
||||
export default function OpenStorePage({
|
||||
locale = "ru",
|
||||
translations,
|
||||
}: OpenStorePageProps) {
|
||||
const [formData, setFormData] = useState<FormData>({
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
email: "",
|
||||
phone: "+993",
|
||||
file: null,
|
||||
})
|
||||
const [errors, setErrors] = useState<FormErrors>({})
|
||||
const [fileName, setFileName] = useState("")
|
||||
});
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [fileName, setFileName] = useState("");
|
||||
|
||||
const { mutate: submitOpenStore, isPending: loading } = useOpenStore()
|
||||
const { toast } = useToast()
|
||||
const { mutate: submitOpenStore, isPending: loading } = useOpenStore();
|
||||
const { toast } = useToast();
|
||||
|
||||
const t = translations || {
|
||||
title: "Форма подачи заявления на открытие магазина",
|
||||
@@ -77,68 +86,68 @@ export default function OpenStorePage({ locale = "ru", translations }: OpenStore
|
||||
fileRequired: "Патент обязателен",
|
||||
fileSizeError: "Файл слишком большой (макс. 25MB)",
|
||||
fileTypeError: "Только PDF и JPG документы",
|
||||
}
|
||||
};
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: FormErrors = {}
|
||||
const newErrors: FormErrors = {};
|
||||
|
||||
if (!formData.firstName.trim()) {
|
||||
newErrors.firstName = t.firstNameRequired
|
||||
newErrors.firstName = t.firstNameRequired;
|
||||
}
|
||||
|
||||
if (!formData.lastName.trim()) {
|
||||
newErrors.lastName = t.lastNameRequired
|
||||
newErrors.lastName = t.lastNameRequired;
|
||||
}
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(formData.email)) {
|
||||
newErrors.email = t.emailInvalid
|
||||
newErrors.email = t.emailInvalid;
|
||||
}
|
||||
|
||||
const phoneRegex = /^\+?[0-9]{6,15}$/
|
||||
const phoneRegex = /^\+?[0-9]{6,15}$/;
|
||||
if (!phoneRegex.test(formData.phone)) {
|
||||
newErrors.phone = t.phoneInvalid
|
||||
newErrors.phone = t.phoneInvalid;
|
||||
}
|
||||
|
||||
if (!formData.file) {
|
||||
newErrors.file = t.fileRequired
|
||||
newErrors.file = t.fileRequired;
|
||||
} else {
|
||||
const allowedTypes = ["image/jpeg", "image/jpg", "application/pdf"]
|
||||
const allowedTypes = ["image/jpeg", "image/jpg", "application/pdf"];
|
||||
if (!allowedTypes.includes(formData.file.type)) {
|
||||
newErrors.file = t.fileTypeError
|
||||
newErrors.file = t.fileTypeError;
|
||||
}
|
||||
if (formData.file.size > 25 * 1024 * 1024) {
|
||||
newErrors.file = t.fileSizeError
|
||||
newErrors.file = t.fileSizeError;
|
||||
}
|
||||
}
|
||||
|
||||
setErrors(newErrors)
|
||||
return Object.keys(newErrors).length === 0
|
||||
}
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target
|
||||
setFormData((prev) => ({ ...prev, [name]: value }))
|
||||
const { name, value } = e.target;
|
||||
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||
if (errors[name as keyof FormErrors]) {
|
||||
setErrors((prev) => ({ ...prev, [name]: undefined }))
|
||||
}
|
||||
setErrors((prev) => ({ ...prev, [name]: undefined }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setFormData((prev) => ({ ...prev, file }))
|
||||
setFileName(file.name)
|
||||
setFormData((prev) => ({ ...prev, file }));
|
||||
setFileName(file.name);
|
||||
if (errors.file) {
|
||||
setErrors((prev) => ({ ...prev, file: undefined }))
|
||||
}
|
||||
setErrors((prev) => ({ ...prev, file: undefined }));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
e.preventDefault();
|
||||
|
||||
if (!validateForm()) return
|
||||
if (!validateForm()) return;
|
||||
|
||||
if (formData.file) {
|
||||
submitOpenStore(
|
||||
@@ -154,34 +163,36 @@ export default function OpenStorePage({ locale = "ru", translations }: OpenStore
|
||||
toast({
|
||||
title: "Success",
|
||||
description: "Your store request has been submitted successfully",
|
||||
})
|
||||
});
|
||||
setFormData({
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
email: "",
|
||||
phone: "+993",
|
||||
file: null,
|
||||
})
|
||||
setFileName("")
|
||||
});
|
||||
setFileName("");
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: error?.message || "Failed to submit store request",
|
||||
variant: "destructive",
|
||||
})
|
||||
});
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
|
||||
<div className=" bg-gray-50 flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md shadow-lg">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-2xl text-center">{t.title}</CardTitle>
|
||||
<CardDescription className="text-center">Заполните форму для подачи заявления</CardDescription>
|
||||
<CardDescription className="text-center">
|
||||
Заполните форму для подачи заявления
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
@@ -195,7 +206,9 @@ export default function OpenStorePage({ locale = "ru", translations }: OpenStore
|
||||
onChange={handleInputChange}
|
||||
className={errors.firstName ? "border-red-500" : ""}
|
||||
/>
|
||||
{errors.firstName && <p className="text-sm text-red-500">{errors.firstName}</p>}
|
||||
{errors.firstName && (
|
||||
<p className="text-sm text-red-500">{errors.firstName}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Last Name */}
|
||||
@@ -208,7 +221,9 @@ export default function OpenStorePage({ locale = "ru", translations }: OpenStore
|
||||
onChange={handleInputChange}
|
||||
className={errors.lastName ? "border-red-500" : ""}
|
||||
/>
|
||||
{errors.lastName && <p className="text-sm text-red-500">{errors.lastName}</p>}
|
||||
{errors.lastName && (
|
||||
<p className="text-sm text-red-500">{errors.lastName}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Email */}
|
||||
@@ -222,7 +237,9 @@ export default function OpenStorePage({ locale = "ru", translations }: OpenStore
|
||||
onChange={handleInputChange}
|
||||
className={errors.email ? "border-red-500" : ""}
|
||||
/>
|
||||
{errors.email && <p className="text-sm text-red-500">{errors.email}</p>}
|
||||
{errors.email && (
|
||||
<p className="text-sm text-red-500">{errors.email}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Phone */}
|
||||
@@ -236,14 +253,22 @@ export default function OpenStorePage({ locale = "ru", translations }: OpenStore
|
||||
placeholder="+99361111111"
|
||||
className={errors.phone ? "border-red-500" : ""}
|
||||
/>
|
||||
{errors.phone && <p className="text-sm text-red-500">{errors.phone}</p>}
|
||||
{errors.phone && (
|
||||
<p className="text-sm text-red-500">{errors.phone}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* File Upload */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="file">{t.uploadPatent}</Label>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Input id="file" type="file" accept=".pdf,.jpg,.jpeg" onChange={handleFileChange} className="hidden" />
|
||||
<Input
|
||||
id="file"
|
||||
type="file"
|
||||
accept=".pdf,.jpg,.jpeg"
|
||||
onChange={handleFileChange}
|
||||
className="hidden"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
@@ -258,17 +283,23 @@ export default function OpenStorePage({ locale = "ru", translations }: OpenStore
|
||||
{t.selectedFile}: {fileName}
|
||||
</p>
|
||||
)}
|
||||
{errors.file && <p className="text-sm text-red-500">{errors.file}</p>}
|
||||
{errors.file && (
|
||||
<p className="text-sm text-red-500">{errors.file}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full cursor-pointer bg-[#005bff] hover:bg-[#0041c4]"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Загрузка..." : t.submit}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,14 +3,8 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { X, Menu, Search, Store, LogOut, User as UserIcon } from "lucide-react";
|
||||
import { X, Search, Store, User as UserIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import Logo from "@/public/logo.webp";
|
||||
import CategoryMenu from "./ui/CategoryMenu";
|
||||
import SearchBar from "./ui/SearchBar";
|
||||
@@ -65,10 +59,16 @@ export default function Header({ locale = "ru" }: HeaderProps) {
|
||||
<>
|
||||
<header className="sticky top-0 z-50 w-full border-b bg-white shadow-sm">
|
||||
<div className="container mx-auto px-4">
|
||||
<div className="flex h-16 items-center justify-between gap-4">
|
||||
<div className="flex h-16 items-center justify-between gap-3">
|
||||
<Link href="/" className="shrink-0">
|
||||
<div className="relative h-8 w-[180px]">
|
||||
<Image src={Logo} alt="Logo" fill className="object-contain" priority />
|
||||
<Image
|
||||
src={Logo}
|
||||
alt="Logo"
|
||||
fill
|
||||
className="object-contain"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
@@ -82,7 +82,11 @@ export default function Header({ locale = "ru" }: HeaderProps) {
|
||||
</Button>
|
||||
|
||||
<div className="flex items-center gap-2 sm:hidden">
|
||||
<Button variant="ghost" size="icon" onClick={() => setIsMobileSearchOpen(true)}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setIsMobileSearchOpen(true)}
|
||||
>
|
||||
<Search className="h-5 w-5" />
|
||||
</Button>
|
||||
<LanguageSelector />
|
||||
@@ -106,13 +110,6 @@ export default function Header({ locale = "ru" }: HeaderProps) {
|
||||
onAuthClick={handleAuthClick}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Link href="/openStore">
|
||||
<Button variant="ghost" size="sm" className="relative flex gap-0.5 h-auto pb-2">
|
||||
<Store className="h-5 w-5 text-gray-600" />
|
||||
<span className="text-xs text-gray-700">{t("common.openStore")}</span>
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -126,10 +123,7 @@ export default function Header({ locale = "ru" }: HeaderProps) {
|
||||
locale={locale}
|
||||
/>
|
||||
|
||||
<AuthDialog
|
||||
isOpen={isLoginOpen}
|
||||
onClose={() => setIsLoginOpen(false)}
|
||||
/>
|
||||
<AuthDialog isOpen={isLoginOpen} onClose={() => setIsLoginOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useMemo } from "react";
|
||||
import type React from "react";
|
||||
import Link from "next/link";
|
||||
import { User, Truck, Heart, ShoppingCart, LogOut } from "lucide-react";
|
||||
import { User, Truck, Heart, Store, LogOut } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
@@ -16,7 +16,12 @@ import { useCart, useFavorites, useOrders } from "@/lib/hooks";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useLogout } from "@/lib/hooks/useAuth";
|
||||
import { CartIcon, FavoriteIcon, OrderIcon, ProfileIcon } from "@/components/icons";
|
||||
import {
|
||||
CartIcon,
|
||||
FavoriteIcon,
|
||||
OrderIcon,
|
||||
ProfileIcon,
|
||||
} from "@/components/icons";
|
||||
|
||||
interface ActionButtonsProps {
|
||||
isAuthenticated: boolean;
|
||||
@@ -38,7 +43,7 @@ export default function ActionButtons({
|
||||
isAuthenticated,
|
||||
onAuthClick,
|
||||
isLoading: authLoading,
|
||||
locale = "ru"
|
||||
locale = "ru",
|
||||
}: ActionButtonsProps) {
|
||||
const t = useTranslations();
|
||||
const { mutate: logout, isPending: isLoggingOut } = useLogout();
|
||||
@@ -69,7 +74,13 @@ export default function ActionButtons({
|
||||
logout();
|
||||
};
|
||||
|
||||
const buttons: ActionButtonData[] = useMemo(() => [
|
||||
const buttons: ActionButtonData[] = useMemo(
|
||||
() => [
|
||||
{
|
||||
icon: <Store />,
|
||||
label: t("common.openStore"),
|
||||
href: "/openStore",
|
||||
},
|
||||
{
|
||||
icon: <OrderIcon />,
|
||||
label: t("common.orders"),
|
||||
@@ -90,8 +101,19 @@ export default function ActionButtons({
|
||||
href: "/cart",
|
||||
badgeCount: cartCount,
|
||||
isLoading: cartLoading,
|
||||
},
|
||||
], [ordersCount, ordersLoading, favoritesCount, favoritesLoading, cartCount, cartLoading, t]);
|
||||
}
|
||||
|
||||
],
|
||||
[
|
||||
ordersCount,
|
||||
ordersLoading,
|
||||
favoritesCount,
|
||||
favoritesLoading,
|
||||
cartCount,
|
||||
cartLoading,
|
||||
t,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="hidden items-center gap-1 md:flex">
|
||||
@@ -101,13 +123,19 @@ export default function ActionButtons({
|
||||
) : isAuthenticated ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="flex-col gap-0.5 h-auto px-2 py-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex-col gap-0.5 h-auto px-2 py-2"
|
||||
>
|
||||
<ProfileIcon />
|
||||
<span className="text-xs text-gray-700">{t("profile")}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => (window.location.href = `/${locale}/me`)}>
|
||||
<DropdownMenuItem
|
||||
onClick={() => (window.location.href = `/${locale}/me`)}
|
||||
>
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
{t("profile")}
|
||||
</DropdownMenuItem>
|
||||
@@ -118,7 +146,12 @@ export default function ActionButtons({
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<Button variant="ghost" size="sm" className="flex-col gap-0.5 h-auto px-2 py-2" onClick={onAuthClick}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex-col gap-0.5 h-auto px-2 py-2"
|
||||
onClick={onAuthClick}
|
||||
>
|
||||
<ProfileIcon />
|
||||
<span className="text-xs text-gray-700">{t("common.login")}</span>
|
||||
</Button>
|
||||
@@ -132,9 +165,21 @@ export default function ActionButtons({
|
||||
);
|
||||
}
|
||||
|
||||
function ActionButton({ icon, label, href, onClick, badgeCount, isLoading }: ActionButtonData) {
|
||||
function ActionButton({
|
||||
icon,
|
||||
label,
|
||||
href,
|
||||
onClick,
|
||||
badgeCount,
|
||||
isLoading,
|
||||
}: ActionButtonData) {
|
||||
const buttonContent = (
|
||||
<Button variant="ghost" size="sm" className="relative flex-col gap-0.5 h-auto px-2 py-2" onClick={onClick}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="relative flex-col gap-0.5 h-auto px-2 py-2"
|
||||
onClick={onClick}
|
||||
>
|
||||
<div className="relative">
|
||||
{icon}
|
||||
{badgeCount !== undefined && badgeCount > 0 && (
|
||||
@@ -142,7 +187,11 @@ function ActionButton({ icon, label, href, onClick, badgeCount, isLoading }: Act
|
||||
variant="destructive"
|
||||
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
|
||||
>
|
||||
{isLoading ? <Skeleton className="h-3 w-3 rounded-full" /> : badgeCount}
|
||||
{isLoading ? (
|
||||
<Skeleton className="h-3 w-3 rounded-full" />
|
||||
) : (
|
||||
badgeCount
|
||||
)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -140,7 +140,7 @@ export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
|
||||
|
||||
<Button
|
||||
onClick={otpSent ? handleLogin : handleSendOtp}
|
||||
className="w-full h-12 rounded-xl font-bold text-base"
|
||||
className="w-full h-12 rounded-xl font-bold text-base bg-[#005bff] hover:bg-[#0041c4]"
|
||||
size="lg"
|
||||
disabled={isLoginLoading || isVerifyLoading}
|
||||
>
|
||||
|
||||
@@ -22,7 +22,7 @@ export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
|
||||
const activeCategory = hoveredCategory !== null ? categoryList[hoveredCategory] : null
|
||||
|
||||
return (
|
||||
<div className="fixed left-0 right-0 top-22 z-40 bg-white border-b shadow-lg max-w-[1504px] mx-auto">
|
||||
<div className="fixed left-0 right-0 top-15 z-40 bg-white border-b shadow-lg max-w-[1504px] mx-auto">
|
||||
<div className="container mx-auto px-4">
|
||||
<div className="flex">
|
||||
<CategoryList
|
||||
|
||||
@@ -1,29 +1,39 @@
|
||||
"use client"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Image from "next/image"
|
||||
import { useLocale } from "next-intl"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import tm from "@/public/tm.png"
|
||||
import ru from "@/public/ru.png"
|
||||
"use client";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import Image from "next/image";
|
||||
import { useLocale } from "next-intl";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import tm from "@/public/tm.png";
|
||||
import ru from "@/public/ru.png";
|
||||
|
||||
interface Language {
|
||||
code: string
|
||||
name: string
|
||||
flag: any
|
||||
code: string;
|
||||
name: string;
|
||||
flag: any;
|
||||
}
|
||||
|
||||
const LANGUAGES: Language[] = [
|
||||
{ code: "ru", name: "Russian", flag: ru },
|
||||
{ code: "tm", name: "Turkmen", flag: tm },
|
||||
]
|
||||
];
|
||||
|
||||
export default function LanguageSelector() {
|
||||
const locale = useLocale()
|
||||
const router = useRouter()
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname(); // Şu anki path'i al
|
||||
|
||||
const handleLanguageChange = (newLocale: string) => {
|
||||
router.push(`/${newLocale}`)
|
||||
}
|
||||
// Mevcut path'i yeni locale ile değiştir
|
||||
// Örnek: /tm/cart -> /ru/cart
|
||||
const currentPath = pathname.replace(`/${locale}`, "");
|
||||
router.push(`/${newLocale}${currentPath}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<Select value={locale} onValueChange={handleLanguageChange}>
|
||||
@@ -43,17 +53,22 @@ export default function LanguageSelector() {
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function FlagIcon({ locale }: { locale: string }) {
|
||||
const language = LANGUAGES.find((lang) => lang.code === locale)
|
||||
const language = LANGUAGES.find((lang) => lang.code === locale);
|
||||
|
||||
if (!language) return null
|
||||
if (!language) return null;
|
||||
|
||||
return (
|
||||
<div className="relative h-5 w-7">
|
||||
<Image src={language.flag || "/placeholder.svg"} alt={language.name} fill className="object-cover rounded" />
|
||||
<Image
|
||||
src={language.flag || "/placeholder.svg"}
|
||||
alt={language.name}
|
||||
fill
|
||||
className="object-cover rounded"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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">
|
||||
|
||||
<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,18 +97,83 @@ 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>) => {
|
||||
// Sync localQuantity with cart
|
||||
useEffect(() => {
|
||||
if (cartItem?.product_quantity) {
|
||||
setLocalQuantity(cartItem.product_quantity);
|
||||
} else {
|
||||
setLocalQuantity(1);
|
||||
}
|
||||
}, [cartItem]);
|
||||
|
||||
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();
|
||||
|
||||
@@ -93,17 +182,73 @@ export default function ProductCard({
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
toast.success(
|
||||
data.wasAdded
|
||||
? "Товар добавлен в избранное"
|
||||
: "Товар удален из избранного"
|
||||
data.wasAdded ? "Added to favorites" : "Removed from favorites"
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Ошибка. Попробуйте снова");
|
||||
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);
|
||||
@@ -63,19 +86,50 @@ 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>;
|
||||
}
|
||||
|
||||
@@ -84,50 +138,48 @@ export default function OrdersPageClient({ locale }: OrdersPageClientProps) {
|
||||
|
||||
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,90 +287,188 @@ 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">
|
||||
<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>
|
||||
<div className="flex justify-between items-center mb-3">
|
||||
<h3 className="text-lg font-semibold">
|
||||
<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 className="flex items-center gap-4">
|
||||
{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}
|
||||
<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>
|
||||
|
||||
<div className="space-y-2 mb-3 max-h-48 overflow-y-auto">
|
||||
{/* 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-start gap-3">
|
||||
<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}
|
||||
src={
|
||||
item.product.images_400x400 || item.product.thumbnail
|
||||
}
|
||||
alt={item.product.name}
|
||||
width={50}
|
||||
height={50}
|
||||
className="rounded object-cover"
|
||||
fill
|
||||
className="object-contain p-1"
|
||||
/>
|
||||
</div>
|
||||
<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
|
||||
<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>
|
||||
|
||||
<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>
|
||||
</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 && (
|
||||
<div className="mt-4">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => onCancel(order)}
|
||||
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">
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
"cash": "Наличные",
|
||||
"card": "Карта",
|
||||
"choose_address": "Выберите адрес",
|
||||
"brand": "Бренд",
|
||||
"brands": "Бренд",
|
||||
"color": "Цвет",
|
||||
"price": "Цена",
|
||||
"price_from": "От",
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"login": "Girmek",
|
||||
"logout": "Çykmak",
|
||||
"profile": "Profil",
|
||||
"openStore": "Dükan açmak",
|
||||
"openStore": "Satyjy bolmak",
|
||||
"phone": "Telefon",
|
||||
"code": "Kod",
|
||||
"send": "Ugrat",
|
||||
@@ -50,7 +50,7 @@
|
||||
"cash": "Nagt",
|
||||
"card": "Kartdan tölemek",
|
||||
"choose_address": "Adres saýla",
|
||||
"brand": "Brend",
|
||||
"brands": "Brendler",
|
||||
"color": "Reňk",
|
||||
"price": "Baha",
|
||||
"price_from": "Pesi",
|
||||
|
||||
Reference in New Issue
Block a user