From 33bd002f9885ac8fa3d4443b21d5d89b517dd5f5 Mon Sep 17 00:00:00 2001 From: SlimusMinus Date: Wed, 28 Oct 2026 21:17:58 +0300 Subject: [PATCH] Show which listing each chat is about The chat list and header show the listing's type, city and closed/deleted status; the header info button opens the full listing in PostDetailModal with a "show on map" action. Deleted or unpublished listings are marked. Co-Authored-By: Claude Opus 5.5 --- src/components/PostDetailModal.jsx | 49 ++++++++-- src/components/chat/ChatHeader.jsx | 43 +++++++-- src/components/chat/ChatListItem.jsx | 2 + src/components/chat/ChatPostInfo.test.jsx | 38 ++++++++ src/components/chat/ChatPostMeta.jsx | 34 +++++++ src/locales/en.json | 10 ++- src/locales/ru.json | 10 ++- src/pages/ChatPage.jsx | 36 ++++++++ src/pages/PostOnFeed.jsx | 4 +- src/stores/chatPostStore.js | 6 ++ src/styles/chat.css | 105 +++++++++++++++++++++- src/styles/desktop.css | 4 + 12 files changed, 319 insertions(+), 22 deletions(-) create mode 100644 src/components/chat/ChatPostInfo.test.jsx create mode 100644 src/components/chat/ChatPostMeta.jsx diff --git a/src/components/PostDetailModal.jsx b/src/components/PostDetailModal.jsx index fb35626..9e939f6 100644 --- a/src/components/PostDetailModal.jsx +++ b/src/components/PostDetailModal.jsx @@ -6,7 +6,25 @@ import { useAuthContext } from "../context/AuthContext"; import PostOnFeed from "../pages/PostOnFeed"; import CloseIcon from "./icons/CloseIcon"; -export default function PostDetailModal({ postId, onClose, onLocationClick, onAuthRequired }) { +/** + * Модалка с полным объявлением, догружаемым по id. + * + * compact — компактная карточка (без адреса и даты), как при открытии с карты; + * hideContact — без кнопки «Написать» (модалка открыта из самого чата); + * fallbackTitle — что показать над сообщением, если объявление удалено или скрыто; + * footer(post) — дополнительные действия под карточкой. + * + * @param {{ + * postId: any, onClose: () => void, + * onLocationClick?: (ad: any) => void, onAuthRequired?: () => void, + * compact?: boolean, hideContact?: boolean, + * fallbackTitle?: string, footer?: (post: any) => any, + * }} props + */ +export default function PostDetailModal({ + postId, onClose, onLocationClick, onAuthRequired, + compact = true, hideContact = false, fallbackTitle, footer, +}) { const { t } = useTranslation(); const { user } = useAuthContext(); const [post, setPost] = useState(null); @@ -22,6 +40,8 @@ export default function PostDetailModal({ postId, onClose, onLocationClick, onAu setError(null); try { const res = await apiFetch(`${API_URL}/api/v1/posts/${encodeURIComponent(postId)}`); + // 404 — объявление удалено или снято с публикации (модерация, отклонено) + if (res.status === 404) throw new Error("notFound"); if (!res.ok) throw new Error("Failed to load post"); const data = await res.json(); if (!cancelled) { @@ -52,20 +72,31 @@ export default function PostDetailModal({ postId, onClose, onLocationClick, onAu )} - {error && ( + {error === "notFound" && ( +
+ {fallbackTitle &&
{fallbackTitle}
} +
{t("chat.postUnavailable")}
+
+ )} + + {error && error !== "notFound" && (
{t("common.error")}
)} {post && ( - + <> + + {footer?.(post)} + )} diff --git a/src/components/chat/ChatHeader.jsx b/src/components/chat/ChatHeader.jsx index 6d17cbf..dc4d39a 100644 --- a/src/components/chat/ChatHeader.jsx +++ b/src/components/chat/ChatHeader.jsx @@ -1,14 +1,45 @@ -export default function ChatHeader({ title, onBack, avatar }) { +/** + * Шапка чата. С onInfo аватар и заголовок объявления кликабельны, а справа + * есть кнопка «ⓘ» — обе открывают карточку объявления, к которому относится чат. + */ +export default function ChatHeader({ title, onBack, avatar, subtitle, onInfo, infoLabel }) { + const main = ( + <> + {avatar !== undefined && ( +
{avatar}
+ )} +
+
{title}
+ {subtitle} +
+ + ); + return (
- {avatar !== undefined && ( -
{avatar}
+ {onInfo ? ( + + ) : ( +
{main}
+ )} + {onInfo ? ( + + ) : ( +
)} -
{title}
-
); -} \ No newline at end of file +} diff --git a/src/components/chat/ChatListItem.jsx b/src/components/chat/ChatListItem.jsx index 7ba62a6..f5b88ea 100644 --- a/src/components/chat/ChatListItem.jsx +++ b/src/components/chat/ChatListItem.jsx @@ -1,5 +1,6 @@ import { getChatDisplayInfo } from "../../utils/chatDisplay"; import TrashIcon from "../icons/TrashIcon"; +import ChatPostMeta from "./ChatPostMeta"; export default function ChatListItem({ chat, post, unreadMap, t, onOpen, onDelete }) { const { title, imgSrc, emoji, unreadCount, preview } = getChatDisplayInfo(chat, post, unreadMap, t); @@ -18,6 +19,7 @@ export default function ChatListItem({ chat, post, unreadMap, t, onOpen, onDelet
{title}
+
{preview}
diff --git a/src/components/chat/ChatPostInfo.test.jsx b/src/components/chat/ChatPostInfo.test.jsx new file mode 100644 index 0000000..0db2034 --- /dev/null +++ b/src/components/chat/ChatPostInfo.test.jsx @@ -0,0 +1,38 @@ +/** + * По какому объявлению чат: подпись в списке/шапке (тип, город, статус) + * и кнопка в шапке, открывающая карточку. Удалённое объявление помечается. + */ +import { render, screen, fireEvent } from "@testing-library/react"; +import i18n from "../../i18n"; +import ChatPostMeta from "./ChatPostMeta"; +import ChatHeader from "./ChatHeader"; +import { cachePostsFromChats, getPostForChat } from "../../stores/chatPostStore"; + +const t = i18n.t.bind(i18n); + +beforeAll(() => i18n.changeLanguage("ru")); + +test("подпись показывает тип, город и закрытый статус", () => { + render(); + expect(screen.getByText("Находка")).toBeTruthy(); + expect(screen.getByText("Москва")).toBeTruthy(); + expect(screen.getByText("Закрыто")).toBeTruthy(); +}); + +test("удалённое объявление сохраняет прежний заголовок и помечается", () => { + cachePostsFromChats([{ id: 501, postId: 9, post: { id: 9, title: "Шляпа", images: [] } }]); + cachePostsFromChats([{ id: 501, postId: 9, post: null }]); + + const post = getPostForChat(501); + expect(post).toMatchObject({ id: 9, title: "Шляпа", removed: true }); + + render(); + expect(screen.getByText("Объявление удалено")).toBeTruthy(); +}); + +test("кнопка в шапке открывает объявление", () => { + const onInfo = jest.fn(); + render( {}} onInfo={onInfo} infoLabel="Объявление этого чата" />); + fireEvent.click(screen.getByLabelText("Объявление этого чата")); + expect(onInfo).toHaveBeenCalledTimes(1); +}); diff --git a/src/components/chat/ChatPostMeta.jsx b/src/components/chat/ChatPostMeta.jsx new file mode 100644 index 0000000..79d77a5 --- /dev/null +++ b/src/components/chat/ChatPostMeta.jsx @@ -0,0 +1,34 @@ +import { POST_STATUS_CLOSED } from "../../config/postConstants"; + +/** + * Короткая подпись объявления, к которому относится чат: тип, город, статус. + * Помогает различать чаты по похожим объявлениям (три «шляпы» в списке). + * Тип и статус бэкенд отдаёт в верхнем регистре (FOUND, CLOSED). + */ +export default function ChatPostMeta({ post, t, className = "" }) { + if (!post) return null; + + if (post.removed) { + return ( +
+ {t("chat.postRemoved")} +
+ ); + } + + const type = String(post.type || "").toLowerCase(); + const isClosed = String(post.status || "").toUpperCase() === POST_STATUS_CLOSED; + if (!type && !post.city && !isClosed) return null; + + return ( +
+ {type && ( + + {type === "found" ? t("postCard.found") : t("postCard.loss")} + + )} + {post.city && {post.city}} + {isClosed && {t("chat.postClosed")}} +
+ ); +} diff --git a/src/locales/en.json b/src/locales/en.json index df3bb9a..901dade 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -215,7 +215,12 @@ "noChats": "You have no chats yet", "deleteChat": "Delete chat", "confirmDeleteChat": "Are you sure you want to delete this chat?", - "user": "User" + "user": "User", + "postInfo": "Listing for this chat", + "postRemoved": "Listing deleted", + "postClosed": "Closed", + "postUnavailable": "The listing was deleted or unpublished. The conversation is kept.", + "showOnMap": "Show on map" }, "reviews": { "anonymous": "Anonymous", @@ -592,7 +597,8 @@ "processingFailed": "Failed to process the image" }, "common": { - "close": "Close" + "close": "Close", + "error": "Failed to load" }, "fullscreenAd": { "label": "Ad", diff --git a/src/locales/ru.json b/src/locales/ru.json index 3964036..c606c78 100644 --- a/src/locales/ru.json +++ b/src/locales/ru.json @@ -215,7 +215,12 @@ "noChats": "У вас пока нет чатов", "deleteChat": "Удалить чат", "confirmDeleteChat": "Вы уверены, что хотите удалить этот чат?", - "user": "Пользователь" + "user": "Пользователь", + "postInfo": "Объявление этого чата", + "postRemoved": "Объявление удалено", + "postClosed": "Закрыто", + "postUnavailable": "Объявление удалено или снято с публикации. Переписка сохранилась.", + "showOnMap": "Показать на карте" }, "reviews": { "anonymous": "Аноним", @@ -592,7 +597,8 @@ "processingFailed": "Не удалось обработать изображение" }, "common": { - "close": "Закрыть" + "close": "Закрыть", + "error": "Ошибка загрузки" }, "fullscreenAd": { "label": "Реклама", diff --git a/src/pages/ChatPage.jsx b/src/pages/ChatPage.jsx index efa8a4c..c38947f 100644 --- a/src/pages/ChatPage.jsx +++ b/src/pages/ChatPage.jsx @@ -13,6 +13,9 @@ import { getImageUrl } from "../config/authConstants"; import ChatHeader from "../components/chat/ChatHeader"; import MessageBubble from "../components/chat/MessageBubble"; import ChatInputBar from "../components/chat/ChatInputBar"; +import ChatPostMeta from "../components/chat/ChatPostMeta"; +import PostDetailModal from "../components/PostDetailModal"; +import { POST_STATUS_CLOSED } from "../config/postConstants"; import Toast from "../components/Toast"; /** @@ -37,6 +40,7 @@ export default function ChatPage({ embedded = false, onActivity } = {}) { const [input, setInput] = useState(""); const [loadError, setLoadError] = useState(""); const [sendError, setSendError] = useState(""); + const [showPost, setShowPost] = useState(false); const messagesEndRef = useRef(null); const pageRef = useRef(null); @@ -149,6 +153,17 @@ export default function ChatPage({ embedded = false, onActivity } = {}) { const post = draft ? draft.post : getPostForChat(chatId); const postImg = getImageUrl(post?.images?.[0]); + const postId = post?.id ?? draft?.postId; + + // «Перейти к объявлению» — на карту с фокусом на нём (тот же URL, что у + // кнопки адреса в ленте). Без координат на карте фокусироваться не на чем. + const hasCoords = (ad) => ad?.latitude != null && ad?.longitude != null + && Number.isFinite(Number(ad.latitude)) && Number.isFinite(Number(ad.longitude)); + const openOnMap = (ad) => { + if (!hasCoords(ad)) return; + const params = new URLSearchParams({ view: "map", post: String(ad.id), lat: String(ad.latitude), lng: String(ad.longitude) }); + navigate(`/feed?${params.toString()}`); + }; const content = ( <> @@ -156,6 +171,9 @@ export default function ChatPage({ embedded = false, onActivity } = {}) { navigate("/chats")} + subtitle={} + onInfo={postId != null ? () => setShowPost(true) : undefined} + infoLabel={t('chat.postInfo')} avatar={postImg ? ( ) : ( @@ -183,6 +201,24 @@ export default function ChatPage({ embedded = false, onActivity } = {}) { />
+ {showPost && ( + setShowPost(false)} + onLocationClick={openOnMap} + compact={false} + hideContact + fallbackTitle={post?.title} + footer={(ad) => ad.status !== POST_STATUS_CLOSED && hasCoords(ad) && ( +
+ +
+ )} + /> + )} + {sendError && ( {isOwnAd ? ( {t('postCard.ownAd')} - ) : ( + ) : !hideContact && (