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

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

File diff suppressed because it is too large Load Diff

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,18 +121,57 @@ 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">
Отзыв
</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>
<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>
</>
{/* Доп. блоки для волонтёра по желанию:
- данные назначенного волонтёра 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>
<p className="font-montserrat text-[11px] text-black">
Контакты заявителя: {details.contact_phone || "не указаны"}
</p>
</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">
Развернуть