Code edited in Lovable Code Editor

This commit is contained in:
gpt-engineer-app[bot]
2025-11-03 16:32:36 +00:00
parent 6c3a8e4f51
commit 826747d58a

View File

@@ -1,22 +1,22 @@
import React, { useState } from 'react'; import React, { useState } from "react";
import { invokeWithTracking } from '@/lib/edgeFunctionTracking'; import { invokeWithTracking } from "@/lib/edgeFunctionTracking";
import { logger } from '@/lib/logger'; import { logger } from "@/lib/logger";
import { getErrorMessage } from '@/lib/errorHandler'; import { getErrorMessage } from "@/lib/errorHandler";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from '@/components/ui/input'; import { Input } from "@/components/ui/input";
import { Label } from '@/components/ui/label'; import { Label } from "@/components/ui/label";
import { Textarea } from '@/components/ui/textarea'; import { Textarea } from "@/components/ui/textarea";
import { Button } from '@/components/ui/button'; import { Button } from "@/components/ui/button";
import { Badge } from '@/components/ui/badge'; import { Badge } from "@/components/ui/badge";
import { Separator } from '@/components/ui/separator'; import { Separator } from "@/components/ui/separator";
import { Progress } from '@/components/ui/progress'; import { Progress } from "@/components/ui/progress";
import { UppyPhotoUploadLazy } from './UppyPhotoUploadLazy'; import { UppyPhotoUploadLazy } from "./UppyPhotoUploadLazy";
import { PhotoCaptionEditor, PhotoWithCaption } from './PhotoCaptionEditor'; import { PhotoCaptionEditor, PhotoWithCaption } from "./PhotoCaptionEditor";
import { supabase } from '@/integrations/supabase/client'; import { supabase } from "@/integrations/supabase/client";
import { useAuth } from '@/hooks/useAuth'; import { useAuth } from "@/hooks/useAuth";
import { useToast } from '@/hooks/use-toast'; import { useToast } from "@/hooks/use-toast";
import { Camera, CheckCircle, AlertCircle, Info } from 'lucide-react'; import { Camera, CheckCircle, AlertCircle, Info } from "lucide-react";
import { UppyPhotoSubmissionUploadProps } from '@/types/submissions'; import { UppyPhotoSubmissionUploadProps } from "@/types/submissions";
export function UppyPhotoSubmissionUpload({ export function UppyPhotoSubmissionUpload({
onSubmissionComplete, onSubmissionComplete,
@@ -24,7 +24,7 @@ export function UppyPhotoSubmissionUpload({
entityType, entityType,
parentId, parentId,
}: UppyPhotoSubmissionUploadProps) { }: UppyPhotoSubmissionUploadProps) {
const [title, setTitle] = useState(''); const [title, setTitle] = useState("");
const [photos, setPhotos] = useState<PhotoWithCaption[]>([]); const [photos, setPhotos] = useState<PhotoWithCaption[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [uploadProgress, setUploadProgress] = useState<{ current: number; total: number } | null>(null); const [uploadProgress, setUploadProgress] = useState<{ current: number; total: number } | null>(null);
@@ -36,11 +36,11 @@ export function UppyPhotoSubmissionUpload({
const newPhotos: PhotoWithCaption[] = files.map((file, index) => ({ const newPhotos: PhotoWithCaption[] = files.map((file, index) => ({
url: URL.createObjectURL(file), // Object URL for preview url: URL.createObjectURL(file), // Object URL for preview
file, // Store the file for later upload file, // Store the file for later upload
caption: '', caption: "",
order: photos.length + index, order: photos.length + index,
uploadStatus: 'pending' as const, uploadStatus: "pending" as const,
})); }));
setPhotos(prev => [...prev, ...newPhotos]); setPhotos((prev) => [...prev, ...newPhotos]);
}; };
const handlePhotosChange = (updatedPhotos: PhotoWithCaption[]) => { const handlePhotosChange = (updatedPhotos: PhotoWithCaption[]) => {
@@ -48,10 +48,10 @@ export function UppyPhotoSubmissionUpload({
}; };
const handleRemovePhoto = (index: number) => { const handleRemovePhoto = (index: number) => {
setPhotos(prev => { setPhotos((prev) => {
const photo = prev[index]; const photo = prev[index];
// Revoke object URL if it exists // Revoke object URL if it exists
if (photo.file && photo.url.startsWith('blob:')) { if (photo.file && photo.url.startsWith("blob:")) {
URL.revokeObjectURL(photo.url); URL.revokeObjectURL(photo.url);
} }
return prev.filter((_, i) => i !== index); return prev.filter((_, i) => i !== index);
@@ -61,29 +61,28 @@ export function UppyPhotoSubmissionUpload({
const handleSubmit = async () => { const handleSubmit = async () => {
if (!user) { if (!user) {
toast({ toast({
variant: 'destructive', variant: "destructive",
title: 'Authentication Required', title: "Authentication Required",
description: 'Please sign in to submit photos.', description: "Please sign in to submit photos.",
}); });
return; return;
} }
if (photos.length === 0) { if (photos.length === 0) {
toast({ toast({
variant: 'destructive', variant: "destructive",
title: 'No Photos', title: "No Photos",
description: 'Please upload at least one photo before submitting.', description: "Please upload at least one photo before submitting.",
}); });
return; return;
} }
setIsSubmitting(true); setIsSubmitting(true);
try { try {
// Upload all photos that haven't been uploaded yet // Upload all photos that haven't been uploaded yet
const uploadedPhotos: PhotoWithCaption[] = []; const uploadedPhotos: PhotoWithCaption[] = [];
const photosToUpload = photos.filter(p => p.file); const photosToUpload = photos.filter((p) => p.file);
if (photosToUpload.length > 0) { if (photosToUpload.length > 0) {
setUploadProgress({ current: 0, total: photosToUpload.length }); setUploadProgress({ current: 0, total: photosToUpload.length });
@@ -93,16 +92,14 @@ export function UppyPhotoSubmissionUpload({
setUploadProgress({ current: i + 1, total: photosToUpload.length }); setUploadProgress({ current: i + 1, total: photosToUpload.length });
// Update status // Update status
setPhotos(prev => prev.map(p => setPhotos((prev) => prev.map((p) => (p === photo ? { ...p, uploadStatus: "uploading" as const } : p)));
p === photo ? { ...p, uploadStatus: 'uploading' as const } : p
));
try { try {
// Get upload URL from edge function // Get upload URL from edge function
const { data: uploadData, error: uploadError } = await invokeWithTracking( const { data: uploadData, error: uploadError } = await invokeWithTracking(
'upload-image', "upload-image",
{ metadata: { requireSignedURLs: false }, variant: 'public' }, { metadata: { requireSignedURLs: false }, variant: "public" },
user?.id user?.id,
); );
if (uploadError) throw uploadError; if (uploadError) throw uploadError;
@@ -111,37 +108,37 @@ export function UppyPhotoSubmissionUpload({
// Upload file to Cloudflare // Upload file to Cloudflare
if (!photo.file) { if (!photo.file) {
throw new Error('Photo file is missing'); throw new Error("Photo file is missing");
} }
const formData = new FormData(); const formData = new FormData();
formData.append('file', photo.file); formData.append("file", photo.file);
const uploadResponse = await fetch(uploadURL, { const uploadResponse = await fetch(uploadURL, {
method: 'POST', method: "POST",
body: formData, body: formData,
}); });
if (!uploadResponse.ok) { if (!uploadResponse.ok) {
throw new Error('Failed to upload to Cloudflare'); throw new Error("Failed to upload to Cloudflare");
} }
// Poll for processing completion // Poll for processing completion
let attempts = 0; let attempts = 0;
const maxAttempts = 30; const maxAttempts = 30;
let cloudflareUrl = ''; let cloudflareUrl = "";
while (attempts < maxAttempts) { while (attempts < maxAttempts) {
const { data: { session } } = await supabase.auth.getSession(); const {
const supabaseUrl = 'https://ydvtmnrszybqnbcqbdcy.supabase.co'; data: { session },
const statusResponse = await fetch( } = await supabase.auth.getSession();
`${supabaseUrl}/functions/v1/upload-image?id=${cloudflareId}`, const supabaseUrl = "https://api.thrillwiki.com";
{ const statusResponse = await fetch(`${supabaseUrl}/functions/v1/upload-image?id=${cloudflareId}`, {
headers: { headers: {
'Authorization': `Bearer ${session?.access_token || ''}`, Authorization: `Bearer ${session?.access_token || ""}`,
'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4', apikey:
} "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4",
} },
); });
if (statusResponse.ok) { if (statusResponse.ok) {
const status = await statusResponse.json(); const status = await statusResponse.json();
@@ -151,12 +148,12 @@ export function UppyPhotoSubmissionUpload({
} }
} }
await new Promise(resolve => setTimeout(resolve, 1000)); await new Promise((resolve) => setTimeout(resolve, 1000));
attempts++; attempts++;
} }
if (!cloudflareUrl) { if (!cloudflareUrl) {
throw new Error('Upload processing timeout'); throw new Error("Upload processing timeout");
} }
// Revoke object URL // Revoke object URL
@@ -165,28 +162,25 @@ export function UppyPhotoSubmissionUpload({
uploadedPhotos.push({ uploadedPhotos.push({
...photo, ...photo,
url: cloudflareUrl, url: cloudflareUrl,
uploadStatus: 'uploaded' as const, uploadStatus: "uploaded" as const,
}); });
// Update status // Update status
setPhotos(prev => prev.map(p => setPhotos((prev) =>
p === photo ? { ...p, url: cloudflareUrl, uploadStatus: 'uploaded' as const } : p prev.map((p) => (p === photo ? { ...p, url: cloudflareUrl, uploadStatus: "uploaded" as const } : p)),
)); );
} catch (error: unknown) { } catch (error: unknown) {
const errorMsg = getErrorMessage(error); const errorMsg = getErrorMessage(error);
logger.error('Photo submission upload failed', { logger.error("Photo submission upload failed", {
photoTitle: photo.title, photoTitle: photo.title,
photoOrder: photo.order, photoOrder: photo.order,
fileName: photo.file?.name, fileName: photo.file?.name,
error: errorMsg error: errorMsg,
}); });
setPhotos(prev => prev.map(p => setPhotos((prev) => prev.map((p) => (p === photo ? { ...p, uploadStatus: "failed" as const } : p)));
p === photo ? { ...p, uploadStatus: 'failed' as const } : p
));
throw new Error(`Failed to upload ${photo.title || 'photo'}: ${errorMsg}`); throw new Error(`Failed to upload ${photo.title || "photo"}: ${errorMsg}`);
} }
} }
} }
@@ -195,22 +189,22 @@ export function UppyPhotoSubmissionUpload({
// Create content_submission record first // Create content_submission record first
const { data: submissionData, error: submissionError } = await supabase const { data: submissionData, error: submissionError } = await supabase
.from('content_submissions') .from("content_submissions")
.insert({ .insert({
user_id: user.id, user_id: user.id,
submission_type: 'photo', submission_type: "photo",
content: {}, // Empty content, all data is in relational tables content: {}, // Empty content, all data is in relational tables
}) })
.select() .select()
.single(); .single();
if (submissionError || !submissionData) { if (submissionError || !submissionData) {
throw submissionError || new Error('Failed to create submission record'); throw submissionError || new Error("Failed to create submission record");
} }
// Create photo_submission record // Create photo_submission record
const { data: photoSubmissionData, error: photoSubmissionError } = await supabase const { data: photoSubmissionData, error: photoSubmissionError } = await supabase
.from('photo_submissions') .from("photo_submissions")
.insert({ .insert({
submission_id: submissionData.id, submission_id: submissionData.id,
entity_type: entityType, entity_type: entityType,
@@ -222,14 +216,17 @@ export function UppyPhotoSubmissionUpload({
.single(); .single();
if (photoSubmissionError || !photoSubmissionData) { if (photoSubmissionError || !photoSubmissionData) {
throw photoSubmissionError || new Error('Failed to create photo submission'); throw photoSubmissionError || new Error("Failed to create photo submission");
} }
// Insert all photo items // Insert all photo items
const photoItems = photos.map((photo, index) => ({ const photoItems = photos.map((photo, index) => ({
photo_submission_id: photoSubmissionData.id, photo_submission_id: photoSubmissionData.id,
cloudflare_image_id: photo.url.split('/').slice(-2, -1)[0] || '', // Extract ID from URL cloudflare_image_id: photo.url.split("/").slice(-2, -1)[0] || "", // Extract ID from URL
cloudflare_image_url: photo.uploadStatus === 'uploaded' ? photo.url : uploadedPhotos.find(p => p.order === photo.order)?.url || photo.url, cloudflare_image_url:
photo.uploadStatus === "uploaded"
? photo.url
: uploadedPhotos.find((p) => p.order === photo.order)?.url || photo.url,
caption: photo.caption.trim() || null, caption: photo.caption.trim() || null,
title: photo.title?.trim() || null, title: photo.title?.trim() || null,
filename: photo.file?.name || null, filename: photo.file?.name || null,
@@ -238,43 +235,41 @@ export function UppyPhotoSubmissionUpload({
mime_type: photo.file?.type || null, mime_type: photo.file?.type || null,
})); }));
const { error: itemsError } = await supabase const { error: itemsError } = await supabase.from("photo_submission_items").insert(photoItems);
.from('photo_submission_items')
.insert(photoItems);
if (itemsError) { if (itemsError) {
throw itemsError; throw itemsError;
} }
toast({ toast({
title: 'Submission Successful', title: "Submission Successful",
description: 'Your photos have been submitted for review. Thank you for contributing!', description: "Your photos have been submitted for review. Thank you for contributing!",
}); });
// Cleanup and reset form // Cleanup and reset form
photos.forEach(photo => { photos.forEach((photo) => {
if (photo.url.startsWith('blob:')) { if (photo.url.startsWith("blob:")) {
URL.revokeObjectURL(photo.url); URL.revokeObjectURL(photo.url);
} }
}); });
setTitle(''); setTitle("");
setPhotos([]); setPhotos([]);
onSubmissionComplete?.(); onSubmissionComplete?.();
} catch (error: unknown) { } catch (error: unknown) {
const errorMsg = getErrorMessage(error); const errorMsg = getErrorMessage(error);
logger.error('Photo submission failed', { logger.error("Photo submission failed", {
entityType, entityType,
entityId, entityId,
photoCount: photos.length, photoCount: photos.length,
userId: user?.id, userId: user?.id,
error: errorMsg error: errorMsg,
}); });
toast({ toast({
variant: 'destructive', variant: "destructive",
title: 'Submission Failed', title: "Submission Failed",
description: errorMsg || 'There was an error submitting your photos. Please try again.', description: errorMsg || "There was an error submitting your photos. Please try again.",
}); });
} finally { } finally {
setIsSubmitting(false); setIsSubmitting(false);
@@ -285,8 +280,8 @@ export function UppyPhotoSubmissionUpload({
// Cleanup on unmount // Cleanup on unmount
React.useEffect(() => { React.useEffect(() => {
return () => { return () => {
photos.forEach(photo => { photos.forEach((photo) => {
if (photo.url.startsWith('blob:')) { if (photo.url.startsWith("blob:")) {
URL.revokeObjectURL(photo.url); URL.revokeObjectURL(photo.url);
} }
}); });
@@ -294,7 +289,7 @@ export function UppyPhotoSubmissionUpload({
}, []); }, []);
const metadata = { const metadata = {
submissionType: 'photo', submissionType: "photo",
entityId, entityId,
entityType, entityType,
parentId, parentId,
@@ -308,9 +303,7 @@ export function UppyPhotoSubmissionUpload({
<Camera className="w-8 h-8 text-accent" /> <Camera className="w-8 h-8 text-accent" />
</div> </div>
<div> <div>
<CardTitle className="text-2xl text-accent"> <CardTitle className="text-2xl text-accent">Submit Photos</CardTitle>
Submit Photos
</CardTitle>
<CardDescription className="text-base mt-2"> <CardDescription className="text-base mt-2">
Share your photos with the community. All submissions will be reviewed before being published. Share your photos with the community. All submissions will be reviewed before being published.
</CardDescription> </CardDescription>
@@ -348,9 +341,7 @@ export function UppyPhotoSubmissionUpload({
disabled={isSubmitting} disabled={isSubmitting}
className="transition-all duration-200 focus:ring-2 focus:ring-primary/20" className="transition-all duration-200 focus:ring-2 focus:ring-primary/20"
/> />
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">{title.length}/100 characters</p>
{title.length}/100 characters
</p>
</div> </div>
<div className="space-y-3"> <div className="space-y-3">
@@ -358,7 +349,7 @@ export function UppyPhotoSubmissionUpload({
<Label className="text-base font-medium">Photos *</Label> <Label className="text-base font-medium">Photos *</Label>
{photos.length > 0 && ( {photos.length > 0 && (
<Badge variant="secondary" className="text-xs"> <Badge variant="secondary" className="text-xs">
{photos.length} photo{photos.length !== 1 ? 's' : ''} selected {photos.length} photo{photos.length !== 1 ? "s" : ""} selected
</Badge> </Badge>
)} )}
</div> </div>
@@ -412,12 +403,12 @@ export function UppyPhotoSubmissionUpload({
{isSubmitting ? ( {isSubmitting ? (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div className="w-4 h-4 border-2 border-primary-foreground/30 border-t-primary-foreground rounded-full animate-spin" /> <div className="w-4 h-4 border-2 border-primary-foreground/30 border-t-primary-foreground rounded-full animate-spin" />
{uploadProgress ? `Uploading ${uploadProgress.current}/${uploadProgress.total}...` : 'Submitting...'} {uploadProgress ? `Uploading ${uploadProgress.current}/${uploadProgress.total}...` : "Submitting..."}
</div> </div>
) : ( ) : (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<CheckCircle className="w-5 h-5" /> <CheckCircle className="w-5 h-5" />
Submit {photos.length} Photo{photos.length !== 1 ? 's' : ''} Submit {photos.length} Photo{photos.length !== 1 ? "s" : ""}
</div> </div>
)} )}
</Button> </Button>