feat: Implement user tier-based feature gating system (refs #8)
All checks were successful
Deploy to Staging / Build Images (pull_request) Successful in 4m35s
Deploy to Staging / Deploy to Staging (pull_request) Successful in 27s
Deploy to Staging / Verify Staging (pull_request) Successful in 5s
Deploy to Staging / Notify Staging Ready (pull_request) Successful in 5s
Deploy to Staging / Notify Staging Failure (pull_request) Has been skipped
All checks were successful
Deploy to Staging / Build Images (pull_request) Successful in 4m35s
Deploy to Staging / Deploy to Staging (pull_request) Successful in 27s
Deploy to Staging / Verify Staging (pull_request) Successful in 5s
Deploy to Staging / Notify Staging Ready (pull_request) Successful in 5s
Deploy to Staging / Notify Staging Failure (pull_request) Has been skipped
Add subscription tier system to gate features behind Free/Pro/Enterprise tiers. Backend: - Create feature-tiers.ts with FEATURE_TIERS config and utilities - Add /api/config/feature-tiers endpoint for frontend config fetch - Create requireTier middleware for route-level tier enforcement - Add subscriptionTier to request.userContext in auth plugin - Gate scanForMaintenance in documents controller (Pro+ required) - Add migration to reset scanForMaintenance for free users Frontend: - Create useTierAccess hook for tier checking - Create UpgradeRequiredDialog component (responsive) - Gate DocumentForm checkbox with lock icon for free users - Add SubscriptionTier type to profile.types.ts Documentation: - Add TIER-GATING.md with usage guide Tests: 30 passing (feature-tiers, tier-guard, controller) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
8
frontend/src/core/hooks/index.ts
Normal file
8
frontend/src/core/hooks/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* @ai-summary Core hooks barrel export
|
||||
*/
|
||||
|
||||
export { useDataSync } from './useDataSync';
|
||||
export { useFormState } from './useFormState';
|
||||
export { useTierAccess } from './useTierAccess';
|
||||
export type { FeatureConfig } from './useTierAccess';
|
||||
111
frontend/src/core/hooks/useTierAccess.ts
Normal file
111
frontend/src/core/hooks/useTierAccess.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* @ai-summary React hook for tier-based feature access checking
|
||||
* @ai-context Used to gate premium features based on user subscription tier
|
||||
*/
|
||||
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useAuth0 } from '@auth0/auth0-react';
|
||||
import { apiClient } from '../api/client';
|
||||
import type { SubscriptionTier } from '../../features/settings/types/profile.types';
|
||||
|
||||
// Feature tier configuration (mirrors backend)
|
||||
export interface FeatureConfig {
|
||||
minTier: SubscriptionTier;
|
||||
name: string;
|
||||
upgradePrompt: string;
|
||||
}
|
||||
|
||||
interface FeatureTiersResponse {
|
||||
tiers: Record<SubscriptionTier, number>;
|
||||
features: Record<string, FeatureConfig>;
|
||||
}
|
||||
|
||||
interface AccessCheckResult {
|
||||
allowed: boolean;
|
||||
requiredTier: SubscriptionTier | null;
|
||||
config: FeatureConfig | null;
|
||||
}
|
||||
|
||||
// Tier hierarchy for comparison
|
||||
const TIER_LEVELS: Record<SubscriptionTier, number> = {
|
||||
free: 0,
|
||||
pro: 1,
|
||||
enterprise: 2,
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to check if user can access tier-gated features
|
||||
* Fetches user profile for tier and feature config from backend
|
||||
*/
|
||||
export const useTierAccess = () => {
|
||||
const { isAuthenticated, isLoading: authLoading } = useAuth0();
|
||||
|
||||
// Fetch user profile for current tier
|
||||
const profileQuery = useQuery({
|
||||
queryKey: ['user-profile'],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get('/user/profile');
|
||||
return response.data;
|
||||
},
|
||||
enabled: isAuthenticated && !authLoading,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
gcTime: 10 * 60 * 1000,
|
||||
});
|
||||
|
||||
// Fetch feature tier config from backend (single source of truth)
|
||||
const featureConfigQuery = useQuery({
|
||||
queryKey: ['feature-tiers'],
|
||||
queryFn: async () => {
|
||||
const response = await apiClient.get<FeatureTiersResponse>('/config/feature-tiers');
|
||||
return response.data;
|
||||
},
|
||||
enabled: isAuthenticated && !authLoading,
|
||||
staleTime: 30 * 60 * 1000, // 30 minutes - config rarely changes
|
||||
gcTime: 60 * 60 * 1000, // 1 hour cache
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnMount: false,
|
||||
});
|
||||
|
||||
const tier: SubscriptionTier = profileQuery.data?.subscriptionTier || 'free';
|
||||
const features = featureConfigQuery.data?.features || {};
|
||||
|
||||
/**
|
||||
* Check if user can access a feature by key
|
||||
*/
|
||||
const hasAccess = (featureKey: string): boolean => {
|
||||
const config = features[featureKey];
|
||||
if (!config) {
|
||||
// Unknown features are allowed (fail open for safety)
|
||||
return true;
|
||||
}
|
||||
return TIER_LEVELS[tier] >= TIER_LEVELS[config.minTier];
|
||||
};
|
||||
|
||||
/**
|
||||
* Get detailed access information for a feature
|
||||
*/
|
||||
const checkAccess = (featureKey: string): AccessCheckResult => {
|
||||
const config = features[featureKey] || null;
|
||||
if (!config) {
|
||||
return {
|
||||
allowed: true,
|
||||
requiredTier: null,
|
||||
config: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
allowed: TIER_LEVELS[tier] >= TIER_LEVELS[config.minTier],
|
||||
requiredTier: config.minTier,
|
||||
config,
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
tier,
|
||||
loading: profileQuery.isLoading || featureConfigQuery.isLoading,
|
||||
hasAccess,
|
||||
checkAccess,
|
||||
};
|
||||
};
|
||||
|
||||
export default useTierAccess;
|
||||
@@ -1,14 +1,17 @@
|
||||
import React from 'react';
|
||||
import { Button } from '../../../shared-minimal/components/Button';
|
||||
import { UpgradeRequiredDialog } from '../../../shared-minimal/components/UpgradeRequiredDialog';
|
||||
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
|
||||
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
|
||||
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
|
||||
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
|
||||
import dayjs from 'dayjs';
|
||||
import { useCreateDocument } from '../hooks/useDocuments';
|
||||
import { documentsApi } from '../api/documents.api';
|
||||
import type { DocumentType } from '../types/documents.types';
|
||||
import { useVehicles } from '../../vehicles/hooks/useVehicles';
|
||||
import type { Vehicle } from '../../vehicles/types/vehicles.types';
|
||||
import { useTierAccess } from '../../../core/hooks/useTierAccess';
|
||||
|
||||
interface DocumentFormProps {
|
||||
onSuccess?: () => void;
|
||||
@@ -42,9 +45,12 @@ export const DocumentForm: React.FC<DocumentFormProps> = ({ onSuccess, onCancel
|
||||
const [file, setFile] = React.useState<File | null>(null);
|
||||
const [uploadProgress, setUploadProgress] = React.useState<number>(0);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
const [upgradeDialogOpen, setUpgradeDialogOpen] = React.useState<boolean>(false);
|
||||
|
||||
const { data: vehicles } = useVehicles();
|
||||
const create = useCreateDocument();
|
||||
const { hasAccess } = useTierAccess();
|
||||
const canScanMaintenance = hasAccess('document.scanMaintenanceSchedule');
|
||||
|
||||
const resetForm = () => {
|
||||
setTitle('');
|
||||
@@ -349,18 +355,31 @@ export const DocumentForm: React.FC<DocumentFormProps> = ({ onSuccess, onCancel
|
||||
|
||||
{documentType === 'manual' && (
|
||||
<div className="flex items-center md:col-span-2">
|
||||
<label className="flex items-center cursor-pointer">
|
||||
<label className={`flex items-center ${canScanMaintenance ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'}`}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={scanForMaintenance}
|
||||
onChange={(e) => setScanForMaintenance(e.target.checked)}
|
||||
className="w-5 h-5 rounded border-slate-300 text-primary-600 focus:ring-primary-500 dark:border-silverstone dark:focus:ring-abudhabi"
|
||||
checked={canScanMaintenance ? scanForMaintenance : false}
|
||||
onChange={(e) => canScanMaintenance && setScanForMaintenance(e.target.checked)}
|
||||
disabled={!canScanMaintenance}
|
||||
className="w-5 h-5 rounded border-slate-300 text-primary-600 focus:ring-primary-500 dark:border-silverstone dark:focus:ring-abudhabi disabled:opacity-50"
|
||||
/>
|
||||
<span className="ml-2 text-sm font-medium text-slate-700 dark:text-avus">
|
||||
Scan for Maintenance Schedule
|
||||
</span>
|
||||
</label>
|
||||
<span className="ml-2 text-xs text-slate-500 dark:text-titanio">(Coming soon)</span>
|
||||
{!canScanMaintenance && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setUpgradeDialogOpen(true)}
|
||||
className="ml-2 p-1 text-slate-500 hover:text-primary-600 dark:text-titanio dark:hover:text-abudhabi transition-colors"
|
||||
title="Upgrade to Pro to unlock this feature"
|
||||
>
|
||||
<LockOutlinedIcon fontSize="small" />
|
||||
</button>
|
||||
)}
|
||||
{canScanMaintenance && (
|
||||
<span className="ml-2 text-xs text-slate-500 dark:text-titanio">(Coming soon)</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -395,6 +414,12 @@ export const DocumentForm: React.FC<DocumentFormProps> = ({ onSuccess, onCancel
|
||||
<Button type="submit" className="min-h-[44px]">Create Document</Button>
|
||||
<Button type="button" variant="secondary" onClick={onCancel} className="min-h-[44px]">Cancel</Button>
|
||||
</div>
|
||||
|
||||
<UpgradeRequiredDialog
|
||||
featureKey="document.scanMaintenanceSchedule"
|
||||
open={upgradeDialogOpen}
|
||||
onClose={() => setUpgradeDialogOpen(false)}
|
||||
/>
|
||||
</form>
|
||||
</LocalizationProvider>
|
||||
);
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
* @ai-summary User profile types for settings feature
|
||||
*/
|
||||
|
||||
export type SubscriptionTier = 'free' | 'pro' | 'enterprise';
|
||||
|
||||
export interface UserProfile {
|
||||
id: string;
|
||||
auth0Sub: string;
|
||||
email: string;
|
||||
displayName?: string;
|
||||
notificationEmail?: string;
|
||||
subscriptionTier: SubscriptionTier;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
178
frontend/src/shared-minimal/components/UpgradeRequiredDialog.tsx
Normal file
178
frontend/src/shared-minimal/components/UpgradeRequiredDialog.tsx
Normal file
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* @ai-summary Dialog prompting users to upgrade their subscription tier
|
||||
* @ai-context Shown when users attempt to use a tier-gated feature
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Button,
|
||||
Typography,
|
||||
Box,
|
||||
Chip,
|
||||
useMediaQuery,
|
||||
useTheme,
|
||||
IconButton,
|
||||
} from '@mui/material';
|
||||
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
|
||||
import CloseIcon from '@mui/icons-material/Close';
|
||||
import { useTierAccess } from '../../core/hooks/useTierAccess';
|
||||
import type { SubscriptionTier } from '../../features/settings/types/profile.types';
|
||||
|
||||
interface UpgradeRequiredDialogProps {
|
||||
featureKey: string;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const tierDisplayNames: Record<SubscriptionTier, string> = {
|
||||
free: 'Free',
|
||||
pro: 'Pro',
|
||||
enterprise: 'Enterprise',
|
||||
};
|
||||
|
||||
const tierColors: Record<SubscriptionTier, 'default' | 'primary' | 'secondary'> = {
|
||||
free: 'default',
|
||||
pro: 'primary',
|
||||
enterprise: 'secondary',
|
||||
};
|
||||
|
||||
export const UpgradeRequiredDialog: React.FC<UpgradeRequiredDialogProps> = ({
|
||||
featureKey,
|
||||
open,
|
||||
onClose,
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const isSmall = useMediaQuery(theme.breakpoints.down('sm'));
|
||||
const { tier, checkAccess } = useTierAccess();
|
||||
|
||||
const { config, requiredTier } = checkAccess(featureKey);
|
||||
|
||||
const handleUpgradeClick = () => {
|
||||
// TODO: Navigate to upgrade page when Stripe integration is added
|
||||
// For now, just close the dialog
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
fullScreen={isSmall}
|
||||
maxWidth="sm"
|
||||
fullWidth
|
||||
PaperProps={{
|
||||
sx: {
|
||||
maxHeight: isSmall ? '100%' : '90vh',
|
||||
m: isSmall ? 0 : 2,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{isSmall && (
|
||||
<IconButton
|
||||
aria-label="close"
|
||||
onClick={onClose}
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
right: 8,
|
||||
top: 8,
|
||||
color: (theme) => theme.palette.grey[500],
|
||||
}}
|
||||
>
|
||||
<CloseIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
<DialogTitle sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
<LockOutlinedIcon color="action" />
|
||||
Upgrade Required
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
|
||||
{/* Feature name */}
|
||||
<Box>
|
||||
<Typography variant="h6" gutterBottom>
|
||||
{config?.name || 'Premium Feature'}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{config?.upgradePrompt || 'This feature requires a higher subscription tier.'}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* Tier comparison */}
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 2,
|
||||
py: 2,
|
||||
px: 3,
|
||||
bgcolor: 'action.hover',
|
||||
borderRadius: 1,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="caption" color="text.secondary" display="block">
|
||||
Your Plan
|
||||
</Typography>
|
||||
<Chip
|
||||
label={tierDisplayNames[tier]}
|
||||
color={tierColors[tier]}
|
||||
size="small"
|
||||
sx={{ mt: 0.5 }}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Typography variant="h5" color="text.secondary">
|
||||
→
|
||||
</Typography>
|
||||
|
||||
<Box sx={{ textAlign: 'center' }}>
|
||||
<Typography variant="caption" color="text.secondary" display="block">
|
||||
Required
|
||||
</Typography>
|
||||
<Chip
|
||||
label={requiredTier ? tierDisplayNames[requiredTier] : 'Pro'}
|
||||
color={requiredTier ? tierColors[requiredTier] : 'primary'}
|
||||
size="small"
|
||||
sx={{ mt: 0.5 }}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Benefits preview */}
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
Upgrade to unlock this feature and more premium capabilities.
|
||||
</Typography>
|
||||
</Box>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions sx={{ px: 3, pb: 3, pt: 1, flexDirection: isSmall ? 'column' : 'row', gap: 1 }}>
|
||||
<Button
|
||||
onClick={onClose}
|
||||
variant="outlined"
|
||||
fullWidth={isSmall}
|
||||
sx={{ order: isSmall ? 2 : 1 }}
|
||||
>
|
||||
Maybe Later
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleUpgradeClick}
|
||||
variant="contained"
|
||||
color="primary"
|
||||
fullWidth={isSmall}
|
||||
sx={{ order: isSmall ? 1 : 2 }}
|
||||
>
|
||||
Upgrade (Coming Soon)
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpgradeRequiredDialog;
|
||||
7
frontend/src/shared-minimal/components/index.ts
Normal file
7
frontend/src/shared-minimal/components/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* @ai-summary Shared minimal components barrel export
|
||||
*/
|
||||
|
||||
export { Button } from './Button';
|
||||
export { Card } from './Card';
|
||||
export { UpgradeRequiredDialog } from './UpgradeRequiredDialog';
|
||||
Reference in New Issue
Block a user