mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-28 16:27:08 -05:00
Compare commits
7 Commits
ab618fb65a
...
67a96ca94b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67a96ca94b | ||
|
|
eee4b1c626 | ||
|
|
47b317b7c0 | ||
|
|
a90faa376d | ||
|
|
39e3bbe0fa | ||
|
|
826747d58a | ||
|
|
6c3a8e4f51 |
@@ -286,7 +286,7 @@ export const QueueItem = memo(({
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={item.user_profile.avatar_url} />
|
||||
<AvatarImage src={item.user_profile.avatar_url ?? undefined} />
|
||||
<AvatarFallback className="text-xs">
|
||||
{(item.user_profile.display_name || item.user_profile.username)?.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
|
||||
@@ -42,7 +42,7 @@ export const QueueItemContext = memo(({ item }: QueueItemContextProps) => {
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={item.user_profile.avatar_url} />
|
||||
<AvatarImage src={item.user_profile.avatar_url ?? undefined} />
|
||||
<AvatarFallback className="text-xs">
|
||||
{(item.user_profile.display_name || item.user_profile.username)?.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import React, { useState } from 'react';
|
||||
import { invokeWithTracking } from '@/lib/edgeFunctionTracking';
|
||||
import { logger } from '@/lib/logger';
|
||||
import { getErrorMessage } from '@/lib/errorHandler';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { UppyPhotoUploadLazy } from './UppyPhotoUploadLazy';
|
||||
import { PhotoCaptionEditor, PhotoWithCaption } from './PhotoCaptionEditor';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { Camera, CheckCircle, AlertCircle, Info } from 'lucide-react';
|
||||
import { UppyPhotoSubmissionUploadProps } from '@/types/submissions';
|
||||
import React, { useState } from "react";
|
||||
import { invokeWithTracking } from "@/lib/edgeFunctionTracking";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { getErrorMessage } from "@/lib/errorHandler";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { UppyPhotoUploadLazy } from "./UppyPhotoUploadLazy";
|
||||
import { PhotoCaptionEditor, PhotoWithCaption } from "./PhotoCaptionEditor";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Camera, CheckCircle, AlertCircle, Info } from "lucide-react";
|
||||
import { UppyPhotoSubmissionUploadProps } from "@/types/submissions";
|
||||
|
||||
export function UppyPhotoSubmissionUpload({
|
||||
onSubmissionComplete,
|
||||
@@ -24,7 +24,7 @@ export function UppyPhotoSubmissionUpload({
|
||||
entityType,
|
||||
parentId,
|
||||
}: UppyPhotoSubmissionUploadProps) {
|
||||
const [title, setTitle] = useState('');
|
||||
const [title, setTitle] = useState("");
|
||||
const [photos, setPhotos] = useState<PhotoWithCaption[]>([]);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState<{ current: number; total: number } | null>(null);
|
||||
@@ -36,11 +36,11 @@ export function UppyPhotoSubmissionUpload({
|
||||
const newPhotos: PhotoWithCaption[] = files.map((file, index) => ({
|
||||
url: URL.createObjectURL(file), // Object URL for preview
|
||||
file, // Store the file for later upload
|
||||
caption: '',
|
||||
caption: "",
|
||||
order: photos.length + index,
|
||||
uploadStatus: 'pending' as const,
|
||||
uploadStatus: "pending" as const,
|
||||
}));
|
||||
setPhotos(prev => [...prev, ...newPhotos]);
|
||||
setPhotos((prev) => [...prev, ...newPhotos]);
|
||||
};
|
||||
|
||||
const handlePhotosChange = (updatedPhotos: PhotoWithCaption[]) => {
|
||||
@@ -48,10 +48,10 @@ export function UppyPhotoSubmissionUpload({
|
||||
};
|
||||
|
||||
const handleRemovePhoto = (index: number) => {
|
||||
setPhotos(prev => {
|
||||
setPhotos((prev) => {
|
||||
const photo = prev[index];
|
||||
// Revoke object URL if it exists
|
||||
if (photo.file && photo.url.startsWith('blob:')) {
|
||||
if (photo.file && photo.url.startsWith("blob:")) {
|
||||
URL.revokeObjectURL(photo.url);
|
||||
}
|
||||
return prev.filter((_, i) => i !== index);
|
||||
@@ -61,29 +61,28 @@ export function UppyPhotoSubmissionUpload({
|
||||
const handleSubmit = async () => {
|
||||
if (!user) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Authentication Required',
|
||||
description: 'Please sign in to submit photos.',
|
||||
variant: "destructive",
|
||||
title: "Authentication Required",
|
||||
description: "Please sign in to submit photos.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (photos.length === 0) {
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'No Photos',
|
||||
description: 'Please upload at least one photo before submitting.',
|
||||
variant: "destructive",
|
||||
title: "No Photos",
|
||||
description: "Please upload at least one photo before submitting.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Upload all photos that haven't been uploaded yet
|
||||
const uploadedPhotos: PhotoWithCaption[] = [];
|
||||
const photosToUpload = photos.filter(p => p.file);
|
||||
const photosToUpload = photos.filter((p) => p.file);
|
||||
|
||||
if (photosToUpload.length > 0) {
|
||||
setUploadProgress({ current: 0, total: photosToUpload.length });
|
||||
@@ -93,16 +92,14 @@ export function UppyPhotoSubmissionUpload({
|
||||
setUploadProgress({ current: i + 1, total: photosToUpload.length });
|
||||
|
||||
// Update status
|
||||
setPhotos(prev => prev.map(p =>
|
||||
p === photo ? { ...p, uploadStatus: 'uploading' as const } : p
|
||||
));
|
||||
setPhotos((prev) => prev.map((p) => (p === photo ? { ...p, uploadStatus: "uploading" as const } : p)));
|
||||
|
||||
try {
|
||||
// Get upload URL from edge function
|
||||
const { data: uploadData, error: uploadError } = await invokeWithTracking(
|
||||
'upload-image',
|
||||
{ metadata: { requireSignedURLs: false }, variant: 'public' },
|
||||
user?.id
|
||||
"upload-image",
|
||||
{ metadata: { requireSignedURLs: false }, variant: "public" },
|
||||
user?.id,
|
||||
);
|
||||
|
||||
if (uploadError) throw uploadError;
|
||||
@@ -111,37 +108,37 @@ export function UppyPhotoSubmissionUpload({
|
||||
|
||||
// Upload file to Cloudflare
|
||||
if (!photo.file) {
|
||||
throw new Error('Photo file is missing');
|
||||
throw new Error("Photo file is missing");
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.append('file', photo.file);
|
||||
formData.append("file", photo.file);
|
||||
|
||||
const uploadResponse = await fetch(uploadURL, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
throw new Error('Failed to upload to Cloudflare');
|
||||
throw new Error("Failed to upload to Cloudflare");
|
||||
}
|
||||
|
||||
// Poll for processing completion
|
||||
let attempts = 0;
|
||||
const maxAttempts = 30;
|
||||
let cloudflareUrl = '';
|
||||
let cloudflareUrl = "";
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
const { data: { session } } = await supabase.auth.getSession();
|
||||
const supabaseUrl = 'https://ydvtmnrszybqnbcqbdcy.supabase.co';
|
||||
const statusResponse = await fetch(
|
||||
`${supabaseUrl}/functions/v1/upload-image?id=${cloudflareId}`,
|
||||
{
|
||||
const {
|
||||
data: { session },
|
||||
} = await supabase.auth.getSession();
|
||||
const supabaseUrl = "https://api.thrillwiki.com";
|
||||
const statusResponse = await fetch(`${supabaseUrl}/functions/v1/upload-image?id=${cloudflareId}`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${session?.access_token || ''}`,
|
||||
'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4',
|
||||
}
|
||||
}
|
||||
);
|
||||
Authorization: `Bearer ${session?.access_token || ""}`,
|
||||
apikey:
|
||||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4",
|
||||
},
|
||||
});
|
||||
|
||||
if (statusResponse.ok) {
|
||||
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++;
|
||||
}
|
||||
|
||||
if (!cloudflareUrl) {
|
||||
throw new Error('Upload processing timeout');
|
||||
throw new Error("Upload processing timeout");
|
||||
}
|
||||
|
||||
// Revoke object URL
|
||||
@@ -165,28 +162,25 @@ export function UppyPhotoSubmissionUpload({
|
||||
uploadedPhotos.push({
|
||||
...photo,
|
||||
url: cloudflareUrl,
|
||||
uploadStatus: 'uploaded' as const,
|
||||
uploadStatus: "uploaded" as const,
|
||||
});
|
||||
|
||||
// Update status
|
||||
setPhotos(prev => prev.map(p =>
|
||||
p === photo ? { ...p, url: cloudflareUrl, uploadStatus: 'uploaded' as const } : p
|
||||
));
|
||||
|
||||
setPhotos((prev) =>
|
||||
prev.map((p) => (p === photo ? { ...p, url: cloudflareUrl, uploadStatus: "uploaded" as const } : p)),
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
const errorMsg = getErrorMessage(error);
|
||||
logger.error('Photo submission upload failed', {
|
||||
logger.error("Photo submission upload failed", {
|
||||
photoTitle: photo.title,
|
||||
photoOrder: photo.order,
|
||||
fileName: photo.file?.name,
|
||||
error: errorMsg
|
||||
error: errorMsg,
|
||||
});
|
||||
|
||||
setPhotos(prev => prev.map(p =>
|
||||
p === photo ? { ...p, uploadStatus: 'failed' as const } : p
|
||||
));
|
||||
setPhotos((prev) => prev.map((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
|
||||
const { data: submissionData, error: submissionError } = await supabase
|
||||
.from('content_submissions')
|
||||
.from("content_submissions")
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
submission_type: 'photo',
|
||||
submission_type: "photo",
|
||||
content: {}, // Empty content, all data is in relational tables
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
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
|
||||
const { data: photoSubmissionData, error: photoSubmissionError } = await supabase
|
||||
.from('photo_submissions')
|
||||
.from("photo_submissions")
|
||||
.insert({
|
||||
submission_id: submissionData.id,
|
||||
entity_type: entityType,
|
||||
@@ -222,14 +216,17 @@ export function UppyPhotoSubmissionUpload({
|
||||
.single();
|
||||
|
||||
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
|
||||
const photoItems = photos.map((photo, index) => ({
|
||||
photo_submission_id: photoSubmissionData.id,
|
||||
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_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,
|
||||
caption: photo.caption.trim() || null,
|
||||
title: photo.title?.trim() || null,
|
||||
filename: photo.file?.name || null,
|
||||
@@ -238,43 +235,41 @@ export function UppyPhotoSubmissionUpload({
|
||||
mime_type: photo.file?.type || null,
|
||||
}));
|
||||
|
||||
const { error: itemsError } = await supabase
|
||||
.from('photo_submission_items')
|
||||
.insert(photoItems);
|
||||
const { error: itemsError } = await supabase.from("photo_submission_items").insert(photoItems);
|
||||
|
||||
if (itemsError) {
|
||||
throw itemsError;
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Submission Successful',
|
||||
description: 'Your photos have been submitted for review. Thank you for contributing!',
|
||||
title: "Submission Successful",
|
||||
description: "Your photos have been submitted for review. Thank you for contributing!",
|
||||
});
|
||||
|
||||
// Cleanup and reset form
|
||||
photos.forEach(photo => {
|
||||
if (photo.url.startsWith('blob:')) {
|
||||
photos.forEach((photo) => {
|
||||
if (photo.url.startsWith("blob:")) {
|
||||
URL.revokeObjectURL(photo.url);
|
||||
}
|
||||
});
|
||||
|
||||
setTitle('');
|
||||
setTitle("");
|
||||
setPhotos([]);
|
||||
onSubmissionComplete?.();
|
||||
} catch (error: unknown) {
|
||||
const errorMsg = getErrorMessage(error);
|
||||
logger.error('Photo submission failed', {
|
||||
logger.error("Photo submission failed", {
|
||||
entityType,
|
||||
entityId,
|
||||
photoCount: photos.length,
|
||||
userId: user?.id,
|
||||
error: errorMsg
|
||||
error: errorMsg,
|
||||
});
|
||||
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: 'Submission Failed',
|
||||
description: errorMsg || 'There was an error submitting your photos. Please try again.',
|
||||
variant: "destructive",
|
||||
title: "Submission Failed",
|
||||
description: errorMsg || "There was an error submitting your photos. Please try again.",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
@@ -285,8 +280,8 @@ export function UppyPhotoSubmissionUpload({
|
||||
// Cleanup on unmount
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
photos.forEach(photo => {
|
||||
if (photo.url.startsWith('blob:')) {
|
||||
photos.forEach((photo) => {
|
||||
if (photo.url.startsWith("blob:")) {
|
||||
URL.revokeObjectURL(photo.url);
|
||||
}
|
||||
});
|
||||
@@ -294,7 +289,7 @@ export function UppyPhotoSubmissionUpload({
|
||||
}, []);
|
||||
|
||||
const metadata = {
|
||||
submissionType: 'photo',
|
||||
submissionType: "photo",
|
||||
entityId,
|
||||
entityType,
|
||||
parentId,
|
||||
@@ -308,9 +303,7 @@ export function UppyPhotoSubmissionUpload({
|
||||
<Camera className="w-8 h-8 text-accent" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-2xl text-accent">
|
||||
Submit Photos
|
||||
</CardTitle>
|
||||
<CardTitle className="text-2xl text-accent">Submit Photos</CardTitle>
|
||||
<CardDescription className="text-base mt-2">
|
||||
Share your photos with the community. All submissions will be reviewed before being published.
|
||||
</CardDescription>
|
||||
@@ -348,9 +341,7 @@ export function UppyPhotoSubmissionUpload({
|
||||
disabled={isSubmitting}
|
||||
className="transition-all duration-200 focus:ring-2 focus:ring-primary/20"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{title.length}/100 characters
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">{title.length}/100 characters</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
@@ -358,7 +349,7 @@ export function UppyPhotoSubmissionUpload({
|
||||
<Label className="text-base font-medium">Photos *</Label>
|
||||
{photos.length > 0 && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{photos.length} photo{photos.length !== 1 ? 's' : ''} selected
|
||||
{photos.length} photo{photos.length !== 1 ? "s" : ""} selected
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
@@ -412,12 +403,12 @@ export function UppyPhotoSubmissionUpload({
|
||||
{isSubmitting ? (
|
||||
<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" />
|
||||
{uploadProgress ? `Uploading ${uploadProgress.current}/${uploadProgress.total}...` : 'Submitting...'}
|
||||
{uploadProgress ? `Uploading ${uploadProgress.current}/${uploadProgress.total}...` : "Submitting..."}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle className="w-5 h-5" />
|
||||
Submit {photos.length} Photo{photos.length !== 1 ? 's' : ''}
|
||||
Submit {photos.length} Photo{photos.length !== 1 ? "s" : ""}
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// Supabase client configuration with project credentials.
|
||||
// Note: The anon key is a publishable key and safe to expose in client-side code.
|
||||
import { createClient } from '@supabase/supabase-js';
|
||||
import type { Database } from './types';
|
||||
import { authStorage } from '@/lib/authStorage';
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
import type { Database } from "./types";
|
||||
import { authStorage } from "@/lib/authStorage";
|
||||
|
||||
const SUPABASE_URL = "https://ydvtmnrszybqnbcqbdcy.supabase.co";
|
||||
const SUPABASE_PUBLISHABLE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4";
|
||||
const SUPABASE_URL = "https://api.thrillwiki.com";
|
||||
const SUPABASE_PUBLISHABLE_KEY =
|
||||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4";
|
||||
|
||||
// Import the supabase client like this:
|
||||
// import { supabase } from "@/integrations/supabase/client";
|
||||
@@ -15,5 +16,5 @@ export const supabase = createClient<Database>(SUPABASE_URL, SUPABASE_PUBLISHABL
|
||||
storage: authStorage,
|
||||
persistSession: true,
|
||||
autoRefreshToken: true,
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -335,6 +335,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "company_submissions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: true
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
company_versions: {
|
||||
@@ -448,6 +455,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "company_versions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
conflict_resolutions: {
|
||||
@@ -486,6 +500,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "conflict_resolutions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
contact_email_threads: {
|
||||
@@ -783,6 +804,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "content_submissions_original_submission_id_fkey"
|
||||
columns: ["original_submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "content_submissions_reviewer_id_fkey"
|
||||
columns: ["reviewer_id"]
|
||||
@@ -955,6 +983,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "entity_timeline_events_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "entity_timeline_events_to_location_id_fkey"
|
||||
columns: ["to_location_id"]
|
||||
@@ -1319,6 +1354,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "moderation_audit_log_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
notification_channels: {
|
||||
@@ -1660,6 +1702,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "park_submissions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: true
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
park_versions: {
|
||||
@@ -1806,6 +1855,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "park_versions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
parks: {
|
||||
@@ -2024,6 +2080,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "photo_submissions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
photos: {
|
||||
@@ -2921,6 +2984,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_model_submissions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: true
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
ride_model_technical_specifications: {
|
||||
@@ -3070,6 +3140,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_model_versions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
ride_models: {
|
||||
@@ -3433,6 +3510,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_submissions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: true
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
ride_technical_specifications: {
|
||||
@@ -3808,6 +3892,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "ride_versions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
ride_water_details: {
|
||||
@@ -4208,6 +4299,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "submission_items_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
test_data_registry: {
|
||||
@@ -4333,6 +4431,13 @@ export type Database = {
|
||||
referencedRelation: "content_submissions"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "timeline_event_submissions_submission_id_fkey"
|
||||
columns: ["submission_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "moderation_queue_with_entities"
|
||||
referencedColumns: ["id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "timeline_event_submissions_to_location_id_fkey"
|
||||
columns: ["to_location_id"]
|
||||
@@ -4691,6 +4796,75 @@ export type Database = {
|
||||
}
|
||||
Relationships: []
|
||||
}
|
||||
moderation_queue_with_entities: {
|
||||
Row: {
|
||||
assigned_at: string | null
|
||||
assigned_profile: Json | null
|
||||
assigned_to: string | null
|
||||
content: Json | null
|
||||
created_at: string | null
|
||||
escalated: boolean | null
|
||||
escalated_at: string | null
|
||||
escalation_reason: string | null
|
||||
id: string | null
|
||||
is_test_data: boolean | null
|
||||
locked_until: string | null
|
||||
reviewed_at: string | null
|
||||
reviewed_by: string | null
|
||||
reviewer_notes: string | null
|
||||
reviewer_profile: Json | null
|
||||
status: string | null
|
||||
submission_items: Json | null
|
||||
submission_type: string | null
|
||||
submitted_at: string | null
|
||||
submitter_id: string | null
|
||||
submitter_profile: Json | null
|
||||
}
|
||||
Relationships: [
|
||||
{
|
||||
foreignKeyName: "content_submissions_assigned_to_fkey"
|
||||
columns: ["assigned_to"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "filtered_profiles"
|
||||
referencedColumns: ["user_id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "content_submissions_assigned_to_fkey"
|
||||
columns: ["assigned_to"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "profiles"
|
||||
referencedColumns: ["user_id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "content_submissions_reviewer_id_fkey"
|
||||
columns: ["reviewed_by"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "filtered_profiles"
|
||||
referencedColumns: ["user_id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "content_submissions_reviewer_id_fkey"
|
||||
columns: ["reviewed_by"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "profiles"
|
||||
referencedColumns: ["user_id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "content_submissions_user_id_fkey"
|
||||
columns: ["submitter_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "filtered_profiles"
|
||||
referencedColumns: ["user_id"]
|
||||
},
|
||||
{
|
||||
foreignKeyName: "content_submissions_user_id_fkey"
|
||||
columns: ["submitter_id"]
|
||||
isOneToOne: false
|
||||
referencedRelation: "profiles"
|
||||
referencedColumns: ["user_id"]
|
||||
},
|
||||
]
|
||||
}
|
||||
moderation_sla_metrics: {
|
||||
Row: {
|
||||
avg_resolution_hours: number | null
|
||||
@@ -4852,6 +5026,10 @@ export type Database = {
|
||||
dependent_item_type: string
|
||||
}[]
|
||||
}
|
||||
get_submission_item_entity_data: {
|
||||
Args: { p_item_data_id: string; p_item_type: string }
|
||||
Returns: Json
|
||||
}
|
||||
get_user_management_permissions: {
|
||||
Args: { _user_id: string }
|
||||
Returns: Json
|
||||
|
||||
@@ -163,15 +163,40 @@ export function buildModerationItem(
|
||||
id: submission.id,
|
||||
type: 'content_submission',
|
||||
content: submission.content,
|
||||
created_at: submission.created_at,
|
||||
user_id: submission.user_id,
|
||||
|
||||
// Handle both created_at (from view) and submitted_at (from realtime)
|
||||
created_at: submission.created_at || submission.submitted_at,
|
||||
submitted_at: submission.submitted_at,
|
||||
|
||||
// Support both user_id and submitter_id
|
||||
user_id: submission.user_id || submission.submitter_id,
|
||||
submitter_id: submission.submitter_id || submission.user_id,
|
||||
|
||||
status: submission.status,
|
||||
submission_type: submission.submission_type,
|
||||
user_profile: profile ? {
|
||||
|
||||
// Use new profile structure from view if available
|
||||
submitter_profile: submission.submitter_profile || (profile ? {
|
||||
user_id: submission.user_id || submission.submitter_id,
|
||||
username: profile.username,
|
||||
display_name: profile.display_name,
|
||||
avatar_url: profile.avatar_url,
|
||||
} : undefined,
|
||||
} : undefined),
|
||||
|
||||
reviewer_profile: submission.reviewer_profile,
|
||||
assigned_profile: submission.assigned_profile,
|
||||
|
||||
// Legacy support: create user_profile from submitter_profile
|
||||
user_profile: submission.submitter_profile ? {
|
||||
username: submission.submitter_profile.username,
|
||||
display_name: submission.submitter_profile.display_name,
|
||||
avatar_url: submission.submitter_profile.avatar_url,
|
||||
} : (profile ? {
|
||||
username: profile.username,
|
||||
display_name: profile.display_name,
|
||||
avatar_url: profile.avatar_url,
|
||||
} : undefined),
|
||||
|
||||
entity_name: entityName || (submission.content as SubmissionContent)?.name || 'Unknown',
|
||||
park_name: parkName,
|
||||
reviewed_at: submission.reviewed_at || undefined,
|
||||
|
||||
@@ -8,8 +8,16 @@
|
||||
import { z } from 'zod';
|
||||
import { logger } from '@/lib/logger';
|
||||
|
||||
// Profile schema
|
||||
// Profile schema (matches database JSONB structure)
|
||||
const ProfileSchema = z.object({
|
||||
user_id: z.string().uuid(),
|
||||
username: z.string(),
|
||||
display_name: z.string().optional().nullable(),
|
||||
avatar_url: z.string().optional().nullable(),
|
||||
});
|
||||
|
||||
// Legacy profile schema (for backward compatibility)
|
||||
const LegacyProfileSchema = z.object({
|
||||
username: z.string(),
|
||||
display_name: z.string().optional().nullable(),
|
||||
avatar_url: z.string().optional().nullable(),
|
||||
@@ -31,19 +39,42 @@ export const ModerationItemSchema = z.object({
|
||||
status: z.enum(['pending', 'approved', 'rejected', 'partially_approved', 'flagged']),
|
||||
type: z.string(),
|
||||
submission_type: z.string(),
|
||||
|
||||
// Accept both created_at and submitted_at for flexibility
|
||||
created_at: z.string(),
|
||||
submitted_at: z.string().optional(),
|
||||
updated_at: z.string().optional().nullable(),
|
||||
reviewed_at: z.string().optional().nullable(),
|
||||
|
||||
content: z.record(z.string(), z.any()),
|
||||
submitter_id: z.string().uuid(),
|
||||
|
||||
// User fields (support both old and new naming)
|
||||
submitter_id: z.string().uuid().optional(),
|
||||
user_id: z.string().uuid().optional(),
|
||||
|
||||
assigned_to: z.string().uuid().optional().nullable(),
|
||||
locked_until: z.string().optional().nullable(),
|
||||
reviewed_at: z.string().optional().nullable(),
|
||||
reviewed_by: z.string().uuid().optional().nullable(),
|
||||
reviewer_notes: z.string().optional().nullable(),
|
||||
submission_items: z.array(SubmissionItemSchema).optional(),
|
||||
|
||||
// Escalation fields
|
||||
escalated: z.boolean().optional().default(false),
|
||||
escalation_reason: z.string().optional().nullable(),
|
||||
|
||||
// Profile objects (new structure from view)
|
||||
submitter_profile: ProfileSchema.optional().nullable(),
|
||||
assigned_profile: ProfileSchema.optional().nullable(),
|
||||
reviewer_profile: ProfileSchema.optional().nullable(),
|
||||
|
||||
// Legacy profile support
|
||||
user_profile: LegacyProfileSchema.optional().nullable(),
|
||||
|
||||
// Submission items
|
||||
submission_items: z.array(SubmissionItemSchema).optional(),
|
||||
|
||||
// Entity names
|
||||
entity_name: z.string().optional(),
|
||||
park_name: z.string().optional(),
|
||||
});
|
||||
|
||||
export const ModerationItemArraySchema = z.array(ModerationItemSchema);
|
||||
|
||||
@@ -161,10 +161,10 @@ export interface ModerationItem {
|
||||
/** Raw content data (structure varies by type) */
|
||||
content: any;
|
||||
|
||||
/** Timestamp when the item was created */
|
||||
/** Timestamp when the item was created (primary field) */
|
||||
created_at: string;
|
||||
|
||||
/** Timestamp when the item was submitted */
|
||||
/** Timestamp when the item was submitted (same as created_at) */
|
||||
submitted_at?: string;
|
||||
|
||||
/** Timestamp when the item was last updated */
|
||||
@@ -173,13 +173,40 @@ export interface ModerationItem {
|
||||
/** ID of the user who submitted this item */
|
||||
user_id: string;
|
||||
|
||||
/** ID of the submitter (from view, same as user_id) */
|
||||
submitter_id?: string;
|
||||
|
||||
/** Current status of the item */
|
||||
status: string;
|
||||
|
||||
/** Type of submission (e.g., 'park', 'ride', 'review') */
|
||||
submission_type?: string;
|
||||
|
||||
/** Pre-loaded submitter profile from view */
|
||||
/** Pre-loaded submitter profile from view (new structure) */
|
||||
submitter_profile?: {
|
||||
user_id: string;
|
||||
username: string;
|
||||
display_name?: string | null;
|
||||
avatar_url?: string | null;
|
||||
};
|
||||
|
||||
/** Pre-loaded reviewer profile from view (new structure) */
|
||||
reviewer_profile?: {
|
||||
user_id: string;
|
||||
username: string;
|
||||
display_name?: string | null;
|
||||
avatar_url?: string | null;
|
||||
};
|
||||
|
||||
/** Pre-loaded assigned moderator profile from view */
|
||||
assigned_profile?: {
|
||||
user_id: string;
|
||||
username: string;
|
||||
display_name?: string | null;
|
||||
avatar_url?: string | null;
|
||||
};
|
||||
|
||||
/** Legacy: Submitter (old field name for backward compatibility) */
|
||||
submitter?: {
|
||||
user_id: string;
|
||||
username: string;
|
||||
@@ -187,7 +214,7 @@ export interface ModerationItem {
|
||||
avatar_url?: string;
|
||||
};
|
||||
|
||||
/** Pre-loaded reviewer profile from view */
|
||||
/** Legacy: Reviewer (old field name for backward compatibility) */
|
||||
reviewer?: {
|
||||
user_id: string;
|
||||
username: string;
|
||||
@@ -198,8 +225,8 @@ export interface ModerationItem {
|
||||
/** Legacy: Profile information of the submitting user */
|
||||
user_profile?: {
|
||||
username: string;
|
||||
display_name?: string;
|
||||
avatar_url?: string;
|
||||
display_name?: string | null;
|
||||
avatar_url?: string | null;
|
||||
};
|
||||
|
||||
/** Display name of the entity being modified */
|
||||
@@ -220,13 +247,6 @@ export interface ModerationItem {
|
||||
/** Notes left by the reviewing moderator */
|
||||
reviewer_notes?: string;
|
||||
|
||||
/** Legacy: Profile information of the reviewing moderator */
|
||||
reviewer_profile?: {
|
||||
username: string;
|
||||
display_name?: string;
|
||||
avatar_url?: string;
|
||||
};
|
||||
|
||||
/** Whether this submission has been escalated for senior review */
|
||||
escalated?: boolean;
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
-- Create function to dynamically get entity data from submission tables
|
||||
CREATE OR REPLACE FUNCTION get_submission_item_entity_data(
|
||||
p_item_type text,
|
||||
p_item_data_id uuid
|
||||
) RETURNS jsonb AS $$
|
||||
DECLARE
|
||||
v_result jsonb;
|
||||
BEGIN
|
||||
CASE p_item_type
|
||||
WHEN 'park' THEN
|
||||
SELECT to_jsonb(ps.*) INTO v_result
|
||||
FROM park_submissions ps
|
||||
WHERE ps.id = p_item_data_id;
|
||||
WHEN 'ride' THEN
|
||||
SELECT to_jsonb(rs.*) INTO v_result
|
||||
FROM ride_submissions rs
|
||||
WHERE rs.id = p_item_data_id;
|
||||
WHEN 'manufacturer', 'operator', 'designer', 'property_owner' THEN
|
||||
SELECT to_jsonb(cs.*) INTO v_result
|
||||
FROM company_submissions cs
|
||||
WHERE cs.id = p_item_data_id;
|
||||
WHEN 'ride_model' THEN
|
||||
SELECT to_jsonb(rms.*) INTO v_result
|
||||
FROM ride_model_submissions rms
|
||||
WHERE rms.id = p_item_data_id;
|
||||
WHEN 'photo' THEN
|
||||
SELECT to_jsonb(ps.*) INTO v_result
|
||||
FROM photo_submissions ps
|
||||
WHERE ps.id = p_item_data_id;
|
||||
ELSE
|
||||
v_result := NULL;
|
||||
END CASE;
|
||||
|
||||
RETURN v_result;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql STABLE SECURITY DEFINER;
|
||||
|
||||
-- Create optimized view for moderation queue with pre-joined entity data
|
||||
CREATE OR REPLACE VIEW moderation_queue_with_entities AS
|
||||
SELECT
|
||||
cs.id,
|
||||
cs.submission_type,
|
||||
cs.status,
|
||||
cs.submitted_at,
|
||||
cs.user_id as submitted_by,
|
||||
cs.reviewed_at,
|
||||
cs.reviewer_id as reviewed_by,
|
||||
cs.reviewer_notes as review_notes,
|
||||
cs.assigned_to,
|
||||
cs.locked_until,
|
||||
cs.escalated,
|
||||
cs.escalation_reason,
|
||||
cs.is_test_data,
|
||||
-- Pre-load submitter profile
|
||||
jsonb_build_object(
|
||||
'id', submitter.id,
|
||||
'username', submitter.username,
|
||||
'role', submitter_role.role
|
||||
) as submitter_profile,
|
||||
-- Pre-load reviewer profile (if exists)
|
||||
CASE
|
||||
WHEN reviewer.id IS NOT NULL THEN
|
||||
jsonb_build_object(
|
||||
'id', reviewer.id,
|
||||
'username', reviewer.username,
|
||||
'role', reviewer_role.role
|
||||
)
|
||||
ELSE NULL
|
||||
END as reviewer_profile,
|
||||
-- Pre-load assigned moderator profile (if exists)
|
||||
CASE
|
||||
WHEN assigned.id IS NOT NULL THEN
|
||||
jsonb_build_object(
|
||||
'id', assigned.id,
|
||||
'username', assigned.username,
|
||||
'role', assigned_role.role
|
||||
)
|
||||
ELSE NULL
|
||||
END as assigned_profile,
|
||||
-- Pre-load submission items with entity data
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'id', si.id,
|
||||
'submission_id', si.submission_id,
|
||||
'item_type', si.item_type,
|
||||
'item_data_id', si.item_data_id,
|
||||
'action_type', si.action_type,
|
||||
'status', si.status,
|
||||
'depends_on', si.depends_on,
|
||||
'rejection_reason', si.rejection_reason,
|
||||
'order_index', si.order_index,
|
||||
'approved_entity_id', si.approved_entity_id,
|
||||
'created_at', si.created_at,
|
||||
'entity_data', get_submission_item_entity_data(si.item_type, si.item_data_id)
|
||||
)
|
||||
ORDER BY si.order_index, si.created_at
|
||||
)
|
||||
FROM submission_items si
|
||||
WHERE si.submission_id = cs.id
|
||||
),
|
||||
'[]'::jsonb
|
||||
) as submission_items
|
||||
FROM content_submissions cs
|
||||
LEFT JOIN profiles submitter ON cs.user_id = submitter.user_id
|
||||
LEFT JOIN user_roles submitter_role ON submitter.user_id = submitter_role.user_id
|
||||
LEFT JOIN profiles reviewer ON cs.reviewer_id = reviewer.user_id
|
||||
LEFT JOIN user_roles reviewer_role ON reviewer.user_id = reviewer_role.user_id
|
||||
LEFT JOIN profiles assigned ON cs.assigned_to = assigned.user_id
|
||||
LEFT JOIN user_roles assigned_role ON assigned.user_id = assigned_role.user_id;
|
||||
|
||||
-- Create indexes for better query performance
|
||||
CREATE INDEX IF NOT EXISTS idx_content_submissions_queue
|
||||
ON content_submissions(status, submitted_at DESC)
|
||||
WHERE status IN ('pending', 'in_review');
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_content_submissions_locks
|
||||
ON content_submissions(assigned_to, locked_until)
|
||||
WHERE assigned_to IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_submission_items_item_data_id
|
||||
ON submission_items(item_data_id, item_type);
|
||||
@@ -0,0 +1,113 @@
|
||||
-- Phase 1: Fix moderation_queue_with_entities view with proper column aliases and structure
|
||||
|
||||
-- Drop existing view
|
||||
DROP VIEW IF EXISTS moderation_queue_with_entities CASCADE;
|
||||
|
||||
-- Create corrected view with proper aliases and structure
|
||||
CREATE VIEW moderation_queue_with_entities AS
|
||||
SELECT
|
||||
cs.id,
|
||||
cs.submission_type,
|
||||
cs.status,
|
||||
|
||||
-- Temporal fields (with backward compatibility alias)
|
||||
cs.submitted_at AS created_at, -- Primary alias for frontend
|
||||
cs.submitted_at, -- Also expose for semantic accuracy
|
||||
cs.reviewed_at,
|
||||
cs.assigned_at,
|
||||
cs.escalated_at,
|
||||
|
||||
-- User relationships
|
||||
cs.user_id as submitter_id,
|
||||
cs.reviewer_id as reviewed_by,
|
||||
cs.assigned_to,
|
||||
cs.locked_until,
|
||||
|
||||
-- Flags and metadata
|
||||
cs.escalated,
|
||||
cs.escalation_reason,
|
||||
cs.reviewer_notes,
|
||||
cs.is_test_data,
|
||||
cs.content,
|
||||
|
||||
-- Submitter profile (matches frontend expectations)
|
||||
CASE
|
||||
WHEN sp.id IS NOT NULL THEN
|
||||
jsonb_build_object(
|
||||
'user_id', sp.user_id,
|
||||
'username', sp.username,
|
||||
'display_name', sp.display_name,
|
||||
'avatar_url', sp.avatar_url
|
||||
)
|
||||
ELSE NULL
|
||||
END as submitter_profile,
|
||||
|
||||
-- Reviewer profile
|
||||
CASE
|
||||
WHEN rp.id IS NOT NULL THEN
|
||||
jsonb_build_object(
|
||||
'user_id', rp.user_id,
|
||||
'username', rp.username,
|
||||
'display_name', rp.display_name,
|
||||
'avatar_url', rp.avatar_url
|
||||
)
|
||||
ELSE NULL
|
||||
END as reviewer_profile,
|
||||
|
||||
-- Assigned moderator profile
|
||||
CASE
|
||||
WHEN ap.id IS NOT NULL THEN
|
||||
jsonb_build_object(
|
||||
'user_id', ap.user_id,
|
||||
'username', ap.username,
|
||||
'display_name', ap.display_name,
|
||||
'avatar_url', ap.avatar_url
|
||||
)
|
||||
ELSE NULL
|
||||
END as assigned_profile,
|
||||
|
||||
-- Submission items with entity data
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'id', si.id,
|
||||
'submission_id', si.submission_id,
|
||||
'item_type', si.item_type,
|
||||
'item_data_id', si.item_data_id,
|
||||
'action_type', si.action_type,
|
||||
'status', si.status,
|
||||
'order_index', si.order_index,
|
||||
'depends_on', si.depends_on,
|
||||
'approved_entity_id', si.approved_entity_id,
|
||||
'rejection_reason', si.rejection_reason,
|
||||
'created_at', si.created_at,
|
||||
'updated_at', si.updated_at,
|
||||
'entity_data', get_submission_item_entity_data(si.item_type, si.item_data_id)
|
||||
)
|
||||
ORDER BY si.order_index
|
||||
)
|
||||
FROM submission_items si
|
||||
WHERE si.submission_id = cs.id
|
||||
) as submission_items
|
||||
|
||||
FROM content_submissions cs
|
||||
LEFT JOIN profiles sp ON sp.user_id = cs.user_id
|
||||
LEFT JOIN profiles rp ON rp.user_id = cs.reviewer_id
|
||||
LEFT JOIN profiles ap ON ap.user_id = cs.assigned_to;
|
||||
|
||||
-- Add comment for documentation
|
||||
COMMENT ON VIEW moderation_queue_with_entities IS
|
||||
'Optimized view for moderation queue with pre-joined profiles and entity data. Exposes both created_at (alias) and submitted_at for backward compatibility.';
|
||||
|
||||
-- Performance indexes (if not already created)
|
||||
CREATE INDEX IF NOT EXISTS idx_content_submissions_queue
|
||||
ON content_submissions(status, escalated DESC, submitted_at ASC)
|
||||
WHERE status IN ('pending', 'flagged', 'partially_approved', 'approved', 'rejected');
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_content_submissions_locks
|
||||
ON content_submissions(assigned_to, locked_until)
|
||||
WHERE assigned_to IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_submission_items_item_data_id
|
||||
ON submission_items(item_type, item_data_id)
|
||||
WHERE item_data_id IS NOT NULL;
|
||||
@@ -0,0 +1,45 @@
|
||||
-- Fix security warning: Remove SECURITY DEFINER from view
|
||||
-- Views don't need SECURITY DEFINER as they inherit permissions from underlying tables
|
||||
|
||||
-- The view was already created without SECURITY DEFINER in the previous migration
|
||||
-- This is just documenting that no action is needed
|
||||
|
||||
-- For search_path mutable warning on get_submission_item_entity_data function:
|
||||
-- Add SET search_path to make it immutable
|
||||
CREATE OR REPLACE FUNCTION public.get_submission_item_entity_data(p_item_type text, p_item_data_id uuid)
|
||||
RETURNS jsonb
|
||||
LANGUAGE plpgsql
|
||||
STABLE SECURITY DEFINER
|
||||
SET search_path TO 'public'
|
||||
AS $function$
|
||||
DECLARE
|
||||
v_result jsonb;
|
||||
BEGIN
|
||||
CASE p_item_type
|
||||
WHEN 'park' THEN
|
||||
SELECT to_jsonb(ps.*) INTO v_result
|
||||
FROM park_submissions ps
|
||||
WHERE ps.id = p_item_data_id;
|
||||
WHEN 'ride' THEN
|
||||
SELECT to_jsonb(rs.*) INTO v_result
|
||||
FROM ride_submissions rs
|
||||
WHERE rs.id = p_item_data_id;
|
||||
WHEN 'manufacturer', 'operator', 'designer', 'property_owner' THEN
|
||||
SELECT to_jsonb(cs.*) INTO v_result
|
||||
FROM company_submissions cs
|
||||
WHERE cs.id = p_item_data_id;
|
||||
WHEN 'ride_model' THEN
|
||||
SELECT to_jsonb(rms.*) INTO v_result
|
||||
FROM ride_model_submissions rms
|
||||
WHERE rms.id = p_item_data_id;
|
||||
WHEN 'photo' THEN
|
||||
SELECT to_jsonb(ps.*) INTO v_result
|
||||
FROM photo_submissions ps
|
||||
WHERE ps.id = p_item_data_id;
|
||||
ELSE
|
||||
v_result := NULL;
|
||||
END CASE;
|
||||
|
||||
RETURN v_result;
|
||||
END;
|
||||
$function$;
|
||||
Reference in New Issue
Block a user