another one

This commit is contained in:
2025-02-22 20:12:27 +03:00
parent 1e803b4beb
commit b6fa50a59e
201 changed files with 5165 additions and 8036 deletions

View File

@@ -1,14 +1,14 @@
"use client"
import type React from "react"
import { useState } from "react"
import { Button } from "./ui/button"
import { Textarea } from "./ui/textarea"
import { Label } from "./ui/label"
import { LogIn, Star } from 'lucide-react'
import { Star } from 'lucide-react'
import { useAuth } from "@/contexts/auth-context"
import Link from "next/link"
interface ReviewFormProps {
productId: number
}
@@ -16,43 +16,69 @@ interface ReviewFormProps {
export function ReviewForm({ productId }: ReviewFormProps) {
const [rating, setRating] = useState(0)
const [comment, setComment] = useState("")
const { isLoggedIn } = useAuth()
const [isSubmitting, setIsSubmitting] = useState(false)
const { isLoggedIn, user } = useAuth()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
const reviewData = {
username: "No name", // Здесь можно подтянуть имя из Auth-контекста
rating,
comment,
}
setIsSubmitting(true)
try {
const response = await fetch(`http://localhost:8080/product/${productId}`, {
// Добавляем console.log для отладки
console.log('Submitting review with data:', {
productId,
rating,
comment,
username: user?.name || 'Anonymous'
});
const reviewData = {
product_id: productId,
username: user?.name || "Anonymous",
rating: rating,
comment: comment
}
const response = await fetch(`http://localhost:8080/product/${productId}/reviews`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(reviewData),
body: JSON.stringify(reviewData)
})
// Добавляем console.log для отладки ответа
console.log('Response status:', response.status);
const responseData = await response.json();
console.log('Response data:', responseData);
if (!response.ok) {
throw new Error("Ошибка при отправке отзыва")
throw new Error(`HTTP error! status: ${response.status}`);
}
console.log("Отзыв успешно отправлен!")
// Очищаем форму после успешной отправки
setRating(0)
setComment("")
alert("Отзыв успешно добавлен!")
// Перезагружаем страницу для отображения нового отзыва
window.location.reload()
} catch (error) {
console.error("Ошибка:", error)
console.error("Error submitting review:", error)
alert("Произошла ошибка при отправке отзыва. Пожалуйста, попробуйте еще раз.")
} finally {
setIsSubmitting(false)
}
}
if (!isLoggedIn) {
return (
<p className="text-gray-600">
Чтобы оставить отзыв, пожалуйста, <Link href="/login" className="text-blue-600 hover:underline">войдите в систему</Link>.
Чтобы оставить отзыв, пожалуйста,{" "}
<Link href="/login" className="text-blue-600 hover:underline">
войдите в систему
</Link>
.
</p>
)
}
@@ -63,20 +89,27 @@ export function ReviewForm({ productId }: ReviewFormProps) {
<Label htmlFor="rating">Рейтинг</Label>
<div className="flex items-center gap-1">
{[1, 2, 3, 4, 5].map((star) => (
<button
key={star}
type="button"
onClick={() => setRating(star)}
<button
key={star}
type="button"
onClick={() => setRating(star)}
className="focus:outline-none"
>
<Star
<Star
className={`h-6 w-6 ${
star <= rating ? 'text-yellow-400 fill-yellow-400' : 'text-gray-300'
}`}
star <= rating ? "text-yellow-400 fill-yellow-400" : "text-gray-300"
}`}
/>
</button>
))}
</div>
{/* Добавляем скрытое поле для отображения выбранного рейтинга */}
<input
type="hidden"
name="rating"
value={rating}
required
/>
</div>
<div>
<Label htmlFor="comment">Комментарий</Label>
@@ -86,10 +119,14 @@ export function ReviewForm({ productId }: ReviewFormProps) {
onChange={(e) => setComment(e.target.value)}
rows={4}
placeholder="Напишите ваш отзыв здесь..."
required
/>
</div>
<Button type="submit" disabled={rating === 0 || comment.trim() === ""}>
Отправить отзыв
<Button
type="submit"
disabled={isSubmitting || rating === 0 || comment.trim() === ""}
>
{isSubmitting ? "Отправка..." : "Отправить отзыв"}
</Button>
</form>
)