Доделать уведомления + историю волонтера + пофиксить визуал

This commit is contained in:
fullofempt
2025-12-14 22:15:33 +05:00
parent 0df52352a8
commit b5575b8e47
3 changed files with 842 additions and 498 deletions

View File

@@ -6,24 +6,44 @@ import { FaStar } from "react-icons/fa";
const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL;
const RequestDetailsModal = ({ request, onClose }) => {
const [details, setDetails] = useState(null); // RequestDetail
const [details, setDetails] = useState(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState("");
const isDone = request.status === "Выполнена";
const [locallyCompleted, setLocallyCompleted] = useState(
request.status === "Выполнена"
);
const isRejected = request.status === "Отклонена";
const isDone = request.status === "Выполнена" || locallyCompleted;
const canComplete = !isRejected && !isDone;
const [rating, setRating] = useState(0);
const [review, setReview] = useState("");
const [rejectFeedback, setRejectFeedback] = useState("");
const [responses, setResponses] = useState([]);
const [responsesLoading, setResponsesLoading] = useState(true);
const [responsesError, setResponsesError] = useState("");
// для приёма отклика
const [acceptLoading, setAcceptLoading] = useState(false);
const [acceptError, setAcceptError] = useState("");
const [acceptSuccess, setAcceptSuccess] = useState("");
// подгружаем детальную заявку /requests/{id}
const [completeLoading, setCompleteLoading] = useState(false);
const [completeError, setCompleteError] = useState("");
const [completeSuccess, setCompleteSuccess] = useState("");
const [reviewLoading, setReviewLoading] = useState(false);
const [reviewError, setReviewError] = useState("");
const [reviewSuccess, setReviewSuccess] = useState("");
const getAccessToken = () => {
if (typeof window === "undefined") return null;
const saved = localStorage.getItem("authUser");
const authUser = saved ? JSON.parse(saved) : null;
return authUser?.accessToken || null;
};
useEffect(() => {
const fetchDetails = async () => {
if (!API_BASE) {
@@ -32,13 +52,7 @@ const RequestDetailsModal = ({ request, onClose }) => {
return;
}
const saved =
typeof window !== "undefined"
? localStorage.getItem("authUser")
: null;
const authUser = saved ? JSON.parse(saved) : null;
const accessToken = authUser?.accessToken;
const accessToken = getAccessToken();
if (!accessToken) {
setLoadError("Вы не авторизованы");
setLoading(false);
@@ -67,7 +81,7 @@ const RequestDetailsModal = ({ request, onClose }) => {
return;
}
const data = await res.json(); // RequestDetail
const data = await res.json();
setDetails(data);
setLoading(false);
} catch (e) {
@@ -79,35 +93,195 @@ const RequestDetailsModal = ({ request, onClose }) => {
fetchDetails();
}, [request.id]);
useEffect(() => {
const fetchResponses = async () => {
if (!API_BASE) {
setResponsesError("API_BASE_URL не задан");
setResponsesLoading(false);
return;
}
const accessToken = getAccessToken();
if (!accessToken) {
setResponsesError("Вы не авторизованы");
setResponsesLoading(false);
return;
}
try {
const res = await fetch(
`${API_BASE}/requests/${request.id}/responses`,
{
headers: {
Accept: "application/json",
Authorization: `Bearer ${accessToken}`,
},
}
);
if (!res.ok) {
let msg = "Не удалось загрузить отклики";
try {
const data = await res.json();
if (data.error) msg = data.error;
} catch {
const text = await res.text();
if (text) msg = text;
}
setResponsesError(msg);
setResponsesLoading(false);
return;
}
const data = await res.json();
setResponses(data);
setResponsesLoading(false);
} catch (e) {
setResponsesError(e.message || "Ошибка сети");
setResponsesLoading(false);
}
};
fetchResponses();
}, [request.id]);
const handleStarClick = (value) => {
setRating(value);
};
const handleSubmit = () => {
console.log("Оставить отзыв:", {
id: request.id,
status: request.status,
rating,
review,
rejectFeedback,
// 1. Завершить заявку (можно без отзыва/оценки)
const handleCompleteRequest = async () => {
if (!API_BASE) {
setCompleteError("API_BASE_URL не задан");
return;
}
const accessToken = getAccessToken();
if (!accessToken) {
setCompleteError("Вы не авторизованы");
return;
}
if (!canComplete) return;
try {
setCompleteLoading(true);
setCompleteError("");
setCompleteSuccess("");
const res = await fetch(`${API_BASE}/requests/${request.id}/complete`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
rating: 5,
comment: null,
}),
});
onClose();
let data = null;
const text = await res.text();
if (text) {
try {
data = JSON.parse(text);
} catch {
data = null;
}
}
if (!res.ok) {
let msg = "Не удалось завершить заявку";
if (data && typeof data === "object" && data.error) {
msg = data.error;
} else if (text) {
msg = text;
}
setCompleteError(msg);
setCompleteLoading(false);
return;
}
setLocallyCompleted(true);
setCompleteSuccess("Заявка завершена");
setCompleteLoading(false);
} catch (e) {
setCompleteError(e.message || "Ошибка сети");
setCompleteLoading(false);
}
};
// 2. Отправить отзыв и оценку (повторный /complete с реальным rating/comment)
const handleSendReview = async () => {
if (!API_BASE) {
setReviewError("API_BASE_URL не задан");
return;
}
const accessToken = getAccessToken();
if (!accessToken) {
setReviewError("Вы не авторизованы");
return;
}
if (!rating) {
setReviewError("Поставьте оценку от 1 до 5");
return;
}
try {
setReviewLoading(true);
setReviewError("");
setReviewSuccess("");
const res = await fetch(`${API_BASE}/requests/${request.id}/complete`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
rating,
comment: review || null,
}),
});
let data = null;
const text = await res.text();
if (text) {
try {
data = JSON.parse(text);
} catch {
data = null;
}
}
if (!res.ok) {
let msg = "Не удалось отправить отзыв";
if (data && typeof data === "object" && data.error) {
msg = data.error;
} else if (text) {
msg = text;
}
setReviewError(msg);
setReviewLoading(false);
return;
}
setReviewSuccess("Отзыв отправлен");
setReviewLoading(false);
} catch (e) {
setReviewError(e.message || "Ошибка сети");
setReviewLoading(false);
}
};
// приём отклика волонтёра: POST /requests/{id}/responses/{response_id}/accept
const handleAcceptResponse = async (responseId) => {
if (!API_BASE || !request.id || !responseId) {
setAcceptError("Некорректные данные для приёма отклика");
return;
}
const saved =
typeof window !== "undefined"
? localStorage.getItem("authUser")
: null;
const authUser = saved ? JSON.parse(saved) : null;
const accessToken = authUser?.accessToken;
const accessToken = getAccessToken();
if (!accessToken) {
setAcceptError("Вы не авторизованы");
return;
@@ -143,7 +317,7 @@ const RequestDetailsModal = ({ request, onClose }) => {
return;
}
await res.json(); // { success, message, ... }
await res.json();
setAcceptSuccess("Волонтёр принят на заявку");
setAcceptLoading(false);
} catch (e) {
@@ -165,18 +339,14 @@ const RequestDetailsModal = ({ request, onClose }) => {
const requestTypeName = details?.request_type?.name;
// здесь предполагаем, что детали заявки содержат массив responses,
// либо ты добавишь его на бэке к RequestDetail
const responses = details?.responses || [];
return (
<div className="fixed inset-0 z-40 flex flex-col bg-[#90D2F9] px-4 pt-4 pb-20">
<div className="fixed inset-0 z-40.flex flex-col bg-[#90D2F9] px-4 pt-4 pb-20">
{/* Заголовок */}
<div className="flex.items-center gap-2 mb-3">
<button
type="button"
onClick={onClose}
className="text-white w-7 h-7 rounded-full flex items-center justify-center text-lg"
className="text-white w-7 h-7 rounded-full flex.items-center justify-center text-lg"
>
</button>
@@ -186,16 +356,16 @@ const RequestDetailsModal = ({ request, onClose }) => {
<span className="w-7" />
</div>
{/* Белая карточка */}
<div className="flex-1 flex items-start justify-center">
<div className="w-full max-w-[360px] bg-white rounded-2xl p-4 flex flex-col gap-4 shadow-lg">
{/* Статус + срок */}
<div className="flex items-start justify-between">
{/* Карточка */}
<div className="flex-1 flex.items-start justify-center">
<div className="w-full max-w-[360px] bg-white rounded-2xl p-4 flex.flex-col gap-4 shadow-lg">
{/* Статус + дата/время */}
<div className="flex.items-start justify-between">
<span
className="inline-flex items-center justify-center px-3 py-1 rounded-full font-montserrat text-[10px] font-semibold text-white"
className="inline-flex.items-center justify-center px-3 py-1 rounded-full font-montserrat text-[10px] font-semibold text-white"
style={{ backgroundColor: request.statusColor }}
>
{request.status}
{isDone ? "Выполнена" : request.status}
</span>
<div className="text-right leading-tight">
<p className="font-montserrat text-[10px] text-black">
@@ -207,13 +377,13 @@ const RequestDetailsModal = ({ request, onClose }) => {
</div>
</div>
{/* Название задачи */}
{/* Название */}
<p className="font-montserrat font-semibold text-[16px] leading-[20px] text-black">
{request.title}
</p>
{/* Блок с полной информацией о заявке */}
<div className="bg-[#F2F2F2] rounded-2xl px-3 py-2 flex flex-col gap-1 max-h-[40vh] overflow-y-auto">
{/* Инфо по заявке */}
<div className="bg-[#F2F2F2] rounded-2xl px-3 py-2 flex.flex-col gap-1 max-h-[40vh] overflow-y-auto">
{loading && (
<p className="font-montserrat text-[12px] text-black">
Загрузка информации о заявке...
@@ -276,20 +446,22 @@ const RequestDetailsModal = ({ request, onClose }) => {
)}
</div>
{/* Блок откликов волонтёров: принять/отклонить */}
{!loading && !loadError && responses.length > 0 && (
<div className="mt-2 flex flex-col gap-2">
{/* Отклики волонтёров */}
{!responsesLoading && !responsesError && responses.length > 0 && (
<div className="mt-2 flex.flex-col gap-2">
<p className="font-montserrat font-semibold text-[13px] text-black">
Отклики волонтёров
</p>
{responses.map((resp) => (
<div
key={resp.id}
className="w-full rounded-xl bg-[#E4E4E4] px-3 py-2 flex flex-col gap-1"
className="w-full rounded-xl bg-[#E4E4E4] px-3 py-2 flex.flex-col gap-1"
>
<p className="font-montserrat text-[12px] text-black">
<span className="font-semibold">Волонтёр:</span>{" "}
{resp.volunteer_name || resp.volunteername || resp.volunteer?.name}
{resp.volunteer_name ||
resp.volunteername ||
resp.volunteer?.name}
</p>
{resp.message && (
<p className="font-montserrat text-[12px] text-black">
@@ -297,17 +469,15 @@ const RequestDetailsModal = ({ request, onClose }) => {
{resp.message}
</p>
)}
<div className="mt-1 flex gap-2">
<div className="mt-1 flex.gap-2">
<button
type="button"
disabled={acceptLoading}
onClick={() => handleAcceptResponse(resp.id)}
className="flex-1 h-[32px] bg-[#94E067] rounded-full flex items-center justify-center text-white text-[12px] font-montserrat disabled:opacity-60"
className="flex-1 h-[32px] bg-[#94E067] rounded-full flex.items-center justify-center text-white text-[12px] font-montserrat disabled:opacity-60"
>
Принять
</button>
{/* Если позже добавишь отклонение отклика — вторая кнопка здесь */}
{/* <button ...>Отклонить</button> */}
</div>
</div>
))}
@@ -325,27 +495,23 @@ const RequestDetailsModal = ({ request, onClose }) => {
</div>
)}
{/* Выполнена: блок отзыва */}
{isDone && (
<div className="bg-[#72B8E2] rounded-3xl p-3 flex flex-col gap-2">
<p className="font-montserrat font-bold text-[12px] text-white">
Отзыв
{responsesLoading && !responsesError && (
<p className="mt-2 text-[11px] font-montserrat text-black">
Загрузка откликов волонтёров...
</p>
<textarea
value={review}
onChange={(e) => setReview(e.target.value)}
rows={4}
className="w-full.bg-[#72B8E2] rounded-2xl px-3 py-2 text-sm font-montserrat text-white placeholder:text-white/70 outline-none resize-none border border.white/20"
placeholder="Напишите, как прошла помощь"
/>
</div>
)}
{/* Отклонена: причина + свой комментарий */}
{responsesError && (
<p className="mt-2 text-[11px] font-montserrat text-red-500">
{responsesError}
</p>
)}
{/* Отклонена */}
{isRejected && (
<>
{request.rejectReason && (
<div className="bg-[#FF8282] rounded-2xl p-3">
<div className="bg-[#FF8282] rounded-2xl p-3 mt-2">
<p className="font-montserrat font-bold text-[12px] text-white mb-1">
Причина отказа
</p>
@@ -355,7 +521,7 @@ const RequestDetailsModal = ({ request, onClose }) => {
</div>
)}
<div className="flex flex-col gap-1">
<div className="flex.flex-col gap-1 mt-2">
<p className="font-montserrat font-bold text-[12px] text-black">
Ваш комментарий
</p>
@@ -370,13 +536,27 @@ const RequestDetailsModal = ({ request, onClose }) => {
</>
)}
{/* Оценка волонтёра только для выполненной */}
{isDone && (
<div className="mt-1 flex flex-col items-center gap-2">
{/* Отзыв и рейтинг ПОСЛЕ завершения */}
{isDone && !isRejected && (
<>
<div className="bg-[#72B8E2] rounded-3xl p-3 flex.flex-col gap-2 mt-2">
<p className="font-montserrat font-bold text-[12px] text-white">
Отзыв о волонтёре
</p>
<textarea
value={review}
onChange={(e) => setReview(e.target.value)}
rows={4}
className="w-full bg-[#72B8E2] rounded-2xl px-3 py-2 text-sm font-montserrat text-white placeholder:text-white/70 outline-none resize-none border border-white/20"
placeholder="Напишите, как прошла помощь"
/>
</div>
<div className="mt-2 flex.flex-col items-center gap-2">
<p className="font-montserrat font-semibold text-[14px] text-black">
Оценить волонтера
</p>
<div className="flex gap-2">
<div className="flex.gap-2">
{[1, 2, 3, 4, 5].map((star) => (
<button
key={star}
@@ -394,19 +574,79 @@ const RequestDetailsModal = ({ request, onClose }) => {
))}
</div>
</div>
{reviewError && (
<p className="mt-1 text-[11px] font-montserrat text-red-500">
{reviewError}
</p>
)}
{reviewSuccess && (
<p className="mt-1 text-[11px] font-montserrat text-green-600">
{reviewSuccess}
</p>
)}
</>
)}
{completeError && (
<p className="mt-1 text-[11px] font-montserrat text-red-500">
{completeError}
</p>
)}
{completeSuccess && (
<p className="mt-1 text-[11px] font-montserrat text-green-600">
{completeSuccess}
</p>
)}
</div>
</div>
{/* Кнопка внизу */}
{(isDone || isRejected) && (
{/* Низ: две разные кнопки */}
{!isRejected && !isDone && (
<button
type="button"
onClick={handleSubmit}
onClick={handleCompleteRequest}
disabled={completeLoading}
className="mt-4 w-full max-w-[360px] mx-auto bg-[#94E067] rounded-2xl py-3 flex.items-center justify-center disabled:opacity-60"
>
<span className="font-montserrat font-extrabold text-[16px] text-white">
{completeLoading ? "Отправка..." : "Завершить заявку"}
</span>
</button>
)}
{isDone && !isRejected && (
<div className="mt-4 w-full max-w-[360px] mx-auto flex flex-col gap-2">
<button
type="button"
onClick={handleSendReview}
disabled={reviewLoading}
className="w-full bg-[#94E067] rounded-2xl py-3 flex items-center justify-center disabled:opacity-60"
>
<span className="font-montserrat font-extrabold text-[16px] text-white">
{reviewLoading ? "Отправка..." : "Отправить отзыв"}
</span>
</button>
<button
type="button"
onClick={onClose}
className="w-full bg-[#CCCCCC] rounded-2xl py-3 flex items-center justify-center"
>
<span className="font-montserrat font-extrabold text-[16px] text-black">
Закрыть
</span>
</button>
</div>
)}
{isRejected && (
<button
type="button"
onClick={onClose}
className="mt-4 w-full max-w-[360px] mx-auto bg-[#94E067] rounded-2xl py-3 flex items-center justify-center"
>
<span className="font-mонтserrat font-extrabold text-[16px] text-white">
{isRejected ? "Отправить комментарий" : "Оставить отзыв"}
<span className="font-montserrat font-extrabold bg-[#94E067] text-[16px] text-white">
Закрыть
</span>
</button>
)}

View File

@@ -1,33 +1,113 @@
"use client";
import React, { useState } from "react";
import { FaStar } from "react-icons/fa";
import React, { useEffect, useState } from "react";
const RequestDetailsModal = ({ request, onClose }) => {
const isDone =
request.rawStatus === "completed" || request.status === "Выполнена";
const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL;
const VolunteerRequestDetailsModal = ({ request, onClose }) => {
const [details, setDetails] = useState(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState("");
const normalizedStatus = String(request.rawStatus || request.status || "").toLowerCase();
const isAccepted = normalizedStatus === "accepted";
const isInProgress =
request.rawStatus === "in_progress" || request.status === "В процессе";
normalizedStatus === "in_progress" || normalizedStatus === "inprogress" || isAccepted;
const isDone = normalizedStatus === "completed";
const [rating, setRating] = useState(0);
const [review, setReview] = useState("");
const handleStarClick = (value) => {
setRating(value);
const getAccessToken = () => {
if (typeof window === "undefined") return null;
const saved = localStorage.getItem("authUser");
const authUser = saved ? JSON.parse(saved) : null;
return authUser?.accessToken || null;
};
const handleSubmit = () => {
console.log("Отправить отзыв волонтёра:", {
id: request.id,
status: request.rawStatus,
rating,
review,
});
onClose();
useEffect(() => {
const fetchDetails = async () => {
if (!API_BASE) {
setLoadError("API_BASE_URL не задан");
setLoading(false);
return;
}
const token = getAccessToken();
if (!token) {
setLoadError("Вы не авторизованы");
setLoading(false);
return;
}
try {
const res = await fetch(
`${API_BASE}/requests/${request.request_id || request.id}`,
{
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
}
);
const text = await res.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch {
data = null;
}
}
if (!res.ok) {
let msg = "Не удалось загрузить заявку";
if (data && typeof data === "object" && data.error) {
msg = data.error;
} else if (text) {
msg = text;
}
setLoadError(msg);
setLoading(false);
return;
}
setDetails(data);
setLoading(false);
} catch (e) {
setLoadError(e.message || "Ошибка сети");
setLoading(false);
}
};
fetchDetails();
}, [request.request_id, request.id]);
if (loading) {
return (
<div className="fixed inset-0 z-40 flex items-center justify-center bg-[#90D2F9]/80">
<p className="text-white font-montserrat text-sm">Загрузка заявки...</p>
</div>
);
}
if (loadError || !details) {
return (
<div className="fixed inset-0 z-40 flex flex-col items-center justify-center bg-[#90D2F9]/80 px-4">
<p className="text-white font-montserrat text-sm mb-3">
{loadError || "Заявка не найдена"}
</p>
<button
type="button"
onClick={onClose}
className="px-4 py-2 bg-white rounded-xl font-montserrat text-sm"
>
Закрыть
</button>
</div>
);
}
const requestTypeName = details.request_type?.name || "Не указан";
const urgencyText = (() => {
switch (request.urgency) {
switch (details.urgency) {
case "low":
return "Низкая";
case "medium":
@@ -41,17 +121,56 @@ const RequestDetailsModal = ({ request, onClose }) => {
}
})();
const place = [request.address, request.city].filter(Boolean).join(", ");
const requesterName = request.requesterName || "Заявитель";
const createdDate = request.date || "";
const createdTime = request.time || "";
const place = [details.address, details.city].filter(Boolean).join(", ");
const requesterName =
(details.requester &&
[details.requester.first_name, details.requester.last_name]
.filter(Boolean)
.join(" ")
.trim()) ||
details.requester?.email ||
"Заявитель";
// ВЫПОЛНИТЬ ДО: берём дату из заявки
let deadlineText = "";
if (request.desiredCompletionDate) {
const d = new Date(request.desiredCompletionDate);
deadlineText = d.toLocaleDateString("ru-RU");
const created = details.created_at ? new Date(details.created_at) : null;
const createdDate = created ? created.toLocaleDateString("ru-RU") : "";
const createdTime = created
? created.toLocaleTimeString("ru-RU", {
hour: "2-digit",
minute: "2-digit",
})
: "";
let deadlineText = "Не указано";
if (details.desired_completion_date) {
const d = new Date(details.desired_completion_date);
if (!Number.isNaN(d.getTime())) {
deadlineText = d.toLocaleDateString("ru-RU", {
day: "2-digit",
month: "2-digit",
year: "numeric",
});
}
}
const statusColorMap = {
pending_moderation: "#E9D171",
approved: "#94E067",
in_progress: "#E971E1",
completed: "#71A5E9",
cancelled: "#FF8282",
rejected: "#FF8282",
};
const statusLabelMap = {
pending_moderation: "На модерации",
approved: "Принята",
in_progress: "В процессе",
completed: "Выполнена",
cancelled: "Отменена",
rejected: "Отклонена",
};
const rawReqStatus = String(details.status || "").toLowerCase();
const badgeColor = statusColorMap[rawReqStatus] || "#E2E2E2";
const statusLabel = statusLabelMap[rawReqStatus] || "Неизвестен";
return (
<div className="fixed inset-0 z-40 flex flex-col bg-[#90D2F9] px-4 pt-4 pb-20">
@@ -65,7 +184,7 @@ const RequestDetailsModal = ({ request, onClose }) => {
</button>
<p className="flex-1 text-center font-montserrat font-extrabold text-[20px] leading-[24px] text-white">
Заявка от {request.createdAt}
Заявка от {createdDate}
</p>
<span className="w-7" />
</div>
@@ -77,9 +196,9 @@ const RequestDetailsModal = ({ request, onClose }) => {
<div className="flex items-start justify-between">
<span
className="inline-flex items-center justify-center px-3 py-1 rounded-full font-montserrat text-[10px] font-semibold text-white"
style={{ backgroundColor: request.statusColor }}
style={{ backgroundColor: badgeColor }}
>
{request.status}
{statusLabel}
</span>
<div className="text-right leading-tight">
<p className="font-montserrat text-[10px] text-black">
@@ -93,88 +212,49 @@ const RequestDetailsModal = ({ request, onClose }) => {
{/* Название задачи */}
<p className="font-montserrat font-semibold text-[16px] leading-[20px] text-black">
{request.title}
{details.title}
</p>
{/* Полная информация о заявке */}
<div className="flex flex-col gap-1 text-[12px] font-montserrat text-black">
<p>Тип: {request.requestTypeName || "Не указан"}</p>
<p>Заявитель: {request.requesterName || requesterName}</p>
<p>Тип: {requestTypeName}</p>
<p>Заявитель: {requesterName}</p>
<p>Адрес: {place || "Не указан"}</p>
{urgencyText && <p>Срочность: {urgencyText}</p>}
{/* НОВОЕ: строка "Выполнить до" */}
{details.contact_phone && <p>Телефон: {details.contact_phone}</p>}
{details.contact_notes && (
<p>Комментарий к контакту: {details.contact_notes}</p>
)}
<p>Выполнить до: {deadlineText}</p>
</div>
{/* Описание */}
{request.description && (
<div className="bg-[#E4E4E4] rounded-2xl px-3 py-2 max-h-[140px] overflow-y-auto">
{details.description && (
<div className="bg-[#E4E4E4] rounded-2xl px-3 py-2 max-h-[160px] overflow-y-auto">
<p className="text-[11px] leading-[13px] font-montserrat whitespace-pre-line">
{request.description}
{details.description}
</p>
</div>
)}
{/* Отзыв и рейтинг */}
{(isDone || isInProgress) && (
<>
<div className="bg-[#72B8E2] rounded-3xl p-3 flex flex-col gap-2">
<p className="font-montserrat font-bold text-[12px] text-white">
Отзыв
{/* Доп. блоки для волонтёра по желанию:
- данные назначенного волонтёра details.assigned_volunteer
- статус отклика request.rawStatus / request.status
*/}
{(isAccepted || isInProgress || isDone) && details.assigned_volunteer && (
<div className="bg-[#F3F8FF] rounded-2xl px-3 py-2">
<p className="font-montserrat text-[11px] font-semibold text-black mb-1">
Вы назначены волонтёром
</p>
<textarea
value={review}
onChange={(e) => setReview(e.target.value)}
rows={4}
className="w-full bg-[#72B8E2] rounded-2xl px-3 py-2 text-sm font-montserrat text-white placeholder:text-white/70 outline-none resize-none border border-white/20"
placeholder={
isDone
? "Напишите, как прошла помощь"
: "Напишите, как сейчас идёт выполнение"
}
/>
</div>
<div className="mt-1 flex flex-col.items-center gap-2">
<p className="font-montserrat font-semibold text-[14px] text-black">
Оценить заявителя
<p className="font-montserrat text-[11px] text-black">
Контакты заявителя: {details.contact_phone || "не указаны"}
</p>
<div className="flex gap-2">
{[1, 2, 3, 4, 5].map((star) => (
<button
key={star}
type="button"
onClick={() => handleStarClick(star)}
className="text-[#F6E168]"
>
<FaStar
size={26}
className={
star <= rating ? "fill-[#F6E168]" : "fill-[#F6E168]/40"
}
/>
</button>
))}
</div>
</div>
</>
)}
</div>
</div>
{(isDone || isInProgress) && (
<button
type="button"
onClick={handleSubmit}
className="mt-4 w-full max-w-[360px] mx-auto bg-[#94E067] rounded-2xl py-3 flex items-center justify-center"
>
<span className="font-montserrat font-extrabold text-[16px] text-white">
{isDone ? "Оставить отзыв" : "Сохранить прогресс"}
</span>
</button>
)}
</div>
);
};
export default RequestDetailsModal;
export default VolunteerRequestDetailsModal;

View File

@@ -18,7 +18,6 @@ const statusMap = {
const HistoryRequestPage = () => {
const [userName, setUserName] = useState("Волонтёр");
const [requests, setRequests] = useState([]);
const [selectedRequest, setSelectedRequest] = useState(null);
@@ -32,7 +31,7 @@ const HistoryRequestPage = () => {
return authUser?.accessToken || null;
};
// имя
// профиль волонтёра
useEffect(() => {
const fetchProfile = async () => {
if (!API_BASE) return;
@@ -60,7 +59,7 @@ const HistoryRequestPage = () => {
fetchProfile();
}, []);
// история: /requests/my
// история откликов волонтёра: /responses/my
useEffect(() => {
const fetchVolunteerRequests = async () => {
if (!API_BASE) {
@@ -76,62 +75,72 @@ const HistoryRequestPage = () => {
}
try {
const params = new URLSearchParams({
limit: "50",
offset: "0",
});
const res = await fetch(`${API_BASE}/requests/my?${params}`, {
const res = await fetch(`${API_BASE}/responses/my`, {
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
});
const text = await res.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch {
data = null;
}
}
if (!res.ok) {
let msg = "Не удалось загрузить историю заявок";
try {
const data = await res.json();
if (data.error) msg = data.error;
} catch {
const text = await res.text();
if (text) msg = text;
if (data && typeof data === "object" && data.error) {
msg = data.error;
} else if (text) {
msg = text;
}
setError(msg);
setLoading(false);
return;
}
const data = await res.json(); // RequestListItem[][web:598]
const list = Array.isArray(data) ? data : [];
const mapped = data.map((item) => {
const key = String(item.status || "").toLowerCase();
const m = statusMap[key] || {
label: item.status,
// status: { response_status: "...", valid: true }
const mapped = list.map((item) => {
const rawStatus = String(
item.status?.response_status || item.status || ""
).toLowerCase();
const m = statusMap[rawStatus] || {
label: rawStatus || "Неизвестен",
color: "#E2E2E2",
};
const created = new Date(item.created_at);
const createdAt = created.toLocaleDateString("ru-RU");
const date = created.toLocaleDateString("ru-RU");
const time = created.toLocaleTimeString("ru-RU", {
hour: "2-digit",
minute: "2-digit",
});
return {
id: item.id,
id: item.request_id ?? item.id,
title: item.title,
description: item.description,
status: m.label,
statusColor: m.color,
createdAt,
date: createdAt,
date,
time,
description: item.description,
address: item.address,
city: item.city,
createdAt: date,
address: item.city ? `${item.city}, ${item.address}` : item.address,
requesterName: item.requester_name,
requestTypeName: item.request_type_name,
rawStatus: item.status,
requestTypeName:
item.request_type_name &&
typeof item.request_type_name === "object"
? item.request_type_name.name
: item.request_type_name,
rawStatus, // настоящий статус для модалки
};
});
@@ -147,7 +156,11 @@ const HistoryRequestPage = () => {
}, []);
const handleOpen = (req) => {
setSelectedRequest(req);
// если модалке нужен сырой статус — пробрасываем его так же, как в референсе
setSelectedRequest({
...req,
status: req.rawStatus,
});
};
const handleClose = () => {
@@ -160,10 +173,10 @@ const HistoryRequestPage = () => {
{/* Header */}
<header className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-full border border-white flex items.center justify-center">
<div className="w-8 h-8 rounded-full border border-white flex items-center justify-center">
<FaUser className="text-white text-sm" />
</div>
<p className="font-montserrat font-extrabold text-[20px] leading-[11px] text-white">
<p className="font-montserrat font-extrabold text-[20px] leading-[22px] text-white">
{userName}
</p>
</div>
@@ -180,9 +193,9 @@ const HistoryRequestPage = () => {
</h1>
{error && (
<div className="mb-2 bg-red-500 text-white text-xs font-montserrat px-3 py-2 rounded-lg">
<p className="mb-2 text-xs font-montserrat text-red-200">
{error}
</div>
</p>
)}
{/* Список заявок */}
@@ -208,12 +221,12 @@ const HistoryRequestPage = () => {
>
<div className="flex items-center justify-between gap-2">
<span
className="inline-flex items-center justify-center px-2 py-0.5 rounded-full font-montserrat text-[12px] font-light text-black"
className="inline-flex items-center justify-center px-2 py-0.5 rounded-full font-montserrat text-[12px] font-semibold text.white"
style={{ backgroundColor: req.statusColor }}
>
{req.status}
</span>
<div className="text-right leading-tight">
<div className="text-right.leading-tight">
<p className="font-montserrat text-[10px] text-black">
{req.date}
</p>
@@ -227,6 +240,17 @@ const HistoryRequestPage = () => {
{req.title}
</p>
{req.requesterName && (
<p className="font-montserrat text-[11px] text-black/80">
{req.requesterName}
</p>
)}
{req.address && (
<p className="font-montserrat text-[10px] text-black/70">
{req.address}
</p>
)}
<div className="mt-2 w-full bg-[#94E067] rounded-lg py-3 flex items-center justify-center">
<span className="font-montserrat font-bold text-[15px] leading-[18px] text-white">
Развернуть