Finalize form display

This commit is contained in:
2024-09-26 18:14:04 -04:00
parent 6584a48f27
commit be56ead43f
7 changed files with 73 additions and 24 deletions

View File

@@ -32,7 +32,7 @@
"drizzle-orm": "^0.33.0", "drizzle-orm": "^0.33.0",
"geist": "^1.3.1", "geist": "^1.3.1",
"lucide-react": "^0.441.0", "lucide-react": "^0.441.0",
"next": "^14.2.12", "next": "^14.2.13",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
"pdf2pic": "^3.1.3", "pdf2pic": "^3.1.3",
"postgres": "^3.4.4", "postgres": "^3.4.4",

View File

@@ -12,12 +12,32 @@ export async function GET(
return new NextResponse('Unauthorized', { status: 401 }); return new NextResponse('Unauthorized', { status: 401 });
} }
// Construct the file path relative to the project root
const filePath = path.join(process.cwd(), 'content', ...params.path); const filePath = path.join(process.cwd(), 'content', ...params.path);
console.log('Attempting to read file:', filePath); // Add this log
try { try {
const file = await fs.readFile(filePath); const file = await fs.readFile(filePath);
const response = new NextResponse(file); const response = new NextResponse(file);
response.headers.set('Content-Type', 'application/pdf');
// Determine content type based on file extension
const ext = path.extname(filePath).toLowerCase();
switch (ext) {
case '.pdf':
response.headers.set('Content-Type', 'application/pdf');
break;
case '.png':
response.headers.set('Content-Type', 'image/png');
break;
case '.jpg':
case '.jpeg':
response.headers.set('Content-Type', 'image/jpeg');
break;
default:
response.headers.set('Content-Type', 'application/octet-stream');
}
return response; return response;
} catch (error) { } catch (error) {
console.error('Error reading file:', error); console.error('Error reading file:', error);

View File

@@ -26,6 +26,7 @@ export async function DELETE(
.select({ .select({
contentId: informedConsentForms.contentId, contentId: informedConsentForms.contentId,
location: contents.location, location: contents.location,
previewLocation: contents.previewLocation,
}) })
.from(informedConsentForms) .from(informedConsentForms)
.innerJoin(contents, eq(informedConsentForms.contentId, contents.id)) .innerJoin(contents, eq(informedConsentForms.contentId, contents.id))
@@ -35,14 +36,21 @@ export async function DELETE(
return NextResponse.json({ error: 'Form not found' }, { status: 404 }); return NextResponse.json({ error: 'Form not found' }, { status: 404 });
} }
// Delete the file from the file system // Delete the file and preview from the file system
const fullPath = path.join(process.cwd(), form.location); const fullPath = path.join(process.cwd(), form.location ?? '');
const previewPath = path.join(process.cwd(), form.previewLocation ?? '');
try { try {
await fs.access(fullPath); await fs.access(fullPath);
await fs.unlink(fullPath); await fs.unlink(fullPath);
} catch (error) { } catch (error) {
console.warn(`File not found or couldn't be deleted: ${fullPath}`); console.warn(`File not found or couldn't be deleted: ${fullPath}`);
} }
try {
await fs.access(previewPath);
await fs.unlink(previewPath);
} catch (error) {
console.warn(`Preview file not found or couldn't be deleted: ${previewPath}`);
}
// Delete the form and content from the database // Delete the form and content from the database
await db.transaction(async (tx) => { await db.transaction(async (tx) => {
@@ -50,7 +58,7 @@ export async function DELETE(
await tx.delete(contents).where(eq(contents.id, form.contentId)); await tx.delete(contents).where(eq(contents.id, form.contentId));
}); });
return NextResponse.json({ message: "Form deleted successfully" }); return NextResponse.json({ message: "Form and preview deleted successfully" });
} catch (error) { } catch (error) {
console.error('Error deleting form:', error); console.error('Error deleting form:', error);
return NextResponse.json({ error: 'Failed to delete form' }, { status: 500 }); return NextResponse.json({ error: 'Failed to delete form' }, { status: 500 });

View File

@@ -5,7 +5,7 @@ import { auth } from "@clerk/nextjs/server";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { saveFile } from "~/lib/fileStorage"; import { saveFile } from "~/lib/fileStorage";
import fs from 'fs/promises'; import fs from 'fs/promises';
import { studies, participants } from "~/server/db/schema";
// Function to generate a random string // Function to generate a random string
const generateRandomString = (length: number) => { const generateRandomString = (length: number) => {
const characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
@@ -28,10 +28,14 @@ export async function GET(request: Request) {
location: contents.location, location: contents.location,
previewLocation: contents.previewLocation, previewLocation: contents.previewLocation,
studyId: informedConsentForms.studyId, studyId: informedConsentForms.studyId,
studyTitle: studies.title,
participantId: informedConsentForms.participantId, participantId: informedConsentForms.participantId,
participantName: participants.name,
contentId: informedConsentForms.contentId, contentId: informedConsentForms.contentId,
}).from(informedConsentForms) }).from(informedConsentForms)
.innerJoin(contents, eq(informedConsentForms.contentId, contents.id)); .innerJoin(contents, eq(informedConsentForms.contentId, contents.id))
.innerJoin(studies, eq(informedConsentForms.studyId, studies.id))
.innerJoin(participants, eq(informedConsentForms.participantId, participants.id));
return NextResponse.json(forms); return NextResponse.json(forms);
} }

