Fix JSON violations

This commit is contained in:
gpt-engineer-app[bot]
2025-10-02 19:23:33 +00:00
parent f82c2151df
commit 4629fc0df5
6 changed files with 131 additions and 353 deletions

View File

@@ -111,10 +111,8 @@ export function PhotoManagementDialog({
user_id: user.id,
submission_type: 'photo_delete',
content: {
photo_id: photoToDelete.id,
entity_type: entityType,
entity_id: entityId,
reason: deleteReason
action: 'delete',
photo_id: photoToDelete.id
}
}])
.select()
@@ -178,9 +176,8 @@ export function PhotoManagementDialog({
user_id: user.id,
submission_type: 'photo_edit',
content: {
photo_id: editingPhoto.id,
entity_type: entityType,
entity_id: entityId
action: 'edit',
photo_id: editingPhoto.id
}
}])
.select()

View File

@@ -1,296 +0,0 @@
/**
* @deprecated This component is deprecated. Use UppyPhotoSubmissionUpload instead.
* This file is kept for backwards compatibility only.
*
* For new implementations, use:
* - UppyPhotoSubmissionUpload for direct uploads
* - EntityPhotoGallery for entity-specific photo galleries
*/
import { useState } from 'react';
import { Upload, X, Camera } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';
interface PhotoSubmissionUploadProps {
onSubmissionComplete?: () => void;
parkId?: string;
rideId?: string;
}
export function PhotoSubmissionUpload({ onSubmissionComplete, parkId, rideId }: PhotoSubmissionUploadProps) {
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
const [uploading, setUploading] = useState(false);
const [caption, setCaption] = useState('');
const [title, setTitle] = useState('');
const { toast } = useToast();
const { user } = useAuth();
const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(event.target.files || []);
const imageFiles = files.filter(file => file.type.startsWith('image/'));
if (imageFiles.length !== files.length) {
toast({
title: "Invalid Files",
description: "Only image files are allowed",
variant: "destructive",
});
}
setSelectedFiles(prev => [...prev, ...imageFiles].slice(0, 5)); // Max 5 files
};
const removeFile = (index: number) => {
setSelectedFiles(prev => prev.filter((_, i) => i !== index));
};
const uploadFileToCloudflare = async (file: File): Promise<{ id: string; url: string }> => {
try {
// Get upload URL from Supabase edge function
const { data: uploadData, error: uploadError } = await supabase.functions.invoke('upload-image', {
method: 'POST',
});
if (uploadError || !uploadData?.uploadURL) {
console.error('Failed to get upload URL:', uploadError);
throw new Error('Failed to get upload URL');
}
// Upload file directly to Cloudflare
const formData = new FormData();
formData.append('file', file);
const uploadResponse = await fetch(uploadData.uploadURL, {
method: 'POST',
body: formData,
});
if (!uploadResponse.ok) {
const errorText = await uploadResponse.text();
console.error('Cloudflare upload failed:', errorText);
throw new Error('Failed to upload file to Cloudflare');
}
const result = await uploadResponse.json();
const imageId = result.result?.id;
if (!imageId) {
console.error('No image ID returned from Cloudflare:', result);
throw new Error('Invalid response from Cloudflare');
}
// Get the delivery URL using the edge function with URL parameters
const getImageUrl = new URL(`https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/upload-image`);
getImageUrl.searchParams.set('id', imageId);
const response = await fetch(getImageUrl.toString(), {
method: 'GET',
headers: {
'Authorization': `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4`,
'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4',
},
});
if (!response.ok) {
const errorText = await response.text();
console.error('Failed to get image status:', errorText);
throw new Error('Failed to get image URL');
}
const statusData = await response.json();
if (!statusData?.urls?.public) {
console.error('No image URL returned:', statusData);
throw new Error('No image URL available');
}
return {
id: imageId,
url: statusData.urls.public,
};
} catch (error) {
console.error('Upload error:', error);
throw error;
}
};
const handleSubmit = async () => {
if (!user) {
toast({
title: "Authentication Required",
description: "Please log in to submit photos",
variant: "destructive",
});
return;
}
if (selectedFiles.length === 0) {
toast({
title: "No Files Selected",
description: "Please select at least one image to submit",
variant: "destructive",
});
return;
}
setUploading(true);
try {
// Upload files to Cloudflare Images first
const photoSubmissions = await Promise.all(
selectedFiles.map(async (file, index) => {
const uploadResult = await uploadFileToCloudflare(file);
return {
filename: file.name,
size: file.size,
type: file.type,
url: uploadResult.url,
imageId: uploadResult.id,
caption: index === 0 ? caption : '', // Only first image gets the caption
};
})
);
// Submit to content_submissions table
const { error } = await supabase
.from('content_submissions')
.insert({
user_id: user.id,
submission_type: 'photo',
content: {
photos: photoSubmissions,
title: title.trim() || undefined,
caption: caption.trim() || undefined,
park_id: parkId,
ride_id: rideId,
context: parkId ? 'park' : rideId ? 'ride' : 'general',
},
status: 'pending',
});
if (error) throw error;
toast({
title: "Photos Submitted",
description: "Your photos have been submitted for moderation review",
});
// Reset form
setSelectedFiles([]);
setCaption('');
setTitle('');
onSubmissionComplete?.();
} catch (error) {
console.error('Error submitting photos:', error);
toast({
title: "Submission Failed",
description: "Failed to submit photos. Please try again.",
variant: "destructive",
});
} finally {
setUploading(false);
}
};
return (
<Card>
<CardContent className="p-6 space-y-4">
<div className="flex items-center gap-2 mb-4">
<Camera className="w-5 h-5" />
<h3 className="text-lg font-semibold">Submit Photos</h3>
</div>
<div className="space-y-4">
<div>
<Label htmlFor="photo-title">Title (optional)</Label>
<Input
id="photo-title"
placeholder="Give your photo submission a title"
value={title}
onChange={(e) => setTitle(e.target.value)}
maxLength={100}
/>
</div>
<div>
<Label htmlFor="photo-caption">Caption (optional)</Label>
<Textarea
id="photo-caption"
placeholder="Add a caption to describe your photos"
value={caption}
onChange={(e) => setCaption(e.target.value)}
rows={3}
maxLength={500}
/>
</div>
<div>
<Label htmlFor="photo-upload">Select Photos</Label>
<div className="mt-2">
<input
id="photo-upload"
type="file"
accept="image/*"
multiple
onChange={handleFileSelect}
className="hidden"
/>
<Button
type="button"
variant="outline"
onClick={() => document.getElementById('photo-upload')?.click()}
className="w-full"
disabled={selectedFiles.length >= 5}
>
<Upload className="w-4 h-4 mr-2" />
Choose Photos {selectedFiles.length > 0 && `(${selectedFiles.length}/5)`}
</Button>
</div>
</div>
{selectedFiles.length > 0 && (
<div className="space-y-3">
<Label>Selected Photos:</Label>
<div className="grid grid-cols-2 md:grid-cols-3 gap-3">
{selectedFiles.map((file, index) => (
<div key={index} className="relative">
<img
src={URL.createObjectURL(file)}
alt={`Preview ${index + 1}`}
className="w-full h-24 object-cover rounded border"
/>
<Button
type="button"
variant="destructive"
size="sm"
className="absolute -top-2 -right-2 h-6 w-6 rounded-full p-0"
onClick={() => removeFile(index)}
>
<X className="h-3 w-3" />
</Button>
</div>
))}
</div>
</div>
)}
<Button
onClick={handleSubmit}
disabled={uploading || selectedFiles.length === 0}
className="w-full"
>
{uploading ? 'Submitting...' : 'Submit Photos for Review'}
</Button>
</div>
</CardContent>
</Card>
);
}

