mirror of
https://github.com/Sosokker/B2D-Ventures.git
synced 2025-12-19 05:54:06 +01:00
Refactor uploadFile function to remove userID parameter and update folder path
This commit is contained in:
parent
0cfb93efac
commit
87f8e13f37
@ -1,14 +1,18 @@
|
|||||||
import { createSupabaseClient } from "@/lib/supabase/clientComponentClient";
|
import { createSupabaseClient } from "@/lib/supabase/clientComponentClient";
|
||||||
import Swal from "sweetalert2";
|
import Swal from "sweetalert2";
|
||||||
|
|
||||||
export async function uploadFile(file: File, userID: string, bucketName: string, filePath: string) {
|
export async function uploadFile(
|
||||||
|
file: File,
|
||||||
|
bucketName: string,
|
||||||
|
filePath: string
|
||||||
|
) {
|
||||||
const supabase = createSupabaseClient();
|
const supabase = createSupabaseClient();
|
||||||
let errorMessages: string[] = [];
|
let errorMessages: string[] = [];
|
||||||
|
|
||||||
// check if the folder exists
|
// check if the folder exists
|
||||||
const { data: folderData, error: folderError } = await supabase.storage
|
const { data: folderData, error: folderError } = await supabase.storage
|
||||||
.from(bucketName)
|
.from(bucketName)
|
||||||
.list(`${userID}/`);
|
.list(filePath);
|
||||||
|
|
||||||
if (folderError) {
|
if (folderError) {
|
||||||
errorMessages.push(`Error checking for folder: ${folderError.message}`);
|
errorMessages.push(`Error checking for folder: ${folderError.message}`);
|
||||||
@ -16,12 +20,10 @@ export async function uploadFile(file: File, userID: string, bucketName: string,
|
|||||||
|
|
||||||
// if the folder exists, clear the folder
|
// if the folder exists, clear the folder
|
||||||
if (folderData && folderData.length > 0) {
|
if (folderData && folderData.length > 0) {
|
||||||
// console.log("Folder exists. Clearing contents...");
|
|
||||||
|
|
||||||
for (const fileItem of folderData) {
|
for (const fileItem of folderData) {
|
||||||
const { error: removeError } = await supabase.storage
|
const { error: removeError } = await supabase.storage
|
||||||
.from(bucketName)
|
.from(bucketName)
|
||||||
.remove([`${userID}/${fileItem.name}`]);
|
.remove([`${filePath}/${fileItem.name}`]);
|
||||||
|
|
||||||
if (removeError) {
|
if (removeError) {
|
||||||
errorMessages.push(
|
errorMessages.push(
|
||||||
|
|||||||
@ -33,7 +33,6 @@ export default function ApplyBusiness() {
|
|||||||
if (user?.id) {
|
if (user?.id) {
|
||||||
const uploadSuccess = await uploadFile(
|
const uploadSuccess = await uploadFile(
|
||||||
recvData["businessPitchDeck"],
|
recvData["businessPitchDeck"],
|
||||||
user.id,
|
|
||||||
BUCKET_PITCH_NAME,
|
BUCKET_PITCH_NAME,
|
||||||
// file structure: userId/fileName
|
// file structure: userId/fileName
|
||||||
`${user?.id}/${recvData["businessPitchDeck"].name}`
|
`${user?.id}/${recvData["businessPitchDeck"].name}`
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { useState } from "react";
|
|
||||||
import { createSupabaseClient } from "@/lib/supabase/clientComponentClient";
|
import { createSupabaseClient } from "@/lib/supabase/clientComponentClient";
|
||||||
import ProjectForm from "@/components/ProjectForm";
|
import ProjectForm from "@/components/ProjectForm";
|
||||||
import { projectFormSchema } from "@/types/schemas/application.schema";
|
import { projectFormSchema } from "@/types/schemas/application.schema";
|
||||||
@ -10,27 +9,22 @@ import { uploadFile } from "@/app/api/generalApi";
|
|||||||
|
|
||||||
type projectSchema = z.infer<typeof projectFormSchema>;
|
type projectSchema = z.infer<typeof projectFormSchema>;
|
||||||
let supabase = createSupabaseClient();
|
let supabase = createSupabaseClient();
|
||||||
const BUCKET_PITCH_APPLICATION_NAME = "project-pitches";
|
const BUCKET_PITCH_APPLICATION_NAME = "project-application";
|
||||||
|
|
||||||
export default function ApplyProject() {
|
export default function ApplyProject() {
|
||||||
const onSubmit: SubmitHandler<projectSchema> = async (data) => {
|
const onSubmit: SubmitHandler<projectSchema> = async (data) => {
|
||||||
alert("มาแน้ววว");
|
alert("มาแน้ววว");
|
||||||
await sendApplication(data);
|
await sendApplication(data);
|
||||||
// console.table(data);
|
console.table(data);
|
||||||
// console.log(typeof data["projectPhotos"], data["projectPhotos"]);
|
// console.log(typeof data["projectPhotos"], data["projectPhotos"]);
|
||||||
};
|
};
|
||||||
const sendApplication = async (recvData: any) => {
|
const saveApplicationData = async (recvData: any, userId: string) => {
|
||||||
const {
|
|
||||||
data: { user },
|
|
||||||
} = await supabase.auth.getUser();
|
|
||||||
let projectId = null;
|
|
||||||
const pitchType = typeof recvData["projectPitchDeck"];
|
const pitchType = typeof recvData["projectPitchDeck"];
|
||||||
// save the general application data to project_application table
|
const { data: projectData, error: projectError } = await supabase
|
||||||
const { data: project_application, error } = await supabase
|
|
||||||
.from("project_application")
|
.from("project_application")
|
||||||
.insert([
|
.insert([
|
||||||
{
|
{
|
||||||
user_id: user?.id,
|
user_id: userId,
|
||||||
pitch_deck_url:
|
pitch_deck_url:
|
||||||
pitchType === "string" ? recvData["projectPitchDeck"] : "",
|
pitchType === "string" ? recvData["projectPitchDeck"] : "",
|
||||||
target_investment: recvData["targetInvest"],
|
target_investment: recvData["targetInvest"],
|
||||||
@ -42,42 +36,135 @@ export default function ApplyProject() {
|
|||||||
},
|
},
|
||||||
])
|
])
|
||||||
.select();
|
.select();
|
||||||
if (project_application) {
|
|
||||||
projectId = project_application[0].id;
|
return { projectId: projectData?.[0]?.id, error: projectError };
|
||||||
|
};
|
||||||
|
const saveTags = async (tags: string[], projectId: string) => {
|
||||||
|
const tagPromises = tags.map(async (tag) => {
|
||||||
|
const { data, error } = await supabase
|
||||||
|
.from("project_application_tag")
|
||||||
|
.insert([{ tag_id: tag, project_id: projectId }])
|
||||||
|
.select();
|
||||||
|
|
||||||
|
return { data, error };
|
||||||
|
});
|
||||||
|
|
||||||
|
const results = await Promise.all(tagPromises);
|
||||||
|
const errors = results
|
||||||
|
.filter((result) => result.error)
|
||||||
|
.map((result) => result.error);
|
||||||
|
|
||||||
|
return { errors };
|
||||||
|
};
|
||||||
|
|
||||||
|
const uploadPitchFile = async (
|
||||||
|
file: File,
|
||||||
|
userId: string,
|
||||||
|
projectId: string
|
||||||
|
) => {
|
||||||
|
if (!file || !userId) {
|
||||||
|
console.error("Pitch file or user ID is undefined.");
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
// upload pitch file
|
|
||||||
if (pitchType === "object") {
|
return await uploadFile(
|
||||||
if (user?.id) {
|
file,
|
||||||
const uploadSuccess = await uploadFile(
|
"BUCKET_PITCH_APPLICATION_NAME",
|
||||||
recvData["businessPitchDeck"],
|
`${userId}/${projectId}/pitches/${file.name}`
|
||||||
user.id,
|
);
|
||||||
BUCKET_PITCH_APPLICATION_NAME,
|
};
|
||||||
`${user?.id}/${projectId}/pitches/${recvData["projectPitchDeck"].name}`
|
|
||||||
|
const uploadLogoAndPhotos = async (
|
||||||
|
logoFile: File,
|
||||||
|
photos: File[],
|
||||||
|
userId: string,
|
||||||
|
projectId: string
|
||||||
|
) => {
|
||||||
|
if (logoFile) {
|
||||||
|
const uploadLogoSuccess = await uploadFile(
|
||||||
|
logoFile,
|
||||||
|
"BUCKET_PITCH_APPLICATION_NAME",
|
||||||
|
`${userId}/${projectId}/logo/${logoFile.name}`
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!uploadSuccess) {
|
if (!uploadLogoSuccess) {
|
||||||
return;
|
console.error("Error uploading logo.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("file upload successful");
|
const uploadPhotoPromises = photos.map((image) =>
|
||||||
} else {
|
uploadFile(
|
||||||
console.error("user ID is undefined.");
|
image,
|
||||||
return;
|
"BUCKET_PITCH_APPLICATION_NAME",
|
||||||
}
|
`${userId}/${projectId}/photos/${image.name}`
|
||||||
}
|
)
|
||||||
// console.table(data);
|
);
|
||||||
|
|
||||||
|
const photoResults = await Promise.all(uploadPhotoPromises);
|
||||||
|
return photoResults.every(Boolean); // Checks if all photos uploaded successfully
|
||||||
|
};
|
||||||
|
|
||||||
|
const displayAlert = (error: any) => {
|
||||||
Swal.fire({
|
Swal.fire({
|
||||||
icon: error == null ? "success" : "error",
|
icon: error == null ? "success" : "error",
|
||||||
title: error == null ? "success" : "Error: " + error.code,
|
title: error == null ? "Success" : `Error: ${error.code}`,
|
||||||
text:
|
text:
|
||||||
error == null ? "Your application has been submitted" : error.message,
|
error == null ? "Your application has been submitted" : error.message,
|
||||||
confirmButtonColor: error == null ? "green" : "red",
|
confirmButtonColor: error == null ? "green" : "red",
|
||||||
}).then((result) => {
|
}).then((result) => {
|
||||||
if (result.isConfirmed) {
|
if (result.isConfirmed) {
|
||||||
// window.location.href = "/";
|
window.location.href = "/";
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const sendApplication = async (recvData: any) => {
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (!user?.id) {
|
||||||
|
console.error("User ID is undefined.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// save application data
|
||||||
|
const { projectId, error } = await saveApplicationData(recvData, user.id);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
displayAlert(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// upload pitch file if it’s a file
|
||||||
|
if (typeof recvData["projectPitchDeck"] === "object") {
|
||||||
|
const uploadPitchSuccess = await uploadPitchFile(
|
||||||
|
recvData["projectPitchDeck"],
|
||||||
|
user.id,
|
||||||
|
projectId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!uploadPitchSuccess) {
|
||||||
|
console.error("Error uploading pitch file.");
|
||||||
|
} else {
|
||||||
|
console.log("Pitch file uploaded successfully.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// upload logo and photos
|
||||||
|
const uploadMediaSuccess = await uploadLogoAndPhotos(
|
||||||
|
recvData["projectLogo"],
|
||||||
|
recvData["projectPhotos"],
|
||||||
|
user.id,
|
||||||
|
projectId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!uploadMediaSuccess) {
|
||||||
|
console.error("Error uploading media files.");
|
||||||
|
}
|
||||||
|
displayAlert(error);
|
||||||
|
};
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="grid grid-flow-row auto-rows-max w-full h-52 md:h-92 bg-gray-2s00 dark:bg-gray-800 p-5">
|
<div className="grid grid-flow-row auto-rows-max w-full h-52 md:h-92 bg-gray-2s00 dark:bg-gray-800 p-5">
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user