mirror of
https://github.com/jjbrunton/Sauci.git
synced 2026-11-01 18:19:43 +00:00
Update
This commit is contained in:
1 parent
d18f9d32b0
commit
f7eaf0adcf
24 files changed
+1826
-393
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import { supabase } from '@/config';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -9,6 +9,8 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ArrowLeft, Check, CheckCheck, Eye } from 'lucide-react';
|
||||
import { format, isToday, isYesterday } from 'date-fns';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useRealtimeSubscription } from '@/hooks/useRealtimeSubscription';
|
||||
import { RealtimeStatusIndicator } from '@/components/RealtimeStatusIndicator';
|
||||
|
||||
interface Profile {
|
||||
id: string;
|
||||
@@ -123,6 +125,22 @@ export function MatchChatPage() {
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Real-time subscription for messages in this chat
|
||||
const { status: realtimeStatus } = useRealtimeSubscription<Message>({
|
||||
table: 'messages',
|
||||
filter: matchId ? `match_id=eq.${matchId}` : undefined,
|
||||
enabled: !!matchId,
|
||||
onInsert: useCallback((newMessage: Message) => {
|
||||
setMessages(prev => [...prev, newMessage]);
|
||||
}, []),
|
||||
onUpdate: useCallback(({ new: updated }: { old: Message; new: Message }) => {
|
||||
setMessages(prev => prev.map(m => m.id === updated.id ? updated : m));
|
||||
}, []),
|
||||
onDelete: useCallback((deleted: Message) => {
|
||||
setMessages(prev => prev.filter(m => m.id !== deleted.id));
|
||||
}, []),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
if (!userId || !matchId) return;
|
||||
@@ -221,6 +239,7 @@ export function MatchChatPage() {
|
||||
<Badge variant="secondary">
|
||||
{matchTypeLabels[match.match_type]}
|
||||
</Badge>
|
||||
<RealtimeStatusIndicator status={realtimeStatus} showLabel />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground line-clamp-1">
|
||||
{match.question?.text}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import { supabase } from '@/config';
|
||||
import { auditedSupabase } from '@/hooks/useAuditedSupabase';
|
||||
import { useRealtimeSubscription } from '@/hooks/useRealtimeSubscription';
|
||||
import { RealtimeStatusIndicator } from '@/components/RealtimeStatusIndicator';
|
||||
import { useAuth, PERMISSION_KEYS } from '@/contexts/AuthContext';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
@@ -216,54 +218,53 @@ export function UserDetailPage() {
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
if (!userId) return;
|
||||
const fetchData = useCallback(async () => {
|
||||
if (!userId) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
// Fetch profile
|
||||
const { data: profileData } = await supabase
|
||||
setLoading(true);
|
||||
try {
|
||||
// Fetch profile
|
||||
const { data: profileData } = await supabase
|
||||
.from('profiles')
|
||||
.select('*')
|
||||
.eq('id', userId)
|
||||
.single();
|
||||
|
||||
setProfile(profileData);
|
||||
|
||||
// Fetch partner if coupled
|
||||
if (profileData?.couple_id) {
|
||||
const { data: partnerData } = await supabase
|
||||
.from('profiles')
|
||||
.select('*')
|
||||
.eq('id', userId)
|
||||
.select('id, name')
|
||||
.eq('couple_id', profileData.couple_id)
|
||||
.neq('id', userId)
|
||||
.single();
|
||||
|
||||
setProfile(profileData);
|
||||
setPartner(partnerData);
|
||||
}
|
||||
|
||||
// Fetch partner if coupled
|
||||
if (profileData?.couple_id) {
|
||||
const { data: partnerData } = await supabase
|
||||
.from('profiles')
|
||||
.select('id, name')
|
||||
.eq('couple_id', profileData.couple_id)
|
||||
.neq('id', userId)
|
||||
.single();
|
||||
|
||||
setPartner(partnerData);
|
||||
}
|
||||
|
||||
// Fetch responses with question and pack info
|
||||
const { data: responseData } = await supabase
|
||||
.from('responses')
|
||||
.select(`
|
||||
// Fetch responses with question and pack info
|
||||
const { data: responseData } = await supabase
|
||||
.from('responses')
|
||||
.select(`
|
||||
id, answer, created_at,
|
||||
question:questions (
|
||||
id, text,
|
||||
pack:question_packs (name)
|
||||
)
|
||||
`)
|
||||
.eq('user_id', userId)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(50);
|
||||
.eq('user_id', userId)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(50);
|
||||
|
||||
setResponses((responseData || []) as unknown as Response[]);
|
||||
setResponses((responseData || []) as unknown as Response[]);
|
||||
|
||||
// Fetch matches if coupled
|
||||
if (profileData?.couple_id) {
|
||||
const { data: matchData } = await supabase
|
||||
.from('matches')
|
||||
.select(`
|
||||
// Fetch matches if coupled
|
||||
if (profileData?.couple_id) {
|
||||
const { data: matchData } = await supabase
|
||||
.from('matches')
|
||||
.select(`
|
||||
id, match_type, is_new, created_at,
|
||||
question:questions (id, text)
|
||||
`)
|
||||
@@ -271,60 +272,80 @@ export function UserDetailPage() {
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(50);
|
||||
|
||||
// Get message counts for each match
|
||||
const matchIds = (matchData || []).map(m => m.id);
|
||||
const { data: messages } = await supabase
|
||||
.from('messages')
|
||||
.select('match_id')
|
||||
.in('match_id', matchIds);
|
||||
// Get message counts for each match
|
||||
const matchIds = (matchData || []).map(m => m.id);
|
||||
const { data: messages } = await supabase
|
||||
.from('messages')
|
||||
.select('match_id')
|
||||
.in('match_id', matchIds);
|
||||
|
||||
const messageCounts: Record<string, number> = {};
|
||||
messages?.forEach(m => {
|
||||
messageCounts[m.match_id] = (messageCounts[m.match_id] || 0) + 1;
|
||||
});
|
||||
const messageCounts: Record<string, number> = {};
|
||||
messages?.forEach(m => {
|
||||
messageCounts[m.match_id] = (messageCounts[m.match_id] || 0) + 1;
|
||||
});
|
||||
|
||||
setMatches(
|
||||
(matchData || []).map(m => ({
|
||||
...m,
|
||||
message_count: messageCounts[m.id] || 0,
|
||||
})) 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 {
|
||||
setLoading(false);
|
||||
setMatches(
|
||||
(matchData || []).map(m => ({
|
||||
...m,
|
||||
message_count: messageCounts[m.id] || 0,
|
||||
})) as unknown as Match[]
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
// 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 {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [userId]);
|
||||
|
||||
// Real-time subscription for this user's profile
|
||||
const { status: profileStatus } = useRealtimeSubscription<Profile>({
|
||||
table: 'profiles',
|
||||
filter: userId ? `id=eq.${userId}` : undefined,
|
||||
enabled: !!userId,
|
||||
onUpdate: useCallback(({ new: updated }: { old: Profile; new: Profile }) => {
|
||||
setProfile(updated);
|
||||
}, []),
|
||||
});
|
||||
|
||||
// Real-time subscription for this user's responses
|
||||
const { status: responsesStatus } = useRealtimeSubscription<Response>({
|
||||
table: 'responses',
|
||||
filter: userId ? `user_id=eq.${userId}` : undefined,
|
||||
enabled: !!userId,
|
||||
onInsert: fetchData, // Refetch to get question/pack relations
|
||||
onDelete: fetchData,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -363,6 +384,10 @@ export function UserDetailPage() {
|
||||
<h1 className="text-2xl font-bold">
|
||||
{profile.name || 'Unnamed User'}
|
||||
</h1>
|
||||
<RealtimeStatusIndicator
|
||||
status={profileStatus === 'SUBSCRIBED' && responsesStatus === 'SUBSCRIBED' ? 'SUBSCRIBED' : profileStatus}
|
||||
showLabel
|
||||
/>
|
||||
{profile.is_premium && (
|
||||
<Badge className="bg-amber-500">
|
||||
<Crown className="h-3 w-3 mr-1" />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { supabase } from '@/config';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -6,6 +6,8 @@ import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { useRealtimeSubscription } from '@/hooks/useRealtimeSubscription';
|
||||
import { RealtimeStatusIndicator } from '@/components/RealtimeStatusIndicator';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -43,71 +45,94 @@ export function UsersPage() {
|
||||
const [search, setSearch] = useState('');
|
||||
const [filteredProfiles, setFilteredProfiles] = useState<Profile[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProfiles = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// Fetch profiles
|
||||
const { data: profilesData, error } = await supabase
|
||||
.from('profiles')
|
||||
.select('*')
|
||||
.order('created_at', { ascending: false });
|
||||
const fetchProfiles = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// Fetch profiles
|
||||
const { data: profilesData, error } = await supabase
|
||||
.from('profiles')
|
||||
.select('*')
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (error) throw error;
|
||||
if (error) throw error;
|
||||
|
||||
// Fetch storage usage per user from storage.objects
|
||||
const { data: storageData } = await supabase
|
||||
.rpc('get_user_storage_usage');
|
||||
// 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;
|
||||
// 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;
|
||||
});
|
||||
}
|
||||
|
||||
// Build a map of couple_id -> users with premium in that couple
|
||||
const couplePartners: Record<string, { id: string; is_premium: boolean }[]> = {};
|
||||
(profilesData || []).forEach(profile => {
|
||||
if (profile.couple_id) {
|
||||
if (!couplePartners[profile.couple_id]) {
|
||||
couplePartners[profile.couple_id] = [];
|
||||
}
|
||||
couplePartners[profile.couple_id].push({
|
||||
id: profile.id,
|
||||
is_premium: profile.is_premium || false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Build a map of couple_id -> users with premium in that couple
|
||||
const couplePartners: Record<string, { id: string; is_premium: boolean }[]> = {};
|
||||
(profilesData || []).forEach(profile => {
|
||||
if (profile.couple_id) {
|
||||
if (!couplePartners[profile.couple_id]) {
|
||||
couplePartners[profile.couple_id] = [];
|
||||
}
|
||||
couplePartners[profile.couple_id].push({
|
||||
id: profile.id,
|
||||
is_premium: profile.is_premium || false,
|
||||
});
|
||||
}
|
||||
});
|
||||
// Merge storage data and partner premium status with profiles
|
||||
const profilesWithExtras = (profilesData || []).map(profile => {
|
||||
// Check if partner has premium
|
||||
let partnerIsPremium = false;
|
||||
if (profile.couple_id && couplePartners[profile.couple_id]) {
|
||||
const partner = couplePartners[profile.couple_id].find(p => p.id !== profile.id);
|
||||
partnerIsPremium = partner?.is_premium || false;
|
||||
}
|
||||
return {
|
||||
...profile,
|
||||
storage_bytes: storageMap[profile.id] || 0,
|
||||
partner_is_premium: partnerIsPremium,
|
||||
};
|
||||
});
|
||||
|
||||
// Merge storage data and partner premium status with profiles
|
||||
const profilesWithExtras = (profilesData || []).map(profile => {
|
||||
// Check if partner has premium
|
||||
let partnerIsPremium = false;
|
||||
if (profile.couple_id && couplePartners[profile.couple_id]) {
|
||||
const partner = couplePartners[profile.couple_id].find(p => p.id !== profile.id);
|
||||
partnerIsPremium = partner?.is_premium || false;
|
||||
}
|
||||
return {
|
||||
...profile,
|
||||
storage_bytes: storageMap[profile.id] || 0,
|
||||
partner_is_premium: partnerIsPremium,
|
||||
};
|
||||
});
|
||||
|
||||
setProfiles(profilesWithExtras);
|
||||
setFilteredProfiles(profilesWithExtras);
|
||||
} catch (error) {
|
||||
console.error('Failed to load profiles:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchProfiles();
|
||||
setProfiles(profilesWithExtras);
|
||||
setFilteredProfiles(profilesWithExtras);
|
||||
} catch (error) {
|
||||
console.error('Failed to load profiles:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Real-time subscription for profiles table
|
||||
const { status: realtimeStatus } = useRealtimeSubscription<Profile>({
|
||||
table: 'profiles',
|
||||
onInsert: useCallback(() => {
|
||||
// Refetch to get storage and partner data
|
||||
fetchProfiles();
|
||||
}, [fetchProfiles]),
|
||||
onUpdate: useCallback(() => {
|
||||
// Refetch to update partner premium status
|
||||
fetchProfiles();
|
||||
}, [fetchProfiles]),
|
||||
onDelete: useCallback((deleted: Profile) => {
|
||||
setProfiles(prev => prev.filter(p => p.id !== deleted.id));
|
||||
setFilteredProfiles(prev => prev.filter(p => p.id !== deleted.id));
|
||||
}, []),
|
||||
insertToast: {
|
||||
enabled: true,
|
||||
message: (payload) => `New user registered: ${payload.name || payload.email || 'Unknown'}`,
|
||||
type: 'success',
|
||||
},
|
||||
debounceMs: 1000, // Debounce to avoid excessive refetches
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchProfiles();
|
||||
}, [fetchProfiles]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!search.trim()) {
|
||||
setFilteredProfiles(profiles);
|
||||
@@ -142,7 +167,10 @@ export function UsersPage() {
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Users</h1>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Users</h1>
|
||||
<RealtimeStatusIndicator status={realtimeStatus} showLabel />
|
||||
</div>
|
||||
<p className="text-muted-foreground">
|
||||
{profiles.length} registered user{profiles.length !== 1 ? 's' : ''}
|
||||
</p>
|
||||
|
||||
Reference in new issue
Block a user