Files
clinicpro/assets/admin/pages/SubscriptionPage.tsx
T

599 lines
26 KiB
TypeScript

import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
CheckIcon, XMarkIcon, SparklesIcon, RocketLaunchIcon,
ShieldCheckIcon, CreditCardIcon, ClockIcon, ArrowPathIcon,
} 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 Modal from '../components/ui/Modal';
// ── Constants ─────────────────────────────────────────────────────────────
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,
},
};
// ── Main Page ─────────────────────────────────────────────────────────────
export default function SubscriptionPage() {
const qc = useQueryClient();
const [purchaseTarget, setPurchaseTarget] = useState<{ period: SubscriptionPeriod; planName: string } | null>(null);
const [selectedGateway, setSelectedGateway] = useState<string>('');
const { data: plansData, isLoading: plansLoading } = useQuery<ApiResponse<SubscriptionPlan[]>>({
queryKey: ['subscription-plans'],
queryFn: () => api.get('/api/v1/subscription/plans'),
});
const { data: myData, isLoading: myLoading } = useQuery<ApiResponse<MySubscriptionData>>({
queryKey: ['subscription-my'],
queryFn: () => api.get('/api/v1/subscription/my'),
});
const { isTestMode, gateways } = usePaymentConfig();
useEffect(() => {
if (gateways.length > 0 && !gateways.some((g) => g.name === selectedGateway)) {
setSelectedGateway(gateways[0].name);
}
}, [gateways, selectedGateway]);
const plans = plansData?.data ?? [];
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', {}),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['subscription-my'] });
toast.success('تریال رایگان با موفقیت فعال شد');
},
onError: (err: any) => toast.error(err.message),
});
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', {
period_uuid, gateway, amount_rials,
frontend_address: `${window.location.origin}/admin/subscription`,
}),
onSuccess: (res: any) => {
const url = res?.data?.pay_url ?? res?.data?.redirect_url ?? res?.data?.payment_url;
if (url) window.location.href = url;
else toast.error('خطا در دریافت لینک پرداخت');
},
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' }}>
{/* ── Header ── */}
<div style={{ marginBottom: 28 }}>
<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>
)}
{/* ── کارت‌های پلن ── */}
{plansLoading ? (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
{[1, 2, 3].map((i) => (
<div key={i} className="card" style={{ height: 320 }}>
<div className="skeleton" style={{ height: '100%', borderRadius: 'var(--r)' }} />
</div>
))}
</div>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 16 }}>
{plans.map((plan) => (
<PlanCard
key={plan.uuid}
plan={plan}
currentPlanName={my?.plan.name ?? 'free'}
currentPlanLevel={my?.plan.level ?? 0}
currentPlanActive={!!my && (my.days_remaining ?? 0) > 0}
usedTrial={usedTrial}
onPurchase={(period) => setPurchaseTarget({ period, planName: plan.name })}
onTrial={() => trialMutation.mutate()}
trialPending={trialMutation.isPending}
/>
))}
</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
open={!!purchaseTarget}
onClose={() => { setPurchaseTarget(null); setSelectedGateway('mellat'); }}
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',
}}>
<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}
</div>
<div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 1 }}>
{purchaseTarget.period.duration_months} ماه
</div>
</div>
<div style={{ textAlign: 'left' }}>
<div style={{ fontSize: 12, color: 'var(--text-3)', marginBottom: 2 }}>مبلغ قابل پرداخت</div>
<div style={{ fontWeight: 800, fontSize: 20, color: 'var(--primary)' }}>
{formatRial(purchaseTarget.period.price_rials)}
</div>
</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,
}}>
<span style={{ fontSize: 20 }}>⚠️</span>
<div>
<div style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--warning)' }}>درگاه آزمایشی فعال است</div>
<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>
) : (
<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>
)
)}
{/* دکمه‌ها */}
<div style={{ display: 'flex', gap: 10, marginTop: 4 }}>
<button
className="btn primary"
style={{ flex: 1, height: 44 }}
disabled={purchaseMutation.isPending || (!isTestMode && (gateways.length === 0 || selectedGateway === ''))}
onClick={() =>
purchaseMutation.mutate({ period_uuid: purchaseTarget.period.uuid, gateway: selectedGateway, amount_rials: purchaseTarget.period.price_rials })
}
>
{purchaseMutation.isPending
? 'در حال انتقال...'
: isTestMode
? `پرداخت آزمایشی ${formatRial(purchaseTarget.period.price_rials)}`
: `پرداخت ${formatRial(purchaseTarget.period.price_rials)}`
}
</button>
<button className="btn ghost" style={{ height: 44 }} onClick={() => setPurchaseTarget(null)}>
انصراف
</button>
</div>
</div>
)}
</Modal>
</div>
);
}
// ── PlanCard ──────────────────────────────────────────────────────────────
function PlanCard({
plan,
currentPlanName,
currentPlanLevel,
currentPlanActive,
usedTrial,
onPurchase,
onTrial,
trialPending,
}: {
plan: SubscriptionPlan;
currentPlanName: string;
currentPlanLevel: number;
currentPlanActive: boolean;
usedTrial: boolean;
onPurchase: (period: SubscriptionPeriod) => void;
onTrial: () => void;
trialPending: boolean;
}) {
const meta = PLAN_META[plan.name] ?? PLAN_META.free;
const isCurrent = plan.name === currentPlanName;
const isDowngrade = currentPlanActive && (plan.level ?? 0) < currentPlanLevel;
const paidPeriods = plan.periods.filter((p) => !p.is_trial);
const trialPeriod = plan.periods.find((p) => p.is_trial);
const Icon = meta.icon;
return (
<div style={{
background: 'var(--surface)',
border: `${isCurrent ? '2px' : '1.5px'} solid ${isCurrent ? meta.color : '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}`,
}}>
<Icon style={{ width: 22, height: 22 }} />
</div>
<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>
<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,
}}>
<span style={{ fontWeight: 700, color: 'var(--text)' }}>{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>
<ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 9 }}>
{Object.entries(plan.features).map(([key, enabled]) => (
<li key={key} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13.5 }}>
<span style={{
width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
display: 'grid', placeItems: 'center',
background: enabled ? 'var(--success-bg)' : 'var(--surface-3)',
}}>
{enabled
? <CheckIcon style={{ width: 12, color: 'var(--success)' }} />
: <XMarkIcon style={{ width: 11, color: 'var(--text-3)' }} />
}
</span>
<span style={{ color: enabled ? 'var(--text)' : 'var(--text-3)' }}>
{PLAN_FEATURE_LABELS[key] ?? key}
</span>
</li>
))}
</ul>
{/* تریال */}
{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,
}}>
<span>🎁</span>
<span style={{ color: 'var(--text-2)' }}>
تریال <b>{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}
>
{trialPending ? '...' : 'فعال‌سازی'}
</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>
);
}