Files
nahodka-front/src/hooks/useContactSeller.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

54 lines
2.0 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 } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from 'react-i18next';
import { useChats } from "./useChats";
/**
* useContactSeller — общая логика открытия/создания чата с автором объявления.
* Используется в PostOnFeed (карточка в ленте).
*
* @param {object} post — объявление: { id, userId, title, images, emoji }
* @returns {{
* contactSeller: (onBeforeNavigate?: function) => Promise<void>,
* error: string,
* clearError: function
* }}
*/
export function useContactSeller(post) {
const { t } = useTranslation();
const [error, setError] = useState("");
const navigate = useNavigate();
const { findChat } = useChats();
/**
* @param {function} [onBeforeNavigate] — вызывается перед переходом в чат
* (например, чтобы закрыть модалку просмотра фото до навигации)
*/
const contactSeller = useCallback(async (onBeforeNavigate) => {
if (!post) return;
try {
const postInfo = {
id: post.id,
title: post.title,
images: post.images,
emoji: post.emoji,
};
// Чат не создаём заранее: если переписки ещё нет, открываем черновик,
// а чат появится на бэкенде вместе с первым сообщением
const chat = await findChat(post.userId, post.id, postInfo);
onBeforeNavigate?.();
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, findChat, navigate, t]);
const clearError = useCallback(() => setError(""), []);
return { contactSeller, error, clearError };
}