This repository has been archived on 2025-07-07. You can view files and clone it, but cannot push or open issues or pull requests.
Files
eternos/frontend/style/components/review-form.tsx
2025-02-22 20:12:27 +03:00

134 lines
4.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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 { Star } from 'lucide-react'
import { useAuth } from "@/contexts/auth-context"
import Link from "next/link"
interface ReviewFormProps {
productId: number
}
export function ReviewForm({ productId }: ReviewFormProps) {
const [rating, setRating] = useState(0)
const [comment, setComment] = useState("")
const [isSubmitting, setIsSubmitting] = useState(false)
const { isLoggedIn, user } = useAuth()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setIsSubmitting(true)
try {
// Добавляем 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)
})
// Добавляем console.log для отладки ответа
console.log('Response status:', response.status);
const responseData = await response.json();
console.log('Response data:', responseData);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Очищаем форму после успешной отправки
setRating(0)
setComment("")
alert("Отзыв успешно добавлен!")
// Перезагружаем страницу для отображения нового отзыва
window.location.reload()
} catch (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>
.
</p>
)
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<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)}
className="focus:outline-none"
>
<Star
className={`h-6 w-6 ${
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>
<Textarea
id="comment"
value={comment}
onChange={(e) => setComment(e.target.value)}
rows={4}
placeholder="Напишите ваш отзыв здесь..."
required
/>
</div>
<Button
type="submit"
disabled={isSubmitting || rating === 0 || comment.trim() === ""}
>
{isSubmitting ? "Отправка..." : "Отправить отзыв"}
</Button>
</form>
)
}