kaboot/hooks/useUserPreferences.ts
Joey Yakimowich-Payne 2e12edc249
Add Stripe payment integration for AI subscriptions
Implement subscription-based AI access with 250 generations/month at $5/month or $50/year.

Changes:
- Backend: Stripe service, payment routes, webhook handlers, generation tracking
- Frontend: Upgrade page with pricing, payment success/cancel pages, UI prompts
- Database: Add subscription fields to users, payments table, migrations
- Config: Stripe env vars to .env.example, docker-compose.prod.yml, PRODUCTION.md
- Tests: Payment route tests, component tests, subscription hook tests

Users without AI access see upgrade prompts; subscribers see remaining generation count.
2026-01-21 16:11:03 -07:00

129 lines
4.2 KiB
TypeScript

import { useState, useCallback, useEffect } from 'react';
import toast from 'react-hot-toast';
import { useAuthenticatedFetch } from './useAuthenticatedFetch';
import type { UserPreferences } from '../types';
import { COLOR_SCHEMES } from '../types';
const DEFAULT_PREFERENCES: UserPreferences = {
colorScheme: 'blue',
aiProvider: 'gemini',
};
export const applyColorScheme = (schemeId: string) => {
const scheme = COLOR_SCHEMES.find(s => s.id === schemeId) || COLOR_SCHEMES[0];
document.documentElement.style.setProperty('--theme-primary', scheme.primary);
document.documentElement.style.setProperty('--theme-primary-dark', scheme.primaryDark);
document.documentElement.style.setProperty('--theme-primary-darker', scheme.primaryDarker);
};
interface SubscriptionInfo {
hasAccess: boolean;
accessType: 'group' | 'subscription' | 'none';
generationCount: number | null;
generationLimit: number | null;
generationsRemaining: number | null;
}
interface UseUserPreferencesReturn {
preferences: UserPreferences;
hasAIAccess: boolean;
subscription: SubscriptionInfo | null;
loading: boolean;
saving: boolean;
fetchPreferences: () => Promise<void>;
savePreferences: (prefs: UserPreferences) => Promise<void>;
applyColorScheme: (schemeId: string) => void;
}
export const useUserPreferences = (): UseUserPreferencesReturn => {
const { authFetch, isAuthenticated } = useAuthenticatedFetch();
const [preferences, setPreferences] = useState<UserPreferences>(DEFAULT_PREFERENCES);
const [hasAIAccess, setHasAIAccess] = useState(false);
const [subscription, setSubscription] = useState<SubscriptionInfo | null>(null);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const fetchPreferences = useCallback(async () => {
if (!isAuthenticated) return;
setLoading(true);
try {
const response = await authFetch('/api/users/me/preferences');
if (response.ok) {
const data = await response.json();
const prefs: UserPreferences = {
colorScheme: data.colorScheme || 'blue',
aiProvider: data.aiProvider || 'gemini',
geminiApiKey: data.geminiApiKey || undefined,
geminiModel: data.geminiModel || undefined,
openRouterApiKey: data.openRouterApiKey || undefined,
openRouterModel: data.openRouterModel || undefined,
openAIApiKey: data.openAIApiKey || undefined,
openAIModel: data.openAIModel || undefined,
};
setPreferences(prefs);
setHasAIAccess(data.hasAIAccess || false);
applyColorScheme(prefs.colorScheme);
const backendUrl = import.meta.env.VITE_BACKEND_URL || 'http://localhost:3001';
try {
const subResponse = await authFetch(`${backendUrl}/api/payments/status`);
if (subResponse.ok) {
const subData = await subResponse.json();
setSubscription({
hasAccess: subData.hasAccess,
accessType: subData.accessType,
generationCount: subData.generationCount,
generationLimit: subData.generationLimit,
generationsRemaining: subData.generationsRemaining,
});
}
} catch {
// Payments not configured, ignore
}
}
} catch {
} finally {
setLoading(false);
}
}, [authFetch, isAuthenticated]);
const savePreferences = useCallback(async (prefs: UserPreferences) => {
setSaving(true);
try {
const response = await authFetch('/api/users/me/preferences', {
method: 'PUT',
body: JSON.stringify(prefs),
});
if (!response.ok) {
throw new Error('Failed to save preferences');
}
setPreferences(prefs);
applyColorScheme(prefs.colorScheme);
toast.success('Preferences saved!');
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to save preferences';
toast.error(message);
throw err;
} finally {
setSaving(false);
}
}, [authFetch]);
useEffect(() => {
fetchPreferences();
}, [fetchPreferences]);
return {
preferences,
hasAIAccess,
subscription,
loading,
saving,
fetchPreferences,
savePreferences,
applyColorScheme,
};
};