Новые правки в компоенты
This commit is contained in:
parent
36a3d37ad3
commit
815986969a
19 changed files with 1703 additions and 143 deletions
510
frontend/src/components/home/Hero.astro
Normal file
510
frontend/src/components/home/Hero.astro
Normal file
|
|
@ -0,0 +1,510 @@
|
|||
---
|
||||
import Button from '@components/base/Button.astro';
|
||||
import { Icon } from 'astro-icon/components';
|
||||
|
||||
interface HeroProps {
|
||||
badgeText: string;
|
||||
titleWhite: string;
|
||||
titleGold: string;
|
||||
description: string;
|
||||
btnText?: string;
|
||||
btnHref?: string;
|
||||
btnSecondary?: string;
|
||||
btnSecondaryHref?: string;
|
||||
btnSecondaryClass?: string;
|
||||
modalTarget?: string;
|
||||
bgImage?: string;
|
||||
minHeight?: string;
|
||||
headerOffset?: string;
|
||||
layout?: 'default' | 'with-image';
|
||||
sideImage?: string;
|
||||
sideImageAlt?: string;
|
||||
experienceBadge?: {
|
||||
number: string;
|
||||
text: string;
|
||||
};
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
const {
|
||||
badgeText,
|
||||
titleWhite,
|
||||
titleGold,
|
||||
description,
|
||||
btnText,
|
||||
btnHref = "#contact",
|
||||
btnSecondary,
|
||||
btnSecondaryHref = "/services",
|
||||
btnSecondaryClass = "",
|
||||
modalTarget,
|
||||
bgImage = "",
|
||||
minHeight = "100vh",
|
||||
headerOffset = "80px",
|
||||
layout = "default",
|
||||
sideImage = "",
|
||||
sideImageAlt = "",
|
||||
experienceBadge,
|
||||
icon
|
||||
} = Astro.props as HeroProps;
|
||||
|
||||
const showImage = layout === 'with-image' && sideImage;
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
<section
|
||||
class="hero-section hero-home"
|
||||
style={`min-height: ${minHeight}; padding-top: ${headerOffset}; ${bgImage ? `background-image: url("${bgImage}")` : ''}`}
|
||||
>
|
||||
|
||||
{bgImage && (
|
||||
<img
|
||||
src={bgImage}
|
||||
alt=""
|
||||
class="hero-bg-lcp"
|
||||
fetchpriority="high"
|
||||
decoding="async"
|
||||
width="1920"
|
||||
height="1080"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div class="hero-overlay"></div>
|
||||
|
||||
<div class="site-container hero-grid">
|
||||
<div class="hero-content">
|
||||
<div class="badge">
|
||||
{icon ? (
|
||||
<span class="badge-icon">
|
||||
<Icon name={icon} />
|
||||
</span>
|
||||
) : (
|
||||
<span class="status-dot"></span>
|
||||
)}
|
||||
{badgeText}
|
||||
</div>
|
||||
|
||||
<h1 class="hero-title">
|
||||
<span class="text-white">{titleWhite}</span>
|
||||
<br />
|
||||
<span class="text-gold">{titleGold}</span>
|
||||
</h1>
|
||||
|
||||
<p class="hero-description">{description}</p>
|
||||
|
||||
{btnText && (
|
||||
<div class="hero-actions">
|
||||
{modalTarget ? (
|
||||
<Button variant="gold" size="lg" data-modal-target={modalTarget}>
|
||||
{btnText}
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="gold" size="lg" href={btnHref}>
|
||||
{btnText}
|
||||
</Button>
|
||||
)}
|
||||
{btnSecondary && (
|
||||
<Button variant="outline" size="lg" href={btnSecondaryHref} class={btnSecondaryClass}>
|
||||
{btnSecondary}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showImage && (
|
||||
<div class="hero-image-wrapper">
|
||||
<div class="image-composition">
|
||||
<img
|
||||
src={sideImage}
|
||||
alt={sideImageAlt || "Юрист"}
|
||||
class="main-image"
|
||||
width="380"
|
||||
height="500"
|
||||
loading="eager"
|
||||
fetchpriority="high"
|
||||
decoding="async"
|
||||
/>
|
||||
{experienceBadge && (
|
||||
<div class="experience-badge">
|
||||
<span class="exp-number">{experienceBadge.number}</span>
|
||||
<span class="exp-text">{experienceBadge.text}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
.hero-section {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
margin: 0 !important;
|
||||
box-sizing: border-box;
|
||||
overflow: hidden;
|
||||
transition: padding-top 0.3s ease;
|
||||
}
|
||||
|
||||
|
||||
.hero-bg-lcp {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.hero-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #0a2540 0%, rgba(10, 37, 64, 0.9) 50%, rgba(10, 37, 64, 0.7) 100%);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.site-container {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 0 20px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* --- GRID LAYOUT --- */
|
||||
.hero-grid {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 3rem;
|
||||
width: 100%;
|
||||
padding-bottom: 4rem;
|
||||
}
|
||||
|
||||
.hero-content {
|
||||
flex: 1.2;
|
||||
max-width: 700px;
|
||||
}
|
||||
|
||||
/* --- BADGE --- */
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
background-color: rgba(234, 194, 110, 0.15);
|
||||
border: 1px solid rgba(234, 194, 110, 0.3);
|
||||
color: #eac26e;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 6px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 1.5px;
|
||||
margin-bottom: 2.5rem;
|
||||
}
|
||||
|
||||
.badge svg {
|
||||
color: #eac26e;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Мерцающая точка - оптимизированная анимация */
|
||||
.status-dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
background: #22c55e;
|
||||
border-radius: 50%;
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status-dot::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
background: #22c55e;
|
||||
animation: pulse-ring 2s cubic-bezier(0.215, 0.61, 0.355, 1) infinite;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.badge-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.badge-icon svg {
|
||||
width: 20px !important;
|
||||
height: 20px !important;
|
||||
stroke-width: 2 !important;
|
||||
}
|
||||
|
||||
@keyframes pulse-ring {
|
||||
0% {
|
||||
transform: scale(1);
|
||||
opacity: 0.8;
|
||||
}
|
||||
100% {
|
||||
transform: scale(2.5);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- TITLE --- */
|
||||
.hero-title {
|
||||
font-size: clamp(2rem, 5vw, 3.8rem);
|
||||
font-weight: 800;
|
||||
line-height: 1.15;
|
||||
margin: 0 0 2rem 0;
|
||||
}
|
||||
|
||||
.text-white {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.text-gold {
|
||||
color: #eac26e;
|
||||
}
|
||||
|
||||
/* --- DESCRIPTION --- */
|
||||
.hero-description {
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
font-size: 1.15rem;
|
||||
line-height: 1.6;
|
||||
margin-bottom: 2.5rem;
|
||||
max-width: 580px;
|
||||
}
|
||||
|
||||
/* --- ACTIONS --- */
|
||||
.hero-actions {
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.hero-actions > * {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* --- IMAGE BLOCK --- */
|
||||
.hero-image-wrapper {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.image-composition {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
.image-composition::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -10px;
|
||||
left: 20px;
|
||||
right: -20px;
|
||||
bottom: 10px;
|
||||
background-color: #ffffff;
|
||||
border-radius: 12px;
|
||||
transform: rotate(3deg);
|
||||
z-index: -1;
|
||||
opacity: 0;
|
||||
animation: fadeInRotate 0.8s ease 0.6s forwards;
|
||||
}
|
||||
|
||||
@keyframes fadeInRotate {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: rotate(0deg) translateY(20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: rotate(3deg) translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.main-image {
|
||||
width: 100%;
|
||||
border-radius: 12px;
|
||||
border: 8px solid #ffffff;
|
||||
filter: grayscale(100%);
|
||||
box-shadow: 0 30px 60px rgba(0,0,0,0.4);
|
||||
}
|
||||
|
||||
.experience-badge {
|
||||
position: absolute;
|
||||
bottom: 30px;
|
||||
left: -30px;
|
||||
background: #ffffff;
|
||||
padding: 1.5rem;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 15px 35px rgba(0,0,0,0.2);
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
.exp-number {
|
||||
font-size: 2.2rem;
|
||||
font-weight: 900;
|
||||
color: #1e3050;
|
||||
line-height: 1;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.exp-text {
|
||||
font-size: 0.7rem;
|
||||
font-weight: 800;
|
||||
color: #535e6c;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* --- АДАПТАЦИЯ --- */
|
||||
@media (max-width: 992px) {
|
||||
.hero-section {
|
||||
padding-top: 70px;
|
||||
min-height: auto;
|
||||
}
|
||||
|
||||
.hero-grid {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
padding-top: 1.5rem;
|
||||
}
|
||||
|
||||
.hero-content {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.hero-actions {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.hero-image-wrapper {
|
||||
margin-top: 3rem;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.experience-badge {
|
||||
left: 0;
|
||||
bottom: -20px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.hero-section {
|
||||
padding-top: 64px;
|
||||
}
|
||||
|
||||
.hero-title {
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
|
||||
.hero-actions {
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.hero-actions > * {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.image-composition::before {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.hero-section {
|
||||
padding-top: 64px;
|
||||
}
|
||||
|
||||
.hero-title {
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* Кастомные стили для кнопки "Мои услуги" */
|
||||
:global(.btn-services) {
|
||||
background: transparent !important;
|
||||
border: 2px solid #ffffff !important;
|
||||
color: #ffffff !important;
|
||||
padding: 0.875rem 1.5rem !important;
|
||||
font-size: 1.125rem !important;
|
||||
line-height: 1.75rem !important;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
z-index: 1;
|
||||
height: auto !important;
|
||||
min-height: 3.25rem !important;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
:global(.btn-services)::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -100%;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
|
||||
transition: left 0.5s ease;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
:global(.btn-services)::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 0;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.2));
|
||||
transition: width 0.4s ease;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
:global(.btn-services:hover) {
|
||||
background: rgba(255, 255, 255, 0.1) !important;
|
||||
border-color: #eac26e !important;
|
||||
color: #eac26e !important;
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 8px 25px rgba(234, 194, 110, 0.3);
|
||||
}
|
||||
|
||||
:global(.btn-services:hover)::before {
|
||||
left: 100%;
|
||||
}
|
||||
|
||||
:global(.btn-services:hover)::after {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
:global(.btn-services:active) {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 15px rgba(234, 194, 110, 0.2);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -45,10 +45,9 @@ import { COMPANY } from "@constants";
|
|||
</a>
|
||||
|
||||
<div class="header-actions" id="auth-section"></div>
|
||||
</div>
|
||||
|
||||
<div class="mobile-actions">
|
||||
<a href={`tel:${COMPANY.phoneClean}`} class="mobile-phone-btn" aria-label="Позонить: {COMPANY.phone}">
|
||||
<a href={`tel:${COMPANY.phoneClean}`} class="mobile-phone-btn" aria-label="Позони<EFBFBD><EFBFBD>ь: {COMPANY.phone}">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="20"
|
||||
|
|
@ -323,7 +322,30 @@ import { COMPANY } from "@constants";
|
|||
.header-phone {
|
||||
display: flex;
|
||||
}
|
||||
.mobile-phone-btn {
|
||||
.mobile-phone-btn,
|
||||
.burger-btn {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 992px) {
|
||||
.header-phone {
|
||||
display: none;
|
||||
}
|
||||
.mobile-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
.mobile-phone-btn,
|
||||
.burger-btn {
|
||||
display: flex;
|
||||
}
|
||||
.header-right {
|
||||
gap: 0.5rem;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.header-right > *:not(.mobile-actions) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import RatingStars from './RatingStars.astro';
|
|||
|
||||
export interface Props {
|
||||
name: string;
|
||||
car: string;
|
||||
profession: string;
|
||||
text: string;
|
||||
rating: number;
|
||||
initial: string;
|
||||
|
|
@ -15,7 +15,7 @@ export interface Props {
|
|||
|
||||
const {
|
||||
name,
|
||||
car,
|
||||
profession,
|
||||
text,
|
||||
rating,
|
||||
initial,
|
||||
|
|
@ -45,7 +45,7 @@ const formatDate = (dateStr: string) => {
|
|||
</div>
|
||||
<div class="author-details">
|
||||
<h3 class="author-name">{name}</h3>
|
||||
<p class="author-car">{car}</p>
|
||||
<p class="author-profession">{profession}</p>
|
||||
</div>
|
||||
</div>
|
||||
<time class="review-date">{formatDate(date)}</time>
|
||||
|
|
@ -143,7 +143,7 @@ const formatDate = (dateStr: string) => {
|
|||
margin: 0;
|
||||
}
|
||||
|
||||
.author-car {
|
||||
.author-profession {
|
||||
color: #64748b;
|
||||
font-size: 0.875rem;
|
||||
margin: 0;
|
||||
|
|
|
|||
397
frontend/src/components/reviews/ReviewForm.tsx
Normal file
397
frontend/src/components/reviews/ReviewForm.tsx
Normal file
|
|
@ -0,0 +1,397 @@
|
|||
import { createSignal, Show, For, createEffect } from "solid-js";
|
||||
|
||||
interface ReviewFormProps {
|
||||
onSubmit: (data: {
|
||||
name: string;
|
||||
surname: string;
|
||||
profession: string;
|
||||
rating: number;
|
||||
text: string;
|
||||
}) => void;
|
||||
onCancel?: () => void;
|
||||
user?: {
|
||||
name: string;
|
||||
email: string;
|
||||
avatar?: string;
|
||||
};
|
||||
}
|
||||
|
||||
const EMOJIS = [
|
||||
"👍", "👎", "❤️", "😊", "😂", "🎉", "🔥", "👏",
|
||||
"😢", "😮", "😡", "🙏", "⭐", "💯", "❤️🔥", "🤔",
|
||||
"👀", "💪", "🚀", "✨"
|
||||
];
|
||||
|
||||
const DANGEROUS_PATTERNS = [
|
||||
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
|
||||
/javascript:/gi,
|
||||
/on\w+\s*=/gi,
|
||||
/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,
|
||||
/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi,
|
||||
/<embed\b[^<]*>/gi,
|
||||
/data:text\/html/gi,
|
||||
/expression\s*\(/gi,
|
||||
/url\s*\(\s*['"]*\s*javascript:/gi,
|
||||
];
|
||||
|
||||
const MAX_TEXT_LENGTH = 2000;
|
||||
const MIN_TEXT_LENGTH = 50;
|
||||
const MAX_NAME_LENGTH = 50;
|
||||
const MAX_PROFESSION_LENGTH = 100;
|
||||
|
||||
interface ValidationErrors {
|
||||
name?: string;
|
||||
surname?: string;
|
||||
profession?: string;
|
||||
rating?: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
export default function ReviewForm(props: ReviewFormProps) {
|
||||
const [name, setName] = createSignal("");
|
||||
const [surname, setSurname] = createSignal("");
|
||||
const [profession, setProfession] = createSignal("");
|
||||
const [rating, setRating] = createSignal(0);
|
||||
const [text, setText] = createSignal("");
|
||||
const [errors, setErrors] = createSignal<ValidationErrors>({});
|
||||
const [touched, setTouched] = createSignal<{ [key: string]: boolean }>({});
|
||||
const [showEmojiPicker, setShowEmojiPicker] = createSignal(false);
|
||||
|
||||
createEffect(() => {
|
||||
if (props.user?.name) {
|
||||
const parts = props.user.name.split(" ");
|
||||
if (parts.length >= 2) {
|
||||
setName(parts[0]);
|
||||
setSurname(parts.slice(1).join(" "));
|
||||
} else {
|
||||
setName(props.user.name);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const sanitizeInput = (input: string): string => {
|
||||
return input
|
||||
.replace(/[<>]/g, "")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, "&");
|
||||
};
|
||||
|
||||
const containsDangerousContent = (input: string): boolean => {
|
||||
return DANGEROUS_PATTERNS.some((pattern) => pattern.test(input));
|
||||
};
|
||||
|
||||
const validateName = (value: string): string | undefined => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return "Имя обязательно";
|
||||
if (trimmed.length > MAX_NAME_LENGTH) return `Максимум ${MAX_NAME_LENGTH} символов`;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const validateSurname = (value: string): string | undefined => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return "Фамилия обязательна";
|
||||
if (trimmed.length > MAX_NAME_LENGTH) return `Максимум ${MAX_NAME_LENGTH} символов`;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const validateProfession = (value: string): string | undefined => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return "Профессия обязательна";
|
||||
if (trimmed.length > MAX_PROFESSION_LENGTH) return `Максимум ${MAX_PROFESSION_LENGTH} символов`;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const validateRating = (value: number): string | undefined => {
|
||||
if (!value || value < 1 || value > 5) return "Выберите оценку";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const validateText = (value: string): string | undefined => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return "Текст отзыва обязателен";
|
||||
if (trimmed.length < MIN_TEXT_LENGTH)
|
||||
return `Минимум ${MIN_TEXT_LENGTH} символов`;
|
||||
if (trimmed.length > MAX_TEXT_LENGTH)
|
||||
return `Максимум ${MAX_TEXT_LENGTH} символов`;
|
||||
if (containsDangerousContent(trimmed)) return "Обнаружен опасный контент";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const handleTextChange = (e: Event) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
let value = target.value;
|
||||
|
||||
if (containsDangerousContent(value)) {
|
||||
DANGEROUS_PATTERNS.forEach((pattern) => {
|
||||
value = value.replace(pattern, "");
|
||||
});
|
||||
}
|
||||
|
||||
if (value.length > MAX_TEXT_LENGTH) {
|
||||
value = value.slice(0, MAX_TEXT_LENGTH);
|
||||
}
|
||||
|
||||
setText(value);
|
||||
if (touched().text) {
|
||||
setErrors((prev) => ({ ...prev, text: validateText(value) }));
|
||||
}
|
||||
};
|
||||
|
||||
const addEmoji = (emoji: string) => {
|
||||
setText((prev) => prev + emoji);
|
||||
setShowEmojiPicker(false);
|
||||
};
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: ValidationErrors = {
|
||||
name: validateName(name()),
|
||||
surname: validateSurname(surname()),
|
||||
profession: validateProfession(profession()),
|
||||
rating: validateRating(rating()),
|
||||
text: validateText(text()),
|
||||
};
|
||||
|
||||
setErrors(newErrors);
|
||||
setTouched({
|
||||
name: true,
|
||||
surname: true,
|
||||
profession: true,
|
||||
rating: true,
|
||||
text: true,
|
||||
});
|
||||
|
||||
return !Object.values(newErrors).some((error) => error);
|
||||
};
|
||||
|
||||
const handleSubmit = (e: Event) => {
|
||||
e.preventDefault();
|
||||
if (!validateForm()) return;
|
||||
|
||||
props.onSubmit({
|
||||
name: sanitizeInput(name().trim()),
|
||||
surname: sanitizeInput(surname().trim()),
|
||||
profession: sanitizeInput(profession().trim()),
|
||||
rating: rating(),
|
||||
text: sanitizeInput(text().trim()),
|
||||
});
|
||||
|
||||
setName("");
|
||||
setSurname("");
|
||||
setProfession("");
|
||||
setRating(0);
|
||||
setText("");
|
||||
setErrors({});
|
||||
setTouched({});
|
||||
};
|
||||
|
||||
const handleBlur = (field: string) => {
|
||||
setTouched((prev) => ({ ...prev, [field]: true }));
|
||||
|
||||
const fieldValidators: Record<string, () => string | undefined> = {
|
||||
name: () => validateName(name()),
|
||||
surname: () => validateSurname(surname()),
|
||||
profession: () => validateProfession(profession()),
|
||||
rating: () => validateRating(rating()),
|
||||
text: () => validateText(text()),
|
||||
};
|
||||
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
[field]: fieldValidators[field](),
|
||||
}));
|
||||
};
|
||||
|
||||
const isValid = () => {
|
||||
return !errors().name && !errors().surname && !errors().profession &&
|
||||
!errors().rating && !errors().text &&
|
||||
name().trim() && surname().trim() && profession().trim() &&
|
||||
rating() > 0 && text().trim();
|
||||
};
|
||||
|
||||
const ratingOptions = [
|
||||
{ value: 5, label: "5 — Отлично" },
|
||||
{ value: 4, label: "4 — Хорошо" },
|
||||
{ value: 3, label: "3 — Удовлетворительно" },
|
||||
{ value: 2, label: "2 — Плохо" },
|
||||
{ value: 1, label: "1 — Очень плохо" },
|
||||
];
|
||||
|
||||
const getInputClass = (field: keyof ValidationErrors) => {
|
||||
const hasError = errors()[field] && touched()[field];
|
||||
return `w-full px-4 py-3 rounded-xl border transition-all resize-none bg-white text-gray-900 placeholder-gray-400 outline-none ${
|
||||
hasError
|
||||
? "border-red-300 focus:border-red-500 focus:ring-2 focus:ring-red-200"
|
||||
: "border-gray-200 focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
|
||||
}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} class="review-form max-w-700px mx-auto flex flex-col gap-6">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="text-sm font-semibold text-gray-900">Имя *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={name()}
|
||||
onInput={(e) => setName(e.currentTarget.value)}
|
||||
onBlur={() => handleBlur("name")}
|
||||
placeholder="Иван"
|
||||
class={getInputClass("name")}
|
||||
/>
|
||||
<Show when={errors().name && touched().name}>
|
||||
<p class="text-sm text-red-500 flex items-center gap-1">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
{errors().name}
|
||||
</p>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="text-sm font-semibold text-gray-900">Фамилия *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={surname()}
|
||||
onInput={(e) => setSurname(e.currentTarget.value)}
|
||||
onBlur={() => handleBlur("surname")}
|
||||
placeholder="Иванов"
|
||||
class={getInputClass("surname")}
|
||||
/>
|
||||
<Show when={errors().surname && touched().surname}>
|
||||
<p class="text-sm text-red-500 flex items-center gap-1">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
{errors().surname}
|
||||
</p>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="text-sm font-semibold text-gray-900">Профессия *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={profession()}
|
||||
onInput={(e) => setProfession(e.currentTarget.value)}
|
||||
onBlur={() => handleBlur("profession")}
|
||||
placeholder="Например: Предприниматель, Врач, Инженер..."
|
||||
class={getInputClass("profession")}
|
||||
/>
|
||||
<Show when={errors().profession && touched().profession}>
|
||||
<p class="text-sm text-red-500 flex items-center gap-1">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
{errors().profession}
|
||||
</p>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<label class="text-sm font-semibold text-gray-900">Оценка *</label>
|
||||
<select
|
||||
value={rating()}
|
||||
onChange={(e) => setRating(parseInt(e.currentTarget.value))}
|
||||
onBlur={() => handleBlur("rating")}
|
||||
class={getInputClass("rating")}
|
||||
>
|
||||
<option value="">Выберите оценку</option>
|
||||
<For each={ratingOptions}>
|
||||
{(option) => (
|
||||
<option value={option.value}>{option.label}</option>
|
||||
)}
|
||||
</For>
|
||||
</select>
|
||||
<Show when={errors().rating && touched().rating}>
|
||||
<p class="text-sm text-red-500 flex items-center gap-1">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
{errors().rating}
|
||||
</p>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="flex justify-between items-center">
|
||||
<label class="text-sm font-semibold text-gray-900">Ваш отзыв *</label>
|
||||
<div class="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowEmojiPicker(!showEmojiPicker())}
|
||||
class="p-2 text-gray-400 hover:text-blue-600 transition-colors rounded-lg hover:bg-gray-100"
|
||||
>
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
</button>
|
||||
<Show when={showEmojiPicker()}>
|
||||
<div class="absolute bottom-full right-0 mb-2 bg-white rounded-xl shadow-lg border border-gray-200 p-3 z-10 w-64">
|
||||
<div class="grid grid-cols-5 gap-2">
|
||||
<For each={EMOJIS}>
|
||||
{(emoji) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => addEmoji(emoji)}
|
||||
class="p-2 text-xl hover:bg-gray-100 rounded-lg transition-colors"
|
||||
>
|
||||
{emoji}
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
<textarea
|
||||
value={text()}
|
||||
onInput={handleTextChange}
|
||||
onBlur={() => handleBlur("text")}
|
||||
placeholder="Расскажите о вашем опыте работы с нами..."
|
||||
rows={5}
|
||||
class={getInputClass("text")}
|
||||
/>
|
||||
<div class="flex justify-between items-center">
|
||||
<Show when={errors().text && touched().text}>
|
||||
<p class="text-sm text-red-500 flex items-center gap-1">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
{errors().text}
|
||||
</p>
|
||||
</Show>
|
||||
<p
|
||||
class={`text-xs text-right ml-auto ${text().length > MAX_TEXT_LENGTH * 0.9 ? "text-orange-500" : "text-gray-400"}`}
|
||||
>
|
||||
{text().length}/{MAX_TEXT_LENGTH}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!isValid()}
|
||||
class="px-8 py-3 bg-gradient-to-b from-blue-600 to-blue-800 hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-xl transition-all flex items-center gap-2 hover:cursor-pointer group"
|
||||
>
|
||||
<svg
|
||||
class="w-5 h-5 transition-transform duration-300 group-hover:rotate-90"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/>
|
||||
</svg>
|
||||
Отправить отзыв
|
||||
</button>
|
||||
|
||||
<p class="text-xs text-gray-500 text-center">
|
||||
Нажимая кнопку, вы соглашаетесь с{" "}
|
||||
<a href="/privacy" class="text-blue-600 hover:underline">политикой конфиденциальности</a>
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
151
frontend/src/components/reviews/ReviewFormContainer.tsx
Normal file
151
frontend/src/components/reviews/ReviewFormContainer.tsx
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
import { createSignal, onMount, Show } from "solid-js";
|
||||
import ReviewForm from "./ReviewForm";
|
||||
|
||||
interface ToastMessage {
|
||||
type: "success" | "error";
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
avatar?: string;
|
||||
}
|
||||
|
||||
export default function ReviewFormContainer() {
|
||||
const [isAuthenticated, setIsAuthenticated] = createSignal(false);
|
||||
const [currentUser, setCurrentUser] = createSignal<User | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = createSignal(true);
|
||||
const [toast, setToast] = createSignal<ToastMessage | null>(null);
|
||||
|
||||
const showToast = (message: ToastMessage): void => {
|
||||
setToast(message);
|
||||
setTimeout(() => setToast(null), 3000);
|
||||
};
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const response = await fetch("/api/auth/me", {
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.authenticated && data.user) {
|
||||
setIsAuthenticated(true);
|
||||
setCurrentUser({
|
||||
id: data.user.id,
|
||||
name: data.user.name || "Пользователь",
|
||||
email: data.user.email,
|
||||
avatar: data.user.avatar,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[ReviewForm] Ошибка проверки авторизации:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
const handleSubmit = async (data: {
|
||||
name: string;
|
||||
surname: string;
|
||||
profession: string;
|
||||
rating: number;
|
||||
text: string;
|
||||
}) => {
|
||||
try {
|
||||
const response = await fetch("/api/reviews", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({
|
||||
name: data.name,
|
||||
surname: data.surname,
|
||||
profession: data.profession,
|
||||
rating: data.rating,
|
||||
text: data.text,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || "Failed to create review");
|
||||
}
|
||||
|
||||
showToast({ type: "success", message: "Спасибо! Ваш отзыв отправлен на модерацию." });
|
||||
} catch (error) {
|
||||
console.error("[ReviewForm] Ошибка создания отзыва:", error);
|
||||
showToast({ type: "error", message: "Не удалось отправить отзыв. Попробуйте позже." });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Show when={toast()}>
|
||||
{(t) => (
|
||||
<div
|
||||
class={`fixed bottom-4 right-4 px-6 py-3 rounded-xl shadow-lg transition-all duration-300 z-50 ${
|
||||
t().type === "success"
|
||||
? "bg-green-500 text-white"
|
||||
: "bg-red-500 text-white"
|
||||
}`}
|
||||
>
|
||||
{t().message}
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
|
||||
<Show when={isLoading()}>
|
||||
<div class="max-w-700px mx-auto text-center py-12">
|
||||
<div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div>
|
||||
<p class="mt-4 text-gray-600">Загрузка...</p>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<Show when={!isLoading()}>
|
||||
<Show when={isAuthenticated()} fallback={
|
||||
<div class="max-w-700px mx-auto">
|
||||
<div class="bg-linear-to-br from-gray-50 to-gray-100 rounded-2xl p-8 md:p-12 border border-gray-200 text-center" style="background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);">
|
||||
<div class="w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center" style="background: linear-gradient(135deg, rgba(37, 99, 235, 0.2) 0%, rgba(30, 64, 175, 0.3) 100%);">
|
||||
<svg class="w-10 h-10 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h4 class="text-xl font-semibold text-gray-900 mb-3">
|
||||
Авторизуйтесь, чтобы оставить отзыв
|
||||
</h4>
|
||||
<p class="text-gray-600 mb-6">
|
||||
Чтобы поделиться своим опытом, пожалуйста, войдите в личный кабинет.
|
||||
</p>
|
||||
<a
|
||||
href={`/auth/sign-in?redirect=${encodeURIComponent(window.location.pathname)}`}
|
||||
class="inline-flex items-center justify-center font-semibold transition-all duration-300 rounded-md cursor-pointer px-6 py-3 text-lg"
|
||||
style="background: linear-gradient(to bottom, #2563eb, #1e40af); color: white; box-shadow: 0 2px 4px rgba(37, 99, 235, 0.3);"
|
||||
>
|
||||
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"/>
|
||||
</svg>
|
||||
Войти в кабинет
|
||||
</a>
|
||||
<p class="mt-4 text-sm text-gray-600">
|
||||
Нет аккаунта?{" "}
|
||||
<a
|
||||
href={`/auth/sign-up?redirect=${encodeURIComponent(window.location.pathname)}`}
|
||||
class="font-medium hover:underline"
|
||||
style="color: #2563eb;"
|
||||
>
|
||||
Зарегистрироваться
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
}>
|
||||
<ReviewForm onSubmit={handleSubmit} user={currentUser()} />
|
||||
</Show>
|
||||
</Show>
|
||||
</>
|
||||
);
|
||||
}
|
||||
170
frontend/src/components/reviews/ReviewsList.tsx
Normal file
170
frontend/src/components/reviews/ReviewsList.tsx
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
import { createSignal, For, Show, onMount, createMemo } from "solid-js";
|
||||
import ReviewCard from "./ReviewCard.astro";
|
||||
import type { Review } from "../../data/reviewsData";
|
||||
|
||||
interface ReviewRecord {
|
||||
id: string;
|
||||
name: string;
|
||||
surname?: string;
|
||||
profession?: string;
|
||||
text: string;
|
||||
rating: number;
|
||||
status: string;
|
||||
votesCount: number;
|
||||
created: string;
|
||||
expand?: {
|
||||
user?: {
|
||||
id: string;
|
||||
name: string;
|
||||
firstName?: string;
|
||||
email: string;
|
||||
avatar?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
interface ReviewsListProps {
|
||||
initialReviews?: Review[];
|
||||
}
|
||||
|
||||
const colors = [
|
||||
"bg-blue-100 text-blue-600", "bg-teal-100 text-teal-600", "bg-orange-100 text-orange-600",
|
||||
"bg-pink-100 text-pink-600", "bg-purple-100 text-purple-600", "bg-indigo-100 text-indigo-600",
|
||||
"bg-green-100 text-green-600", "bg-yellow-100 text-yellow-600", "bg-red-100 text-red-600"
|
||||
];
|
||||
|
||||
export default function ReviewsList(props: ReviewsListProps) {
|
||||
const [isLoading, setIsLoading] = createSignal(true);
|
||||
const [reviews, setReviews] = createSignal<ReviewRecord[]>([]);
|
||||
const [error, setError] = createSignal<string | null>(null);
|
||||
|
||||
const loadReviews = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await fetch("/api/reviews", {
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch reviews");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setReviews(data.items || []);
|
||||
} catch (err) {
|
||||
console.error("[ReviewsList] Error:", err);
|
||||
setError("Не удалось загрузить отзывы");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
loadReviews();
|
||||
});
|
||||
|
||||
const formatDate = (dateStr: string) => {
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleDateString("ru-RU", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
year: "numeric"
|
||||
});
|
||||
};
|
||||
|
||||
const getAvatarInfo = (name: string) => {
|
||||
const initial = name.charAt(0).toUpperCase();
|
||||
const color = colors[initial.charCodeAt(0) % colors.length];
|
||||
return { initial, color };
|
||||
};
|
||||
|
||||
const votingSummary = createMemo(() => {
|
||||
const allReviews = reviews();
|
||||
const totalReviews = allReviews.length;
|
||||
const totalRating = allReviews.reduce((sum, r) => sum + r.rating, 0);
|
||||
const averageRating = totalReviews > 0 ? parseFloat((totalRating / totalReviews).toFixed(1)) : 0;
|
||||
const totalVotes = allReviews.reduce((sum, r) => sum + (r.votesCount || 0), 0);
|
||||
const distribution = allReviews.reduce((acc, r) => {
|
||||
acc[r.rating] = (acc[r.rating] || 0) + 1;
|
||||
return acc;
|
||||
}, {} as Record<number, number>);
|
||||
return { averageRating, totalVotes, totalReviews, ratingDistribution: distribution };
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<Show when={isLoading()}>
|
||||
<div class="text-center py-12">
|
||||
<div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div>
|
||||
<p class="mt-4 text-gray-600">Загрузка отзывов...</p>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<Show when={error()}>
|
||||
<div class="text-center py-12 text-red-500">
|
||||
<p>{error()}</p>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<Show when={!isLoading() && !error()}>
|
||||
{/* Статистика голосования - можно вынести в отдельный компонент */}
|
||||
<Show when={reviews().length > 0}>
|
||||
<div class="voting-summary mb-12 p-6 bg-white rounded-2xl border border-gray-100 shadow-sm">
|
||||
<div class="flex items-center justify-between flex-wrap gap-4">
|
||||
<div class="flex items-center gap-4">
|
||||
<div class="text-5xl font-bold text-gray-900">{votingSummary().averageRating}</div>
|
||||
<div>
|
||||
<div class="flex gap-1 mb-1">
|
||||
<For each={[1, 2, 3, 4, 5]}>
|
||||
{(star) => (
|
||||
<svg
|
||||
class={`w-5 h-5 ${star <= Math.round(votingSummary().averageRating) ? "text-yellow-400" : "text-gray-300"}`}
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
|
||||
</svg>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
<p class="text-sm text-gray-500">{votingSummary().totalReviews} отзывов</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<p class="text-sm text-gray-500">{votingSummary().totalVotes} голосов</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
{/* Сетка отзывов */}
|
||||
<Show when={reviews().length > 0} fallback={
|
||||
<div class="text-center py-12 text-gray-500">
|
||||
<p>Пока нет отзывов. Будьте первым!</p>
|
||||
</div>
|
||||
}>
|
||||
<div class="reviews-grid">
|
||||
<For each={reviews()}>
|
||||
{(review) => {
|
||||
const avatarInfo = getAvatarInfo(review.name);
|
||||
return (
|
||||
<ReviewCard
|
||||
name={`${review.name} ${review.surname || ""}`.trim()}
|
||||
profession={review.profession || "Клиент"}
|
||||
text={review.text}
|
||||
rating={review.rating}
|
||||
initial={avatarInfo.initial}
|
||||
color={avatarInfo.color}
|
||||
date={formatDate(review.created)}
|
||||
votesCount={review.votesCount || 0}
|
||||
isHelpful={false}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
</For>
|
||||
</div>
|
||||
</Show>
|
||||
</Show>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
export interface Review {
|
||||
id: number;
|
||||
name: string;
|
||||
car: string;
|
||||
surname?: string;
|
||||
profession: string;
|
||||
text: string;
|
||||
rating: number;
|
||||
avatar: { initial: string; color: string; };
|
||||
|
|
@ -14,7 +15,7 @@ const reviewsRaw = [
|
|||
{
|
||||
id: 1,
|
||||
name: "Алексей М.",
|
||||
car: "Toyota Camry",
|
||||
profession: "Предприниматель",
|
||||
text: "Помогли вернуть права после того, как инспектор незаконно составил протокол за встречку. Юрист нашел кучу ошибок в схеме ДТП. Огромное спасибо!",
|
||||
rating: 5,
|
||||
date: "2024-03-15",
|
||||
|
|
@ -24,7 +25,7 @@ const reviewsRaw = [
|
|||
{
|
||||
id: 2,
|
||||
name: "Екатерина П.",
|
||||
car: "Hyundai Solaris",
|
||||
profession: "Бухгалтер",
|
||||
text: "Страховая выплатила копейки по ОСАГО. Обратилась сюда, сделали независимую экспертизу и через суд взыскали еще 120 тысяч. Профессионалы!",
|
||||
rating: 5,
|
||||
date: "2024-03-10",
|
||||
|
|
@ -34,7 +35,7 @@ const reviewsRaw = [
|
|||
{
|
||||
id: 3,
|
||||
name: "Игорь С.",
|
||||
car: "Lexus RX",
|
||||
profession: "IT-специалист",
|
||||
text: "Грамотно разобрали сложное ДТП на перекрестке. Доказали, что я не виноват, хотя ГИБДД изначально решило иначе. Лучшие в Сургуте.",
|
||||
rating: 5,
|
||||
date: "2024-03-05",
|
||||
|
|
@ -44,7 +45,7 @@ const reviewsRaw = [
|
|||
{
|
||||
id: 4,
|
||||
name: "Марина К.",
|
||||
car: "Kia Rio",
|
||||
profession: "Менеджер",
|
||||
text: "Обратилась по вопросу возврата прав после лишения. Всё сделали быстро и профессионально. Через 2 месяца права уже были у меня. Рекомендую!",
|
||||
rating: 4,
|
||||
date: "2024-02-28",
|
||||
|
|
@ -54,7 +55,7 @@ const reviewsRaw = [
|
|||
{
|
||||
id: 5,
|
||||
name: "Дмитрий В.",
|
||||
car: "Volkswagen Tiguan",
|
||||
profession: "Инженер",
|
||||
text: "Были проблемы со страховой после ДТП. Юристы помогли составить претензию, потом представляли интересы в суде. Выиграли дело полностью.",
|
||||
rating: 5,
|
||||
date: "2024-02-20",
|
||||
|
|
@ -64,7 +65,7 @@ const reviewsRaw = [
|
|||
{
|
||||
id: 6,
|
||||
name: "Ольга Н.",
|
||||
car: "Mazda CX-5",
|
||||
profession: "Врач",
|
||||
text: "Купила б/у авто с проблемами, которые не были указаны при продаже. Юристы помогли вернуть деньги через суд. Очень благодарна за помощь!",
|
||||
rating: 5,
|
||||
date: "2024-02-15",
|
||||
|
|
@ -74,7 +75,7 @@ const reviewsRaw = [
|
|||
{
|
||||
id: 7,
|
||||
name: "Сергей Т.",
|
||||
car: "Nissan Qashqai",
|
||||
profession: "Водитель",
|
||||
text: "Спор со страховой длился полгода. Сам не мог ничего добиться. Обратился сюда - ребята за 2 месяца решили вопрос в мою пользу. Супер!",
|
||||
rating: 4,
|
||||
date: "2024-02-08",
|
||||
|
|
@ -84,7 +85,7 @@ const reviewsRaw = [
|
|||
{
|
||||
id: 8,
|
||||
name: "Анна Р.",
|
||||
car: "Skoda Octavia",
|
||||
profession: "Учитель",
|
||||
text: "Помогли оспорить штраф с камеры, который пришел ошибочно. Юрист быстро разобрался в ситуации и подготовил все документы. Спасибо!",
|
||||
rating: 5,
|
||||
date: "2024-02-01",
|
||||
|
|
@ -94,7 +95,7 @@ const reviewsRaw = [
|
|||
{
|
||||
id: 9,
|
||||
name: "Виктор Л.",
|
||||
car: "Honda CR-V",
|
||||
profession: "Предприниматель",
|
||||
text: "Обратился по вопросу компенсации после ДТП. Страховая занижала выплату в 3 раза. Сделали экспертизу и через суд добились справедливой суммы.",
|
||||
rating: 5,
|
||||
date: "2024-01-25",
|
||||
|
|
|
|||
132
frontend/src/pages/api/reviews/index.ts
Normal file
132
frontend/src/pages/api/reviews/index.ts
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
import type { APIRoute } from "astro";
|
||||
|
||||
const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || "http://localhost:8090";
|
||||
|
||||
export const POST: APIRoute = async ({ request, cookies }) => {
|
||||
const pbAuthCookie = cookies.get("pb_auth")?.value;
|
||||
const token = pbAuthCookie?.trim();
|
||||
|
||||
if (!token) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Unauthorized" }),
|
||||
{ status: 401, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
let userId: string | null = null;
|
||||
const userResponse = await fetch(
|
||||
`${POCKETBASE_URL}/api/collections/users/auth-refresh`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
if (userResponse.ok) {
|
||||
const userData = await userResponse.json();
|
||||
userId = userData.record?.id;
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Unauthorized" }),
|
||||
{ status: 401, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, surname, profession, rating, text } = body;
|
||||
|
||||
if (!name || !surname || !profession || !rating || !text) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Все поля обязательны" }),
|
||||
{ status: 400, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
if (text.length < 50 || text.length > 2000) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Текст отзыва должен быть от 50 до 2000 символов" }),
|
||||
{ status: 400, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
if (rating < 1 || rating > 5) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Оценка должна быть от 1 до 5" }),
|
||||
{ status: 400, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`${POCKETBASE_URL}/api/collections/reviews/records`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
surname,
|
||||
profession,
|
||||
rating,
|
||||
text,
|
||||
status: "pending",
|
||||
votesCount: 0,
|
||||
user: userId,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
return new Response(JSON.stringify(data), {
|
||||
status: response.status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify(data), {
|
||||
status: 201,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[Reviews API POST] Error:", error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Failed to create review" }),
|
||||
{ status: 500, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const GET: APIRoute = async ({ url }) => {
|
||||
const status = url.searchParams.get("status") || "published";
|
||||
const expand = "user";
|
||||
const sort = "-created";
|
||||
|
||||
let filter = `status = "${status}"`;
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${POCKETBASE_URL}/api/collections/reviews/records?expand=${expand}&filter=${encodeURIComponent(filter)}&sort=${sort}`,
|
||||
{}
|
||||
);
|
||||
|
||||
const data = await response.json();
|
||||
return new Response(JSON.stringify(data), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[Reviews API GET] Error:", error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Failed to fetch reviews" }),
|
||||
{ status: 500, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
import Layout from '@layouts/Layout.astro';
|
||||
import PageHero from '@components/base/PageHero.astro';
|
||||
import Hero from '@components/home/Hero.astro';
|
||||
import Services from "@components/home/Services.astro";
|
||||
import Steps from "@components/home/Steps.astro";
|
||||
import WhyUs from "@components/home/WhyUs.astro";
|
||||
|
|
@ -14,7 +14,7 @@ import { SITE_URL } from '@constants';
|
|||
description="Профессиональная юридическая помощь автовладельцам в Сургуте. Споры со страховыми, возврат прав, ДТП, споры с автосалонами."
|
||||
canonicalLink={SITE_URL}
|
||||
>
|
||||
<PageHero
|
||||
<Hero
|
||||
badgeText="ЗАЩИТА ВОДИТЕЛЕЙ В СУРГУТЕ"
|
||||
titleWhite="Защитите свои права"
|
||||
titleGold="и водительское удостоверение"
|
||||
|
|
|
|||
|
|
@ -4,13 +4,12 @@ import { SITE_URL } from '@constants';
|
|||
import PageHero from '@components/base/PageHero.astro';
|
||||
import Pagination from '@components/base/Pagination.astro';
|
||||
import ReviewCard from '@components/reviews/ReviewCard.astro';
|
||||
import ReviewFormContainer from '@components/reviews/ReviewFormContainer.tsx';
|
||||
import ReviewsList from '@components/reviews/ReviewsList.tsx';
|
||||
import VotingSummary from '@components/reviews/VotingSummary.astro';
|
||||
import AuthLockBlock from '@components/base/AuthLockBlock.astro';
|
||||
import { reviewsData, votingSummary } from '@data/reviewsData';
|
||||
|
||||
// Логика авторизации (пока статичная переменная)
|
||||
const isAuthorized = true; // Измените на true, чтобы увидеть форму
|
||||
|
||||
const REVIEWS_PER_PAGE = 6;
|
||||
const currentPage = 1;
|
||||
const totalPages = Math.ceil(reviewsData.length / REVIEWS_PER_PAGE);
|
||||
|
|
@ -48,39 +47,8 @@ const paginatedReviews = reviewsData.slice(startIndex, endIndex);
|
|||
<section class="reviews-page">
|
||||
<div class="site-container">
|
||||
|
||||
<!-- Блок статистики голосования -->
|
||||
<VotingSummary
|
||||
averageRating={votingSummary.averageRating}
|
||||
totalVotes={votingSummary.totalVotes}
|
||||
totalReviews={votingSummary.totalReviews}
|
||||
ratingDistribution={votingSummary.ratingDistribution}
|
||||
/>
|
||||
|
||||
<!-- Сетка отзывов -->
|
||||
<div class="reviews-grid">
|
||||
{paginatedReviews.map((review) => (
|
||||
<ReviewCard
|
||||
name={review.name}
|
||||
car={review.car}
|
||||
text={review.text}
|
||||
rating={review.rating}
|
||||
initial={review.initial}
|
||||
color={review.color}
|
||||
date={review.date}
|
||||
votesCount={review.votesCount}
|
||||
isHelpful={review.isHelpful}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<!-- Пагинация -->
|
||||
{totalPages > 1 && (
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalPages={totalPages}
|
||||
baseUrl="/reviews"
|
||||
/>
|
||||
)}
|
||||
<!-- Блок статистики голосования -->
|
||||
<ReviewsList client:load />
|
||||
|
||||
<!-- Форма для отзыва -->
|
||||
<section class="review-form-section">
|
||||
|
|
@ -94,80 +62,7 @@ const paginatedReviews = reviewsData.slice(startIndex, endIndex);
|
|||
</p>
|
||||
</div>
|
||||
|
||||
{isAuthorized ? (
|
||||
<form class="review-form animate-on-scroll" data-animation="fade-up" data-delay="200" action="#" method="POST" id="review-form">
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="review-name" class="form-label">Имя *</label>
|
||||
<input
|
||||
type="text"
|
||||
id="review-name"
|
||||
name="name"
|
||||
class="form-input"
|
||||
placeholder="Иван"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="review-surname" class="form-label">Фамилия *</label>
|
||||
<input
|
||||
type="text"
|
||||
id="review-surname"
|
||||
name="surname"
|
||||
class="form-input"
|
||||
placeholder="Иванов"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="review-rating" class="form-label">Оценка *</label>
|
||||
<select
|
||||
id="review-rating"
|
||||
name="rating"
|
||||
class="form-input"
|
||||
required
|
||||
>
|
||||
<option value="">Выберите оценку</option>
|
||||
<option value="5">5 — Отлично</option>
|
||||
<option value="4">4 — Хорошо</option>
|
||||
<option value="3">3 — Удовлетворительно</option>
|
||||
<option value="2">2 — Плохо</option>
|
||||
<option value="1">1 — Очень плохо</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="review-text" class="form-label">Ваш отзыв *</label>
|
||||
<textarea
|
||||
id="review-text"
|
||||
name="review"
|
||||
class="form-textarea"
|
||||
placeholder="Расскажите о вашем опыте работы с нами..."
|
||||
rows="5"
|
||||
required
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="submit-btn">
|
||||
Отправить отзыв
|
||||
</button>
|
||||
|
||||
<p class="form-privacy">
|
||||
Нажимая кнопку, вы соглашаетесь с
|
||||
<a href="/privacy" class="privacy-link">политикой конфиденциальности</a>
|
||||
</p>
|
||||
</form>
|
||||
) : (
|
||||
<AuthLockBlock
|
||||
title="Авторизуйтесь, чтобы оставить отзыв"
|
||||
description="Чтобы поделиться своим опытом, пожалуйста, войдите в личный кабинет."
|
||||
buttonText="Войти в кабинет"
|
||||
buttonHref="/auth/sign-in"
|
||||
className="animate-on-scroll"
|
||||
/>
|
||||
)}
|
||||
<ReviewFormContainer client:load />
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
|
@ -311,20 +206,6 @@ const paginatedReviews = reviewsData.slice(startIndex, endIndex);
|
|||
});
|
||||
};
|
||||
|
||||
// Обработка формы отзыва
|
||||
const setupReviewForm = () => {
|
||||
const form = document.getElementById('review-form') as HTMLFormElement;
|
||||
if (form) {
|
||||
form.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(form);
|
||||
console.log('Отправка отзыва:', Object.fromEntries(formData));
|
||||
alert('Спасибо! Ваш отзыв отправлен на модерацию.');
|
||||
form.reset();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Запуск
|
||||
setupAnimations();
|
||||
setupReviewForm();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue