Add verification questions, claim flow and scam warnings

- post form: up to 3 verification questions (loss and found) and a
  "how not to get scammed" note; sent as verificationQuestions JSON
- feed card: "I found it" / "It's mine" instead of "Write" for posts with
  questions; phone shows "after check" until the author approves
- chat draft shows ClaimForm; VerificationPanel lets the author approve or
  reject answers and locks the claimant's input until approval, then offers
  the author's phone
- messages: claim answers card, verification system line, fraudSignal
  warnings for the recipient; ChatSafetyNotice with new-account mark
- tests, README

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-11-11 01:04:55 +03:00
parent 133becd255
commit 3dd174afa5
20 changed files with 811 additions and 23 deletions

View File

@@ -15,6 +15,9 @@ import MessageBubble from "../components/chat/MessageBubble";
import ChatInputBar from "../components/chat/ChatInputBar";
import ChatPhotoViewer from "../components/chat/ChatPhotoViewer";
import ChatPostMeta from "../components/chat/ChatPostMeta";
import ChatSafetyNotice from "../components/chat/ChatSafetyNotice";
import ClaimForm from "../components/chat/ClaimForm";
import VerificationPanel from "../components/chat/VerificationPanel";
import PostDetailModal from "../components/PostDetailModal";
import { POST_STATUS_CLOSED } from "../config/postConstants";
import { ACCEPT as IMAGE_ACCEPT, useImageUpload } from "../hooks/useImageUpload";
@@ -39,7 +42,8 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
// Черновик (/chats/new): переписки ещё нет, чат создастся с первым сообщением
const draft = chatId ? null : location.state;
const [startingChat, setStartingChat] = useState(false);
const { fetchMessages, markAsRead, startChat, sendPhotoMessage, sendVideoMessage, refreshAttachmentUrl } = useChats();
const { fetchMessages, markAsRead, startChat, sendPhotoMessage, sendVideoMessage, refreshAttachmentUrl,
fetchChat, claimPost, decideVerification } = useChats();
const { clearChatUnread } = useUnread();
const { user, isAuthenticated } = useAuthContext();
const [messages, setMessages] = useState([]);
@@ -56,6 +60,11 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
const { selectVideo } = videoAttach;
// Прогресс загрузки видео в хранилище, 0..1; null — загрузки нет
const [videoProgress, setVideoProgress] = useState(null);
// Чат с бэкенда: статус проверки ответов на вопросы объявления и дата регистрации собеседника
const [chatInfo, setChatInfo] = useState(null);
const [deciding, setDeciding] = useState(false);
// Черновик к объявлению с контрольными вопросами: вместо поля ввода — форма ответов
const claimQuestions = draft?.questions?.length ? draft.questions : null;
// id вложений, для которых уже запрашивали свежую ссылку, — без повторов по кругу
const refreshedPhotosRef = useRef(new Set());
const messagesEndRef = useRef(null);
@@ -78,6 +87,10 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
const handleIncoming = useCallback((msg) => {
addMessage(msg);
// Автор подтвердил или отклонил ответы: снимаем или оставляем блокировку ввода
if (msg.kind === "VERIFICATION" && msg.verificationStatus) {
setChatInfo((prev) => (prev ? { ...prev, verificationStatus: msg.verificationStatus } : prev));
}
}, [addMessage]);
// Сервер отклонил отправку (пустое/длинное сообщение, нет доступа к чату)
@@ -115,11 +128,14 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
})
.catch(() => setLoadError(t('chats.loadError')));
setChatInfo(null);
fetchChat(chatId).then(setChatInfo).catch(() => {});
markAsRead(chatId);
clearChatUnread(chatId);
return () => setActiveChatId(null);
}, [chatId, fetchMessages, markAsRead, clearChatUnread, t]);
}, [chatId, fetchMessages, markAsRead, clearChatUnread, fetchChat, t]);
// Шапка и поле ввода лежат поверх ленты сообщений — меряем их высоту в
// CSS-переменные --chat-header-height / --chat-input-height, чтобы первое
@@ -222,6 +238,33 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
}, [input, sendMessage, t, draft, startingChat, startChat, navigate, onActivity,
upload, sendingPhotos, sendPhotoMessage, chatId, addMessage, videoAttach, sendVideoMessage]);
// «Это моё»: чат создаётся вместе с ответами, дальше ждём решения автора
const handleClaim = useCallback((answers) => {
if (startingChat) return;
setStartingChat(true);
claimPost(draft.postId, answers, draft.post)
.then((chat) => {
onActivity?.();
navigate(`/chats/${chat.id}`, { replace: true });
})
// 429 — лимит заявок; 409 — уже отвечали; 400 — не все ответы
.catch((err) => setSendError(describeApiError(err, t('chat.claimError'))))
.finally(() => setStartingChat(false));
}, [startingChat, claimPost, draft, onActivity, navigate, t]);
const handleDecide = useCallback((approved) => {
if (deciding) return;
setDeciding(true);
decideVerification(chatId, approved)
.then((msg) => {
addMessage(msg);
setChatInfo((prev) => ({ ...prev, verificationStatus: msg.verificationStatus }));
onActivity?.();
})
.catch((err) => setSendError(describeApiError(err, t('chat.verifyError'))))
.finally(() => setDeciding(false));
}, [deciding, decideVerification, chatId, addMessage, onActivity, t]);
/**
* Выбор файлов: фото (до 10) или одно видео. Видео уходит отдельным
* сообщением — вместе с фото его не отправить.
@@ -265,7 +308,11 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
.catch(() => {});
}, [chatId, refreshAttachmentUrl]);
const post = draft ? draft.post : getPostForChat(chatId);
const post = draft ? draft.post : (getPostForChat(chatId) || chatInfo?.post);
const verificationStatus = chatInfo?.verificationStatus ?? null;
const isClaimant = chatInfo?.claimantId != null && String(chatInfo.claimantId) === String(myUserId);
// Заявитель пишет только после подтверждения ответов (бэкенд отклонит и сам)
const inputLocked = isClaimant && verificationStatus != null && verificationStatus !== "APPROVED";
const postImg = getImageUrl(post?.images?.[0]);
const postId = post?.id ?? draft?.postId;
@@ -296,8 +343,12 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
/>
<div className="chat-messages">
<ChatSafetyNotice key={chatId ?? "draft"} chatId={chatId} otherUserCreatedAt={chatInfo?.otherUserCreatedAt} t={t} />
{loadError && <div className="chat-empty">{loadError}</div>}
{!loadError && messages.length === 0 && (
{claimQuestions && (
<ClaimForm questions={claimQuestions} onSubmit={handleClaim} sending={startingChat} t={t} />
)}
{!loadError && !claimQuestions && messages.length === 0 && (
<div className="chat-empty">{t('chat.noMessages')}</div>
)}
{messages.map((m) => (
@@ -313,6 +364,18 @@ export default function ChatPage({ embedded = false, onActivity } = {}) {
</div>
<ChatInputBar
locked={!!claimQuestions || inputLocked}
notice={(
<VerificationPanel
status={verificationStatus}
isClaimant={isClaimant}
postId={postId}
phoneVisible={!!(chatInfo?.post?.phoneVisible ?? post?.phoneVisible)}
onDecide={handleDecide}
deciding={deciding}
t={t}
/>
)}
input={input}
onInputChange={setInput}
onSend={handleSend}