diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index fd7928e2..26d65123 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -594,6 +594,7 @@ export function createBot(o: BotOptions) { await keepFeedbackMode(db, user.id, f.id); await reply( m.chat.id, + // glossary-ignore: «команда» here is the team of people, not a terminal command [tr("Спасибо, передали команде. Обращение №{id}.", { id: f.id }), tr("Можно прислать ещё скриншоты — до {n} на обращение.", { n: FEEDBACK_MAX_SHOTS }), tr("Ваши обращения: {url}/feedback", { url: esc(o.webUrl) })].join("\n"), m.message_id, ); @@ -799,7 +800,7 @@ export function createBot(o: BotOptions) { // PEP-143: «Сообщить о проблеме». if (/^\/(problem|feedback)\b/.test(text)) { await openFeedbackMode(db, user.id); - await reply(m.chat.id, [tr("Опишите, что случилось, одним сообщением — текстом, фото экрана с подписью или голосом."), tr("Мы передадим это команде Peppa FACTORY.")].join("\n")); + await reply(m.chat.id, [tr("Опишите, что случилось, одним сообщением — текстом, фото экрана с подписью или голосом."), tr("Мы передадим это тем, кто делает Peppa FACTORY.")].join("\n")); return "done"; } // A superadmin pressed «Не исправлять»: this message is the reason. diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 0c572fa8..6a3861eb 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -60,6 +60,7 @@ import { checkGiteaBotToken, setUiMode, } from "@peppa/core"; +import { fixFeedback, linkFeedback, rejectFeedback } from "@peppa/core"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; import { acceptStory, fixStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription } from "@peppa/runner"; @@ -801,3 +802,26 @@ export async function disconnectOwnBotAction(f: FormData) { return str(f, "back") === "/" ? "/" : "/settings#telegram"; }); } + + +// ── PEP-143: users' reports about Peppa — the superadmin decides ───────────────────── +export async function fixFeedbackAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + await fixFeedback(db, user, Number(str(f, "feedbackId")), Number(str(f, "option"))); + }); +} + +export async function linkFeedbackAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + await linkFeedback(db, user, Number(str(f, "feedbackId")), str(f, "task") || null); + }); +} + +export async function rejectFeedbackAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + await rejectFeedback(db, user, Number(str(f, "feedbackId")), str(f, "reason") || null); + }); +} diff --git a/apps/web/app/(app)/feedback/page.tsx b/apps/web/app/(app)/feedback/page.tsx new file mode 100644 index 00000000..b01532be --- /dev/null +++ b/apps/web/app/(app)/feedback/page.tsx @@ -0,0 +1,52 @@ +import Link from "next/link"; +import { FEEDBACK_ADMIN_STATUS, FEEDBACK_STATUSES, isFeedbackStatus, isSuperadmin, listAllFeedback, listUserFeedback } from "@peppa/core"; +import { AdminFeedbackCard, MyFeedbackCard } from "@/components/Feedback"; +import { Empty, Flash, PageHeader, Section } from "@/components/common"; +import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { getT } from "@/lib/i18n"; +import { cn } from "@/lib/utils"; + +/** + * PEP-143: «Обращения». Everybody sees their own reports and where they stand; the superadmin + * also sees everybody's, filtered by status, and decides on them. + */ +export default async function FeedbackPage({ searchParams }: { searchParams: Promise<{ error?: string; status?: string; id?: string }> }) { + const user = await requireUser(); + const t = await getT(); + const { error, status, id } = await searchParams; + const superadmin = await isSuperadmin(db, user); + const mine = await listUserFeedback(db, user.id); + const filter = isFeedbackStatus(status) ? status : null; + const all = superadmin ? await listAllFeedback(db, { status: filter }) : []; + // A link from a message opens one report first. + const focus = Number(id); + const sorted = Number.isInteger(focus) ? [...all].sort((a, b) => Number(b.id === focus) - Number(a.id === focus)) : all; + const back = `/feedback${filter ? `?status=${filter}` : ""}`; + const tab = (href: string, label: string, active: boolean) => ( + + {label} + + ); + return ( + +
+ + {t("Здесь всё, что вы сообщили о проблемах в Peppa FACTORY, и что с этим стало. Новое обращение — кнопка «Сообщить о проблеме» внизу любой страницы.")} + {superadmin && ( +
+ + {sorted.length === 0 ? {t("Таких обращений нет.")} : sorted.map((f) => )} +
+ )} +
+ {mine.length === 0 ? {t("Вы пока ничего не сообщали. Заметили проблему — нажмите «Сообщить о проблеме».")} : mine.map((f) => )} +
+
+
+ ); +} diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index 30661920..3bf63614 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -79,6 +79,7 @@ function rich(s: string): ReactNode { async function ProductHelp() { const t = PRODUCT_HELP[await getLocale()] ?? PRODUCT_HELP.ru; const connect = CONNECT_HELP[await getLocale()] ?? CONNECT_HELP.ru; + const tr = await getT(); return (
@@ -100,6 +101,10 @@ async function ProductHelp() { ))}

{t.question}

+

+ {t.problem}{" "} + {tr("Ваши обращения")} +

{connect.linkFromHelp}{" "} {connect.linkLabel} @@ -248,6 +253,12 @@ export default async function Help() {

+
+

+ {t("Кнопка «Сообщить о проблеме» внизу любой страницы — для проблем в самой Peppa FACTORY: текст и до 5 скриншотов (файл, перетаскивание, вставка из буфера); страница, вид, язык, браузер и последние ошибки браузера прикладываются сами. В Telegram — /problem, затем текст, фото с подписью или голосовое. Обращение разбирает агент обратной связи; суперадмин получает разбор с вариантами исправления и решает: завести задачу, связать с существующей или не исправлять. Автор видит статус в разделе «Обращения» и получает сообщение, когда задача принята.")} +

+
+

{rich(t("В Настройках → Уведомления для каждого события (вопросы агентов, готово к ревью, сбои и лимиты, релизы, ошибки из прода, дайджест) выбирается, куда присылать: Telegram и/или браузер. Тихие часы: Telegram приходит без звука, push не показываются. Снятые проекты не присылают ничего — вопросы остаются в вебе. Push в браузере включаются там же кнопкой (Chrome спросит разрешение) и работают при закрытой вкладке; клик открывает стори. Во вкладке Peppa FACTORY в заголовке и на значке приложения — сколько ждёт вас, при новом вопросе звучит сигнал (если звук включён). Ежедневный дайджест приходит в выбранное время (по умолчанию 09:00): сделано за сутки, в работе, на ревью, ждёт вас, зависло, лимиты; пустой не приходит."))} diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index 0f8e0708..4639ee97 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from "react"; -import { accountUsageForUser, agentsLine, getNotifyPrefs, isSuperadmin } from "@peppa/core"; +import { accountUsageForUser, agentsLine, getNotifyPrefs, isSuperadmin, pendingFeedbackCount } from "@peppa/core"; import { db } from "@/lib/db"; import { requireUser, uiMode } from "@/lib/auth"; import { navCounts } from "@/lib/queries"; @@ -10,6 +10,7 @@ import { CommandPalette } from "@/components/CommandPalette"; import { AgentsStrip, UsageStrip } from "@/components/Accounting"; import { VersionWatch } from "@/components/VersionWatch"; import { bootId } from "@/lib/boot"; +import { FeedbackButton } from "@/components/FeedbackButton"; export const dynamic = "force-dynamic"; @@ -29,13 +30,15 @@ export default async function AppLayout({ children }: { children: ReactNode }) {

- +
{line ? : } {children}
+ {/* PEP-143: «Сообщить о проблеме» on every page. */} +
); diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 8caf012d..2148b466 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -1,5 +1,6 @@ import { redirect } from "next/navigation"; -import { claimWelcome, listUserProjects, onboardingChecklist, progressOverview } from "@peppa/core"; +import { claimWelcome, isSuperadmin, listUserProjects, onboardingChecklist, pendingFeedback, progressOverview } from "@peppa/core"; +import { AdminFeedbackCard } from "@/components/Feedback"; import { ProgressOverview } from "@/components/ProgressOverview"; import { OnboardingChecklist } from "@/components/Onboarding"; import { PugBanner } from "@/components/PugMascot"; @@ -20,6 +21,8 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e const w = await words(); if (await claimWelcome(db, user.id)) redirect("/welcome"); const [items, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]); + // PEP-143: users' reports about Peppa FACTORY wait for the superadmin's decision here. + const reports = (await isSuperadmin(db, user)) ? await pendingFeedback(db) : []; return ( }> @@ -30,6 +33,11 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e {items.map((q) => )}
+ {reports.length > 0 && ( +
{t("все обращения")}}> + {reports.slice(0, 5).map((f) => )} +
+ )}
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 215492ef..079a4273 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -108,6 +108,9 @@ export default async function Settings({ searchParams }: { searchParams: Promise + diff --git a/apps/web/app/api/feedback/[id]/shots/[n]/route.ts b/apps/web/app/api/feedback/[id]/shots/[n]/route.ts new file mode 100644 index 00000000..633f8497 --- /dev/null +++ b/apps/web/app/api/feedback/[id]/shots/[n]/route.ts @@ -0,0 +1,20 @@ +// PEP-143: a screenshot of a report — only its author and the superadmins see it. +import { feedbackScreenshot } from "@peppa/core"; +import { currentUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { getT } from "@/lib/i18n"; + +export const dynamic = "force-dynamic"; + +export async function GET(_req: Request, { params }: { params: Promise<{ id: string; n: string }> }) { + const user = await currentUser(); + const t = await getT(); + if (!user) return new Response(t("Нужен вход"), { status: 401 }); + const { id, n } = await params; + const shot = /^\d+$/.test(id) && /^\d+$/.test(n) ? await feedbackScreenshot(db, user, Number(id), Number(n)) : null; + // Somebody else's report and a missing one look the same. + if (!shot) return new Response(t("Не найдено"), { status: 404 }); + return new Response(new Uint8Array(shot.data), { + headers: { "Content-Type": shot.mime, "Cache-Control": "private, max-age=3600", "X-Content-Type-Options": "nosniff", "Content-Disposition": "inline", "Content-Security-Policy": "default-src 'none'; sandbox" }, + }); +} diff --git a/apps/web/app/api/feedback/route.ts b/apps/web/app/api/feedback/route.ts new file mode 100644 index 00000000..d36a37b1 --- /dev/null +++ b/apps/web/app/api/feedback/route.ts @@ -0,0 +1,47 @@ +// PEP-143: «Сообщить о проблеме» — the form posts text, screenshots and what the page knows +// (multipart: a server action's body is capped at 1 MB, screenshots are bigger). +import { FEEDBACK_MAX_BYTES, FEEDBACK_MAX_SHOTS, PeppaError, submitFeedback } from "@peppa/core"; +import { m } from "@peppa/shared/i18n"; +import { asWebActor, currentUser, uiMode } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { getLocale, getT } from "@/lib/i18n"; + +export const dynamic = "force-dynamic"; + +const MAX_BODY = FEEDBACK_MAX_SHOTS * FEEDBACK_MAX_BYTES + 512 * 1024; + +export async function POST(req: Request) { + const t = await getT(); + const fail = (status: number, error: string) => Response.json({ error }, { status }); + const me = await currentUser(); + if (!me) return fail(401, t("Нужен вход")); + const user = asWebActor(me); + if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY) return fail(413, t("Скриншоты слишком большие. Приложите файлы поменьше.")); + let form: FormData; + try { + form = await req.formData(); + } catch { + return fail(400, t("Не получилось прочитать форму. Попробуйте ещё раз.")); + } + const shots = form.getAll("shots").filter((v): v is File => typeof v !== "string"); + let context: Record = {}; + try { + context = JSON.parse(String(form.get("context") ?? "{}")) as Record; + } catch {} + try { + // Oversized files are refused before their bytes are read into memory. + if (shots.some((s) => s.size > FEEDBACK_MAX_BYTES)) throw new PeppaError(m("Скриншот больше 5 МБ. Приложите файл поменьше.")); + const files = await Promise.all(shots.slice(0, FEEDBACK_MAX_SHOTS + 1).map(async (s) => new Uint8Array(await s.arrayBuffer()))); + const f = await submitFeedback(db, user, { + text: String(form.get("text") ?? ""), + via: "web", + files, + // The view and the language are the server's knowledge, not the page's claim. + context: { ...context, mode: await uiMode(), locale: await getLocale(), userAgent: req.headers.get("user-agent") ?? undefined }, + }); + return Response.json({ ok: true, id: f.id }); + } catch (e) { + if (e instanceof PeppaError) return fail(400, t.text(e.message)); + throw e; + } +} diff --git a/apps/web/components/ErrorReporter.tsx b/apps/web/components/ErrorReporter.tsx index c6b030ef..bbdf37a9 100644 --- a/apps/web/components/ErrorReporter.tsx +++ b/apps/web/components/ErrorReporter.tsx @@ -37,6 +37,11 @@ export function ErrorReporter() { let sent = 0; const seen = new Set(); const send = (type: string, message: string, stack?: string) => { + // PEP-143: «Сообщить о проблеме» attaches the page's last errors to the report. + if (message) { + const w = window as unknown as { __peppaErrors?: Array<{ type: string; message: string; at: string }> }; + w.__peppaErrors = [...(w.__peppaErrors ?? []), { type, message: message.slice(0, 500), at: new Date().toISOString() }].slice(-10); + } const key = `${type}|${message}`; if (sent >= MAX_PER_PAGE || seen.has(key) || !message) return; seen.add(key); diff --git a/apps/web/components/Feedback.tsx b/apps/web/components/Feedback.tsx new file mode 100644 index 00000000..17311b22 --- /dev/null +++ b/apps/web/components/Feedback.tsx @@ -0,0 +1,139 @@ +import Link from "next/link"; +import { FEEDBACK_ADMIN_STATUS, FEEDBACK_KIND, FEEDBACK_SIZE, FEEDBACK_USER_STATUS, feedbackTitle, type FeedbackView } from "@peppa/core"; +import { Hidden } from "@/components/cards"; +import { ago, Disclosure } from "@/components/common"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { Card } from "@/components/ui/card"; +import { Input } from "@/components/ui/input"; +import { getT } from "@/lib/i18n"; +import { fixFeedbackAction, linkFeedbackAction, rejectFeedbackAction } from "@/app/(app)/actions"; + +const TONE = { received: "muted", analyzed: "info", planned: "info", fixed: "ok", rejected: "warn" } as const; + +function Shots({ f, label }: { f: FeedbackView; label: (n: number) => string }) { + if (!f.screenshots.length) return null; + return ( +
+ {f.screenshots.map((s, i) => ( + + {label(i + + ))} +
+ ); +} + +/** PEP-143: the author's own report — what they wrote, where it stands, what they were answered. */ +export async function MyFeedbackCard({ f }: { f: FeedbackView }) { + const t = await getT(); + return ( + +
+ {feedbackTitle(f)} + {t.text(FEEDBACK_USER_STATUS[f.status])} + {ago(f.createdAt, t)} +
+ {f.text.includes("\n") &&

{f.text}

} + t("Скриншот {n}", { n })} /> + {f.status === "fixed" &&

{t("Исправили. Спасибо, что сообщили.")}

} + {f.status === "rejected" &&

{f.rejectReason ? t("Решили пока не исправлять. Причина: {reason}", { reason: f.rejectReason }) : t("Решили пока не исправлять.")}

} +
+ ); +} + +/** PEP-143: a report for the superadmin — who, where, what, the agent's analysis and the decision. */ +export async function AdminFeedbackCard({ f, back }: { f: FeedbackView; back: string }) { + const t = await getT(); + const a = f.analysis; + const c = f.context; + const open = f.status === "received" || f.status === "analyzed"; + const fields = { feedbackId: f.id, back }; + return ( + +
+ №{f.id} + {f.authorName && f.authorName.toLowerCase() !== f.authorLogin.toLowerCase() ? `${f.authorName} (${f.authorLogin})` : f.authorLogin} + {f.via === "telegram" ? "Telegram" : t("веб")} + {a && {t.text(FEEDBACK_KIND[a.kind])}} + {t.text(FEEDBACK_ADMIN_STATUS[f.status])} + {ago(f.createdAt, t)} +
+ {f.text ?

{f.text}

:

{t("Скриншот без подписи")}

} + t("Скриншот {n}", { n })} /> + {(c.url || c.userAgent || c.errors?.length) && ( + +
+ {c.projectKey && (<>
{t("Проект")}
{c.taskKey ?? c.projectKey}
)} + {c.mode && (<>
{t("Вид")}
{c.mode === "engineer" ? t("Инженер") : t("Продакт")}
)} + {c.locale && (<>
{t("Язык")}
{c.locale}
)} + {c.viewport && (<>
{t("Окно")}
{c.viewport}
)} + {c.userAgent && (<>
{t("Браузер")}
{c.userAgent}
)} + {c.errors?.map((e, i) => ( +
+
{t("Ошибка")}
+
{e.type}: {e.message}
+
+ ))} +
+
+ )} + {a ? ( +
+

{t("Суть")}: {a.summary}

+ {a.cause &&

{t("Вероятная причина")}: {a.cause}

} + {!a.confident &&

{t("Агент не уверен в разборе — проверьте сами.")}

} + {a.options.map((o, i) => ( +
+
+ {t("Вариант {n}", { n: i + 1 })} + {o.title} + {a.recommended === i + 1 && {t("рекомендуем")}} + {t.text(FEEDBACK_SIZE[o.size])} + {f.optionIndex === i + 1 && {t("выбран")}} +
+

{o.what}

+ {o.pros &&

➕ {o.pros}

} + {o.cons &&

➖ {o.cons}

} + {open && ( +
+ + + + )} +
+ ))} +
+ ) : ( + f.status !== "received" &&

{f.analysisError ? t("Разбора нет: агент не смог ответить.") : t("Разбора нет.")}

+ )} + {f.status === "received" &&

{t("Агент обратной связи разбирает обращение…")}

} + {f.taskKey && ( +

+ {t("Задача")}: {f.taskKey} {f.taskTitle} +

+ )} + {f.status === "rejected" &&

{f.rejectReason ? t("Не исправляем. Причина: {reason}", { reason: f.rejectReason }) : t("Не исправляем.")}

} + {open && ( +
+ {!a?.options.length && ( +
+ + + + )} +
+ + + + +
+ + + + +
+ )} +
+ ); +} diff --git a/apps/web/components/FeedbackButton.tsx b/apps/web/components/FeedbackButton.tsx new file mode 100644 index 00000000..d5215c87 --- /dev/null +++ b/apps/web/components/FeedbackButton.tsx @@ -0,0 +1,227 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { usePathname } from "next/navigation"; +import { CircleCheck, ImagePlus, MessageCircleWarning, X } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Textarea } from "@/components/ui/input"; +import { useT } from "@/components/I18n"; +import { cn } from "@/lib/utils"; + +const MAX_SHOTS = 5; +const MAX_BYTES = 5 * 1024 * 1024; +const TYPES = ["image/png", "image/jpeg", "image/webp"]; + +interface Shot { + file: File; + url: string; +} + +/** + * PEP-143: «Сообщить о проблеме» on every page — text plus up to five screenshots (file picker, + * drag and drop, paste from the clipboard). The page address, the window size and the page's + * last browser errors go along by themselves. + */ +export function FeedbackButton() { + const t = useT(); + const path = usePathname(); + const dialog = useRef(null); + const picker = useRef(null); + const [text, setText] = useState(""); + const [shots, setShots] = useState([]); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const [sent, setSent] = useState(false); + const [over, setOver] = useState(false); + + const add = useCallback( + (files: Iterable) => { + setError(null); + setShots((cur) => { + const next = [...cur]; + for (const file of files) { + if (!TYPES.includes(file.type)) { + setError(t("Файл не похож на картинку. Приложите скриншот в формате PNG, JPEG или WebP.")); + continue; + } + if (file.size > MAX_BYTES) { + setError(t("Скриншот больше 5 МБ. Приложите файл поменьше.")); + continue; + } + if (next.length >= MAX_SHOTS) { + setError(t("Можно приложить не больше {n} скриншотов.", { n: MAX_SHOTS })); + break; + } + next.push({ file, url: URL.createObjectURL(file) }); + } + return next; + }); + }, + [t], + ); + + const remove = (i: number) => + setShots((cur) => { + URL.revokeObjectURL(cur[i]!.url); + return cur.filter((_, j) => j !== i); + }); + + const reset = () => { + shots.forEach((s) => URL.revokeObjectURL(s.url)); + setShots([]); + setText(""); + setError(null); + setSent(false); + }; + + const open = () => { + if (sent) reset(); + dialog.current?.showModal(); + }; + + // Ctrl+V anywhere in the open form: a picture from the clipboard becomes a screenshot. + useEffect(() => { + const onPaste = (e: ClipboardEvent) => { + if (!dialog.current?.open) return; + const files = [...(e.clipboardData?.files ?? [])].filter((f) => f.type.startsWith("image/")); + if (!files.length) return; + e.preventDefault(); + add(files); + }; + window.addEventListener("paste", onPaste); + return () => window.removeEventListener("paste", onPaste); + }, [add]); + + const submit = async () => { + if (!text.trim() && !shots.length) return setError(t("Напишите, что случилось, или приложите скриншот.")); + setBusy(true); + setError(null); + try { + const form = new FormData(); + form.set("text", text); + const errors = (window as unknown as { __peppaErrors?: unknown[] }).__peppaErrors ?? []; + form.set("context", JSON.stringify({ url: location.pathname + location.search, viewport: `${window.innerWidth}x${window.innerHeight}`, errors })); + shots.forEach((s) => form.append("shots", s.file, "screenshot")); + const res = await fetch("/api/feedback", { method: "POST", body: form }); + const body = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string }; + if (!res.ok || !body.ok) return setError(body.error ?? t("Не получилось отправить. Проверьте интернет и попробуйте ещё раз.")); + setSent(true); + } catch { + setError(t("Не получилось отправить. Проверьте интернет и попробуйте ещё раз.")); + } finally { + setBusy(false); + } + }; + + return ( + <> + + e.target === dialog.current && dialog.current.close()} + className="m-auto w-[520px] max-w-[calc(100vw-1.5rem)] rounded-xl border bg-card p-0 text-foreground backdrop:bg-black/50" + > +
+
+

{t("Сообщить о проблеме")}

+ +
+ {sent ? ( +
+

+ + {/* glossary-ignore: «команда» here is the team of people, not a terminal command */} + {t("Спасибо, передали команде")} +

+

{t("Мы разберём обращение и напишем вам, когда всё исправим. Статус виден в списке ваших обращений.")}

+
+ + +
+
+ ) : ( + <> +

{t("Напишите, что случилось, и приложите скриншот. Обращение увидят те, кто делает Peppa FACTORY, — мы разберёмся и ответим вам.")}

+