connected api with profile, order
This commit is contained in:
176
features/cart/components/CartItemCard.tsx
Normal file
176
features/cart/components/CartItemCard.tsx
Normal file
@@ -0,0 +1,176 @@
|
||||
"use client"
|
||||
import { useState, useEffect, useRef } from "react"
|
||||
import Image from "next/image"
|
||||
import { Minus, Plus, Trash2 } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { useUpdateCartItemQuantity, useRemoveFromCart } from "@/lib/hooks"
|
||||
import type { CartItem, CartTranslations } from "./types"
|
||||
|
||||
interface CartItemCardProps {
|
||||
item: CartItem
|
||||
translations: CartTranslations
|
||||
onUpdate?: () => void
|
||||
}
|
||||
|
||||
export default function CartItemCard({ 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()
|
||||
|
||||
useEffect(() => {
|
||||
setLocalQuantity(item.quantity)
|
||||
setPendingQuantity(item.quantity)
|
||||
}, [item.quantity])
|
||||
|
||||
useEffect(() => {
|
||||
if (pendingQuantity === item.quantity) return
|
||||
|
||||
if (updateTimeoutRef.current) {
|
||||
clearTimeout(updateTimeoutRef.current)
|
||||
}
|
||||
|
||||
updateTimeoutRef.current = setTimeout(() => {
|
||||
setIsLoading(true)
|
||||
|
||||
if (pendingQuantity <= 0) {
|
||||
removeItem(item.product_id, {
|
||||
onSuccess: () => onUpdate?.(),
|
||||
onError: () => {
|
||||
setLocalQuantity(item.quantity)
|
||||
setPendingQuantity(item.quantity)
|
||||
},
|
||||
onSettled: () => setIsLoading(false),
|
||||
})
|
||||
} else {
|
||||
updateQuantity(
|
||||
{ productId: item.product_id, quantity: pendingQuantity },
|
||||
{
|
||||
onSuccess: () => onUpdate?.(),
|
||||
onError: () => {
|
||||
setLocalQuantity(item.quantity)
|
||||
setPendingQuantity(item.quantity)
|
||||
},
|
||||
onSettled: () => setIsLoading(false),
|
||||
}
|
||||
)
|
||||
}
|
||||
}, 300)
|
||||
|
||||
return () => {
|
||||
if (updateTimeoutRef.current) {
|
||||
clearTimeout(updateTimeoutRef.current)
|
||||
}
|
||||
}
|
||||
}, [pendingQuantity, item.quantity, item.product_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 = () => {
|
||||
setIsLoading(true)
|
||||
removeItem(item.product_id, {
|
||||
onSuccess: () => onUpdate?.(),
|
||||
onSettled: () => setIsLoading(false),
|
||||
})
|
||||
}
|
||||
|
||||
const getImageSrc = () => {
|
||||
if (item.product.image) return item.product.image
|
||||
if (item.product.images?.length > 0) return item.product.images[0]
|
||||
return "/placeholder.svg"
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="p-4 shadow-none border">
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="flex gap-4 flex-1">
|
||||
<div className="relative w-[88px] h-[117px] rounded-xl border overflow-hidden flex-shrink-0">
|
||||
<Image src={getImageSrc()} alt={item.product.name} fill className="object-contain" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<h3 className="font-semibold text-base">{item.product.name}</h3>
|
||||
<p className="text-sm text-gray-600">{item.seller?.name || "Store"}</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleDelete}
|
||||
disabled={isRemoving || isLoading}
|
||||
className="w-fit p-0 h-auto hover:bg-transparent hover:text-red-500"
|
||||
>
|
||||
<Trash2 className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between">
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold">
|
||||
{t.pricePerUnit} <span className="text-primary">{item.price_formatted}</span>
|
||||
</p>
|
||||
<p className="text-sm font-semibold">
|
||||
{t.additionalPrice} {item.sub_total_formatted}
|
||||
</p>
|
||||
{item.discount_formatted && item.discount_formatted !== "0 TMT" && (
|
||||
<p className="text-sm font-semibold">{t.discount} {item.discount_formatted}</p>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-semibold">{t.totalPrice}</span>
|
||||
<span className="bg-green-500 text-white px-3 py-1 rounded-xl font-semibold text-base">
|
||||
{item.total_formatted}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleQuantityDecrease}
|
||||
disabled={isLoading || isRemoving}
|
||||
className="rounded-xl bg-blue-50"
|
||||
>
|
||||
<Minus className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="w-12 text-center font-semibold">{localQuantity}</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleQuantityIncrease}
|
||||
disabled={isLoading || isRemoving}
|
||||
className="rounded-xl bg-blue-50"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
57
features/cart/components/DeliveryTypeSelector.tsx
Normal file
57
features/cart/components/DeliveryTypeSelector.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
"use client"
|
||||
import { Truck, Warehouse } from "lucide-react"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { DeliveryType, CartTranslations } from "../types"
|
||||
|
||||
interface DeliveryTypeSelectorProps {
|
||||
selectedType: DeliveryType
|
||||
onSelect: (type: DeliveryType) => void
|
||||
translations: CartTranslations
|
||||
}
|
||||
|
||||
export default function DeliveryTypeSelector({
|
||||
selectedType,
|
||||
onSelect,
|
||||
translations: t,
|
||||
}: DeliveryTypeSelectorProps) {
|
||||
const deliveryOptions: {
|
||||
type: DeliveryType
|
||||
label: string
|
||||
icon: typeof Truck
|
||||
}[] = [
|
||||
{ type: "SELECTED_DELIVERY", label: t.delivery, icon: Truck },
|
||||
{ type: "PICK_UP", label: t.pickup, icon: Warehouse },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-semibold mb-3">{t.deliveryType}</h3>
|
||||
<div className="flex gap-2">
|
||||
{deliveryOptions.map(({ type, label, icon: Icon }) => (
|
||||
<Card
|
||||
key={type}
|
||||
className={`flex-1 cursor-pointer transition-all hover:shadow-md ${
|
||||
selectedType === type
|
||||
? "border-2 border-[#005bff] bg-blue-50"
|
||||
: "border-2 border-gray-200"
|
||||
}`}
|
||||
onClick={() => onSelect(type)}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center p-4 gap-2">
|
||||
<Icon
|
||||
className={`h-8 w-8 ${
|
||||
selectedType === type ? "text-[#005bff]" : "text-gray-600"
|
||||
}`}
|
||||
/>
|
||||
<span className={`text-xs font-medium ${
|
||||
selectedType === type ? "text-[#005bff]" : "text-gray-700"
|
||||
}`}>
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
176
features/cart/components/OrderSummary.tsx
Normal file
176
features/cart/components/OrderSummary.tsx
Normal file
@@ -0,0 +1,176 @@
|
||||
"use client"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import DeliveryTypeSelector from "./DeliveryTypeSelector"
|
||||
import type { Order, Province, DeliveryType, CartTranslations, PaymentType } from "../types"
|
||||
|
||||
interface OrderSummaryProps {
|
||||
order: Order
|
||||
translations: CartTranslations
|
||||
paymentType: PaymentType | null
|
||||
deliveryType: DeliveryType
|
||||
selectedRegion: string
|
||||
selectedProvince: number | null
|
||||
note: string
|
||||
regionGroups: Record<string, Province[]>
|
||||
availableRegions: string[]
|
||||
paymentTypes: PaymentType[]
|
||||
onPaymentTypeChange: (type: PaymentType) => void
|
||||
onDeliveryTypeChange: (type: DeliveryType) => void
|
||||
onRegionChange: (regionCode: string) => void
|
||||
onProvinceChange: (provinceId: number) => void
|
||||
onNoteChange: (note: string) => void
|
||||
onCompleteOrder: () => void
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
export default function OrderSummary({
|
||||
order,
|
||||
translations: t,
|
||||
paymentType,
|
||||
deliveryType,
|
||||
selectedRegion,
|
||||
selectedProvince,
|
||||
note,
|
||||
regionGroups,
|
||||
availableRegions,
|
||||
paymentTypes,
|
||||
onPaymentTypeChange,
|
||||
onDeliveryTypeChange,
|
||||
onRegionChange,
|
||||
onProvinceChange,
|
||||
onNoteChange,
|
||||
onCompleteOrder,
|
||||
isLoading,
|
||||
}: OrderSummaryProps) {
|
||||
const provincesForSelectedRegion = selectedRegion ? regionGroups[selectedRegion] || [] : []
|
||||
const isFormValid = selectedRegion && selectedProvince && paymentType
|
||||
|
||||
return (
|
||||
<Card className="w-full md:w-[380px] p-6 rounded-xl h-fit sticky top-20">
|
||||
{/* Payment Type */}
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-semibold mb-3">{t.paymentType}</h3>
|
||||
<div className="flex gap-2">
|
||||
{paymentTypes.map((type) => (
|
||||
<Card
|
||||
key={type.id}
|
||||
className={`flex-1 cursor-pointer transition-all ${
|
||||
paymentType?.id === type.id
|
||||
? "border-2 border-[#005bff] bg-blue-50"
|
||||
: "border-2 border-gray-200"
|
||||
}`}
|
||||
onClick={() => onPaymentTypeChange(type)}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center p-4 gap-2">
|
||||
<span className={`text-xs font-medium ${
|
||||
paymentType?.id === type.id ? "text-[#005bff]" : ""
|
||||
}`}>
|
||||
{type.name}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Delivery Type */}
|
||||
<DeliveryTypeSelector
|
||||
selectedType={deliveryType}
|
||||
onSelect={onDeliveryTypeChange}
|
||||
translations={t}
|
||||
/>
|
||||
|
||||
{/* Region Selection */}
|
||||
<div className="mb-6">
|
||||
<Label className="text-lg font-semibold mb-3 block">{t.selectRegion}</Label>
|
||||
<RadioGroup
|
||||
value={selectedRegion}
|
||||
onValueChange={(value) => {
|
||||
onRegionChange(value)
|
||||
onProvinceChange(null as any)
|
||||
}}
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
{availableRegions.map((regionCode) => (
|
||||
<div key={regionCode} className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value={regionCode}
|
||||
id={`region-${regionCode}`}
|
||||
className="border-2 border-gray-400 data-[state=checked]:border-[#005bff] data-[state=checked]:bg-white"
|
||||
/>
|
||||
<Label htmlFor={`region-${regionCode}`} className="cursor-pointer uppercase">
|
||||
{regionCode}
|
||||
</Label>
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
{/* Province Selection */}
|
||||
{selectedRegion && provincesForSelectedRegion.length > 0 && (
|
||||
<div className="mb-6">
|
||||
<Label className="text-lg font-semibold mb-3 block">{t.selectAddress}</Label>
|
||||
<Select
|
||||
value={selectedProvince?.toString() || ""}
|
||||
onValueChange={(value) => onProvinceChange(parseInt(value))}
|
||||
>
|
||||
<SelectTrigger className="rounded-xl">
|
||||
<SelectValue placeholder={t.selectAddress} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{provincesForSelectedRegion.map((province) => (
|
||||
<SelectItem key={province.id} value={province.id.toString()}>
|
||||
{province.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Note */}
|
||||
<div className="mb-6">
|
||||
<Label className="text-lg font-semibold mb-3 block">{t.note}</Label>
|
||||
<Textarea
|
||||
value={note}
|
||||
onChange={(e) => onNoteChange(e.target.value)}
|
||||
className="rounded-xl resize-none"
|
||||
rows={3}
|
||||
placeholder={t.note}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Billing */}
|
||||
<div className="space-y-2 mb-4">
|
||||
{order.billing.body.map((item, index) => (
|
||||
<div key={index} className="flex justify-between text-base font-medium">
|
||||
<span>{item.title}:</span>
|
||||
<span>{item.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Separator className="my-4" />
|
||||
|
||||
<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-bold text-green-600">{order.billing.footer.value}</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={onCompleteOrder}
|
||||
disabled={!isFormValid || isLoading}
|
||||
className="w-full rounded-xl bg-[#005bff] hover:bg-[#004dcc] h-12 text-lg font-bold disabled:opacity-50"
|
||||
size="lg"
|
||||
>
|
||||
{isLoading ? `${t.placeOrder}...` : t.placeOrder}
|
||||
</Button>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
49
features/cart/components/PaymentTypeSelector.tsx
Normal file
49
features/cart/components/PaymentTypeSelector.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import React from "react";
|
||||
import { CreditCard } from "lucide-react";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { PaymentType, CartTranslations } from "./types";
|
||||
|
||||
interface PaymentTypeSelectorProps {
|
||||
selectedType: PaymentType;
|
||||
onSelect: (type: PaymentType) => void;
|
||||
translations: CartTranslations;
|
||||
}
|
||||
|
||||
export default function PaymentTypeSelector({
|
||||
selectedType,
|
||||
onSelect,
|
||||
translations: t,
|
||||
}: PaymentTypeSelectorProps) {
|
||||
const paymentOptions: { type: PaymentType; label: string }[] = [
|
||||
{ type: "CASH", label: t.cash },
|
||||
{ type: "CARD", label: t.card },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-semibold mb-3">{t.paymentType}</h3>
|
||||
<div className="flex gap-2">
|
||||
{paymentOptions.map(({ type, label }) => (
|
||||
<Card
|
||||
key={type}
|
||||
className={`flex-1 cursor-pointer transition-all ${
|
||||
selectedType === type
|
||||
? "border-2 border-[#005bff]"
|
||||
: "border-2 border-gray-200"
|
||||
}`}
|
||||
onClick={() => onSelect(type)}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center p-4 gap-2">
|
||||
<CreditCard
|
||||
className={`h-8 w-8 ${
|
||||
selectedType === type ? "text-[#005bff]" : ""
|
||||
}`}
|
||||
/>
|
||||
<span className="text-xs">{label}</span>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
25
features/cart/hooks/useAddresses.ts
Normal file
25
features/cart/hooks/useAddresses.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { apiClient } from "@/lib/api"
|
||||
|
||||
interface Province {
|
||||
id: number
|
||||
region: string
|
||||
name: string
|
||||
}
|
||||
|
||||
interface ProvincesResponse {
|
||||
message: string
|
||||
data: Province[]
|
||||
}
|
||||
|
||||
export function useRegions() {
|
||||
return useQuery({
|
||||
queryKey: ["regions"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<ProvincesResponse>("/provinces")
|
||||
return response.data.data
|
||||
},
|
||||
staleTime: 1000 * 60 * 60, // 1 hour
|
||||
})
|
||||
}
|
||||
|
||||
248
features/cart/hooks/useCart.ts
Normal file
248
features/cart/hooks/useCart.ts
Normal file
@@ -0,0 +1,248 @@
|
||||
import { useQuery, useMutation, useQueryClient, UseQueryOptions } from "@tanstack/react-query"
|
||||
import { apiClient } from "@/lib/api"
|
||||
import type { CartItem } from "@/lib/types/api"
|
||||
|
||||
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({
|
||||
queryKey: ["cart"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get("/carts")
|
||||
return transformCartResponse(response.data)
|
||||
},
|
||||
refetchInterval: 5000, // Poll every 5 seconds like RTK
|
||||
refetchOnMount: true,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: true,
|
||||
staleTime: 0,
|
||||
retry: 1,
|
||||
...options,
|
||||
})
|
||||
}
|
||||
|
||||
export function useAddToCart() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ productId, quantity = 1 }: { productId: number; quantity?: number }) => {
|
||||
const params = new URLSearchParams({
|
||||
product_id: String(productId),
|
||||
product_quantity: String(quantity),
|
||||
})
|
||||
|
||||
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: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Add to cart error:", error.response?.data?.message || error.message)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useRemoveFromCart() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (productId: number) => {
|
||||
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: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdateCartItemQuantity() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ productId, quantity }: { productId: number; quantity: number }) => {
|
||||
const params = new URLSearchParams({
|
||||
product_id: String(productId),
|
||||
product_quantity: String(quantity),
|
||||
})
|
||||
|
||||
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: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("API update failed:", error.response?.data?.message || error.message)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useCreateOrder() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (payload: {
|
||||
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
|
||||
}) => {
|
||||
const response = await apiClient.post("/orders", payload)
|
||||
return response.data
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"] })
|
||||
queryClient.invalidateQueries({ queryKey: ["orders"] })
|
||||
},
|
||||
onError: (error: any) => {
|
||||
console.error("Create order error:", error.response?.data?.message || error.message)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
23
features/cart/hooks/usePaymentTypes.ts
Normal file
23
features/cart/hooks/usePaymentTypes.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { apiClient } from "@/lib/api"
|
||||
|
||||
interface PaymentType {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
interface PaymentTypesResponse {
|
||||
message: string
|
||||
data: PaymentType[]
|
||||
}
|
||||
|
||||
export function usePaymentTypes() {
|
||||
return useQuery({
|
||||
queryKey: ["paymentTypes"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<PaymentTypesResponse>("/order-payments")
|
||||
return response.data.data
|
||||
},
|
||||
staleTime: 1000 * 60 * 60, // 1 hour
|
||||
})
|
||||
}
|
||||
171
features/cart/types.ts
Normal file
171
features/cart/types.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import type { StaticImageData } from "next/image";
|
||||
|
||||
export interface Cart {
|
||||
message: string;
|
||||
data: CartItem[];
|
||||
errorDetails?: string;
|
||||
total?: number;
|
||||
total_formatted?: string;
|
||||
items?: CartItem[]; // Alternative structure
|
||||
}
|
||||
|
||||
export interface Order {
|
||||
id: number;
|
||||
seller: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
items: CartItem[];
|
||||
billing: {
|
||||
body: Array<{ title: string; value: string }>;
|
||||
footer: { title: string; value: string };
|
||||
};
|
||||
}
|
||||
|
||||
export interface Region {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Address {
|
||||
id: number;
|
||||
title: string;
|
||||
region_id: number;
|
||||
address: string;
|
||||
phone?: string;
|
||||
is_default?: boolean;
|
||||
}
|
||||
|
||||
export interface PickUpPoint {
|
||||
id: number;
|
||||
name: string;
|
||||
address: string;
|
||||
}
|
||||
|
||||
export interface PaymentTypeOption {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
export interface CartTranslations {
|
||||
cart: string;
|
||||
ordersIn: string;
|
||||
pricePerUnit: string;
|
||||
additionalPrice: string;
|
||||
discount: string;
|
||||
totalPrice: string;
|
||||
paymentType: string;
|
||||
cash: string;
|
||||
card: string;
|
||||
deliveryType: string;
|
||||
delivery: string;
|
||||
pickup: string;
|
||||
selectRegion: string;
|
||||
selectAddress: string;
|
||||
note: string;
|
||||
placeOrder: string;
|
||||
emptyCart: string;
|
||||
map: string;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
export interface CartItem {
|
||||
id: number;
|
||||
product_id: number;
|
||||
product: {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string;
|
||||
media?: Array<{ images_800x800?: string; thumbnail?: string }>;
|
||||
channel?: Array<{ id: number; name: string }>;
|
||||
price_amount?: string;
|
||||
stock?: number;
|
||||
};
|
||||
product_quantity: number;
|
||||
quantity?: number; // For compatibility
|
||||
seller?: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
price?: number;
|
||||
total?: number;
|
||||
price_formatted?: string;
|
||||
sub_total_formatted?: string;
|
||||
discount_formatted?: string;
|
||||
total_formatted?: string;
|
||||
}
|
||||
|
||||
export interface Province {
|
||||
id: number;
|
||||
region: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface PaymentType {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Order {
|
||||
id: number;
|
||||
seller: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
items: CartItem[];
|
||||
billing: {
|
||||
body: Array<{ title: string; value: string }>;
|
||||
footer: { title: string; value: string };
|
||||
};
|
||||
}
|
||||
|
||||
export interface CartTranslations {
|
||||
cart: string;
|
||||
ordersIn: string;
|
||||
pricePerUnit: string;
|
||||
additionalPrice: string;
|
||||
discount: string;
|
||||
totalPrice: string;
|
||||
paymentType: string;
|
||||
cash: string;
|
||||
card: string;
|
||||
deliveryType: string;
|
||||
delivery: string;
|
||||
pickup: string;
|
||||
selectRegion: string;
|
||||
selectAddress: string;
|
||||
note: string;
|
||||
placeOrder: string;
|
||||
emptyCart: string;
|
||||
map: string;
|
||||
}
|
||||
|
||||
export type DeliveryType = "SELECTED_DELIVERY" | "PICK_UP";
|
||||
|
||||
export interface CreateOrderPayload {
|
||||
customer_address: string;
|
||||
shipping_method: string;
|
||||
payment_type_id: number;
|
||||
region: string;
|
||||
note?: string;
|
||||
}
|
||||
629
features/category/components/CategoryClient.tsx
Normal file
629
features/category/components/CategoryClient.tsx
Normal file
@@ -0,0 +1,629 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useMemo, useCallback } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { ChevronLeft, SlidersHorizontal, X } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Slider } from "@/components/ui/slider";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@/components/ui/sheet";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import InfiniteScroll from "react-infinite-scroll-component";
|
||||
import ProductCard from "@/components/ProductCard";
|
||||
import Loader from "@/components/Loader";
|
||||
import {
|
||||
useCategories,
|
||||
useAllCategoryProducts,
|
||||
useAllCategoryProductsPaginated,
|
||||
useCategoryProducts,
|
||||
} from "@/features/category/hooks/useCategories";
|
||||
import { notFound } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import type { Category, Product } from "@/lib/types/api";
|
||||
|
||||
interface CategoryPageClientProps {
|
||||
params: { locale: string; slug: string };
|
||||
}
|
||||
|
||||
export default function CategoryPageClient({
|
||||
params,
|
||||
}: CategoryPageClientProps) {
|
||||
const { slug, locale } = params;
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const t = useTranslations();
|
||||
|
||||
// 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
|
||||
const [priceRange, setPriceRange] = useState<[number, number]>([0, 10000]);
|
||||
|
||||
// Selected filters state
|
||||
const [selectedFilters, setSelectedFilters] = useState<Record<string, Set<number>>>({
|
||||
brand: new Set(),
|
||||
color: 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,
|
||||
});
|
||||
|
||||
|
||||
|
||||
if (!slug) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// Helper function to find category by ID
|
||||
const findCategoryById = (
|
||||
categories: Category[] | undefined,
|
||||
id: number
|
||||
): Category | null => {
|
||||
if (!categories) return null;
|
||||
|
||||
for (const category of categories) {
|
||||
if (category.id === id) return category;
|
||||
if (category.children) {
|
||||
const found = findCategoryById(category.children, id);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// Helper to check if product already exists in list
|
||||
const isProductInList = (list: Product[], newProduct: Product) => {
|
||||
return list.some((product) => product.id === newProduct.id);
|
||||
};
|
||||
|
||||
// Setup subcategories when category changes
|
||||
useEffect(() => {
|
||||
if (selectedCategory) {
|
||||
// Reset states
|
||||
setAllProducts([]);
|
||||
setHasMore(true);
|
||||
setCurrentPage(1);
|
||||
|
||||
// Set subcategories
|
||||
if (selectedCategory.children && selectedCategory.children.length > 0) {
|
||||
setHasSubcategories(true);
|
||||
setSubcategoriesToShow(selectedCategory.children);
|
||||
} else {
|
||||
setHasSubcategories(false);
|
||||
setSubcategoriesToShow([]);
|
||||
}
|
||||
}
|
||||
}, [selectedCategory?.id]);
|
||||
|
||||
// Handle first page products for subcategories
|
||||
useEffect(() => {
|
||||
if (
|
||||
selectedCategory &&
|
||||
isSubCategory &&
|
||||
subcategoryProducts.length > 0 &&
|
||||
currentPage === 1
|
||||
) {
|
||||
console.log("Setting subcategory products:", subcategoryProducts.length);
|
||||
setAllProducts(subcategoryProducts);
|
||||
setHasMore(true);
|
||||
}
|
||||
}, [selectedCategory, subcategoryProducts, currentPage, isSubCategory]);
|
||||
|
||||
// Handle paginated category products (non-subcategories) - FIXED
|
||||
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];
|
||||
});
|
||||
|
||||
// FIXED: Check next_page_url instead of pagination object existence
|
||||
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) {
|
||||
console.log("Cannot load more:", { hasMore, categoryPaginatedFetching, subcategoryPaginatedLoading });
|
||||
return;
|
||||
}
|
||||
console.log("Loading more, current page:", currentPage, "next 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 || t("category");
|
||||
|
||||
const handleFilterChange = (key: string, value: number) => {
|
||||
setSelectedFilters((prev) => {
|
||||
const newFilters = { ...prev };
|
||||
if (!newFilters[key]) {
|
||||
newFilters[key] = new Set();
|
||||
}
|
||||
|
||||
if (newFilters[key].has(value)) {
|
||||
newFilters[key].delete(value);
|
||||
} else {
|
||||
newFilters[key].add(value);
|
||||
}
|
||||
|
||||
return newFilters;
|
||||
});
|
||||
};
|
||||
|
||||
const handlePriceChange = (values: number[]) => {
|
||||
setPriceRange([values[0], values[1]]);
|
||||
};
|
||||
|
||||
const handlePriceInputChange = (type: "from" | "to", value: string) => {
|
||||
const numValue = parseInt(value) || 0;
|
||||
if (type === "from") {
|
||||
setPriceRange([numValue, priceRange[1]]);
|
||||
} else {
|
||||
setPriceRange([priceRange[0], numValue]);
|
||||
}
|
||||
};
|
||||
|
||||
const resetFilters = () => {
|
||||
setSelectedFilters({
|
||||
brand: new Set(),
|
||||
color: new Set(),
|
||||
tag: new Set(),
|
||||
});
|
||||
setPriceRange([0, 10000]);
|
||||
setPriceSort("none");
|
||||
};
|
||||
|
||||
const FiltersContent = () => (
|
||||
<div className="space-y-6">
|
||||
{hasSubcategories && subcategoriesToShow.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-3">{t("subcategories")}</h3>
|
||||
<div className="space-y-1">
|
||||
{subcategoriesToShow.map((subCategory) => (
|
||||
<button
|
||||
key={subCategory.id}
|
||||
onClick={() => handleSubCategorySelect(subCategory)}
|
||||
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"
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
{subCategory.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-3">{t("composition")}</h3>
|
||||
<div className="space-y-2">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="sort"
|
||||
checked={priceSort === "none"}
|
||||
onChange={() => handlePriceSortChange("none")}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<span>{t("neverMind")}</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="sort"
|
||||
checked={priceSort === "lowToHigh"}
|
||||
onChange={() => handlePriceSortChange("lowToHigh")}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<span>{t("fromCheapToExpensive")}</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="sort"
|
||||
checked={priceSort === "highToLow"}
|
||||
onChange={() => handlePriceSortChange("highToLow")}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<span>{t("fromExpensiveToHigh")}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PriceFilter
|
||||
title={t("price")}
|
||||
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")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (isLoading) return <div>{t("loading") || "Ýüklenýär..."}</div>;
|
||||
|
||||
if (!selectedCategory && !categoriesLoading) {
|
||||
return <div className="text-center py-8">Bölüm tapylmady</div>;
|
||||
}
|
||||
|
||||
console.log(
|
||||
"Current state - products:",
|
||||
products.length,
|
||||
"hasMore:",
|
||||
hasMore,
|
||||
"page:",
|
||||
currentPage,
|
||||
"isFetching:",
|
||||
categoryPaginatedFetching
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{selectedCategory && renderBreadcrumbs()}
|
||||
<h2 className="text-3xl font-bold">{pageTitle}</h2>
|
||||
<p className="text-gray-600">
|
||||
{t("total")}: {totalItems} {t("items")}
|
||||
</p>
|
||||
|
||||
<div className="flex gap-4">
|
||||
{/* Desktop Filters - LEFT SIDE */}
|
||||
<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>Ýüklenýär...</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("nResults")}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mobile Filter Sheet */}
|
||||
<Sheet open={isOpen} onOpenChange={setIsOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
className="sm:hidden fixed bottom-20 right-4 rounded-xl font-bold gap-2 z-10 shadow-lg"
|
||||
size="lg"
|
||||
>
|
||||
{t("filter")}
|
||||
<SlidersHorizontal className="h-5 w-5" />
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="left" className="w-[290px] p-0">
|
||||
<SheetHeader className="p-4 border-b">
|
||||
<SheetTitle>{t("filter")}</SheetTitle>
|
||||
<button
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="absolute top-4 right-4 rounded-md ring-offset-background transition-opacity hover:opacity-100"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Ýap</span>
|
||||
</button>
|
||||
</SheetHeader>
|
||||
<ScrollArea className="h-[calc(100vh-80px)] p-4">
|
||||
<FiltersContent />
|
||||
</ScrollArea>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PriceFilter({
|
||||
title,
|
||||
priceRange,
|
||||
onPriceChange,
|
||||
onInputChange,
|
||||
translations,
|
||||
}: {
|
||||
title: string;
|
||||
priceRange: [number, number];
|
||||
onPriceChange: (values: number[]) => void;
|
||||
onInputChange: (type: "from" | "to", value: string) => void;
|
||||
translations: { from: string; to: string };
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-3">{title}</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="price-from" className="text-xs mb-1">
|
||||
{translations.from}
|
||||
</Label>
|
||||
<Input
|
||||
id="price-from"
|
||||
type="number"
|
||||
value={priceRange[0]}
|
||||
onChange={(e) => onInputChange("from", e.target.value)}
|
||||
className="rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="price-to" className="text-xs mb-1">
|
||||
{translations.to}
|
||||
</Label>
|
||||
<Input
|
||||
id="price-to"
|
||||
type="number"
|
||||
value={priceRange[1]}
|
||||
onChange={(e) => onInputChange("to", e.target.value)}
|
||||
className="rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Slider
|
||||
min={0}
|
||||
max={99999}
|
||||
step={100}
|
||||
value={priceRange}
|
||||
onValueChange={onPriceChange}
|
||||
className="mt-2"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
9
features/category/components/CategoryContent.tsx
Normal file
9
features/category/components/CategoryContent.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
"use client"
|
||||
export default function CategoryPageContent({ slug }: { slug: string }) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<h1 className="text-3xl font-bold mb-6">Category: {slug}</h1>
|
||||
{/* Category content will go here */}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
158
features/category/hooks/useCategories.ts
Normal file
158
features/category/hooks/useCategories.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { apiClient } from "@/lib/api"
|
||||
import type { Category, Product, PaginatedResponse } from "@/lib/types/api"
|
||||
|
||||
// Get all categories as tree
|
||||
export function useCategories(options?: { enabled?: boolean }) {
|
||||
return useQuery({
|
||||
queryKey: ["categories"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<PaginatedResponse<Category>>("/categories", {
|
||||
params: { type: "tree" },
|
||||
})
|
||||
return response.data.data || response.data
|
||||
},
|
||||
enabled: options?.enabled !== false,
|
||||
staleTime: 1000 * 60 * 30, // 30 minutes
|
||||
})
|
||||
}
|
||||
|
||||
// Get single category by ID
|
||||
export function useCategory(id: number | string, options?: { enabled?: boolean }) {
|
||||
return useQuery({
|
||||
queryKey: ["category", id],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<Category>(`/categories/${id}`)
|
||||
return response.data
|
||||
},
|
||||
enabled: options?.enabled !== false && !!id,
|
||||
staleTime: 1000 * 60 * 15,
|
||||
})
|
||||
}
|
||||
|
||||
// Get products for a single category with pagination
|
||||
export function useCategoryProducts(
|
||||
categoryId: number | string,
|
||||
options?: {
|
||||
enabled?: boolean
|
||||
page?: number
|
||||
limit?: number
|
||||
}
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["category", categoryId, "products", options?.page, options?.limit],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<PaginatedResponse<Product>>(
|
||||
`/categories/${categoryId}/products`,
|
||||
{
|
||||
params: {
|
||||
page: options?.page || 1,
|
||||
limit: options?.limit
|
||||
},
|
||||
}
|
||||
)
|
||||
return {
|
||||
data: response.data.data || [],
|
||||
pagination: response.data.pagination || {}
|
||||
}
|
||||
},
|
||||
enabled: options?.enabled !== false && !!categoryId,
|
||||
})
|
||||
}
|
||||
|
||||
// Get ALL products from category and its children - NO pagination (for initial load)
|
||||
export function useAllCategoryProducts(
|
||||
category: Category | undefined,
|
||||
options?: { enabled?: boolean }
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["category", category?.id, "all-products"],
|
||||
queryFn: async () => {
|
||||
if (!category) return []
|
||||
|
||||
const fetchProducts = async (categoryId: number) => {
|
||||
const response = await apiClient.get<PaginatedResponse<Product>>(
|
||||
`/categories/${categoryId}/products`
|
||||
)
|
||||
return response.data.data || []
|
||||
}
|
||||
|
||||
let allProducts = await fetchProducts(category.id)
|
||||
|
||||
if (category.children && category.children.length > 0) {
|
||||
for (const child of category.children) {
|
||||
const childProducts = await fetchProducts(child.id)
|
||||
allProducts = [...allProducts, ...childProducts]
|
||||
}
|
||||
}
|
||||
|
||||
return allProducts
|
||||
},
|
||||
enabled: options?.enabled !== false && !!category,
|
||||
})
|
||||
}
|
||||
|
||||
// Get products from category and children WITH pagination (mimics RTK getAllCategoryProductsPaginated)
|
||||
export function useAllCategoryProductsPaginated(
|
||||
category: Category | undefined,
|
||||
options?: {
|
||||
enabled?: boolean
|
||||
page?: number
|
||||
limit?: number
|
||||
}
|
||||
) {
|
||||
const page = options?.page || 1
|
||||
const limit = options?.limit || 6
|
||||
|
||||
return useQuery({
|
||||
queryKey: ["category", category?.id, "paginated-products", page, limit],
|
||||
queryFn: async () => {
|
||||
if (!category) {
|
||||
return {
|
||||
data: [],
|
||||
pagination: {
|
||||
currentPage: page,
|
||||
hasMorePages: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const categoryIds = [category.id]
|
||||
if (category.children && category.children.length > 0) {
|
||||
category.children.forEach((child) => categoryIds.push(child.id))
|
||||
}
|
||||
|
||||
const perCategoryLimit = Math.ceil(limit / categoryIds.length)
|
||||
const hasMoreByCategory: Record<number, boolean> = {}
|
||||
let allPageProducts: Product[] = []
|
||||
|
||||
for (const categoryId of categoryIds) {
|
||||
const response = await apiClient.get<PaginatedResponse<Product>>(
|
||||
`/categories/${categoryId}/products`,
|
||||
{
|
||||
params: {
|
||||
page,
|
||||
limit: perCategoryLimit
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (response.data.data) {
|
||||
allPageProducts = [...allPageProducts, ...response.data.data]
|
||||
hasMoreByCategory[categoryId] = !!response.data.pagination?.next_page_url
|
||||
}
|
||||
}
|
||||
|
||||
const hasMorePages = Object.values(hasMoreByCategory).some((hasMore) => hasMore)
|
||||
|
||||
return {
|
||||
data: allPageProducts,
|
||||
pagination: {
|
||||
currentPage: page,
|
||||
hasMorePages
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled: options?.enabled !== false && !!category,
|
||||
})
|
||||
}
|
||||
0
features/category/types.ts
Normal file
0
features/category/types.ts
Normal file
112
features/favorites/hooks/useFavorites.ts
Normal file
112
features/favorites/hooks/useFavorites.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { apiClient } from "@/lib/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() {
|
||||
return useQuery({
|
||||
queryKey: ["favorites"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get("/favorites");
|
||||
return transformFavoritesResponse(response.data);
|
||||
},
|
||||
staleTime: 1000 * 60 * 5,
|
||||
retry: 1,
|
||||
});
|
||||
}
|
||||
|
||||
export function useAddToFavorites() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (productId: number) => {
|
||||
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, "Added");
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["favorites"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useRemoveFromFavorites() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (productId: number) => {
|
||||
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: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["favorites"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
0
features/favorites/types.ts
Normal file
0
features/favorites/types.ts
Normal file
38
features/home/components/Carousel.tsx
Normal file
38
features/home/components/Carousel.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
"use client"
|
||||
import Image, { type StaticImageData } from "next/image"
|
||||
import { Swiper, SwiperSlide } from "swiper/react"
|
||||
import { Autoplay } from "swiper/modules"
|
||||
import "swiper/css"
|
||||
|
||||
type CarouselItem = {
|
||||
title: string
|
||||
image: StaticImageData | string
|
||||
url?: string | null
|
||||
}
|
||||
|
||||
export default function HeroCarousel({ items }: { items: CarouselItem[] }) {
|
||||
return (
|
||||
<section className="rounded-2xl overflow-hidden">
|
||||
<Swiper
|
||||
modules={[Autoplay]}
|
||||
slidesPerView={1}
|
||||
loop
|
||||
autoplay={{ delay: 3000, disableOnInteraction: false }}
|
||||
>
|
||||
{items.map((item, i) => (
|
||||
<SwiperSlide key={i}>
|
||||
<div className="relative w-full h-[200px] sm:h-[300px] md:h-[420px]">
|
||||
<Image
|
||||
src={item.image}
|
||||
alt={item.title}
|
||||
fill
|
||||
className="object-cover"
|
||||
priority={i === 0}
|
||||
/>
|
||||
</div>
|
||||
</SwiperSlide>
|
||||
))}
|
||||
</Swiper>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
79
features/home/components/CategoryGrid.tsx
Normal file
79
features/home/components/CategoryGrid.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import type { Category } from "@/lib/types/api";
|
||||
|
||||
type Props = {
|
||||
categories: Category[] | undefined;
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
locale: string;
|
||||
title: string;
|
||||
};
|
||||
|
||||
export default function CategoryGrid({
|
||||
categories,
|
||||
isLoading,
|
||||
isError,
|
||||
locale,
|
||||
title,
|
||||
}: Props) {
|
||||
if (isError) {
|
||||
return (
|
||||
<section className="bg-white rounded-2xl shadow-sm p-6">
|
||||
<h2 className="text-xl font-semibold mb-4">{title}</h2>
|
||||
<p className="text-red-600">
|
||||
Failed to load categories. Please try again.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<section className="bg-white rounded-2xl shadow-sm p-6">
|
||||
<h2 className="text-xl font-semibold mb-4">{title}</h2>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<div key={i} className="space-y-2">
|
||||
<Skeleton className="w-full h-36 rounded-lg" />
|
||||
<Skeleton className="w-full h-4 rounded" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="bg-white rounded-2xl shadow-sm p-6">
|
||||
<h2 className="text-xl font-semibold mb-4">{title}</h2>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
|
||||
{categories?.map((cat) => (
|
||||
<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">
|
||||
<div className="relative w-full h-36 overflow-hidden rounded-lg">
|
||||
<Image
|
||||
src={cat.media?.[0]?.images_400x400 || "/placeholder.svg"}
|
||||
alt={cat.name}
|
||||
fill
|
||||
className="object-contain"
|
||||
/>
|
||||
</div>
|
||||
<CardContent className="py-2">
|
||||
<p className="text-sm font-medium text-gray-800 truncate text-center">
|
||||
{cat.name}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
118
features/home/components/HomePage.tsx
Normal file
118
features/home/components/HomePage.tsx
Normal file
@@ -0,0 +1,118 @@
|
||||
"use client";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useEffect, useState } from "react";
|
||||
import InfiniteScroll from "react-infinite-scroll-component";
|
||||
import HeroCarousel from "./Carousel";
|
||||
import CategoryGrid from "./CategoryGrid";
|
||||
import CollectionSection from "./ProductGrid";
|
||||
import { useCategories, useCarousels, useCollections } from "@/lib/hooks";
|
||||
|
||||
|
||||
export default function HomePage() {
|
||||
const locale = useLocale();
|
||||
const t = useTranslations("common");
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [visibleCount, setVisibleCount] = useState(10);
|
||||
|
||||
const {
|
||||
data: categories,
|
||||
isLoading: categoriesLoading,
|
||||
isError: categoriesError,
|
||||
} = useCategories();
|
||||
|
||||
const { data: carousels, isLoading: carouselsLoading } = useCarousels();
|
||||
|
||||
const {
|
||||
data: collections,
|
||||
isLoading: collectionsLoading,
|
||||
isError: collectionsError,
|
||||
} = useCollections();
|
||||
|
||||
useEffect(() => setMounted(true), []);
|
||||
|
||||
const loadMore = () => {
|
||||
if (collections && visibleCount < collections.length) {
|
||||
setVisibleCount((prev) => Math.min(prev + 10, collections.length));
|
||||
}
|
||||
};
|
||||
|
||||
if (!mounted) return <div className="p-8">Loading...</div>;
|
||||
|
||||
const carouselItems =
|
||||
carousels?.map((carousel) => ({
|
||||
title: carousel.title || "",
|
||||
image: carousel.image || carousel.thumbnail,
|
||||
url: carousel.link || null,
|
||||
})) || [];
|
||||
|
||||
const visibleCollections = collections?.slice(0, visibleCount) || [];
|
||||
const hasMore = collections ? visibleCount < collections.length : false;
|
||||
|
||||
return (
|
||||
<div className="px-4 md:px-8 lg:px-12 pt-8 pb-12 space-y-8">
|
||||
{!carouselsLoading && carouselItems.length > 0 && (
|
||||
<HeroCarousel items={carouselItems} />
|
||||
)}
|
||||
|
||||
<CategoryGrid
|
||||
categories={categories}
|
||||
isLoading={categoriesLoading}
|
||||
isError={categoriesError}
|
||||
locale={locale}
|
||||
title={t("categories")}
|
||||
/>
|
||||
|
||||
{collectionsError ? (
|
||||
<section className="bg-white rounded-2xl shadow-sm p-6">
|
||||
<p className="text-red-600">
|
||||
Failed to load collections. Please try again.
|
||||
</p>
|
||||
</section>
|
||||
) : collectionsLoading ? (
|
||||
<div className="space-y-8">
|
||||
{Array.from({ length: 3 }).map((_, i) => (
|
||||
<div key={i} className="bg-white rounded-2xl shadow-sm p-6">
|
||||
<div className="h-8 bg-gray-200 rounded w-48 mb-4 animate-pulse" />
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
|
||||
{Array.from({ length: 4 }).map((_, j) => (
|
||||
<div
|
||||
key={j}
|
||||
className="h-64 bg-gray-200 rounded-lg animate-pulse"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<InfiniteScroll
|
||||
dataLength={visibleCollections.length}
|
||||
next={loadMore}
|
||||
hasMore={hasMore}
|
||||
loader={
|
||||
<div className="text-center py-8">
|
||||
<div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-blue-600 border-r-transparent"></div>
|
||||
<p className="text-gray-500 mt-2">Loading more collections...</p>
|
||||
</div>
|
||||
}
|
||||
endMessage={
|
||||
<div className="text-center py-8">
|
||||
<p className="text-gray-600">✓ All collections loaded</p>
|
||||
</div>
|
||||
}
|
||||
scrollThreshold={0.8}
|
||||
>
|
||||
<div className="space-y-8">
|
||||
{visibleCollections.map((collection) => (
|
||||
<CollectionSection
|
||||
key={collection.id}
|
||||
collection={collection}
|
||||
locale={locale}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</InfiniteScroll>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
115
features/home/components/ProductGrid.tsx
Normal file
115
features/home/components/ProductGrid.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
"use client";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import ProductCard from "@/components/ProductCard";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useCollectionProducts } from "@/lib/hooks";
|
||||
import type { Collection } from "@/lib/types/api";
|
||||
|
||||
type Props = {
|
||||
collection: Collection;
|
||||
locale: string;
|
||||
};
|
||||
|
||||
export default function CollectionSection({ collection, locale }: Props) {
|
||||
const router = useRouter();
|
||||
const [shouldRender, setShouldRender] = useState(true);
|
||||
|
||||
const {
|
||||
data: productsData,
|
||||
isLoading,
|
||||
isError,
|
||||
} = useCollectionProducts(collection.id, { enabled: shouldRender });
|
||||
|
||||
// Determine if section should render based on products
|
||||
useEffect(() => {
|
||||
if (!isLoading && productsData) {
|
||||
const hasProducts = productsData.data && productsData.data.length > 0;
|
||||
setShouldRender(hasProducts);
|
||||
}
|
||||
}, [isLoading, productsData]);
|
||||
|
||||
// Don't render if no products after loading
|
||||
if (!isLoading && (!productsData?.data || productsData.data.length === 0)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleTitleClick = () => {
|
||||
router.push(`/${locale}/collections/${collection.id}`);
|
||||
};
|
||||
|
||||
// Show skeleton while loading
|
||||
if (isLoading) {
|
||||
return (
|
||||
<section className="bg-white rounded-2xl shadow-sm p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<Skeleton className="h-8 w-48" />
|
||||
<Skeleton className="h-6 w-6 rounded-full" />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<Skeleton key={i} className="w-full h-64 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// Show error state
|
||||
if (isError) {
|
||||
return null; // Silently skip errored collections
|
||||
}
|
||||
|
||||
// Slice to show only first 4 products
|
||||
const displayProducts = productsData?.data.slice(0, 4) || [];
|
||||
|
||||
return (
|
||||
<section className="bg-white rounded-2xl shadow-sm p-6">
|
||||
<div
|
||||
className="flex items-center justify-between mb-4 cursor-pointer group"
|
||||
onClick={handleTitleClick}
|
||||
>
|
||||
<h2 className="text-xl font-semibold group-hover:text-blue-600 transition-colors">
|
||||
{collection.name}
|
||||
</h2>
|
||||
<ChevronRight className="w-6 h-6 text-gray-400 group-hover:text-blue-600 group-hover:translate-x-1 transition-all" />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
|
||||
{displayProducts.map((product) => {
|
||||
// Extract first media image or use placeholder
|
||||
const firstImage =
|
||||
product.media?.[0]?.images_800x800 ||
|
||||
product.media?.[0]?.images_720x720 ||
|
||||
product.media?.[0]?.thumbnail ||
|
||||
"/placeholder-product.jpg";
|
||||
|
||||
// Format price
|
||||
const formattedPrice = product.price_amount
|
||||
? `${parseFloat(product.price_amount).toFixed(2)} TMT`
|
||||
: "Price not available";
|
||||
|
||||
return (
|
||||
<ProductCard
|
||||
key={product.id}
|
||||
id={product.id}
|
||||
name={product.name}
|
||||
price={
|
||||
product.price_amount ? parseFloat(product.price_amount) : null
|
||||
}
|
||||
struct_price_text={formattedPrice}
|
||||
images={[firstImage]}
|
||||
is_favorite={false}
|
||||
labels={[]}
|
||||
price_color="#111"
|
||||
height={360}
|
||||
width={250}
|
||||
button={false}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
151
features/home/hooks/useCollections.ts
Normal file
151
features/home/hooks/useCollections.ts
Normal file
@@ -0,0 +1,151 @@
|
||||
import { useQuery, useInfiniteQuery } from "@tanstack/react-query";
|
||||
import { apiClient } from "@/lib/api";
|
||||
import type { Collection, Product, PaginatedResponse } from "@/lib/types/api";
|
||||
|
||||
// Get ALL collections (fetch all pages)
|
||||
export function useCollections(options?: { enabled?: boolean }) {
|
||||
return useQuery({
|
||||
queryKey: ["collections"],
|
||||
queryFn: async () => {
|
||||
const allCollections: Collection[] = [];
|
||||
let currentPage = 1;
|
||||
let hasMorePages = true;
|
||||
|
||||
while (hasMorePages) {
|
||||
const response = await apiClient.get<PaginatedResponse<Collection>>(
|
||||
"/collections",
|
||||
{ params: { page: currentPage, perPage: 50 } }
|
||||
);
|
||||
|
||||
const collections = response.data.data || [];
|
||||
allCollections.push(...collections);
|
||||
|
||||
// Check if there are more pages
|
||||
const pagination = response.data.pagination;
|
||||
if (pagination && pagination.next_page_url) {
|
||||
currentPage++;
|
||||
} else {
|
||||
hasMorePages = false;
|
||||
}
|
||||
}
|
||||
|
||||
return allCollections;
|
||||
},
|
||||
enabled: options?.enabled !== false,
|
||||
staleTime: 1000 * 60 * 30, // 30 minutes
|
||||
});
|
||||
}
|
||||
|
||||
// Get single collection by ID
|
||||
export function useCollection(
|
||||
id: number | string,
|
||||
options?: { enabled?: boolean }
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["collection", id],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<Collection>(`/collections/${id}`);
|
||||
return response.data;
|
||||
},
|
||||
enabled: options?.enabled !== false && !!id,
|
||||
staleTime: 1000 * 60 * 15,
|
||||
});
|
||||
}
|
||||
|
||||
// Get ALL products for a collection (fetch all pages)
|
||||
export function useCollectionProducts(
|
||||
collectionId: number | string,
|
||||
options?: { enabled?: boolean }
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["collection", collectionId, "products"],
|
||||
queryFn: async () => {
|
||||
const allProducts: Product[] = [];
|
||||
let currentPage = 1;
|
||||
let hasMorePages = true;
|
||||
|
||||
while (hasMorePages) {
|
||||
const response = await apiClient.get<PaginatedResponse<Product>>(
|
||||
`/collections/${collectionId}/products`,
|
||||
{ params: { page: currentPage, perPage: 50 } }
|
||||
);
|
||||
|
||||
const products = response.data.data || [];
|
||||
allProducts.push(...products);
|
||||
|
||||
// Check if there are more pages
|
||||
const pagination = response.data.pagination;
|
||||
if (pagination && pagination.next_page_url) {
|
||||
currentPage++;
|
||||
} else {
|
||||
hasMorePages = false;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
data: allProducts,
|
||||
isEmpty: allProducts.length === 0,
|
||||
};
|
||||
},
|
||||
enabled: options?.enabled !== false && !!collectionId,
|
||||
});
|
||||
}
|
||||
|
||||
// Check if collection has products (limit=1 for efficiency)
|
||||
export function useCollectionHasProducts(
|
||||
collectionId: number | string,
|
||||
options?: { enabled?: boolean }
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["collection", collectionId, "has-products"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<PaginatedResponse<Product>>(
|
||||
`/collections/${collectionId}/products`,
|
||||
{ params: { perPage: 1 } }
|
||||
);
|
||||
return {
|
||||
hasProducts: response.data.data && response.data.data.length > 0,
|
||||
};
|
||||
},
|
||||
enabled: options?.enabled !== false && !!collectionId,
|
||||
staleTime: 1000 * 60 * 5, // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
// Get collection products with infinite scroll (recommended for UI)
|
||||
export function useCollectionProductsInfinite(
|
||||
collectionId: number | string,
|
||||
options?: { enabled?: boolean; perPage?: number }
|
||||
) {
|
||||
const perPage = options?.perPage || 6;
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: ["collection", collectionId, "products-infinite", perPage],
|
||||
queryFn: async ({ pageParam = 1 }) => {
|
||||
const response = await apiClient.get<PaginatedResponse<Product>>(
|
||||
`/collections/${collectionId}/products`,
|
||||
{
|
||||
params: {
|
||||
page: pageParam,
|
||||
perPage,
|
||||
},
|
||||
}
|
||||
);
|
||||
return {
|
||||
data: response.data.data || [],
|
||||
pagination: response.data.pagination,
|
||||
isEmpty: !response.data.data || response.data.data.length === 0,
|
||||
};
|
||||
},
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (lastPage.pagination?.next_page_url) {
|
||||
// Extract page number from URL or increment
|
||||
const currentPage = lastPage.pagination.page || 1;
|
||||
return currentPage + 1;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
enabled: options?.enabled !== false && !!collectionId,
|
||||
initialPageParam: 1,
|
||||
});
|
||||
}
|
||||
29
features/home/hooks/useMedia.ts
Normal file
29
features/home/hooks/useMedia.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import { apiClient } from "@/lib/api"
|
||||
import type { Carousel, Banner, PaginatedResponse } from "@/lib/types/api"
|
||||
|
||||
// Get all carousels
|
||||
export function useCarousels(options?: { enabled?: boolean }) {
|
||||
return useQuery({
|
||||
queryKey: ["carousels"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<PaginatedResponse<Carousel>>("/media/carousels")
|
||||
return response.data.data || response.data
|
||||
},
|
||||
enabled: options?.enabled !== false,
|
||||
staleTime: 1000 * 60 * 30, // 30 minutes
|
||||
})
|
||||
}
|
||||
|
||||
// Get all banners
|
||||
export function useBanners(options?: { enabled?: boolean }) {
|
||||
return useQuery({
|
||||
queryKey: ["banners"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<PaginatedResponse<Banner>>("/media/banners")
|
||||
return response.data.data || response.data
|
||||
},
|
||||
enabled: options?.enabled !== false,
|
||||
staleTime: 1000 * 60 * 30, // 30 minutes
|
||||
})
|
||||
}
|
||||
0
features/home/types.ts
Normal file
0
features/home/types.ts
Normal file
46
features/orders/components/orders-content.tsx
Normal file
46
features/orders/components/orders-content.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
|
||||
// ... existing types and code ...
|
||||
|
||||
interface OrdersContentProps {
|
||||
locale: string
|
||||
}
|
||||
|
||||
export default function OrdersPageContent({ locale }: OrdersContentProps) {
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
|
||||
const [selectedOrderId, setSelectedOrderId] = useState<number | null>(null)
|
||||
const [activeTab, setActiveTab] = useState<"active" | "completed">("active")
|
||||
|
||||
const t = {
|
||||
orders: "Заказы",
|
||||
active: "Активные",
|
||||
completed: "Завершенные",
|
||||
cancelOrder: "Отменить заказ",
|
||||
areYouSure: "Вы уверены?",
|
||||
yes: "Да",
|
||||
no: "Нет",
|
||||
orderNumber: "№",
|
||||
}
|
||||
|
||||
const handleCancelOrder = (orderId: number) => {
|
||||
setSelectedOrderId(orderId)
|
||||
setIsDeleteModalOpen(true)
|
||||
}
|
||||
|
||||
const confirmCancelOrder = async () => {
|
||||
if (selectedOrderId) {
|
||||
console.log("Canceling order:", selectedOrderId)
|
||||
setIsDeleteModalOpen(false)
|
||||
setSelectedOrderId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t.orders}</h1>
|
||||
{/* Orders content */}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
336
features/orders/components/orders-page-client.tsx
Normal file
336
features/orders/components/orders-page-client.tsx
Normal file
@@ -0,0 +1,336 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Image from "next/image";
|
||||
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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { useOrders, useCancelOrder } from "@/lib/hooks";
|
||||
import type { Order } from "../types";
|
||||
|
||||
export default function OrdersPageClient() {
|
||||
const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false);
|
||||
const [orderToCancel, setOrderToCancel] = useState<Order | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
const { data: orders, isLoading, isError, error } = useOrders();
|
||||
const { mutate: cancelOrder, isPending: isCancellingOrder } = useCancelOrder();
|
||||
|
||||
const t = {
|
||||
myOrders: "Мои заказы",
|
||||
activeOrders: "Активные заказы",
|
||||
completedOrders: "Завершенные заказы",
|
||||
cancelOrder: "Отменить заказ",
|
||||
keepOrder: "Оставить заказ",
|
||||
cancelConfirmation: "Вы уверены, что хотите отменить этот заказ?",
|
||||
cancelling: "Отмена...",
|
||||
orderNumber: "Заказ №",
|
||||
ordered: "Заказано",
|
||||
completed: "Завершено",
|
||||
estimatedDelivery: "Ожид. доставка",
|
||||
quantity: "Кол-во",
|
||||
total: "Итого",
|
||||
noOrders: "У вас пока нет заказов",
|
||||
noActiveOrders: "У вас нет активных заказов",
|
||||
noCompletedOrders: "У вас нет завершенных заказов",
|
||||
loadError: "Не удалось загрузить заказы",
|
||||
orderCancelled: "Заказ отменен",
|
||||
orderCancelledDescription: "Ваш заказ был успешно отменен",
|
||||
error: "Ошибка",
|
||||
status: "Статус",
|
||||
deliveryTime: "Время доставки",
|
||||
deliveryDate: "Дата доставки",
|
||||
address: "Адрес",
|
||||
paymentMethod: "Способ оплаты",
|
||||
};
|
||||
|
||||
const handleCancelOrder = (order: Order) => {
|
||||
setOrderToCancel(order);
|
||||
setIsCancelDialogOpen(true);
|
||||
};
|
||||
|
||||
const confirmCancelOrder = () => {
|
||||
if (!orderToCancel) return;
|
||||
|
||||
cancelOrder(orderToCancel.id, {
|
||||
onSuccess: () => {
|
||||
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: string) => {
|
||||
const lowerStatus = status.toLowerCase();
|
||||
|
||||
if (lowerStatus.includes("ожидается") || lowerStatus.includes("pending")) {
|
||||
return <Badge variant="outline">{status}</Badge>;
|
||||
}
|
||||
if (lowerStatus.includes("обработка") || lowerStatus.includes("processing")) {
|
||||
return <Badge variant="secondary">{status}</Badge>;
|
||||
}
|
||||
if (lowerStatus.includes("отправлен") || lowerStatus.includes("shipped")) {
|
||||
return <Badge>{status}</Badge>;
|
||||
}
|
||||
if (lowerStatus.includes("доставлен") || lowerStatus.includes("delivered")) {
|
||||
return <Badge className="bg-green-600">{status}</Badge>;
|
||||
}
|
||||
if (lowerStatus.includes("отменен") || lowerStatus.includes("cancelled")) {
|
||||
return <Badge variant="destructive">{status}</Badge>;
|
||||
}
|
||||
|
||||
return <Badge>{status}</Badge>;
|
||||
};
|
||||
|
||||
const isActiveOrder = (status: string) => {
|
||||
const lower = status.toLowerCase();
|
||||
return lower.includes("ожидается") || lower.includes("обработка") || lower.includes("отправлен") ||
|
||||
lower.includes("pending") || lower.includes("processing") || lower.includes("shipped");
|
||||
};
|
||||
|
||||
const activeOrders = orders?.filter((o) => isActiveOrder(o.status)) || [];
|
||||
const completedOrders = orders?.filter((o) => !isActiveOrder(o.status)) || [];
|
||||
|
||||
const calculateTotal = (order: Order) => {
|
||||
return order.orderItems.reduce((sum, item) => {
|
||||
return sum + (parseFloat(item.unit_price_amount) * item.quantity);
|
||||
}, 0);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="container mx-auto p-4 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-10 w-40" />
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-64 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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">
|
||||
<p className="text-red-600">{t.loadError}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!orders || orders.length === 0) {
|
||||
return (
|
||||
<div className="container mx-auto p-4 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<p className="text-2xl text-gray-400">{t.noOrders}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 min-h-screen">
|
||||
<h1 className="text-3xl font-bold mb-6">{t.myOrders}</h1>
|
||||
|
||||
<Tabs defaultValue="active" className="w-full">
|
||||
<TabsList className="mb-6">
|
||||
<TabsTrigger value="active">
|
||||
{t.activeOrders} ({activeOrders.length})
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="completed">
|
||||
{t.completedOrders} ({completedOrders.length})
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="active">
|
||||
{activeOrders.length === 0 ? (
|
||||
<div className="flex items-center justify-center min-h-[40vh]">
|
||||
<p className="text-xl text-gray-400">{t.noActiveOrders}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{activeOrders.map((order) => (
|
||||
<OrderCard
|
||||
key={order.id}
|
||||
order={order}
|
||||
onCancel={handleCancelOrder}
|
||||
isCancelling={isCancellingOrder}
|
||||
getStatusBadge={getStatusBadge}
|
||||
calculateTotal={calculateTotal}
|
||||
translations={t}
|
||||
showCancelButton
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="completed">
|
||||
{completedOrders.length === 0 ? (
|
||||
<div className="flex items-center justify-center min-h-[40vh]">
|
||||
<p className="text-xl text-gray-400">{t.noCompletedOrders}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{completedOrders.map((order) => (
|
||||
<OrderCard
|
||||
key={order.id}
|
||||
order={order}
|
||||
onCancel={handleCancelOrder}
|
||||
isCancelling={isCancellingOrder}
|
||||
getStatusBadge={getStatusBadge}
|
||||
calculateTotal={calculateTotal}
|
||||
translations={t}
|
||||
showCancelButton={false}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<Dialog open={isCancelDialogOpen} onOpenChange={setIsCancelDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{t.cancelOrder} #{orderToCancel?.id}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{t.cancelConfirmation}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setIsCancelDialogOpen(false)}
|
||||
disabled={isCancellingOrder}
|
||||
>
|
||||
{t.keepOrder}
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={confirmCancelOrder} disabled={isCancellingOrder}>
|
||||
{isCancellingOrder ? t.cancelling : t.cancelOrder}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface OrderCardProps {
|
||||
order: Order;
|
||||
onCancel: (order: Order) => void;
|
||||
isCancelling: boolean;
|
||||
getStatusBadge: (status: string) => React.ReactNode;
|
||||
calculateTotal: (order: Order) => number;
|
||||
translations: any;
|
||||
showCancelButton: boolean;
|
||||
}
|
||||
|
||||
function OrderCard({
|
||||
order,
|
||||
onCancel,
|
||||
isCancelling,
|
||||
getStatusBadge,
|
||||
calculateTotal,
|
||||
translations: t,
|
||||
showCancelButton,
|
||||
}: OrderCardProps) {
|
||||
const total = calculateTotal(order);
|
||||
|
||||
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 text-sm">
|
||||
<p className="text-gray-600">
|
||||
<span className="font-medium">{t.deliveryTime}:</span> {order.delivery_time}
|
||||
</p>
|
||||
<p className="text-gray-600">
|
||||
<span className="font-medium">{t.deliveryDate}:</span>{" "}
|
||||
{new Date(order.delivery_at).toLocaleDateString()}
|
||||
</p>
|
||||
<p className="text-gray-600">
|
||||
<span className="font-medium">{t.address}:</span> {order.customer_address}
|
||||
</p>
|
||||
<p className="text-gray-600">
|
||||
<span className="font-medium">{t.paymentMethod}:</span> {order.payment_type}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 mb-3 max-h-48 overflow-y-auto">
|
||||
{order.orderItems.map((item, index) => (
|
||||
<div key={index} className="flex items-start gap-3">
|
||||
<Image
|
||||
src={item.product.images_400x400 || item.product.thumbnail}
|
||||
alt={item.product.name}
|
||||
width={50}
|
||||
height={50}
|
||||
className="rounded object-cover"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium line-clamp-2">{item.product.name}</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
{t.quantity}: {item.quantity} × {item.unit_price_amount} TMT
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-3">
|
||||
<div className="flex justify-between font-semibold">
|
||||
<span>{t.total}</span>
|
||||
<span>{total.toFixed(2)} TMT</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showCancelButton && (
|
||||
<div className="mt-4">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => onCancel(order)}
|
||||
disabled={isCancelling}
|
||||
className="w-full"
|
||||
>
|
||||
{t.cancelOrder}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
78
features/orders/hooks/useOrders.ts
Normal file
78
features/orders/hooks/useOrders.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { apiClient } from "@/lib/api";
|
||||
import type { Order, OrdersResponse, CreateOrderRequest } from "../types";
|
||||
|
||||
export function useOrders(options?: { page?: number; perPage?: number }) {
|
||||
return useQuery<Order[]>({
|
||||
queryKey: ["orders", options?.page],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<OrdersResponse>("/orders", {
|
||||
params: {
|
||||
page: options?.page || 1,
|
||||
per_page: options?.perPage || 20,
|
||||
},
|
||||
});
|
||||
|
||||
// API response'dan data array'ini döndür
|
||||
return response.data.data;
|
||||
},
|
||||
staleTime: 1000 * 60 * 5,
|
||||
retry: 1,
|
||||
});
|
||||
}
|
||||
|
||||
export function useOrder(id: number | string) {
|
||||
return useQuery<Order | null>({
|
||||
queryKey: ["order", id],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get(`/orders/${id}`);
|
||||
return response.data.data || null;
|
||||
},
|
||||
enabled: !!id,
|
||||
staleTime: 1000 * 60 * 5,
|
||||
retry: 1,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateOrder() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (orderData: CreateOrderRequest) => {
|
||||
const formData = new 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",
|
||||
},
|
||||
});
|
||||
|
||||
return response.data;
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["cart"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCancelOrder() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (orderId: number) => {
|
||||
const response = await apiClient.delete(`/orders/${orderId}`);
|
||||
return response.data;
|
||||
},
|
||||
onSuccess: (_, orderId) => {
|
||||
queryClient.invalidateQueries({ queryKey: ["orders"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["order", orderId] });
|
||||
},
|
||||
});
|
||||
}
|
||||
59
features/orders/types.ts
Normal file
59
features/orders/types.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
export interface OrderProduct {
|
||||
id: number;
|
||||
name: string;
|
||||
thumbnail: string;
|
||||
images_400x400: string;
|
||||
images_800x800: string;
|
||||
images_1200x1200: string;
|
||||
}
|
||||
|
||||
export interface OrderItem {
|
||||
product: OrderProduct;
|
||||
order: {
|
||||
id: number;
|
||||
};
|
||||
quantity: number;
|
||||
unit_price_amount: string;
|
||||
}
|
||||
|
||||
export interface Order {
|
||||
id: number;
|
||||
status: string;
|
||||
shipping_method: string;
|
||||
notes: string | null;
|
||||
customer_name: string;
|
||||
customer_phone: string;
|
||||
customer_address: string;
|
||||
delivery_time: string;
|
||||
delivery_at: string;
|
||||
region: string;
|
||||
user_id: number;
|
||||
province_id: number | null;
|
||||
payment_type: string;
|
||||
orderItems: OrderItem[];
|
||||
}
|
||||
|
||||
export interface OrdersResponse {
|
||||
message: string;
|
||||
data: Order[];
|
||||
pagination: {
|
||||
page: number;
|
||||
perPage: number;
|
||||
count: number;
|
||||
first_page_url: string;
|
||||
next_page_url: string | null;
|
||||
prev_page_url: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CreateOrderRequest {
|
||||
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;
|
||||
}
|
||||
401
features/products/components/ProductPageContent.tsx
Normal file
401
features/products/components/ProductPageContent.tsx
Normal file
@@ -0,0 +1,401 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import Image from "next/image"
|
||||
import Link from "next/link"
|
||||
import { Minus, Plus, Heart, ShoppingCart, Store } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card } from "@/components/ui/card"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { useProductsBySlug } from "@/features/products/hooks/useProducts"
|
||||
import { useAddToCart, useUpdateCartItemQuantity, useCart } from "@/features/cart/hooks/useCart"
|
||||
import { toast } from "sonner"
|
||||
|
||||
interface ProductDetailProps {
|
||||
slug: string
|
||||
}
|
||||
|
||||
const ProductPageContent = ({ slug }: ProductDetailProps) => {
|
||||
const [selectedImage, setSelectedImage] = useState(0)
|
||||
const [quantity, setQuantity] = useState(1)
|
||||
const [isFavorite, setIsFavorite] = useState(false)
|
||||
|
||||
// Get product data
|
||||
const { data: product, isLoading: productLoading, error } = useProductsBySlug(slug)
|
||||
|
||||
// Get cart data to check if product is already in cart
|
||||
const { data: cartData } = useCart()
|
||||
|
||||
// Cart mutations
|
||||
const addToCartMutation = useAddToCart()
|
||||
const updateCartMutation = useUpdateCartItemQuantity()
|
||||
|
||||
const t = {
|
||||
addToCart: "Sebede goş",
|
||||
goToCart: "Sebede git",
|
||||
price: "Bahasy:",
|
||||
aboutProduct: "Haryt barada",
|
||||
brand: "Marka",
|
||||
stock: "Mukdary",
|
||||
description: "Düşündiriş",
|
||||
store: "Dükan",
|
||||
writeToStore: "Dükana ýaz",
|
||||
color: "Reňk:",
|
||||
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 () => {
|
||||
if (!product?.id) return
|
||||
|
||||
try {
|
||||
await addToCartMutation.mutateAsync({
|
||||
productId: product.id,
|
||||
quantity: quantity,
|
||||
})
|
||||
|
||||
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) => {
|
||||
if (newQuantity < 1 || !product?.id) return
|
||||
if (newQuantity > product.stock) return
|
||||
|
||||
setQuantity(newQuantity)
|
||||
|
||||
// If product is already in cart, update it
|
||||
if (isInCart) {
|
||||
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 = () => {
|
||||
setIsFavorite(!isFavorite)
|
||||
// TODO: Implement favorites API
|
||||
}
|
||||
|
||||
// Loading state
|
||||
if (productLoading) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="flex flex-col lg:flex-row gap-8">
|
||||
<div className="flex-1 max-w-2xl">
|
||||
<Skeleton className="aspect-square w-full rounded-2xl" />
|
||||
<div className="mt-4 flex gap-2">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<Skeleton key={i} className="w-16 h-16 rounded" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 space-y-6">
|
||||
<Skeleton className="h-10 w-64" />
|
||||
<Skeleton className="h-20 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (error || !product) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 text-center">
|
||||
<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>
|
||||
)
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="flex flex-col lg:flex-row gap-8">
|
||||
{/* Product Images */}
|
||||
<div className="flex-1 max-w-2xl">
|
||||
<div className="relative">
|
||||
<div className="relative aspect-square w-full rounded-2xl overflow-hidden bg-gray-50">
|
||||
{imageUrls.length > 0 ? (
|
||||
<Image
|
||||
src={imageUrls[selectedImage]}
|
||||
alt={product.name}
|
||||
fill
|
||||
className="object-contain"
|
||||
priority
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full text-gray-400">
|
||||
Surat ýok
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Thumbnail Images */}
|
||||
{imageUrls.length > 1 && (
|
||||
<div className="mt-4 flex gap-2 overflow-x-auto pb-2">
|
||||
{imageUrls.map((image, index) => (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => setSelectedImage(index)}
|
||||
className={`relative w-16 h-16 flex-shrink-0 rounded overflow-hidden border-2 transition-all ${
|
||||
selectedImage === index
|
||||
? "border-primary ring-2 ring-primary/20"
|
||||
: "border-gray-200 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
<Image
|
||||
src={image}
|
||||
alt={`${product.name} ${index + 1}`}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Product Info */}
|
||||
<div className="flex-1 space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold mb-2">{product.name}</h1>
|
||||
{product.categories && product.categories.length > 0 && (
|
||||
<div className="flex gap-2 flex-wrap mt-2">
|
||||
{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>
|
||||
|
||||
{/* Product Info Table */}
|
||||
<Card className="p-4 rounded-xl border-gray-200">
|
||||
<h3 className="text-xl font-semibold mb-4">{t.aboutProduct}</h3>
|
||||
<div className="space-y-3">
|
||||
{product.brand?.name && (
|
||||
<>
|
||||
<div className="flex justify-between items-center py-2">
|
||||
<span className="text-gray-500">{t.brand}</span>
|
||||
<span className="font-medium">{product.brand.name}</span>
|
||||
</div>
|
||||
<Separator />
|
||||
</>
|
||||
)}
|
||||
|
||||
{product.stock !== undefined && (
|
||||
<>
|
||||
<div className="flex justify-between items-center py-2">
|
||||
<span className="text-gray-500">{t.stock}</span>
|
||||
<span className={`font-medium ${product.stock === 0 ? 'text-red-500' : 'text-green-600'}`}>
|
||||
{product.stock === 0 ? 'Ýok' : product.stock}
|
||||
</span>
|
||||
</div>
|
||||
<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>
|
||||
</Card>
|
||||
|
||||
{/* Description */}
|
||||
{product.description && (
|
||||
<Card className="p-4 rounded-xl border-gray-200">
|
||||
<h3 className="text-xl font-semibold mb-3">{t.description}</h3>
|
||||
<div
|
||||
className="text-gray-700 leading-relaxed prose prose-sm max-w-none"
|
||||
dangerouslySetInnerHTML={{ __html: product.description }}
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Price & Actions Sidebar */}
|
||||
<div className="lg:w-[380px] space-y-4">
|
||||
<Card className="p-6 rounded-xl shadow-lg sticky top-4">
|
||||
<div className="flex justify-between items-start mb-6">
|
||||
<span className="text-lg text-gray-500">{t.price}</span>
|
||||
<div className="flex flex-col items-end">
|
||||
<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 className="space-y-3">
|
||||
{isInCart ? (
|
||||
<>
|
||||
<Link href="/cart">
|
||||
<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" />
|
||||
{t.goToCart}
|
||||
</Button>
|
||||
</Link>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => handleQuantityChange(quantity - 1)}
|
||||
disabled={quantity === 1 || isLoading}
|
||||
className="rounded-xl h-12 w-12"
|
||||
>
|
||||
<Minus className="h-5 w-5" />
|
||||
</Button>
|
||||
<div className="flex-1 text-center font-semibold text-xl border rounded-xl h-12 flex items-center justify-center">
|
||||
{quantity}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => handleQuantityChange(quantity + 1)}
|
||||
disabled={isLoading || quantity >= product.stock}
|
||||
className="rounded-xl h-12 w-12"
|
||||
>
|
||||
<Plus className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={handleAddToCart}
|
||||
disabled={isLoading || product.stock === 0}
|
||||
className="w-full rounded-xl text-lg font-bold"
|
||||
>
|
||||
<ShoppingCart className="mr-2 h-5 w-5" />
|
||||
{isLoading ? "Goşulýar..." : product.stock === 0 ? "Haryt ýok" : t.addToCart}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
onClick={handleToggleFavorite}
|
||||
className={`w-full rounded-xl transition-all ${
|
||||
isFavorite
|
||||
? "bg-red-50 border-red-300 hover:bg-red-100"
|
||||
: "hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<Heart
|
||||
className={`h-6 w-6 transition-all ${
|
||||
isFavorite ? "fill-red-500 text-red-500" : "text-gray-600"
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Store/Channel Card */}
|
||||
{product.channel && product.channel.length > 0 && (
|
||||
<Card className="p-6 rounded-xl">
|
||||
<div className="flex items-center gap-4 mb-4">
|
||||
<Avatar className="w-14 h-14 bg-primary/10">
|
||||
<AvatarFallback className="bg-transparent">
|
||||
<Store className="h-6 w-6 text-primary" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">{t.store}</p>
|
||||
<h4 className="text-lg font-bold">{product.channel[0].name}</h4>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="w-full rounded-xl"
|
||||
>
|
||||
{t.writeToStore}
|
||||
</Button>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ProductPageContent
|
||||
9
features/products/components/product-content.tsx
Normal file
9
features/products/components/product-content.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
"use client"
|
||||
export default function ProductPageContent({ slug }: { slug: string }) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<h1 className="text-3xl font-bold">Product: {slug}</h1>
|
||||
{/* Product content will go here */}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
216
features/products/hooks/useProducts.ts
Normal file
216
features/products/hooks/useProducts.ts
Normal file
@@ -0,0 +1,216 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { apiClient } from "@/lib/api";
|
||||
import type { Review, Product, PaginatedResponse } from "@/lib/types/api";
|
||||
|
||||
// Get single review by ID
|
||||
export function useReview(
|
||||
reviewId: number | string,
|
||||
options?: { enabled?: boolean }
|
||||
) {
|
||||
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) {
|
||||
return useQuery({
|
||||
queryKey: ["products", options?.page, options?.perPage],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<PaginatedResponse<Product>>(
|
||||
"/products",
|
||||
{
|
||||
params: {
|
||||
page: options?.page || 1,
|
||||
per_page: options?.perPage || 20,
|
||||
},
|
||||
}
|
||||
);
|
||||
return response.data.data || response.data;
|
||||
},
|
||||
staleTime: options?.staleTime ?? 1000 * 60 * 5,
|
||||
enabled: options?.enabled !== false,
|
||||
});
|
||||
}
|
||||
|
||||
// Get single product by ID (for review context)
|
||||
export function useProduct(
|
||||
productId: number | string,
|
||||
options?: { enabled?: boolean }
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["product", productId],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<Product>(`/products/${productId}`);
|
||||
return response.data;
|
||||
},
|
||||
enabled: options?.enabled !== false && !!productId,
|
||||
staleTime: 1000 * 60 * 10,
|
||||
});
|
||||
}
|
||||
|
||||
export function useProductsBySlug(
|
||||
slug: string,
|
||||
options?: { enabled?: boolean }
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ["products", "slug", slug],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get(`/products/${slug}`);
|
||||
// API returns { message: "success", data: {...} }
|
||||
return response.data.data || response.data;
|
||||
},
|
||||
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"],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
0
features/products/types.ts
Normal file
0
features/products/types.ts
Normal file
124
features/profile/components/client-page.tsx
Normal file
124
features/profile/components/client-page.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
"use client";
|
||||
|
||||
import { LogOut } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useUserProfile } from "@/lib/hooks";
|
||||
import { clearAuthToken } from "@/lib/api";
|
||||
|
||||
interface ProfilePageProps {
|
||||
params: Promise<{ locale: string }>;
|
||||
}
|
||||
|
||||
export default function ClientProfilePage(props: ProfilePageProps) {
|
||||
const { data: user, isLoading, error } = useUserProfile();
|
||||
|
||||
const translations = {
|
||||
profile: "Профиль",
|
||||
personalInfo: "Личная информация",
|
||||
profileDescription: "Ваши данные профиля",
|
||||
firstName: "Имя",
|
||||
lastName: "Фамилия",
|
||||
phone: "Номер телефона",
|
||||
address: "Адрес",
|
||||
logout: "Выйти",
|
||||
loading: "Загрузка...",
|
||||
errorLoading: "Не удалось загрузить профиль",
|
||||
tryAgain: "Попробовать снова",
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
clearAuthToken();
|
||||
window.location.href = "/";
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-4 pt-20">
|
||||
<div className="container mx-auto max-w-2xl">
|
||||
<Skeleton className="h-10 w-48 mb-6" />
|
||||
<Card className="shadow-lg mb-4">
|
||||
<CardHeader>
|
||||
<Skeleton className="h-6 w-32 mb-2" />
|
||||
<Skeleton className="h-4 w-48" />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{[1, 2, 3, 4].map((i) => (
|
||||
<div key={i} className="space-y-2">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-10 w-full" />
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="pt-6 text-center">
|
||||
<p className="text-red-600 mb-4">{translations.errorLoading}</p>
|
||||
<Button onClick={() => window.location.reload()}>{translations.tryAgain}</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-4 pt-20">
|
||||
<div className="container mx-auto max-w-2xl">
|
||||
<h1 className="text-3xl font-bold mb-6">{translations.profile}</h1>
|
||||
|
||||
<Card className="shadow-lg mb-4">
|
||||
<CardHeader>
|
||||
<CardTitle>{translations.personalInfo}</CardTitle>
|
||||
<CardDescription>{translations.profileDescription}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{user && (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="firstName">{translations.firstName}</Label>
|
||||
<Input id="firstName" value={user.first_name || ""} disabled className="bg-gray-50" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="lastName">{translations.lastName}</Label>
|
||||
<Input id="lastName" value={user.last_name || ""} disabled className="bg-gray-50" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="phone">{translations.phone}</Label>
|
||||
<Input id="phone" value={user.phone_number || ""} disabled className="bg-gray-50" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="address">{translations.address}</Label>
|
||||
<Input id="address" value={user.address || ""} disabled className="bg-gray-50" />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Button
|
||||
onClick={handleLogout}
|
||||
variant="destructive"
|
||||
size="lg"
|
||||
className="w-full max-w-md flex items-center justify-center gap-2"
|
||||
>
|
||||
<LogOut className="h-5 w-5" />
|
||||
{translations.logout}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
66
features/profile/components/profile-content.tsx
Normal file
66
features/profile/components/profile-content.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
|
||||
interface User {
|
||||
first_name: string
|
||||
last_name: string
|
||||
phone: string
|
||||
email?: string
|
||||
}
|
||||
|
||||
interface ProfileContentProps {
|
||||
locale: string
|
||||
}
|
||||
|
||||
export default function ProfilePageContent({ locale }: ProfileContentProps) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const t = {
|
||||
profile: "Профиль",
|
||||
firstName: "Имя",
|
||||
lastName: "Фамилия",
|
||||
phone: "Номер телефона",
|
||||
email: "Email",
|
||||
logout: "Выйти",
|
||||
loading: "Загрузка...",
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUserData = () => {
|
||||
setTimeout(() => {
|
||||
setUser({
|
||||
first_name: "Иван",
|
||||
last_name: "Иванов",
|
||||
phone: "+99361234567",
|
||||
email: "ivan@example.com",
|
||||
})
|
||||
setLoading(false)
|
||||
}, 500)
|
||||
}
|
||||
|
||||
fetchUserData()
|
||||
}, [])
|
||||
|
||||
const handleLogout = () => {
|
||||
window.location.href = "/"
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
|
||||
<p className="text-lg text-gray-600">{t.loading}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 p-4 pt-20">
|
||||
<div className="container mx-auto max-w-2xl">
|
||||
<h1 className="text-3xl font-bold mb-6">{t.profile}</h1>
|
||||
{/* Profile content */}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
37
features/profile/hooks/useUserProfile.ts
Normal file
37
features/profile/hooks/useUserProfile.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { apiClient } from "@/lib/api";
|
||||
import { userStore } from "../userStore";
|
||||
import type { ProfileResponse, UpdateProfileRequest, UpdateProfileResponse } from "../types";
|
||||
|
||||
export const useUserProfile = () => {
|
||||
return useQuery<ProfileResponse["data"]>({
|
||||
queryKey: ["user-profile"],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<ProfileResponse>("/profile");
|
||||
const userData = response.data.data;
|
||||
|
||||
// Store'a kaydet
|
||||
userStore.setUser(userData);
|
||||
|
||||
return userData;
|
||||
},
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
});
|
||||
};
|
||||
|
||||
export const useUpdateProfile = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation<UpdateProfileResponse["data"], Error, UpdateProfileRequest>({
|
||||
mutationFn: async (profileData) => {
|
||||
const response = await apiClient.post<UpdateProfileResponse>("/profile", profileData);
|
||||
return response.data.data;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
userStore.setUser(data);
|
||||
queryClient.setQueryData(["user-profile"], data);
|
||||
queryClient.invalidateQueries({ queryKey: ["user-profile"] });
|
||||
},
|
||||
});
|
||||
};
|
||||
23
features/profile/types.ts
Normal file
23
features/profile/types.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
export interface UserProfile {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
phone_number: string;
|
||||
address: string;
|
||||
}
|
||||
|
||||
export interface ProfileResponse {
|
||||
message: string;
|
||||
data: UserProfile;
|
||||
}
|
||||
|
||||
export interface UpdateProfileRequest {
|
||||
first_name?: string;
|
||||
last_name?: string;
|
||||
phone_number?: string;
|
||||
address?: string;
|
||||
}
|
||||
|
||||
export interface UpdateProfileResponse {
|
||||
message: string;
|
||||
data: UserProfile;
|
||||
}
|
||||
29
features/profile/userStore.ts
Normal file
29
features/profile/userStore.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { UserProfile } from "./types";
|
||||
|
||||
// In-memory store (session-based, no persistence)
|
||||
class UserStore {
|
||||
private user: UserProfile | null = null;
|
||||
|
||||
setUser(user: UserProfile | null) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
getUser(): UserProfile | null {
|
||||
return this.user;
|
||||
}
|
||||
|
||||
clearUser() {
|
||||
this.user = null;
|
||||
}
|
||||
|
||||
getOrderData(): { customer_name: string; customer_phone: string } | null {
|
||||
if (!this.user) return null;
|
||||
|
||||
return {
|
||||
customer_name: `${this.user.first_name} ${this.user.last_name}`.trim(),
|
||||
customer_phone: this.user.phone_number,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const userStore = new UserStore();
|
||||
Reference in New Issue
Block a user