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>
This commit is contained in:
SlimusMinus
2026-10-13 01:45:21 +03:00
parent e26283f907
commit 08f3a7e2bb
4 changed files with 94 additions and 31 deletions

View File

@@ -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);
}
}