feat(subscription): implement feature gating for subscription-based access in admin panel

This commit is contained in:
hamed
2026-06-15 12:00:36 +03:30
parent 3d33cf09b8
commit fa6656df48
11 changed files with 534 additions and 26 deletions
+28 -18
View File
@@ -13,6 +13,7 @@ import {
DocumentTextIcon,
HeartIcon,
KeyIcon,
LockClosedIcon,
StarIcon,
TagIcon,
UserCircleIcon,
@@ -26,8 +27,9 @@ import {
import { NavLink, useNavigate } from "react-router-dom";
import { useAuthStore } from "../../stores/authStore";
import { useUiStore } from "../../stores/uiStore";
import { useSubscription } from "../../hooks/useSubscription";
type SectionItem = { to: string; icon: React.ElementType; label: string };
type SectionItem = { to: string; icon: React.ElementType; label: string; feature?: string };
type Section = { label: string; items: SectionItem[] };
function buildSections(primaryRole: string | null, dbUuid: string | null): Section[] {
@@ -87,11 +89,11 @@ function buildSections(primaryRole: string | null, dbUuid: string | null): Secti
label: 'مدیریت',
items: [
{ to: '/admin/appointments', icon: CalendarDaysIcon, label: 'نوبت‌ها' },
{ to: '/admin/my-patients', icon: FolderOpenIcon, label: 'پرونده بیماران' },
{ to: '/admin/my-patients', icon: FolderOpenIcon, label: 'پرونده بیماران', feature: 'patient_records' },
{ to: '/admin/staff', icon: UserPlusIcon, label: 'پرسنل' },
{ to: '/admin/my-secretaries', icon: IdentificationIcon, label: 'منشیان' },
{ to: '/admin/clinic-services', icon: WrenchScrewdriverIcon, label: 'سرویس‌ها' },
{ to: '/admin/sms-wallet', icon: DevicePhoneMobileIcon, label: 'کیف پول پیامک' },
{ to: '/admin/clinic-services', icon: WrenchScrewdriverIcon, label: 'سرویس‌ها', feature: 'services' },
{ to: '/admin/sms-wallet', icon: DevicePhoneMobileIcon, label: 'کیف پول پیامک', feature: 'sms_panel' },
],
},
{
@@ -121,11 +123,11 @@ function buildSections(primaryRole: string | null, dbUuid: string | null): Secti
label: 'مدیریت',
items: [
{ to: '/admin/appointments', icon: CalendarDaysIcon, label: 'نوبت‌های من' },
{ to: '/admin/my-patients', icon: FolderOpenIcon, label: 'پرونده بیماران' },
{ to: '/admin/my-patients', icon: FolderOpenIcon, label: 'پرونده بیماران', feature: 'patient_records' },
{ to: '/admin/staff', icon: UserPlusIcon, label: 'پرسنل' },
{ to: '/admin/my-secretaries', icon: IdentificationIcon, label: 'منشیان' },
{ to: '/admin/clinic-services', icon: WrenchScrewdriverIcon, label: 'سرویس‌ها' },
{ to: '/admin/sms-wallet', icon: DevicePhoneMobileIcon, label: 'کیف پول پیامک' },
{ to: '/admin/clinic-services', icon: WrenchScrewdriverIcon, label: 'سرویس‌ها', feature: 'services' },
{ to: '/admin/sms-wallet', icon: DevicePhoneMobileIcon, label: 'کیف پول پیامک', feature: 'sms_panel' },
],
},
{
@@ -149,6 +151,7 @@ function buildSections(primaryRole: string | null, dbUuid: string | null): Secti
label: 'مدیریت',
items: [
{ to: '/admin/appointments', icon: CalendarDaysIcon, label: 'نوبت‌ها' },
{ to: '/admin/my-patients', icon: FolderOpenIcon, label: 'پرونده بیماران', feature: 'patient_records' },
],
},
];
@@ -185,6 +188,7 @@ interface Props {
export default function Sidebar({ mobileOpen: _m, onMobileClose: _c }: Props) {
const sidebarOpen = useUiStore((s) => s.sidebarOpen);
const { logout, primaryRole, userName, availableContexts, dbUuid } = useAuthStore();
const { hasFeature } = useSubscription();
const navigate = useNavigate();
const sections = buildSections(primaryRole, dbUuid);
@@ -208,17 +212,23 @@ export default function Sidebar({ mobileOpen: _m, onMobileClose: _c }: Props) {
{sections.map((section) => (
<div className="nav-group" key={section.label}>
<span className="nav-label">{section.label}</span>
{section.items.map(({ to, icon: Icon, label }) => (
<NavLink
key={to}
to={to}
title={!sidebarOpen ? label : undefined}
className={({ isActive }) => `nav-item${isActive ? ' active' : ''}`}
>
<Icon style={{ width: 19, height: 19, flexShrink: 0 }} />
<span>{label}</span>
</NavLink>
))}
{section.items.map(({ to, icon: Icon, label, feature }) => {
const isLocked = feature ? !hasFeature(feature) : false;
const dest = isLocked ? '/admin/subscription' : to;
return (
<NavLink
key={to}
to={dest}
title={isLocked ? 'نیاز به ارتقاء پنل' : (!sidebarOpen ? label : undefined)}
className={({ isActive }) => `nav-item${isActive && !isLocked ? ' active' : ''}${isLocked ? ' locked' : ''}`}
style={isLocked ? { opacity: 0.55 } : undefined}
>
<Icon style={{ width: 19, height: 19, flexShrink: 0 }} />
<span>{label}</span>
{isLocked && <LockClosedIcon style={{ width: 12, height: 12, marginRight: 'auto', flexShrink: 0 }} />}
</NavLink>
);
})}
</div>
))}
@@ -0,0 +1,45 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { LockClosedIcon } from '@heroicons/react/24/outline';
import { useSubscription } from '../../hooks/useSubscription';
interface FeatureGateProps {
feature: string;
children: React.ReactNode;
}
export default function FeatureGate({ feature, children }: FeatureGateProps) {
const { hasFeature, hasPlan } = useSubscription();
if (hasFeature(feature)) return <>{children}</>;
return (
<div style={{
display: 'flex', flexDirection: 'column',
alignItems: 'center', justifyContent: 'center',
minHeight: 320, gap: 16, padding: 40, textAlign: 'center',
}}>
<div style={{
width: 64, height: 64, borderRadius: '50%',
background: 'oklch(0.97 0.01 256)',
display: 'grid', placeItems: 'center',
border: '1px solid var(--border)',
}}>
<LockClosedIcon style={{ width: 28, color: 'var(--text-3)' }} />
</div>
<div>
<div style={{ fontWeight: 700, fontSize: 16, marginBottom: 6 }}>
این قابلیت در پنل فعلی شما فعال نیست
</div>
<div style={{ color: 'var(--text-3)', fontSize: 13.5, maxWidth: 360, lineHeight: 1.6 }}>
{hasPlan
? 'برای استفاده از این قابلیت پنل خود را ارتقاء دهید'
: 'برای استفاده از این قابلیت یک پنل اشتراکی فعال کنید'}
</div>
</div>
<Link to="/admin/subscription" className="btn primary sm" style={{ textDecoration: 'none' }}>
{hasPlan ? 'ارتقاء پنل' : 'مشاهده پنل‌های اشتراکی'}
</Link>
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import { useAuthStore } from '../stores/authStore';
import type { MySubscriptionData } from '../types';
export function useSubscription() {
const primaryRole = useAuthStore((s) => s.primaryRole);
const enabled = primaryRole === 'doctor' || primaryRole === 'clinic' || primaryRole === 'secretary';
const { data } = useQuery<ApiResponse<MySubscriptionData>>({
queryKey: ['subscription-my'],
queryFn: () => api.get('/api/v1/subscription/my'),
enabled,
staleTime: 2 * 60 * 1000,
});
const sub = data?.data?.subscription ?? null;
const features: Record<string, boolean> = sub?.plan?.features ?? {};
const maxSecretaries: number = sub?.plan?.max_secretaries ?? 1;
const hasPlan = sub !== null;
return {
subscription: sub,
hasFeature: (key: string) => hasPlan && (features[key] ?? false),
maxSecretaries,
hasPlan,
isExpiringSoon: (sub?.days_remaining ?? 0) > 0 && (sub?.days_remaining ?? 0) <= 7,
};
}
+10 -1
View File
@@ -14,6 +14,7 @@ import PriceInput from '../components/ui/PriceInput';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import PageHeader from '../components/ui/PageHeader';
import SearchableSelect from '../components/ui/SearchableSelect';
import FeatureGate from '../components/ui/FeatureGate';
const sectionSchema = z.object({ name: z.string().min(1, 'نام بخش الزامی است') });
const itemSchema = z.object({
@@ -27,7 +28,7 @@ type ItemForm = z.infer<typeof itemSchema>;
const EMPTY_SECTIONS: ServiceSection[] = [];
const EMPTY_ITEMS: ServiceItem[] = [];
export default function ClinicServicesPage() {
function ClinicServicesPageInner() {
const qc = useQueryClient();
const [selectedSection, setSelectedSection] = useState<ServiceSection | null>(null);
@@ -409,3 +410,11 @@ export default function ClinicServicesPage() {
</>
);
}
export default function ClinicServicesPage() {
return (
<FeatureGate feature="services">
<ClinicServicesPageInner />
</FeatureGate>
);
}
+10 -1
View File
@@ -17,6 +17,7 @@ import Pagination from '../components/ui/Pagination';
import Modal from '../components/ui/Modal';
import PageHeader from '../components/ui/PageHeader';
import SearchableSelect from '../components/ui/SearchableSelect';
import FeatureGate from '../components/ui/FeatureGate';
const sessionSchema = z.object({
visit_price_rials: z.coerce.number().min(0),
@@ -44,7 +45,7 @@ function calcFinalPrice(visitPrice: number, baseDiscount: number, suppDiscount:
return Math.round(afterSupp) + servicesTotal;
}
export default function MyPatientsPage() {
function MyPatientsPageInner() {
const qc = useQueryClient();
const [selectedRecord, setSelectedRecord] = useState<PatientRecord | null>(null);
const [page, setPage] = useState(1);
@@ -543,3 +544,11 @@ function EditSessionModal({
</Modal>
);
}
export default function MyPatientsPage() {
return (
<FeatureGate feature="patient_records">
<MyPatientsPageInner />
</FeatureGate>
);
}
+13 -4
View File
@@ -15,6 +15,8 @@ import Modal from '../components/ui/Modal';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import PageHeader from '../components/ui/PageHeader';
import { useAuthStore } from '../stores/authStore';
import { useSubscription } from '../hooks/useSubscription';
import { Link } from 'react-router-dom';
// ── Default permissions & labels ──────────────────────────────────────────
@@ -143,6 +145,7 @@ export default function MySecretariesPage() {
const { doctorUuid, dbUuid, primaryRole } = useAuthStore();
const isClinic = primaryRole === 'clinic';
const { maxSecretaries } = useSubscription();
// for clinic: selected doctor to add secretary for
const [selectedDoctorUuid, setSelectedDoctorUuid] = useState<string>('');
@@ -309,10 +312,16 @@ export default function MySecretariesPage() {
title="منشیان من"
description="مدیریت منشیان و دسترسی‌های آن‌ها"
action={
<button className="btn primary sm" onClick={handleCreateOpen} disabled={isClinic && !selectedDoctorUuid}>
<PlusIcon style={{ width: 16 }} />
افزودن منشی
</button>
secretaries.length >= maxSecretaries ? (
<Link to="/admin/subscription" className="btn sm" style={{ textDecoration: 'none', opacity: 0.8 }} title={`حداکثر ${maxSecretaries} منشی مجاز است`}>
ارتقاء پنل برای افزودن منشی
</Link>
) : (
<button className="btn primary sm" onClick={handleCreateOpen} disabled={isClinic && !selectedDoctorUuid}>
<PlusIcon style={{ width: 16 }} />
افزودن منشی
</button>
)
}
/>
+10 -1
View File
@@ -14,6 +14,7 @@ import { formatRial, formatNumber, formatDateTime } from '../lib/utils';
import Modal from '../components/ui/Modal';
import Pagination from '../components/ui/Pagination';
import PageHeader from '../components/ui/PageHeader';
import FeatureGate from '../components/ui/FeatureGate';
const chargeSchema = z.object({
amount_rials: z.coerce.number().min(10000, 'حداقل مبلغ ۱۰,۰۰۰ ریال است'),
@@ -22,7 +23,7 @@ type ChargeForm = z.infer<typeof chargeSchema>;
const EMPTY_LOGS: SmsWalletLog[] = [];
export default function SmsWalletPage() {
function SmsWalletPageInner() {
const qc = useQueryClient();
const [chargeOpen, setChargeOpen] = useState(false);
const [gateway, setGateway] = useState<'mellat' | 'sep'>('mellat');
@@ -433,3 +434,11 @@ export default function SmsWalletPage() {
</>
);
}
export default function SmsWalletPage() {
return (
<FeatureGate feature="sms_panel">
<SmsWalletPageInner />
</FeatureGate>
);
}
+1 -1
View File
@@ -339,7 +339,7 @@ export interface SubscriptionPeriod {
export interface MySubscriptionData {
subscription: {
plan: { name: string; level: number; features: Record<string, boolean> };
plan: { name: string; level: number; max_secretaries: number; features: Record<string, boolean> };
period?: { label: string; duration_months: number };
is_trial: boolean;
starts_at?: number;