"use client"; import React, { useState, useEffect } from "react"; import { FaBell, FaUser } from "react-icons/fa"; import TabBar from "../components/TabBar"; import RequestDetailsModal from "../components/RequestDetailsModal"; const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL; // маппинг статусов API -> текст/цвет для UI const statusMap = { pending_moderation: { label: "На модерации", color: "#E9D171" }, approved: { label: "Принята", color: "#94E067" }, in_progress: { label: "В процессе", color: "#E971E1" }, completed: { label: "Выполнена", color: "#71A5E9" }, cancelled: { label: "Отменена", color: "#FF8282" }, rejected: { label: "Отклонена", color: "#FF8282" }, }; const HistoryRequestPage = () => { const [requests, setRequests] = useState([]); const [selectedRequest, setSelectedRequest] = useState(null); const [error, setError] = useState(""); const [loading, setLoading] = useState(true); const [userName, setUserName] = useState("Пользователь"); const [profileError, setProfileError] = useState(""); // профиль: /users/me useEffect(() => { const fetchProfile = async () => { if (!API_BASE) return; const saved = typeof window !== "undefined" ? localStorage.getItem("authUser") : null; const authUser = saved ? JSON.parse(saved) : null; const accessToken = authUser?.accessToken; if (!accessToken) return; try { const res = await fetch(`${API_BASE}/users/me`, { headers: { Accept: "application/json", Authorization: `Bearer ${accessToken}`, }, }); if (!res.ok) { setProfileError("Не удалось загрузить профиль"); return; } const data = await res.json(); const fullName = [data.first_name, data.last_name] .filter(Boolean) .join(" ") .trim() || data.email; setUserName(fullName); } catch { setProfileError("Ошибка загрузки профиля"); } }; fetchProfile(); }, []); // заявки: /requests/my useEffect(() => { const fetchRequests = async () => { if (!API_BASE) { setError("API_BASE_URL не задан"); setLoading(false); return; } const saved = typeof window !== "undefined" ? localStorage.getItem("authUser") : null; const authUser = saved ? JSON.parse(saved) : null; const accessToken = authUser?.accessToken; if (!accessToken) { setError("Вы не авторизованы"); setLoading(false); return; } try { const res = await fetch(`${API_BASE}/requests/my`, { 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; } setError(msg); setLoading(false); return; } const data = await res.json(); console.log("requests/my data:", data); const mapped = data.map((item) => { const rawStatus = typeof item.status === "string" ? item.status : item.status?.request_status; const m = statusMap[rawStatus] || { label: rawStatus || "unknown", color: "#E2E2E2", }; const created = new Date(item.created_at); const createdAt = created.toLocaleDateString("ru-RU"); const time = created.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", }); return { id: item.id, title: item.title, status: m.label, statusColor: m.color, createdAt, date: createdAt, time, description: item.description, // если позже появятся причина/оценка — можно добавить сюда }; }); setRequests(mapped); setLoading(false); } catch (e) { setError(e.message || "Ошибка сети"); setLoading(false); } }; fetchRequests(); }, []); const handleOpen = (req) => setSelectedRequest(req); const handleClose = () => setSelectedRequest(null); return (
{/* Header */}

{userName}

{profileError && (

{profileError}

)}

История заявок

{error && (
{error}
)} {/* Список заявок */}
{loading && (

Загрузка...

)} {!loading && requests.length === 0 && !error && (

У вас пока нет заявок

)} {requests.map((req) => ( ))}
{/* Попап деталей */} {selectedRequest && ( )}
); }; export default HistoryRequestPage;