Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
ivbq committed Sep 27, 2024
2 parents 9f6c780 + cf5ceb0 commit 89d6777
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 51 deletions.
2 changes: 1 addition & 1 deletion src/components/Company/UploadButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function UploadButton({
);
}
} else {
alert(t.exhibitorSettings.table.row1.imageTypeNotSupported);
alert(`${t.exhibitorSettings.table.row1.imageTypeNotSupported} file is ${e.target.files[0].type} but should be ${accept.join(", ")}`);
}

e.target.files = null;
Expand Down
15 changes: 11 additions & 4 deletions src/components/Student/Info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { CheckMark } from "../CheckMark";
import { InputField } from "../InputField";
import { api } from "@/utils/api";
import { useModal } from "@/utils/context";
import { set } from "zod";

interface User{
ugkthid: string;
Expand Down Expand Up @@ -60,6 +61,7 @@ export default function StudentInfo(

const inputData = api.student.inputData.useMutation();
const [saved, setSaved] = useState(false);
const [error, setError] = useState(false);

const section = t.exhibitorSettings.table.row1.section2;

Expand All @@ -84,15 +86,17 @@ export default function StudentInfo(
}

function saveHandlerFunc(data: User){

inputData.mutateAsync(JSON.stringify(data))
.then((res) =>{
setSaved(true);

setTimeout(()=>{setSaved(false)}, 2000);
})
.catch((err) => {
.catch((err: any) => {

setUser({...user, cv: ""} as User);
alert("Error saving user: pdf can not be saved");
setSaved(false);

});

}
Expand Down Expand Up @@ -173,7 +177,7 @@ export default function StudentInfo(
md:text-sm text-[9px] ">
{t.students.info.cv}:
</label>
<UploadCV t={t} file={user.cv} setFile={(value)=>{setUser({...user, cv:value})}}/>
<UploadCV t={t} file={user.cv ?? ""} setFile={(value)=>{setUser({...user, cv:value})}}/>
</div>
<div className="justify-center flex flex-col mt-[40px] w-full max-w-[300px] mx-auto">
{user.cv && user.cv !== 'undefined' ?
Expand All @@ -186,6 +190,9 @@ export default function StudentInfo(
<p className="text-white self-center">
{saved? (!user.first_name ? t.students.info.addFirstName : !user.last_name ? t. students.info.addLastName : !user.study_year ? t.students.info.addYear : "Saved") : ""}
</p>
<p className="text-red-600 font-bold self-center">
{error? ("Error saving user: pdf can not be saved, reloading...") : ""}
</p>
</div>:
<p className="font-bold text-xl text-yellow text-center">
{t.students.info.subHeader}
Expand Down
41 changes: 31 additions & 10 deletions src/components/Student/UploadCV.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Locale from "@/locales";
import React, { Dispatch } from 'react';
import { Buffer } from 'buffer';
import base64ToFile from "@/shared/HandlePDF";
import { set } from "zod";

export default function UploadCV(
{
Expand All @@ -19,6 +20,13 @@ export default function UploadCV(
if (files && files.length > 0) {
const newFile = files[0];

const ALLOWED_FILE_TYPE = "application/pdf";
if (newFile.type !== ALLOWED_FILE_TYPE) {
alert(t.exhibitorSettings.table.row1.fileTypeNotSupported);
setFile("");
return false;
}

// Check file size
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 MB
const FILE_SIZE = newFile.size;
Expand All @@ -27,22 +35,35 @@ export default function UploadCV(
(FILE_SIZE / 1e6).toFixed(2),
(MAX_FILE_SIZE / 1e6).toFixed(0)
));
return;
setFile("");
return false;
}



const fileReader = new FileReader();
fileReader.readAsDataURL(newFile);

// Handle successful file load
fileReader.onload = () => {
const base64String = fileReader.result as string;
const base64WithFilename = `data:${newFile.type};name=${newFile.name};base64,${base64String.split(',')[1]}`;
setFile(base64WithFilename);
try {
const base64String = fileReader.result as string;
const base64WithFilename = `data:${newFile.type};name=${newFile.name};base64,${base64String.split(',')[1]}`;
setFile(base64WithFilename);
} catch (error) {
console.error("Error processing PDF:", error);
alert(t.exhibitorSettings.table.row1.fileDataMalformed);
}
};
}
}



// Handle file load errors
fileReader.onerror = () => {
alert(t.exhibitorSettings.table.row1.fileDataMalformed);
console.error("Error reading file:", fileReader.error);
};

fileReader.readAsDataURL(newFile);
}
}

return (
<div className="flex text-white items-center relative bg-black/25 min-w-[200px] h-[60px] p-4 rounded-3xl border-solid border-yellow border-2 overflow-hidden">
Expand All @@ -61,7 +82,7 @@ export default function UploadCV(

<h2 className="absolute bottom-0 left-0 right-0 text-center text-[12px] text-slate-400">
{"" == "" ? (
"pdf"
"Type: pdf"
) : ""}
</h2>
<div>
Expand Down
3 changes: 3 additions & 0 deletions src/locales/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@ export default {
"Error uploading file: The image format type is not supported.",
maxImageWarning: (imageSize: string, maxImageSize: string) =>
`Error uploading file: File is too big (${imageSize}MB). Max filesize: ${maxImageSize}MB.`,
fileTypeNotSupported:
"Error uploading file: Only the pdf format is supported.",
fileDataMalformed: "Error uploading file to our system: The file is malformed.",
},
row2: {
title: "Your Package And Extra Orders",
Expand Down
3 changes: 3 additions & 0 deletions src/locales/sv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,9 @@ export default {
"Det gick inte att ladda upp filen: Bildformatet stöds inte.",
maxImageWarning: (imageSize: string, maxImageSize: string) =>
`Det gick inte att ladda upp filen: Filen är för stor (${imageSize}MB). Max filstorlek: ${maxImageSize}MB.`,
fileTypeNotSupported:
"Det gick inte att ladda upp filen: bara PDF-formatet stöds.",
fileDataMalformed: "Det gick inte att ladda upp filen till vårat system: filen är skadad.",
},
row2: {
title: "Ert Paket Och Extra Beställningar",
Expand Down
16 changes: 7 additions & 9 deletions src/pages/logos.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ function RenderLogos(packageList: any[], rowSize: number, logoSize: string) {
{chunk.map((exhibitor, idx) => (
<div key={idx}>
<Logo
pic={exhibitor.logoColor}
pic={exhibitor.logo}
companyName={exhibitor.name}
description={exhibitor.description}
size={logoSize}
Expand All @@ -157,8 +157,7 @@ type LogosProps = {
exhibitorData: {
id?: string;
name: string;
logoWhite?: string | null;
logoColor?: string | null;
logo?: string | null;
description?: string;
packageTier: number;
jobOfferId?: string;
Expand All @@ -170,17 +169,17 @@ export default function Logos({ exhibitorData }: LogosProps) {
const t = useLocale();

const mainsponsorPackages = exhibitorData.filter(
(e) => e.packageTier === 3 && e.logoColor
(e) => e.packageTier === 3 && e.logo
);
const largeAndMediumPackages = exhibitorData.filter(
(e) =>
(e.packageTier === 2 || e.packageTier === 1) && e.logoColor
(e.packageTier === 2 || e.packageTier === 1) && e.logo
);
const smallPackages = exhibitorData.filter(
(e) => e.packageTier === 0 && e.logoColor
(e) => e.packageTier === 0 && e.logo
);
const startupPackages = exhibitorData.filter(
(e) => e.packageTier === 4 && e.logoColor
(e) => e.packageTier === 4 && e.logo
);
const smallAndStartUpPackages = [...smallPackages, ...startupPackages];

Expand Down Expand Up @@ -222,8 +221,7 @@ export async function getServerSideProps() {

const exhibitorData = exhibitors.map((exhibitor:any) => ({
name: exhibitor.name || null,
logoWhite: exhibitor.logoWhite?.toString("base64") || null,
logoColor: exhibitor.logoColor?.toString("base64") || null,
logo: exhibitor.logoColor?.toString("base64") || exhibitor.logoWhite?.toString("base64") || null,
description: exhibitor.description || null,
jobOfferId: exhibitor.jobOfferId || null,
packageTier: exhibitor.packageTier,
Expand Down
16 changes: 8 additions & 8 deletions src/pages/student.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ interface InterestedCompany{
}

const set_session_storage = (loginToken: string) => {
sessionStorage.setItem("login_token", loginToken);
sessionStorage.setItem("d_login_token", loginToken);
};

export default function LoggedInPage() {
Expand Down Expand Up @@ -66,22 +66,22 @@ export default function LoggedInPage() {

useEffect(()=>{
const params: URLSearchParams = new URL(window.location.href).searchParams;
let loginToken: string = params.get('login_token') || "";
let loginToken: string = params.get('d_login_token') ?? "";

// log in the user if not logged in
if (!isLoggedIn && !sessionStorage.getItem("login_token") && (!loginToken || loginToken === "null")){
window.location.href = `https://login.datasektionen.se/login?callback=${window.location.href.replace(/^(https?:\/\/[^\/]+).*/, '$1')}/student?login_token=`
if (!isLoggedIn && !sessionStorage.getItem("d_login_token") && (!loginToken || loginToken === "null" || loginToken === "")) {
window.location.href = `https://login.datasektionen.se/login?callback=${window.location.href.replace(/^(https?:\/\/[^\/]+).*/, '$1')}/student?d_login_token=`
}
}, [isLoggedIn])

useEffect(() => {
//router.push("/förstudenter"); // remove when page should be available
const params: URLSearchParams = new URL(window.location.href).searchParams;
let loginToken: string = params.get('login_token') || "";
let loginToken: string = params.get('d_login_token') ?? "";

// If no login_token in url, check if login token in cookies
if ((!loginToken || loginToken === "null") && sessionStorage.getItem("login_token")) {
const token = sessionStorage.getItem("login_token");
// If no login_token in url, check if login token in session storage
if ((!loginToken || loginToken === "null") && sessionStorage.getItem("d_login_token")) {
const token = sessionStorage.getItem("d_login_token");
if (token !== null) {
loginToken = token;
}
Expand Down
49 changes: 30 additions & 19 deletions src/server/api/routers/student.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { getLocale } from "@/locales";
import { send } from "process";

// This is not a gud solution, but for now here we gooo! :-)
const times = ["10:00-10:30", "10:30-11:00", "11:00-11:30", "11:30-12:00", "12:00-12:30", "12:30-13:00",
"13:00-13:30", "13:30-14:00", "14:00-14:30", "14:30-15:00", "15:00-15:30", "15:30-16:00"]
const times = [ "10:00-10:30", "10:30-11:00", "11:00-11:30", "11:30-12:00", "12:00-12:30", "12:30-13:00",
"13:00-13:30", "13:30-14:00", "14:00-14:30", "14:30-15:00", "15:00-15:30", "15:30-16:00"]

const companyLocationMap = {
"5020109681":{
Expand Down Expand Up @@ -88,7 +88,7 @@ export const studentRouter = createTRPCRouter({
});

if (!student) {
//console.log("Should create a new student")
console.log("Should create a new student")
const student_body = {
ugkthid: String(input_json.ugkthid),
first_name: String(input_json.first_name) ?? "",
Expand All @@ -104,25 +104,31 @@ export const studentRouter = createTRPCRouter({
traineeProgram: !!input_json.traineeProgram,
cv: String(input_json.cv) ?? "",
has_cv: input_json.cv != null ? true : false,
linkedin_url: String(input_json.linkedin_url) ?? "",
github_url: String(input_json.github_url) ?? "",
other_link: String(input_json.other_link) ?? "",
personal_story: String(input_json.personal_story) ?? "",
linkedin_url: "",//String(input_json.linkedin_url) ?? "",
github_url: "",//String(input_json.github_url) ?? "",
other_link: "",//String(input_json.other_link) ?? "",
personal_story: "",//String(input_json.personal_story) ?? "",
company_meeting_interests: JSON.stringify([]),
} as Prisma.StudentsCreateInput;
// If no user exists, create a new user with default values

await ctx.prisma.students.create({
data: student_body,
});
try {
const res = await ctx.prisma.students.create({
data: student_body,
});

if(res) console.log("Student created")

} catch (error) {
console.error("Error creating student", error);
}
}
else{
// If user exists, update the existing user data with new values
if(student.cv != null) console.log("Student has CV")

console.log(input_json.cv)
//console.log("data:",input_json.ugkthid)

student = await ctx.prisma.students.update({
const regular_data = await ctx.prisma.students.update({
where: {
ugkthid: input_json.ugkthid
},
Expand All @@ -138,16 +144,21 @@ export const studentRouter = createTRPCRouter({
masterThesis: input_json.masterThesis ?? student.masterThesis,
fullTimeJob: input_json.fullTimeJob ?? student.fullTimeJob,
traineeProgram: input_json.traineeProgram ?? student.traineeProgram,
//company_meeting_interests: student.company_meeting_interests,
},
});

// we sepearate the cv from the rest of the data because it is gimmicky
const cv_data = await ctx.prisma.students.update({
where: {
ugkthid: input_json.ugkthid
},
data: {
cv: input_json.cv ?? student.cv,
has_cv: input_json.cv != null ? true : false,
linkedin_url: input_json.linkedin_url ?? student.linkedin_url,
github_url: input_json.github_url ?? student.github_url,
other_link: input_json.other_link ?? student.other_link,
personal_story: input_json.personal_story ?? student.personal_story,
//company_meeting_interests: student.company_meeting_interests,
},
});

//return {regular_data, cv_data}
}

return student; // Return the updated or newly created student
Expand Down

0 comments on commit 89d6777

Please sign in to comment.