Add message reporting and account deletion

- Add user message reporting via long press menu
- Add delete-account edge function for App Store compliance
- Update admin moderation page with AI/User tabs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Jamie BruntonandClaude Opus 4.5 committed 2026-01-07 13:24:30 +00:00
1 parent 314745c6cb
commit 693ae59321
14 files changed
+1455 -83

No files matched your search

+3
View File
@@ -100,6 +100,8 @@ When using Claude Code with MCP tools:
Edge functions in `apps/supabase/functions/` handle complex operations:
- `submit-response` - Saves response, checks for matches, triggers notifications
- `manage-couple` - Join/leave couple operations
- `delete-relationship` - Deletes couple data (matches, messages, media) while keeping accounts
- `delete-account` - Permanently deletes user account and all associated data (Apple App Store requirement)
- `send-notification` - Push notifications for matches
- `revenuecat-webhook` - Subscription webhook handler
- `sync-subscription` - Syncs RevenueCat subscription status
@@ -127,6 +129,7 @@ This approach:
| `submit-response` | false | Manual via getUser() |
| `sync-subscription` | false | Manual via getUser() |
| `delete-relationship` | false | Manual via getUser() |
| `delete-account` | false | Manual via getUser() |
| `redeem-code` | false | Manual via getUser() |
| `revenuecat-webhook` | false | Webhook signature validation |
| `send-notification` | false | Internal trigger (no auth) |
+393 -30
View File
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Table,
TableBody,
@@ -13,7 +14,7 @@ import {
TableRow,
} from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { CheckCircle, Eye, RefreshCw, MessageSquare, Sparkles } from 'lucide-react';
import { CheckCircle, Eye, RefreshCw, MessageSquare, Sparkles, Flag, AlertTriangle, XCircle } from 'lucide-react';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { describeImage } from '@/lib/ai/analyzers/media';
@@ -30,21 +31,59 @@ interface FlaggedMessage {
media_type?: string;
}
interface UserReport {
id: string;
message_id: string;
reporter_id: string;
reason: string;
status: 'pending' | 'reviewed' | 'dismissed';
created_at: string;
message: {
id: string;
user_id: string;
match_id: string | null;
content: string | null;
media_path: string | null;
media_type: string | null;
} | null;
reporter_profile: {
name: string | null;
email: string | null;
} | null;
}
const REASON_LABELS: Record<string, string> = {
harassment: 'Harassment',
spam: 'Spam',
inappropriate_content: 'Inappropriate Content',
other: 'Other',
};
export function FlaggedMessagesPage() {
const navigate = useNavigate();
const [messages, setMessages] = useState<FlaggedMessage[]>([]);
const [loading, setLoading] = useState(true);
// AI Flagged state
const [aiMessages, setAiMessages] = useState<FlaggedMessage[]>([]);
const [aiLoading, setAiLoading] = useState(true);
// User Reports state
const [userReports, setUserReports] = useState<UserReport[]>([]);
const [reportsLoading, setReportsLoading] = useState(true);
// Shared state
const [selectedMessage, setSelectedMessage] = useState<FlaggedMessage | null>(null);
const [selectedReport, setSelectedReport] = useState<UserReport | null>(null);
const [decryptedContent, setDecryptedContent] = useState<{ text: string | null; mediaUrl: string | null }>({ text: null, mediaUrl: null });
const [decrypting, setDecrypting] = useState(false);
const [processing, setProcessing] = useState<string | null>(null); // messageId being processed
const [processing, setProcessing] = useState<string | null>(null);
const [imageDescription, setImageDescription] = useState<string | null>(null);
const [describing, setDescribing] = useState(false);
const [inlineDescriptions, setInlineDescriptions] = useState<Record<string, string>>({});
const [describingInline, setDescribingInline] = useState<string | null>(null);
const fetchMessages = async () => {
setLoading(true);
// Fetch AI flagged messages
const fetchAiMessages = async () => {
setAiLoading(true);
try {
const { data, error } = await supabase
.from('messages')
@@ -53,17 +92,47 @@ export function FlaggedMessagesPage() {
.order('created_at', { ascending: false });
if (error) throw error;
setMessages(data || []);
setAiMessages(data || []);
} catch (error) {
console.error('Failed to load flagged messages:', error);
toast.error('Failed to load messages');
} finally {
setLoading(false);
setAiLoading(false);
}
};
// Fetch user reports
const fetchUserReports = async () => {
setReportsLoading(true);
try {
const { data, error } = await supabase
.from('message_reports')
.select(`
id,
message_id,
reporter_id,
reason,
status,
created_at,
message:messages(id, user_id, match_id, content, media_path, media_type),
reporter_profile:profiles!reporter_id(name, email)
`)
.eq('status', 'pending')
.order('created_at', { ascending: false });
if (error) throw error;
setUserReports((data || []) as unknown as UserReport[]);
} catch (error) {
console.error('Failed to load user reports:', error);
toast.error('Failed to load reports');
} finally {
setReportsLoading(false);
}
};
useEffect(() => {
fetchMessages();
fetchAiMessages();
fetchUserReports();
}, []);
// Custom media fetcher because supabase.functions.invoke is JSON-centric
@@ -91,14 +160,14 @@ export function FlaggedMessagesPage() {
}
};
const handleView = async (message: FlaggedMessage) => {
const handleViewAiMessage = async (message: FlaggedMessage) => {
setSelectedMessage(message);
setSelectedReport(null);
setDecrypting(true);
setDecryptedContent({ text: null, mediaUrl: null });
setImageDescription(null);
try {
// Text
const { data: textData, error: textError } = await supabase.functions.invoke('admin-decrypt-message', {
body: { messageId: message.id }
});
@@ -120,6 +189,40 @@ export function FlaggedMessagesPage() {
}
};
const handleViewReport = async (report: UserReport) => {
if (!report.message) {
toast.error('Message no longer exists');
return;
}
setSelectedReport(report);
setSelectedMessage(null);
setDecrypting(true);
setDecryptedContent({ text: null, mediaUrl: null });
setImageDescription(null);
try {
const { data: textData, error: textError } = await supabase.functions.invoke('admin-decrypt-message', {
body: { messageId: report.message.id }
});
let mediaUrl = null;
if (report.message.media_path) {
mediaUrl = await fetchDecryptedMedia(report.message.id);
}
setDecryptedContent({
text: textData?.content || (textError ? 'Error decrypting text' : null),
mediaUrl
});
} catch (e) {
toast.error("Error loading content");
} finally {
setDecrypting(false);
}
};
const handleDescribeImage = async () => {
if (!decryptedContent.mediaUrl) return;
@@ -140,7 +243,6 @@ export function FlaggedMessagesPage() {
setDescribingInline(message.id);
try {
// First fetch the decrypted media as blob
const { data: { session } } = await supabase.auth.getSession();
if (!session) {
toast.error('Not authenticated');
@@ -161,13 +263,11 @@ export function FlaggedMessagesPage() {
return;
}
// Convert blob to base64
const blob = await response.blob();
const base64 = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const result = reader.result as string;
// Extract base64 part from data URL
const base64Data = result.split(',')[1];
resolve(base64Data);
};
@@ -175,7 +275,6 @@ export function FlaggedMessagesPage() {
reader.readAsDataURL(blob);
});
// Then describe it
const description = await describeImage(base64);
setInlineDescriptions(prev => ({ ...prev, [message.id]: description }));
} catch (error) {
@@ -197,7 +296,7 @@ export function FlaggedMessagesPage() {
if (error) throw error;
toast.success('Message marked as safe');
setMessages(prev => prev.filter(m => m.id !== messageId));
setAiMessages(prev => prev.filter(m => m.id !== messageId));
if (selectedMessage?.id === messageId) setSelectedMessage(null);
} catch (error) {
toast.error('Failed to update status');
@@ -206,25 +305,95 @@ export function FlaggedMessagesPage() {
}
};
const handleDismissReport = async (reportId: string) => {
setProcessing(reportId);
try {
const { error } = await supabase
.from('message_reports')
.update({ status: 'dismissed', reviewed_at: new Date().toISOString() })
.eq('id', reportId);
if (error) throw error;
toast.success('Report dismissed');
setUserReports(prev => prev.filter(r => r.id !== reportId));
if (selectedReport?.id === reportId) setSelectedReport(null);
} catch (error) {
toast.error('Failed to dismiss report');
} finally {
setProcessing(null);
}
};
const handleReviewReport = async (reportId: string) => {
setProcessing(reportId);
try {
const { error } = await supabase
.from('message_reports')
.update({ status: 'reviewed', reviewed_at: new Date().toISOString() })
.eq('id', reportId);
if (error) throw error;
toast.success('Report marked as reviewed');
setUserReports(prev => prev.filter(r => r.id !== reportId));
if (selectedReport?.id === reportId) setSelectedReport(null);
} catch (error) {
toast.error('Failed to update report');
} finally {
setProcessing(null);
}
};
const handleJumpToChat = () => {
if (!selectedMessage || !selectedMessage.match_id) {
const matchId = selectedMessage?.match_id || selectedReport?.message?.match_id;
const userId = selectedMessage?.user_id || selectedReport?.message?.user_id;
if (!matchId) {
toast.error("No match context available");
return;
}
navigate(`/users/${selectedMessage.user_id}/matches/${selectedMessage.match_id}`);
navigate(`/users/${userId}/matches/${matchId}`);
};
const closeDialogs = () => {
setSelectedMessage(null);
setSelectedReport(null);
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Flagged Messages</h1>
<h1 className="text-3xl font-bold tracking-tight">Content Moderation</h1>
<p className="text-muted-foreground">
Review content flagged by AI moderation
Review AI-flagged content and user reports
</p>
</div>
<Button variant="outline" onClick={fetchMessages} disabled={loading}>
<RefreshCw className={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
</div>
<Tabs defaultValue="ai-flagged" className="w-full">
<TabsList>
<TabsTrigger value="ai-flagged" className="gap-2">
<AlertTriangle className="h-4 w-4" />
AI Flagged
{aiMessages.length > 0 && (
<Badge variant="secondary" className="ml-1">{aiMessages.length}</Badge>
)}
</TabsTrigger>
<TabsTrigger value="user-reports" className="gap-2">
<Flag className="h-4 w-4" />
User Reports
{userReports.length > 0 && (
<Badge variant="secondary" className="ml-1">{userReports.length}</Badge>
)}
</TabsTrigger>
</TabsList>
<TabsContent value="ai-flagged" className="space-y-4">
<div className="flex justify-end">
<Button variant="outline" onClick={fetchAiMessages} disabled={aiLoading}>
<RefreshCw className={`h-4 w-4 mr-2 ${aiLoading ? 'animate-spin' : ''}`} />
Refresh
</Button>
</div>
@@ -240,17 +409,17 @@ export function FlaggedMessagesPage() {
</TableRow>
</TableHeader>
<TableBody>
{messages.length === 0 ? (
{aiMessages.length === 0 ? (
<TableRow>
<TableCell colSpan={4} className="text-center py-8 text-muted-foreground">
<div className="flex flex-col items-center gap-2">
<CheckCircle className="h-8 w-8 text-green-500/50" />
<p>No flagged messages found. Good job!</p>
<p>No AI-flagged messages found. Good job!</p>
</div>
</TableCell>
</TableRow>
) : (
messages.map((message) => (
aiMessages.map((message) => (
<React.Fragment key={message.id}>
<TableRow>
<TableCell className="font-mono text-sm">
@@ -272,7 +441,7 @@ export function FlaggedMessagesPage() {
<Button
variant="ghost"
size="sm"
onClick={() => handleView(message)}
onClick={() => handleViewAiMessage(message)}
>
<Eye className="h-4 w-4 mr-2" />
Review
@@ -322,11 +491,102 @@ export function FlaggedMessagesPage() {
</TableBody>
</Table>
</Card>
</TabsContent>
<Dialog open={!!selectedMessage} onOpenChange={(open) => !open && setSelectedMessage(null)}>
<TabsContent value="user-reports" className="space-y-4">
<div className="flex justify-end">
<Button variant="outline" onClick={fetchUserReports} disabled={reportsLoading}>
<RefreshCw className={`h-4 w-4 mr-2 ${reportsLoading ? 'animate-spin' : ''}`} />
Refresh
</Button>
</div>
<Card>
<Table>
<TableHeader>
<TableRow>
<TableHead>Time</TableHead>
<TableHead>Reporter</TableHead>
<TableHead>Reason</TableHead>
<TableHead>Type</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{userReports.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
<div className="flex flex-col items-center gap-2">
<CheckCircle className="h-8 w-8 text-green-500/50" />
<p>No pending user reports. All clear!</p>
</div>
</TableCell>
</TableRow>
) : (
userReports.map((report) => (
<TableRow key={report.id}>
<TableCell className="font-mono text-sm">
{format(new Date(report.created_at), 'MMM d, HH:mm')}
</TableCell>
<TableCell className="text-sm">
{report.reporter_profile?.name || report.reporter_profile?.email || 'Unknown'}
</TableCell>
<TableCell>
<Badge variant="outline" className="bg-orange-500/10 text-orange-600 border-orange-200">
{REASON_LABELS[report.reason] || report.reason}
</Badge>
</TableCell>
<TableCell>
{report.message?.media_path ? (
<Badge variant="outline">{report.message.media_type || 'Media'}</Badge>
) : (
<Badge variant="secondary">Text</Badge>
)}
</TableCell>
<TableCell className="text-right space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => handleViewReport(report)}
>
<Eye className="h-4 w-4 mr-2" />
Review
</Button>
<Button
variant="outline"
size="sm"
className="text-orange-600 hover:text-orange-700 hover:bg-orange-50"
onClick={() => handleDismissReport(report.id)}
disabled={processing === report.id}
>
<XCircle className="h-4 w-4 mr-2" />
Dismiss
</Button>
<Button
variant="outline"
size="sm"
className="text-green-600 hover:text-green-700 hover:bg-green-50"
onClick={() => handleReviewReport(report.id)}
disabled={processing === report.id}
>
<CheckCircle className="h-4 w-4 mr-2" />
Mark Reviewed
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</Card>
</TabsContent>
</Tabs>
{/* Review Dialog - AI Flagged Messages */}
<Dialog open={!!selectedMessage} onOpenChange={(open) => !open && closeDialogs()}>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle>Review Content</DialogTitle>
<DialogTitle>Review AI Flagged Content</DialogTitle>
<DialogDescription>
Decrypted content for review. Flagged for: {selectedMessage?.flag_reason}
</DialogDescription>
@@ -405,7 +665,7 @@ export function FlaggedMessagesPage() {
</Button>
</div>
<div className="flex gap-2">
<Button variant="ghost" onClick={() => setSelectedMessage(null)}>Cancel</Button>
<Button variant="ghost" onClick={closeDialogs}>Cancel</Button>
<Button
className="bg-green-600 hover:bg-green-700"
onClick={() => selectedMessage && handleMarkSafe(selectedMessage.id)}
@@ -416,7 +676,110 @@ export function FlaggedMessagesPage() {
</DialogFooter>
</DialogContent>
</Dialog>
{/* Review Dialog - User Reports */}
<Dialog open={!!selectedReport} onOpenChange={(open) => !open && closeDialogs()}>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle>Review User Report</DialogTitle>
<DialogDescription>
Reported by: {selectedReport?.reporter_profile?.name || selectedReport?.reporter_profile?.email || 'Unknown'}
<br />
Reason: {selectedReport?.reason ? (REASON_LABELS[selectedReport.reason] || selectedReport.reason) : 'Unknown'}
</DialogDescription>
</DialogHeader>
<div className="min-h-[200px] bg-muted/30 rounded-md p-4 flex flex-col gap-4">
{decrypting ? (
<div className="flex flex-col items-center gap-2 text-muted-foreground py-8">
<RefreshCw className="h-6 w-6 animate-spin" />
<p className="text-sm">Decrypting secure content...</p>
</div>
) : (
<div className="w-full space-y-4">
{decryptedContent.text && (
<div className="space-y-2">
<h4 className="text-sm font-medium text-muted-foreground">Message Text</h4>
<div className="bg-background border rounded p-3 text-sm whitespace-pre-wrap">
{decryptedContent.text}
</div>
</div>
)}
{decryptedContent.mediaUrl && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium text-muted-foreground">Media Content</h4>
{selectedReport?.message?.media_type !== 'video' && (
<Button
variant="secondary"
size="sm"
onClick={handleDescribeImage}
disabled={describing}
>
{describing ? (
<RefreshCw className="h-3 w-3 mr-2 animate-spin" />
) : (
<Sparkles className="h-3 w-3 mr-2" />
)}
Describe Image
</Button>
)}
</div>
<div className="flex justify-center bg-black/5 rounded-lg overflow-hidden border">
{selectedReport?.message?.media_type === 'video' ? (
<video src={decryptedContent.mediaUrl} controls className="max-h-[400px] w-full object-contain" />
) : (
<img src={decryptedContent.mediaUrl} alt="Reported content" className="max-h-[400px] w-full object-contain" />
)}
</div>
{imageDescription && (
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-md p-3">
<h5 className="text-xs font-semibold text-blue-700 dark:text-blue-300 mb-1 flex items-center">
<Sparkles className="h-3 w-3 mr-1" />
AI Description
</h5>
<p className="text-sm text-blue-800 dark:text-blue-200">{imageDescription}</p>
</div>
)}
</div>
)}
{!decryptedContent.text && !decryptedContent.mediaUrl && (
<p className="text-center text-muted-foreground py-8">No content displayed</p>
)}
</div>
)}
</div>
<DialogFooter className="gap-2 sm:justify-between">
<div className="flex gap-2">
<Button variant="outline" onClick={handleJumpToChat}>
<MessageSquare className="h-4 w-4 mr-2" />
Jump to Chat
</Button>
</div>
<div className="flex gap-2">
<Button variant="ghost" onClick={closeDialogs}>Cancel</Button>
<Button
variant="outline"
className="text-orange-600 hover:text-orange-700 hover:bg-orange-50"
onClick={() => selectedReport && handleDismissReport(selectedReport.id)}
>
Dismiss
</Button>
<Button
className="bg-green-600 hover:bg-green-700"
onClick={() => selectedReport && handleReviewReport(selectedReport.id)}
>
Mark Reviewed
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+141
View File
@@ -27,6 +27,147 @@
"NSPhotoLibraryUsageDescription": "Sauci uses your photo library so you can select photos and videos to share privately with your partner in encrypted chat messages.",
"NSPhotoLibraryAddUsageDescription": "Sauci saves photos and videos from your partner's messages to your photo library when you tap the save button.",
"NSMicrophoneUsageDescription": "Sauci uses your microphone to record audio when you capture videos to share privately with your partner."
},
"privacyManifest": {
"NSPrivacyTracking": false,
"NSPrivacyCollectedDataTypes": [
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeEmailAddress",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeName",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeSensitiveInfo",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality",
"NSPrivacyCollectedDataTypePurposeProductPersonalization"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeUserID",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality",
"NSPrivacyCollectedDataTypePurposeAnalytics"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeDeviceID",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypePhotosorVideos",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeAudioData",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeOtherUserContent",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeProductInteraction",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAnalytics"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeCrashData",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAnalytics"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypePerformanceData",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAnalytics"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypeOtherDiagnosticData",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAnalytics"
]
},
{
"NSPrivacyCollectedDataType": "NSPrivacyCollectedDataTypePurchaseHistory",
"NSPrivacyCollectedDataTypeLinked": true,
"NSPrivacyCollectedDataTypeTracking": false,
"NSPrivacyCollectedDataTypePurposes": [
"NSPrivacyCollectedDataTypePurposeAppFunctionality"
]
}
],
"NSPrivacyAccessedAPITypes": [
{
"NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryFileTimestamp",
"NSPrivacyAccessedAPITypeReasons": [
"C617.1",
"0A2A.1",
"3B52.1"
]
},
{
"NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryUserDefaults",
"NSPrivacyAccessedAPITypeReasons": [
"CA92.1",
"C56D.1"
]
},
{
"NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategoryDiskSpace",
"NSPrivacyAccessedAPITypeReasons": [
"E174.1",
"85F4.1"
]
},
{
"NSPrivacyAccessedAPIType": "NSPrivacyAccessedAPICategorySystemBootTime",
"NSPrivacyAccessedAPITypeReasons": [
"35F9.1"
]
}
]
}
},
"android": {
+57 -4
View File
@@ -9,9 +9,10 @@ import { Ionicons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";
import Animated, { FadeInDown, useAnimatedStyle } from "react-native-reanimated";
import { InputBar, ChatHeader, ChatMessages } from "./components";
import { InputBar, ChatHeader, ChatMessages, ReportMessageSheet } from "./components";
import { useMediaUpload } from "./hooks/useMediaUpload";
import { useMessageActions } from "./hooks/useMessageActions";
import type { ReportReason } from "./types";
import { supabase } from "../../lib/supabase";
import { useAuthStore, useMessageStore } from "../../store";
@@ -42,6 +43,7 @@ export const ChatScreen: React.FC = () => {
const [fullScreenImage, setFullScreenImage] = useState<string | null>(null);
const [fullScreenImageLoading, setFullScreenImageLoading] = useState(true);
const [fullScreenVideo, setFullScreenVideo] = useState<string | null>(null);
const [reportingMessage, setReportingMessage] = useState<Message | null>(null);
// Ambient orb breathing animations
const { orbStyle1, orbStyle2 } = useAmbientOrbAnimation({
@@ -75,16 +77,60 @@ export const ChatScreen: React.FC = () => {
// E2EE encryption hook for sending messages
const { encryptMessage, isE2EEAvailable } = useEncryptedSend();
// Message actions hook for deletion
const { showDeleteOptions } = useMessageActions({ userId: user?.id });
// Message actions hook for deletion and reporting
const { showDeleteOptions, deleteForSelf } = useMessageActions({
userId: user?.id,
onReport: (message) => setReportingMessage(message),
});
// Handle long press on message to show delete options
// Handle long press on message to show options
const handleMessageLongPress = useCallback((message: Message, isMe: boolean) => {
// Don't show options for already deleted messages
if (message.deleted_at) return;
showDeleteOptions(message, isMe);
}, [showDeleteOptions]);
// Handle report submission
const handleSubmitReport = async (reason: ReportReason) => {
if (!reportingMessage || !user?.id) return;
try {
// Insert the report
const { error: reportError } = await supabase
.from('message_reports')
.insert({
message_id: reportingMessage.id,
reporter_id: user.id,
reason: reason,
});
if (reportError) {
if (reportError.code === '23505') {
// Unique violation - already reported
Alert.alert('Already Reported', 'You have already reported this message.');
} else {
console.error('Report error:', reportError);
Alert.alert('Error', 'Failed to submit report');
}
setReportingMessage(null);
return;
}
// Also delete the message for the reporter (so they don't see it anymore)
await deleteForSelf(reportingMessage.id);
// Remove from local state
setMessages(prev => prev.filter(m => m.id !== reportingMessage.id));
Alert.alert('Report Submitted', 'Thank you for your report. We will review it shortly.');
setReportingMessage(null);
} catch (err) {
console.error('Report error:', err);
Alert.alert('Error', 'Failed to submit report');
setReportingMessage(null);
}
};
// Track active chat to prevent notifications for current chat
useFocusEffect(
useCallback(() => {
@@ -436,6 +482,13 @@ export const ChatScreen: React.FC = () => {
)}
</View>
</Modal>
{/* Report Message Sheet */}
<ReportMessageSheet
visible={reportingMessage !== null}
onClose={() => setReportingMessage(null)}
onSubmit={handleSubmitReport}
/>
</GradientBackground>
);
};
@@ -0,0 +1,297 @@
import { useState, useEffect } from "react";
import {
View,
Text,
StyleSheet,
Modal,
TouchableOpacity,
TouchableWithoutFeedback,
ActivityIndicator,
Platform,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { BlurView } from "expo-blur";
import Animated, { FadeIn, FadeOut, SlideInDown, SlideOutDown } from "react-native-reanimated";
import { colors, spacing, typography, radius } from "../../../theme";
import { REPORT_REASONS, type ReportReason } from "../types";
interface ReportMessageSheetProps {
visible: boolean;
onClose: () => void;
onSubmit: (reason: ReportReason) => Promise<void>;
}
export function ReportMessageSheet({ visible, onClose, onSubmit }: ReportMessageSheetProps) {
const [selectedReason, setSelectedReason] = useState<ReportReason | null>(null);
const [isLoading, setIsLoading] = useState(false);
// Reset state when modal closes
useEffect(() => {
if (!visible) {
setSelectedReason(null);
setIsLoading(false);
}
}, [visible]);
const handleSubmit = async () => {
if (!selectedReason || isLoading) return;
setIsLoading(true);
await onSubmit(selectedReason);
setIsLoading(false);
};
const ReasonButton = ({ reason }: { reason: typeof REPORT_REASONS[number] }) => {
const isSelected = selectedReason === reason.value;
return (
<TouchableOpacity
style={[
styles.reasonButton,
isSelected && styles.reasonButtonSelected,
]}
onPress={() => setSelectedReason(reason.value)}
disabled={isLoading}
activeOpacity={0.7}
>
<View style={styles.reasonContent}>
<View style={[styles.radioOuter, isSelected && styles.radioOuterSelected]}>
{isSelected && <View style={styles.radioInner} />}
</View>
<Text style={[styles.reasonText, isSelected && styles.reasonTextSelected]}>
{reason.label}
</Text>
</View>
</TouchableOpacity>
);
};
return (
<Modal
visible={visible}
transparent
animationType="none"
onRequestClose={onClose}
statusBarTranslucent
>
<Animated.View style={styles.overlay} entering={FadeIn.duration(200)} exiting={FadeOut.duration(200)}>
<TouchableWithoutFeedback onPress={onClose}>
<View style={styles.backdrop} />
</TouchableWithoutFeedback>
<Animated.View
style={styles.sheetContainer}
entering={SlideInDown.springify().damping(20)}
exiting={SlideOutDown.duration(200)}
>
{Platform.OS === "ios" ? (
<BlurView intensity={80} tint="dark" style={styles.sheet}>
<SheetContent
ReasonButton={ReasonButton}
selectedReason={selectedReason}
isLoading={isLoading}
onClose={onClose}
onSubmit={handleSubmit}
/>
</BlurView>
) : (
<View style={[styles.sheet, styles.sheetAndroid]}>
<SheetContent
ReasonButton={ReasonButton}
selectedReason={selectedReason}
isLoading={isLoading}
onClose={onClose}
onSubmit={handleSubmit}
/>
</View>
)}
</Animated.View>
</Animated.View>
</Modal>
);
}
// Sheet content extracted for reuse between iOS blur and Android solid background
function SheetContent({
ReasonButton,
selectedReason,
isLoading,
onClose,
onSubmit,
}: {
ReasonButton: React.FC<{ reason: typeof REPORT_REASONS[number] }>;
selectedReason: ReportReason | null;
isLoading: boolean;
onClose: () => void;
onSubmit: () => void;
}) {
return (
<>
{/* Handle */}
<View style={styles.handle} />
{/* Header */}
<View style={styles.header}>
<Text style={styles.headerTitle}>Report Message</Text>
<TouchableOpacity style={styles.closeButton} onPress={onClose}>
<Ionicons name="close" size={20} color={colors.textSecondary} />
</TouchableOpacity>
</View>
{/* Description */}
<Text style={styles.description}>
Why are you reporting this message?
</Text>
{/* Reason buttons */}
<View style={styles.reasonButtons}>
{REPORT_REASONS.map((reason) => (
<ReasonButton key={reason.value} reason={reason} />
))}
</View>
{/* Submit button */}
<TouchableOpacity
style={[
styles.submitButton,
!selectedReason && styles.submitButtonDisabled,
]}
onPress={onSubmit}
disabled={!selectedReason || isLoading}
activeOpacity={0.7}
>
{isLoading ? (
<ActivityIndicator color={colors.text} size="small" />
) : (
<Text style={styles.submitButtonText}>Submit Report</Text>
)}
</TouchableOpacity>
{/* Bottom padding for safe area */}
<View style={styles.bottomPadding} />
</>
);
}
const styles = StyleSheet.create({
overlay: {
flex: 1,
justifyContent: "flex-end",
},
backdrop: {
...StyleSheet.absoluteFillObject,
backgroundColor: "rgba(0, 0, 0, 0.6)",
},
sheetContainer: {
maxHeight: "80%",
},
sheet: {
borderTopLeftRadius: radius.xl,
borderTopRightRadius: radius.xl,
overflow: "hidden",
paddingHorizontal: spacing.lg,
paddingTop: spacing.md,
},
sheetAndroid: {
backgroundColor: colors.backgroundLight,
},
handle: {
width: 40,
height: 4,
backgroundColor: "rgba(255, 255, 255, 0.3)",
borderRadius: 2,
alignSelf: "center",
marginBottom: spacing.md,
},
header: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
marginBottom: spacing.md,
},
headerTitle: {
...typography.title3,
color: colors.text,
},
closeButton: {
position: "absolute",
right: 0,
width: 32,
height: 32,
borderRadius: 16,
backgroundColor: "rgba(255, 255, 255, 0.1)",
justifyContent: "center",
alignItems: "center",
},
description: {
...typography.body,
color: colors.textSecondary,
textAlign: "center",
marginBottom: spacing.lg,
},
reasonButtons: {
gap: spacing.sm,
marginBottom: spacing.lg,
},
reasonButton: {
paddingVertical: spacing.md,
paddingHorizontal: spacing.lg,
borderRadius: radius.lg,
backgroundColor: "rgba(255, 255, 255, 0.05)",
borderWidth: 1,
borderColor: "rgba(255, 255, 255, 0.1)",
},
reasonButtonSelected: {
backgroundColor: "rgba(231, 76, 60, 0.1)",
borderColor: "rgba(231, 76, 60, 0.3)",
},
reasonContent: {
flexDirection: "row",
alignItems: "center",
gap: spacing.md,
},
radioOuter: {
width: 22,
height: 22,
borderRadius: 11,
borderWidth: 2,
borderColor: colors.textTertiary,
justifyContent: "center",
alignItems: "center",
},
radioOuterSelected: {
borderColor: colors.error,
},
radioInner: {
width: 12,
height: 12,
borderRadius: 6,
backgroundColor: colors.error,
},
reasonText: {
...typography.body,
color: colors.textSecondary,
},
reasonTextSelected: {
color: colors.text,
fontWeight: "600",
},
submitButton: {
paddingVertical: spacing.md,
borderRadius: radius.lg,
backgroundColor: colors.error,
alignItems: "center",
justifyContent: "center",
},
submitButtonDisabled: {
backgroundColor: "rgba(231, 76, 60, 0.3)",
},
submitButtonText: {
...typography.callout,
color: colors.text,
fontWeight: "600",
},
bottomPadding: {
height: Platform.OS === "ios" ? 34 : 20,
},
});
@@ -15,3 +15,4 @@ export type { MessageBubbleProps } from './MessageBubble';
export { ChatHeader } from './ChatHeader';
export { ChatMessages } from './ChatMessages';
export { MatchCard } from './MatchCard';
export { ReportMessageSheet } from './ReportMessageSheet';
@@ -1,6 +1,6 @@
/**
* useMessageActions - Hook for message deletion actions
* Handles "delete for self" and "delete for everyone" functionality.
* useMessageActions - Hook for message actions
* Handles "delete for self", "delete for everyone", and "report" functionality.
*/
import { Platform, ActionSheetIOS, Alert } from 'react-native';
import * as Haptics from 'expo-haptics';
@@ -9,9 +9,10 @@ import type { Message } from '../types';
interface UseMessageActionsConfig {
userId: string | undefined;
onReport?: (message: Message) => void;
}
export function useMessageActions({ userId }: UseMessageActionsConfig) {
export function useMessageActions({ userId, onReport }: UseMessageActionsConfig) {
/**
* Delete a message for the current user only.
* Message will still be visible to the partner.
@@ -46,8 +47,8 @@ export function useMessageActions({ userId }: UseMessageActionsConfig) {
};
/**
* Show delete options for a message.
* Author gets both options, non-author only gets "delete for me".
* Show options for a message.
* Author gets delete options, non-author gets delete for me + report.
*/
const showDeleteOptions = (message: Message, isMe: boolean) => {
// Don't show options for already deleted messages
@@ -57,44 +58,73 @@ export function useMessageActions({ userId }: UseMessageActionsConfig) {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
if (Platform.OS === 'ios') {
const options = ['Cancel', 'Delete for me'];
if (isMe) options.push('Delete for everyone');
if (isMe) {
// Author sees: Cancel, Delete for me, Delete for everyone
const options = ['Cancel', 'Delete for me', 'Delete for everyone'];
ActionSheetIOS.showActionSheetWithOptions(
{
options,
destructiveButtonIndex: isMe ? 2 : 1,
destructiveButtonIndex: 2,
cancelButtonIndex: 0,
title: 'Delete message?',
},
(buttonIndex) => {
if (buttonIndex === 1) {
deleteForSelf(message.id);
} else if (buttonIndex === 2 && isMe) {
} else if (buttonIndex === 2) {
deleteForEveryone(message.id);
}
}
);
} else {
// Non-author sees: Cancel, Delete for me, Report
const options = ['Cancel', 'Delete for me', 'Report'];
ActionSheetIOS.showActionSheetWithOptions(
{
options,
destructiveButtonIndex: 2,
cancelButtonIndex: 0,
title: 'Message options',
},
(buttonIndex) => {
if (buttonIndex === 1) {
deleteForSelf(message.id);
} else if (buttonIndex === 2 && onReport) {
onReport(message);
}
}
);
}
} else {
// Android fallback using Alert
const buttons: Array<{ text: string; style?: 'cancel' | 'default' | 'destructive'; onPress?: () => void }> = [
if (isMe) {
Alert.alert('Delete message?', undefined, [
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete for me',
style: 'destructive',
onPress: () => deleteForSelf(message.id),
},
];
if (isMe) {
buttons.push({
{
text: 'Delete for everyone',
style: 'destructive',
onPress: () => deleteForEveryone(message.id),
});
},
]);
} else {
Alert.alert('Message options', undefined, [
{ text: 'Cancel', style: 'cancel' },
{
text: 'Delete for me',
onPress: () => deleteForSelf(message.id),
},
{
text: 'Report',
style: 'destructive',
onPress: () => onReport?.(message),
},
]);
}
Alert.alert('Delete message?', undefined, buttons);
}
};
+10
View File
@@ -39,3 +39,13 @@ export const CHAT_COLORS = {
ROSE: 'rgb(232, 164, 174)',
ROSE_RGBA: 'rgba(232, 164, 174, ',
} as const;
/** Report reasons for message reporting */
export type ReportReason = 'harassment' | 'spam' | 'inappropriate_content' | 'other';
export const REPORT_REASONS: { value: ReportReason; label: string }[] = [
{ value: 'harassment', label: 'Harassment' },
{ value: 'spam', label: 'Spam' },
{ value: 'inappropriate_content', label: 'Inappropriate Content' },
{ value: 'other', label: 'Other' },
];
@@ -51,6 +51,7 @@ export function ProfileScreen() {
handleDeleteRelationship,
handleResetProgress,
handleSignOut,
handleDeleteAccount,
navigateToPairing
} = useCoupleManagement();
@@ -373,9 +374,11 @@ export function ProfileScreen() {
)}
{/* Danger Zone */}
{couple && (
<DangerZone onDeleteRelationship={handleDeleteRelationship} />
)}
<DangerZone
onDeleteRelationship={couple ? handleDeleteRelationship : undefined}
onDeleteAccount={handleDeleteAccount}
hasRelationship={!!couple}
/>
{/* Version */}
<Animated.View
@@ -1,5 +1,5 @@
import React, { useState } from 'react';
import { View, Text, StyleSheet, Modal, Platform, KeyboardAvoidingView, TouchableOpacity, ActivityIndicator, TextInput } from 'react-native';
import { View, Text, StyleSheet, Modal, Platform, KeyboardAvoidingView, TouchableOpacity, ActivityIndicator, TextInput, ViewStyle } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import Animated, { FadeInDown } from 'react-native-reanimated';
import { BlurView } from 'expo-blur';
@@ -7,25 +7,59 @@ import { GlassCard, GlassButton } from '../../../components/ui';
import { colors, spacing, radius, typography } from '../../../theme';
interface DangerZoneProps {
onDeleteRelationship: () => Promise<void>;
onDeleteRelationship?: () => Promise<void>;
onDeleteAccount: () => Promise<void>;
hasRelationship?: boolean;
}
export const DangerZone: React.FC<DangerZoneProps> = ({ onDeleteRelationship }) => {
const [showDeleteModal, setShowDeleteModal] = useState(false);
export const DangerZone: React.FC<DangerZoneProps> = ({
onDeleteRelationship,
onDeleteAccount,
hasRelationship = false
}) => {
const [showDeleteRelationshipModal, setShowDeleteRelationshipModal] = useState(false);
const [showDeleteAccountModal, setShowDeleteAccountModal] = useState(false);
const [deleteConfirmText, setDeleteConfirmText] = useState("");
const [isDeleting, setIsDeleting] = useState(false);
const [isDeletingRelationship, setIsDeletingRelationship] = useState(false);
const [isDeletingAccount, setIsDeletingAccount] = useState(false);
const handleDelete = async () => {
if (deleteConfirmText !== "DELETE") return;
setIsDeleting(true);
const handleDeleteRelationship = async () => {
if (deleteConfirmText !== "DELETE" || !onDeleteRelationship) return;
setIsDeletingRelationship(true);
try {
await onDeleteRelationship();
setShowDeleteModal(false);
setShowDeleteRelationshipModal(false);
setDeleteConfirmText("");
} catch (error) {
// Error handling relies on parent throwing or managing its own alerts
} finally {
setIsDeleting(false);
setIsDeletingRelationship(false);
}
};
const handleDeleteAccount = async () => {
if (deleteConfirmText !== "DELETE") return;
setIsDeletingAccount(true);
try {
await onDeleteAccount();
// No need to close modal - user will be signed out
} catch (error) {
// Error handling relies on parent throwing or managing its own alerts
setIsDeletingAccount(false);
}
};
const closeRelationshipModal = () => {
if (!isDeletingRelationship) {
setShowDeleteRelationshipModal(false);
setDeleteConfirmText("");
}
};
const closeAccountModal = () => {
if (!isDeletingAccount) {
setShowDeleteAccountModal(false);
setDeleteConfirmText("");
}
};
@@ -36,23 +70,53 @@ export const DangerZone: React.FC<DangerZoneProps> = ({ onDeleteRelationship })
style={styles.section}
>
<Text style={styles.dangerSectionTitle}>Danger Zone</Text>
{/* Delete Relationship - only show if in a relationship */}
{hasRelationship && onDeleteRelationship && (
<GlassCard style={styles.dangerCard}>
<View style={styles.dangerContent}>
<View style={styles.dangerInfo}>
<View style={styles.dangerIconContainer}>
<Ionicons name="warning" size={20} color={colors.error} />
<Ionicons name="heart-dislike" size={20} color={colors.error} />
</View>
<View style={styles.dangerTextContainer}>
<Text style={styles.dangerTitle}>Delete All Data</Text>
<Text style={styles.dangerTitle}>Delete Relationship Data</Text>
<Text style={styles.dangerDescription}>
Permanently delete your relationship including all matches, chats, and shared photos.
Delete your relationship including all matches, chats, and shared photos. Your account will remain.
</Text>
</View>
</View>
<GlassButton
variant="danger"
size="sm"
onPress={() => setShowDeleteModal(true)}
onPress={() => setShowDeleteRelationshipModal(true)}
icon={<Ionicons name="trash-outline" size={16} color={colors.text} />}
style={styles.dangerButton}
>
Delete
</GlassButton>
</View>
</GlassCard>
)}
{/* Delete Account - always show */}
<GlassCard style={hasRelationship ? StyleSheet.flatten([styles.dangerCard, styles.dangerCardSpacing]) as ViewStyle : styles.dangerCard}>
<View style={styles.dangerContent}>
<View style={styles.dangerInfo}>
<View style={styles.dangerIconContainer}>
<Ionicons name="person-remove" size={20} color={colors.error} />
</View>
<View style={styles.dangerTextContainer}>
<Text style={styles.dangerTitle}>Delete Account</Text>
<Text style={styles.dangerDescription}>
Permanently delete your account and all associated data. This cannot be undone.
</Text>
</View>
</View>
<GlassButton
variant="danger"
size="sm"
onPress={() => setShowDeleteAccountModal(true)}
icon={<Ionicons name="trash-outline" size={16} color={colors.text} />}
style={styles.dangerButton}
>
@@ -62,11 +126,12 @@ export const DangerZone: React.FC<DangerZoneProps> = ({ onDeleteRelationship })
</GlassCard>
</Animated.View>
{/* Delete Relationship Modal */}
<Modal
visible={showDeleteModal}
visible={showDeleteRelationshipModal}
transparent
animationType="fade"
onRequestClose={() => !isDeleting && setShowDeleteModal(false)}
onRequestClose={closeRelationshipModal}
>
<BlurView
intensity={Platform.OS === 'ios' ? 20 : 0}
@@ -80,9 +145,9 @@ export const DangerZone: React.FC<DangerZoneProps> = ({ onDeleteRelationship })
<View style={styles.modalContent}>
<View style={styles.modalHeader}>
<View style={styles.modalIconContainer}>
<Ionicons name="warning" size={32} color={colors.error} />
<Ionicons name="heart-dislike" size={32} color={colors.error} />
</View>
<Text style={styles.modalTitle}>Delete All Data?</Text>
<Text style={styles.modalTitle}>Delete Relationship Data?</Text>
</View>
<Text style={styles.modalDescription}>
@@ -120,17 +185,14 @@ export const DangerZone: React.FC<DangerZoneProps> = ({ onDeleteRelationship })
placeholderTextColor={colors.textTertiary}
autoCapitalize="characters"
autoCorrect={false}
editable={!isDeleting}
editable={!isDeletingRelationship}
/>
<View style={styles.modalButtons}>
<TouchableOpacity
style={styles.cancelButton}
onPress={() => {
setShowDeleteModal(false);
setDeleteConfirmText("");
}}
disabled={isDeleting}
onPress={closeRelationshipModal}
disabled={isDeletingRelationship}
activeOpacity={0.7}
>
<Text style={styles.cancelButtonText}>Cancel</Text>
@@ -139,13 +201,13 @@ export const DangerZone: React.FC<DangerZoneProps> = ({ onDeleteRelationship })
<TouchableOpacity
style={[
styles.deleteButton,
(deleteConfirmText !== "DELETE" || isDeleting) && styles.deleteButtonDisabled,
(deleteConfirmText !== "DELETE" || isDeletingRelationship) && styles.deleteButtonDisabled,
]}
onPress={handleDelete}
disabled={deleteConfirmText !== "DELETE" || isDeleting}
onPress={handleDeleteRelationship}
disabled={deleteConfirmText !== "DELETE" || isDeletingRelationship}
activeOpacity={0.7}
>
{isDeleting ? (
{isDeletingRelationship ? (
<ActivityIndicator size="small" color={colors.text} />
) : (
<>
@@ -159,6 +221,110 @@ export const DangerZone: React.FC<DangerZoneProps> = ({ onDeleteRelationship })
</KeyboardAvoidingView>
</BlurView>
</Modal>
{/* Delete Account Modal */}
<Modal
visible={showDeleteAccountModal}
transparent
animationType="fade"
onRequestClose={closeAccountModal}
>
<BlurView
intensity={Platform.OS === 'ios' ? 20 : 0}
tint="dark"
style={StyleSheet.absoluteFill}
>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={styles.modalOverlay}
>
<View style={styles.modalContent}>
<View style={styles.modalHeader}>
<View style={styles.modalIconContainer}>
<Ionicons name="person-remove" size={32} color={colors.error} />
</View>
<Text style={styles.modalTitle}>Delete Account?</Text>
</View>
<Text style={styles.modalDescription}>
This action cannot be undone. This will permanently delete:
</Text>
<View style={styles.deleteList}>
<View style={styles.deleteListItem}>
<Ionicons name="person" size={16} color={colors.error} />
<Text style={styles.deleteListText}>Your account and profile</Text>
</View>
{hasRelationship && (
<>
<View style={styles.deleteListItem}>
<Ionicons name="heart-dislike" size={16} color={colors.error} />
<Text style={styles.deleteListText}>Your relationship data</Text>
</View>
<View style={styles.deleteListItem}>
<Ionicons name="chatbubbles" size={16} color={colors.error} />
<Text style={styles.deleteListText}>All chat messages and photos</Text>
</View>
</>
)}
<View style={styles.deleteListItem}>
<Ionicons name="key" size={16} color={colors.error} />
<Text style={styles.deleteListText}>Your encryption keys</Text>
</View>
<View style={styles.deleteListItem}>
<Ionicons name="cloud-offline" size={16} color={colors.error} />
<Text style={styles.deleteListText}>All cloud-stored data</Text>
</View>
</View>
<Text style={styles.confirmLabel}>
Type <Text style={styles.confirmKeyword}>DELETE</Text> to confirm:
</Text>
<TextInput
style={styles.confirmInput}
value={deleteConfirmText}
onChangeText={setDeleteConfirmText}
placeholder="Type DELETE"
placeholderTextColor={colors.textTertiary}
autoCapitalize="characters"
autoCorrect={false}
editable={!isDeletingAccount}
/>
<View style={styles.modalButtons}>
<TouchableOpacity
style={styles.cancelButton}
onPress={closeAccountModal}
disabled={isDeletingAccount}
activeOpacity={0.7}
>
<Text style={styles.cancelButtonText}>Cancel</Text>
</TouchableOpacity>
<TouchableOpacity
style={[
styles.deleteButton,
(deleteConfirmText !== "DELETE" || isDeletingAccount) && styles.deleteButtonDisabled,
]}
onPress={handleDeleteAccount}
disabled={deleteConfirmText !== "DELETE" || isDeletingAccount}
activeOpacity={0.7}
>
{isDeletingAccount ? (
<ActivityIndicator size="small" color={colors.text} />
) : (
<>
<Ionicons name="trash" size={16} color={colors.text} />
<Text style={styles.deleteButtonText}>Delete Account</Text>
</>
)}
</TouchableOpacity>
</View>
</View>
</KeyboardAvoidingView>
</BlurView>
</Modal>
</>
);
};
@@ -180,6 +346,9 @@ const styles = StyleSheet.create({
borderColor: 'rgba(231, 76, 60, 0.3)',
borderWidth: 1,
},
dangerCardSpacing: {
marginTop: spacing.md,
},
dangerContent: {
gap: spacing.md,
},
@@ -4,6 +4,7 @@ import { useRouter } from 'expo-router';
import { useAuthStore, useMatchStore, useMessageStore, usePacksStore } from '../../../store';
import { supabase } from '../../../lib/supabase';
import { Events } from '../../../lib/analytics';
import { clearKeys } from '../../../lib/encryption';
export function useCoupleManagement() {
const router = useRouter();
@@ -13,6 +14,7 @@ export function useCoupleManagement() {
const { clearPacks } = usePacksStore();
const [isResettingProgress, setIsResettingProgress] = useState(false);
const [isDeletingAccount, setIsDeletingAccount] = useState(false);
const handleUnpair = async () => {
Alert.alert(
@@ -99,16 +101,46 @@ export function useCoupleManagement() {
);
};
const handleDeleteAccount = async () => {
setIsDeletingAccount(true);
try {
const { error } = await supabase.functions.invoke("delete-account", {
method: "DELETE",
});
if (error) throw error;
// Clear all local data
clearMatches();
clearMessages();
clearPacks();
await clearKeys();
Events.accountDeleted();
// Sign out the user (this will redirect to login)
await signOut();
} catch (error) {
console.error("Delete account error:", error);
Alert.alert("Error", "Failed to delete account. Please try again.");
throw error;
} finally {
setIsDeletingAccount(false);
}
};
const navigateToPairing = () => {
router.push("/(app)/pairing");
};
return {
isResettingProgress,
isDeletingAccount,
handleUnpair,
handleDeleteRelationship,
handleResetProgress,
handleSignOut,
handleDeleteAccount,
navigateToPairing,
};
}
+1
View File
@@ -157,6 +157,7 @@ export const Events = {
// Relationship events
relationshipEnded: () => logEvent("relationship_ended"),
accountDeleted: () => logEvent("account_deleted"),
// Milestone events
firstMatch: () => logEvent("first_match"),
@@ -0,0 +1,204 @@
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
interface ExpoPushMessage {
to: string;
title: string;
body: string;
sound?: string;
data?: Record<string, unknown>;
}
async function sendExpoPushNotifications(messages: ExpoPushMessage[]) {
if (messages.length === 0) return;
const response = await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(messages),
});
if (!response.ok) {
const error = await response.text();
console.error("Expo push error:", error);
}
return response.json();
}
Deno.serve(async (req) => {
// Handle CORS preflight
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
if (req.method !== "DELETE") {
return new Response(
JSON.stringify({ error: "Method not allowed" }),
{ status: 405, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
try {
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);
// Get user from JWT
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
return new Response(
JSON.stringify({ error: "Missing authorization header" }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
const { data: { user }, error: authError } = await supabase.auth.getUser(
authHeader.replace("Bearer ", "")
);
if (authError || !user) {
console.error("Auth Error:", authError);
return new Response(
JSON.stringify({ error: `Invalid token: ${authError?.message || 'No user found'}` }),
{ status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Get user's profile
const { data: profile, error: profileError } = await supabase
.from("profiles")
.select("couple_id")
.eq("id", user.id)
.maybeSingle();
if (profileError) {
console.error("Profile fetch error:", profileError);
return new Response(
JSON.stringify({ error: "Failed to fetch profile" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// If user is in a relationship, handle couple data deletion
if (profile?.couple_id) {
const coupleId = profile.couple_id;
// Get partner's push token BEFORE clearing data
const { data: partnerProfile } = await supabase
.from("profiles")
.select("push_token")
.eq("couple_id", coupleId)
.neq("id", user.id)
.maybeSingle();
// Get all match IDs for this couple (needed for storage cleanup)
const { data: matches } = await supabase
.from("matches")
.select("id")
.eq("couple_id", coupleId);
const matchIds = matches?.map(m => m.id) || [];
// Delete all chat media from storage for each match
for (const matchId of matchIds) {
const { data: files } = await supabase.storage
.from("chat-media")
.list(matchId);
if (files && files.length > 0) {
const filePaths = files.map(f => `${matchId}/${f.name}`);
await supabase.storage
.from("chat-media")
.remove(filePaths);
}
}
// Clear couple_id from partner's profile (don't clear our own yet, will be deleted)
await supabase
.from("profiles")
.update({ couple_id: null })
.eq("couple_id", coupleId)
.neq("id", user.id);
// Delete the couple record (cascades to responses, matches, messages, couple_packs)
const { error: deleteError } = await supabase
.from("couples")
.delete()
.eq("id", coupleId);
if (deleteError) {
console.error("Failed to delete couple:", deleteError);
// Continue anyway - we still want to delete the account
}
// Notify partner about the account deletion
if (partnerProfile?.push_token) {
await sendExpoPushNotifications([{
to: partnerProfile.push_token,
title: "Partner Left",
body: "Your partner has deleted their account. You can start fresh with a new partner anytime.",
sound: "default",
data: { type: "partner_account_deleted" },
}]);
}
}
// Delete any avatar from storage
const { data: avatarFiles } = await supabase.storage
.from("avatars")
.list(user.id);
if (avatarFiles && avatarFiles.length > 0) {
const avatarPaths = avatarFiles.map(f => `${user.id}/${f.name}`);
await supabase.storage
.from("avatars")
.remove(avatarPaths);
}
// Delete the user's profile (this will cascade delete any orphaned responses)
const { error: profileDeleteError } = await supabase
.from("profiles")
.delete()
.eq("id", user.id);
if (profileDeleteError) {
console.error("Failed to delete profile:", profileDeleteError);
return new Response(
JSON.stringify({ error: "Failed to delete profile" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
// Delete the user from auth.users using admin API
const { error: authDeleteError } = await supabase.auth.admin.deleteUser(user.id);
if (authDeleteError) {
console.error("Failed to delete auth user:", authDeleteError);
return new Response(
JSON.stringify({ error: "Failed to delete authentication record" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
return new Response(
JSON.stringify({ success: true, message: "Account deleted successfully" }),
{ headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
} catch (error) {
console.error("Error:", error);
return new Response(
JSON.stringify({ error: "Internal server error" }),
{ status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
);
}
});
@@ -0,0 +1,65 @@
-- Create enum for report reasons
CREATE TYPE report_reason AS ENUM ('harassment', 'spam', 'inappropriate_content', 'other');
-- Create message_reports table
CREATE TABLE message_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
reporter_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
reason report_reason NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'reviewed', 'dismissed')),
reviewed_by UUID REFERENCES auth.users(id),
reviewed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT now(),
-- Prevent duplicate reports from same user
UNIQUE(message_id, reporter_id)
);
-- Indexes for efficient queries
CREATE INDEX idx_message_reports_status ON message_reports(status);
CREATE INDEX idx_message_reports_created ON message_reports(created_at DESC);
CREATE INDEX idx_message_reports_message ON message_reports(message_id);
-- Enable RLS
ALTER TABLE message_reports ENABLE ROW LEVEL SECURITY;
-- RLS Policies
-- Users can view their own reports
CREATE POLICY "Users can view own reports"
ON message_reports FOR SELECT
USING (reporter_id = auth.uid());
-- Users can create reports for messages in their couple's matches (but NOT their own messages)
CREATE POLICY "Users can report partner messages"
ON message_reports FOR INSERT
WITH CHECK (
reporter_id = auth.uid() AND
EXISTS (
SELECT 1 FROM messages m
JOIN matches ma ON ma.id = m.match_id
JOIN profiles p ON p.couple_id = ma.couple_id
WHERE m.id = message_reports.message_id
AND p.id = auth.uid()
AND m.user_id != auth.uid() -- Cannot report own messages
)
);
-- Admins can view all reports
CREATE POLICY "Admins can view all reports"
ON message_reports FOR SELECT
USING (is_admin());
-- Admins can update reports (for review status)
CREATE POLICY "Admins can update reports"
ON message_reports FOR UPDATE
USING (is_admin());
-- Add to realtime for live updates in admin
ALTER PUBLICATION supabase_realtime ADD TABLE message_reports;
-- Comments
COMMENT ON TABLE message_reports IS 'User-submitted reports for messages. Separate from AI moderation (moderation_status on messages table).';
COMMENT ON COLUMN message_reports.status IS 'Report status: pending (new), reviewed (action taken), dismissed (no action needed).';
COMMENT ON COLUMN message_reports.reason IS 'User-selected reason for reporting: harassment, spam, inappropriate_content, or other.';