This commit is contained in:
Jamie Brunton committed 2025-12-31 10:40:17 +00:00
1 parent 71667d6104
commit f46f0d59df
24 files changed
+2647 -516

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
# Admin Dashboard - Agent Guidelines
**STRICT RULES - DO NOT VIOLATE**
## Architecture
This is a React Admin dashboard using:
- **Build**: Vite
- **Routing**: react-router-dom with component-based routing in `App.tsx`
- **Styling**: Tailwind CSS
- **State**: React Context (`AuthContext`)
- **Backend**: Supabase client in `src/lib/supabase.ts`
## Directory Structure
```
src/
components/ # Reusable components
layout/ # AppLayout, Sidebar, etc.
ProtectedRoute.tsx # Route guard
contexts/ # React contexts (AuthContext)
hooks/ # Custom hooks
lib/ # Utilities (supabase)
pages/ # Page components
content/ # Categories, Packs, Questions
users/ # User management (super_admin only)
admins/ # Admin management (super_admin only)
```
## Critical Rules
### Authentication & Authorization
Two admin roles exist:
- `admin` - Content management only (categories, packs, questions)
- `super_admin` - Full access including user data, admins, audit logs
Use `<ProtectedRoute requireSuperAdmin>` for super_admin-only routes.
### Route Structure
```typescript
// Public
/login
// Protected (all admins)
/ # Dashboard
/categories # Category management
/categories/:id/packs # Packs in category
/packs/:id/questions # Questions in pack
// Protected (super_admin only)
/users # User list
/users/:id # User detail
/users/:id/matches/:id # Match chat view
/admins # Admin management
/audit-logs # Audit log viewer
```
### Supabase Queries
- **Always use `.maybeSingle()` instead of `.single()`** when the row might not exist
- All admin operations are audited - check `audit_logs` table structure
### UI Patterns
- Use Tailwind CSS for styling
- Follow existing component patterns in `src/components/`
- Use `AppLayout` wrapper for all protected pages
### Security
- Never expose user passwords or sensitive data in admin views
- Audit log all administrative actions
- Verify admin role before performing operations
## Forbidden Actions
1. **DO NOT** expose user passwords or auth tokens
2. **DO NOT** allow content admins to access user data
3. **DO NOT** bypass role checks in protected routes
4. **DO NOT** perform destructive operations without confirmation
5. **DO NOT** use `.single()` for queries that might return 0 rows
6. **DO NOT** skip audit logging for administrative actions
+124 -1
View File
@@ -34,7 +34,7 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Crown, Users, MessageCircle, ChevronRight, ThumbsUp, ThumbsDown, Minus, Gift } from 'lucide-react';
import { Crown, Users, MessageCircle, ChevronRight, ThumbsUp, ThumbsDown, Minus, Gift, Image, HardDrive, ExternalLink } from 'lucide-react';
import { format } from 'date-fns';
interface Profile {
@@ -77,6 +77,18 @@ interface Match {
message_count?: number;
}
interface MediaFile {
id: string;
name: string;
bucket_id: string;
created_at: string | null;
metadata: {
size: number;
mimetype: string;
};
signedUrl?: string;
}
const answerIcons = {
yes: <ThumbsUp className="h-4 w-4 text-green-500" />,
no: <ThumbsDown className="h-4 w-4 text-red-500" />,
@@ -89,12 +101,22 @@ const matchTypeLabels = {
maybe_maybe: 'Both Maybe',
};
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
export function UserDetailPage() {
const { userId } = useParams<{ userId: string }>();
const [profile, setProfile] = useState<Profile | null>(null);
const [partner, setPartner] = useState<Partner | null>(null);
const [responses, setResponses] = useState<Response[]>([]);
const [matches, setMatches] = useState<Match[]>([]);
const [media, setMedia] = useState<MediaFile[]>([]);
const [totalStorage, setTotalStorage] = useState(0);
const [loading, setLoading] = useState(true);
const [upgradeOpen, setUpgradeOpen] = useState(false);
@@ -239,6 +261,31 @@ export function UserDetailPage() {
})) as unknown as Match[]
);
}
// Fetch media files uploaded by this user
const { data: mediaData } = await supabase
.rpc('get_user_media_files', { user_id: userId });
if (mediaData && mediaData.length > 0) {
// Calculate total storage
const total = mediaData.reduce((sum: number, file: MediaFile) =>
sum + (file.metadata?.size || 0), 0);
setTotalStorage(total);
// Get signed URLs for each file
const mediaWithUrls = await Promise.all(
mediaData.map(async (file: MediaFile) => {
const { data: signedData } = await supabase.storage
.from('chat-media')
.createSignedUrl(file.name, 3600); // 1 hour expiry
return {
...file,
signedUrl: signedData?.signedUrl,
};
})
);
setMedia(mediaWithUrls);
}
} catch (error) {
console.error('Failed to load user data:', error);
} finally {
@@ -392,6 +439,9 @@ export function UserDetailPage() {
<TabsTrigger value="matches" disabled={!profile.couple_id}>
Matches ({matches.length})
</TabsTrigger>
<TabsTrigger value="media">
Media ({media.length})
</TabsTrigger>
</TabsList>
<TabsContent value="responses" className="mt-4">
@@ -479,6 +529,79 @@ export function UserDetailPage() {
</div>
)}
</TabsContent>
<TabsContent value="media" className="mt-4">
{media.length === 0 ? (
<Card className="flex flex-col items-center justify-center py-12">
<Image className="h-12 w-12 text-muted-foreground mb-4" />
<p className="text-muted-foreground">No media uploaded</p>
</Card>
) : (
<div className="space-y-4">
{/* Storage Summary */}
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-3">
<HardDrive className="h-5 w-5 text-muted-foreground" />
<div>
<p className="font-medium">Total Storage Used</p>
<p className="text-2xl font-bold">{formatBytes(totalStorage)}</p>
</div>
<div className="ml-auto text-sm text-muted-foreground">
{media.length} file{media.length !== 1 ? 's' : ''}
</div>
</div>
</CardContent>
</Card>
{/* Media Grid */}
<div className="grid gap-4 grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
{media.map((file) => (
<Card key={file.id} className="overflow-hidden">
<div className="aspect-square bg-muted relative">
{file.signedUrl ? (
<img
src={file.signedUrl}
alt={file.name}
className="w-full h-full object-cover"
onError={(e) => {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
) : (
<div className="w-full h-full flex items-center justify-center">
<Image className="h-8 w-8 text-muted-foreground" />
</div>
)}
</div>
<CardContent className="p-3">
<div className="flex items-center justify-between text-sm">
<div className="truncate text-muted-foreground">
{formatBytes(file.metadata?.size || 0)}
</div>
{file.signedUrl && (
<a
href={file.signedUrl}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline flex items-center gap-1"
>
<ExternalLink className="h-3 w-3" />
</a>
)}
</div>
<div className="text-xs text-muted-foreground mt-1">
{file.created_at
? format(new Date(file.created_at), 'MMM d, yyyy')
: '—'}
</div>
</CardContent>
</Card>
))}
</div>
</div>
)}
</TabsContent>
</Tabs>
</div>
);
+45 -5
View File
@@ -14,7 +14,7 @@ import {
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Search, Crown, Users, ChevronRight } from 'lucide-react';
import { Search, Crown, Users, ChevronRight, HardDrive } from 'lucide-react';
import { format } from 'date-fns';
interface Profile {
@@ -25,6 +25,15 @@ interface Profile {
is_premium: boolean | null;
couple_id: string | null;
created_at: string | null;
storage_bytes?: number;
}
function formatBytes(bytes: number): string {
if (bytes === 0) return '—';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
export function UsersPage() {
@@ -37,14 +46,34 @@ export function UsersPage() {
const fetchProfiles = async () => {
setLoading(true);
try {
const { data, error } = await supabase
// Fetch profiles
const { data: profilesData, error } = await supabase
.from('profiles')
.select('*')
.order('created_at', { ascending: false });
if (error) throw error;
setProfiles(data || []);
setFilteredProfiles(data || []);
// Fetch storage usage per user from storage.objects
const { data: storageData } = await supabase
.rpc('get_user_storage_usage');
// Create a map of user_id -> storage_bytes
const storageMap: Record<string, number> = {};
if (storageData) {
storageData.forEach((row: { owner: string; total_bytes: number }) => {
storageMap[row.owner] = row.total_bytes;
});
}
// Merge storage data with profiles
const profilesWithStorage = (profilesData || []).map(profile => ({
...profile,
storage_bytes: storageMap[profile.id] || 0,
}));
setProfiles(profilesWithStorage);
setFilteredProfiles(profilesWithStorage);
} catch (error) {
console.error('Failed to load profiles:', error);
} finally {
@@ -114,6 +143,7 @@ export function UsersPage() {
<TableHead>Email</TableHead>
<TableHead>Status</TableHead>
<TableHead>Couple</TableHead>
<TableHead>Storage</TableHead>
<TableHead>Joined</TableHead>
<TableHead className="w-12"></TableHead>
</TableRow>
@@ -121,7 +151,7 @@ export function UsersPage() {
<TableBody>
{filteredProfiles.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
<TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
{search ? 'No users found matching your search.' : 'No users yet.'}
</TableCell>
</TableRow>
@@ -166,6 +196,16 @@ export function UsersPage() {
<span className="text-muted-foreground text-sm">—</span>
)}
</TableCell>
<TableCell>
{profile.storage_bytes && profile.storage_bytes > 0 ? (
<div className="flex items-center gap-1 text-sm">
<HardDrive className="h-3 w-3 text-muted-foreground" />
{formatBytes(profile.storage_bytes)}
</div>
) : (
<span className="text-muted-foreground text-sm">—</span>
)}
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{profile.created_at
? format(new Date(profile.created_at), 'MMM d, yyyy')