diff --git a/src/App.js b/src/App.js index ba99fc1..79162a0 100644 --- a/src/App.js +++ b/src/App.js @@ -60,6 +60,7 @@ function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/hooks/useChats.js b/src/hooks/useChats.js index 236c6f5..cbea66e 100644 --- a/src/hooks/useChats.js +++ b/src/hooks/useChats.js @@ -42,31 +42,35 @@ export function useChats() { } }, [updateFromChats, t]); - const createOrGetChat = useCallback(async (otherUserId, postId, postInfo) => { - const url = new URL(`${API_URL}/api/v1/chats/with/${otherUserId}`); - if (postId) url.searchParams.set("postId", postId); - - const res = await apiFetch(url, { method: "POST" }); + /** + * Существующий чат с пользователем по объявлению или 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) { - // Причину отказа (чат с собой, чужое объявление и т.п.) пишем в консоль, - // иначе 400 выглядит как необъяснимый сбой - const body = await res.json().catch(() => null); - console.warn("createOrGetChat failed:", res.status, body?.message); + await logChatError("findChat", res); throw new Error(t('chats.createError')); } const chat = await res.json(); - // Объявление чата берём из ответа бэкенда: если он вернул существующий чат по - // другому объявлению, postInfo с карточки привязал бы к нему чужую картинку. - // postInfo — только дополнение (emoji) для того же объявления. - if (chat.id) { - 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); - } + 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]); @@ -90,5 +94,34 @@ export function useChats() { } }, [clearChatUnread]); - return { chats, loading, error, fetchChats, createOrGetChat, fetchMessages, markAsRead }; + 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); + } } \ No newline at end of file diff --git a/src/hooks/useContactSeller.js b/src/hooks/useContactSeller.js index 8a2183e..3ff879f 100644 --- a/src/hooks/useContactSeller.js +++ b/src/hooks/useContactSeller.js @@ -18,7 +18,7 @@ export function useContactSeller(post) { const { t } = useTranslation(); const [error, setError] = useState(""); const navigate = useNavigate(); - const { createOrGetChat } = useChats(); + const { findChat } = useChats(); /** * @param {function} [onBeforeNavigate] — вызывается перед переходом в чат @@ -27,19 +27,26 @@ export function useContactSeller(post) { const contactSeller = useCallback(async (onBeforeNavigate) => { if (!post) return; try { - const chat = await createOrGetChat(post.userId, post.id, { + const postInfo = { id: post.id, title: post.title, images: post.images, emoji: post.emoji, - }); + }; + // Чат не создаём заранее: если переписки ещё нет, открываем черновик, + // а чат появится на бэкенде вместе с первым сообщением + const chat = await findChat(post.userId, post.id, postInfo); onBeforeNavigate?.(); - navigate(`/chats/${chat.id}`); + if (chat) { + navigate(`/chats/${chat.id}`); + } else { + navigate("/chats/new", { state: { otherUserId: post.userId, postId: post.id, post: postInfo } }); + } } catch (err) { console.error(err); setError(t('postCard.contactError')); } - }, [post, createOrGetChat, navigate, t]); + }, [post, findChat, navigate, t]); const clearError = useCallback(() => setError(""), []); diff --git a/src/pages/ChatPage.jsx b/src/pages/ChatPage.jsx index 945f668..5fd6dd2 100644 --- a/src/pages/ChatPage.jsx +++ b/src/pages/ChatPage.jsx @@ -1,5 +1,5 @@ import { useState, useEffect, useCallback, useRef } from "react"; -import { useParams, useNavigate } from "react-router-dom"; +import { useParams, useNavigate, useLocation } from "react-router-dom"; import { useTranslation } from 'react-i18next'; import { useChats } from "../hooks/useChats"; import { useChatSocket } from "../hooks/useChatSocket"; @@ -18,7 +18,11 @@ export default function ChatPage() { const { t } = useTranslation(); const { chatId } = useParams(); const navigate = useNavigate(); - const { fetchMessages, markAsRead } = useChats(); + const location = useLocation(); + // Черновик (/chats/new): переписки ещё нет, чат создастся с первым сообщением + const draft = chatId ? null : location.state; + const [startingChat, setStartingChat] = useState(false); + const { fetchMessages, markAsRead, startChat } = useChats(); const { clearChatUnread } = useUnread(); const { user } = useAuthContext(); const [messages, setMessages] = useState([]); @@ -43,6 +47,11 @@ export default function ChatPage() { const { sendMessage, connected } = useChatSocket(chatId, handleIncoming); + // /chats/new без данных черновика (например, после перезагрузки) — открывать нечего + useEffect(() => { + if (!chatId && !draft) navigate("/chats", { replace: true }); + }, [chatId, draft, navigate]); + useEffect(() => { if (!chatId) return; @@ -80,15 +89,28 @@ export default function ChatPage() { const trimmed = input.trim(); if (!trimmed) return; + if (draft) { + if (startingChat) return; + setStartingChat(true); + startChat(draft.otherUserId, draft.postId, trimmed, draft.post) + .then((chat) => { + setInput(""); + navigate(`/chats/${chat.id}`, { replace: true }); + }) + .catch(() => setSendError(t('chats.sendError'))) + .finally(() => setStartingChat(false)); + return; + } + const sent = sendMessage(trimmed); if (!sent) { setSendError(t('chats.sendError')); return; } setInput(""); - }, [input, sendMessage, t]); + }, [input, sendMessage, t, draft, startingChat, startChat, navigate]); - const post = getPostForChat(chatId); + const post = draft ? draft.post : getPostForChat(chatId); const postImg = getImageUrl(post?.images?.[0]); return ( @@ -119,7 +141,7 @@ export default function ChatPage() { input={input} onInputChange={setInput} onSend={handleSend} - connected={connected} + connected={draft ? !startingChat : connected} placeholder={t('chat.messagePlaceholder')} />