View File

@@ -2,6 +2,52 @@ import { supabase } from '@/integrations/supabase/client';
import { ImageAssignments } from '@/components/upload/EntityMultiImageUploader';
import { uploadPendingImages } from './imageUploadHelper';
/**
* ═══════════════════════════════════════════════════════════════════
* SUBMISSION PATTERN STANDARD - CRITICAL PROJECT RULE
* ═══════════════════════════════════════════════════════════════════
*
* ⚠️ NEVER STORE JSON IN SQL COLUMNS ⚠️
*
* content_submissions.content should ONLY contain:
* ✅ action: 'create' | 'edit' | 'delete'
* ✅ Minimal reference IDs (entity_id, parent_id, etc.) - MAX 3 fields
* ❌ NO actual form data
* ❌ NO submission content
* ❌ NO large objects
*
* ALL actual data MUST go in:
* ✅ submission_items.item_data (new data)
* ✅ submission_items.original_data (for edits)
* ✅ Specialized relational tables:
* - photo_submissions + photo_submission_items
* - park_submissions
* - ride_submissions
* - company_submissions
* - ride_model_submissions
*
* If your data is relational, model it relationally.
* JSON blobs destroy:
* - Queryability (can't filter/join)
* - Performance (slower, larger)
* - Data integrity (no constraints)
* - Maintainability (impossible to refactor)
*
* EXAMPLES:
*
* ✅ CORRECT:
* content: { action: 'create' }
* content: { action: 'edit', park_id: uuid }
* content: { action: 'delete', photo_id: uuid }
*
* ❌ WRONG:
* content: { name: '...', description: '...', ...formData }
* content: { photos: [...], metadata: {...} }
* content: data // entire object dump
*
* ═══════════════════════════════════════════════════════════════════
*/
export interface ParkFormData {
name: string;
slug: string;

View File

@@ -110,47 +110,18 @@ export default function ParkDetail() {
}
try {
// Extract composite submission data
const compositeData = rideData._compositeSubmission;
delete rideData._compositeSubmission;
// Determine submission type based on what's being created
let submissionType = 'ride';
if (compositeData?.new_manufacturer && compositeData?.new_ride_model) {
submissionType = 'ride_with_manufacturer_and_model';
} else if (compositeData?.new_manufacturer) {
submissionType = 'ride_with_manufacturer';
} else if (compositeData?.new_ride_model) {
submissionType = 'ride_with_model';
}
const { error } = await supabase
.from('content_submissions')
.insert({
user_id: user.id,
submission_type: submissionType,
status: 'pending',
content: {
...(compositeData || { ride: rideData }),
park_id: park?.id,
park_slug: park?.slug
}
});
if (error) throw error;
let message = "Your ride submission has been sent for moderation review.";
if (compositeData?.new_manufacturer && compositeData?.new_ride_model) {
message = "Your ride, new manufacturer, and new model have been submitted for review.";
} else if (compositeData?.new_manufacturer) {
message = "Your ride and new manufacturer have been submitted for review.";
} else if (compositeData?.new_ride_model) {
message = "Your ride and new model have been submitted for review.";
}
const { submitRideCreation } = await import('@/lib/entitySubmissionHelpers');
await submitRideCreation(
{
...rideData,
park_id: park?.id
},
user.id
);
toast({
title: "Submission Sent",
description: message,
description: "Your ride submission has been sent for moderation review.",
});
setIsAddRideModalOpen(false);

View File

@@ -83,17 +83,8 @@ export default function Rides() {
return;
}
// All users submit for moderation
const { error } = await supabase
.from('content_submissions')
.insert({
user_id: user.id,
submission_type: 'ride',
status: 'pending',
content: data
});
if (error) throw error;
const { submitRideCreation } = await import('@/lib/entitySubmissionHelpers');
await submitRideCreation(data, user.id);
toast({
title: "Ride Submitted",

View File

@@ -59,3 +59,72 @@ export interface UppyPhotoSubmissionUploadProps {
parkId?: string;
rideId?: string;
}
/**
* Enforces minimal content structure for content_submissions.content
* This type prevents accidental JSON blob storage
*
* RULE: content should ONLY contain action + max 2 reference IDs
*/
export interface ContentSubmissionContent {
action: 'create' | 'edit' | 'delete';
// Only reference IDs allowed - no actual data
[key: string]: string | null | undefined;
}
/**
* Type guard to validate content structure
* Prevents JSON blob violations at runtime
*/
export function isValidSubmissionContent(content: any): content is ContentSubmissionContent {
if (!content || typeof content !== 'object') {
console.error('❌ VIOLATION: content_submissions.content must be an object');
return false;
}
if (!['create', 'edit', 'delete'].includes(content.action)) {
console.error('❌ VIOLATION: content_submissions.content must have valid action:', content.action);
return false;
}
const keys = Object.keys(content);
if (keys.length > 3) {
console.error('❌ VIOLATION: content_submissions.content has too many fields:', keys);
console.error(' Only action + max 2 reference IDs allowed');
return false;
}
// Check for common violations
const forbiddenKeys = ['name', 'description', 'photos', 'data', 'items', 'metadata'];
const violations = keys.filter(k => forbiddenKeys.includes(k));
if (violations.length > 0) {
console.error('❌ VIOLATION: content_submissions.content contains forbidden keys:', violations);
console.error(' These should be in submission_items.item_data instead');
return false;
}
return true;
}
/**
* Helper to create safe submission content
* Use this to ensure compliance with the pattern
*/
export function createSubmissionContent(
action: 'create' | 'edit' | 'delete',
referenceIds: Record<string, string> = {}
): ContentSubmissionContent {
const idKeys = Object.keys(referenceIds);
if (idKeys.length > 2) {
throw new Error(
`Too many reference IDs (${idKeys.length}). Maximum is 2. ` +
`Put additional data in submission_items.item_data instead.`
);
}
return {
action,
...referenceIds
};
}