rebuild the app on a typed, modular structure wired to the real API

The whole app lived in one 3,071-line App.tsx on a Figma scaffold (60 unused
packages, 45 unused UI components, no type-check). The live site could not
reach the backend, Persian-keyboard digits were erased from the phone field,
guests were signed out after an hour, "mark read" hit a method the server
does not accept (405), and iOS Safari blocked the payment window.

What changed:
- src/ split into api/ (one typed client: timeouts, GET retry, single-flight
  refresh, SSE), screens/ (one file each), components/, state/, nav/, lib/.
- The API address is configuration only: public/config.js at runtime, then
  VITE_API_BASE_URL at build time, then same-origin /api. No domain in code.
- Responsive shell instead of a fixed 390x844 phone frame; self-hosted
  Vazirmatn instead of Google Fonts; strict TypeScript, `npm run build`
  type-checks first.
- Everything on the handoff list: tutor answers keep their line breaks, have
  thumbs up/down, follow-ups, "from the book" badge, retry, history that
  survives tab switches and reloads, "why was I wrong" from a wrong answer
  with questionId; question reports; hearts with maxHearts/unlimited and a
  no-hearts screen with the refill time; result screen and a visible error
  when lesson completion fails; subscription status, badge, discount code
  before the gateway and the payment-return message; guest refresh token;
  6-digit OTP with resend timer; age saved as a Jalali birthYear; PATCH
  read-all; leaderboard refetched on open with "you" highlighted; selected
  companion shown across the app; logout that revokes the refresh token.
- New screens for endpoints that had none: profile, streak calendar,
  support tickets and bug reports, parents, invite-a-friend (with ?ref=
  tracking), guest-to-phone upgrade.
- Browser/phone back button walks the screen stack.

Checked with a headless-Chrome walkthrough against a local backend at
390x844 and 360x740 (fresh guest: onboarding, setup, a full lesson, map,
island sheet, every tab and sub-screen, one real tutor question, reload,
logout): no console errors, no failed API calls. Real SMS login and a real
Zarinpal payment were not exercised.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-26 23:35:48 +03:30
parent b411b636f4
commit 348bfecea6
120 changed files with 5840 additions and 12783 deletions

View File

