feat: add CoopCredits Solana media rewards ecosystem

Add complete  token system with Plex/Tautulli/Overseer integration:
- Anchor program for SPL token mint/burn/transfer
- Express backend with OAuth, webhooks, Solana integration
- Next.js frontend with dashboard, admin panel, wallet management
- Docker deployment for 172.20.1.0/24 infrastructure
- Production configs with SSL, Nginx, health monitoring

Tautulli webhooks auto-mint  on watch events.
Overseer integration burns  for content requests.
This commit is contained in:
2026-04-14 11:09:50 -04:00
parent f106328f6a
commit e8d9b1fd42
69 changed files with 11382 additions and 0 deletions
+333
View File
@@ -0,0 +1,333 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useStore } from '@/lib/store';
import { adminApi } from '@/lib/api';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Users,
Settings,
Pause,
Play,
TrendingUp,
Search,
Gift
} from 'lucide-react';
import { formatNumber } from '@/lib/utils';
import { toast } from 'sonner';
interface Analytics {
users: {
total: number;
with_wallet: number;
new_this_week: number;
};
transactions: {
total_earned: number;
total_spent: number;
total_transactions: number;
};
watchStats: {
total_seconds: number;
total_credits: number;
total_events: number;
};
}
interface User {
id: string;
plexUsername: string;
email: string | null;
isAdmin: boolean;
isActive: boolean;
walletAddress: string | null;
totalEarned: number;
totalSpent: number;
watchTimeMinutes: number;
createdAt: string;
}
export default function AdminPage() {
const router = useRouter();
const { user, isAuthenticated } = useStore();
const [analytics, setAnalytics] = useState<Analytics | null>(null);
const [users, setUsers] = useState<User[]>([]);
const [settings, setSettings] = useState<any>(null);
const [isLoading, setIsLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
useEffect(() => {
if (!isAuthenticated) {
router.push('/login');
return;
}
if (!user?.isAdmin) {
router.push('/dashboard');
return;
}
loadData();
}, [isAuthenticated, user, router]);
const loadData = async () => {
try {
const [analyticsRes, usersRes, settingsRes] = await Promise.all([
adminApi.getAnalytics(),
adminApi.getUsers(),
adminApi.getSettings()
]);
setAnalytics(analyticsRes.data);
setUsers(usersRes.data.users);
setSettings(settingsRes.data);
} catch (error) {
toast.error('Failed to load admin data');
} finally {
setIsLoading(false);
}
};
const handlePause = async () => {
try {
await adminApi.pause();
toast.success('Minting paused');
loadData();
} catch (error) {
toast.error('Failed to pause minting');
}
};
const handleResume = async () => {
try {
await adminApi.resume();
toast.success('Minting resumed');
loadData();
} catch (error) {
toast.error('Failed to resume minting');
}
};
const handleGrantBonus = async (userId: string) => {
const amount = prompt('Enter bonus amount:');
if (!amount) return;
try {
await adminApi.grantBonus(userId, parseInt(amount), 'Admin bonus');
toast.success('Bonus granted');
loadData();
} catch (error) {
toast.error('Failed to grant bonus');
}
};
if (!isAuthenticated || !user?.isAdmin) {
return null;
}
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<p>Loading...</p>
</div>
);
}
return (
<div className="min-h-screen bg-background">
<header className="border-b bg-card">
<div className="max-w-7xl mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<h1 className="text-2xl font-bold">Admin Dashboard</h1>
<Badge variant="secondary">{user.plexUsername}</Badge>
</div>
<Button variant="ghost" onClick={() => router.push('/dashboard')}>
Back to Dashboard
</Button>
</div>
</header>
<main className="max-w-7xl mx-auto px-4 py-8">
{/* Stats Overview */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium">Total Users</CardTitle>
<Users className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{analytics?.users.total || 0}</div>
<p className="text-xs text-muted-foreground">
{analytics?.users.with_wallet || 0} with wallets
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium">Total Minted</CardTitle>
<TrendingUp className="h-4 w-4 text-green-500" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{formatNumber(analytics?.transactions.total_earned || 0)} $COOP
</div>
<p className="text-xs text-muted-foreground">
{analytics?.transactions.total_transactions || 0} transactions
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium">Watch Time</CardTitle>
<TrendingUp className="h-4 w-4 text-blue-500" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{Math.floor((analytics?.watchStats.total_seconds || 0) / 3600)}h
</div>
<p className="text-xs text-muted-foreground">
{analytics?.watchStats.total_events || 0} watch events
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium">System Status</CardTitle>
<Settings className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="flex items-center gap-2">
<div className={`w-2 h-2 rounded-full ${settings?.mintingPaused ? 'bg-red-500' : 'bg-green-500'}`} />
<span className="font-bold">
{settings?.mintingPaused ? 'Paused' : 'Active'}
</span>
</div>
<div className="flex gap-2 mt-2">
<Button size="sm" variant="outline" onClick={handlePause} disabled={settings?.mintingPaused}>
<Pause className="h-3 w-3 mr-1" />
Pause
</Button>
<Button size="sm" variant="outline" onClick={handleResume} disabled={!settings?.mintingPaused}>
<Play className="h-3 w-3 mr-1" />
Resume
</Button>
</div>
</CardContent>
</Card>
</div>
{/* Tabs */}
<Tabs defaultValue="users">
<TabsList>
<TabsTrigger value="users">Users</TabsTrigger>
<TabsTrigger value="settings">Settings</TabsTrigger>
</TabsList>
<TabsContent value="users" className="space-y-4">
<div className="flex gap-4">
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search users..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
/>
</div>
</div>
<Card>
<CardContent className="p-0">
<div className="divide-y">
{users.map((u) => (
<div key={u.id} className="flex items-center justify-between p-4">
<div>
<p className="font-medium">{u.plexUsername}</p>
<p className="text-sm text-muted-foreground">{u.email}</p>
<div className="flex gap-2 mt-1">
{u.isAdmin && <Badge variant="default">Admin</Badge>}
{!u.isActive && <Badge variant="destructive">Inactive</Badge>}
{u.walletAddress && <Badge variant="secondary">Wallet</Badge>}
</div>
</div>
<div className="text-right">
<p className="font-mono text-sm">
{formatNumber(u.totalEarned - u.totalSpent)} $COOP
</p>
<Button
size="sm"
variant="ghost"
onClick={() => handleGrantBonus(u.id)}
>
<Gift className="h-4 w-4 mr-1" />
Bonus
</Button>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="settings">
<Card>
<CardHeader>
<CardTitle>Minting Settings</CardTitle>
<CardDescription>Configure how users earn $COOP</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Credits Per Minute</Label>
<Input
type="number"
value={settings?.creditsPerMinute || 10}
onChange={(e) => setSettings({ ...settings, creditsPerMinute: parseInt(e.target.value) })}
/>
</div>
<div className="space-y-2">
<Label>Min Watch Percent</Label>
<Input
type="number"
value={settings?.minWatchPercent || 80}
onChange={(e) => setSettings({ ...settings, minWatchPercent: parseInt(e.target.value) })}
/>
</div>
<div className="space-y-2">
<Label>Movie Request Cost</Label>
<Input
type="number"
value={settings?.movieRequestCost || 100}
onChange={(e) => setSettings({ ...settings, movieRequestCost: parseInt(e.target.value) })}
/>
</div>
<div className="space-y-2">
<Label>TV Request Cost</Label>
<Input
type="number"
value={settings?.tvRequestCost || 200}
onChange={(e) => setSettings({ ...settings, tvRequestCost: parseInt(e.target.value) })}
/>
</div>
</div>
<Button onClick={() => adminApi.updateSettings(settings).then(() => toast.success('Settings saved'))}>
Save Settings
</Button>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</main>
</div>
);
}
@@ -0,0 +1,162 @@
'use client';
import { useState } from 'react';
import { walletApi } from '@/lib/api';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Copy, Check, AlertTriangle, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
interface CreateWalletModalProps {
open: boolean;
onClose: () => void;
onCreated: () => void;
}
export function CreateWalletModal({ open, onClose, onCreated }: CreateWalletModalProps) {
const [step, setStep] = useState<'create' | 'backup' | 'success'>('create');
const [privateKey, setPrivateKey] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [copied, setCopied] = useState(false);
const handleCreate = async () => {
setIsLoading(true);
try {
const response = await walletApi.createWallet();
setPrivateKey(response.data.privateKey || '');
setStep('backup');
toast.success('Wallet created successfully!');
onCreated();
} catch (error) {
toast.error('Failed to create wallet');
} finally {
setIsLoading(false);
}
};
const handleBackup = async () => {
try {
const response = await walletApi.backupWallet();
setPrivateKey(response.data.privateKey);
setStep('backup');
} catch (error) {
toast.error('Failed to get backup');
}
};
const copyToClipboard = () => {
navigator.clipboard.writeText(privateKey);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
toast.success('Copied to clipboard');
};
const handleClose = () => {
setStep('create');
setPrivateKey('');
setCopied(false);
onClose();
};
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>
{step === 'create' && 'Create Wallet'}
{step === 'backup' && 'Backup Your Wallet'}
{step === 'success' && 'Wallet Ready!'}
</DialogTitle>
<DialogDescription>
{step === 'create' && 'Create a new Solana wallet to store your $COOP tokens'}
{step === 'backup' && 'Save this private key securely. You will need it to recover your wallet.'}
{step === 'success' && 'Your wallet is ready to use!'}
</DialogDescription>
</DialogHeader>
{step === 'create' && (
<div className="space-y-4">
<Alert>
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
You will be shown a private key. Store it securely - it cannot be recovered!
</AlertDescription>
</Alert>
<Button onClick={handleCreate} disabled={isLoading} className="w-full">
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Creating...
</>
) : (
'Create New Wallet'
)}
</Button>
<div className="text-center">
<span className="text-sm text-muted-foreground">or</span>
</div>
<Button variant="outline" onClick={handleBackup} className="w-full">
Show Existing Backup
</Button>
</div>
)}
{step === 'backup' && (
<div className="space-y-4">
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
Never share this private key with anyone. Store it in a secure password manager.
</AlertDescription>
</Alert>
<div className="space-y-2">
<Label>Private Key</Label>
<div className="flex gap-2">
<Input
type="password"
value={privateKey}
readOnly
className="font-mono"
/>
<Button
size="icon"
variant="outline"
onClick={copyToClipboard}
>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
</div>
<Button onClick={() => setStep('success')} className="w-full">
I have saved my private key
</Button>
</div>
)}
{step === 'success' && (
<div className="space-y-4 text-center">
<div className="mx-auto w-12 h-12 bg-green-500/10 rounded-full flex items-center justify-center">
<Check className="h-6 w-6 text-green-500" />
</div>
<p className="text-muted-foreground">
Your wallet has been created and funded with 2 SOL for transaction fees.
Start watching content on Plex to earn $COOP!
</p>
<Button onClick={handleClose} className="w-full">
Start Earning
</Button>
</div>
)}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,139 @@
'use client';
import { useEffect, useState } from 'react';
import { transactionApi } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { formatNumber, formatDate } from '@/lib/utils';
import { TrendingUp, TrendingDown, Gift, ArrowRightLeft } from 'lucide-react';
interface Transaction {
id: string;
type: 'EARN' | 'SPEND' | 'BONUS' | 'ADJUSTMENT';
amount: number;
description: string | null;
contentTitle: string | null;
createdAt: string;
solanaSignature: string | null;
}
export function TransactionList() {
const [transactions, setTransactions] = useState<Transaction[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
loadTransactions();
}, []);
const loadTransactions = async () => {
try {
const response = await transactionApi.getTransactions();
setTransactions(response.data.transactions);
} catch (error) {
console.error('Failed to load transactions:', error);
} finally {
setIsLoading(false);
}
};
const getTransactionIcon = (type: string) => {
switch (type) {
case 'EARN':
return <TrendingUp className="h-4 w-4 text-green-500" />;
case 'SPEND':
return <TrendingDown className="h-4 w-4 text-red-500" />;
case 'BONUS':
return <Gift className="h-4 w-4 text-purple-500" />;
default:
return <ArrowRightLeft className="h-4 w-4 text-gray-500" />;
}
};
const getTransactionColor = (type: string) => {
switch (type) {
case 'EARN':
return 'bg-green-500/10 text-green-500';
case 'SPEND':
return 'bg-red-500/10 text-red-500';
case 'BONUS':
return 'bg-purple-500/10 text-purple-500';
default:
return 'bg-gray-500/10 text-gray-500';
}
};
if (isLoading) {
return (
<Card>
<CardContent className="py-8 text-center text-muted-foreground">
Loading transactions...
</CardContent>
</Card>
);
}
if (transactions.length === 0) {
return (
<Card>
<CardContent className="py-8 text-center text-muted-foreground">
No transactions yet. Start watching content to earn $COOP!
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle>Recent Transactions</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{transactions.map((tx) => (
<div
key={tx.id}
className="flex items-center justify-between p-4 rounded-lg bg-muted/50"
>
<div className="flex items-center gap-4">
<div className={`p-2 rounded-full ${getTransactionColor(tx.type)}`}>
{getTransactionIcon(tx.type)}
</div>
<div>
<p className="font-medium">
{tx.contentTitle || tx.description || tx.type}
</p>
<p className="text-sm text-muted-foreground">
{formatDate(tx.createdAt)}
</p>
{tx.solanaSignature && (
<a
href={`https://explorer.solana.com/tx/${tx.solanaSignature}?cluster=devnet`}
target="_blank"
rel="noopener noreferrer"
className="text-xs text-blue-500 hover:underline"
>
View on Explorer
</a>
)}
</div>
</div>
<div className="text-right">
<p className={`font-bold ${
tx.type === 'EARN' || tx.type === 'BONUS'
? 'text-green-500'
: 'text-red-500'
}`}>
{tx.type === 'EARN' || tx.type === 'BONUS' ? '+' : '-'}
{formatNumber(tx.amount)} $COOP
</p>
<Badge variant="outline" className="text-xs">
{tx.type}
</Badge>
</div>
</div>
))}
</div>
</CardContent>
</Card>
);
}
@@ -0,0 +1,123 @@
'use client';
import { useEffect, useState } from 'react';
import { userApi } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { formatDuration, formatDate, formatNumber } from '@/lib/utils';
import { Film, Tv, CheckCircle, XCircle, Clock } from 'lucide-react';
interface WatchEvent {
id: string;
contentType: string;
title: string;
grandparentTitle: string | null;
duration: number;
percentComplete: number;
creditsEarned: number;
isProcessed: boolean;
watchedAt: string;
}
export function WatchHistory() {
const [events, setEvents] = useState<WatchEvent[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
loadHistory();
}, []);
const loadHistory = async () => {
try {
const response = await userApi.getWatchHistory();
setEvents(response.data.events);
} catch (error) {
console.error('Failed to load watch history:', error);
} finally {
setIsLoading(false);
}
};
const getContentIcon = (type: string) => {
return type === 'movie' ? (
<Film className="h-4 w-4" />
) : (
<Tv className="h-4 w-4" />
);
};
if (isLoading) {
return (
<Card>
<CardContent className="py-8 text-center text-muted-foreground">
Loading watch history...
</CardContent>
</Card>
);
}
if (events.length === 0) {
return (
<Card>
<CardContent className="py-8 text-center text-muted-foreground">
No watch history yet. Start watching on Plex!
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle>Watch History</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{events.map((event) => (
<div
key={event.id}
className="flex items-center justify-between p-4 rounded-lg bg-muted/50"
>
<div className="flex items-center gap-4">
<div className="p-2 rounded-full bg-primary/10 text-primary">
{getContentIcon(event.contentType)}
</div>
<div>
<p className="font-medium">{event.title}</p>
{event.grandparentTitle && (
<p className="text-sm text-muted-foreground">
{event.grandparentTitle}
</p>
)}
<div className="flex items-center gap-4 mt-1 text-sm text-muted-foreground">
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{formatDuration(event.duration)}
</span>
<span>{event.percentComplete}% watched</span>
<span>{formatDate(event.watchedAt)}</span>
</div>
</div>
</div>
<div className="text-right">
{event.isProcessed ? (
<div className="flex items-center gap-2 text-green-500">
<CheckCircle className="h-4 w-4" />
<span className="font-bold">
+{formatNumber(event.creditsEarned)} $COOP
</span>
</div>
) : (
<div className="flex items-center gap-2 text-yellow-500">
<XCircle className="h-4 w-4" />
<span className="text-sm">Pending</span>
</div>
)}
</div>
</div>
))}
</div>
</CardContent>
</Card>
);
}
+232
View File
@@ -0,0 +1,232 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useStore } from '@/lib/store';
import { walletApi, transactionApi, overseerApi } from '@/lib/api';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Wallet,
TrendingUp,
TrendingDown,
Clock,
Film,
ExternalLink,
Plus,
History
} from 'lucide-react';
import { formatNumber, truncateAddress } from '@/lib/utils';
import { toast } from 'sonner';
import { TransactionList } from './components/TransactionList';
import { WatchHistory } from './components/WatchHistory';
import { CreateWalletModal } from './components/CreateWalletModal';
interface WalletData {
hasWallet: boolean;
address?: string;
balance: number;
totalEarned: number;
totalSpent: number;
explorerUrl?: string;
}
export default function DashboardPage() {
const router = useRouter();
const { user, isAuthenticated, logout } = useStore();
const [wallet, setWallet] = useState<WalletData | null>(null);
const [requestCosts, setRequestCosts] = useState({ movie: 100, tv: 200 });
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
if (!isAuthenticated) {
router.push('/login');
return;
}
loadData();
}, [isAuthenticated, router]);
const loadData = async () => {
try {
const [walletRes, costsRes] = await Promise.all([
walletApi.getWallet(),
overseerApi.getCosts().catch(() => ({ data: { movie: 100, tv: 200 } }))
]);
setWallet(walletRes.data);
setRequestCosts(costsRes.data);
} catch (error) {
toast.error('Failed to load wallet data');
} finally {
setIsLoading(false);
}
};
if (!isAuthenticated || !user) {
return null;
}
return (
<div className="min-h-screen bg-background">
{/* Header */}
<header className="border-b bg-card">
<div className="max-w-7xl mx-auto px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-4">
<h1 className="text-2xl font-bold">CoopCredits</h1>
<Badge variant="secondary">{user.plexUsername}</Badge>
{user.isAdmin && (
<Button variant="outline" size="sm" onClick={() => router.push('/admin')}>
Admin
</Button>
)}
</div>
<Button variant="ghost" onClick={logout}>
Sign Out
</Button>
</div>
</header>
<main className="max-w-7xl mx-auto px-4 py-8">
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium">Balance</CardTitle>
<Wallet className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{wallet ? formatNumber(wallet.balance) : '--'} $COOP
</div>
<p className="text-xs text-muted-foreground">
{wallet?.hasWallet ? 'Ready to spend' : 'Create wallet to start'}
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium">Total Earned</CardTitle>
<TrendingUp className="h-4 w-4 text-green-500" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{wallet ? formatNumber(wallet.totalEarned) : '--'} $COOP
</div>
<p className="text-xs text-muted-foreground">
From watching content
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium">Total Spent</CardTitle>
<TrendingDown className="h-4 w-4 text-red-500" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{wallet ? formatNumber(wallet.totalSpent) : '--'} $COOP
</div>
<p className="text-xs text-muted-foreground">
On content requests
</p>
</CardContent>
</Card>
<Card>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium">Request Cost</CardTitle>
<Film className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{requestCosts.movie} $COOP</div>
<p className="text-xs text-muted-foreground">
Per movie request
</p>
</CardContent>
</Card>
</div>
{/* Wallet Section */}
{!wallet?.hasWallet && (
<Card className="mb-8 border-dashed border-2">
<CardContent className="py-8 text-center">
<Wallet className="mx-auto h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-semibold mb-2">No Wallet Connected</h3>
<p className="text-muted-foreground mb-4">
Create a Solana wallet to start earning and spending $COOP tokens
</p>
<Button onClick={() => setIsCreateModalOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
Create Wallet
</Button>
</CardContent>
</Card>
)}
{wallet?.hasWallet && (
<Card className="mb-8">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Your Wallet
</CardTitle>
<CardDescription>
Manage your Solana wallet and $COOP tokens
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex items-center justify-between p-4 bg-muted rounded-lg">
<div>
<p className="text-sm text-muted-foreground">Address</p>
<p className="font-mono font-medium">
{truncateAddress(wallet.address!)}
</p>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => setIsCreateModalOpen(true)}>
<History className="mr-2 h-4 w-4" />
Backup
</Button>
<Button variant="outline" size="sm" asChild>
<a href={wallet.explorerUrl} target="_blank" rel="noopener noreferrer">
<ExternalLink className="mr-2 h-4 w-4" />
Explorer
</a>
</Button>
</div>
</div>
</CardContent>
</Card>
)}
{/* Tabs */}
<Tabs defaultValue="transactions" className="space-y-4">
<TabsList>
<TabsTrigger value="transactions">Transactions</TabsTrigger>
<TabsTrigger value="history">Watch History</TabsTrigger>
</TabsList>
<TabsContent value="transactions">
<TransactionList />
</TabsContent>
<TabsContent value="history">
<WatchHistory />
</TabsContent>
</Tabs>
</main>
<CreateWalletModal
open={isCreateModalOpen}
onClose={() => setIsCreateModalOpen(false)}
onCreated={loadData}
/>
</div>
);
}
+59
View File
@@ -0,0 +1,59 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 221.2 83.2% 53.3%;
--radius: 0.5rem;
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 217.2 91.2% 59.8%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 224.3 76.3% 48%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}
+29
View File
@@ -0,0 +1,29 @@
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
import { Providers } from '@/components/providers';
import { Toaster } from 'sonner';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: 'CoopCredits - Media Rewards',
description: 'Earn $COOP tokens for watching content on Plex',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" suppressHydrationWarning>
<body className={inter.className}>
<Providers>
{children}
<Toaster position="top-right" />
</Providers>
</body>
</html>
);
}
+101
View File
@@ -0,0 +1,101 @@
'use client';
import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { authApi } from '@/lib/api';
import { useStore } from '@/lib/store';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, Tv } from 'lucide-react';
import { toast } from 'sonner';
export default function LoginPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { setUser, setToken, isAuthenticated } = useStore();
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
// Check for Plex OAuth callback
const code = searchParams.get('code');
if (code) {
handlePlexCallback(code);
}
}, [searchParams]);
useEffect(() => {
if (isAuthenticated) {
router.push('/dashboard');
}
}, [isAuthenticated, router]);
const handlePlexCallback = async (code: string) => {
setIsLoading(true);
try {
const response = await authApi.plexCallback(code);
const { user, token } = response.data;
localStorage.setItem('token', token);
setUser(user);
setToken(token);
toast.success(`Welcome, ${user.plexUsername}!`);
router.push('/dashboard');
} catch (error) {
toast.error('Authentication failed');
console.error(error);
} finally {
setIsLoading(false);
}
};
const handlePlexLogin = async () => {
setIsLoading(true);
try {
const response = await authApi.getPlexUrl();
window.location.href = response.data.authUrl;
} catch (error) {
toast.error('Failed to initiate Plex login');
console.error(error);
setIsLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="mx-auto w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mb-4">
<Tv className="w-8 h-8 text-primary" />
</div>
<CardTitle className="text-2xl">CoopCredits</CardTitle>
<CardDescription>
Earn $COOP tokens for watching content on Plex
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={handlePlexLogin}
disabled={isLoading}
className="w-full h-12 text-lg"
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-5 w-5 animate-spin" />
Connecting...
</>
) : (
<>
<Tv className="mr-2 h-5 w-5" />
Sign in with Plex
</>
)}
</Button>
<p className="mt-4 text-center text-sm text-muted-foreground">
Sign in with your Plex account to start earning rewards
</p>
</CardContent>
</Card>
</div>
);
}
+39
View File
@@ -0,0 +1,39 @@
'use client';
import { ReactNode, useEffect, useState } from 'react';
import { ThemeProvider } from 'next-themes';
import { useStore } from '@/lib/store';
import { authApi } from '@/lib/api';
export function Providers({ children }: { children: ReactNode }) {
const [mounted, setMounted] = useState(false);
const { setUser, setToken } = useStore();
useEffect(() => {
setMounted(true);
// Check for stored token on mount
const token = localStorage.getItem('token');
if (token) {
// Verify token and get user data
authApi.verify()
.then((res) => {
setUser(res.data.user);
setToken(token);
})
.catch(() => {
localStorage.removeItem('token');
});
}
}, [setUser, setToken]);
if (!mounted) {
return <>{children}</>;
}
return (
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem>
{children}
</ThemeProvider>
);
}
+58
View File
@@ -0,0 +1,58 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const alertVariants = cva(
'relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground',
{
variants: {
variant: {
default: 'bg-background text-foreground',
destructive:
'border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive',
},
},
defaultVariants: {
variant: 'default',
},
}
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = 'Alert';
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn('mb-1 font-medium leading-none tracking-tight', className)}
{...props}
/>
));
AlertTitle.displayName = 'AlertTitle';
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('text-sm [&_p]:leading-relaxed', className)}
{...props}
/>
));
AlertDescription.displayName = 'AlertDescription';
export { Alert, AlertTitle, AlertDescription };
+35
View File
@@ -0,0 +1,35 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const badgeVariants = cva(
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
variants: {
variant: {
default:
'border-transparent bg-primary text-primary-foreground hover:bg-primary/80',
secondary:
'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
destructive:
'border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80',
outline: 'text-foreground',
},
},
defaultVariants: {
variant: 'default',
},
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };
+55
View File
@@ -0,0 +1,55 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const buttonVariants = cva(
'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive:
'bg-destructive text-destructive-foreground hover:bg-destructive/90',
outline:
'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
secondary:
'bg-secondary text-secondary-foreground hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-10 px-4 py-2',
sm: 'h-9 rounded-md px-3',
lg: 'h-11 rounded-md px-8',
icon: 'h-10 w-10',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button';
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
}
);
Button.displayName = 'Button';
export { Button, buttonVariants };
+78
View File
@@ -0,0 +1,78 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
'rounded-lg border bg-card text-card-foreground shadow-sm',
className
)}
{...props}
/>
));
Card.displayName = 'Card';
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex flex-col space-y-1.5 p-6', className)}
{...props}
/>
));
CardHeader.displayName = 'CardHeader';
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn(
'text-2xl font-semibold leading-none tracking-tight',
className
)}
{...props}
/>
));
CardTitle.displayName = 'CardTitle';
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
CardDescription.displayName = 'CardDescription';
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
));
CardContent.displayName = 'CardContent';
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex items-center p-6 pt-0', className)}
{...props}
/>
));
CardFooter.displayName = 'CardFooter';
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
+121
View File
@@ -0,0 +1,121 @@
'use client';
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-1.5 text-center sm:text-left',
className
)}
{...props}
/>
);
DialogHeader.displayName = 'DialogHeader';
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
className
)}
{...props}
/>
);
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
'text-lg font-semibold leading-none tracking-tight',
className
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
+24
View File
@@ -0,0 +1,24 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = 'Input';
export { Input };
+25
View File
@@ -0,0 +1,25 @@
'use client';
import * as React from 'react';
import * as LabelPrimitive from '@radix-ui/react-label';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const labelVariants = cva(
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };
+54
View File
@@ -0,0 +1,54 @@
'use client';
import * as React from 'react';
import * as TabsPrimitive from '@radix-ui/react-tabs';
import { cn } from '@/lib/utils';
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
'inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground',
className
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm',
className
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
'mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
className
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };
+98
View File
@@ -0,0 +1,98 @@
import axios from 'axios';
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
export const api = axios.create({
baseURL: `${API_URL}/api`,
headers: {
'Content-Type': 'application/json',
},
});
// Add auth token to requests
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Handle token expiration
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
// Auth API
export const authApi = {
getPlexUrl: () => api.get('/auth/plex/url'),
plexCallback: (code: string) => api.post('/auth/plex/callback', { code }),
verify: () => api.get('/auth/verify'),
logout: () => api.post('/auth/logout'),
};
// User API
export const userApi = {
getMe: () => api.get('/users/me'),
updateMe: (data: { email?: string }) => api.put('/users/me', data),
getWatchHistory: (page = 1, limit = 20) =>
api.get(`/users/me/watch-history?page=${page}&limit=${limit}`),
getRequests: (page = 1, limit = 20, status?: string) =>
api.get(`/users/me/requests?page=${page}&limit=${limit}${status ? `&status=${status}` : ''}`),
};
// Wallet API
export const walletApi = {
getWallet: () => api.get('/wallet'),
createWallet: () => api.post('/wallet/create'),
connectWallet: (address: string) => api.post('/wallet/connect', { address }),
backupWallet: () => api.post('/wallet/backup'),
};
// Transactions API
export const transactionApi = {
getTransactions: (page = 1, limit = 20, type?: string) =>
api.get(`/transactions?page=${page}&limit=${limit}${type ? `&type=${type}` : ''}`),
getStats: () => api.get('/transactions/stats'),
};
// Admin API
export const adminApi = {
getSettings: () => api.get('/admin/settings'),
updateSettings: (data: any) => api.put('/admin/settings', data),
pause: () => api.post('/admin/pause'),
resume: () => api.post('/admin/resume'),
getUsers: (page = 1, limit = 50, search?: string) =>
api.get(`/admin/users?page=${page}&limit=${limit}${search ? `&search=${search}` : ''}`),
updateUser: (id: string, data: any) => api.put(`/admin/users/${id}`, data),
grantBonus: (userId: string, amount: number, reason?: string) =>
api.post(`/admin/users/${userId}/bonus`, { amount, reason }),
getAnalytics: () => api.get('/admin/analytics'),
getAllTransactions: (page = 1, limit = 50) =>
api.get(`/transactions/admin/all?page=${page}&limit=${limit}`),
getSystemStats: () => api.get('/transactions/admin/stats'),
};
// Overseer API
export const overseerApi = {
getCosts: () => api.get('/overseer/costs'),
getBalance: () => api.get('/overseer/balance'),
search: (query: string) => api.get(`/overseer/search?query=${encodeURIComponent(query)}`),
request: (data: { mediaType: string; mediaId: number; title: string; seasons?: number[] }) =>
api.post('/overseer/request', data),
};
// Tautulli API
export const tautulliApi = {
getStatus: () => api.get('/tautulli/status'),
getStats: () => api.get('/tautulli/stats'),
getWebhookConfig: () => api.get('/tautulli/webhook-config'),
};
+42
View File
@@ -0,0 +1,42 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export interface User {
id: string;
plexId: string;
plexUsername: string;
email: string | null;
isAdmin: boolean;
walletAddress: string | null;
totalEarned: number;
totalSpent: number;
}
interface AppState {
user: User | null;
token: string | null;
isAuthenticated: boolean;
setUser: (user: User | null) => void;
setToken: (token: string | null) => void;
logout: () => void;
}
export const useStore = create<AppState>()(
persist(
(set) => ({
user: null,
token: null,
isAuthenticated: false,
setUser: (user) => set({ user, isAuthenticated: !!user }),
setToken: (token) => set({ token }),
logout: () => {
localStorage.removeItem('token');
set({ user: null, token: null, isAuthenticated: false });
},
}),
{
name: 'coop-credits-storage',
partialize: (state) => ({ user: state.user, token: state.token }),
}
)
);
+35
View File
@@ -0,0 +1,35 @@
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function formatNumber(num: number): string {
return new Intl.NumberFormat('en-US').format(num);
}
export function formatDate(date: string | Date): string {
return new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(date));
}
export function formatDuration(seconds: number): string {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
return `${minutes}m`;
}
export function truncateAddress(address: string, chars = 4): string {
if (!address) return '';
return `${address.slice(0, chars)}...${address.slice(-chars)}`;
}