From 3dd174afa5afabb29239e8614872ef262ff4cce1 Mon Sep 17 00:00:00 2001 From: SlimusMinus Date: Wed, 11 Nov 2026 01:04:55 +0300 Subject: [PATCH] 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) --- README.md | 13 ++- src/components/chat/AntiFraud.test.jsx | 100 ++++++++++++++++++++ src/components/chat/ChatInputBar.jsx | 11 ++- src/components/chat/ChatSafetyNotice.jsx | 61 ++++++++++++ src/components/chat/ClaimForm.jsx | 45 +++++++++ src/components/chat/MessageBubble.jsx | 38 ++++++++ src/components/chat/VerificationPanel.jsx | 70 ++++++++++++++ src/config/feedConstants.js | 4 +- src/hooks/useChats.js | 37 +++++++- src/hooks/useContactSeller.js | 8 +- src/locales/en.json | 44 ++++++++- src/locales/ru.json | 44 ++++++++- src/pages/ChatPage.jsx | 71 +++++++++++++- src/pages/CreateUpdatePost.jsx | 59 +++++++++++- src/pages/CreateUpdatePost.test.jsx | 34 +++++++ src/pages/PostOnFeed.jsx | 32 +++++-- src/pages/PostOnFeed.phone.test.jsx | 24 +++++ src/styles/card.css | 13 +++ src/styles/chat.css | 108 ++++++++++++++++++++++ src/styles/modal.css | 18 ++++ 20 files changed, 811 insertions(+), 23 deletions(-) create mode 100644 src/components/chat/AntiFraud.test.jsx create mode 100644 src/components/chat/ChatSafetyNotice.jsx create mode 100644 src/components/chat/ClaimForm.jsx create mode 100644 src/components/chat/VerificationPanel.jsx diff --git a/README.md b/README.md index e3defc9..9a2d4a1 100644 --- a/README.md +++ b/README.md @@ -251,6 +251,13 @@ src/ удаление, отметка «найдено». Номер телефона в ленту не приходит: если автор дал согласие (`phoneVisible`), показывается кнопка «Показать номер» (`useRevealPhone`, proof-of-work); автор видит свой номер сразу. У закрытого объявления кнопки нет. +У объявления с контрольными вопросами (`verificationQuestions`) кнопка «Написать» становится +«Я нашёл» (у потери) или «Это моё» (у находки): черновик чата показывает форму ответов (`ClaimForm`), чат создаётся вместе с ними +(`POST /api/v1/posts/:id/claim`), а писать дальше и видеть номер заявитель может, когда автор +подтвердит ответы (`VerificationPanel`, `POST /api/v1/chats/:id/verification`). В каждом чате — +плашка «не переводите предоплату» (`ChatSafetyNotice`) и отметка о новом аккаунте собеседника; +под сообщением с просьбой о предоплате, данных карты или коде из СМС получатель видит +предупреждение (`message.fraudSignal` с бэкенда). Пропсы `compact` (без адреса и даты — для карты) и `hideContact` (без «Написать» — карточка открыта из самого чата). @@ -260,7 +267,8 @@ proof-of-work); автор видит свой номер сразу. У зак описание, фото (сжатие на клиенте, на десктопе — и перетаскиванием, `useFileDropZone`), категория, карта Яндекса с меткой и обратным геокодированием, адрес, телефон с маской (подставляется из профиля) и галочка согласия на показ номера (`phoneVisible`: без неё -номер не отправляется и не хранится), вознаграждение (только у потерь), чекбокс правил. +номер не отправляется и не хранится), вознаграждение (только у потерь), до трёх контрольных +вопросов (JSON-массивом в `verificationQuestions`) и блок «Как не попасться мошенникам», чекбокс правил. Валидация — `validatePostForm`. С пропом `adminMode` шлёт `PUT /api/v1/admin/posts/{id}` и не меняет согласие автора. @@ -443,6 +451,7 @@ cleanup класса активности. | `DELETE` | `/api/v1/posts/:id` | Удалить | | `PATCH` | `/api/v1/posts/:postId/status` | Статус `ACTIVE` / `CLOSED` | | `GET` | `/api/v1/posts/:id/phone/challenge` | Задача proof-of-work для показа номера (без входа) | +| `POST` | `/api/v1/posts/:id/claim` | «Я нашёл» / «Это моё»: `{ answers }` на контрольные вопросы → чат-заявка (201) | | `POST` | `/api/v1/posts/:id/phone` | `{ salt, number, signature }` → `{ phone }`; 429 — лимит или бан | Автор объявления — поле `userLogin` (прежнее `userEmail` удалено). `phone` приходит @@ -465,6 +474,8 @@ cleanup класса активности. | `GET` | `/api/v1/chats` | Список чатов: `post {id, title, images, type, status, city}`, последнее сообщение, `lastMessageAttachments` / `lastMessageAttachmentKind`, непрочитанные | | `GET` | `/api/v1/chats/with/:otherUserId?postId=` | Найти чат по объявлению; 404 — переписки ещё нет (открывается черновик `/chats/new`) | | `POST` | `/api/v1/chats/with/:otherUserId/messages?postId=` | Первое сообщение `{ content }`: создаёт чат | +| `GET` | `/api/v1/chats/:chatId` | Один чат: `verificationStatus`, `claimantId`, `otherUserCreatedAt` | +| `POST` | `/api/v1/chats/:chatId/verification` | Автор объявления: `{ approved }` → сообщение `kind: VERIFICATION` | | `GET` | `/api/v1/chats/:chatId/messages` | Сообщения (`attachments` у каждого) | | `POST` | `/api/v1/chats/:chatId/messages` | Сообщение с фото: `FormData` (`content`, `files` ×≤10) | | `POST` | `/api/v1/chats/:chatId/videos/upload-url` | `{ contentType, sizeBytes }` → `{ uploadUrl, sourceKey }` | diff --git a/src/components/chat/AntiFraud.test.jsx b/src/components/chat/AntiFraud.test.jsx new file mode 100644 index 0000000..1248c0f --- /dev/null +++ b/src/components/chat/AntiFraud.test.jsx @@ -0,0 +1,100 @@ +/** + * Антифрод в чате: предупреждения о предоплате и кодах, ответы на контрольные + * вопросы находки, решение автора, плашка безопасности и «новый аккаунт». + */ +import { render, screen, fireEvent } from "@testing-library/react"; +import i18n from "../../i18n"; +import MessageBubble from "./MessageBubble"; +import ClaimForm from "./ClaimForm"; +import VerificationPanel from "./VerificationPanel"; +import ChatSafetyNotice, { isNewAccount } from "./ChatSafetyNotice"; + +jest.mock("../../api/phoneApi", () => ({ revealPhone: jest.fn() })); + +const t = i18n.t.bind(i18n); + +beforeAll(() => i18n.changeLanguage("ru")); +beforeEach(() => localStorage.clear()); + +const msg = (extra) => ({ id: 1, senderId: 2, content: "Переведите 500 ₽ за доставку", createdAt: "2026-11-10T10:00:00", ...extra }); + +test("предупреждение о предоплате видит получатель, а не отправитель", () => { + const { rerender } = render(); + expect(screen.getByRole("alert").textContent).toMatch(/предоплаты/); + + rerender(); + expect(screen.queryByRole("alert")).toBeNull(); +}); + +test("ответы на вопросы показываются карточкой вопрос — ответ", () => { + render(); + + expect(screen.getByText("Ответы на вопросы")).toBeTruthy(); + expect(screen.getByText("1. Что на брелке?")).toBeTruthy(); + expect(screen.getByText("Сова")).toBeTruthy(); +}); + +test("решение автора — служебная строка", () => { + render(); + + expect(screen.getByRole("status").className).toContain("chat-system--approved"); +}); + +test("форма ответов отправляется, только когда отвечены все вопросы", () => { + const onSubmit = jest.fn(); + render(); + const [first, second] = screen.getAllByPlaceholderText("Ваш ответ"); + const submit = screen.getByText("Отправить ответы"); + + fireEvent.change(first, { target: { value: " Сова " } }); + expect(submit.disabled).toBe(true); + fireEvent.change(second, { target: { value: "Синий" } }); + fireEvent.click(submit); + + expect(onSubmit).toHaveBeenCalledWith(["Сова", "Синий"]); +}); + +test("автор подтверждает или отклоняет ответы", () => { + const onDecide = jest.fn(); + render(); + + fireEvent.click(screen.getByText("Отклонить")); + fireEvent.click(screen.getByText("Подтвердить")); + expect(onDecide.mock.calls).toEqual([[false], [true]]); +}); + +test("заявитель ждёт решения, после подтверждения может открыть номер", () => { + const { rerender } = render(); + expect(screen.getByText(/проверяет ваши ответы/)).toBeTruthy(); + + rerender(); + expect(screen.getByText("Показать номер автора")).toBeTruthy(); +}); + +test("в обычном чате панели проверки нет", () => { + const { container } = render(); + expect(container.innerHTML).toBe(""); +}); + +test("плашку безопасности можно скрыть в чате, отметку о новом аккаунте — нет", () => { + const recent = new Date(Date.now() - 2 * 24 * 3600 * 1000).toISOString(); + render(); + + fireEvent.click(screen.getByText("Скрыть")); + + expect(screen.queryByText("Осторожно, мошенники")).toBeNull(); + expect(screen.getByText(/Новый аккаунт/)).toBeTruthy(); +}); + +test("новый аккаунт — моложе недели", () => { + const now = Date.parse("2026-11-10T00:00:00Z"); + expect(isNewAccount("2026-11-05T00:00:00Z", now)).toBe(true); + expect(isNewAccount("2026-10-01T00:00:00Z", now)).toBe(false); + expect(isNewAccount(null, now)).toBe(false); +}); diff --git a/src/components/chat/ChatInputBar.jsx b/src/components/chat/ChatInputBar.jsx index f9c5ce0..e6ef95f 100644 --- a/src/components/chat/ChatInputBar.jsx +++ b/src/components/chat/ChatInputBar.jsx @@ -19,6 +19,8 @@ function PaperclipIcon() { * над полем и вставка картинок из буфера обмена. attach: { images, addFiles, * removeImage, fileInputRef, compressing, error, disabled, label, removeLabel, * accept, video, removeVideo, videoProgress }. + * notice — блок над полем (статус проверки ответов на вопросы находки); + * locked — поля ввода нет, только notice: заявитель ждёт решения автора. */ export default function ChatInputBar({ input, @@ -28,6 +30,8 @@ export default function ChatInputBar({ placeholder, attach, sending = false, + notice = null, + locked = false, }) { const images = attach?.images ?? []; const video = attach?.video ?? null; @@ -44,8 +48,9 @@ export default function ChatInputBar({ }; return ( -
- {attach && (images.length > 0 || video || attach.compressing || attach.error) && ( +
+ {notice} + {!locked && attach && (images.length > 0 || video || attach.compressing || attach.error) && (
{images.map((img) => (
@@ -86,6 +91,7 @@ export default function ChatInputBar({ {attach.error &&
{attach.error}
}
)} + {!locked && (
{attach && ( <> @@ -118,6 +124,7 @@ export default function ChatInputBar({ ➤
+ )}
); } diff --git a/src/components/chat/ChatSafetyNotice.jsx b/src/components/chat/ChatSafetyNotice.jsx new file mode 100644 index 0000000..28a9146 --- /dev/null +++ b/src/components/chat/ChatSafetyNotice.jsx @@ -0,0 +1,61 @@ +import { useState } from "react"; + +const STORAGE_KEY = "nakhodka:safetyNoticeHidden"; +// Аккаунт моложе недели — частый признак мошенника, который заводит новые под каждую схему +const NEW_ACCOUNT_DAYS = 7; + +function readHidden() { + try { + return JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]"); + } catch { + return []; + } +} + +/** Собеседник зарегистрировался меньше недели назад. */ +export function isNewAccount(createdAt, now = Date.now()) { + if (!createdAt) return false; + const created = new Date(createdAt).getTime(); + return Number.isFinite(created) && now - created < NEW_ACCOUNT_DAYS * 24 * 60 * 60 * 1000; +} + +/** + * Плашка над перепиской: не переводить предоплату, не называть коды. Скрыть + * можно в каждом чате отдельно; отметку о новом аккаунте собеседника скрыть + * нельзя — она про конкретного человека. + */ +export default function ChatSafetyNotice({ chatId, otherUserCreatedAt, t }) { + const [hidden, setHidden] = useState(() => chatId != null && readHidden().includes(String(chatId))); + const newAccount = isNewAccount(otherUserCreatedAt); + + const hide = () => { + setHidden(true); + if (chatId == null) return; + try { + const ids = [...new Set([...readHidden(), String(chatId)])].slice(-200); + localStorage.setItem(STORAGE_KEY, JSON.stringify(ids)); + } catch { + // приватный режим — плашка просто снова появится + } + }; + + if (hidden && !newAccount) return null; + + return ( +
+ {!hidden && ( +
+ +
+
{t("chat.safetyTitle")}
+
{t("chat.safetyText")}
+
+ +
+ )} + {newAccount &&
⚠️ {t("chat.newAccount")}
} +
+ ); +} diff --git a/src/components/chat/ClaimForm.jsx b/src/components/chat/ClaimForm.jsx new file mode 100644 index 0000000..ed7a4a0 --- /dev/null +++ b/src/components/chat/ClaimForm.jsx @@ -0,0 +1,45 @@ +import { useState } from "react"; + +// Тот же лимит, что ChatClaimService.MAX_ANSWER_LENGTH на бэкенде +const MAX_ANSWER_LENGTH = 500; + +/** + * Ответы на контрольные вопросы объявления («нашёл», «это моё») вместо первого сообщения. + * Чат создаётся вместе с ответами; писать дальше можно после подтверждения. + * + * @param {{ questions: string[], onSubmit: (answers: string[]) => void, sending: boolean, t: function }} props + */ +export default function ClaimForm({ questions, onSubmit, sending, t }) { + const [answers, setAnswers] = useState(() => questions.map(() => "")); + const complete = answers.every((a) => a.trim()); + + const submit = (e) => { + e.preventDefault(); + if (!complete || sending) return; + onSubmit(answers.map((a) => a.trim())); + }; + + return ( +
+
{t("chat.claimTitle")}
+

{t("chat.claimIntro")}

+ {questions.map((question, i) => ( +