@@ -0,0 +1,197 @@
import { useState } from 'react';
import { Bug, MessageCircle, Send } from 'lucide-react';
import { api, type Ticket } from '@/api';
import { useAsync } from '@/lib/useAsync';
import { KEYS, store } from '@/lib/storage';
import { useToast } from '@/components/Toast';
import { InlineError, PrimaryButton, Screen, ScreenBody, ScreenHeader } from '@/components/ui';
import { friendlyError } from '@/lib/errors';
import { toFa } from '@/lib/format';
const CATEGORIES = [
{ id: 'learning', label: 'درس و سوال‌ها' },
{ id: 'payment', label: 'پرداخت و اشتراک' },
{ id: 'account', label: 'حساب و ورود' },
{ id: 'other', label: 'چیزِ دیگه' },
];
const STATUS_LABEL: Record<string, string> = {
open: 'باز',
in_progress: 'در حالِ بررسی',
answered: 'پاسخ داده شد',
closed: 'بسته',
};
/** سرور فهرستِ تیکت‌ها را نمی‌دهد؛ شناسه‌ها را همین‌جا نگه می‌داریم. */
function savedTicketIds(): string[] {
try {
return JSON.parse(store.get(KEYS.ticketIds) ?? '[]') as string[];
} catch {
return [];
}
}
export function SupportScreen() {
const toast = useToast();
const [mode, setMode] = useState<'ticket' | 'bug'>('ticket');
const [category, setCategory] = useState('learning');
const [subject, setSubject] = useState('');
const [text, setText] = useState('');
const [sending, setSending] = useState(false);
const [error, setError] = useState('');
const [ticketIds, setTicketIds] = useState(savedTicketIds);
async function submit() {
if (!subject.trim() || !text.trim()) return;
setSending(true);
setError('');
try {
if (mode === 'bug') {
await api.support.bugReport(subject.trim(), text.trim());
toast('گزارشت رسید؛ ممنون!', 'success');
} else {
const t = await api.support.createTicket(subject.trim(), category);
await api.support.reply(t.ticketId, text.trim());
const ids = [t.ticketId, ...ticketIds].slice(0, 20);
store.set(KEYS.ticketIds, JSON.stringify(ids));
setTicketIds(ids);
toast('پیامت رسید؛ جواب همین‌جا و در اعلان‌ها میاد.', 'success');
}
setSubject('');
setText('');
} catch (err) {
setError(friendlyError(err, 'ارسال نشد، دوباره امتحان کن'));
} finally {
setSending(false);
}
}
return (
<Screen>
<ScreenHeader title="پشتیبانی" subtitle="سوال، مشکل یا پیشنهاد داری؟ بنویس." color="#4C5FD5" back mascot={{ char: 'sigma', mood: 'happy', size: 56 }} />
<ScreenBody className="flex flex-col gap-4">
<div className="flex gap-1 rounded-2xl bg-soft p-1">
{([['ticket', 'پیام به پشتیبانی', MessageCircle], ['bug', 'گزارشِ خطای اپ', Bug]] as const).map(([id, label, Icon]) => (
<button
key={id}
type="button"
onClick={() => setMode(id)}
className={`flex flex-1 items-center justify-center gap-1.5 rounded-xl py-2.5 text-xs font-bold ${mode === id ? 'bg-white text-indigo shadow-sm' : 'text-muted'}`}
>
<Icon size={14} /> {label}
</button>
))}
</div>
{mode === 'ticket' && (
<div className="flex flex-wrap gap-2">
{CATEGORIES.map((c) => (
<button
key={c.id}
type="button"
onClick={() => setCategory(c.id)}
className={`rounded-full border-2 px-3 py-1.5 text-xs font-bold ${category === c.id ? 'border-indigo bg-indigo text-white' : 'border-line bg-white text-body'}`}
>
{c.label}
</button>
))}
</div>
)}
<input
value={subject}
onChange={(e) => setSubject(e.target.value.slice(0, 120))}
placeholder={mode === 'bug' ? 'چی خراب شد؟ (خلاصه)' : 'موضوع'}
className="w-full rounded-2xl border-2 border-line bg-white px-4 py-3.5 text-sm outline-none focus:border-indigo"
/>
<textarea
value={text}
onChange={(e) => setText(e.target.value.slice(0, 2000))}
rows={5}
placeholder={mode === 'bug' ? 'چه کار کردی و چه اتفاقی افتاد؟' : 'پیامت رو بنویس…'}
className="w-full resize-none rounded-2xl border-2 border-line bg-white px-4 py-3.5 text-sm leading-7 outline-none focus:border-indigo"
/>
{error && <InlineError>{error}</InlineError>}
<PrimaryButton color="#4C5FD5" loading={sending} disabled={!subject.trim() || !text.trim()} onClick={() => void submit()}>
<Send size={16} className="-scale-x-100" /> ارسال
</PrimaryButton>
{ticketIds.length > 0 && (
<section>
<h2 className="mb-2 mt-2 text-sm font-black text-ink">پیام‌های قبلیِ تو</h2>
<div className="flex flex-col gap-2">
{ticketIds.map((id) => <TicketCard key={id} ticketId={id} />)}
</div>
</section>
)}
</ScreenBody>
</Screen>
);
}
function TicketCard({ ticketId }: { ticketId: string }) {
const toast = useToast();
const ticket = useAsync(() => api.support.ticket(ticketId), [ticketId]);
const [open, setOpen] = useState(false);
const [reply, setReply] = useState('');
const [sending, setSending] = useState(false);
if (ticket.error || !ticket.data) {
return ticket.loading ? <div className="h-14 animate-pulse rounded-2xl bg-soft" /> : null;
}
const t: Ticket = ticket.data;
const staffReplies = t.messages.filter((m) => m.sender !== 'user').length;
async function send() {
if (!reply.trim()) return;
setSending(true);
try {
await api.support.reply(ticketId, reply.trim());
setReply('');
ticket.reload();
} catch (err) {
toast(friendlyError(err), 'error');
} finally {
setSending(false);
}
}
return (
<div className="rounded-2xl border border-line bg-white">
<button type="button" onClick={() => setOpen((o) => !o)} className="flex w-full items-center gap-3 p-3.5 text-right">
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-bold text-ink">{t.subject}</span>
<span className="text-[11px] text-muted">
{STATUS_LABEL[t.status] ?? t.status}
{staffReplies > 0 && ` · ${toFa(staffReplies)} پاسخ`}
</span>
</span>
</button>
{open && (
<div className="flex flex-col gap-2 border-t border-line p-3.5">
{t.messages.map((m) => (
<div
key={m.id}
className={`whitespace-pre-line rounded-2xl px-3.5 py-2.5 text-xs leading-6 ${m.sender === 'user' ? 'mr-8 bg-soft text-body' : 'ml-8 bg-[#EEF1FF] text-ink'}`}
>
{m.text}
</div>
))}
{t.status !== 'closed' && (
<div className="mt-1 flex gap-2">
<input
value={reply}
onChange={(e) => setReply(e.target.value.slice(0, 2000))}
placeholder="جواب بده…"
className="flex-1 rounded-full bg-soft px-4 py-2 text-xs outline-none"
/>
<button type="button" disabled={!reply.trim() || sending} onClick={() => void send()} className="rounded-full bg-indigo px-3 text-xs font-bold text-white disabled:opacity-40">
ارسال
</button>
</div>
)}
</div>
)}
</div>
);
}