Files
nahodka-front/src/hooks/useChats.js
SlimusMinus 08f3a7e2bb open a draft chat and create it on the first message
"Написать" now looks up an existing chat for the ad (GET, never creates).
If there is none it opens /chats/new as a draft with the ad in the header;
the first send calls POST /chats/with/{userId}/messages, which creates the
chat with that message, and the page switches to /chats/{id}. Reloading
/chats/new without draft data goes back to the chat list.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-13 01:45:21 +03:00

127 lines
5.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

import { useState, useCallback, useRef } from "react";
import { useTranslation } from 'react-i18next';
import { API_URL } from "../config/authConstants";
import { apiFetch } from "../api/apiClient";
import { cachePostsFromChats, setPostForChat } from "../stores/chatPostStore";
import { useUnread } from "../context/UnreadContext";
export function useChats() {
const { t } = useTranslation();
const [chats, setChats] = useState([]);
// Стартуем в состоянии загрузки: иначе самый первый рендер успевает показать
// "Нет чатов" до того, как эффект выставит loading — список "моргает".
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const { updateFromChats, clearChatUnread } = useUnread();
// fetchChats дёргается и при монтировании, и на каждое изменение totalUnread —
// без guard'а медленный предыдущий ответ воскрешал бы прочитанные счётчики.
const requestIdRef = useRef(0);
// silent=true — фоновое обновление списка (новое сообщение по WS, удаление
// чата и т.п.): не трогаем loading, иначе текущий список на миг подменяется
// экраном загрузки и страница "моргает".
const fetchChats = useCallback(async ({ silent = false } = {}) => {
const requestId = ++requestIdRef.current;
if (!silent) setLoading(true);
setError("");
try {
const res = await apiFetch(`${API_URL}/api/v1/chats`);
if (!res.ok) throw new Error(t('chats.fetchError'));
const data = await res.json();
if (requestId !== requestIdRef.current) return; // устаревший ответ
const list = Array.isArray(data) ? data : (data.items ?? data.content ?? []);
cachePostsFromChats(list);
setChats(list);
updateFromChats(list);
} catch (e) {
if (requestId !== requestIdRef.current) return;
setError(e.message || t('chats.fetchError'));
} finally {
if (requestId === requestIdRef.current && !silent) setLoading(false);
}
}, [updateFromChats, t]);
/**
* Существующий чат с пользователем по объявлению или null, если переписки ещё нет.
* Ничего не создаёт: чат появляется только вместе с первым сообщением (startChat).
*/
const findChat = useCallback(async (otherUserId, postId, postInfo) => {
const res = await apiFetch(chatWithUrl(otherUserId, postId));
if (res.status === 404) return null;
if (!res.ok) {
await logChatError("findChat", res);
throw new Error(t('chats.createError'));
}
const chat = await res.json();
cacheChatPost(chat, postInfo);
return chat;
}, [t]);
/** Отправляет первое сообщение: бэкенд создаёт (или находит) чат вместе с ним. */
const startChat = useCallback(async (otherUserId, postId, content, postInfo) => {
const res = await apiFetch(chatWithUrl(otherUserId, postId, "/messages"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content }),
});
if (!res.ok) {
await logChatError("startChat", res);
throw new Error(t('chats.sendError'));
}
const chat = await res.json();
cacheChatPost(chat, postInfo);
return chat;
}, [t]);
const fetchMessages = useCallback(async (chatId) => {
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`);
// Без этой проверки 5xx с JSON-телом ошибки превращался в пустой список,
// и только что отправленное сообщение выглядело как потерянное.
if (!res.ok) throw new Error(`Error ${res.status}`);
const data = await res.json();
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
}, []);
const markAsRead = useCallback(async (chatId) => {
clearChatUnread(chatId);
try {
await apiFetch(`${API_URL}/api/v1/chats/${chatId}/read`, {
method: "POST",
});
} catch (e) {
console.error("Failed to mark as read:", e);
}
}, [clearChatUnread]);
return { chats, loading, error, fetchChats, findChat, startChat, fetchMessages, markAsRead };
}
function chatWithUrl(otherUserId, postId, suffix = "") {
const url = new URL(`${API_URL}/api/v1/chats/with/${otherUserId}${suffix}`);
if (postId) url.searchParams.set("postId", postId);
return url;
}
// Причину отказа (чат с собой, чужое объявление и т.п.) пишем в консоль,
// иначе 400 выглядит как необъяснимый сбой
async function logChatError(action, res) {
const body = await res.json().catch(() => null);
console.warn(`${action} failed:`, res.status, body?.message);
}
/**
* Объявление чата берём из ответа бэкенда: если чат оказался по другому
* объявлению, postInfo с карточки привязал бы к нему чужую картинку.
* postInfo — только дополнение (emoji) для того же объявления.
*/
function cacheChatPost(chat, postInfo) {
if (!chat?.id) return;
const sameAd = postInfo && (chat.post?.id ?? chat.postId) != null
&& String(chat.post?.id ?? chat.postId) === String(postInfo.id);
if (chat.post) {
setPostForChat(chat.id, { ...(sameAd ? postInfo : {}), ...chat.post });
} else if (sameAd) {
setPostForChat(chat.id, postInfo);
}
}