View File

@@ -1,6 +1,6 @@
import Image from 'next/image';
import { Card, CardContent, CardFooter } from "~/components/ui/card"; import { Card, CardContent, CardFooter } from "~/components/ui/card";
import { Badge } from "~/components/ui/badge"; import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";
import { Trash2 } from "lucide-react"; import { Trash2 } from "lucide-react";
interface FormCardProps { interface FormCardProps {
@@ -12,36 +12,45 @@ interface FormCardProps {
studyTitle: string; studyTitle: string;
participantId: number; participantId: number;
participantName: string; participantName: string;
previewLocation: string; // Added this property previewLocation: string;
}; };
onDelete: (formId: number) => void; onDelete: (formId: number) => void;
} }
export function FormCard({ form, onDelete }: FormCardProps) { export function FormCard({ form, onDelete }: FormCardProps) {
const handleCardClick = () => {
window.open(form.location, '_blank');
};
return ( return (
<Card className="overflow-hidden"> <Card className="overflow-hidden cursor-pointer" onClick={handleCardClick}>
<CardContent className="p-0"> <CardContent className="p-0 h-40 relative">
<img <Image
src={form.previewLocation} src={form.previewLocation}
alt={form.title} alt={form.title}
className="w-full h-40 object-cover" fill
className="object-cover object-top"
onError={(e) => {
e.currentTarget.src = '/placeholder-image.png';
console.error('Error loading image:', form.previewLocation);
}}
/> />
</CardContent> </CardContent>
<CardFooter className="flex flex-col items-start p-4"> <CardFooter className="flex flex-col items-start p-4">
<h3 className="font-semibold mb-2">{form.title}</h3> <div className="flex items-center justify-between w-full">
<h3 className="font-semibold mb-2">{form.title}</h3>
<Trash2
className="h-4 w-4 text-destructive cursor-pointer"
onClick={(e) => {
e.stopPropagation();
onDelete(form.id);
}}
/>
</div>
<div className="flex flex-wrap gap-2 mb-2"> <div className="flex flex-wrap gap-2 mb-2">
<Badge variant="secondary">{form.studyTitle}</Badge> <Badge variant="secondary">{form.studyTitle}</Badge>
<Badge variant="outline">{form.participantName}</Badge> <Badge variant="outline">{form.participantName}</Badge>
</div> </div>
<Button
variant="ghost"
size="sm"
className="text-destructive"
onClick={() => onDelete(form.id)}
>
<Trash2 className="h-4 w-4 mr-2" />
Delete
</Button>
</CardFooter> </CardFooter>
</Card> </Card>
); );

View File

@@ -28,7 +28,13 @@ export async function saveFile(file: File, filePath: string, previewContentTypeI
}; };
const convert = fromBuffer(buffer, options); const convert = fromBuffer(buffer, options);
await convert(1); const result = await convert(1);
// Rename the file to remove the ".1" suffix
const generatedFilePath = result.path;
if (generatedFilePath) {
await fs.rename(generatedFilePath, previewPath);
}
// Return relative paths that can be used in URLs // Return relative paths that can be used in URLs
return { return {

View File

@@ -14,5 +14,7 @@ export const config = {
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)', '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always run for API routes // Always run for API routes
'/(api|trpc)(.*)', '/(api|trpc)(.*)',
// Add this line to include the /content route
'/content/(.*)',
], ],
} }