feat(admin): subscription purchase flow under settings shell

Add a doctor/clinic settings sub-navigation shell (SettingsLayout) with
"خرید اشتراک" as its first section, plus a mobile settings-list page.
Rebuild the plan-selection page with a per-plan billing-period toggle,
single price, most-popular badge and a current-plan status banner.
Add a payment-success page that reads the gateway return params
(?payment_uuid&status), shows the transaction receipt and the newly
active plan, and redirects to the plans page with a toast on any
non-success status.

Frontend only — reuses the existing /api/v1/subscription/* and
/api/v1/subscription-payment endpoints; no backend or API-doc changes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-13 12:45:57 +03:30
co-authored by Claude Opus 4.8
parent 272da4ad9d
commit 174ecfa8fb
9 changed files with 800 additions and 370 deletions
+4
View File
@@ -49,6 +49,8 @@ import ClinicServicesPage from './pages/ClinicServicesPage';
import SmsWalletPage from './pages/SmsWalletPage';
import MySecretariesPage from './pages/MySecretariesPage';
import AdminSubscriptionPage from './pages/AdminSubscriptionPage';
import SettingsMenuPage from './pages/SettingsMenuPage';
import PaymentSuccessPage from './pages/PaymentSuccessPage';
import PwaInstallBanner from './components/ui/PwaInstallBanner';
// ── Guards ──────────────────────────────────────────────────────────────────
@@ -192,7 +194,9 @@ export default function App() {
{/* فاز ۲ — دکتر / کلینیک */}
<Route path="staff" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><StaffPage /></RoleRoute>} />
<Route path="settings-menu" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><SettingsMenuPage /></RoleRoute>} />
<Route path="subscription" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><SubscriptionPage /></RoleRoute>} />
<Route path="subscription/success" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><PaymentSuccessPage /></RoleRoute>} />
<Route path="clinic-services" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><ClinicServicesPage /></RoleRoute>} />
<Route path="sms-wallet" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><SmsWalletPage /></RoleRoute>} />
<Route path="my-secretaries" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><MySecretariesPage /></RoleRoute>} />
@@ -0,0 +1,47 @@
import { describe, it, expect } from 'vitest';
import { screen, fireEvent } from '@testing-library/react';
import { renderWithProviders } from '../../test/utils';
import SettingsLayout, { SETTINGS_MENU } from './SettingsLayout';
describe('SettingsLayout', () => {
it('renders every settings menu item and the section content', () => {
renderWithProviders(
<SettingsLayout active="subscription">
<div>محتوای اشتراک</div>
</SettingsLayout>,
);
for (const item of SETTINGS_MENU) {
expect(screen.getByText(item.label)).toBeInTheDocument();
}
expect(screen.getByText('محتوای اشتراک')).toBeInTheDocument();
});
it('marks the active item with aria-current=page', () => {
renderWithProviders(
<SettingsLayout active="subscription"><div /></SettingsLayout>,
);
const active = screen.getByText('خرید اشتراک').closest('a');
expect(active).toHaveAttribute('aria-current', 'page');
expect(active).toHaveAttribute('href', '/admin/subscription');
});
it('renders not-yet-implemented items as disabled placeholders', () => {
renderWithProviders(
<SettingsLayout active="subscription"><div /></SettingsLayout>,
);
// "حساب کاربری" has no route → disabled button with "به‌زودی"
const account = screen.getByText('حساب کاربری').closest('button');
expect(account).toBeDisabled();
expect(screen.getAllByText('به‌زودی').length).toBeGreaterThan(0);
});
it('filters the menu by the search query', () => {
renderWithProviders(
<SettingsLayout active="subscription"><div /></SettingsLayout>,
);
fireEvent.change(screen.getByLabelText('جستجو در تنظیمات'), { target: { value: 'اشتراک' } });
expect(screen.getByText('خرید اشتراک')).toBeInTheDocument();
expect(screen.queryByText('خدمات')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,140 @@
import React, { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import {
CreditCardIcon, UserIcon, CalendarDaysIcon, BuildingOffice2Icon,
WrenchScrewdriverIcon, BanknotesIcon, UsersIcon, ShieldCheckIcon,
TagIcon, ChatBubbleLeftRightIcon, UserCircleIcon, MagnifyingGlassIcon,
} from '@heroicons/react/24/outline';
// ── Settings menu configuration ─────────────────────────────────────────────
// Single source of truth for the settings sub-navigation (desktop shell +
// mobile list). `to` = an existing admin route; items without `to` are not yet
// implemented and render as disabled placeholders ("به‌زودی").
export type SettingsMenuItem = {
key: string;
label: string;
icon: React.ElementType;
to?: string;
};
export const SETTINGS_MENU: SettingsMenuItem[] = [
{ key: 'subscription', label: 'خرید اشتراک', icon: CreditCardIcon, to: '/admin/subscription' },
{ key: 'doctor', label: 'مدیریت پزشک', icon: UserIcon },
{ key: 'appointment', label: 'مدیریت نوبت دهی', icon: CalendarDaysIcon },
{ key: 'clinic', label: 'مدیریت مطب', icon: BuildingOffice2Icon },
{ key: 'services', label: 'خدمات', icon: WrenchScrewdriverIcon, to: '/admin/clinic-services' },
{ key: 'payment', label: 'مدیریت پرداخت', icon: BanknotesIcon, to: '/admin/my-financial' },
{ key: 'secretary', label: 'مدیریت منشی', icon: UsersIcon, to: '/admin/my-secretaries' },
{ key: 'insurance', label: 'مدیریت بیمه', icon: ShieldCheckIcon, to: '/admin/insurance-pricing' },
{ key: 'tags', label: 'برچسب‌ها', icon: TagIcon },
{ key: 'sms', label: 'پیامک‌ها', icon: ChatBubbleLeftRightIcon, to: '/admin/sms-wallet' },
{ key: 'account', label: 'حساب کاربری', icon: UserCircleIcon },
];
// ── Shared item styling ──────────────────────────────────────────────────────
function itemStyle(active: boolean, disabled: boolean): React.CSSProperties {
return {
display: 'flex', alignItems: 'center', gap: 10,
width: '100%', padding: '11px 14px', borderRadius: 'var(--r-sm)',
fontSize: 14, fontWeight: active ? 700 : 500, textAlign: 'right',
fontFamily: 'inherit', border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
background: active ? 'var(--accent)' : 'transparent',
color: active ? '#fff' : disabled ? 'var(--text-3)' : 'var(--text-2)',
transition: 'background .14s, color .14s',
};
}
function MenuRow({ item, active }: { item: SettingsMenuItem; active: boolean }) {
const Icon = item.icon;
const disabled = !item.to;
const inner = (
<>
<Icon style={{ width: 18, height: 18, flexShrink: 0, opacity: disabled ? 0.6 : 1 }} />
<span style={{ flex: 1 }}>{item.label}</span>
{disabled && <span style={{ fontSize: 10.5, color: 'var(--text-3)' }}>بهزودی</span>}
</>
);
if (disabled) {
return <button type="button" disabled style={itemStyle(false, true)}>{inner}</button>;
}
return (
<Link
to={item.to!}
aria-current={active ? 'page' : undefined}
style={itemStyle(active, false)}
onMouseEnter={(e) => { if (!active) (e.currentTarget as HTMLElement).style.background = 'var(--surface-2)'; }}
onMouseLeave={(e) => { if (!active) (e.currentTarget as HTMLElement).style.background = 'transparent'; }}
>
{inner}
</Link>
);
}
/**
* SettingsLayout — presentational shell for the doctor/clinic settings area.
* Renders a right-hand settings sub-navigation menu (desktop) beside the page
* content. On mobile the menu is hidden (the standalone settings list page owns
* navigation) and the content spans full width.
*
* @param active key of the currently-open settings section (highlighted)
* @param children the section content (e.g. subscription plans)
*/
export default function SettingsLayout({ active, children }: { active: string; children: React.ReactNode }) {
const [query, setQuery] = useState('');
const items = useMemo(
() => SETTINGS_MENU.filter((i) => i.label.includes(query.trim())),
[query],
);
return (
<div className="fade-in" style={{ maxWidth: 1180, margin: '0 auto' }}>
<div className="grid grid-cols-1 lg:grid-cols-[260px_minmax(0,1fr)] gap-5">
{/* Settings sub-nav — desktop only */}
<aside
className="hidden lg:block"
aria-label="منوی تنظیمات"
style={{
background: 'var(--surface)', border: '1px solid var(--border)',
borderRadius: 'var(--r-lg)', padding: 14, alignSelf: 'start',
position: 'sticky', top: 'calc(var(--topbar-h) + 16px)',
}}
>
<h2 className="section-title" style={{ fontSize: 16, marginBottom: 12 }}>تنظیمات</h2>
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
background: 'var(--surface-2)', border: '1px solid var(--border)',
borderRadius: 'var(--r-sm)', padding: '8px 12px', marginBottom: 12,
}}>
<MagnifyingGlassIcon style={{ width: 16, color: 'var(--text-3)', flexShrink: 0 }} />
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="جستجو در تنظیمات"
aria-label="جستجو در تنظیمات"
style={{
border: 'none', outline: 'none', background: 'transparent',
fontFamily: 'inherit', fontSize: 13, color: 'var(--text)', width: '100%',
}}
/>
</div>
<nav style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{items.map((item) => (
<MenuRow key={item.key} item={item} active={item.key === active} />
))}
{items.length === 0 && (
<div style={{ padding: '12px 4px', fontSize: 13, color: 'var(--text-3)', textAlign: 'center' }}>
موردی یافت نشد
</div>
)}
</nav>
</aside>
{/* Section content */}
<div style={{ minWidth: 0 }}>{children}</div>
</div>
</div>
);
}
@@ -0,0 +1,60 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';
const navSpy = vi.fn();
vi.mock('react-router-dom', async (orig) => ({
...(await orig<typeof import('react-router-dom')>()),
useNavigate: () => navSpy,
}));
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../lib/api', () => ({
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
ApiError: class extends Error {},
}));
import { api } from '../lib/api';
import { toast } from 'sonner';
import PaymentSuccessPage from './PaymentSuccessPage';
const get = api.get as ReturnType<typeof vi.fn>;
beforeEach(() => {
get.mockReset();
navSpy.mockReset();
(toast.error as ReturnType<typeof vi.fn>).mockReset();
get.mockImplementation((url: string) => {
if (url.includes('/payment/')) return Promise.resolve({ success: true, data: {
uuid: 'pay-1', order_id: 'ORD1', amount_rials: 9000000, status: 'success',
gateway: 'mellat', reference_id: '987654', created_at: 1700000000,
} });
if (url.includes('/subscription/my')) return Promise.resolve({ success: true, data: {
subscription: {
plan: { name: 'professional', level: 2, max_secretaries: 10, features: { patient_records: true, sms_panel: true } },
period: { label: 'یک ساله', duration_months: 12 },
is_trial: false, expires_at: 1710000000, days_remaining: 300,
},
used_trial: true, effective_plan: null,
} });
return Promise.resolve({ success: true, data: null });
});
});
describe('PaymentSuccessPage', () => {
it('shows the receipt and purchased plan on success', async () => {
renderWithProviders(<PaymentSuccessPage />, { route: '/admin/subscription/success?payment_uuid=pay-1&status=success' });
expect(await screen.findByText('پرداخت شما با موفقیت انجام شد!')).toBeInTheDocument();
expect(await screen.findByText('987654')).toBeInTheDocument(); // شماره تراکنش (reference_id)
expect(await screen.findByText('پلن حرفه‌ای')).toBeInTheDocument(); // purchased plan
expect(await screen.findByText('پرونده بیمار')).toBeInTheDocument(); // feature label
expect(navSpy).not.toHaveBeenCalled();
});
it('redirects to the plans page with an error toast on non-success status', () => {
renderWithProviders(<PaymentSuccessPage />, { route: '/admin/subscription/success?payment_uuid=pay-1&status=failed' });
expect(navSpy).toHaveBeenCalledWith('/admin/subscription', { replace: true });
expect(toast.error).toHaveBeenCalled();
});
});
+163
View File
@@ -0,0 +1,163 @@
import React, { useEffect } from 'react';
import { useSearchParams, useNavigate, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { CheckBadgeIcon, SparklesIcon, CalendarDaysIcon, CreditCardIcon, ArrowLeftIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { MySubscriptionData } from '../types';
import { formatRial, formatDate } from '../lib/utils';
import { PLAN_FEATURE_LABELS, planMetaOf } from './SubscriptionPage';
interface PaymentDetails {
uuid: string;
order_id: string;
amount_rials: number;
status: string;
gateway: string;
reference_id: string | null;
created_at: number;
}
/**
* PaymentSuccessPage — landing shown when the payment gateway redirects back
* after a subscription purchase (frontend_address + ?payment_uuid&status).
* On success it shows the transaction receipt and the newly-active plan; any
* non-success status redirects back to the plans page with an error toast.
*/
export default function PaymentSuccessPage() {
const [params] = useSearchParams();
const navigate = useNavigate();
const paymentUuid = params.get('payment_uuid') ?? '';
const status = params.get('status') ?? '';
const isSuccess = status === 'success';
useEffect(() => {
if (!isSuccess) {
toast.error('پرداخت انجام نشد یا لغو شد');
navigate('/admin/subscription', { replace: true });
}
}, [isSuccess, navigate]);
const { data: payData, isLoading: payLoading } = useQuery<ApiResponse<PaymentDetails>>({
queryKey: ['payment', paymentUuid],
queryFn: () => api.get(`/api/v1/payment/${paymentUuid}`),
enabled: isSuccess && paymentUuid !== '',
});
const { data: myData } = useQuery<ApiResponse<MySubscriptionData>>({
queryKey: ['subscription-my'],
queryFn: () => api.get('/api/v1/subscription/my'),
enabled: isSuccess,
});
if (!isSuccess) return null;
const payment = payData?.data ?? null;
const sub = myData?.data?.subscription ?? null;
const meta = sub ? planMetaOf(sub.plan.name) : null;
const months = sub?.period?.duration_months ?? 0;
return (
<div className="fade-in" style={{ maxWidth: 860, margin: '0 auto', padding: '8px 0 40px' }}>
{/* ── Success header ── */}
<div style={{ textAlign: 'center', marginBottom: 24 }}>
<div style={{
width: 72, height: 72, borderRadius: '50%', margin: '0 auto 16px',
background: 'var(--success-bg)', display: 'grid', placeItems: 'center',
}}>
<CheckBadgeIcon style={{ width: 40, color: 'var(--success)' }} />
</div>
<h1 style={{ fontSize: 22, fontWeight: 800, color: 'var(--text)', margin: 0 }}>
پرداخت شما با موفقیت انجام شد!
</h1>
</div>
{/* ── Transaction receipt ── */}
<div style={{
border: '1px solid var(--border)', borderRadius: 'var(--r-lg)',
padding: '18px 22px', marginBottom: 28,
display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 16,
}}>
<Receipt label="شماره تراکنش" value={payment?.reference_id ?? payment?.order_id ?? '—'} loading={payLoading} />
<Receipt label="تاریخ پرداخت" value={payment ? formatDate(payment.created_at) : '—'} loading={payLoading} center />
<Receipt label="مبلغ پرداخت شده" value={payment ? formatRial(payment.amount_rials) : '—'} loading={payLoading} left />
</div>
{/* ── Purchased plan ── */}
<h2 style={{ textAlign: 'center', fontSize: 17, fontWeight: 800, color: 'var(--accent)', marginBottom: 16 }}>
پلن خریداری شده شما:
</h2>
{sub && meta && (
<div style={{
background: 'var(--primary-soft)', border: '1.5px solid var(--primary)',
borderRadius: 'var(--r-lg)', padding: 24,
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginBottom: 8 }}>
<SparklesIcon style={{ width: 18, color: 'var(--accent)' }} />
<span style={{ fontWeight: 800, fontSize: 19, color: 'var(--text)' }}>پلن {meta.label}</span>
<SparklesIcon style={{ width: 18, color: 'var(--accent)' }} />
</div>
<div style={{ textAlign: 'center', fontSize: 13.5, color: 'var(--text-2)', marginBottom: 18 }}>{meta.desc}</div>
<div style={{
display: 'flex', justifyContent: 'center', gap: 28, flexWrap: 'wrap',
paddingBottom: 18, borderBottom: '1px solid var(--border)', marginBottom: 18,
}}>
{payment && months > 0 && (
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13.5, color: 'var(--text-2)' }}>
<CreditCardIcon style={{ width: 16, color: 'var(--text-3)' }} />
هزینه ماهیانه: <b style={{ color: 'var(--text)' }}>{formatRial(Math.round(payment.amount_rials / months))}</b>
</span>
)}
{sub.expires_at && (
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13.5, color: 'var(--text-2)' }}>
<CalendarDaysIcon style={{ width: 16, color: 'var(--text-3)' }} />
تاریخ انقضا: <b style={{ color: 'var(--text)' }}>{formatDate(sub.expires_at)}</b>
</span>
)}
</div>
<div style={{ textAlign: 'center', fontWeight: 700, fontSize: 14, color: 'var(--text)', marginBottom: 14 }}>امکانات</div>
<ul style={{
listStyle: 'none', padding: 0, margin: '0 auto', maxWidth: 520,
display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 10,
}}>
{Object.entries(sub.plan.features).filter(([, v]) => v).map(([key]) => (
<li key={key} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5, color: 'var(--text)' }}>
<span style={{
width: 20, height: 20, borderRadius: 6, flexShrink: 0,
display: 'grid', placeItems: 'center', background: 'var(--surface)', border: '1px solid var(--primary)',
}}>
<CheckBadgeIcon style={{ width: 13, color: 'var(--primary)' }} />
</span>
{PLAN_FEATURE_LABELS[key] ?? key}
</li>
))}
</ul>
</div>
)}
{/* ── Back ── */}
<div style={{ marginTop: 28 }}>
<Link to="/admin/subscription" className="btn primary" style={{ height: 46, padding: '0 22px' }}>
<ArrowLeftIcon style={{ width: 18 }} />
صفحه اشتراکها
</Link>
</div>
</div>
);
}
function Receipt({ label, value, loading, center, left }: { label: string; value: string; loading?: boolean; center?: boolean; left?: boolean }) {
return (
<div style={{ textAlign: center ? 'center' : left ? 'left' : 'right' }}>
<div style={{ fontSize: 12.5, color: 'var(--text-3)', marginBottom: 6 }}>{label}</div>
{loading
? <div className="skeleton" style={{ height: 18, width: 90, borderRadius: 6, display: 'inline-block' }} />
: <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)' }}>{value}</div>}
</div>
);
}
@@ -0,0 +1,22 @@
import { describe, it, expect } from 'vitest';
import { screen } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';
import SettingsMenuPage from './SettingsMenuPage';
import { SETTINGS_MENU } from '../components/layout/SettingsLayout';
describe('SettingsMenuPage', () => {
it('lists every settings section', () => {
renderWithProviders(<SettingsMenuPage />);
for (const item of SETTINGS_MENU) {
expect(screen.getByText(item.label)).toBeInTheDocument();
}
});
it('links implemented sections and disables the rest', () => {
renderWithProviders(<SettingsMenuPage />);
// implemented → anchor with href
expect(screen.getByText('خرید اشتراک').closest('a')).toHaveAttribute('href', '/admin/subscription');
// not implemented → disabled button
expect(screen.getByText('مدیریت پزشک').closest('button')).toBeDisabled();
});
});
+61
View File
@@ -0,0 +1,61 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { ChevronLeftIcon } from '@heroicons/react/24/outline';
import { SETTINGS_MENU } from '../components/layout/SettingsLayout';
/**
* SettingsMenuPage — the settings landing list for doctor/clinic users.
* A full-width tappable list of settings sections (mobile-first, matches the
* Figma mobile design). Implemented sections link to their route; the rest
* render as disabled rows labelled "به‌زودی". On desktop the same list is shown;
* each section itself renders the desktop shell via SettingsLayout.
*/
export default function SettingsMenuPage() {
return (
<div className="fade-in" style={{ maxWidth: 720, margin: '0 auto' }}>
<h1 className="section-title" style={{ marginBottom: 16 }}>تنظیمات</h1>
<div style={{
background: 'var(--surface)', border: '1px solid var(--border)',
borderRadius: 'var(--r-lg)', overflow: 'hidden',
}}>
{SETTINGS_MENU.map((item, idx) => {
const Icon = item.icon;
const disabled = !item.to;
const rowStyle: React.CSSProperties = {
display: 'flex', alignItems: 'center', gap: 12,
padding: '16px 18px', fontSize: 15, fontFamily: 'inherit',
borderTop: idx === 0 ? 'none' : '1px solid var(--border)',
color: disabled ? 'var(--text-3)' : 'var(--text)',
cursor: disabled ? 'not-allowed' : 'pointer',
background: 'transparent', width: '100%', textAlign: 'right',
};
const inner = (
<>
<Icon style={{ width: 20, height: 20, flexShrink: 0, color: disabled ? 'var(--text-3)' : 'var(--primary)' }} />
<span style={{ flex: 1, fontWeight: 600 }}>{item.label}</span>
{disabled
? <span style={{ fontSize: 11, color: 'var(--text-3)' }}>بهزودی</span>
: <ChevronLeftIcon style={{ width: 18, color: 'var(--text-3)', flexShrink: 0 }} />}
</>
);
return disabled ? (
<button key={item.key} type="button" disabled style={{ ...rowStyle, border: 'none', borderTop: rowStyle.borderTop }}>
{inner}
</button>
) : (
<Link
key={item.key}
to={item.to!}
style={rowStyle}
onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.background = 'var(--surface-2)'; }}
onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.background = 'transparent'; }}
>
{inner}
</Link>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,77 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent, within } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';
import { formatRial } from '../lib/utils';
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../lib/api', () => ({
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
ApiError: class extends Error {},
}));
import { api } from '../lib/api';
import SubscriptionPage from './SubscriptionPage';
const get = api.get as ReturnType<typeof vi.fn>;
const PLANS = [
{ uuid: 'p-free', name: 'free', level: 0, max_secretaries: 1,
features: { patient_records: false, services: false, sms_panel: false }, active: true, periods: [] },
{ uuid: 'p-basic', name: 'basic', level: 1, max_secretaries: 3,
features: { patient_records: true, services: true, sms_panel: false }, active: true,
periods: [
{ uuid: 'per-1m', label: 'یک ماهه', duration_months: 1, price_rials: 1000000, is_trial: false },
{ uuid: 'per-12m', label: 'یک ساله', duration_months: 12, price_rials: 9000000, is_trial: false },
] },
{ uuid: 'p-pro', name: 'professional', level: 2, max_secretaries: 10,
features: { patient_records: true, services: true, sms_panel: true }, active: true, periods: [] },
];
function mockApi(overrides: Partial<Record<string, any>> = {}) {
get.mockImplementation((url: string) => {
if (url.includes('/subscription/plans')) return Promise.resolve({ success: true, data: PLANS });
if (url.includes('/subscription/my')) return Promise.resolve({ success: true, data: overrides.my ?? {
subscription: { plan: { name: 'basic', level: 1, max_secretaries: 3, features: {} }, is_trial: false, days_remaining: 25 },
used_trial: true, effective_plan: null,
} });
if (url.includes('/payment/config')) return Promise.resolve({ success: true, data: { test_mode: true, appointment_fee_rials: 0, gateways: [] } });
return Promise.resolve({ success: true, data: null });
});
}
beforeEach(() => { get.mockReset(); mockApi(); });
describe('SubscriptionPage', () => {
it('renders the three plans with the most-popular badge on the basic plan', async () => {
renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
expect(await screen.findByText('پلن پایه')).toBeInTheDocument();
expect(screen.getByText('پلن رایگان')).toBeInTheDocument();
expect(screen.getByText('پلن حرفه‌ای')).toBeInTheDocument();
expect(screen.getByText('محبوب‌ترین')).toBeInTheDocument();
});
it('shows the current-plan banner with days remaining', async () => {
renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
expect(await screen.findByText(/پلن فعلی شما/)).toBeInTheDocument();
expect(screen.getByText(/روز تا پایان اشتراک/)).toBeInTheDocument();
});
it('the period toggle switches the displayed price', async () => {
renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
const basicCard = (await screen.findByText('پلن پایه')).closest('div')!.parentElement!.parentElement!;
const card = within(basicCard);
// default = longest period (یک ساله)
expect(card.getByText(formatRial(9000000))).toBeInTheDocument();
// switch to monthly
fireEvent.click(card.getByRole('tab', { name: 'یک ماهه' }));
expect(card.getByText(formatRial(1000000))).toBeInTheDocument();
});
it('clicking the buy button opens the payment modal with the selected amount', async () => {
renderWithProviders(<SubscriptionPage />, { route: '/admin/subscription' });
// basic is the current plan → button reads "تمدید اشتراک"
fireEvent.click(await screen.findByText('تمدید اشتراک'));
expect(await screen.findByText('پرداخت اشتراک')).toBeInTheDocument();
expect(screen.getByText('درگاه آزمایشی فعال است')).toBeInTheDocument();
});
});
+226 -370
View File
@@ -1,47 +1,38 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import {
CheckIcon, XMarkIcon, SparklesIcon, RocketLaunchIcon,
ShieldCheckIcon, CreditCardIcon, ClockIcon, ArrowPathIcon,
CheckIcon, XMarkIcon, SparklesIcon, UserIcon,
CreditCardIcon, ClockIcon, ArrowPathIcon, GiftIcon,
} from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { SubscriptionPlan, MySubscriptionData, SubscriptionPeriod } from '../types';
import { usePaymentConfig } from '../hooks/usePaymentConfig';
import { formatDate, formatRial, formatNumber } from '../lib/utils';
import { formatRial, formatNumber } from '../lib/utils';
import Modal from '../components/ui/Modal';
import SettingsLayout from '../components/layout/SettingsLayout';
// ── Constants ─────────────────────────────────────────────────────────────
const PLAN_FEATURE_LABELS: Record<string, string> = {
export const PLAN_FEATURE_LABELS: Record<string, string> = {
patient_records: 'پرونده بیمار',
services: 'مدیریت سرویس‌ها',
sms_panel: 'پنل پیامک',
};
const PLAN_META: Record<string, {
label: string; desc: string;
color: string; bg: string; border: string;
icon: React.ElementType;
}> = {
free: {
label: 'رایگان', desc: 'برای شروع کار با سیستم',
color: 'var(--text-2)', bg: 'var(--surface-2)', border: 'var(--border)',
icon: ShieldCheckIcon,
},
basic: {
label: 'پایه', desc: 'برای مطب‌های کوچک و متوسط',
color: 'var(--info)', bg: 'var(--info-bg)', border: 'color-mix(in oklch, var(--info) 40%, transparent)',
icon: RocketLaunchIcon,
},
professional: {
label: 'حرفه‌ای', desc: 'برای کلینیک‌های بزرگ',
color: 'var(--violet)', bg: 'var(--violet-bg)', border: 'color-mix(in oklch, var(--violet) 40%, transparent)',
icon: SparklesIcon,
},
/** The plan highlighted as "most popular" in the UI (no backend flag exists). */
const POPULAR_PLAN_NAME = 'basic';
const PLAN_META: Record<string, { label: string; desc: string; tint: string }> = {
free: { label: 'رایگان', desc: 'مناسب برای شروع کار', tint: 'var(--surface-2)' },
basic: { label: 'پایه', desc: 'مناسب برای مطب‌های کوچک و متوسط', tint: 'var(--primary-soft)' },
professional: { label: 'حرفه‌ای', desc: 'مناسب برای کلینیک‌های بزرگ', tint: 'var(--violet-bg)' },
};
export const planMetaOf = (name: string) => PLAN_META[name] ?? PLAN_META.free;
// ── Main Page ─────────────────────────────────────────────────────────────
export default function SubscriptionPage() {
@@ -67,10 +58,11 @@ export default function SubscriptionPage() {
}
}, [gateways, selectedGateway]);
const plans = plansData?.data ?? [];
const myRaw = myData?.data;
const my = myRaw?.subscription ?? null;
const usedTrial = myRaw?.used_trial ?? false;
// Highest plan first so, under RTL, the top-tier plan sits on the right (Figma order).
const plans = [...(plansData?.data ?? [])].sort((a, b) => b.level - a.level);
const myRaw = myData?.data;
const my = myRaw?.subscription ?? null;
const usedTrial = myRaw?.used_trial ?? false;
const trialMutation = useMutation({
mutationFn: () => api.post('/api/v1/subscription/trial', {}),
@@ -83,9 +75,10 @@ export default function SubscriptionPage() {
const purchaseMutation = useMutation({
mutationFn: ({ period_uuid, gateway, amount_rials }: { period_uuid: string; gateway: string; amount_rials: number }) =>
api.post<{ data: { payment_url: string } }>('/api/v1/subscription-payment', {
api.post<{ data: { pay_url?: string; redirect_url?: string; payment_url?: string } }>('/api/v1/subscription-payment', {
period_uuid, gateway, amount_rials,
frontend_address: `${window.location.origin}/admin/subscription`,
// Gateway returns here (with ?payment_uuid&status); the success page reads them.
frontend_address: `${window.location.origin}/admin/subscription/success`,
}),
onSuccess: (res: any) => {
const url = res?.data?.pay_url ?? res?.data?.redirect_url ?? res?.data?.payment_url;
@@ -95,162 +88,30 @@ export default function SubscriptionPage() {
onError: (err: any) => toast.error(err.message),
});
const daysTotal = my?.expires_at && my?.starts_at ? Math.round((my.expires_at - my.starts_at) / 86400) : null;
const daysLeft = my?.days_remaining ?? 0;
const daysProgress = daysTotal ? Math.max(0, Math.min(100, ((daysTotal - daysLeft) / daysTotal) * 100)) : null;
const planMeta = my ? (PLAN_META[my.plan.name] ?? PLAN_META.free) : null;
const isExpiringSoon = daysLeft > 0 && daysLeft <= 7;
return (
<div className="fade-in" style={{ maxWidth: 980, margin: '0 auto' }}>
<SettingsLayout active="subscription">
{/* ── Header ── */}
<div style={{ marginBottom: 28 }}>
<h1 className="section-title" style={{ marginBottom: 4 }}>پنل اشتراکی</h1>
<div style={{ marginBottom: 20 }}>
<h1 className="section-title" style={{ marginBottom: 4 }}>انتخاب پلن اشتراک</h1>
<p style={{ color: 'var(--text-3)', fontSize: 14, margin: 0 }}>
پنل خود را انتخاب کنید و از امکانات بیشتر بهرهمند شوید
پلن اشتراک مناسب خود را انتخاب نمایید:
</p>
</div>
{/* ── وضعیت فعلی ── */}
{!myLoading && my && (
<div style={{
background: `linear-gradient(135deg, ${planMeta!.bg} 0%, var(--surface) 100%)`,
border: `1.5px solid ${planMeta!.border}`,
borderRadius: 'var(--r-lg)',
padding: '22px 24px',
marginBottom: 28,
position: 'relative',
overflow: 'hidden',
}}>
{/* decorative circle */}
<div style={{
position: 'absolute', left: -40, top: -40,
width: 180, height: 180, borderRadius: '50%',
background: planMeta!.color, opacity: 0.06, pointerEvents: 'none',
}} />
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
{/* icon */}
<div style={{
width: 52, height: 52, borderRadius: 14, flexShrink: 0,
background: planMeta!.color, color: '#fff',
display: 'grid', placeItems: 'center',
boxShadow: `0 6px 18px ${planMeta!.color}44`,
}}>
{planMeta && <planMeta.icon style={{ width: 26, height: 26 }} />}
</div>
{/* info */}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 4 }}>
<span style={{ fontWeight: 800, fontSize: 18, color: 'var(--text)' }}>
پنل {planMeta!.label}
</span>
{my.is_trial && (
<span className="badge amber" style={{ fontSize: 11 }}>
<span className="bdot" />تریال
</span>
)}
{isExpiringSoon && (
<span className="badge red" style={{ fontSize: 11 }}>
<span className="bdot" />در حال انقضا
</span>
)}
</div>
{my.expires_at ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--text-2)' }}>
<ClockIcon style={{ width: 14, flexShrink: 0 }} />
انقضا {formatDate(my.expires_at)}
<span style={{
marginRight: 4, fontWeight: 700,
color: isExpiringSoon ? 'var(--danger)' : planMeta!.color,
}}>
({formatNumber(daysLeft)} روز مانده)
</span>
</div>
) : (
<div style={{ fontSize: 13, color: 'var(--text-3)' }}>بدون تاریخ انقضا</div>
)}
{/* progress bar */}
{daysProgress !== null && (
<div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
<div style={{ flex: 1, height: 7, background: 'var(--border)', borderRadius: 99, overflow: 'hidden' }}>
<div style={{
width: `${daysProgress}%`, height: '100%', borderRadius: 99,
background: isExpiringSoon
? 'var(--danger)'
: `linear-gradient(90deg, ${planMeta!.color}, ${planMeta!.color}cc)`,
transition: 'width .6s cubic-bezier(.22,.61,.36,1)',
}} />
</div>
<span style={{ fontSize: 11.5, color: 'var(--text-3)', flexShrink: 0 }}>
{Math.round(daysProgress)}% گذشته
</span>
</div>
)}
</div>
{/* trial CTA */}
{!usedTrial && (
<button
className="btn primary sm"
style={{ flexShrink: 0, alignSelf: 'flex-start', marginTop: 4 }}
onClick={() => trialMutation.mutate()}
disabled={trialMutation.isPending}
>
{trialMutation.isPending
? <><ArrowPathIcon style={{ width: 14, animation: 'spin 1s linear infinite' }} /> در حال فعالسازی...</>
: '🎁 فعال‌سازی تریال رایگان'
}
</button>
)}
</div>
</div>
)}
{/* ── بنر تریال (اگر هنوز استفاده نشده و اشتراکی ندارد) ── */}
{!myLoading && !my && !usedTrial && (
<div style={{
background: 'linear-gradient(135deg, var(--info-bg), var(--violet-bg))',
border: '1.5px dashed color-mix(in oklch, var(--info) 50%, transparent)',
borderRadius: 'var(--r-lg)',
padding: '18px 22px',
marginBottom: 24,
display: 'flex', alignItems: 'center', gap: 14,
}}>
<SparklesIcon style={{ width: 28, color: 'var(--info)', flexShrink: 0 }} />
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 700, fontSize: 15, color: 'var(--text)', marginBottom: 2 }}>
یک ماه تریال رایگان دارید!
</div>
<div style={{ fontSize: 13, color: 'var(--text-3)' }}>
پنل پایه را به مدت یک ماه رایگان امتحان کنید
</div>
</div>
<button
className="btn primary sm"
onClick={() => trialMutation.mutate()}
disabled={trialMutation.isPending}
>
فعالسازی تریال
</button>
</div>
)}
{/* ── وضعیت پلن فعلی ── */}
{!myLoading && <CurrentPlanBanner my={my} />}
{/* ── کارت‌های پلن ── */}
{plansLoading ? (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 16 }}>
{[1, 2, 3].map((i) => (
<div key={i} className="card" style={{ height: 320 }}>
<div key={i} className="card" style={{ height: 420 }}>
<div className="skeleton" style={{ height: '100%', borderRadius: 'var(--r)' }} />
</div>
))}
</div>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 16 }}>
{plans.map((plan) => (
<PlanCard
key={plan.uuid}
@@ -267,29 +128,15 @@ export default function SubscriptionPage() {
</div>
)}
{/* ── فوتر راهنما ── */}
<div style={{
marginTop: 32, padding: '16px 20px',
background: 'var(--surface-2)', borderRadius: 'var(--r)',
border: '1px solid var(--border)',
display: 'flex', gap: 24, flexWrap: 'wrap',
fontSize: 12.5, color: 'var(--text-3)',
}}>
<span>🔒 پرداخت امن از طریق درگاههای معتبر</span>
<span>🔄 تمدید از تاریخ انقضای قبلی محاسبه میشود</span>
<span>📦 دادهها پس از انقضا حفظ میشوند</span>
</div>
{/* ── Modal پرداخت ── */}
{/* ── Modal پرداخت (انتخاب درگاه) ── */}
<Modal
open={!!purchaseTarget}
onClose={() => { setPurchaseTarget(null); setSelectedGateway('mellat'); }}
onClose={() => { setPurchaseTarget(null); setSelectedGateway(gateways[0]?.name ?? ''); }}
title="پرداخت اشتراک"
size="sm"
>
{purchaseTarget && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
{/* خلاصه خرید */}
<div style={{
background: 'var(--surface-2)', borderRadius: 'var(--r-sm)',
padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
@@ -297,7 +144,7 @@ export default function SubscriptionPage() {
<div>
<div style={{ fontSize: 13, color: 'var(--text-3)', marginBottom: 2 }}>دوره انتخابی</div>
<div style={{ fontWeight: 700, fontSize: 15 }}>
{PLAN_META[purchaseTarget.planName]?.label ?? purchaseTarget.planName} {purchaseTarget.period.label}
{planMetaOf(purchaseTarget.planName).label} {purchaseTarget.period.label}
</div>
<div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 1 }}>
{purchaseTarget.period.duration_months} ماه
@@ -311,14 +158,10 @@ export default function SubscriptionPage() {
</div>
</div>
{/* انتخاب درگاه */}
{isTestMode ? (
<div style={{
background: 'var(--warning-bg)',
border: '1px solid var(--warning)',
borderRadius: 10,
padding: '12px 16px',
display: 'flex', alignItems: 'center', gap: 10,
background: 'var(--warning-bg)', border: '1px solid var(--warning)',
borderRadius: 10, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10,
}}>
<span style={{ fontSize: 20 }}></span>
<div>
@@ -326,44 +169,41 @@ export default function SubscriptionPage() {
<div style={{ fontSize: 12, color: 'var(--warning)', marginTop: 2, opacity: 0.8 }}>پول واقعی کسر نخواهد شد این تراکنش آزمایشی است</div>
</div>
</div>
) : gateways.length === 0 ? (
<div style={{
background: 'var(--danger-bg)', border: '1px solid var(--danger)',
borderRadius: 10, padding: '12px 16px', fontSize: 13, color: 'var(--danger)',
}}>
در حال حاضر هیچ درگاه پرداخت فعالی وجود ندارد. لطفاً با پشتیبانی تماس بگیرید.
</div>
) : (
gateways.length === 0 ? (
<div style={{
background: 'var(--danger-bg)', border: '1px solid var(--danger)',
borderRadius: 10, padding: '12px 16px', fontSize: 13, color: 'var(--danger)',
}}>
در حال حاضر هیچ درگاه پرداخت فعالی وجود ندارد. لطفاً با پشتیبانی تماس بگیرید.
<div>
<div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', marginBottom: 10 }}>
انتخاب درگاه پرداخت
</div>
) : (
<div>
<div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-2)', marginBottom: 10 }}>
انتخاب درگاه پرداخت
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
{gateways.map((gw) => (
<button
key={gw.name}
onClick={() => setSelectedGateway(gw.name)}
style={{
padding: '12px 16px', borderRadius: 'var(--r-sm)', cursor: 'pointer',
border: `2px solid ${selectedGateway === gw.name ? 'var(--primary)' : 'var(--border)'}`,
background: selectedGateway === gw.name ? 'var(--primary-soft)' : 'var(--surface)',
color: selectedGateway === gw.name ? 'var(--primary-700)' : 'var(--text-2)',
fontWeight: selectedGateway === gw.name ? 700 : 500,
fontSize: 13, transition: '.14s', fontFamily: 'inherit',
display: 'flex', alignItems: 'center', gap: 8,
}}
>
<CreditCardIcon style={{ width: 17, flexShrink: 0 }} />
{gw.label}
</button>
))}
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
{gateways.map((gw) => (
<button
key={gw.name}
onClick={() => setSelectedGateway(gw.name)}
style={{
padding: '12px 16px', borderRadius: 'var(--r-sm)', cursor: 'pointer',
border: `2px solid ${selectedGateway === gw.name ? 'var(--primary)' : 'var(--border)'}`,
background: selectedGateway === gw.name ? 'var(--primary-soft)' : 'var(--surface)',
color: selectedGateway === gw.name ? 'var(--primary-700)' : 'var(--text-2)',
fontWeight: selectedGateway === gw.name ? 700 : 500,
fontSize: 13, transition: '.14s', fontFamily: 'inherit',
display: 'flex', alignItems: 'center', gap: 8,
}}
>
<CreditCardIcon style={{ width: 17, flexShrink: 0 }} />
{gw.label}
</button>
))}
</div>
)
</div>
)}
{/* دکمه‌ها */}
<div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
<button
className="btn primary"
@@ -375,10 +215,7 @@ export default function SubscriptionPage() {
>
{purchaseMutation.isPending
? 'در حال انتقال...'
: isTestMode
? `پرداخت آزمایشی ${formatRial(purchaseTarget.period.price_rials)}`
: `پرداخت ${formatRial(purchaseTarget.period.price_rials)}`
}
: `پرداخت ${formatRial(purchaseTarget.period.price_rials)}`}
</button>
<button className="btn ghost" style={{ height: 44 }} onClick={() => setPurchaseTarget(null)}>
انصراف
@@ -387,6 +224,41 @@ export default function SubscriptionPage() {
</div>
)}
</Modal>
</SettingsLayout>
);
}
// ── Current plan banner ─────────────────────────────────────────────────────
function CurrentPlanBanner({ my }: { my: MySubscriptionData['subscription'] }) {
if (!my) return null;
const meta = planMetaOf(my.plan.name);
const daysLeft = my.days_remaining ?? 0;
const expiring = daysLeft > 0 && daysLeft <= 7;
return (
<div style={{
display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap',
background: 'var(--surface)', border: '1px solid var(--border)',
borderRadius: 'var(--r-lg)', padding: '14px 18px', marginBottom: 20,
}}>
<div style={{ flex: 1, minWidth: 180 }}>
<div style={{ fontSize: 13, color: 'var(--text-3)', marginBottom: 2 }}>
پلن فعلی شما: <b style={{ color: 'var(--text)' }}>{meta.label}</b>
{my.is_trial && <span className="badge amber" style={{ marginRight: 8, fontSize: 11 }}><span className="bdot" />تریال</span>}
</div>
{daysLeft > 0 ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: expiring ? 'var(--danger)' : 'var(--success)', fontWeight: 600 }}>
<ClockIcon style={{ width: 14, flexShrink: 0 }} />
{formatNumber(daysLeft)} روز تا پایان اشتراک
</div>
) : (
<div style={{ fontSize: 13, color: 'var(--text-3)' }}>اشتراک فعالی ندارید</div>
)}
</div>
<Link to="/admin/my-financial" className="btn ghost sm" style={{ flexShrink: 0 }}>
مشاهده فاکتور
</Link>
</div>
);
}
@@ -394,14 +266,8 @@ export default function SubscriptionPage() {
// ── PlanCard ──────────────────────────────────────────────────────────────
function PlanCard({
plan,
currentPlanName,
currentPlanLevel,
currentPlanActive,
usedTrial,
onPurchase,
onTrial,
trialPending,
plan, currentPlanName, currentPlanLevel, currentPlanActive,
usedTrial, onPurchase, onTrial, trialPending,
}: {
plan: SubscriptionPlan;
currentPlanName: string;
@@ -412,80 +278,109 @@ function PlanCard({
onTrial: () => void;
trialPending: boolean;
}) {
const meta = PLAN_META[plan.name] ?? PLAN_META.free;
const meta = planMetaOf(plan.name);
const isCurrent = plan.name === currentPlanName;
const isPopular = plan.name === POPULAR_PLAN_NAME;
const isDowngrade = currentPlanActive && (plan.level ?? 0) < currentPlanLevel;
const paidPeriods = plan.periods.filter((p) => !p.is_trial);
const paidPeriods = useMemo(
() => [...plan.periods].filter((p) => !p.is_trial).sort((a, b) => a.duration_months - b.duration_months),
[plan.periods],
);
const trialPeriod = plan.periods.find((p) => p.is_trial);
const Icon = meta.icon;
// Default to the longest (best-value) period, matching the Figma default.
const [selectedUuid, setSelectedUuid] = useState<string>('');
useEffect(() => {
if (paidPeriods.length > 0 && !paidPeriods.some((p) => p.uuid === selectedUuid)) {
setSelectedUuid(paidPeriods[paidPeriods.length - 1].uuid);
}
}, [paidPeriods, selectedUuid]);
const selectedPeriod = paidPeriods.find((p) => p.uuid === selectedUuid) ?? paidPeriods[0];
const accent = isPopular ? 'var(--primary)' : 'var(--border-2)';
return (
<div style={{
background: 'var(--surface)',
border: `${isCurrent ? '2px' : '1.5px'} solid ${isCurrent ? meta.color : 'var(--border)'}`,
border: `${isPopular || isCurrent ? '2px' : '1.5px'} solid ${isPopular ? 'var(--primary)' : isCurrent ? 'var(--primary)' : 'var(--border)'}`,
borderRadius: 'var(--r-lg)',
display: 'flex', flexDirection: 'column',
position: 'relative', overflow: 'hidden',
transition: 'box-shadow .2s, transform .2s',
}}
onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.boxShadow = 'var(--shadow)'; (e.currentTarget as HTMLElement).style.transform = 'translateY(-3px)'; }}
onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.boxShadow = ''; (e.currentTarget as HTMLElement).style.transform = ''; }}
>
{/* توپ تزئینی */}
<div style={{
position: 'absolute', right: -30, top: -30,
width: 120, height: 120, borderRadius: '50%',
background: meta.color, opacity: 0.07, pointerEvents: 'none',
}} />
{/* سربرگ کارت */}
<div style={{
padding: '20px 20px 16px',
borderBottom: '1px solid var(--border)',
position: 'relative',
}}>
{isCurrent && (
<span style={{
position: 'absolute', top: 14, left: 14,
background: meta.color, color: '#fff',
fontSize: 10.5, fontWeight: 700, padding: '3px 9px',
borderRadius: 999,
}}>
پنل فعلی
</span>
)}
<div style={{
width: 42, height: 42, borderRadius: 12, marginBottom: 12,
background: meta.bg, color: meta.color,
display: 'grid', placeItems: 'center',
border: `1.5px solid ${meta.border}`,
}}>
{/* بج محبوب‌ترین */}
{isPopular && (
<span style={{
position: 'absolute', top: 14, left: 14, zIndex: 1,
background: 'var(--primary)', color: '#fff',
fontSize: 11, fontWeight: 700, padding: '4px 10px',
borderRadius: 999, display: 'inline-flex', alignItems: 'center', gap: 5,
}}>
<Icon style={{ width: 22, height: 22 }} />
</div>
<SparklesIcon style={{ width: 13, height: 13 }} />
محبوبترین
</span>
)}
<div style={{ fontWeight: 800, fontSize: 19, color: meta.color, marginBottom: 3 }}>
{meta.label}
</div>
<div style={{ fontSize: 12.5, color: 'var(--text-3)', marginBottom: 10 }}>
{meta.desc}
{/* سربرگ */}
<div style={{ padding: '20px 20px 16px', background: meta.tint }}>
<div style={{ fontWeight: 800, fontSize: 20, color: 'var(--text)', marginBottom: 4 }}>
پلن {meta.label}
</div>
<div style={{ fontSize: 13, color: 'var(--text-2)', marginBottom: 12 }}>{meta.desc}</div>
<div style={{
display: 'inline-flex', alignItems: 'center', gap: 5,
background: 'var(--surface-2)', border: '1px solid var(--border)',
borderRadius: 99, padding: '3px 10px', fontSize: 12,
background: 'var(--surface)', border: '1px solid var(--border)',
borderRadius: 999, padding: '4px 12px', fontSize: 12.5,
}}>
<span style={{ fontWeight: 700, color: 'var(--text)' }}>{plan.max_secretaries}</span>
<UserIcon style={{ width: 14, color: 'var(--text-3)' }} />
<span style={{ fontWeight: 700, color: 'var(--text)' }}>{formatNumber(plan.max_secretaries)}</span>
<span style={{ color: 'var(--text-3)' }}>منشی</span>
</div>
</div>
{/* قابلیت‌ها */}
<div style={{ padding: '16px 20px', borderBottom: paidPeriods.length > 0 ? '1px solid var(--border)' : 'none', flex: 1 }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-3)', marginBottom: 10, textTransform: 'uppercase', letterSpacing: '.5px' }}>
امکانات
<div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 14, flex: 1 }}>
{/* توگل دوره */}
{paidPeriods.length > 1 && (
<div role="tablist" aria-label="دوره اشتراک" style={{
display: 'grid', gridTemplateColumns: `repeat(${paidPeriods.length}, 1fr)`, gap: 4,
background: 'var(--surface-2)', border: '1px solid var(--border)',
borderRadius: 'var(--r-sm)', padding: 4,
}}>
{paidPeriods.map((p) => {
const on = p.uuid === selectedPeriod?.uuid;
return (
<button
key={p.uuid} role="tab" aria-selected={on}
onClick={() => setSelectedUuid(p.uuid)}
style={{
padding: '7px 6px', borderRadius: 'var(--r-xs)', border: 'none', cursor: 'pointer',
fontFamily: 'inherit', fontSize: 12.5, fontWeight: on ? 700 : 500, transition: '.14s',
background: on ? 'var(--primary)' : 'transparent',
color: on ? '#fff' : 'var(--text-2)',
}}
>
{p.label}
</button>
);
})}
</div>
)}
{/* قیمت */}
<div>
{selectedPeriod ? (
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
<span style={{ fontSize: 13, color: 'var(--text-3)' }}>قیمت:</span>
<span style={{ fontWeight: 800, fontSize: 20, color: 'var(--text)' }}>
{formatRial(selectedPeriod.price_rials)}
</span>
</div>
) : (
<div style={{ fontWeight: 800, fontSize: 18, color: 'var(--success)' }}>رایگان</div>
)}
</div>
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 9 }}>
{/* امکانات */}
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
{Object.entries(plan.features).map(([key, enabled]) => (
<li key={key} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5 }}>
<span style={{
@@ -495,8 +390,7 @@ function PlanCard({
}}>
{enabled
? <CheckIcon style={{ width: 12, color: 'var(--success)' }} />
: <XMarkIcon style={{ width: 11, color: 'var(--text-3)' }} />
}
: <XMarkIcon style={{ width: 11, color: 'var(--text-3)' }} />}
</span>
<span style={{ color: enabled ? 'var(--text)' : 'var(--text-3)' }}>
{PLAN_FEATURE_LABELS[key] ?? key}
@@ -508,91 +402,53 @@ function PlanCard({
{/* تریال */}
{trialPeriod && !usedTrial && plan.level > 0 && !isDowngrade && (
<div style={{
marginTop: 14, padding: '10px 12px', borderRadius: 'var(--r-sm)',
background: 'linear-gradient(135deg, var(--info-bg), var(--violet-bg))',
border: '1px dashed color-mix(in oklch, var(--info) 50%, transparent)', fontSize: 12.5,
display: 'flex', alignItems: 'center', gap: 8,
padding: '10px 12px', borderRadius: 'var(--r-sm)',
background: 'var(--accent-bg)',
border: '1px dashed color-mix(in oklch, var(--accent) 45%, transparent)',
fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 8,
}}>
<span>🎁</span>
<GiftIcon style={{ width: 16, color: 'var(--accent)', flexShrink: 0 }} />
<span style={{ color: 'var(--text-2)' }}>
تریال <b>{trialPeriod.duration_months} ماهه</b> رایگان
تریال <b>{formatNumber(trialPeriod.duration_months)} ماهه</b> رایگان
</span>
<button
className="btn primary sm"
style={{ marginRight: 'auto', fontSize: 11.5, height: 28, padding: '0 10px' }}
onClick={onTrial}
disabled={trialPending}
onClick={onTrial} disabled={trialPending}
style={{
marginRight: 'auto', background: 'none', border: 'none', cursor: 'pointer',
color: 'var(--accent)', fontWeight: 700, fontSize: 12.5, fontFamily: 'inherit',
}}
>
{trialPending ? '...' : 'فعال‌سازی'}
{trialPending
? <ArrowPathIcon style={{ width: 14, animation: 'spin 1s linear infinite' }} />
: 'فعال سازی'}
</button>
</div>
)}
</div>
{/* دوره‌های پرداختی */}
{paidPeriods.length > 0 && (
<div style={{ padding: '14px 20px', display: 'flex', flexDirection: 'column', gap: 8 }}>
{isDowngrade && (
<div style={{
display: 'flex', alignItems: 'center', gap: 8,
padding: '10px 12px', borderRadius: 'var(--r-sm)',
background: 'var(--warning-bg)', border: '1px solid var(--warning)',
fontSize: 12.5, color: 'var(--warning)', marginBottom: 2,
}}>
<span style={{ fontSize: 15 }}>🔒</span>
<span>تا پایان اشتراک فعلی قابل انتخاب نیست</span>
</div>
)}
{paidPeriods.map((period) => (
<div key={period.uuid} style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
gap: 8, padding: '8px 10px', borderRadius: 'var(--r-sm)',
border: '1px solid var(--border)',
background: isDowngrade ? 'var(--surface-3)' : 'var(--surface-2)',
opacity: isDowngrade ? 0.6 : 1,
}}>
<div>
<div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>{period.label}</div>
<div style={{ fontSize: 11.5, color: 'var(--text-3)' }}>{period.duration_months} ماه</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ fontWeight: 700, fontSize: 13.5, color: isDowngrade ? 'var(--text-3)' : meta.color }}>
{formatRial(period.price_rials)}
</span>
<button
disabled={isDowngrade}
onClick={() => !isDowngrade && onPurchase(period)}
style={{
padding: '6px 14px', borderRadius: 'var(--r-sm)',
cursor: isDowngrade ? 'not-allowed' : 'pointer',
background: isDowngrade ? 'var(--surface-3)' : isCurrent ? 'var(--surface)' : meta.color,
color: isDowngrade ? 'var(--text-3)' : isCurrent ? meta.color : '#fff',
border: `1.5px solid ${isDowngrade ? 'var(--border)' : meta.color}`,
fontSize: 12.5, fontWeight: 700, transition: '.14s',
fontFamily: 'inherit',
}}
onMouseEnter={(e) => { if (!isDowngrade) (e.currentTarget as HTMLElement).style.opacity = '.85'; }}
onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.opacity = '1'; }}
>
{isCurrent ? 'تمدید' : 'خرید'}
</button>
</div>
</div>
))}
</div>
)}
{/* پنل رایگان — بدون دوره */}
{paidPeriods.length === 0 && plan.level === 0 && (
<div style={{
padding: '14px 20px',
textAlign: 'center', fontSize: 13,
color: isCurrent ? 'var(--success)' : 'var(--text-3)',
fontWeight: isCurrent ? 700 : 400,
}}>
{isCurrent ? '✓ شما اکنون در این پنل هستید' : 'رایگان — بدون هزینه'}
</div>
)}
{/* دکمه خرید */}
<div style={{ padding: '0 20px 20px' }}>
{isDowngrade ? (
<button className="btn" style={{ width: '100%', height: 44, opacity: 0.6, cursor: 'not-allowed' }} disabled>
تا پایان اشتراک فعلی قابل انتخاب نیست
</button>
) : selectedPeriod ? (
<button
className={isPopular ? 'btn primary' : 'btn'}
style={{
width: '100%', height: 44, fontWeight: 700,
...(isPopular ? {} : { border: '1.5px solid var(--primary)', color: 'var(--primary)', background: 'var(--surface)' }),
}}
onClick={() => onPurchase(selectedPeriod)}
>
{isCurrent ? 'تمدید اشتراک' : 'خرید اشتراک'}
</button>
) : (
<button className="btn" style={{ width: '100%', height: 44, cursor: 'default' }} disabled>
{isCurrent ? 'پلن فعلی شما' : 'رایگان'}
</button>
)}
</div>
</div>
);
}