added some api
This commit is contained in:
@@ -20,12 +20,16 @@ export default function CartPage() {
|
|||||||
|
|
||||||
const t = useTranslations()
|
const t = useTranslations()
|
||||||
|
|
||||||
const { data: cart, isLoading, isError } = useCart()
|
// useCart dönen data yapısı: { message: "success", data: [...] }
|
||||||
|
const { data: cartResponse, isLoading, isError } = useCart()
|
||||||
const { data: regions = [] } = useRegions()
|
const { data: regions = [] } = useRegions()
|
||||||
const { data: addresses = [] } = useAddresses()
|
const { data: addresses = [] } = useAddresses()
|
||||||
const { data: paymentTypes = [] } = usePaymentTypes()
|
const { data: paymentTypes = [] } = usePaymentTypes()
|
||||||
const { mutate: createOrder, isPending: isCreatingOrder } = useCreateOrder()
|
const { mutate: createOrder, isPending: isCreatingOrder } = useCreateOrder()
|
||||||
|
|
||||||
|
// Cart items'ı doğru şekilde al
|
||||||
|
const cartItems = cartResponse?.data || []
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setIsClient(true)
|
setIsClient(true)
|
||||||
}, [])
|
}, [])
|
||||||
@@ -37,12 +41,10 @@ export default function CartPage() {
|
|||||||
|
|
||||||
const handleCompleteOrder = () => {
|
const handleCompleteOrder = () => {
|
||||||
if (!selectedRegion || !selectedAddress || !paymentType) {
|
if (!selectedRegion || !selectedAddress || !paymentType) {
|
||||||
console.warn("[v0] Missing required fields for order")
|
console.warn("Missing required fields for order")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const selectedRegionObj = regions.find((r) => r.code === selectedRegion)
|
|
||||||
|
|
||||||
createOrder(
|
createOrder(
|
||||||
{
|
{
|
||||||
customer_address: selectedAddress,
|
customer_address: selectedAddress,
|
||||||
@@ -53,7 +55,6 @@ export default function CartPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
// Navigate to orders page after successful order creation
|
|
||||||
router.push(`/orders`)
|
router.push(`/orders`)
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -70,7 +71,7 @@ export default function CartPage() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isError || !cart?.items || cart.items.length === 0) {
|
if (isError || cartItems.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="container mx-auto px-4 min-h-[90vh] flex items-center justify-center">
|
<div className="container mx-auto px-4 min-h-[90vh] flex items-center justify-center">
|
||||||
<h2 className="text-3xl md:text-4xl lg:text-5xl text-gray-400 font-semibold">
|
<h2 className="text-3xl md:text-4xl lg:text-5xl text-gray-400 font-semibold">
|
||||||
@@ -101,18 +102,30 @@ export default function CartPage() {
|
|||||||
map: t("address"),
|
map: t("address"),
|
||||||
}
|
}
|
||||||
|
|
||||||
const itemsBySeller = cart.items.reduce(
|
// Group items by seller (from channel)
|
||||||
|
const itemsBySeller = cartItems.reduce(
|
||||||
(acc, item) => {
|
(acc, item) => {
|
||||||
const sellerId = item.seller.id
|
const sellerId = item.product.channel?.[0]?.id || 0
|
||||||
|
const sellerName = item.product.channel?.[0]?.name || "Unknown Seller"
|
||||||
|
|
||||||
if (!acc[sellerId]) {
|
if (!acc[sellerId]) {
|
||||||
acc[sellerId] = { seller: item.seller, items: [] }
|
acc[sellerId] = {
|
||||||
|
seller: { id: sellerId, name: sellerName },
|
||||||
|
items: []
|
||||||
|
}
|
||||||
}
|
}
|
||||||
acc[sellerId].items.push(item)
|
acc[sellerId].items.push(item)
|
||||||
return acc
|
return acc
|
||||||
},
|
},
|
||||||
{} as Record<number, { seller: any; items: typeof cart.items }>,
|
{} as Record<number, { seller: any; items: typeof cartItems }>
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Calculate total
|
||||||
|
const totalAmount = cartItems.reduce((sum, item) => {
|
||||||
|
const price = parseFloat(item.product.price_amount || "0")
|
||||||
|
return sum + (price * item.product_quantity)
|
||||||
|
}, 0)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="container mx-auto px-4 py-8 min-h-screen">
|
<div className="container mx-auto px-4 py-8 min-h-screen">
|
||||||
<h1 className="text-3xl font-bold mb-6">{translations.cart}</h1>
|
<h1 className="text-3xl font-bold mb-6">{translations.cart}</h1>
|
||||||
@@ -126,9 +139,34 @@ export default function CartPage() {
|
|||||||
<div key={sellerId} className="mb-6">
|
<div key={sellerId} className="mb-6">
|
||||||
<p className="text-base font-semibold mb-3">{seller.name}</p>
|
<p className="text-base font-semibold mb-3">{seller.name}</p>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{items.map((item) => (
|
{items.map((item) => {
|
||||||
<CartItemCard key={item.id} item={item} translations={translations} />
|
const price = parseFloat(item.product.price_amount || "0")
|
||||||
))}
|
const quantity = item.product_quantity
|
||||||
|
const total = price * quantity
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CartItemCard
|
||||||
|
key={item.id}
|
||||||
|
item={{
|
||||||
|
...item,
|
||||||
|
quantity: quantity,
|
||||||
|
price: price,
|
||||||
|
total: total,
|
||||||
|
seller: seller,
|
||||||
|
price_formatted: `${item.product.price_amount} TMT`,
|
||||||
|
sub_total_formatted: `${item.product.price_amount} TMT`,
|
||||||
|
total_formatted: `${total.toFixed(2)} TMT`,
|
||||||
|
discount_formatted: "0 TMT",
|
||||||
|
product: {
|
||||||
|
...item.product,
|
||||||
|
image: item.product.media?.[0]?.images_800x800 || item.product.media?.[0]?.thumbnail,
|
||||||
|
images: item.product.media?.map(m => m.images_800x800 || m.thumbnail) || []
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
translations={translations}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
{Object.entries(itemsBySeller).length > 1 && <Separator className="mt-4" />}
|
{Object.entries(itemsBySeller).length > 1 && <Separator className="mt-4" />}
|
||||||
</div>
|
</div>
|
||||||
@@ -141,10 +179,27 @@ export default function CartPage() {
|
|||||||
order={{
|
order={{
|
||||||
id: 1,
|
id: 1,
|
||||||
seller: { id: 1, name: "Store" },
|
seller: { id: 1, name: "Store" },
|
||||||
items: cart.items,
|
items: cartItems.map(item => ({
|
||||||
|
...item,
|
||||||
|
quantity: item.product_quantity,
|
||||||
|
price: parseFloat(item.product.price_amount || "0"),
|
||||||
|
total: parseFloat(item.product.price_amount || "0") * item.product_quantity,
|
||||||
|
seller: {
|
||||||
|
id: item.product.channel?.[0]?.id || 0,
|
||||||
|
name: item.product.channel?.[0]?.name || "Unknown"
|
||||||
|
}
|
||||||
|
})),
|
||||||
billing: {
|
billing: {
|
||||||
body: [{ title: t("goods"), value: `${cart.total_formatted || `${cart.total} TMT`}` }],
|
body: [
|
||||||
footer: { title: t("total"), value: `${cart.total_formatted || `${cart.total} TMT`}` },
|
{
|
||||||
|
title: t("goods"),
|
||||||
|
value: `${totalAmount.toFixed(2)} TMT`
|
||||||
|
}
|
||||||
|
],
|
||||||
|
footer: {
|
||||||
|
title: t("total"),
|
||||||
|
value: `${totalAmount.toFixed(2)} TMT`
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
translations={translations}
|
translations={translations}
|
||||||
|
|||||||
@@ -1,29 +1,147 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
import { useState, useEffect, useRef } from "react"
|
||||||
import Image from "next/image"
|
import Image from "next/image"
|
||||||
import { Minus, Plus, Trash2 } from "lucide-react"
|
import { Minus, Plus, Trash2 } from "lucide-react"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Card } from "@/components/ui/card"
|
import { Card } from "@/components/ui/card"
|
||||||
import { useUpdateCartItemQuantity, useRemoveFromCart } from "@/lib/hooks"
|
import {
|
||||||
|
useUpdateCartItemQuantity,
|
||||||
|
useRemoveFromCart
|
||||||
|
} from "@/lib/hooks"
|
||||||
import type { CartItem, CartTranslations } from "./types"
|
import type { CartItem, CartTranslations } from "./types"
|
||||||
|
|
||||||
interface CartItemCardProps {
|
interface CartItemCardProps {
|
||||||
item: CartItem
|
item: CartItem
|
||||||
translations: CartTranslations
|
translations: CartTranslations
|
||||||
|
onUpdate?: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CartItemCard({ item, translations: t }: CartItemCardProps) {
|
export default function CartItemCard({
|
||||||
const { mutate: updateQuantity, isPending: isUpdating } = useUpdateCartItemQuantity()
|
item,
|
||||||
|
translations: t,
|
||||||
|
onUpdate
|
||||||
|
}: CartItemCardProps) {
|
||||||
|
const [localQuantity, setLocalQuantity] = useState(item.quantity)
|
||||||
|
const [pendingQuantity, setPendingQuantity] = useState(item.quantity)
|
||||||
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
|
const updateTimeoutRef = useRef<NodeJS.Timeout>()
|
||||||
|
|
||||||
|
const { mutate: updateQuantity } = useUpdateCartItemQuantity()
|
||||||
const { mutate: removeItem, isPending: isRemoving } = useRemoveFromCart()
|
const { mutate: removeItem, isPending: isRemoving } = useRemoveFromCart()
|
||||||
|
|
||||||
const handleQuantityChange = (delta: number) => {
|
// Sync local quantity with server quantity
|
||||||
const newQuantity = item.quantity + delta
|
useEffect(() => {
|
||||||
if (newQuantity >= 1) {
|
setLocalQuantity(item.quantity)
|
||||||
updateQuantity({ itemId: item.id, quantity: newQuantity })
|
setPendingQuantity(item.quantity)
|
||||||
|
}, [item.quantity])
|
||||||
|
|
||||||
|
// Debounced update effect
|
||||||
|
useEffect(() => {
|
||||||
|
if (pendingQuantity === item.quantity) {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clear previous timeout
|
||||||
|
if (updateTimeoutRef.current) {
|
||||||
|
clearTimeout(updateTimeoutRef.current)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set new timeout for update
|
||||||
|
updateTimeoutRef.current = setTimeout(() => {
|
||||||
|
setIsLoading(true)
|
||||||
|
|
||||||
|
if (pendingQuantity <= 0) {
|
||||||
|
removeItem(item.id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
onUpdate?.()
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to remove item:", error)
|
||||||
|
// Revert on error
|
||||||
|
setLocalQuantity(item.quantity)
|
||||||
|
setPendingQuantity(item.quantity)
|
||||||
|
},
|
||||||
|
onSettled: () => {
|
||||||
|
setIsLoading(false)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
updateQuantity(
|
||||||
|
{ itemId: item.id, quantity: pendingQuantity },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
onUpdate?.()
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to update quantity:", error)
|
||||||
|
// Revert on error
|
||||||
|
setLocalQuantity(item.quantity)
|
||||||
|
setPendingQuantity(item.quantity)
|
||||||
|
},
|
||||||
|
onSettled: () => {
|
||||||
|
setIsLoading(false)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}, 300)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (updateTimeoutRef.current) {
|
||||||
|
clearTimeout(updateTimeoutRef.current)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [pendingQuantity, item.quantity, item.id, updateQuantity, removeItem, onUpdate])
|
||||||
|
|
||||||
|
const handleQuantityIncrease = (e: React.MouseEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
|
||||||
|
if (isLoading) return
|
||||||
|
|
||||||
|
const newQuantity = localQuantity + 1
|
||||||
|
setLocalQuantity(newQuantity)
|
||||||
|
setPendingQuantity(newQuantity)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleQuantityDecrease = (e: React.MouseEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
|
||||||
|
if (isLoading) return
|
||||||
|
|
||||||
|
const newQuantity = localQuantity - 1
|
||||||
|
|
||||||
|
if (newQuantity < 1) {
|
||||||
|
handleDelete()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
setLocalQuantity(newQuantity)
|
||||||
|
setPendingQuantity(newQuantity)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleDelete = () => {
|
const handleDelete = () => {
|
||||||
removeItem(item.id)
|
setIsLoading(true)
|
||||||
|
removeItem(item.id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
onUpdate?.()
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error("Failed to remove item:", error)
|
||||||
|
},
|
||||||
|
onSettled: () => {
|
||||||
|
setIsLoading(false)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const getImageSrc = () => {
|
||||||
|
if (item.product.image) return item.product.image
|
||||||
|
if (item.product.images && item.product.images.length > 0) {
|
||||||
|
return item.product.images[0]
|
||||||
|
}
|
||||||
|
return "/placeholder.svg"
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -33,7 +151,7 @@ export default function CartItemCard({ item, translations: t }: CartItemCardProp
|
|||||||
<div className="flex gap-4 flex-1">
|
<div className="flex gap-4 flex-1">
|
||||||
<div className="relative w-[88px] h-[117px] rounded-xl border overflow-hidden flex-shrink-0">
|
<div className="relative w-[88px] h-[117px] rounded-xl border overflow-hidden flex-shrink-0">
|
||||||
<Image
|
<Image
|
||||||
src={item.product.image || item.product.images[0] || "/placeholder.svg"}
|
src={getImageSrc()}
|
||||||
alt={item.product.name}
|
alt={item.product.name}
|
||||||
fill
|
fill
|
||||||
className="object-contain"
|
className="object-contain"
|
||||||
@@ -46,7 +164,7 @@ export default function CartItemCard({ item, translations: t }: CartItemCardProp
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={handleDelete}
|
onClick={handleDelete}
|
||||||
disabled={isRemoving}
|
disabled={isRemoving || isLoading}
|
||||||
className="w-fit p-0 h-auto hover:bg-transparent hover:text-red-500"
|
className="w-fit p-0 h-auto hover:bg-transparent hover:text-red-500"
|
||||||
>
|
>
|
||||||
<Trash2 className="h-5 w-5" />
|
<Trash2 className="h-5 w-5" />
|
||||||
@@ -58,10 +176,14 @@ export default function CartItemCard({ item, translations: t }: CartItemCardProp
|
|||||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between">
|
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<p className="text-sm font-semibold">
|
<p className="text-sm font-semibold">
|
||||||
{t.pricePerUnit} <span className="text-primary">{item.price_formatted || `${item.price} TMT`}</span>
|
{t.pricePerUnit}{" "}
|
||||||
|
<span className="text-primary">
|
||||||
|
{item.price_formatted || `${item.price} TMT`}
|
||||||
|
</span>
|
||||||
</p>
|
</p>
|
||||||
<p className="text-sm font-semibold">
|
<p className="text-sm font-semibold">
|
||||||
{t.additionalPrice} {item.sub_total_formatted || `${item.total} TMT`}
|
{t.additionalPrice}{" "}
|
||||||
|
{item.sub_total_formatted || `${item.total} TMT`}
|
||||||
</p>
|
</p>
|
||||||
{item.discount_formatted && item.discount_formatted !== "0 TMT" && (
|
{item.discount_formatted && item.discount_formatted !== "0 TMT" && (
|
||||||
<p className="text-sm font-semibold">
|
<p className="text-sm font-semibold">
|
||||||
@@ -81,18 +203,20 @@ export default function CartItemCard({ item, translations: t }: CartItemCardProp
|
|||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => handleQuantityChange(-1)}
|
onClick={handleQuantityDecrease}
|
||||||
disabled={item.quantity === 1 || isUpdating}
|
disabled={isLoading || isRemoving}
|
||||||
className="rounded-xl bg-blue-50"
|
className="rounded-xl bg-blue-50"
|
||||||
>
|
>
|
||||||
<Minus className="h-4 w-4" />
|
<Minus className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
<div className="w-12 text-center font-semibold">{item.quantity}</div>
|
<div className="w-12 text-center font-semibold">
|
||||||
|
{localQuantity}
|
||||||
|
</div>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => handleQuantityChange(1)}
|
onClick={handleQuantityIncrease}
|
||||||
disabled={isUpdating}
|
disabled={isLoading || isRemoving}
|
||||||
className="rounded-xl bg-blue-50"
|
className="rounded-xl bg-blue-50"
|
||||||
>
|
>
|
||||||
<Plus className="h-4 w-4" />
|
<Plus className="h-4 w-4" />
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import React from "react";
|
"use client"
|
||||||
import { Truck, Warehouse } from "lucide-react";
|
import { Truck, Warehouse } from "lucide-react"
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card"
|
||||||
import { DeliveryType, CartTranslations } from "./types";
|
import { DeliveryType, CartTranslations } from "./types"
|
||||||
|
|
||||||
interface DeliveryTypeSelectorProps {
|
interface DeliveryTypeSelectorProps {
|
||||||
selectedType: DeliveryType;
|
selectedType: DeliveryType
|
||||||
onSelect: (type: DeliveryType) => void;
|
onSelect: (type: DeliveryType) => void
|
||||||
translations: CartTranslations;
|
translations: CartTranslations
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function DeliveryTypeSelector({
|
export default function DeliveryTypeSelector({
|
||||||
@@ -15,13 +15,13 @@ export default function DeliveryTypeSelector({
|
|||||||
translations: t,
|
translations: t,
|
||||||
}: DeliveryTypeSelectorProps) {
|
}: DeliveryTypeSelectorProps) {
|
||||||
const deliveryOptions: {
|
const deliveryOptions: {
|
||||||
type: DeliveryType;
|
type: DeliveryType
|
||||||
label: string;
|
label: string
|
||||||
icon: typeof Truck;
|
icon: typeof Truck
|
||||||
}[] = [
|
}[] = [
|
||||||
{ type: "SELECTED_DELIVERY", label: t.delivery, icon: Truck },
|
{ type: "SELECTED_DELIVERY", label: t.delivery, icon: Truck },
|
||||||
{ type: "PICK_UP", label: t.pickup, icon: Warehouse },
|
{ type: "PICK_UP", label: t.pickup, icon: Warehouse },
|
||||||
];
|
]
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
@@ -30,9 +30,9 @@ export default function DeliveryTypeSelector({
|
|||||||
{deliveryOptions.map(({ type, label, icon: Icon }) => (
|
{deliveryOptions.map(({ type, label, icon: Icon }) => (
|
||||||
<Card
|
<Card
|
||||||
key={type}
|
key={type}
|
||||||
className={`flex-1 cursor-pointer transition-all ${
|
className={`flex-1 cursor-pointer transition-all hover:shadow-md ${
|
||||||
selectedType === type
|
selectedType === type
|
||||||
? "border-2 border-[#005bff]"
|
? "border-2 border-[#005bff] bg-blue-50"
|
||||||
: "border-2 border-gray-200"
|
: "border-2 border-gray-200"
|
||||||
}`}
|
}`}
|
||||||
onClick={() => onSelect(type)}
|
onClick={() => onSelect(type)}
|
||||||
@@ -40,14 +40,18 @@ export default function DeliveryTypeSelector({
|
|||||||
<div className="flex flex-col items-center justify-center p-4 gap-2">
|
<div className="flex flex-col items-center justify-center p-4 gap-2">
|
||||||
<Icon
|
<Icon
|
||||||
className={`h-8 w-8 ${
|
className={`h-8 w-8 ${
|
||||||
selectedType === type ? "text-[#005bff]" : ""
|
selectedType === type ? "text-[#005bff]" : "text-gray-600"
|
||||||
}`}
|
}`}
|
||||||
/>
|
/>
|
||||||
<span className="text-xs">{label}</span>
|
<span className={`text-xs font-medium ${
|
||||||
|
selectedType === type ? "text-[#005bff]" : "text-gray-700"
|
||||||
|
}`}>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
@@ -6,9 +6,22 @@ import { Label } from "@/components/ui/label"
|
|||||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
|
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
import { Textarea } from "@/components/ui/textarea"
|
||||||
import { Separator } from "@/components/ui/separator"
|
import { Separator } from "@/components/ui/separator"
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue
|
||||||
|
} from "@/components/ui/select"
|
||||||
import DeliveryTypeSelector from "./DeliveryTypeSelector"
|
import DeliveryTypeSelector from "./DeliveryTypeSelector"
|
||||||
import type { Order, Region, Address, DeliveryType, CartTranslations, PaymentTypeOption } from "./types"
|
import type {
|
||||||
|
Order,
|
||||||
|
Region,
|
||||||
|
Address,
|
||||||
|
DeliveryType,
|
||||||
|
CartTranslations,
|
||||||
|
PaymentTypeOption
|
||||||
|
} from "./types"
|
||||||
|
|
||||||
interface OrderSummaryProps {
|
interface OrderSummaryProps {
|
||||||
order: Order
|
order: Order
|
||||||
@@ -51,6 +64,7 @@ export default function OrderSummary({
|
|||||||
onCompleteOrder,
|
onCompleteOrder,
|
||||||
isLoading,
|
isLoading,
|
||||||
}: OrderSummaryProps) {
|
}: OrderSummaryProps) {
|
||||||
|
// Filter addresses based on selected region
|
||||||
const filteredAddresses = selectedRegion
|
const filteredAddresses = selectedRegion
|
||||||
? addresses.filter((addr) => {
|
? addresses.filter((addr) => {
|
||||||
const region = regions.find((r) => r.code === selectedRegion)
|
const region = regions.find((r) => r.code === selectedRegion)
|
||||||
@@ -58,11 +72,12 @@ export default function OrderSummary({
|
|||||||
})
|
})
|
||||||
: []
|
: []
|
||||||
|
|
||||||
|
// Validate form completion
|
||||||
const isFormValid = selectedRegion && selectedAddress && paymentType
|
const isFormValid = selectedRegion && selectedAddress && paymentType
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="w-full md:w-[380px] p-6 rounded-xl h-fit sticky top-20">
|
<Card className="w-full md:w-[380px] p-6 rounded-xl h-fit sticky top-20">
|
||||||
{/* Payment Type */}
|
{/* Payment Type Selection */}
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<h3 className="text-lg font-semibold mb-3">{t.paymentType}</h3>
|
<h3 className="text-lg font-semibold mb-3">{t.paymentType}</h3>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
@@ -70,7 +85,9 @@ export default function OrderSummary({
|
|||||||
<Card
|
<Card
|
||||||
key={type.id}
|
key={type.id}
|
||||||
className={`flex-1 cursor-pointer transition-all ${
|
className={`flex-1 cursor-pointer transition-all ${
|
||||||
paymentType?.id === type.id ? "border-2 border-[#005bff]" : "border-2 border-gray-200"
|
paymentType?.id === type.id
|
||||||
|
? "border-2 border-[#005bff]"
|
||||||
|
: "border-2 border-gray-200"
|
||||||
}`}
|
}`}
|
||||||
onClick={() => onPaymentTypeChange(type)}
|
onClick={() => onPaymentTypeChange(type)}
|
||||||
>
|
>
|
||||||
@@ -82,13 +99,23 @@ export default function OrderSummary({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Delivery Type */}
|
{/* Delivery Type Selection */}
|
||||||
<DeliveryTypeSelector selectedType={deliveryType} onSelect={onDeliveryTypeChange} translations={t} />
|
<DeliveryTypeSelector
|
||||||
|
selectedType={deliveryType}
|
||||||
|
onSelect={onDeliveryTypeChange}
|
||||||
|
translations={t}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Region Selection */}
|
{/* Region Selection */}
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<Label className="text-lg font-semibold mb-3 block">{t.selectRegion}</Label>
|
<Label className="text-lg font-semibold mb-3 block">
|
||||||
<RadioGroup value={selectedRegion || ""} onValueChange={onRegionChange} className="flex flex-wrap gap-4">
|
{t.selectRegion}
|
||||||
|
</Label>
|
||||||
|
<RadioGroup
|
||||||
|
value={selectedRegion || ""}
|
||||||
|
onValueChange={onRegionChange}
|
||||||
|
className="flex flex-wrap gap-4"
|
||||||
|
>
|
||||||
{regions.map((region) => (
|
{regions.map((region) => (
|
||||||
<div key={region.id} className="flex items-center space-x-2">
|
<div key={region.id} className="flex items-center space-x-2">
|
||||||
<RadioGroupItem
|
<RadioGroupItem
|
||||||
@@ -96,7 +123,10 @@ export default function OrderSummary({
|
|||||||
id={`region-${region.id}`}
|
id={`region-${region.id}`}
|
||||||
className="border-2 border-gray-400 data-[state=checked]:border-[#005bff] data-[state=checked]:bg-white data-[state=checked]:[&_svg]:fill-[#005bff] data-[state=checked]:[&_svg]:stroke-[#005bff]"
|
className="border-2 border-gray-400 data-[state=checked]:border-[#005bff] data-[state=checked]:bg-white data-[state=checked]:[&_svg]:fill-[#005bff] data-[state=checked]:[&_svg]:stroke-[#005bff]"
|
||||||
/>
|
/>
|
||||||
<Label htmlFor={`region-${region.id}`} className="cursor-pointer">
|
<Label
|
||||||
|
htmlFor={`region-${region.id}`}
|
||||||
|
className="cursor-pointer"
|
||||||
|
>
|
||||||
{region.name}
|
{region.name}
|
||||||
</Label>
|
</Label>
|
||||||
</div>
|
</div>
|
||||||
@@ -104,10 +134,12 @@ export default function OrderSummary({
|
|||||||
</RadioGroup>
|
</RadioGroup>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Address Selection */}
|
{/* Address Selection (only show when region is selected) */}
|
||||||
{filteredAddresses.length > 0 && (
|
{selectedRegion && filteredAddresses.length > 0 && (
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<Label className="text-lg font-semibold mb-3 block">{t.selectAddress}</Label>
|
<Label className="text-lg font-semibold mb-3 block">
|
||||||
|
{t.selectAddress}
|
||||||
|
</Label>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Select value={selectedAddress} onValueChange={onAddressChange}>
|
<Select value={selectedAddress} onValueChange={onAddressChange}>
|
||||||
<SelectTrigger className="rounded-xl">
|
<SelectTrigger className="rounded-xl">
|
||||||
@@ -133,7 +165,7 @@ export default function OrderSummary({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Note */}
|
{/* Note Input */}
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<Label className="text-lg font-semibold mb-3 block">{t.note}</Label>
|
<Label className="text-lg font-semibold mb-3 block">{t.note}</Label>
|
||||||
<Textarea
|
<Textarea
|
||||||
@@ -148,7 +180,10 @@ export default function OrderSummary({
|
|||||||
{/* Billing Summary */}
|
{/* Billing Summary */}
|
||||||
<div className="space-y-2 mb-4">
|
<div className="space-y-2 mb-4">
|
||||||
{order.billing.body.map((item, index) => (
|
{order.billing.body.map((item, index) => (
|
||||||
<div key={index} className="flex justify-between text-base font-medium">
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex justify-between text-base font-medium"
|
||||||
|
>
|
||||||
<span>{item.title}:</span>
|
<span>{item.title}:</span>
|
||||||
<span>{item.value}</span>
|
<span>{item.value}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -157,20 +192,24 @@ export default function OrderSummary({
|
|||||||
|
|
||||||
<Separator className="my-4" />
|
<Separator className="my-4" />
|
||||||
|
|
||||||
{/* Total */}
|
{/* Total Amount */}
|
||||||
<div className="flex justify-between items-center mb-6">
|
<div className="flex justify-between items-center mb-6">
|
||||||
<span className="text-lg font-semibold">{order.billing.footer.title}:</span>
|
<span className="text-lg font-semibold">
|
||||||
<span className="text-lg font-bold text-green-600">{order.billing.footer.value}</span>
|
{order.billing.footer.title}:
|
||||||
|
</span>
|
||||||
|
<span className="text-lg font-bold text-green-600">
|
||||||
|
{order.billing.footer.value}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Complete Order Button */}
|
{/* Complete Order Button */}
|
||||||
<Button
|
<Button
|
||||||
onClick={onCompleteOrder}
|
onClick={onCompleteOrder}
|
||||||
disabled={!isFormValid || isLoading}
|
disabled={!isFormValid || isLoading}
|
||||||
className="w-full rounded-xl bg-[#005bff] hover:bg-[#005bff] cursor-pointer h-12 text-lg font-bold disabled:opacity-50"
|
className="w-full rounded-xl bg-[#005bff] hover:bg-[#004dcc] cursor-pointer h-12 text-lg font-bold disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
size="lg"
|
size="lg"
|
||||||
>
|
>
|
||||||
{isLoading ? t.placeOrder + "..." : t.placeOrder}
|
{isLoading ? `${t.placeOrder}...` : t.placeOrder}
|
||||||
</Button>
|
</Button>
|
||||||
</Card>
|
</Card>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -6,14 +6,18 @@ export interface CartItem {
|
|||||||
product: {
|
product: {
|
||||||
id: number
|
id: number
|
||||||
name: string
|
name: string
|
||||||
|
description?: string
|
||||||
images: (StaticImageData | string)[]
|
images: (StaticImageData | string)[]
|
||||||
image?: StaticImageData | string
|
image?: StaticImageData | string
|
||||||
|
stock?: number
|
||||||
|
price_amount?: string
|
||||||
}
|
}
|
||||||
seller: {
|
seller: {
|
||||||
id: number
|
id: number
|
||||||
name: string
|
name: string
|
||||||
}
|
}
|
||||||
quantity: number
|
quantity: number
|
||||||
|
product_quantity?: number // For compatibility with old API
|
||||||
price: number
|
price: number
|
||||||
total: number
|
total: number
|
||||||
price_formatted?: string
|
price_formatted?: string
|
||||||
@@ -22,6 +26,15 @@ export interface CartItem {
|
|||||||
total_formatted?: string
|
total_formatted?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface Cart {
|
||||||
|
message: string
|
||||||
|
data: CartItem[]
|
||||||
|
errorDetails?: string
|
||||||
|
total?: number
|
||||||
|
total_formatted?: string
|
||||||
|
items?: CartItem[] // Alternative structure
|
||||||
|
}
|
||||||
|
|
||||||
export interface Order {
|
export interface Order {
|
||||||
id: number
|
id: number
|
||||||
seller: {
|
seller: {
|
||||||
@@ -85,3 +98,22 @@ export interface CartTranslations {
|
|||||||
|
|
||||||
export type PaymentType = "CASH" | "CARD"
|
export type PaymentType = "CASH" | "CARD"
|
||||||
export type DeliveryType = "SELECTED_DELIVERY" | "PICK_UP"
|
export type DeliveryType = "SELECTED_DELIVERY" | "PICK_UP"
|
||||||
|
|
||||||
|
// API Response types
|
||||||
|
export interface ApiResponse<T> {
|
||||||
|
message: string
|
||||||
|
data: T
|
||||||
|
errorDetails?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateOrderPayload {
|
||||||
|
customer_name?: string
|
||||||
|
customer_phone?: string
|
||||||
|
customer_address: string
|
||||||
|
shipping_method: string
|
||||||
|
payment_type_id: number
|
||||||
|
delivery_time?: string
|
||||||
|
delivery_at?: string
|
||||||
|
region: string
|
||||||
|
note?: string
|
||||||
|
}
|
||||||
@@ -1,262 +1,577 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react"
|
import { useEffect, useState, useMemo, useCallback } from "react";
|
||||||
import Link from "next/link"
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import Image from "next/image"
|
import { ChevronLeft, SlidersHorizontal, X } from "lucide-react";
|
||||||
import { useRouter, useSearchParams } from "next/navigation"
|
import { Button } from "@/components/ui/button";
|
||||||
import { ChevronLeft, SlidersHorizontal, X } from "lucide-react"
|
import { Checkbox } from "@/components/ui/checkbox";
|
||||||
import { Button } from "@/components/ui/button"
|
import { Input } from "@/components/ui/input";
|
||||||
import { Checkbox } from "@/components/ui/checkbox"
|
import { Label } from "@/components/ui/label";
|
||||||
import { Input } from "@/components/ui/input"
|
import { Slider } from "@/components/ui/slider";
|
||||||
import { Label } from "@/components/ui/label"
|
import {
|
||||||
import { Slider } from "@/components/ui/slider"
|
Sheet,
|
||||||
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
|
SheetContent,
|
||||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
SheetHeader,
|
||||||
import CategoryPageContent from "./CategoryContent"
|
SheetTitle,
|
||||||
import { notFound } from "next/navigation"
|
SheetTrigger,
|
||||||
|
} from "@/components/ui/sheet";
|
||||||
interface FilterItem {
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
key: string
|
import InfiniteScroll from "react-infinite-scroll-component";
|
||||||
value: number
|
import ProductCard from "@/components/ProductCard";
|
||||||
name: string
|
import Loader from "@/components/Loader";
|
||||||
hex?: string
|
import {
|
||||||
image?: string
|
useCategories,
|
||||||
selected?: boolean
|
useAllCategoryProducts,
|
||||||
slug?: string
|
useAllCategoryProductsPaginated,
|
||||||
children?: FilterItem[]
|
useCategoryProducts,
|
||||||
}
|
} from "@/lib/hooks/useCategories";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
interface Filter {
|
import type { Category, Product } from "@/lib/types/api";
|
||||||
uuid: string
|
|
||||||
title: string
|
|
||||||
type: "TREE" | "SELECTABLE" | "VOLUME" | "TAB" | "COLOR"
|
|
||||||
items: FilterItem | FilterItem[]
|
|
||||||
}
|
|
||||||
|
|
||||||
interface CategoryPageClientProps {
|
interface CategoryPageClientProps {
|
||||||
params: { locale: string; slug: string }
|
params: { locale: string; slug: string };
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function CategoryPageClient({ params }: CategoryPageClientProps) {
|
export default function CategoryPageClient({
|
||||||
const { slug, locale } = params
|
params,
|
||||||
const router = useRouter()
|
}: CategoryPageClientProps) {
|
||||||
const searchParams = useSearchParams()
|
const { slug, locale } = params;
|
||||||
const [isOpen, setIsOpen] = useState(false)
|
const router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
|
||||||
|
// Fetch all categories first
|
||||||
|
const { data: categoriesData, isLoading: categoriesLoading } =
|
||||||
|
useCategories();
|
||||||
|
|
||||||
|
// Find category from slug
|
||||||
|
const selectedCategory = useMemo(() => {
|
||||||
|
if (!categoriesData || !slug) return null;
|
||||||
|
|
||||||
|
const findBySlug = (categories: Category[]): Category | null => {
|
||||||
|
for (const category of categories) {
|
||||||
|
if (category.slug === slug) return category;
|
||||||
|
if (category.children) {
|
||||||
|
const found = findBySlug(category.children);
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
return findBySlug(categoriesData);
|
||||||
|
}, [categoriesData, slug]);
|
||||||
|
|
||||||
|
// Track subcategories
|
||||||
|
const [hasSubcategories, setHasSubcategories] = useState(false);
|
||||||
|
const [subcategoriesToShow, setSubcategoriesToShow] = useState<Category[]>(
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Pagination state
|
||||||
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
|
const [hasMore, setHasMore] = useState(true);
|
||||||
|
const [allProducts, setAllProducts] = useState<Product[]>([]);
|
||||||
|
|
||||||
|
// Price sorting state
|
||||||
|
const [priceSort, setPriceSort] = useState<
|
||||||
|
"none" | "lowToHigh" | "highToLow"
|
||||||
|
>("none");
|
||||||
|
|
||||||
// Price filter state
|
// Price filter state
|
||||||
const [priceRange, setPriceRange] = useState<[number, number]>([0, 10000])
|
const [priceRange, setPriceRange] = useState<[number, number]>([0, 10000]);
|
||||||
|
|
||||||
// Selected filters state
|
// Selected filters state
|
||||||
const [selectedFilters, setSelectedFilters] = useState<Record<string, Set<number>>>({
|
const [selectedFilters, setSelectedFilters] = useState<
|
||||||
|
Record<string, Set<number>>
|
||||||
|
>({
|
||||||
brand: new Set(),
|
brand: new Set(),
|
||||||
color: new Set(),
|
color: new Set(),
|
||||||
tag: new Set(),
|
tag: new Set(),
|
||||||
})
|
});
|
||||||
|
|
||||||
|
// Determine if category is a subcategory
|
||||||
|
const isSubCategory = useMemo(() => {
|
||||||
|
if (!categoriesData || !selectedCategory) return false;
|
||||||
|
|
||||||
|
const checkIsSubCategory = (
|
||||||
|
categories: Category[],
|
||||||
|
targetId: number
|
||||||
|
): boolean => {
|
||||||
|
for (const category of categories) {
|
||||||
|
if (category.children) {
|
||||||
|
for (const subCategory of category.children) {
|
||||||
|
if (subCategory.id === targetId) return true;
|
||||||
|
if (subCategory.children) {
|
||||||
|
const foundInNested = checkIsSubCategory([subCategory], targetId);
|
||||||
|
if (foundInNested) return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
return checkIsSubCategory(categoriesData, selectedCategory.id);
|
||||||
|
}, [categoriesData, selectedCategory]);
|
||||||
|
|
||||||
|
// Fetch initial products for subcategories (first page only)
|
||||||
|
const { data: subcategoryProducts = [], isLoading: subcategoryLoading } =
|
||||||
|
useAllCategoryProducts(selectedCategory || undefined, {
|
||||||
|
enabled: !!selectedCategory && isSubCategory && currentPage === 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fetch paginated subcategory products (page 2+)
|
||||||
|
const {
|
||||||
|
data: paginatedSubcategoryData,
|
||||||
|
isLoading: subcategoryPaginatedLoading,
|
||||||
|
} = useAllCategoryProductsPaginated(selectedCategory || undefined, {
|
||||||
|
enabled: !!selectedCategory && isSubCategory && currentPage > 1,
|
||||||
|
page: currentPage,
|
||||||
|
limit: 6,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fetch paginated category products (for non-subcategories)
|
||||||
|
const {
|
||||||
|
data: paginatedCategoryData,
|
||||||
|
isLoading: categoryPaginatedLoading,
|
||||||
|
isFetching: categoryPaginatedFetching,
|
||||||
|
} = useCategoryProducts(selectedCategory?.id?.toString() || "", {
|
||||||
|
enabled: !!selectedCategory && !isSubCategory,
|
||||||
|
page: currentPage,
|
||||||
|
limit: 6,
|
||||||
|
});
|
||||||
|
|
||||||
const t = {
|
const t = {
|
||||||
filter: "Filters",
|
filter: "Filtreler",
|
||||||
from: "From",
|
from: "Min",
|
||||||
to: "To",
|
to: "Max",
|
||||||
reset: "Reset",
|
reset: "Sıfırla",
|
||||||
}
|
total: "Toplam",
|
||||||
|
items: "ürün",
|
||||||
|
subCategories: "Alt Kategoriler",
|
||||||
|
composition: "Sıralama",
|
||||||
|
neverMind: "Varsayılan",
|
||||||
|
From_cheap_to_expensive: "Ucuzdan Pahalıya",
|
||||||
|
From_expensive_to_cheap: "Pahalıdan Ucuza",
|
||||||
|
brands: "Markalar",
|
||||||
|
noResults: "Ürün bulunamadı",
|
||||||
|
};
|
||||||
|
|
||||||
if (!slug) {
|
if (!slug) {
|
||||||
notFound()
|
notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
const filters: Filter[] = [
|
// Helper function to find category by ID
|
||||||
{
|
const findCategoryById = (
|
||||||
uuid: "1",
|
categories: Category[] | undefined,
|
||||||
title: "Category",
|
id: number
|
||||||
type: "TREE",
|
): Category | null => {
|
||||||
items: {
|
if (!categories) return null;
|
||||||
key: "category",
|
|
||||||
value: 1,
|
for (const category of categories) {
|
||||||
name: "All",
|
if (category.id === id) return category;
|
||||||
slug: slug,
|
if (category.children) {
|
||||||
selected: true,
|
const found = findCategoryById(category.children, id);
|
||||||
children: [
|
if (found) return found;
|
||||||
{ key: "category", value: 2, name: "Electronics", slug: "electronics", selected: false },
|
}
|
||||||
{ key: "category", value: 3, name: "Clothing", slug: "clothing", selected: false },
|
}
|
||||||
],
|
return null;
|
||||||
},
|
};
|
||||||
},
|
|
||||||
{
|
// Helper to check if product already exists in list
|
||||||
uuid: "2",
|
const isProductInList = (list: Product[], newProduct: Product) => {
|
||||||
title: "Brand",
|
return list.some((product) => product.id === newProduct.id);
|
||||||
type: "SELECTABLE",
|
};
|
||||||
items: [
|
|
||||||
{ key: "brand", value: 10, name: "Brand A", image: "/brand-a.png", selected: false },
|
// Setup subcategories when category changes
|
||||||
{ key: "brand", value: 11, name: "Brand B", image: "/brand-b.png", selected: false },
|
useEffect(() => {
|
||||||
],
|
if (selectedCategory) {
|
||||||
},
|
// Reset states
|
||||||
{
|
setAllProducts([]);
|
||||||
uuid: "3",
|
setHasMore(true);
|
||||||
title: "Price",
|
setCurrentPage(1);
|
||||||
type: "VOLUME",
|
|
||||||
items: {} as FilterItem,
|
// Set subcategories
|
||||||
},
|
if (selectedCategory.children && selectedCategory.children.length > 0) {
|
||||||
{
|
setHasSubcategories(true);
|
||||||
uuid: "4",
|
setSubcategoriesToShow(selectedCategory.children);
|
||||||
title: "Color",
|
} else {
|
||||||
type: "COLOR",
|
setHasSubcategories(false);
|
||||||
items: [
|
setSubcategoriesToShow([]);
|
||||||
{ key: "color", value: 100, name: "Red", hex: "#FF0000", selected: false },
|
}
|
||||||
{ key: "color", value: 101, name: "Blue", hex: "#0000FF", selected: false },
|
}
|
||||||
],
|
}, [selectedCategory?.id]);
|
||||||
},
|
|
||||||
{
|
// Handle first page products for subcategories
|
||||||
uuid: "5",
|
useEffect(() => {
|
||||||
title: "Tags",
|
if (
|
||||||
type: "TAB",
|
selectedCategory &&
|
||||||
items: [
|
isSubCategory &&
|
||||||
{ key: "tag", value: 200, name: "New Arrival", selected: false },
|
subcategoryProducts.length > 0 &&
|
||||||
{ key: "tag", value: 201, name: "Sale", selected: false },
|
currentPage === 1
|
||||||
],
|
) {
|
||||||
},
|
console.log("Setting subcategory products:", subcategoryProducts.length);
|
||||||
]
|
setAllProducts(subcategoryProducts);
|
||||||
|
setHasMore(true);
|
||||||
|
}
|
||||||
|
}, [selectedCategory, subcategoryProducts, currentPage, isSubCategory]);
|
||||||
|
|
||||||
|
// Handle paginated category products (non-subcategories)
|
||||||
|
useEffect(() => {
|
||||||
|
if (paginatedCategoryData && selectedCategory && !isSubCategory) {
|
||||||
|
console.log("Paginated category data:", paginatedCategoryData);
|
||||||
|
|
||||||
|
if (paginatedCategoryData.data && paginatedCategoryData.data.length > 0) {
|
||||||
|
setAllProducts((prevProducts) => {
|
||||||
|
if (currentPage === 1) {
|
||||||
|
return [...paginatedCategoryData.data];
|
||||||
|
}
|
||||||
|
|
||||||
|
const newProducts = paginatedCategoryData.data.filter(
|
||||||
|
(newProduct: Product) => !isProductInList(prevProducts, newProduct)
|
||||||
|
);
|
||||||
|
|
||||||
|
return [...prevProducts, ...newProducts];
|
||||||
|
});
|
||||||
|
|
||||||
|
setHasMore(!!paginatedCategoryData.pagination?.next_page_url);
|
||||||
|
} else if (currentPage === 1) {
|
||||||
|
setAllProducts([]);
|
||||||
|
setHasMore(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [paginatedCategoryData, currentPage, selectedCategory, isSubCategory]);
|
||||||
|
|
||||||
|
// Handle paginated subcategory products
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
paginatedSubcategoryData &&
|
||||||
|
selectedCategory &&
|
||||||
|
isSubCategory &&
|
||||||
|
currentPage > 1
|
||||||
|
) {
|
||||||
|
console.log("Paginated subcategory data:", paginatedSubcategoryData);
|
||||||
|
|
||||||
|
if (
|
||||||
|
paginatedSubcategoryData.data &&
|
||||||
|
paginatedSubcategoryData.data.length > 0
|
||||||
|
) {
|
||||||
|
setAllProducts((prevProducts) => {
|
||||||
|
const newProducts = paginatedSubcategoryData.data.filter(
|
||||||
|
(newProduct: Product) => !isProductInList(prevProducts, newProduct)
|
||||||
|
);
|
||||||
|
|
||||||
|
return [...prevProducts, ...newProducts];
|
||||||
|
});
|
||||||
|
|
||||||
|
setHasMore(paginatedSubcategoryData.pagination?.hasMorePages || false);
|
||||||
|
} else {
|
||||||
|
setHasMore(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [paginatedSubcategoryData, currentPage, selectedCategory, isSubCategory]);
|
||||||
|
|
||||||
|
const loadMoreData = useCallback(() => {
|
||||||
|
if (!hasMore || categoryPaginatedFetching || subcategoryPaginatedLoading)
|
||||||
|
return;
|
||||||
|
console.log("Loading more, page:", currentPage + 1);
|
||||||
|
setCurrentPage((prevPage) => prevPage + 1);
|
||||||
|
}, [
|
||||||
|
hasMore,
|
||||||
|
categoryPaginatedFetching,
|
||||||
|
subcategoryPaginatedLoading,
|
||||||
|
currentPage,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const isLoading =
|
||||||
|
categoriesLoading ||
|
||||||
|
(subcategoryLoading && currentPage === 1) ||
|
||||||
|
(categoryPaginatedLoading && currentPage === 1);
|
||||||
|
|
||||||
|
const products = useMemo(() => {
|
||||||
|
let productsList = [...allProducts];
|
||||||
|
|
||||||
|
if (priceSort === "lowToHigh") {
|
||||||
|
return [...productsList].sort(
|
||||||
|
(a, b) =>
|
||||||
|
parseFloat(a.price_amount || "0") - parseFloat(b.price_amount || "0")
|
||||||
|
);
|
||||||
|
} else if (priceSort === "highToLow") {
|
||||||
|
return [...productsList].sort(
|
||||||
|
(a, b) =>
|
||||||
|
parseFloat(b.price_amount || "0") - parseFloat(a.price_amount || "0")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return productsList;
|
||||||
|
}, [priceSort, allProducts]);
|
||||||
|
|
||||||
|
const totalItems = useMemo(() => {
|
||||||
|
if (
|
||||||
|
paginatedCategoryData?.pagination &&
|
||||||
|
!isSubCategory &&
|
||||||
|
selectedCategory
|
||||||
|
) {
|
||||||
|
return paginatedCategoryData.pagination.total || products.length || 0;
|
||||||
|
}
|
||||||
|
return products.length || 0;
|
||||||
|
}, [paginatedCategoryData, products, isSubCategory, selectedCategory]);
|
||||||
|
|
||||||
|
const handlePriceSortChange = (
|
||||||
|
sortType: "none" | "lowToHigh" | "highToLow"
|
||||||
|
) => {
|
||||||
|
setPriceSort(sortType);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubCategorySelect = (subCategory: Category) => {
|
||||||
|
setAllProducts([]);
|
||||||
|
setCurrentPage(1);
|
||||||
|
setHasMore(true);
|
||||||
|
setPriceSort("none");
|
||||||
|
|
||||||
|
router.push(`/${locale}/category/${subCategory.slug}`, { scroll: false });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCategoryClick = (category: Category) => {
|
||||||
|
setAllProducts([]);
|
||||||
|
setCurrentPage(1);
|
||||||
|
setHasMore(true);
|
||||||
|
router.push(`/${locale}/category/${category.slug}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderBreadcrumbs = () => {
|
||||||
|
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={() => handleCategoryClick(category)}
|
||||||
|
className="hover:text-primary transition-colors"
|
||||||
|
>
|
||||||
|
{category.name}
|
||||||
|
</button>
|
||||||
|
{index < breadcrumbs.length - 1 && <span>/</span>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const pageTitle = selectedCategory?.name || "Kategori";
|
||||||
|
|
||||||
const handleFilterChange = (key: string, value: number) => {
|
const handleFilterChange = (key: string, value: number) => {
|
||||||
setSelectedFilters((prev) => {
|
setSelectedFilters((prev) => {
|
||||||
const newFilters = { ...prev }
|
const newFilters = { ...prev };
|
||||||
if (!newFilters[key]) {
|
if (!newFilters[key]) {
|
||||||
newFilters[key] = new Set()
|
newFilters[key] = new Set();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (newFilters[key].has(value)) {
|
if (newFilters[key].has(value)) {
|
||||||
newFilters[key].delete(value)
|
newFilters[key].delete(value);
|
||||||
} else {
|
} else {
|
||||||
newFilters[key].add(value)
|
newFilters[key].add(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
return newFilters
|
return newFilters;
|
||||||
})
|
});
|
||||||
|
};
|
||||||
updateURLParams(key, Array.from(selectedFilters[key] || []))
|
|
||||||
}
|
|
||||||
|
|
||||||
const handlePriceChange = (values: number[]) => {
|
const handlePriceChange = (values: number[]) => {
|
||||||
setPriceRange([values[0], values[1]])
|
setPriceRange([values[0], values[1]]);
|
||||||
updateURLParams("price_min", values[0])
|
};
|
||||||
updateURLParams("price_max", values[1])
|
|
||||||
}
|
|
||||||
|
|
||||||
const handlePriceInputChange = (type: "from" | "to", value: string) => {
|
const handlePriceInputChange = (type: "from" | "to", value: string) => {
|
||||||
const numValue = parseInt(value) || 0
|
const numValue = parseInt(value) || 0;
|
||||||
if (type === "from") {
|
if (type === "from") {
|
||||||
setPriceRange([numValue, priceRange[1]])
|
setPriceRange([numValue, priceRange[1]]);
|
||||||
updateURLParams("price_min", numValue)
|
|
||||||
} else {
|
} else {
|
||||||
setPriceRange([priceRange[0], numValue])
|
setPriceRange([priceRange[0], numValue]);
|
||||||
updateURLParams("price_max", numValue)
|
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const updateURLParams = (key: string, value: number | number[]) => {
|
|
||||||
const params = new URLSearchParams(searchParams.toString())
|
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
params.delete(key)
|
|
||||||
value.forEach((v) => params.append(key, v.toString()))
|
|
||||||
} else {
|
|
||||||
params.set(key, value.toString())
|
|
||||||
}
|
|
||||||
|
|
||||||
router.push(`/${locale}/category/${slug}?${params.toString()}`, { scroll: false })
|
|
||||||
}
|
|
||||||
|
|
||||||
const resetFilters = () => {
|
const resetFilters = () => {
|
||||||
setSelectedFilters({
|
setSelectedFilters({
|
||||||
brand: new Set(),
|
brand: new Set(),
|
||||||
color: new Set(),
|
color: new Set(),
|
||||||
tag: new Set(),
|
tag: new Set(),
|
||||||
})
|
});
|
||||||
setPriceRange([0, 10000])
|
setPriceRange([0, 10000]);
|
||||||
router.push(`/${locale}/category/${slug}`)
|
setPriceSort("none");
|
||||||
}
|
};
|
||||||
|
|
||||||
const FiltersContent = () => (
|
const FiltersContent = () => (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{filters.map((filter) => {
|
{hasSubcategories && subcategoriesToShow.length > 0 && (
|
||||||
switch (filter.type) {
|
<div>
|
||||||
case "TREE":
|
<h3 className="text-lg font-semibold mb-3">{t.subCategories}</h3>
|
||||||
return (
|
<div className="space-y-1">
|
||||||
<CategoryFilter
|
{subcategoriesToShow.map((subCategory) => (
|
||||||
key={filter.uuid}
|
<button
|
||||||
data={filter.items as FilterItem}
|
key={subCategory.id}
|
||||||
title={filter.title}
|
onClick={() => handleSubCategorySelect(subCategory)}
|
||||||
locale={locale}
|
className={`w-full text-left py-2 px-2 rounded-lg hover:bg-gray-100 transition-colors ${
|
||||||
/>
|
slug === subCategory.slug
|
||||||
)
|
? "text-primary font-medium bg-gray-50"
|
||||||
case "SELECTABLE":
|
: ""
|
||||||
return (
|
}`}
|
||||||
<BrandFilter
|
>
|
||||||
key={filter.uuid}
|
{subCategory.name}
|
||||||
data={filter.items as FilterItem[]}
|
</button>
|
||||||
title={filter.title}
|
))}
|
||||||
selectedValues={selectedFilters.brand}
|
</div>
|
||||||
onFilterChange={handleFilterChange}
|
</div>
|
||||||
/>
|
)}
|
||||||
)
|
|
||||||
case "VOLUME":
|
<div>
|
||||||
return (
|
<h3 className="text-lg font-semibold mb-3">{t.composition}</h3>
|
||||||
<PriceFilter
|
<div className="space-y-2">
|
||||||
key={filter.uuid}
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
title={filter.title}
|
<input
|
||||||
priceRange={priceRange}
|
type="radio"
|
||||||
onPriceChange={handlePriceChange}
|
name="sort"
|
||||||
onInputChange={handlePriceInputChange}
|
checked={priceSort === "none"}
|
||||||
translations={{ from: t.from, to: t.to }}
|
onChange={() => handlePriceSortChange("none")}
|
||||||
/>
|
className="w-4 h-4"
|
||||||
)
|
/>
|
||||||
case "COLOR":
|
<span>{t.neverMind}</span>
|
||||||
return (
|
</label>
|
||||||
<ColorFilter
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
key={filter.uuid}
|
<input
|
||||||
data={filter.items as FilterItem[]}
|
type="radio"
|
||||||
title={filter.title}
|
name="sort"
|
||||||
selectedValues={selectedFilters.color}
|
checked={priceSort === "lowToHigh"}
|
||||||
onFilterChange={handleFilterChange}
|
onChange={() => handlePriceSortChange("lowToHigh")}
|
||||||
/>
|
className="w-4 h-4"
|
||||||
)
|
/>
|
||||||
case "TAB":
|
<span>{t.From_cheap_to_expensive}</span>
|
||||||
return (
|
</label>
|
||||||
<TagFilter
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
key={filter.uuid}
|
<input
|
||||||
data={filter.items as FilterItem[]}
|
type="radio"
|
||||||
title={filter.title}
|
name="sort"
|
||||||
selectedValues={selectedFilters.tag}
|
checked={priceSort === "highToLow"}
|
||||||
onFilterChange={handleFilterChange}
|
onChange={() => handlePriceSortChange("highToLow")}
|
||||||
/>
|
className="w-4 h-4"
|
||||||
)
|
/>
|
||||||
default:
|
<span>{t.From_expensive_to_cheap}</span>
|
||||||
return null
|
</label>
|
||||||
}
|
</div>
|
||||||
})}
|
</div>
|
||||||
<Button variant="outline" className="w-full rounded-xl bg-transparent" onClick={resetFilters}>
|
|
||||||
|
<PriceFilter
|
||||||
|
title="Fiyat"
|
||||||
|
priceRange={priceRange}
|
||||||
|
onPriceChange={handlePriceChange}
|
||||||
|
onInputChange={handlePriceInputChange}
|
||||||
|
translations={{ from: t.from, to: t.to }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full rounded-xl bg-transparent"
|
||||||
|
onClick={resetFilters}
|
||||||
|
>
|
||||||
{t.reset}
|
{t.reset}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
|
|
||||||
|
if (isLoading) return <div>Loading...</div>;
|
||||||
|
|
||||||
|
if (!selectedCategory && !categoriesLoading) {
|
||||||
|
return <div className="text-center py-8">Kategori bulunamadı</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
"Current products:",
|
||||||
|
products.length,
|
||||||
|
"Has more:",
|
||||||
|
hasMore,
|
||||||
|
"Page:",
|
||||||
|
currentPage
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
{/* Desktop Filters - LEFT SIDE */}
|
{selectedCategory && renderBreadcrumbs()}
|
||||||
<div className="hidden sm:block w-[280px] flex-shrink-0 border-r pr-4">
|
<h2 className="text-3xl font-bold">{pageTitle}</h2>
|
||||||
<ScrollArea className="h-[calc(100vh-120px)]">
|
<p className="text-gray-600">
|
||||||
<FiltersContent />
|
{t.total}: {totalItems} {t.items}
|
||||||
</ScrollArea>
|
</p>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Content - RIGHT SIDE */}
|
<div className="flex gap-4">
|
||||||
<div className="flex-1">
|
{/* Desktop Filters - LEFT SIDE */}
|
||||||
<CategoryPageContent slug={slug} filters={selectedFilters} priceRange={priceRange} />
|
<div className="hidden sm:block w-[280px] flex-shrink-0 border-r pr-4">
|
||||||
|
<ScrollArea className="h-[calc(100vh-200px)]">
|
||||||
|
<FiltersContent />
|
||||||
|
</ScrollArea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content - RIGHT SIDE */}
|
||||||
|
<div className="flex-1">
|
||||||
|
{products.length > 0 ? (
|
||||||
|
<InfiniteScroll
|
||||||
|
dataLength={products.length}
|
||||||
|
next={loadMoreData}
|
||||||
|
hasMore={hasMore}
|
||||||
|
scrollThreshold={0.8}
|
||||||
|
style={{ overflow: "visible" }}
|
||||||
|
loader={
|
||||||
|
<div className="flex justify-center py-4">
|
||||||
|
<div>Loading...</div>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
|
{products.map((product) => (
|
||||||
|
<ProductCard
|
||||||
|
key={product.id}
|
||||||
|
id={product.id}
|
||||||
|
name={product.name}
|
||||||
|
price={
|
||||||
|
product.price_amount
|
||||||
|
? parseFloat(product.price_amount)
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
struct_price_text={`${product.price_amount} TMT`}
|
||||||
|
images={[product.media?.[0]?.images_400x400]}
|
||||||
|
is_favorite={false}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</InfiniteScroll>
|
||||||
|
) : (
|
||||||
|
<div className="text-center py-8 text-gray-500">{t.noResults}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Mobile Filter Sheet */}
|
{/* Mobile Filter Sheet */}
|
||||||
<Sheet open={isOpen} onOpenChange={setIsOpen}>
|
<Sheet open={isOpen} onOpenChange={setIsOpen}>
|
||||||
<SheetTrigger asChild>
|
<SheetTrigger asChild>
|
||||||
<Button className="sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg" size="lg">
|
<Button
|
||||||
|
className="sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
{t.filter}
|
{t.filter}
|
||||||
<SlidersHorizontal className="h-5 w-5" />
|
<SlidersHorizontal className="h-5 w-5" />
|
||||||
</Button>
|
</Button>
|
||||||
@@ -269,7 +584,7 @@ export default function CategoryPageClient({ params }: CategoryPageClientProps)
|
|||||||
className="absolute top-4 right-4 rounded-md ring-offset-background transition-opacity hover:opacity-100"
|
className="absolute top-4 right-4 rounded-md ring-offset-background transition-opacity hover:opacity-100"
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Kapat</span>
|
||||||
</button>
|
</button>
|
||||||
</SheetHeader>
|
</SheetHeader>
|
||||||
<ScrollArea className="h-[calc(100vh-80px)] p-4">
|
<ScrollArea className="h-[calc(100vh-80px)] p-4">
|
||||||
@@ -278,96 +593,7 @@ export default function CategoryPageClient({ params }: CategoryPageClientProps)
|
|||||||
</SheetContent>
|
</SheetContent>
|
||||||
</Sheet>
|
</Sheet>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
|
||||||
|
|
||||||
function CategoryFilter({
|
|
||||||
data,
|
|
||||||
title,
|
|
||||||
locale
|
|
||||||
}: {
|
|
||||||
data: FilterItem
|
|
||||||
title: string
|
|
||||||
locale: string
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold mb-3">{title}</h3>
|
|
||||||
<div className="space-y-1">
|
|
||||||
<Link
|
|
||||||
href={`/${locale}/category/${data.slug}?category_id=${data.value}`}
|
|
||||||
className={`flex items-center gap-2 py-2 px-2 rounded-lg hover:bg-gray-100 transition-colors ${
|
|
||||||
data.selected ? "text-primary font-medium" : ""
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<ChevronLeft className="h-4 w-4" />
|
|
||||||
{data.name}
|
|
||||||
</Link>
|
|
||||||
{data.children && data.children.length > 0 && (
|
|
||||||
<div className="ml-6 space-y-1">
|
|
||||||
{data.children.map((child) => (
|
|
||||||
<Link
|
|
||||||
key={child.value}
|
|
||||||
href={`/${locale}/category/${child.slug}?category_id=${child.value}`}
|
|
||||||
className={`block py-2 px-2 rounded-lg hover:bg-gray-100 transition-colors ${
|
|
||||||
child.selected ? "text-primary font-medium" : ""
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{child.name}
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function BrandFilter({
|
|
||||||
data,
|
|
||||||
title,
|
|
||||||
selectedValues,
|
|
||||||
onFilterChange,
|
|
||||||
}: {
|
|
||||||
data: FilterItem[]
|
|
||||||
title: string
|
|
||||||
selectedValues: Set<number>
|
|
||||||
onFilterChange: (key: string, value: number) => void
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold mb-3">{title}</h3>
|
|
||||||
<ScrollArea className="max-h-[410px]">
|
|
||||||
<div className="space-y-1">
|
|
||||||
{data.map((item) => {
|
|
||||||
const isSelected = selectedValues.has(item.value)
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={item.value}
|
|
||||||
onClick={() => onFilterChange(item.key, item.value)}
|
|
||||||
className={`w-full flex items-center gap-3 py-2 px-2 rounded-lg hover:bg-gray-100 transition-colors group ${
|
|
||||||
isSelected ? "text-primary" : ""
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{item.image && (
|
|
||||||
<div
|
|
||||||
className={`flex items-center justify-center w-[50px] h-[50px] bg-gray-50 rounded-lg border-2 transition-colors ${
|
|
||||||
isSelected ? "border-primary" : "border-transparent group-hover:border-primary"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<div className="relative w-8 h-8">
|
|
||||||
<Image src={item.image || "/placeholder.svg"} alt={item.name} fill className="object-contain" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<span className="text-left">{item.name}</span>
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</ScrollArea>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function PriceFilter({
|
function PriceFilter({
|
||||||
@@ -377,11 +603,11 @@ function PriceFilter({
|
|||||||
onInputChange,
|
onInputChange,
|
||||||
translations,
|
translations,
|
||||||
}: {
|
}: {
|
||||||
title: string
|
title: string;
|
||||||
priceRange: [number, number]
|
priceRange: [number, number];
|
||||||
onPriceChange: (values: number[]) => void
|
onPriceChange: (values: number[]) => void;
|
||||||
onInputChange: (type: "from" | "to", value: string) => void
|
onInputChange: (type: "from" | "to", value: string) => void;
|
||||||
translations: { from: string; to: string }
|
translations: { from: string; to: string };
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -413,78 +639,15 @@ function PriceFilter({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Slider min={0} max={99999} step={100} value={priceRange} onValueChange={onPriceChange} className="mt-2" />
|
<Slider
|
||||||
|
min={0}
|
||||||
|
max={99999}
|
||||||
|
step={100}
|
||||||
|
value={priceRange}
|
||||||
|
onValueChange={onPriceChange}
|
||||||
|
className="mt-2"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
|
||||||
|
|
||||||
function TagFilter({
|
|
||||||
data,
|
|
||||||
title,
|
|
||||||
selectedValues,
|
|
||||||
onFilterChange,
|
|
||||||
}: {
|
|
||||||
data: FilterItem[]
|
|
||||||
title: string
|
|
||||||
selectedValues: Set<number>
|
|
||||||
onFilterChange: (key: string, value: number) => void
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold mb-3">{title}</h3>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{data.map((item) => {
|
|
||||||
const isSelected = selectedValues.has(item.value)
|
|
||||||
return (
|
|
||||||
<div key={item.value} className="flex items-center space-x-2">
|
|
||||||
<Checkbox
|
|
||||||
id={`tag-${item.value}`}
|
|
||||||
checked={isSelected}
|
|
||||||
onCheckedChange={() => onFilterChange(item.key, item.value)}
|
|
||||||
/>
|
|
||||||
<Label htmlFor={`tag-${item.value}`} className="text-sm font-normal cursor-pointer">
|
|
||||||
{item.name}
|
|
||||||
</Label>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function ColorFilter({
|
|
||||||
data,
|
|
||||||
title,
|
|
||||||
selectedValues,
|
|
||||||
onFilterChange,
|
|
||||||
}: {
|
|
||||||
data: FilterItem[]
|
|
||||||
title: string
|
|
||||||
selectedValues: Set<number>
|
|
||||||
onFilterChange: (key: string, value: number) => void
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-semibold mb-3">{title}</h3>
|
|
||||||
<div className="grid grid-cols-5 gap-2">
|
|
||||||
{data.map((item) => {
|
|
||||||
const isSelected = selectedValues.has(item.value)
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={item.value}
|
|
||||||
onClick={() => onFilterChange(item.key, item.value)}
|
|
||||||
className={`w-[36px] h-[36px] rounded-lg border-2 p-1 transition-all hover:scale-110 ${
|
|
||||||
isSelected ? "border-primary shadow-md" : "border-gray-200"
|
|
||||||
}`}
|
|
||||||
title={item.name}
|
|
||||||
>
|
|
||||||
<div className="w-full h-full rounded-md border-2 border-gray-200" style={{ backgroundColor: item.hex }} />
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
@@ -1,27 +1,74 @@
|
|||||||
"use client"
|
"use client";
|
||||||
import { useFavorites, useAddToCart, useRemoveFromFavorites } from "@/lib/hooks"
|
import {
|
||||||
import { useState } from "react"
|
useFavorites,
|
||||||
import Image from "next/image"
|
useAddToCart,
|
||||||
import Link from "next/link"
|
useRemoveFromFavorites,
|
||||||
import { Heart, ShoppingCart } from "lucide-react"
|
} from "@/lib/hooks";
|
||||||
import { Button } from "@/components/ui/button"
|
import { useState } from "react";
|
||||||
import { Card } from "@/components/ui/card"
|
import Image from "next/image";
|
||||||
import { Badge } from "@/components/ui/badge"
|
import Link from "next/link";
|
||||||
import { Skeleton } from "@/components/ui/skeleton"
|
import { Heart, ShoppingCart } from "lucide-react";
|
||||||
import type { Product } from "@/lib/types/api"
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { useToast } from "@/hooks/use-toast";
|
||||||
|
import type { Favorite } from "@/lib/types/api";
|
||||||
|
|
||||||
export default function FavoritesPage() {
|
export default function FavoritesPage() {
|
||||||
const [isHovered, setIsHovered] = useState<number | null>(null)
|
const [isHovered, setIsHovered] = useState<number | null>(null);
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
const { data: favorites, isLoading, isError } = useFavorites()
|
const { data: favorites, isLoading, isError } = useFavorites();
|
||||||
const { mutate: removeFromFavorites } = useRemoveFromFavorites()
|
const { mutate: removeFromFavorites, isPending: isRemoving } =
|
||||||
const { mutate: addToCart } = useAddToCart()
|
useRemoveFromFavorites();
|
||||||
|
const { mutate: addToCart, isPending: isAddingToCart } = useAddToCart();
|
||||||
|
|
||||||
const t = {
|
const t = {
|
||||||
favorites: "Избранные",
|
favorites: "Избранные",
|
||||||
addToCart: "В корзину",
|
addToCart: "В корзину",
|
||||||
emptyFavorites: "У вас пока нет избранных товаров",
|
emptyFavorites: "У вас пока нет избранных товаров",
|
||||||
}
|
removedFromFavorites: "Товар удален из избранного",
|
||||||
|
addedToCart: "Товар добавлен в корзину",
|
||||||
|
error: "Произошла ошибка",
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveFromFavorites = (productId: number) => {
|
||||||
|
removeFromFavorites(productId, {
|
||||||
|
onSuccess: () => {
|
||||||
|
toast({
|
||||||
|
title: t.removedFromFavorites,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast({
|
||||||
|
title: t.error,
|
||||||
|
description: error.message,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddToCart = (productId: number) => {
|
||||||
|
addToCart(
|
||||||
|
{ productId },
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
toast({
|
||||||
|
title: t.addedToCart,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast({
|
||||||
|
title: t.error,
|
||||||
|
description: error.message,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
@@ -33,7 +80,7 @@ export default function FavoritesPage() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isError || !favorites || favorites.length === 0) {
|
if (isError || !favorites || favorites.length === 0) {
|
||||||
@@ -44,38 +91,58 @@ export default function FavoritesPage() {
|
|||||||
<p className="text-2xl text-gray-400">{t.emptyFavorites}</p>
|
<p className="text-2xl text-gray-400">{t.emptyFavorites}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="container mx-auto px-4 py-8 min-h-screen">
|
<div className="container mx-auto px-4 py-8 min-h-screen">
|
||||||
<h1 className="text-3xl font-bold mb-6">{t.favorites}</h1>
|
<h1 className="text-3xl font-bold mb-6">{t.favorites}</h1>
|
||||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
|
||||||
{favorites.map((favorite) => (
|
{favorites.map((favorite: Favorite) => (
|
||||||
<ProductCard
|
<ProductCard
|
||||||
key={favorite.id}
|
key={favorite.created_at}
|
||||||
productId={favorite.product_id}
|
productId={favorite.product.id}
|
||||||
product={favorite.product}
|
product={favorite.product}
|
||||||
onRemove={() => removeFromFavorites(favorite.product_id)}
|
onRemove={() => handleRemoveFromFavorites(favorite.product.id)}
|
||||||
onAddToCart={() => addToCart({ productId: favorite.product_id })}
|
onAddToCart={() => handleAddToCart(favorite.product.id)}
|
||||||
onHover={setIsHovered}
|
onHover={setIsHovered}
|
||||||
isHovered={isHovered === favorite.product_id}
|
isHovered={isHovered === favorite.product.id}
|
||||||
|
isRemoving={isRemoving}
|
||||||
|
isAddingToCart={isAddingToCart}
|
||||||
translations={t}
|
translations={t}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ProductCardProps {
|
interface ProductCardProps {
|
||||||
productId: number
|
productId: number;
|
||||||
product?: Product
|
product: Product;
|
||||||
onRemove: () => void
|
onRemove: () => void;
|
||||||
onAddToCart: () => void
|
onAddToCart: () => void;
|
||||||
onHover: (id: number | null) => void
|
onHover: (id: number | null) => void;
|
||||||
isHovered: boolean
|
isHovered: boolean;
|
||||||
translations: { addToCart: string }
|
isRemoving: boolean;
|
||||||
|
isAddingToCart: boolean;
|
||||||
|
translations: { addToCart: string };
|
||||||
}
|
}
|
||||||
|
|
||||||
function ProductCard({
|
function ProductCard({
|
||||||
@@ -85,70 +152,91 @@ function ProductCard({
|
|||||||
onAddToCart,
|
onAddToCart,
|
||||||
onHover,
|
onHover,
|
||||||
isHovered,
|
isHovered,
|
||||||
|
isRemoving,
|
||||||
|
isAddingToCart,
|
||||||
translations,
|
translations,
|
||||||
}: ProductCardProps) {
|
}: ProductCardProps) {
|
||||||
if (!product) return null
|
if (!product) return null;
|
||||||
|
|
||||||
|
// Получаем первое изображение из media
|
||||||
|
const imageUrl =
|
||||||
|
product.media?.[0]?.images_800x800 ||
|
||||||
|
product.media?.[0]?.thumbnail ||
|
||||||
|
"/placeholder.svg";
|
||||||
|
|
||||||
|
// Форматируем цену
|
||||||
|
const price = product.old_price_amount
|
||||||
|
? `${parseFloat(product.price_amount).toFixed(2)} TMT`
|
||||||
|
: `${parseFloat(product.price_amount).toFixed(2)} TMT`;
|
||||||
|
|
||||||
|
const oldPrice = product.old_price_amount
|
||||||
|
? `${parseFloat(product.old_price_amount).toFixed(2)} TMT`
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card
|
<Card
|
||||||
className="group overflow-hidden rounded-xl transition-shadow hover:shadow-lg relative"
|
className="group overflow-hidden rounded-xl transition-shadow hover:shadow-lg relative border-none"
|
||||||
onMouseEnter={() => onHover(productId)}
|
onMouseEnter={() => onHover(productId)}
|
||||||
onMouseLeave={() => onHover(null)}
|
onMouseLeave={() => onHover(null)}
|
||||||
>
|
>
|
||||||
<Link href={`/product/${product.slug || productId}`} className="block">
|
<Link href={`/product/${product.slug || productId}`} className="block">
|
||||||
<div className="relative aspect-square bg-gray-50">
|
<div className="relative aspect-square bg-gray-50">
|
||||||
{/* Labels */}
|
|
||||||
{product.labels && product.labels.length > 0 && (
|
|
||||||
<div className="absolute top-2 left-2 z-10 flex flex-col gap-1">
|
|
||||||
{product.labels.map((label) => (
|
|
||||||
<Badge
|
|
||||||
key={label.text}
|
|
||||||
className="text-white text-[10px] font-bold uppercase px-2 py-0.5"
|
|
||||||
style={{ backgroundColor: label.bg_color }}
|
|
||||||
>
|
|
||||||
{label.text}
|
|
||||||
</Badge>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Favorite Button */}
|
{/* Favorite Button */}
|
||||||
<button
|
<button
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
e.stopPropagation()
|
e.stopPropagation();
|
||||||
onRemove()
|
onRemove();
|
||||||
}}
|
}}
|
||||||
className="absolute top-2 right-2 z-10 bg-white rounded-full p-2 shadow-md hover:scale-110 transition-transform"
|
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" />
|
<Heart className="h-5 w-5 fill-red-500 text-red-500" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{/* Product Image */}
|
||||||
<Image
|
<Image
|
||||||
src={product.image || product.images?.[0] || "/placeholder.svg"}
|
src={imageUrl}
|
||||||
alt={product.name}
|
alt={product.name}
|
||||||
fill
|
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"
|
className="object-contain p-4 group-hover:scale-105 transition-transform"
|
||||||
|
priority={false}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Out of Stock Badge */}
|
||||||
|
{product.stock === 0 && (
|
||||||
|
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
|
||||||
|
<Badge variant="secondary" className="text-sm">
|
||||||
|
Нет в наличии
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Product Info */}
|
{/* Product Info */}
|
||||||
<div className="p-3">
|
<div className="p-3">
|
||||||
<h3 className="font-medium text-sm line-clamp-2 mb-2 min-h-[40px]">{product.name}</h3>
|
<h3 className="font-medium text-sm line-clamp-2 mb-2 min-h-[40px]">
|
||||||
|
{product.name}
|
||||||
|
</h3>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<p className="text-lg font-bold">{product.struct_price_text || `$${product.price}`}</p>
|
{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>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
{/* Add to Cart Button */}
|
{/* Add to Cart Button - показывается при hover */}
|
||||||
{isHovered && (
|
{isHovered && product.stock > 0 && (
|
||||||
<div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-white to-transparent">
|
<div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-white via-white to-transparent">
|
||||||
<Button
|
<Button
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.preventDefault()
|
e.preventDefault();
|
||||||
onAddToCart()
|
onAddToCart();
|
||||||
}}
|
}}
|
||||||
|
disabled={isAddingToCart}
|
||||||
className="w-full rounded-xl gap-2"
|
className="w-full rounded-xl gap-2"
|
||||||
size="sm"
|
size="sm"
|
||||||
>
|
>
|
||||||
@@ -158,5 +246,5 @@ function ProductCard({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog"
|
} from "@/components/ui/dialog"
|
||||||
|
import { useToast } from "@/hooks/use-toast"
|
||||||
import { useOrders, useCancelOrder } from "@/lib/hooks"
|
import { useOrders, useCancelOrder } from "@/lib/hooks"
|
||||||
import type { Order } from "@/lib/types/api"
|
import type { Order } from "@/lib/types/api"
|
||||||
|
|
||||||
@@ -25,51 +26,101 @@ interface OrdersPageProps {
|
|||||||
export default function OrdersPageClient({ locale }: OrdersPageProps) {
|
export default function OrdersPageClient({ locale }: OrdersPageProps) {
|
||||||
const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false)
|
const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false)
|
||||||
const [orderToCancel, setOrderToCancel] = useState<Order | null>(null)
|
const [orderToCancel, setOrderToCancel] = useState<Order | null>(null)
|
||||||
|
const { toast } = useToast()
|
||||||
|
|
||||||
const { data: orders, isLoading, isError } = useOrders()
|
const { data: orders, isLoading, isError, error } = useOrders()
|
||||||
const { mutate: cancelOrder, isPending: isCancellingOrder } = useCancelOrder()
|
const { mutate: cancelOrder, isPending: isCancellingOrder } = useCancelOrder()
|
||||||
|
|
||||||
|
const t = {
|
||||||
|
orders: "Заказы",
|
||||||
|
myOrders: "Мои заказы",
|
||||||
|
active: "Активные",
|
||||||
|
completed: "Завершенные",
|
||||||
|
activeOrders: "Активные заказы",
|
||||||
|
completedOrders: "Завершенные заказы",
|
||||||
|
cancelOrder: "Отменить заказ",
|
||||||
|
keepOrder: "Оставить заказ",
|
||||||
|
areYouSure: "Вы уверены?",
|
||||||
|
cancelConfirmation: "Вы уверены, что хотите отменить этот заказ? Это действие нельзя отменить.",
|
||||||
|
cancelling: "Отмена...",
|
||||||
|
orderNumber: "Заказ №",
|
||||||
|
ordered: "Заказано",
|
||||||
|
completed: "Завершено",
|
||||||
|
estimatedDelivery: "Ожид. доставка",
|
||||||
|
quantity: "Кол-во",
|
||||||
|
total: "Итого",
|
||||||
|
noOrders: "У вас пока нет заказов",
|
||||||
|
noActiveOrders: "У вас нет активных заказов",
|
||||||
|
noCompletedOrders: "У вас нет завершенных заказов",
|
||||||
|
loadError: "Не удалось загрузить заказы. Пожалуйста, попробуйте позже.",
|
||||||
|
orderCancelled: "Заказ отменен",
|
||||||
|
orderCancelledDescription: "Ваш заказ был успешно отменен",
|
||||||
|
error: "Ошибка",
|
||||||
|
cannotCancelShipped: "Нельзя отменить заказ, который уже отправлен или доставлен",
|
||||||
|
}
|
||||||
|
|
||||||
const handleCancelOrder = (order: Order) => {
|
const handleCancelOrder = (order: Order) => {
|
||||||
|
// Check if order can be cancelled
|
||||||
|
if (order.status === "shipped" || order.status === "delivered") {
|
||||||
|
toast({
|
||||||
|
title: t.error,
|
||||||
|
description: t.cannotCancelShipped,
|
||||||
|
variant: "destructive",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
setOrderToCancel(order)
|
setOrderToCancel(order)
|
||||||
setIsCancelDialogOpen(true)
|
setIsCancelDialogOpen(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
const confirmCancelOrder = () => {
|
const confirmCancelOrder = () => {
|
||||||
if (orderToCancel) {
|
if (!orderToCancel) return
|
||||||
cancelOrder(orderToCancel.id, {
|
|
||||||
onSuccess: () => {
|
cancelOrder(orderToCancel.id, {
|
||||||
setIsCancelDialogOpen(false)
|
onSuccess: () => {
|
||||||
setOrderToCancel(null)
|
toast({
|
||||||
},
|
title: t.orderCancelled,
|
||||||
})
|
description: t.orderCancelledDescription,
|
||||||
}
|
})
|
||||||
|
setIsCancelDialogOpen(false)
|
||||||
|
setOrderToCancel(null)
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
toast({
|
||||||
|
title: t.error,
|
||||||
|
description: error.message || "Не удалось отменить заказ",
|
||||||
|
variant: "destructive",
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const getStatusBadge = (status: Order["status"]) => {
|
const getStatusBadge = (status: Order["status"]) => {
|
||||||
switch (status) {
|
const statusMap: Record<string, { label: string; variant: string; className?: string }> = {
|
||||||
case "pending":
|
pending: { label: "Ожидание", variant: "outline" },
|
||||||
return <Badge variant="outline">{status}</Badge>
|
processing: { label: "Обработка", variant: "secondary" },
|
||||||
case "processing":
|
shipped: { label: "Отправлен", variant: "default" },
|
||||||
return <Badge variant="secondary">{status}</Badge>
|
delivered: { label: "Доставлен", variant: "default", className: "bg-green-600" },
|
||||||
case "shipped":
|
cancelled: { label: "Отменен", variant: "destructive" },
|
||||||
return <Badge variant="default">{status}</Badge>
|
|
||||||
case "delivered":
|
|
||||||
return <Badge className="bg-green-600">{status}</Badge>
|
|
||||||
case "cancelled":
|
|
||||||
return <Badge variant="destructive">{status}</Badge>
|
|
||||||
default:
|
|
||||||
return <Badge>{status}</Badge>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const statusInfo = statusMap[status] || { label: status, variant: "default" }
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Badge variant={statusInfo.variant as any} className={statusInfo.className}>
|
||||||
|
{statusInfo.label}
|
||||||
|
</Badge>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const activeOrders = orders?.filter((o) => ["pending", "processing", "shipped"].includes(o.status)) || []
|
const activeOrders = orders?.filter((o) => ["pending", "processing", "shipped"].includes(o.status)) || []
|
||||||
const completedOrders = orders?.filter((o) => ["delivered", "cancelled"].includes(o.status)) || []
|
const completedOrders = orders?.filter((o) => ["delivered", "cancelled"].includes(o.status)) || []
|
||||||
|
|
||||||
return (
|
if (isLoading) {
|
||||||
<div className="container mx-auto p-4">
|
return (
|
||||||
<h1 className="text-3xl font-bold mb-6">My Orders</h1>
|
<div className="container mx-auto p-4 min-h-screen">
|
||||||
|
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
|
||||||
{isLoading ? (
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<Skeleton className="h-10 w-40" />
|
<Skeleton className="h-10 w-40" />
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
@@ -78,150 +129,110 @@ export default function OrdersPageClient({ locale }: OrdersPageProps) {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : isError ? (
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isError) {
|
||||||
|
return (
|
||||||
|
<div className="container mx-auto p-4 min-h-screen">
|
||||||
|
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
|
||||||
<div className="bg-red-50 p-4 rounded-lg border border-red-200">
|
<div className="bg-red-50 p-4 rounded-lg border border-red-200">
|
||||||
<p className="text-red-600">Failed to load orders. Please try again later.</p>
|
<p className="text-red-600">{t.loadError}</p>
|
||||||
|
{error && <p className="text-sm text-red-500 mt-2">{error.message}</p>}
|
||||||
</div>
|
</div>
|
||||||
) : !orders || orders.length === 0 ? (
|
</div>
|
||||||
<p className="text-gray-500">You have no orders yet.</p>
|
)
|
||||||
) : (
|
}
|
||||||
<Tabs defaultValue="active" className="w-full">
|
|
||||||
<TabsList className="mb-6">
|
|
||||||
<TabsTrigger value="active">Active Orders ({activeOrders.length})</TabsTrigger>
|
|
||||||
<TabsTrigger value="completed">Completed Orders ({completedOrders.length})</TabsTrigger>
|
|
||||||
</TabsList>
|
|
||||||
|
|
||||||
<TabsContent value="active">
|
if (!orders || orders.length === 0) {
|
||||||
{activeOrders.length === 0 ? (
|
return (
|
||||||
<p className="text-gray-500">You have no active orders.</p>
|
<div className="container mx-auto p-4 min-h-screen">
|
||||||
) : (
|
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<div className="flex items-center justify-center min-h-[60vh]">
|
||||||
{activeOrders.map((order) => (
|
<p className="text-2xl text-gray-400">{t.noOrders}</p>
|
||||||
<Card key={order.id} className="p-4 flex flex-col justify-between">
|
</div>
|
||||||
<div>
|
</div>
|
||||||
<div className="flex justify-between items-center mb-3">
|
)
|
||||||
<h3 className="text-lg font-semibold">Order #{order.id}</h3>
|
}
|
||||||
{getStatusBadge(order.status)}
|
|
||||||
</div>
|
|
||||||
<div className="mb-3">
|
|
||||||
<p className="text-sm text-gray-600">
|
|
||||||
Ordered: {new Date(order.created_at).toLocaleDateString()}
|
|
||||||
</p>
|
|
||||||
{order.estimated_delivery && (
|
|
||||||
<p className="text-sm text-gray-600">Est. Delivery: {order.estimated_delivery}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2 mb-3">
|
|
||||||
{order.items?.map((item) => (
|
|
||||||
<div key={item.id} className="flex items-start gap-3">
|
|
||||||
{item.product?.image && (
|
|
||||||
<Image
|
|
||||||
src={item.product.image || "/placeholder.svg"}
|
|
||||||
alt={item.product.name}
|
|
||||||
width={50}
|
|
||||||
height={50}
|
|
||||||
className="rounded"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="text-sm font-medium">{item.product?.name}</p>
|
|
||||||
<p className="text-xs text-gray-500">Qty: {item.quantity}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div className="border-t pt-3">
|
|
||||||
<div className="flex justify-between font-semibold">
|
|
||||||
<span>Total</span>
|
|
||||||
<span>{order.total_formatted || `$${order.total}`}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="mt-4">
|
|
||||||
<Button
|
|
||||||
variant="destructive"
|
|
||||||
onClick={() => handleCancelOrder(order)}
|
|
||||||
disabled={isCancellingOrder || order.status === "shipped" || order.status === "delivered"}
|
|
||||||
>
|
|
||||||
Cancel Order
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</TabsContent>
|
|
||||||
|
|
||||||
<TabsContent value="completed">
|
return (
|
||||||
{completedOrders.length === 0 ? (
|
<div className="container mx-auto p-4 min-h-screen">
|
||||||
<p className="text-gray-500">You have no completed orders.</p>
|
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
|
||||||
) : (
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
<Tabs defaultValue="active" className="w-full">
|
||||||
{completedOrders.map((order) => (
|
<TabsList className="mb-6">
|
||||||
<Card key={order.id} className="p-4">
|
<TabsTrigger value="active">
|
||||||
<div>
|
{t.activeOrders} ({activeOrders.length})
|
||||||
<div className="flex justify-between items-center mb-3">
|
</TabsTrigger>
|
||||||
<h3 className="text-lg font-semibold">Order #{order.id}</h3>
|
<TabsTrigger value="completed">
|
||||||
{getStatusBadge(order.status)}
|
{t.completedOrders} ({completedOrders.length})
|
||||||
</div>
|
</TabsTrigger>
|
||||||
<div className="mb-3">
|
</TabsList>
|
||||||
<p className="text-sm text-gray-600">
|
|
||||||
Ordered: {new Date(order.created_at).toLocaleDateString()}
|
<TabsContent value="active">
|
||||||
</p>
|
{activeOrders.length === 0 ? (
|
||||||
{order.updated_at && (
|
<div className="flex items-center justify-center min-h-[40vh]">
|
||||||
<p className="text-sm text-gray-600">
|
<p className="text-xl text-gray-400">{t.noActiveOrders}</p>
|
||||||
Completed: {new Date(order.updated_at).toLocaleDateString()}
|
</div>
|
||||||
</p>
|
) : (
|
||||||
)}
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
</div>
|
{activeOrders.map((order) => (
|
||||||
<div className="space-y-2 mb-3">
|
<OrderCard
|
||||||
{order.items?.map((item) => (
|
key={order.id}
|
||||||
<div key={item.id} className="flex items-start gap-3">
|
order={order}
|
||||||
{item.product?.image && (
|
onCancel={handleCancelOrder}
|
||||||
<Image
|
isCancelling={isCancellingOrder}
|
||||||
src={item.product.image || "/placeholder.svg"}
|
getStatusBadge={getStatusBadge}
|
||||||
alt={item.product.name}
|
translations={t}
|
||||||
width={50}
|
showCancelButton
|
||||||
height={50}
|
/>
|
||||||
className="rounded"
|
))}
|
||||||
/>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="flex-1">
|
</TabsContent>
|
||||||
<p className="text-sm font-medium">{item.product?.name}</p>
|
|
||||||
<p className="text-xs text-gray-500">Qty: {item.quantity}</p>
|
<TabsContent value="completed">
|
||||||
</div>
|
{completedOrders.length === 0 ? (
|
||||||
</div>
|
<div className="flex items-center justify-center min-h-[40vh]">
|
||||||
))}
|
<p className="text-xl text-gray-400">{t.noCompletedOrders}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="border-t pt-3">
|
) : (
|
||||||
<div className="flex justify-between font-semibold">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
<span>Total</span>
|
{completedOrders.map((order) => (
|
||||||
<span>{order.total_formatted || `$${order.total}`}</span>
|
<OrderCard
|
||||||
</div>
|
key={order.id}
|
||||||
</div>
|
order={order}
|
||||||
</div>
|
onCancel={handleCancelOrder}
|
||||||
</Card>
|
isCancelling={isCancellingOrder}
|
||||||
))}
|
getStatusBadge={getStatusBadge}
|
||||||
</div>
|
translations={t}
|
||||||
)}
|
showCancelButton={false}
|
||||||
</TabsContent>
|
/>
|
||||||
</Tabs>
|
))}
|
||||||
)}
|
</div>
|
||||||
|
)}
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
|
||||||
<Dialog open={isCancelDialogOpen} onOpenChange={setIsCancelDialogOpen}>
|
<Dialog open={isCancelDialogOpen} onOpenChange={setIsCancelDialogOpen}>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>Cancel Order #{orderToCancel?.id}</DialogTitle>
|
<DialogTitle>
|
||||||
<DialogDescription>
|
{t.cancelOrder} #{orderToCancel?.id}
|
||||||
Are you sure you want to cancel this order? This action cannot be undone.
|
</DialogTitle>
|
||||||
</DialogDescription>
|
<DialogDescription>{t.cancelConfirmation}</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" onClick={() => setIsCancelDialogOpen(false)}>
|
<Button
|
||||||
Keep Order
|
variant="outline"
|
||||||
|
onClick={() => setIsCancelDialogOpen(false)}
|
||||||
|
disabled={isCancellingOrder}
|
||||||
|
>
|
||||||
|
{t.keepOrder}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="destructive" onClick={confirmCancelOrder} disabled={isCancellingOrder}>
|
<Button variant="destructive" onClick={confirmCancelOrder} disabled={isCancellingOrder}>
|
||||||
{isCancellingOrder ? "Cancelling..." : "Cancel Order"}
|
{isCancellingOrder ? t.cancelling : t.cancelOrder}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
@@ -229,3 +240,95 @@ export default function OrdersPageClient({ locale }: OrdersPageProps) {
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface OrderCardProps {
|
||||||
|
order: Order
|
||||||
|
onCancel: (order: Order) => void
|
||||||
|
isCancelling: boolean
|
||||||
|
getStatusBadge: (status: Order["status"]) => React.ReactNode
|
||||||
|
translations: any
|
||||||
|
showCancelButton: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function OrderCard({
|
||||||
|
order,
|
||||||
|
onCancel,
|
||||||
|
isCancelling,
|
||||||
|
getStatusBadge,
|
||||||
|
translations: t,
|
||||||
|
showCancelButton,
|
||||||
|
}: OrderCardProps) {
|
||||||
|
const canCancel =
|
||||||
|
showCancelButton && order.status !== "shipped" && order.status !== "delivered" && order.status !== "cancelled"
|
||||||
|
|
||||||
|
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.orderNumber}{order.id}
|
||||||
|
</h3>
|
||||||
|
{getStatusBadge(order.status)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-3 space-y-1">
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
{t.ordered}: {new Date(order.created_at).toLocaleDateString()}
|
||||||
|
</p>
|
||||||
|
{order.estimated_delivery && (
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
{t.estimatedDelivery}: {order.estimated_delivery}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{!showCancelButton && order.updated_at && (
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
{t.completed}: {new Date(order.updated_at).toLocaleDateString()}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2 mb-3 max-h-48 overflow-y-auto">
|
||||||
|
{order.items?.map((item) => (
|
||||||
|
<div key={item.id} className="flex items-start gap-3">
|
||||||
|
{item.product?.image && (
|
||||||
|
<Image
|
||||||
|
src={item.product.image || "/placeholder.svg"}
|
||||||
|
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.quantity}: {item.quantity}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border-t pt-3">
|
||||||
|
<div className="flex justify-between font-semibold">
|
||||||
|
<span>{t.total}</span>
|
||||||
|
<span>{order.total_formatted || `$${order.total}`}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{canCancel && (
|
||||||
|
<div className="mt-4">
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => onCancel(order)}
|
||||||
|
disabled={isCancelling}
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
{t.cancelOrder}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -7,73 +7,105 @@ import { Minus, Plus, Heart, ShoppingCart, Store } from "lucide-react"
|
|||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Card } from "@/components/ui/card"
|
import { Card } from "@/components/ui/card"
|
||||||
import { Separator } from "@/components/ui/separator"
|
import { Separator } from "@/components/ui/separator"
|
||||||
import { Badge } from "@/components/ui/badge"
|
|
||||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
|
||||||
import placeholder from "@/public/jb.webp"
|
|
||||||
import { useProduct, useCategories } from "@/lib/hooks"
|
|
||||||
import { Skeleton } from "@/components/ui/skeleton"
|
import { Skeleton } from "@/components/ui/skeleton"
|
||||||
|
import { useProductsBySlug } from "@/lib/hooks/useProducts"
|
||||||
|
import { useAddToCart, useUpdateCartItemQuantity, useCart } from "@/lib/hooks/useCart"
|
||||||
|
import { toast } from "sonner"
|
||||||
|
|
||||||
interface ProductDetailProps {
|
interface ProductDetailProps {
|
||||||
slug: string
|
slug: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const ProductPageContent = ({ slug }: ProductDetailProps) => {
|
const ProductPageContent = ({ slug }: ProductDetailProps) => {
|
||||||
const [isClient, setIsClient] = useState(false)
|
|
||||||
const [selectedImage, setSelectedImage] = useState(0)
|
const [selectedImage, setSelectedImage] = useState(0)
|
||||||
const [quantity, setQuantity] = useState(1)
|
const [quantity, setQuantity] = useState(1)
|
||||||
const [isFavorite, setIsFavorite] = useState(false)
|
const [isFavorite, setIsFavorite] = useState(false)
|
||||||
const [isInCart, setIsInCart] = useState(false)
|
|
||||||
const [isLoading, setIsLoading] = useState(false)
|
|
||||||
|
|
||||||
const { data: product, isLoading: productLoading, error } = useProduct(slug)
|
// Get product data
|
||||||
const { data: categoriesData } = useCategories()
|
const { data: product, isLoading: productLoading, error } = useProductsBySlug(slug)
|
||||||
|
|
||||||
if (!isClient) {
|
// Get cart data to check if product is already in cart
|
||||||
typeof window !== "undefined" && setIsClient(true)
|
const { data: cartData } = useCart()
|
||||||
}
|
|
||||||
|
// Cart mutations
|
||||||
|
const addToCartMutation = useAddToCart()
|
||||||
|
const updateCartMutation = useUpdateCartItemQuantity()
|
||||||
|
|
||||||
const t = {
|
const t = {
|
||||||
addToCart: "Add to Cart",
|
addToCart: "Sebede goş",
|
||||||
goToCart: "Go to Cart",
|
goToCart: "Sebede git",
|
||||||
price: "Price:",
|
price: "Bahasy:",
|
||||||
aboutProduct: "About Product",
|
aboutProduct: "Haryt barada",
|
||||||
brand: "Brand",
|
brand: "Marka",
|
||||||
model: "Model",
|
stock: "Mukdary",
|
||||||
description: "Product Description",
|
description: "Düşündiriş",
|
||||||
recommended: "Recommended Products",
|
store: "Dükan",
|
||||||
store: "Store",
|
writeToStore: "Dükana ýaz",
|
||||||
writeToStore: "Write to Store",
|
color: "Reňk:",
|
||||||
color: "Color:",
|
category: "Kategoriýa:",
|
||||||
|
barcode: "Barkod:",
|
||||||
|
addedToCart: "Sebede goşuldy",
|
||||||
|
updatedCart: "Sebe täzelendi",
|
||||||
|
error: "Ýalňyşlyk ýüze çykdy",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if product is in cart
|
||||||
|
const cartItem = cartData?.data?.find((item: any) => item.product?.id === product?.id)
|
||||||
|
const isInCart = !!cartItem
|
||||||
|
|
||||||
const handleAddToCart = async () => {
|
const handleAddToCart = async () => {
|
||||||
setIsLoading(true)
|
if (!product?.id) return
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// TODO: implement cart API call
|
await addToCartMutation.mutateAsync({
|
||||||
await new Promise((resolve) => setTimeout(resolve, 500))
|
productId: product.id,
|
||||||
setIsInCart(true)
|
quantity: quantity,
|
||||||
} finally {
|
})
|
||||||
setIsLoading(false)
|
|
||||||
|
toast.success(t.addedToCart, {
|
||||||
|
description: `${product.name} sebede goşuldy`,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Add to cart error:", error)
|
||||||
|
toast.error(t.error, {
|
||||||
|
description: "Haryt sebede goşup bolmady",
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleQuantityChange = async (newQuantity: number) => {
|
const handleQuantityChange = async (newQuantity: number) => {
|
||||||
if (newQuantity < 1) return
|
if (newQuantity < 1 || !product?.id) return
|
||||||
setIsLoading(true)
|
if (newQuantity > product.stock) return
|
||||||
try {
|
|
||||||
setQuantity(newQuantity)
|
setQuantity(newQuantity)
|
||||||
// TODO: implement cart quantity update API call
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
// If product is already in cart, update it
|
||||||
} finally {
|
if (isInCart) {
|
||||||
setIsLoading(false)
|
try {
|
||||||
|
await updateCartMutation.mutateAsync({
|
||||||
|
productId: product.id,
|
||||||
|
quantity: newQuantity,
|
||||||
|
})
|
||||||
|
|
||||||
|
toast.success(t.updatedCart, {
|
||||||
|
description: `Mukdar: ${newQuantity}`,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Update cart error:", error)
|
||||||
|
toast.error(t.error, {
|
||||||
|
description: "Mukdar täzelenip bolmady",
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleToggleFavorite = () => {
|
const handleToggleFavorite = () => {
|
||||||
setIsFavorite(!isFavorite)
|
setIsFavorite(!isFavorite)
|
||||||
// TODO: implement favorites API call
|
// TODO: Implement favorites API
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Loading state
|
||||||
if (productLoading) {
|
if (productLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="container mx-auto px-4 py-8">
|
<div className="container mx-auto px-4 py-8">
|
||||||
@@ -95,14 +127,21 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Error state
|
||||||
if (error || !product) {
|
if (error || !product) {
|
||||||
return (
|
return (
|
||||||
<div className="container mx-auto px-4 py-8 text-center">
|
<div className="container mx-auto px-4 py-8 text-center">
|
||||||
<h2 className="text-2xl font-bold text-red-600">Product not found</h2>
|
<h2 className="text-2xl font-bold text-red-600">Haryt tapylmady</h2>
|
||||||
|
<p className="text-gray-500 mt-2">Bu haryt ýok ýa-da aýryldy</p>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Extract image URLs from media array
|
||||||
|
const imageUrls = product.media?.map(m => m.images_800x800 || m.images_720x720 || m.thumbnail) || []
|
||||||
|
|
||||||
|
const isLoading = addToCartMutation.isPending || updateCartMutation.isPending
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="container mx-auto px-4 py-8">
|
<div className="container mx-auto px-4 py-8">
|
||||||
<div className="flex flex-col lg:flex-row gap-8">
|
<div className="flex flex-col lg:flex-row gap-8">
|
||||||
@@ -110,42 +149,37 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
|
|||||||
<div className="flex-1 max-w-2xl">
|
<div className="flex-1 max-w-2xl">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<div className="relative aspect-square w-full rounded-2xl overflow-hidden bg-gray-50">
|
<div className="relative aspect-square w-full rounded-2xl overflow-hidden bg-gray-50">
|
||||||
{product.labels && product.labels.length > 0 && (
|
{imageUrls.length > 0 ? (
|
||||||
<div className="absolute top-0 right-0 z-10 flex flex-col gap-1">
|
<Image
|
||||||
{product.labels.map((label) => (
|
src={imageUrls[selectedImage]}
|
||||||
<Badge
|
alt={product.name}
|
||||||
key={label.text}
|
fill
|
||||||
className="rounded-l-md rounded-r-none text-white text-xs font-bold uppercase"
|
className="object-contain"
|
||||||
style={{ backgroundColor: label.bg_color }}
|
priority
|
||||||
>
|
/>
|
||||||
{label.text}
|
) : (
|
||||||
</Badge>
|
<div className="flex items-center justify-center h-full text-gray-400">
|
||||||
))}
|
Surat ýok
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<Image
|
|
||||||
src={product.images?.[selectedImage] || product.image || placeholder}
|
|
||||||
alt={product.name}
|
|
||||||
fill
|
|
||||||
className="object-contain"
|
|
||||||
priority
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Thumbnail Images */}
|
{/* Thumbnail Images */}
|
||||||
{product.images && product.images.length > 1 && (
|
{imageUrls.length > 1 && (
|
||||||
<div className="mt-4 flex gap-2 overflow-x-auto pb-2">
|
<div className="mt-4 flex gap-2 overflow-x-auto pb-2">
|
||||||
{product.images.map((image, index) => (
|
{imageUrls.map((image, index) => (
|
||||||
<button
|
<button
|
||||||
key={index}
|
key={index}
|
||||||
onClick={() => setSelectedImage(index)}
|
onClick={() => setSelectedImage(index)}
|
||||||
className={`relative w-16 h-16 rounded overflow-hidden border ${
|
className={`relative w-16 h-16 flex-shrink-0 rounded overflow-hidden border-2 transition-all ${
|
||||||
selectedImage === index ? "border-black" : "border-transparent"
|
selectedImage === index
|
||||||
|
? "border-primary ring-2 ring-primary/20"
|
||||||
|
: "border-gray-200 hover:border-gray-300"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<Image
|
<Image
|
||||||
src={image || "/placeholder.svg"}
|
src={image}
|
||||||
alt={`${product.name} thumbnail ${index + 1}`}
|
alt={`${product.name} ${index + 1}`}
|
||||||
fill
|
fill
|
||||||
className="object-cover"
|
className="object-cover"
|
||||||
/>
|
/>
|
||||||
@@ -160,60 +194,121 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
|
|||||||
<div className="flex-1 space-y-6">
|
<div className="flex-1 space-y-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-3xl font-bold mb-2">{product.name}</h1>
|
<h1 className="text-3xl font-bold mb-2">{product.name}</h1>
|
||||||
{product.category && (
|
{product.categories && product.categories.length > 0 && (
|
||||||
<div className="flex gap-2 flex-wrap">
|
<div className="flex gap-2 flex-wrap mt-2">
|
||||||
<span className="text-sm text-gray-500">Category: {product.category}</span>
|
{product.categories.map((cat, idx) => (
|
||||||
|
<span
|
||||||
|
key={idx}
|
||||||
|
className="text-sm px-3 py-1 bg-gray-100 rounded-full text-gray-600"
|
||||||
|
>
|
||||||
|
{cat.name}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Product Info Table */}
|
{/* Product Info Table */}
|
||||||
<Card className="p-4 rounded-xl">
|
<Card className="p-4 rounded-xl border-gray-200">
|
||||||
<h3 className="text-xl font-semibold mb-4">{t.aboutProduct}</h3>
|
<h3 className="text-xl font-semibold mb-4">{t.aboutProduct}</h3>
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{product.brand && (
|
{product.brand?.name && (
|
||||||
<>
|
<>
|
||||||
<div className="flex justify-between items-center py-2">
|
<div className="flex justify-between items-center py-2">
|
||||||
<span className="text-gray-500">{t.brand}</span>
|
<span className="text-gray-500">{t.brand}</span>
|
||||||
<span className="font-medium">{product.brand}</span>
|
<span className="font-medium">{product.brand.name}</span>
|
||||||
</div>
|
</div>
|
||||||
<Separator />
|
<Separator />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{product.stock !== undefined && (
|
{product.stock !== undefined && (
|
||||||
<>
|
<>
|
||||||
<div className="flex justify-between items-center py-2">
|
<div className="flex justify-between items-center py-2">
|
||||||
<span className="text-gray-500">Stock</span>
|
<span className="text-gray-500">{t.stock}</span>
|
||||||
<span className="font-medium">{product.stock}</span>
|
<span className={`font-medium ${product.stock === 0 ? 'text-red-500' : 'text-green-600'}`}>
|
||||||
|
{product.stock === 0 ? 'Ýok' : product.stock}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<Separator />
|
<Separator />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{product.barcode && (
|
||||||
|
<>
|
||||||
|
<div className="flex justify-between items-center py-2">
|
||||||
|
<span className="text-gray-500">{t.barcode}</span>
|
||||||
|
<span className="font-mono text-sm">{product.barcode}</span>
|
||||||
|
</div>
|
||||||
|
<Separator />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{product.colour && (
|
||||||
|
<>
|
||||||
|
<div className="flex justify-between items-center py-2">
|
||||||
|
<span className="text-gray-500">{t.color}</span>
|
||||||
|
<span className="font-medium">{product.colour}</span>
|
||||||
|
</div>
|
||||||
|
<Separator />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{product.properties && product.properties.length > 0 && (
|
||||||
|
<>
|
||||||
|
{product.properties.map((prop, idx) => (
|
||||||
|
prop.value && (
|
||||||
|
<div key={idx}>
|
||||||
|
<div className="flex justify-between items-center py-2">
|
||||||
|
<span className="text-gray-500">{prop.name}</span>
|
||||||
|
<span className="font-medium">{prop.value}</span>
|
||||||
|
</div>
|
||||||
|
{idx < product.properties.length - 1 && <Separator />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Description */}
|
{/* Description */}
|
||||||
{product.description && (
|
{product.description && (
|
||||||
<div>
|
<Card className="p-4 rounded-xl border-gray-200">
|
||||||
<h3 className="text-xl font-semibold mb-3">{t.description}</h3>
|
<h3 className="text-xl font-semibold mb-3">{t.description}</h3>
|
||||||
<p className="text-gray-700 leading-relaxed">{product.description}</p>
|
<div
|
||||||
</div>
|
className="text-gray-700 leading-relaxed prose prose-sm max-w-none"
|
||||||
|
dangerouslySetInnerHTML={{ __html: product.description }}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Price & Actions Sidebar */}
|
{/* Price & Actions Sidebar */}
|
||||||
<div className="lg:w-[420px] space-y-4">
|
<div className="lg:w-[380px] space-y-4">
|
||||||
<Card className="p-6 rounded-xl shadow-lg">
|
<Card className="p-6 rounded-xl shadow-lg sticky top-4">
|
||||||
<div className="flex justify-between items-center mb-6">
|
<div className="flex justify-between items-start mb-6">
|
||||||
<span className="text-lg text-gray-500">{t.price}</span>
|
<span className="text-lg text-gray-500">{t.price}</span>
|
||||||
<span className="text-3xl font-bold">${product.price}</span>
|
<div className="flex flex-col items-end">
|
||||||
|
<span className="text-3xl font-bold text-primary">
|
||||||
|
{product.price_amount} TMT
|
||||||
|
</span>
|
||||||
|
{product.old_price_amount && parseFloat(product.old_price_amount) > 0 && (
|
||||||
|
<span className="text-lg text-gray-400 line-through">
|
||||||
|
{product.old_price_amount} TMT
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-3">
|
||||||
{isInCart ? (
|
{isInCart ? (
|
||||||
<div className="space-y-3">
|
<>
|
||||||
<Link href="/cart">
|
<Link href="/cart">
|
||||||
<Button size="lg" className="w-full rounded-xl text-lg font-bold bg-green-600 hover:bg-green-700">
|
<Button
|
||||||
|
size="lg"
|
||||||
|
className="w-full rounded-xl text-lg font-bold bg-green-600 hover:bg-green-700"
|
||||||
|
>
|
||||||
<ShoppingCart className="mr-2 h-5 w-5" />
|
<ShoppingCart className="mr-2 h-5 w-5" />
|
||||||
{t.goToCart}
|
{t.goToCart}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -225,31 +320,33 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
|
|||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => handleQuantityChange(quantity - 1)}
|
onClick={() => handleQuantityChange(quantity - 1)}
|
||||||
disabled={quantity === 1 || isLoading}
|
disabled={quantity === 1 || isLoading}
|
||||||
className="rounded-xl bg-blue-50 flex-shrink-0"
|
className="rounded-xl h-12 w-12"
|
||||||
>
|
>
|
||||||
<Minus className="h-5 w-5" />
|
<Minus className="h-5 w-5" />
|
||||||
</Button>
|
</Button>
|
||||||
<div className="flex-1 text-center font-semibold text-lg">{quantity}</div>
|
<div className="flex-1 text-center font-semibold text-xl border rounded-xl h-12 flex items-center justify-center">
|
||||||
|
{quantity}
|
||||||
|
</div>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="icon"
|
size="icon"
|
||||||
onClick={() => handleQuantityChange(quantity + 1)}
|
onClick={() => handleQuantityChange(quantity + 1)}
|
||||||
disabled={isLoading}
|
disabled={isLoading || quantity >= product.stock}
|
||||||
className="rounded-xl bg-blue-50 flex-shrink-0"
|
className="rounded-xl h-12 w-12"
|
||||||
>
|
>
|
||||||
<Plus className="h-5 w-5" />
|
<Plus className="h-5 w-5" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<Button
|
||||||
size="lg"
|
size="lg"
|
||||||
onClick={handleAddToCart}
|
onClick={handleAddToCart}
|
||||||
disabled={isLoading}
|
disabled={isLoading || product.stock === 0}
|
||||||
className="w-full rounded-xl text-lg font-bold"
|
className="w-full rounded-xl text-lg font-bold"
|
||||||
>
|
>
|
||||||
<ShoppingCart className="mr-2 h-5 w-5" />
|
<ShoppingCart className="mr-2 h-5 w-5" />
|
||||||
{t.addToCart}
|
{isLoading ? "Goşulýar..." : product.stock === 0 ? "Haryt ýok" : t.addToCart}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -257,32 +354,44 @@ const ProductPageContent = ({ slug }: ProductDetailProps) => {
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
size="lg"
|
size="lg"
|
||||||
onClick={handleToggleFavorite}
|
onClick={handleToggleFavorite}
|
||||||
className={`w-full rounded-xl ${
|
className={`w-full rounded-xl transition-all ${
|
||||||
isFavorite ? "bg-red-50 border-red-200 hover:bg-red-100" : "bg-blue-50"
|
isFavorite
|
||||||
|
? "bg-red-50 border-red-300 hover:bg-red-100"
|
||||||
|
: "hover:bg-gray-50"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<Heart className={`h-6 w-6 ${isFavorite ? "fill-red-500 text-red-500" : ""}`} />
|
<Heart
|
||||||
|
className={`h-6 w-6 transition-all ${
|
||||||
|
isFavorite ? "fill-red-500 text-red-500" : "text-gray-600"
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
{/* Seller Card */}
|
{/* Store/Channel Card */}
|
||||||
<Card className="p-6 rounded-xl">
|
{product.channel && product.channel.length > 0 && (
|
||||||
<div className="flex items-center gap-4 mb-4">
|
<Card className="p-6 rounded-xl">
|
||||||
<Avatar className="w-14 h-14">
|
<div className="flex items-center gap-4 mb-4">
|
||||||
<AvatarFallback>
|
<Avatar className="w-14 h-14 bg-primary/10">
|
||||||
<Store className="h-6 w-6" />
|
<AvatarFallback className="bg-transparent">
|
||||||
</AvatarFallback>
|
<Store className="h-6 w-6 text-primary" />
|
||||||
</Avatar>
|
</AvatarFallback>
|
||||||
<div>
|
</Avatar>
|
||||||
<p className="text-sm text-gray-500">{t.store}</p>
|
<div>
|
||||||
<h4 className="text-xl font-bold hover:text-primary cursor-pointer">Official Store</h4>
|
<p className="text-sm text-gray-500">{t.store}</p>
|
||||||
|
<h4 className="text-lg font-bold">{product.channel[0].name}</h4>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<Button
|
||||||
<Button variant="outline" size="lg" disabled className="w-full rounded-xl bg-transparent">
|
variant="outline"
|
||||||
{t.writeToStore}
|
size="lg"
|
||||||
</Button>
|
className="w-full rounded-xl"
|
||||||
</Card>
|
>
|
||||||
|
{t.writeToStore}
|
||||||
|
</Button>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, MouseEvent } from "react";
|
import { useState, MouseEvent } from "react";
|
||||||
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardContent } from "@/components/ui/card";
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Heart, HeartOff, Minus, Plus } from "lucide-react";
|
import { Heart, Minus, Plus } from "lucide-react";
|
||||||
import Image, { StaticImageData } from "next/image";
|
import Image, { StaticImageData } from "next/image";
|
||||||
|
import { useAddToFavorites, useRemoveFromFavorites } from "@/lib/hooks";
|
||||||
|
import { useToast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
type ProductCardProps = {
|
type ProductCardProps = {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -43,10 +45,52 @@ export default function ProductCard({
|
|||||||
const [cart, setCart] = useState(false);
|
const [cart, setCart] = useState(false);
|
||||||
const [count, setCount] = useState(1);
|
const [count, setCount] = useState(1);
|
||||||
|
|
||||||
|
const { toast } = useToast();
|
||||||
|
const { mutate: addToFavorites, isPending: isAdding } = useAddToFavorites();
|
||||||
|
const { mutate: removeFromFavorites, isPending: isRemoving } =
|
||||||
|
useRemoveFromFavorites();
|
||||||
|
|
||||||
const handleFavorite = (e: MouseEvent<HTMLButtonElement>) => {
|
const handleFavorite = (e: MouseEvent<HTMLButtonElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
setFavorite((prev) => !prev);
|
|
||||||
|
const newFavoriteState = !favorite;
|
||||||
|
|
||||||
|
if (newFavoriteState) {
|
||||||
|
// Добавляем в избранное
|
||||||
|
addToFavorites(id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
setFavorite(true);
|
||||||
|
toast({
|
||||||
|
title: "Товар добавлен в избранное",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast({
|
||||||
|
title: "Ошибка",
|
||||||
|
description: error.message,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Удаляем из избранного
|
||||||
|
removeFromFavorites(id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
setFavorite(false);
|
||||||
|
toast({
|
||||||
|
title: "Товар удален из избранного",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast({
|
||||||
|
title: "Ошибка",
|
||||||
|
description: error.message,
|
||||||
|
variant: "destructive",
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAddToCart = (e: MouseEvent<HTMLButtonElement>) => {
|
const handleAddToCart = (e: MouseEvent<HTMLButtonElement>) => {
|
||||||
@@ -67,21 +111,23 @@ export default function ProductCard({
|
|||||||
setCount((c) => (c > 1 ? c - 1 : c));
|
setCount((c) => (c > 1 ? c - 1 : c));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const isPending = isAdding || isRemoving;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link href={`/product/${id}`} className="no-underline">
|
<Link href={`/product/${id}`} className="no-underline">
|
||||||
<Card
|
<Card
|
||||||
className={`relative gap-2 border-none shadow-none! p-0 w-full max-w-[${width}px] overflow-hidden rounded-2xl hover:shadow-md transition-all cursor-pointer`}
|
className={`relative gap-2 border-none shadow-none! p-0 w-full max-w-[${width}px] overflow-hidden rounded-2xl hover:shadow-md transition-all cursor-pointer`}
|
||||||
style={{ height }}
|
style={{ height }}
|
||||||
>
|
>
|
||||||
{/* Image Section */}
|
{/* Image Section */}
|
||||||
<div className="relative w-full h-[260px] ">
|
<div className="relative w-full h-[260px]">
|
||||||
{images?.[0] && (
|
{images?.[0] && (
|
||||||
<Image
|
<Image
|
||||||
src={images[0]}
|
src={images[0]}
|
||||||
alt={name}
|
alt={name}
|
||||||
fill
|
fill
|
||||||
sizes="(max-width: 600px) 100vw, 33vw"
|
sizes="(max-width: 600px) 100vw, 33vw"
|
||||||
className="object-contain "
|
className="object-contain"
|
||||||
priority
|
priority
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -89,7 +135,8 @@ export default function ProductCard({
|
|||||||
{/* Favorite Button */}
|
{/* Favorite Button */}
|
||||||
<button
|
<button
|
||||||
onClick={handleFavorite}
|
onClick={handleFavorite}
|
||||||
className="absolute top-3 right-3 z-10 rounded-full bg-white/80 p-2 hover:bg-white"
|
disabled={isPending}
|
||||||
|
className="absolute top-3 right-3 z-10 rounded-full bg-white/80 p-2 hover:bg-white transition-all disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
>
|
>
|
||||||
{favorite ? (
|
{favorite ? (
|
||||||
<Heart className="w-5 h-5 text-red-500 fill-red-500" />
|
<Heart className="w-5 h-5 text-red-500 fill-red-500" />
|
||||||
@@ -125,7 +172,7 @@ export default function ProductCard({
|
|||||||
<p className="text-gray-800 text-sm truncate mx-2">{name}</p>
|
<p className="text-gray-800 text-sm truncate mx-2">{name}</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|
||||||
{/* Buttons */}
|
{/* Buttons - закомментированы в оригинале */}
|
||||||
{/* {button && (
|
{/* {button && (
|
||||||
<div className="p-3">
|
<div className="p-3">
|
||||||
{!cart ? (
|
{!cart ? (
|
||||||
|
|||||||
@@ -47,7 +47,13 @@ export default function CategoryGrid({ categories, isLoading, isError, locale, t
|
|||||||
<Link key={cat.id} href={`/${locale}/category/${cat.slug}?category_id=${cat.id}`}>
|
<Link key={cat.id} href={`/${locale}/category/${cat.slug}?category_id=${cat.id}`}>
|
||||||
<Card className="hover:shadow-md border-none shadow-none p-0 gap-2 transition-all cursor-pointer">
|
<Card className="hover:shadow-md border-none shadow-none p-0 gap-2 transition-all cursor-pointer">
|
||||||
<div className="relative w-full h-36 overflow-hidden rounded-lg">
|
<div className="relative w-full h-36 overflow-hidden rounded-lg">
|
||||||
<Image src={cat.image || "/placeholder.svg"} alt={cat.name} fill className="object-contain" />
|
<Image
|
||||||
|
src={cat.media?.[0]?.images_400x400 || "/placeholder.svg"}
|
||||||
|
alt={cat.name}
|
||||||
|
fill
|
||||||
|
className="object-contain"
|
||||||
|
/>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
<CardContent className="py-2">
|
<CardContent className="py-2">
|
||||||
<p className="text-sm font-medium text-gray-800 truncate text-center">{cat.name}</p>
|
<p className="text-sm font-medium text-gray-800 truncate text-center">{cat.name}</p>
|
||||||
|
|||||||
41
lib/api.ts
41
lib/api.ts
@@ -22,7 +22,6 @@ const removeTokenFromCookie = (name: string): void => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getToken = (): string | null => {
|
const getToken = (): string | null => {
|
||||||
// Check cookies first (more secure)
|
|
||||||
const authToken = getTokenFromCookie("authToken")
|
const authToken = getTokenFromCookie("authToken")
|
||||||
if (authToken) return authToken
|
if (authToken) return authToken
|
||||||
|
|
||||||
@@ -32,6 +31,17 @@ const getToken = (): string | null => {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map internal locale codes to API language codes
|
||||||
|
*/
|
||||||
|
const localeToApiLang = (locale: string): string => {
|
||||||
|
const mapping: Record<string, string> = {
|
||||||
|
tm: "tk",
|
||||||
|
ru: "ru",
|
||||||
|
}
|
||||||
|
return mapping[locale] || locale
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Centralized API client with interceptors
|
* Centralized API client with interceptors
|
||||||
*/
|
*/
|
||||||
@@ -68,13 +78,27 @@ class APIClient {
|
|||||||
config.headers.Authorization = `Bearer ${token}`
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add language parameter if i18n is available
|
// Add language parameter
|
||||||
if (typeof window !== "undefined" && (window as any).i18n) {
|
let lang = "tk" // default fallback
|
||||||
const lang = (window as any).i18n.language || "tm"
|
|
||||||
const url = config.url || ""
|
if (typeof window !== "undefined") {
|
||||||
config.url = `${url}${url.includes("?") ? "&" : "?"}lang=${lang}`
|
// Try to get from i18n
|
||||||
|
if ((window as any).i18n?.language) {
|
||||||
|
lang = localeToApiLang((window as any).i18n.language)
|
||||||
|
}
|
||||||
|
// Try to get from pathname as fallback
|
||||||
|
else {
|
||||||
|
const pathLocale = window.location.pathname.split("/")[1]
|
||||||
|
if (pathLocale === "tm" || pathLocale === "ru") {
|
||||||
|
lang = localeToApiLang(pathLocale)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const url = config.url || ""
|
||||||
|
const separator = url.includes("?") ? "&" : "?"
|
||||||
|
config.url = `${url}${separator}lang=${lang}`
|
||||||
|
|
||||||
return config
|
return config
|
||||||
},
|
},
|
||||||
(error) => Promise.reject(error)
|
(error) => Promise.reject(error)
|
||||||
@@ -89,7 +113,6 @@ class APIClient {
|
|||||||
// Handle 401 errors
|
// Handle 401 errors
|
||||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||||
if (this.isRefreshing) {
|
if (this.isRefreshing) {
|
||||||
// Queue requests while refreshing
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
this.failedQueue.push({ resolve, reject })
|
this.failedQueue.push({ resolve, reject })
|
||||||
})
|
})
|
||||||
@@ -101,7 +124,6 @@ class APIClient {
|
|||||||
this.isRefreshing = true
|
this.isRefreshing = true
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Attempt to get guest token
|
|
||||||
const guestTokenResponse = await axios.post(
|
const guestTokenResponse = await axios.post(
|
||||||
`${this.baseUrl}/api/v1/auth/guest-token`,
|
`${this.baseUrl}/api/v1/auth/guest-token`,
|
||||||
{},
|
{},
|
||||||
@@ -203,10 +225,7 @@ class APIClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Export singleton instance
|
|
||||||
export const apiClient = new APIClient()
|
export const apiClient = new APIClient()
|
||||||
|
|
||||||
// Export helper functions
|
|
||||||
export const setAuthToken = (token: string) => apiClient.setAuthToken(token)
|
export const setAuthToken = (token: string) => apiClient.setAuthToken(token)
|
||||||
export const setGuestToken = (token: string) => apiClient.setGuestToken(token)
|
export const setGuestToken = (token: string) => apiClient.setGuestToken(token)
|
||||||
export const clearAuthToken = () => apiClient.clearAuthToken()
|
export const clearAuthToken = () => apiClient.clearAuthToken()
|
||||||
@@ -9,7 +9,12 @@ export * from "./useOpenStore"
|
|||||||
export * from "./useRegions"
|
export * from "./useRegions"
|
||||||
export * from "./useAddresses"
|
export * from "./useAddresses"
|
||||||
export * from "./usePaymentTypes"
|
export * from "./usePaymentTypes"
|
||||||
export * from "./useCategories"
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export * from "./useMedia"
|
export * from "./useMedia"
|
||||||
export * from "./useCollections"
|
export * from "./useCollections"
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
import { useQuery } from "@tanstack/react-query"
|
|
||||||
import { apiClient } from "@/lib/api"
|
|
||||||
import type { Address } from "@/lib/types/api"
|
|
||||||
|
|
||||||
export function useAddresses() {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["addresses"],
|
|
||||||
queryFn: async () => {
|
|
||||||
const response = await apiClient.get<Address[]>("/api/v1/addresses")
|
|
||||||
return response.data
|
|
||||||
},
|
|
||||||
staleTime: 1000 * 60 * 30, // 30 minutes
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,16 +1,61 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
import { useQuery, useMutation, useQueryClient, UseQueryOptions } from "@tanstack/react-query"
|
||||||
import { apiClient } from "@/lib/api"
|
import { apiClient } from "@/lib/api"
|
||||||
import type { Cart, CartItem } from "@/lib/types/api"
|
import type { Cart, CartItem } from "@/lib/types/api"
|
||||||
|
|
||||||
export function useCart() {
|
interface CartResponse {
|
||||||
|
message: string
|
||||||
|
data: CartItem[]
|
||||||
|
errorDetails?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transform response to handle HTML/malformed responses
|
||||||
|
function transformCartResponse(response: any): CartResponse {
|
||||||
|
if (
|
||||||
|
typeof response === "string" &&
|
||||||
|
(response.trim().startsWith("<!DOCTYPE") || response.trim().startsWith("<html"))
|
||||||
|
) {
|
||||||
|
console.error("Received HTML response instead of JSON:", response.substring(0, 100))
|
||||||
|
return {
|
||||||
|
message: "error",
|
||||||
|
data: [],
|
||||||
|
errorDetails: "Server returned HTML instead of JSON. The server might be down or experiencing issues.",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof response === "object") {
|
||||||
|
if (response.data) {
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
return { message: "success", data: [] }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof response === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(response)
|
||||||
|
return parsed
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to parse response:", error)
|
||||||
|
return { message: "error", data: [] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { message: "unknown", data: [] }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCart(options?: Partial<UseQueryOptions<CartResponse>>) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["cart"],
|
queryKey: ["cart"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await apiClient.get<Cart>("/api/v1/carts")
|
const response = await apiClient.get("/carts")
|
||||||
return response.data
|
return transformCartResponse(response.data)
|
||||||
},
|
},
|
||||||
staleTime: 0, // Always fetch fresh
|
refetchInterval: 5000, // Poll every 5 seconds like RTK
|
||||||
|
refetchOnMount: true,
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
refetchOnReconnect: true,
|
||||||
|
staleTime: 0,
|
||||||
retry: 1,
|
retry: 1,
|
||||||
|
...options,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -19,17 +64,38 @@ export function useAddToCart() {
|
|||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async ({ productId, quantity = 1 }: { productId: number; quantity?: number }) => {
|
mutationFn: async ({ productId, quantity = 1 }: { productId: number; quantity?: number }) => {
|
||||||
const response = await apiClient.post<Cart>("/api/v1/carts", {
|
const params = new URLSearchParams({
|
||||||
product_id: productId,
|
product_id: String(productId),
|
||||||
quantity,
|
product_quantity: String(quantity),
|
||||||
})
|
})
|
||||||
return response.data
|
|
||||||
|
const response = await apiClient.post("/carts", params.toString(), {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (typeof response.data === "object" && response.data.data) {
|
||||||
|
return response.data
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof response.data === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(response.data)
|
||||||
|
return parsed
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to parse add to cart response:", error)
|
||||||
|
return { message: "success", data: "Added to cart" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { message: "success", data: "Added to cart" }
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||||
},
|
},
|
||||||
onError: (error: any) => {
|
onError: (error: any) => {
|
||||||
console.error("[v0] Add to cart error:", error.response?.data?.message || error.message)
|
console.error("Add to cart error:", error.response?.data?.message || error.message)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -38,8 +104,66 @@ export function useRemoveFromCart() {
|
|||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (itemId: number) => {
|
mutationFn: async (productId: number) => {
|
||||||
await apiClient.delete(`/api/v1/carts/${itemId}`)
|
const params = new URLSearchParams({ product_id: String(productId) })
|
||||||
|
|
||||||
|
const response = await apiClient.patch("/carts", params.toString(), {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (typeof response.data === "object" && response.data.data) {
|
||||||
|
return response.data.data
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof response.data === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(response.data)
|
||||||
|
return parsed.data || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to parse cart response:", error)
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return []
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||||
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
console.error("Remove from cart error:", error.response?.data?.message || error.message)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCleanCart() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
const response = await apiClient.delete("/carts", {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (typeof response.data === "object" && response.data.data) {
|
||||||
|
return response.data.data
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof response.data === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(response.data)
|
||||||
|
return parsed.data || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to parse cart response:", error)
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return []
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||||
@@ -51,15 +175,40 @@ export function useUpdateCartItemQuantity() {
|
|||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async ({ itemId, quantity }: { itemId: number; quantity: number }) => {
|
mutationFn: async ({ productId, quantity }: { productId: number; quantity: number }) => {
|
||||||
const response = await apiClient.patch<CartItem>(`/api/v1/carts/${itemId}`, {
|
const params = new URLSearchParams({
|
||||||
quantity,
|
product_id: String(productId),
|
||||||
|
product_quantity: String(quantity),
|
||||||
})
|
})
|
||||||
return response.data
|
|
||||||
|
const response = await apiClient.post("/carts", params.toString(), {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (typeof response.data === "object" && response.data.data) {
|
||||||
|
return response.data
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof response.data === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(response.data)
|
||||||
|
return parsed
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to parse update cart response:", error)
|
||||||
|
return { message: "success", data: "Updated cart" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { message: "success", data: "Updated cart" }
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||||
},
|
},
|
||||||
|
onError: (error: any) => {
|
||||||
|
console.error("API update failed:", error.response?.data?.message || error.message)
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +235,36 @@ export function useCreateOrder() {
|
|||||||
queryClient.invalidateQueries({ queryKey: ["orders"] })
|
queryClient.invalidateQueries({ queryKey: ["orders"] })
|
||||||
},
|
},
|
||||||
onError: (error: any) => {
|
onError: (error: any) => {
|
||||||
console.error("[v0] Create order error:", error.response?.data?.message || error.message)
|
console.error("Create order error:", error.response?.data?.message || error.message)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
import type { Region } from "@/lib/types/api"
|
||||||
|
|
||||||
|
export function useRegions() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["regions"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await apiClient.get<Region[]>("/api/v1/provinces")
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
staleTime: 1000 * 60 * 60, // 1 hour
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import type { Address } from "@/lib/types/api"
|
||||||
|
|
||||||
|
export function useAddresses() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["addresses"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await apiClient.get<Address[]>("/api/v1/addresses")
|
||||||
|
return response.data
|
||||||
|
},
|
||||||
|
staleTime: 1000 * 60 * 30, // 30 minutes
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -92,6 +92,8 @@ export function useAllCategoryProducts(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Get products from category and children WITH pagination (mimics RTK getAllCategoryProductsPaginated)
|
// Get products from category and children WITH pagination (mimics RTK getAllCategoryProductsPaginated)
|
||||||
export function useAllCategoryProductsPaginated(
|
export function useAllCategoryProductsPaginated(
|
||||||
category: Category | undefined,
|
category: Category | undefined,
|
||||||
@@ -156,3 +158,4 @@ export function useAllCategoryProductsPaginated(
|
|||||||
enabled: options?.enabled !== false && !!category,
|
enabled: options?.enabled !== false && !!category,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,42 +1,112 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { apiClient } from "@/lib/api"
|
import { apiClient } from "@/lib/api";
|
||||||
import type { Favorite } from "@/lib/types/api"
|
import type { Favorite } from "@/lib/types/api";
|
||||||
|
|
||||||
|
// Response tiplerini tanımlayalım
|
||||||
|
interface FavoritesResponse {
|
||||||
|
data?: Favorite[];
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FavoriteActionResponse {
|
||||||
|
data?: string | Favorite[];
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response'u transform eden yardımcı fonksiyon
|
||||||
|
function transformFavoritesResponse(response: any): Favorite[] {
|
||||||
|
if (typeof response === "object" && response.data) {
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof response === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(response);
|
||||||
|
return parsed.data || [];
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to parse favorites response:", error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function transformActionResponse(response: any, defaultValue: string): string {
|
||||||
|
if (typeof response === "object" && response.data) {
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof response === "string") {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(response);
|
||||||
|
return parsed.data || defaultValue;
|
||||||
|
} catch (error) {
|
||||||
|
if (response.includes("<!doctype html>")) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
console.error(`Failed to parse favorite response:`, error);
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
export function useFavorites() {
|
export function useFavorites() {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["favorites"],
|
queryKey: ["favorites"],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await apiClient.get<Favorite[]>("/favorites")
|
const response = await apiClient.get("/favorites");
|
||||||
return response.data
|
return transformFavoritesResponse(response.data);
|
||||||
},
|
},
|
||||||
staleTime: 1000 * 60 * 5,
|
staleTime: 1000 * 60 * 5,
|
||||||
retry: 1,
|
retry: 1,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useAddToFavorites() {
|
export function useAddToFavorites() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (productId: number) => {
|
mutationFn: async (productId: number) => {
|
||||||
const response = await apiClient.post<Favorite[]>("/favorites", { product_id: productId })
|
const formData = new URLSearchParams({
|
||||||
return response.data
|
product_id: productId.toString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await apiClient.post("/favorites", formData, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return transformActionResponse(response.data, "Added");
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ["favorites"] })
|
queryClient.invalidateQueries({ queryKey: ["favorites"] });
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useRemoveFromFavorites() {
|
export function useRemoveFromFavorites() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (productId: number) => {
|
mutationFn: async (productId: number) => {
|
||||||
await apiClient.delete(`/favorites/${productId}`)
|
const formData = new URLSearchParams({
|
||||||
|
product_id: productId.toString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await apiClient.post("/favorites", formData, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return transformActionResponse(response.data, "Removed");
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ["favorites"] })
|
queryClient.invalidateQueries({ queryKey: ["favorites"] });
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,59 +1,165 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { apiClient } from "@/lib/api"
|
import { apiClient } from "@/lib/api";
|
||||||
import type { Order, PaginatedResponse } from "@/lib/types/api"
|
import type { Order, PaginatedResponse } from "@/lib/types/api";
|
||||||
|
|
||||||
|
// Response tiplerini tanımlayalım
|
||||||
|
interface OrderResponse {
|
||||||
|
data?: Order | Order[];
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OrderActionResponse {
|
||||||
|
data?: string | Order;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response'u transform eden yardımcı fonksiyonlar
|
||||||
|
function transformOrdersResponse(response: any): Order[] {
|
||||||
|
if (typeof response === "object" && response.data) {
|
||||||
|
return Array.isArray(response.data) ? response.data : [];
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function transformOrderResponse(response: any): Order | null {
|
||||||
|
if (typeof response === "object" && response.data) {
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function transformOrderActionResponse(
|
||||||
|
response: any,
|
||||||
|
defaultValue: string
|
||||||
|
): string | Order {
|
||||||
|
if (response && response.data) {
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isHtmlResponse(response: any): boolean {
|
||||||
|
return typeof response === "string" && response.includes("<!doctype html>");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Orders list query
|
||||||
export function useOrders(options?: { page?: number; perPage?: number }) {
|
export function useOrders(options?: { page?: number; perPage?: number }) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["orders", options?.page],
|
queryKey: ["orders", options?.page],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await apiClient.get<PaginatedResponse<Order>>("/orders", {
|
const response = await apiClient.get("/orders", {
|
||||||
params: {
|
params: {
|
||||||
page: options?.page || 1,
|
page: options?.page || 1,
|
||||||
per_page: options?.perPage || 20,
|
per_page: options?.perPage || 20,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
return response.data.data || response.data
|
return transformOrdersResponse(response.data);
|
||||||
},
|
},
|
||||||
staleTime: 1000 * 60 * 5,
|
staleTime: 1000 * 60 * 5,
|
||||||
retry: 1,
|
retry: 1,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Single order query
|
||||||
export function useOrder(id: number | string) {
|
export function useOrder(id: number | string) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["order", id],
|
queryKey: ["order", id],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await apiClient.get<Order>(`/orders/${id}`)
|
const response = await apiClient.get(`/orders/${id}`);
|
||||||
return response.data
|
return transformOrderResponse(response.data);
|
||||||
},
|
},
|
||||||
enabled: !!id,
|
enabled: !!id,
|
||||||
})
|
staleTime: 1000 * 60 * 5,
|
||||||
|
retry: 1,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Order times query
|
||||||
|
export function useOrderTimes() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["order-times"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await apiClient.get("/order-time");
|
||||||
|
return transformOrdersResponse(response.data);
|
||||||
|
},
|
||||||
|
staleTime: 1000 * 60 * 10,
|
||||||
|
retry: 1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Order payments query
|
||||||
|
export function useOrderPayments() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["order-payments"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await apiClient.get("/order-payments");
|
||||||
|
return transformOrdersResponse(response.data);
|
||||||
|
},
|
||||||
|
staleTime: 1000 * 60 * 10,
|
||||||
|
retry: 1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create/Place order mutation
|
||||||
|
export function useCreateOrder() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (orderData: Record<string, any>) => {
|
||||||
|
try {
|
||||||
|
const formData = new URLSearchParams();
|
||||||
|
|
||||||
|
// Convert orderData to URLSearchParams
|
||||||
|
Object.entries(orderData).forEach(([key, value]) => {
|
||||||
|
if (value !== null && value !== undefined) {
|
||||||
|
formData.append(key, String(value));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await apiClient.post("/orders", formData, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
},
|
||||||
|
validateStatus: (status) => status >= 200 && status < 300,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Check for HTML response
|
||||||
|
if (isHtmlResponse(response.data)) {
|
||||||
|
throw new Error(
|
||||||
|
"Server returned HTML instead of expected response format"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return transformOrderActionResponse(response.data, "Order placed");
|
||||||
|
} catch (error: any) {
|
||||||
|
// Handle HTML error response
|
||||||
|
if (error.response && isHtmlResponse(error.response.data)) {
|
||||||
|
throw new Error(
|
||||||
|
"Server returned HTML instead of expected response format"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["cart"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancel order mutation
|
||||||
export function useCancelOrder() {
|
export function useCancelOrder() {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async (orderId: number) => {
|
mutationFn: async (orderId: number) => {
|
||||||
await apiClient.post(`/orders/${orderId}/cancel`, {})
|
const response = await apiClient.delete(`/orders/${orderId}`);
|
||||||
|
return transformOrderActionResponse(response.data, "Order cancelled");
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: (_, orderId) => {
|
||||||
queryClient.invalidateQueries({ queryKey: ["orders"] })
|
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["order", orderId] });
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
}
|
|
||||||
|
|
||||||
export function useCreateOrder() {
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: async (orderData: any) => {
|
|
||||||
const response = await apiClient.post<Order>("/orders", orderData)
|
|
||||||
return response.data
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ["orders"] })
|
|
||||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,50 +1,216 @@
|
|||||||
import { useQuery } from "@tanstack/react-query"
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { apiClient } from "@/lib/api"
|
import { apiClient } from "@/lib/api";
|
||||||
import type { Product, PaginatedResponse } from "@/lib/types/api"
|
import type { Review, Product, PaginatedResponse } from "@/lib/types/api";
|
||||||
|
|
||||||
interface UseProductsOptions {
|
// Get single review by ID
|
||||||
enabled?: boolean
|
export function useReview(
|
||||||
staleTime?: number
|
reviewId: number | string,
|
||||||
page?: number
|
options?: { enabled?: boolean }
|
||||||
perPage?: number
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["review", reviewId],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await apiClient.get<Review>(`/reviews/${reviewId}`);
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
enabled: options?.enabled !== false && !!reviewId,
|
||||||
|
staleTime: 1000 * 60 * 10,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all reviews with pagination
|
||||||
|
export function useReviews(options?: {
|
||||||
|
enabled?: boolean;
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
}) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["reviews", options?.page, options?.limit],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await apiClient.get<PaginatedResponse<Review>>(
|
||||||
|
`/reviews`,
|
||||||
|
{
|
||||||
|
params: {
|
||||||
|
page: options?.page || 1,
|
||||||
|
limit: options?.limit,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
data: response.data.data || [],
|
||||||
|
pagination: response.data.pagination || {},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
enabled: options?.enabled !== false,
|
||||||
|
staleTime: 1000 * 60 * 5,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get related reviews for a review
|
||||||
|
export function useRelatedReviews(
|
||||||
|
reviewId: number | string,
|
||||||
|
options?: { enabled?: boolean }
|
||||||
|
) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["review", reviewId, "related"],
|
||||||
|
queryFn: async () => {
|
||||||
|
const response = await apiClient.get<PaginatedResponse<Review>>(
|
||||||
|
`/reviews/${reviewId}/related`
|
||||||
|
);
|
||||||
|
return response.data.data || response.data;
|
||||||
|
},
|
||||||
|
enabled: options?.enabled !== false && !!reviewId,
|
||||||
|
staleTime: 1000 * 60 * 15,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useProducts(options?: UseProductsOptions) {
|
export function useProducts(options?: UseProductsOptions) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["products", options?.page, options?.perPage],
|
queryKey: ["products", options?.page, options?.perPage],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await apiClient.get<PaginatedResponse<Product>>("/products", {
|
const response = await apiClient.get<PaginatedResponse<Product>>(
|
||||||
params: {
|
"/products",
|
||||||
page: options?.page || 1,
|
{
|
||||||
per_page: options?.perPage || 20,
|
params: {
|
||||||
},
|
page: options?.page || 1,
|
||||||
})
|
per_page: options?.perPage || 20,
|
||||||
return response.data.data || response.data
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return response.data.data || response.data;
|
||||||
},
|
},
|
||||||
staleTime: options?.staleTime ?? 1000 * 60 * 5, // 5 minutes
|
staleTime: options?.staleTime ?? 1000 * 60 * 5,
|
||||||
enabled: options?.enabled !== false,
|
enabled: options?.enabled !== false,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useProduct(id: number | string, options?: { enabled?: boolean }) {
|
// Get single product by ID (for review context)
|
||||||
|
export function useProduct(
|
||||||
|
productId: number | string,
|
||||||
|
options?: { enabled?: boolean }
|
||||||
|
) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["product", id],
|
queryKey: ["product", productId],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await apiClient.get<Product>(`/products/${id}`)
|
const response = await apiClient.get<Product>(`/products/${productId}`);
|
||||||
return response.data
|
return response.data;
|
||||||
},
|
},
|
||||||
staleTime: 1000 * 60 * 10, // 10 minutes
|
enabled: options?.enabled !== false && !!productId,
|
||||||
enabled: options?.enabled !== false && !!id,
|
staleTime: 1000 * 60 * 10,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useProductsBySlug(slug: string, options?: { enabled?: boolean }) {
|
export function useProductsBySlug(
|
||||||
|
slug: string,
|
||||||
|
options?: { enabled?: boolean }
|
||||||
|
) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["products", "slug", slug],
|
queryKey: ["products", "slug", slug],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const response = await apiClient.get<Product>(`/products/${slug}`)
|
const response = await apiClient.get(`/products/${slug}`);
|
||||||
return response.data
|
// API returns { message: "success", data: {...} }
|
||||||
|
return response.data.data || response.data;
|
||||||
},
|
},
|
||||||
enabled: options?.enabled !== false && !!slug,
|
enabled: options?.enabled !== false && !!slug,
|
||||||
})
|
staleTime: 1000 * 60 * 10,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Submit review mutation
|
||||||
|
export function useSubmitReview() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async ({
|
||||||
|
productId,
|
||||||
|
rating,
|
||||||
|
title,
|
||||||
|
source,
|
||||||
|
}: {
|
||||||
|
productId: number | string;
|
||||||
|
rating: number;
|
||||||
|
title: string;
|
||||||
|
source: string;
|
||||||
|
}) => {
|
||||||
|
const response = await apiClient.post<Review>(
|
||||||
|
`/products/${productId}/reviews`,
|
||||||
|
{ rating, title, source },
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
onSuccess: (_, variables) => {
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["reviews", "product", variables.productId],
|
||||||
|
});
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["product", variables.productId],
|
||||||
|
});
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["reviews"],
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update review mutation
|
||||||
|
export function useUpdateReview() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async ({
|
||||||
|
reviewId,
|
||||||
|
rating,
|
||||||
|
title,
|
||||||
|
source,
|
||||||
|
}: {
|
||||||
|
reviewId: number | string;
|
||||||
|
rating?: number;
|
||||||
|
title?: string;
|
||||||
|
source?: string;
|
||||||
|
}) => {
|
||||||
|
const response = await apiClient.put<Review>(
|
||||||
|
`/reviews/${reviewId}`,
|
||||||
|
{ rating, title, source },
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
onSuccess: (data, variables) => {
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["review", variables.reviewId],
|
||||||
|
});
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["reviews"],
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete review mutation
|
||||||
|
export function useDeleteReview() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (reviewId: number | string) => {
|
||||||
|
const response = await apiClient.delete(`/reviews/${reviewId}`);
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
onSuccess: (_, reviewId) => {
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["review", reviewId],
|
||||||
|
});
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ["reviews"],
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
import { useQuery } from "@tanstack/react-query"
|
|
||||||
import { apiClient } from "@/lib/api"
|
|
||||||
import type { Region } from "@/lib/types/api"
|
|
||||||
|
|
||||||
export function useRegions() {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: ["regions"],
|
|
||||||
queryFn: async () => {
|
|
||||||
const response = await apiClient.get<Region[]>("/api/v1/regions")
|
|
||||||
return response.data
|
|
||||||
},
|
|
||||||
staleTime: 1000 * 60 * 60, // 1 hour
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,23 +4,65 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// Product Types
|
// Product Types
|
||||||
|
export interface ProductMedia {
|
||||||
|
thumbnail: string
|
||||||
|
images_400x400: string
|
||||||
|
images_720x720: string
|
||||||
|
images_800x800: string
|
||||||
|
images_1200x1200: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProductProperty {
|
||||||
|
attribute_id: number
|
||||||
|
name: string
|
||||||
|
value: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProductReviews {
|
||||||
|
count: number
|
||||||
|
rating: string
|
||||||
|
}
|
||||||
|
|
||||||
export interface Product {
|
export interface Product {
|
||||||
id: number
|
id: number
|
||||||
|
parent_id: number | null
|
||||||
name: string
|
name: string
|
||||||
slug?: string
|
slug: string
|
||||||
price: number
|
|
||||||
description: string
|
description: string
|
||||||
image: string
|
sku: string | null
|
||||||
images?: string[]
|
barcode: string
|
||||||
category: string
|
stock: number
|
||||||
brand?: string
|
price_amount: string
|
||||||
stock?: number
|
old_price_amount: string | null
|
||||||
rating?: number
|
backorder: string
|
||||||
reviews_count?: number
|
weight_value: number | null
|
||||||
is_favorite?: boolean
|
weight_unit: string | null
|
||||||
is_in_cart?: boolean
|
height_value: number | null
|
||||||
labels?: Array<{ text: string; bg_color: string }>
|
height_unit: string | null
|
||||||
struct_price_text?: string
|
media: ProductMedia[]
|
||||||
|
created_at: string
|
||||||
|
seo_title: string | null
|
||||||
|
seo_description: string | null
|
||||||
|
colour: string | null
|
||||||
|
size: string | null
|
||||||
|
available_colors: string[]
|
||||||
|
available_sizes: string[]
|
||||||
|
brand: {
|
||||||
|
id: number | null
|
||||||
|
name: string | null
|
||||||
|
}
|
||||||
|
channel: Array<{
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
}>
|
||||||
|
properties: ProductProperty[]
|
||||||
|
variations: any[]
|
||||||
|
reviews: ProductReviews
|
||||||
|
reviews_resources: any[]
|
||||||
|
categories: Array<{
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
}>
|
||||||
}
|
}
|
||||||
|
|
||||||
// Category Types
|
// Category Types
|
||||||
@@ -193,3 +235,5 @@ export interface CreateOrderPayload {
|
|||||||
region: string
|
region: string
|
||||||
note?: string
|
note?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -12,8 +12,13 @@ const nextConfig: NextConfig = {
|
|||||||
},
|
},
|
||||||
images: {
|
images: {
|
||||||
unoptimized: true,
|
unoptimized: true,
|
||||||
|
remotePatterns: [
|
||||||
|
{
|
||||||
|
protocol: "https",
|
||||||
|
hostname: "shop.post.tm",
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
/* config options here */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default withNextIntl(nextConfig)
|
export default withNextIntl(nextConfig)
|
||||||
|
|||||||
Reference in New Issue
Block a user