Files
nahodka-front/src/pages/PostOnFeed.jsx
SlimusMinus 3dd174afa5 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>
2026-11-11 01:04:55 +03:00

431 lines
19 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 {useRef, useState, useEffect} from "react";
import PinIcon from "../components/icons/PinIcon";
import CalendarIcon from "../components/icons/CalendarIcon";
import PhoneIcon from "../components/icons/PhoneIcon";
import TrashIcon from "../components/icons/TrashIcon";
import CheckIcon from "../components/icons/CheckIcon";
import {useContactSeller} from "../hooks/useContactSeller";
import {useRevealPhone} from "../hooks/useRevealPhone";
import {useAuthContext} from "../context/AuthContext";
import {getImageUrl} from "../config/authConstants";
import {CATEGORY_PET} from "../config/feedConstants";
import {POST_STATUS_CLOSED, POST_STATUS_MODERATION, POST_STATUS_REJECTED} from "../config/postConstants";
import {getFoundAt, formatFoundDate} from "../utils/foundAt";
import DateCalendarPopup from "../components/DateCalendarPopup";
import RewardPopup from "../components/feed/RewardPopup";
import Toast from "../components/Toast";
import {useTranslation} from 'react-i18next';
export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen, isOwner, authorLabel, allowEditClosed, onLocationClick, onAuthRequired, compact, hideContact }) {
const { t, i18n } = useTranslation();
const [showCalendar, setShowCalendar] = useState(false);
const [showReward, setShowReward] = useState(false);
const [descExpanded, setDescExpanded] = useState(false);
const [descTruncated, setDescTruncated] = useState(false);
const [imgIndex, setImgIndex] = useState(0);
const dateAnchorRef = useRef(null);
const rewardAnchorRef = useRef(null);
const descRef = useRef(null);
const imgTouchStartRef = useRef(null);
const { isAuthenticated, user } = useAuthContext();
// Своё объявление: писать самому себе нельзя (бэкенд отвечает 400), кнопку не показываем.
// isOwner тут не подходит — в общей ленте он false и для своих объявлений.
const isOwnAd = user?.id != null && ad.userId != null && String(ad.userId) === String(user.id);
const { contactSeller, error: contactError, clearError } = useContactSeller(ad);
const phoneReveal = useRevealPhone(ad.id);
useEffect(() => {
const check = () => {
if (!descExpanded && descRef.current) {
setDescTruncated(descRef.current.scrollHeight > descRef.current.clientHeight + 1);
}
};
check();
window.addEventListener("resize", check);
return () => window.removeEventListener("resize", check);
}, [descExpanded]);
const handleContact = (e) => {
e.stopPropagation();
if (!isAuthenticated) {
if (onAuthRequired) onAuthRequired();
return;
}
contactSeller();
};
const images = Array.isArray(ad.images) ? ad.images : [];
// Карусель включается для любого объявления с несколькими фото: листать
// можно и в ленте, и в детальной модалке. Полноэкранного просмотрщика нет.
const carousel = images.length > 1;
const hasImages = images.length > 0;
// Листание фото прямо в карточке: на телефоне — свайпом, на десктопе —
// стрелками и точками. Листание зациклено: с последнего кадра переходим на
// первый и наоборот.
const goToImage = (target) => {
const len = images.length;
if (!len) return;
setImgIndex(((target % len) + len) % len);
};
const handleImgTouchStart = (e) => {
if (!carousel) return;
imgTouchStartRef.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
};
const handleImgTouchEnd = (e) => {
const start = imgTouchStartRef.current;
imgTouchStartRef.current = null;
if (!start || !carousel) return;
const dx = e.changedTouches[0].clientX - start.x;
const dy = e.changedTouches[0].clientY - start.y;
// Реагируем только на явно горизонтальный жест — вертикальный скролл ленты
// не должен переключать фото.
if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {
const len = images.length;
const step = dx < 0 ? 1 : -1;
setImgIndex(i => (i + step + len) % len);
}
};
// На карточке показываем только город; полный адрес — запасной вариант,
// чтобы у старых объявлений без города не пропала кнопка карты
const address = ad.city || ad.district || ad.address || ad.location;
const createdAt = ad.createdAt
? new Date(ad.createdAt).toLocaleDateString("ru-RU")
: null;
const isClosed = ad.status === POST_STATUS_CLOSED;
const pendingStatusText = ad.status === POST_STATUS_MODERATION
? t('postCard.statusModeration')
: ad.status === POST_STATUS_REJECTED ? t('postCard.statusRejected') : null;
// Для питомцев «найдено» — это хорошая новость с воссоединением, поэтому
// формулировка эмоциональнее, чем сухое «Найдено».
const isPet = ad.category === CATEGORY_PET;
const foundText = isPet ? t('postCard.petFoundStatus') : t('postCard.foundStatus');
const foundDate = isClosed ? formatFoundDate(getFoundAt(ad), i18n.language) : null;
// aria-подпись собираем целиком: статус не должен читаться только цветом.
const foundAriaText = foundDate
? t('postCard.foundStatusWithDate', {status: foundText, date: foundDate})
: foundText;
// Номер в ленту не приходит: в «Моих объявлениях» и в админке он есть в ad.phone,
// в общей ленте его открывают кнопкой (proof-of-work на бэкенде) — и автор
// своего объявления тоже, чтобы видеть то же, что покупатель.
// У закрытого объявления номер не показывается: вещь уже вернулась.
const shownPhone = ad.phone || phoneReveal.phone;
// Объявление с контрольными вопросами: написать — только ответив на них, а номер
// открывается заявителю после подтверждения ответов (в чате). Автор свой номер видит.
// У потери это отсекает «нашёл, оплатите доставку», у находки — «это моё» по фото.
const needsVerification = !isOwnAd
&& Array.isArray(ad.verificationQuestions) && ad.verificationQuestions.length > 0;
const canRevealPhone = !shownPhone && ad.phoneVisible && !isClosed && !needsVerification;
const phoneAfterVerification = !shownPhone && ad.phoneVisible && !isClosed && needsVerification;
const headAccentClass = ad.type === "found" ? " f-head-found" : " f-head-loss";
const typeBadge = (
<div className={`f-type-badge ${ad.type === "loss" ? "f-type-loss" : "f-type-found"}`}>
{ad.type === "loss" ? t('postCard.loss') : t('postCard.found')}
</div>
);
// У находки вознаграждения нет — его предлагает только владелец
const hasReward = ad.reward && ad.type !== "found";
// В ленте кнопка стоит в строке под описанием; в compact (объявление,
// открытое с карты) этой строки нет — кнопка лежит на фото справа снизу,
// чтобы её было видно сразу, без прокрутки окна.
const rewardButton = hasReward && (
<>
<button
ref={rewardAnchorRef}
type="button"
className={`f-card-reward-text f-card-reward-btn${compact ? " f-card-reward-on-img" : ""}`}
onClick={e => {
e.stopPropagation();
setShowReward(s => !s);
}}
>
<span className="f-reward-btn-label">{t("postCard.reward")}</span>
</button>
{showReward && (
<RewardPopup
text={ad.rewardText || t("postCard.reward")}
anchorRef={rewardAnchorRef}
onClose={() => setShowReward(false)}
/>
)}
</>
);
return (
<div className={`f-card${isClosed ? ' f-card-closed' : ''}${ad.type === "found" ? ' f-card-found' : ' f-card-loss'}`}
role="group"
aria-label={isClosed ? `${ad.title}. ${foundAriaText}` : ad.title}>
<div className={`f-card-head${headAccentClass}`}>
<div className="f-card-author">
<div
className="f-card-author-name"
>
{ad.title}
</div>
{authorLabel && (
<div className="f-card-author-sub">{authorLabel}</div>
)}
</div>
<div className="f-card-head-side">
{pendingStatusText && (
<div className={`f-status-badge${ad.status === POST_STATUS_REJECTED ? " f-status-badge-rejected" : ""}`}>
{pendingStatusText}
</div>
)}
{typeBadge}
</div>
</div>
<div
className={`f-card-img${carousel ? " f-card-img-multi" : ""}${hasImages ? " f-card-img-filled" : ""}`}
onTouchStart={handleImgTouchStart}
onTouchEnd={handleImgTouchEnd}
>
{images.length > 0 ? (
carousel ? (
<div
className="f-card-img-track"
style={{ transform: `translateX(-${imgIndex * 100}%)` }}
>
{images.map((raw, i) => (
<img
key={i}
src={getImageUrl(raw)}
alt={ad.title}
className="f-card-img-slide"
draggable={false}
loading="lazy"
decoding="async"
/>
))}
</div>
) : (
<img src={getImageUrl(images[0])} alt={ad.title} loading="lazy" decoding="async" />
)
) : (
<span className="f-card-emoji">{ad.emoji || "📋"}</span>
)}
{/* Плашка статуса поверх фото: при быстром скролле шапка карточки
проезжает мимо, а фото с плашкой — нет. */}
{isClosed && (
<span className={`f-img-found-badge${isPet ? ' f-img-found-badge-pet' : ''}`}>
<CheckIcon size={12}/>
<span>{foundText}</span>
</span>
)}
{carousel && (
<>
<button
type="button"
className="f-img-nav f-img-nav-prev"
aria-label={t('viewer.prevImage')}
onClick={e => { e.stopPropagation(); goToImage(imgIndex - 1); }}
>
‹
</button>
<button
type="button"
className="f-img-nav f-img-nav-next"
aria-label={t('viewer.nextImage')}
onClick={e => { e.stopPropagation(); goToImage(imgIndex + 1); }}
>
›
</button>
<div className="f-img-dots">
{images.map((_, i) => (
<button
type="button"
key={i}
className={`f-img-dot${i === imgIndex ? " active" : ""}`}
aria-label={t('viewer.goToImage', { number: i + 1 })}
onClick={e => { e.stopPropagation(); goToImage(i); }}
/>
))}
</div>
</>
)}
{compact && rewardButton}
</div>
{!compact && (
<div className="f-card-actions">
<div className="f-card-actions-left">
{address && (
<div
className="f-meta-pill f-loc-pill"
title={t('postCard.showOnMap', { address })}
onClick={e => {
e.stopPropagation();
onLocationClick?.(ad);
}}
>
<PinIcon/> {address}
</div>
)}
</div>
<div className="f-card-actions-right">
{onEdit && isOwner && (!isClosed || allowEditClosed) && (
<button type="button" className="f-card-edit-btn"
onClick={e => {
e.stopPropagation();
onEdit(ad);
}}>
✏️
</button>
)}
{onDelete && isOwner && (
<button type="button" className="f-card-delete-btn"
onClick={e => {
e.stopPropagation();
onDelete(ad.id);
}}>
<TrashIcon/>
</button>
)}
{createdAt && (
<div
className="f-meta-pill f-date-pill"
ref={dateAnchorRef}
onClick={e => {
e.stopPropagation();
setShowCalendar(s => !s);
}}
>
<CalendarIcon/> {createdAt}
{showCalendar && (
<DateCalendarPopup
date={ad.createdAt}
onClose={() => setShowCalendar(false)}
anchorRef={dateAnchorRef}
/>
)}
</div>
)}
</div>
</div>
)}
<div className="f-card-caption">
<span
ref={descRef}
className={`f-card-caption-text${descTruncated ? " f-truncatable" : ""}${descExpanded ? " f-expanded" : ""}`}
onClick={descTruncated ? () => setDescExpanded(v => !v) : undefined}
>
{ad.description}
</span>
</div>
{!compact && (
<div className="f-card-meta">
{rewardButton}
{needsVerification && !isClosed && (
<span className="f-card-verify-pill" title={t('postCard.phoneAfterVerificationHint')}>
🛡️ {t('postCard.verifiedClaims')}
</span>
)}
</div>
)}
<div className="f-card-foot">
<div className="f-card-foot-left">
{shownPhone ? (
<div className="f-card-phone-wrap">
<a className="f-card-phone" href={`tel:${shownPhone}`}
onClick={e => e.stopPropagation()}>
<PhoneIcon/> {shownPhone}
</a>
{/* Номер открыл не автор — напоминаем о главной схеме мошенников */}
{!ad.phone && <span className="f-card-phone-hint">{t('postCard.phoneSafetyHint')}</span>}
</div>
) : phoneAfterVerification ? (
<span className="f-card-phone f-card-phone-locked" title={t('postCard.phoneAfterVerificationHint')}>
<PhoneIcon/> {t('postCard.phoneAfterVerification')}
</span>
) : canRevealPhone && (
<button type="button" className="f-card-phone f-card-phone-reveal"
disabled={phoneReveal.loading}
aria-busy={phoneReveal.loading}
onClick={e => {
e.stopPropagation();
phoneReveal.reveal();
}}>
<PhoneIcon/> {phoneReveal.loading ? t('postCard.phoneChecking') : t('postCard.showPhone')}
</button>
)}
</div>
<div className="f-card-foot-right">
{isOwnAd ? (
<span className="f-card-own-label">{t('postCard.ownAd')}</span>
) : !hideContact && (
<button type="button" className="f-card-contact"
onClick={handleContact}>
{!needsVerification ? t('postCard.write')
: ad.type === "found" ? t('postCard.claimItem') : t('postCard.claimFound')}
</button>
)}
</div>
</div>
{onMarkFound && isOwner && !isClosed && (
<div className="f-card-found-wrap">
<button type="button" className="f-card-found-btn"
onClick={e => {
e.stopPropagation();
onMarkFound(ad.id);
}}>
{t('postCard.itemFound')}
</button>
</div>
)}
{isClosed && (
<div className="f-card-found-wrap">
{/* Кнопка «найдено» становится неактивной подтверждением: видно,
что действие уже применено, и повторно не нажать. */}
<button type="button" className="f-card-found-btn f-card-found-btn-done"
disabled
aria-label={foundAriaText}
title={foundAriaText}>
<CheckIcon size={14}/>
<span>{foundText}{foundDate ? ` ${foundDate}` : ''}</span>
</button>
{/* Отмена случайного нажатия — автору; в админ-панели это и есть
возврат объявления в ленту. */}
{onReopen && isOwner && (
<button type="button" className="f-card-found-undo"
onClick={e => {
e.stopPropagation();
onReopen(ad.id);
}}>
{t('postCard.undoFound')}
</button>
)}
</div>
)}
{phoneReveal.error && (
<Toast
message={phoneReveal.error}
type="error"
onDismiss={phoneReveal.clearError}
/>
)}
{contactError && (
<Toast
message={contactError}
type="error"
onDismiss={clearError}
/>
)}
</div>
);
}