From f1f35e40f729973c1acf4a32aee5a587bbd52431 Mon Sep 17 00:00:00 2001 From: IceTeaXXD <13521024@std.stei.itb.ac.id> Date: Thu, 16 Nov 2023 19:44:56 +0700 Subject: [PATCH] chore: reformat code --- controllers/auth.controller.ts | 6 +- controllers/files.controller.ts | 284 ++++++------- controllers/organization.controller.ts | 556 ++++++++++++------------- controllers/scholarship.controller.ts | 15 +- controllers/soap.controller.ts | 157 ++++--- controllers/student.controller.ts | 121 +++--- controllers/university.controller.ts | 8 +- polling/scholarships.ts | 2 +- polling/sync.ts | 8 +- polling/university.ts | 86 ++-- redis.ts | 16 +- routes/assignmentPublic.routes.ts | 10 +- routes/default.routes.ts | 4 +- routes/files.routes.ts | 10 +- routes/filesPublic.routes.ts | 33 +- routes/organization.routes.ts | 10 +- routes/organizationPublic.routes.ts | 7 +- routes/scholarship.routes.ts | 16 +- routes/student.routes.ts | 6 +- routes/university.routes.ts | 10 +- routes/universityPublic.routes.ts | 4 +- templates/getAllScholarship.ts | 15 +- templates/organization.ts | 16 +- templates/scholarship.ts | 24 +- templates/scholarshipAcceptance.ts | 26 +- templates/student.ts | 15 +- templates/university.ts | 16 +- 27 files changed, 733 insertions(+), 748 deletions(-) diff --git a/controllers/auth.controller.ts b/controllers/auth.controller.ts index 7da89f2..bda96de 100644 --- a/controllers/auth.controller.ts +++ b/controllers/auth.controller.ts @@ -201,12 +201,9 @@ export const handleRefreshToken = async (req: Request, res: Response) => { const redisData = await client.get(refreshToken) if (redisData) { // Data found in Redis - console.log("Data found in Redis") const decoded = JSON.parse(redisData) const { user_id, email, name, roles } = decoded - const accessTokenSecret: string = String( - process.env.ACCESS_TOKEN_SECRET - ) + const accessTokenSecret: string = String(process.env.ACCESS_TOKEN_SECRET) const accToken = generateAccessToken( user_id, name, @@ -220,7 +217,6 @@ export const handleRefreshToken = async (req: Request, res: Response) => { res.json({ user_id, email, name, roles, accToken }) } else { // Data not found in Redis - console.log("Data not found in Redis") try { const findUser = await prismaClient.user.findFirst({ where: { diff --git a/controllers/files.controller.ts b/controllers/files.controller.ts index 6e05977..aa60d38 100644 --- a/controllers/files.controller.ts +++ b/controllers/files.controller.ts @@ -1,166 +1,166 @@ import { Request, Response } from "express" import { PrismaClient } from "@prisma/client" import stream from "stream" -import {google} from 'googleapis' +import { google } from "googleapis" import path from "path" import { file } from "googleapis/build/src/apis/file" const prisma = new PrismaClient() /* URL: /scholarship/:sid/assignment/:aid/file/:fid/user/:uid */ export const getFileById = async (req: Request, res: Response) => { - try { - const { sid, aid, fid, uid } = req.params - const files = await prisma.files.findUnique({ - where: { - scholarship_id: Number(sid), - assignment_id: Number(aid), - file_id: Number(fid), - user_id_student: Number(uid) - }, - select: { - file_path: true, - file_id: true, - user_id_student: true - } - }) - - if (!files) { - throw new Error("Files Not Found!") - } - - res.status(200).json({ - status: "success", - message: "File retrieved successfully", - data: { - file_id: files.file_id, - file_path: files.file_path - } - }) - } catch (error: any) { - res.status(400).json({ - status: "error", - message: error.message - }) + try { + const { sid, aid, fid, uid } = req.params + const files = await prisma.files.findUnique({ + where: { + scholarship_id: Number(sid), + assignment_id: Number(aid), + file_id: Number(fid), + user_id_student: Number(uid) + }, + select: { + file_path: true, + file_id: true, + user_id_student: true + } + }) + + if (!files) { + throw new Error("Files Not Found!") } + + res.status(200).json({ + status: "success", + message: "File retrieved successfully", + data: { + file_id: files.file_id, + file_path: files.file_path + } + }) + } catch (error: any) { + res.status(400).json({ + status: "error", + message: error.message + }) + } } /* URL: /scholarship/:sid/assignment/:aid/file */ export const getAllFiles = async (req: Request, res: Response) => { - try { - const { sid, aid } = req.params - const files = await prisma.files.findMany({ - where: { - scholarship_id: Number(sid), - assignment_id: Number(aid) - }, - select: { - file_path: true, - file_id: true, - user_id_student: true - } - }) - - if (!files) { - throw new Error("Files Not Found!") - } - - res.status(200).json({ - status: "success", - message: "File retrieved successfully", - data: { - files - } - }) - } catch (error: any) { - res.status(400).json({ - status: "error", - message: error.message - }) + try { + const { sid, aid } = req.params + const files = await prisma.files.findMany({ + where: { + scholarship_id: Number(sid), + assignment_id: Number(aid) + }, + select: { + file_path: true, + file_id: true, + user_id_student: true + } + }) + + if (!files) { + throw new Error("Files Not Found!") } + + res.status(200).json({ + status: "success", + message: "File retrieved successfully", + data: { + files + } + }) + } catch (error: any) { + res.status(400).json({ + status: "error", + message: error.message + }) + } } /* URL: /scholarship/:sid/assignment/:aid/ */ export const uploadFiles = async (req: Request, res: Response) => { - try { - const { sid, aid } = req.params; - const { uid } = req.body; - const { files } : any = req; - - const scholarship = await prisma.scholarship.findUnique({ - where: { scholarship_id: parseInt(sid) } - }); - - const assignment = await prisma.assignment.findUnique({ - where: { assignment_id: parseInt(aid) } - }); - - if (!scholarship || !assignment) { - return res.status(404).json({ - status: "error", - message: "Scholarship or assignment not found." - }); - } - - const savedFiles = await Promise.all( - files.map(async (file: any) => { - const fileUrl = await uploadFile(file); - return prisma.files.create({ - data: { - user_id_student: Number(uid), - file_path: fileUrl, - organization_id: scholarship.organization_id, - scholarship_id: scholarship.scholarship_id, - assignment_id: assignment.assignment_id - } as any - }); - }) - ); - - res.status(200).json({ - status: "success", - message: "Files uploaded successfully.", - files: savedFiles - }); - } catch (error: any) { - res.status(400).json({ - status: "error", - message: error.message - }); + try { + const { sid, aid } = req.params + const { uid } = req.body + const { files }: any = req + + const scholarship = await prisma.scholarship.findUnique({ + where: { scholarship_id: parseInt(sid) } + }) + + const assignment = await prisma.assignment.findUnique({ + where: { assignment_id: parseInt(aid) } + }) + + if (!scholarship || !assignment) { + return res.status(404).json({ + status: "error", + message: "Scholarship or assignment not found." + }) } -}; -const KEYFILEPATH = path.join(__dirname, '..', 'cred.json') + const savedFiles = await Promise.all( + files.map(async (file: any) => { + const fileUrl = await uploadFile(file) + return prisma.files.create({ + data: { + user_id_student: Number(uid), + file_path: fileUrl, + organization_id: scholarship.organization_id, + scholarship_id: scholarship.scholarship_id, + assignment_id: assignment.assignment_id + } as any + }) + }) + ) + + res.status(200).json({ + status: "success", + message: "Files uploaded successfully.", + files: savedFiles + }) + } catch (error: any) { + res.status(400).json({ + status: "error", + message: error.message + }) + } +} + +const KEYFILEPATH = path.join(__dirname, "..", "cred.json") const SCOPES = ["https://www.googleapis.com/auth/drive"] const auth = new google.auth.GoogleAuth({ - keyFile: KEYFILEPATH, - scopes: SCOPES, -}); - -export const uploadFile = async (fileObject : any) => { - const bufferStream = new stream.PassThrough(); - bufferStream.end(fileObject.buffer); - - try { - const drive = google.drive({ version: 'v3', auth }); - const { data } = await drive.files.create({ - media: { - mimeType: fileObject.mimeType, - body: bufferStream, - }, - requestBody: { - name: fileObject.originalname, - parents: ['16MsCQmIcu4LibyJYMyNeBRXDrRYCs29u'], - }, - fields: 'id,name,webViewLink', - }); - - const fileId = data.id; - const embeddedPreviewUrl = `https://drive.google.com/file/d/${fileId}/preview`; - - return embeddedPreviewUrl; - } catch (error : any) { - console.error('Error uploading file to Google Drive:', error.message); - throw error; - } -}; \ No newline at end of file + keyFile: KEYFILEPATH, + scopes: SCOPES +}) + +export const uploadFile = async (fileObject: any) => { + const bufferStream = new stream.PassThrough() + bufferStream.end(fileObject.buffer) + + try { + const drive = google.drive({ version: "v3", auth }) + const { data } = await drive.files.create({ + media: { + mimeType: fileObject.mimeType, + body: bufferStream + }, + requestBody: { + name: fileObject.originalname, + parents: ["16MsCQmIcu4LibyJYMyNeBRXDrRYCs29u"] + }, + fields: "id,name,webViewLink" + }) + + const fileId = data.id + const embeddedPreviewUrl = `https://drive.google.com/file/d/${fileId}/preview` + + return embeddedPreviewUrl + } catch (error: any) { + console.error("Error uploading file to Google Drive:", error.message) + throw error + } +} diff --git a/controllers/organization.controller.ts b/controllers/organization.controller.ts index 20f4a6b..1be8b4f 100644 --- a/controllers/organization.controller.ts +++ b/controllers/organization.controller.ts @@ -10,320 +10,314 @@ const xml2js = require("xml2js") const prisma = new PrismaClient() export const createOrganization = async (req: Request, res: Response) => { - try { - const { - name, - email, - password, - address, - organizationDescription, - referral_code - } = req.body + try { + const { + name, + email, + password, + address, + organizationDescription, + referral_code + } = req.body - // Verify the referral code - const request = await soapRequest({ - url: validateReferralCode.url, - headers: validateReferralCode.headers, - xml: util.format(validateReferralCode.body, referral_code) - }) + // Verify the referral code + const request = await soapRequest({ + url: validateReferralCode.url, + headers: validateReferralCode.headers, + xml: util.format(validateReferralCode.body, referral_code) + }) - const { body } = request.response - const parser = new xml2js.Parser() - const parsedBody = await parser.parseStringPromise(body) - const message = - parsedBody["S:Envelope"]["S:Body"][0][ - "ns2:validateReferralCodeResponse" - ][0]["return"] - - if (message === "false") { - throw new Error("Invalid referral code") - } - - // If email exists, throw error - const user = await prisma.user.findUnique({ - where: { - email - } - }) - - if (user) { - throw new Error("Email already exists") - } + const { body } = request.response + const parser = new xml2js.Parser() + const parsedBody = await parser.parseStringPromise(body) + const message = + parsedBody["S:Envelope"]["S:Body"][0][ + "ns2:validateReferralCodeResponse" + ][0]["return"] - // Hash the password - const saltRounds = 10 // You can adjust this number based on your security requirements - const hashedPassword = await hash(password, saltRounds) + if (message === "false") { + throw new Error("Invalid referral code") + } - const newOrganization = await prisma.user.create({ - data: { - name, - email, - password: hashedPassword, // Store the hashed password in the database - address, - role: Role.organization, - organization: { - create: { - description: organizationDescription - } - }, - verification: { - create: { - verification_token: crypro - .randomBytes(8) - .toString("hex") - } - } - } - }) + // If email exists, throw error + const user = await prisma.user.findUnique({ + where: { + email + } + }) - // Create a new organization in SOAP - const organizationId = newOrganization.user_id + if (user) { + throw new Error("Email already exists") + } - const requestOrgSoap = await soapRequest({ - url: createRESTId.url, - headers: createRESTId.headers, - xml: util.format(createRESTId.body, organizationId, referral_code) - }) + // Hash the password + const saltRounds = 10 // You can adjust this number based on your security requirements + const hashedPassword = await hash(password, saltRounds) - console.log(requestOrgSoap) + const newOrganization = await prisma.user.create({ + data: { + name, + email, + password: hashedPassword, // Store the hashed password in the database + address, + role: Role.organization, + organization: { + create: { + description: organizationDescription + } + }, + verification: { + create: { + verification_token: crypro.randomBytes(8).toString("hex") + } + } + } + }) - const { body: bodyOrgSoap } = requestOrgSoap.response - const parserOrgSoap = new xml2js.Parser() - const parsedBodyOrgSoap = await parserOrgSoap.parseStringPromise( - bodyOrgSoap - ) + // Create a new organization in SOAP + const organizationId = newOrganization.user_id - const messageOrgSoap = - parsedBodyOrgSoap["S:Envelope"]["S:Body"][0][ - "ns2:createRESTIdResponse" - ][0]["return"] + const requestOrgSoap = await soapRequest({ + url: createRESTId.url, + headers: createRESTId.headers, + xml: util.format(createRESTId.body, organizationId, referral_code) + }) - console.log(messageOrgSoap[0]) + const { body: bodyOrgSoap } = requestOrgSoap.response + const parserOrgSoap = new xml2js.Parser() + const parsedBodyOrgSoap = await parserOrgSoap.parseStringPromise( + bodyOrgSoap + ) - if (messageOrgSoap != "Register Success") { - throw new Error("SOAP request failed") - } + const messageOrgSoap = + parsedBodyOrgSoap["S:Envelope"]["S:Body"][0][ + "ns2:createRESTIdResponse" + ][0]["return"] - res.status(200).json({ - status: "success", - message: "Organization created successfully", - data: { - organization_id: newOrganization.user_id, - organization_name: newOrganization.name, - organization_email: newOrganization.email, - organization_address: newOrganization.address, - organization_description: organizationDescription - } - }) - } catch (error: any) { - res.status(400).json({ - status: "error", - message: error.message - }) + if (messageOrgSoap != "Register Success") { + throw new Error("SOAP request failed") } + + res.status(200).json({ + status: "success", + message: "Organization created successfully", + data: { + organization_id: newOrganization.user_id, + organization_name: newOrganization.name, + organization_email: newOrganization.email, + organization_address: newOrganization.address, + organization_description: organizationDescription + } + }) + } catch (error: any) { + res.status(400).json({ + status: "error", + message: error.message + }) + } } export const getOrganizations = async (req: Request, res: Response) => { - try { - const organizations = await prisma.organization.findMany({ - select: { - organization_id: true, - user: { - select: { - name: true, - email: true, - address: true - } - }, - description: true - } - }) - - if (!organizations) { - throw new Error("Organizations not found") - } + try { + const organizations = await prisma.organization.findMany({ + select: { + organization_id: true, + user: { + select: { + name: true, + email: true, + address: true + } + }, + description: true + } + }) - res.status(200).json({ - status: "success", - message: "Organizations retrieved successfully", - data: organizations.map((organization) => { - return { - organization_id: organization.organization_id, - organization_name: organization.user?.name ?? null, - organization_email: organization.user?.email ?? null, - organization_address: organization.user?.address ?? null, - organization_description: organization.description - } - }) - }) - } catch (error: any) { - res.status(400).json({ - status: "error", - message: error.message - }) + if (!organizations) { + throw new Error("Organizations not found") } + + res.status(200).json({ + status: "success", + message: "Organizations retrieved successfully", + data: organizations.map((organization) => { + return { + organization_id: organization.organization_id, + organization_name: organization.user?.name ?? null, + organization_email: organization.user?.email ?? null, + organization_address: organization.user?.address ?? null, + organization_description: organization.description + } + }) + }) + } catch (error: any) { + res.status(400).json({ + status: "error", + message: error.message + }) + } } export const getOrganization = async (req: Request, res: Response) => { - try { - const { id } = req.params - const organization = await prisma.organization.findUnique({ - where: { - organization_id: Number(id) - }, - select: { - organization_id: true, - user: { - select: { - name: true, - email: true, - address: true - } - }, - description: true - } - }) - - if (!organization) { - throw new Error("Organization not found") - } + try { + const { id } = req.params + const organization = await prisma.organization.findUnique({ + where: { + organization_id: Number(id) + }, + select: { + organization_id: true, + user: { + select: { + name: true, + email: true, + address: true + } + }, + description: true + } + }) - res.status(200).json({ - status: "success", - message: "Organization retrieved successfully", - data: { - organization_id: organization.organization_id, - organization_name: organization.user?.name ?? null, - organization_email: organization.user?.email ?? null, - organization_address: organization.user?.address ?? null, - organization_description: organization.description - } - }) - } catch (error: any) { - res.status(400).json({ - status: "error", - message: error.message - }) + if (!organization) { + throw new Error("Organization not found") } + + res.status(200).json({ + status: "success", + message: "Organization retrieved successfully", + data: { + organization_id: organization.organization_id, + organization_name: organization.user?.name ?? null, + organization_email: organization.user?.email ?? null, + organization_address: organization.user?.address ?? null, + organization_description: organization.description + } + }) + } catch (error: any) { + res.status(400).json({ + status: "error", + message: error.message + }) + } } export const updateOrganization = async (req: Request, res: Response) => { - try { - const { name, email, address, description } = req.body - const { id } = req.params - const organization = await prisma.organization.findUnique({ - where: { - organization_id: Number(id) - }, - select: { - organization_id: true, - user: { - select: { - name: true, - email: true, - address: true - } - }, - description: true - } - }) + try { + const { name, email, address, description } = req.body + const { id } = req.params + const organization = await prisma.organization.findUnique({ + where: { + organization_id: Number(id) + }, + select: { + organization_id: true, + user: { + select: { + name: true, + email: true, + address: true + } + }, + description: true + } + }) - if (!organization) { - throw new Error("Organization not found") - } + if (!organization) { + throw new Error("Organization not found") + } - const updatedOrganization = await prisma.organization.update({ - where: { - organization_id: Number(id) - }, - data: { - user: { - update: { - name, - email, - address - } - }, - description - }, - select: { - organization_id: true, - user: { - select: { - name: true, - email: true, - address: true - } - }, - description: true - } - }) + const updatedOrganization = await prisma.organization.update({ + where: { + organization_id: Number(id) + }, + data: { + user: { + update: { + name, + email, + address + } + }, + description + }, + select: { + organization_id: true, + user: { + select: { + name: true, + email: true, + address: true + } + }, + description: true + } + }) - res.status(200).json({ - status: "success", - message: "Organization updated successfully", - data: { - organization_id: updatedOrganization.organization_id, - organization_name: updatedOrganization.user?.name ?? null, - organization_email: updatedOrganization.user?.email ?? null, - organization_address: updatedOrganization.user?.address ?? null, - organization_description: updatedOrganization.description - } - }) - } catch (error: any) { - res.status(400).json({ - status: "error", - message: error.message - }) - } + res.status(200).json({ + status: "success", + message: "Organization updated successfully", + data: { + organization_id: updatedOrganization.organization_id, + organization_name: updatedOrganization.user?.name ?? null, + organization_email: updatedOrganization.user?.email ?? null, + organization_address: updatedOrganization.user?.address ?? null, + organization_description: updatedOrganization.description + } + }) + } catch (error: any) { + res.status(400).json({ + status: "error", + message: error.message + }) + } } export const deleteOrganization = async (req: Request, res: Response) => { - try { - const { id } = req.params - const organization = await prisma.organization.findUnique({ - where: { - organization_id: Number(id) - }, - select: { - organization_id: true, - user: { - select: { - name: true, - email: true, - address: true - } - }, - description: true - } - }) + try { + const { id } = req.params + const organization = await prisma.organization.findUnique({ + where: { + organization_id: Number(id) + }, + select: { + organization_id: true, + user: { + select: { + name: true, + email: true, + address: true + } + }, + description: true + } + }) - if (!organization) { - throw new Error("Organization not found") - } + if (!organization) { + throw new Error("Organization not found") + } - // delete the user - await prisma.user.delete({ - where: { - user_id: Number(id) - } - }) + // delete the user + await prisma.user.delete({ + where: { + user_id: Number(id) + } + }) - res.status(200).json({ - status: "success", - message: "Organization deleted successfully", - data: { - organization_id: organization.organization_id, - organization_name: organization.user?.name ?? null, - organization_email: organization.user?.email ?? null, - organization_address: organization.user?.address ?? null, - organization_description: organization.description - } - }) - } catch (error: any) { - res.status(400).json({ - status: "error", - message: error.message - }) - } + res.status(200).json({ + status: "success", + message: "Organization deleted successfully", + data: { + organization_id: organization.organization_id, + organization_name: organization.user?.name ?? null, + organization_email: organization.user?.email ?? null, + organization_address: organization.user?.address ?? null, + organization_description: organization.description + } + }) + } catch (error: any) { + res.status(400).json({ + status: "error", + message: error.message + }) + } } diff --git a/controllers/scholarship.controller.ts b/controllers/scholarship.controller.ts index c6cd265..07492d3 100644 --- a/controllers/scholarship.controller.ts +++ b/controllers/scholarship.controller.ts @@ -152,9 +152,10 @@ export const getScholarships = async (req: Request, res: Response) => { numberOfPages, data: scholarships.map((scholarship) => { const countObject = scholarship_count.find( - (count: any) => count.scholarship_id_rest[0] == scholarship.scholarship_id - ); - + (count: any) => + count.scholarship_id_rest[0] == scholarship.scholarship_id + ) + return { organization_id: scholarship.organization_id, scholarship_id: scholarship.scholarship_id, @@ -377,13 +378,13 @@ export const scholarshipCount = async (id: Number) => { }) const { body } = response - + const parser = new xml2js.Parser() const parsedBody = await parser.parseStringPromise(body) const scholarships = - parsedBody["S:Envelope"]["S:Body"][0][ - "ns2:getScholarshipViewResponse" - ][0]["return"] + parsedBody["S:Envelope"]["S:Body"][0]["ns2:getScholarshipViewResponse"][0][ + "return" + ] return scholarships } diff --git a/controllers/soap.controller.ts b/controllers/soap.controller.ts index 8814d2b..b874384 100644 --- a/controllers/soap.controller.ts +++ b/controllers/soap.controller.ts @@ -1,5 +1,8 @@ import { Request, Response } from "express" -import { setAcceptance, getAllScholarshipAcceptance } from "../templates/scholarshipAcceptance" +import { + setAcceptance, + getAllScholarshipAcceptance +} from "../templates/scholarshipAcceptance" import { getAllScholarships } from "../templates/getAllScholarship" const soapRequest = require("easy-soap-request") @@ -11,92 +14,88 @@ const xml2js = require("xml2js") * either accepted or rejected */ export const scholarshipAcceptance = async (req: Request, res: Response) => { - try { - const { user_id_student, scholarship_id, status } = req.body + try { + const { user_id_student, scholarship_id, status } = req.body - const result = await soapRequest({ - url: setAcceptance.url, - headers: setAcceptance.headers, - xml: util.format( - setAcceptance.body, - user_id_student, - scholarship_id, - status - ) - }) + const result = await soapRequest({ + url: setAcceptance.url, + headers: setAcceptance.headers, + xml: util.format( + setAcceptance.body, + user_id_student, + scholarship_id, + status + ) + }) - const { body } = result.response + const { body } = result.response - const parser = new xml2js.Parser() - const parsedBody = await parser.parseStringPromise(body) - const message = - parsedBody["S:Envelope"]["S:Body"][0][ - "ns2:setAcceptanceResponse" - ][0]["return"] + const parser = new xml2js.Parser() + const parsedBody = await parser.parseStringPromise(body) + const message = + parsedBody["S:Envelope"]["S:Body"][0]["ns2:setAcceptanceResponse"][0][ + "return" + ] - res.status(200).json({ - status: "success", - message: message - }) - } catch (error: any) { - console.error("SOAP request error:", error) - throw error - } + res.status(200).json({ + status: "success", + message: message + }) + } catch (error: any) { + console.error("SOAP request error:", error) + throw error + } } -export const getAllScholarship = async(req : Request, res : Response) => { - try { - const result = await soapRequest({ - url : getAllScholarships.getAllScholarshipUrl, - headers: getAllScholarships.headers, - xml : util.format( - getAllScholarships.body - ) - }) +export const getAllScholarship = async (req: Request, res: Response) => { + try { + const result = await soapRequest({ + url: getAllScholarships.getAllScholarshipUrl, + headers: getAllScholarships.headers, + xml: util.format(getAllScholarships.body) + }) - const {body} = result.response + const { body } = result.response - const parser = new xml2js.Parser() - const parsedBody = await parser.parseStringPromise(body) - const message = - parsedBody["S:Envelope"]["S:Body"][0] [ - "ns2:setAcceptanceResponse" - ] [0]["return"] - - res.status(200).json({ - status: "success", - message: message - }) - } catch (error: any) { - console.error("SOAP request error:", error) - throw error - } + const parser = new xml2js.Parser() + const parsedBody = await parser.parseStringPromise(body) + const message = + parsedBody["S:Envelope"]["S:Body"][0]["ns2:setAcceptanceResponse"][0][ + "return" + ] + + res.status(200).json({ + status: "success", + message: message + }) + } catch (error: any) { + console.error("SOAP request error:", error) + throw error + } } -export const getScholarshipAcceptance = async(req : Request, res: Response) => { - try { - const result = await soapRequest({ - url : getAllScholarshipAcceptance.url, - headers : getAllScholarshipAcceptance.headers, - xml : util.format( - getAllScholarshipAcceptance.body - ) - }) - const {body} = result.response +export const getScholarshipAcceptance = async (req: Request, res: Response) => { + try { + const result = await soapRequest({ + url: getAllScholarshipAcceptance.url, + headers: getAllScholarshipAcceptance.headers, + xml: util.format(getAllScholarshipAcceptance.body) + }) + const { body } = result.response + + const parser = new xml2js.Parser() + const parsedBody = await parser.parseStringPromise(body) + const message = + parsedBody["S:Envelope"]["S:Body"][0]["ns2:setAcceptanceResponse"][0][ + "return" + ] - const parser = new xml2js.Parser() - const parsedBody = await parser.parseStringPromise(body) - const message = - parsedBody["S:Envelope"]["S:Body"][0] [ - "ns2:setAcceptanceResponse" - ] [0]["return"] - - res.status(200).json({ - status: "success", - message: message - }) - } catch(error : any) { - console.error("SOAP request error:", error) - throw error - } -} \ No newline at end of file + res.status(200).json({ + status: "success", + message: message + }) + } catch (error: any) { + console.error("SOAP request error:", error) + throw error + } +} diff --git a/controllers/student.controller.ts b/controllers/student.controller.ts index f955f33..2787a37 100644 --- a/controllers/student.controller.ts +++ b/controllers/student.controller.ts @@ -1,70 +1,67 @@ import { Request, Response } from "express" -import axios from 'axios' -import { getStudentOfScholarship } from "../templates/student"; +import axios from "axios" +import { getStudentOfScholarship } from "../templates/student" const xml2js = require("xml2js") const soapRequest = require("easy-soap-request") const util = require("util") -export const getUserPhpInfo = async (req : Request, res : Response) => { - try { - const uid = req.params.uid - const URL = process.env.MONOLITH_URL + "/api/profile/info.php?userid=" + uid - const response = await axios.get(URL); - const { name, email } = response.data; - res.status(200).json({ - status: "success", - message: "Assignment retrieved successfully", - data: { - user: { - name, - email, - }, - }, - }); - } catch (err) { - console.error(err); - res.status(500).json({ - status: "error", - message: "Internal server error", - }); - } -}; +export const getUserPhpInfo = async (req: Request, res: Response) => { + try { + const uid = req.params.uid + const URL = process.env.MONOLITH_URL + "/api/profile/info.php?userid=" + uid + const response = await axios.get(URL) + const { name, email } = response.data + res.status(200).json({ + status: "success", + message: "Assignment retrieved successfully", + data: { + user: { + name, + email + } + } + }) + } catch (err) { + console.error(err) + res.status(500).json({ + status: "error", + message: "Internal server error" + }) + } +} -export const getStudentFromScholarship = async (req: Request, res: Response) => { - try { - const sid = req.params.sid - console.log("SID", sid) +export const getStudentFromScholarship = async ( + req: Request, + res: Response +) => { + try { + const sid = req.params.sid + const { response } = await soapRequest({ + url: getStudentOfScholarship.url, + headers: getStudentOfScholarship.headers, + xml: util.format(getStudentOfScholarship.body, sid) + }) - const { response } = await soapRequest({ - url: getStudentOfScholarship.url, - headers: getStudentOfScholarship.headers, - xml: util.format( - getStudentOfScholarship.body, - sid - ) - }) - - const { body } = response - console.log("body",body) - const parser = new xml2js.Parser() - const parsedBody = await parser.parseStringPromise(body) - const scholarships = - parsedBody["S:Envelope"]["S:Body"][0]["ns2:getStudentOfScholarshipResponse"][0][ - "return" - ] - res.status(200).json({ - status: "success", - message: "User retrieved successfully", - data: { - scholarships - }, - }); - } catch(error : any) { - console.error(error); - res.status(500).json({ - status: "error", - message: "Internal server error", - }); - } -} \ No newline at end of file + const { body } = response + const parser = new xml2js.Parser() + const parsedBody = await parser.parseStringPromise(body) + const scholarships = + parsedBody["S:Envelope"]["S:Body"][0][ + "ns2:getStudentOfScholarshipResponse" + ][0]["return"] + res.status(200).json({ + status: "success", + message: "User retrieved successfully", + data: { + scholarships + } + }) + } catch (error: any) { + console.error(error) + res.status(500).json({ + status: "error", + message: "Internal server error" + }) + } +} diff --git a/controllers/university.controller.ts b/controllers/university.controller.ts index 148dded..1ef2e21 100644 --- a/controllers/university.controller.ts +++ b/controllers/university.controller.ts @@ -299,16 +299,16 @@ export const getUniversityStats = async (req: Request, res: Response) => { const phpId = uniObj ? uniObj.phpUniId[0] : null - const url = new URL (process.env.MONOLITH_URL + "/api/university/stats.php") + const url = new URL(process.env.MONOLITH_URL + "/api/university/stats.php") const params = new URLSearchParams() params.append("uid", phpId) - if(itemsperpage){ + if (itemsperpage) { params.append("name", name ? String(name) : "") params.append("itemsperpage", itemsperpage ? String(itemsperpage) : "") - params.append("currentpage", currentPage ? String(currentPage): "") + params.append("currentpage", currentPage ? String(currentPage) : "") } url.search = params.toString() - const universityAll = await fetch (url.toString()) + const universityAll = await fetch(url.toString()) const universityJSON = await universityAll.json() if (universityJSON) { diff --git a/polling/scholarships.ts b/polling/scholarships.ts index 168a528..1a067cf 100644 --- a/polling/scholarships.ts +++ b/polling/scholarships.ts @@ -169,7 +169,7 @@ const soapSync = async (scholarship: any, newScholarship: any) => { }) /* If scholarship already has acceptance, update the scholarship_id_rest in SOAP */ - const { res } = await soapRequest({ + await soapRequest({ url: setAcceptanceScholarshipIDREST.url, headers: setAcceptanceScholarshipIDREST.headers, xml: util.format( diff --git a/polling/sync.ts b/polling/sync.ts index 1053d1c..466fa18 100644 --- a/polling/sync.ts +++ b/polling/sync.ts @@ -2,8 +2,8 @@ import { scholarshipsSync } from "./scholarships" import { universitySync } from "./university" export const sync = () => { - setInterval(() => { - scholarshipsSync() - universitySync() - }, 10000) + setInterval(() => { + scholarshipsSync() + universitySync() + }, 10000) } diff --git a/polling/university.ts b/polling/university.ts index 5ee0612..03d20e2 100644 --- a/polling/university.ts +++ b/polling/university.ts @@ -6,53 +6,53 @@ const util = require("util") const prisma = new PrismaClient() export const universitySync = async () => { - try { + try { + const { response } = await soapRequest({ + url: getAllUniversities.url, + headers: getAllUniversities.headers, + xml: getAllUniversities.body + }) + const { body } = response + const parser = new xml2js.Parser() + const parsedBody = await parser.parseStringPromise(body) + const universities = + parsedBody["S:Envelope"]["S:Body"][0][ + "ns2:getAllUniversitiesResponse" + ][0]["return"] + + const universitiesFromDatabase = await prisma.university.findMany({ + select: { + university_id: true, + user: { + select: { + name: true + } + } + } + }) + for (const uni of universitiesFromDatabase) { + if ( + !universities || + !universities?.find( + (u: any) => Number(u.restUniId) === uni.university_id + ) + ) { const { response } = await soapRequest({ - url: getAllUniversities.url, - headers: getAllUniversities.headers, - xml: getAllUniversities.body + url: createUniversity.url, + headers: createUniversity.headers, + xml: util.format( + createUniversity.body, + uni.university_id, + uni.user?.name + ) }) const { body } = response const parser = new xml2js.Parser() const parsedBody = await parser.parseStringPromise(body) - const universities = - parsedBody["S:Envelope"]["S:Body"][0][ - "ns2:getAllUniversitiesResponse" - ][0]["return"] - - const universitiesFromDatabase = await prisma.university.findMany({ - select: { - university_id: true, - user: { - select: { - name: true - } - } - } - }) - for (const uni of universitiesFromDatabase) { - if ( - !universities || - !universities?.find( - (u: any) => Number(u.restUniId) === uni.university_id - ) - ) { - const { response } = await soapRequest({ - url: createUniversity.url, - headers: createUniversity.headers, - xml: util.format( - createUniversity.body, - uni.university_id, - uni.user?.name - ) - }) - const { body } = response - const parser = new xml2js.Parser() - const parsedBody = await parser.parseStringPromise(body) - } - } - console.log("🟢[UNIVERSITY] University sync successful") - } catch (error) { - console.error("🛑[UNIVERSITY] Error making SOAP request") + } } + console.log("🟢[UNIVERSITY] University sync successful") + } catch (error) { + console.error("🛑[UNIVERSITY] Error making SOAP request") + } } diff --git a/redis.ts b/redis.ts index bfd3d96..f372232 100644 --- a/redis.ts +++ b/redis.ts @@ -1,11 +1,11 @@ -import { createClient } from 'redis'; -import dotenv from 'dotenv'; +import { createClient } from "redis" +import dotenv from "dotenv" -dotenv.config(); +dotenv.config() export const client = createClient({ - socket: { - host: "127.0.0.1", - port: 6379, - } -}); + socket: { + host: "127.0.0.1", + port: 6379 + } +}) diff --git a/routes/assignmentPublic.routes.ts b/routes/assignmentPublic.routes.ts index 109a83b..ffa2868 100644 --- a/routes/assignmentPublic.routes.ts +++ b/routes/assignmentPublic.routes.ts @@ -1,12 +1,12 @@ import { - getAssignmentBySid, - getAssignment -} from '../controllers/assignment.controller' -import express from 'express' + getAssignmentBySid, + getAssignment +} from "../controllers/assignment.controller" +import express from "express" const router = express.Router() router.get("/assignment/:sid", getAssignmentBySid) router.get("/assignment/:sid/:aid", getAssignment) -module.exports = router \ No newline at end of file +module.exports = router diff --git a/routes/default.routes.ts b/routes/default.routes.ts index 2be789c..164937f 100644 --- a/routes/default.routes.ts +++ b/routes/default.routes.ts @@ -2,7 +2,7 @@ import express, { Request, Response, Express } from "express" const router = express.Router() router.get("/", (req: Request, res: Response) => { - const html = ` + const html = ` <!DOCTYPE html> <html> <head> @@ -52,7 +52,7 @@ router.get("/", (req: Request, res: Response) => { </body> </html> ` - res.type("html").send(html) + res.type("html").send(html) }) module.exports = router diff --git a/routes/files.routes.ts b/routes/files.routes.ts index 44d5058..d01f1c7 100644 --- a/routes/files.routes.ts +++ b/routes/files.routes.ts @@ -1,12 +1,12 @@ import express from "express" -import { - getAllFiles, - getFileById, -} from "../controllers/files.controller" +import { getAllFiles, getFileById } from "../controllers/files.controller" const router = express.Router() -router.get("/files/scholarship/:sid/assignment/:aid/file/:fid/user/:uid", getFileById) +router.get( + "/files/scholarship/:sid/assignment/:aid/file/:fid/user/:uid", + getFileById +) router.get("/files/scholarship/:sid/assignment/:aid", getAllFiles) module.exports = router diff --git a/routes/filesPublic.routes.ts b/routes/filesPublic.routes.ts index 445ee8e..1c82676 100644 --- a/routes/filesPublic.routes.ts +++ b/routes/filesPublic.routes.ts @@ -1,25 +1,26 @@ -import express from "express"; -import { - uploadFiles, - uploadFile -} from "../controllers/files.controller"; +import express from "express" +import { uploadFiles, uploadFile } from "../controllers/files.controller" -import multer from 'multer'; +import multer from "multer" const router = express.Router() const upload = multer() -router.post("/files/scholarship/:sid/assignment/:aid", upload.any(), async (req: any, res: any) => { +router.post( + "/files/scholarship/:sid/assignment/:aid", + upload.any(), + async (req: any, res: any) => { try { - const { files } = req; - const fileUrls = await Promise.all( - files.map(async (file: any) => uploadFile(file)) - ); - console.log("links", fileUrls); - await uploadFiles(req, res); + const { files } = req + const fileUrls = await Promise.all( + files.map(async (file: any) => uploadFile(file)) + ) + console.log("links", fileUrls) + await uploadFiles(req, res) } catch (error: any) { - res.status(500).send(error.message); + res.status(500).send(error.message) } -}); + } +) -module.exports = router \ No newline at end of file +module.exports = router diff --git a/routes/organization.routes.ts b/routes/organization.routes.ts index 2934bcc..628fce3 100644 --- a/routes/organization.routes.ts +++ b/routes/organization.routes.ts @@ -1,10 +1,10 @@ import express from "express" import { - getOrganizations, - getOrganization, - createOrganization, - updateOrganization, - deleteOrganization + getOrganizations, + getOrganization, + createOrganization, + updateOrganization, + deleteOrganization } from "../controllers/organization.controller" const router = express.Router() diff --git a/routes/organizationPublic.routes.ts b/routes/organizationPublic.routes.ts index fca5443..ff27f43 100644 --- a/routes/organizationPublic.routes.ts +++ b/routes/organizationPublic.routes.ts @@ -1,11 +1,8 @@ import express from "express" -import { - createOrganization, -} from "../controllers/organization.controller" +import { createOrganization } from "../controllers/organization.controller" const router = express.Router() router.post("/organization", createOrganization) - -module.exports = router \ No newline at end of file +module.exports = router diff --git a/routes/scholarship.routes.ts b/routes/scholarship.routes.ts index 44b1c9c..3780f02 100644 --- a/routes/scholarship.routes.ts +++ b/routes/scholarship.routes.ts @@ -1,13 +1,13 @@ import express from "express" import { - createScholarship, - getScholarships, - getScholarship, - updateScholarship, - deleteScholarship, - getAllScholarshipTypes, - scholarshipCount, - scholarshipAcceptance + createScholarship, + getScholarships, + getScholarship, + updateScholarship, + deleteScholarship, + getAllScholarshipTypes, + scholarshipCount, + scholarshipAcceptance } from "../controllers/scholarship.controller" const router = express.Router() diff --git a/routes/student.routes.ts b/routes/student.routes.ts index 9a663f1..34d8abf 100644 --- a/routes/student.routes.ts +++ b/routes/student.routes.ts @@ -1,7 +1,7 @@ import express from "express" import { - getUserPhpInfo, - getStudentFromScholarship + getUserPhpInfo, + getStudentFromScholarship } from "../controllers/student.controller" const router = express.Router() @@ -9,4 +9,4 @@ const router = express.Router() router.get("/user/:uid", getUserPhpInfo) router.get("/scholarship/user/:sid", getStudentFromScholarship) -module.exports = router \ No newline at end of file +module.exports = router diff --git a/routes/university.routes.ts b/routes/university.routes.ts index 4a4abe7..4514d7b 100644 --- a/routes/university.routes.ts +++ b/routes/university.routes.ts @@ -1,10 +1,10 @@ import express from "express" import { - getUniversities, - getUniversity, - updateUniversity, - deleteUniversity, - getUniversityStats + getUniversities, + getUniversity, + updateUniversity, + deleteUniversity, + getUniversityStats } from "../controllers/university.controller" const router = express.Router() diff --git a/routes/universityPublic.routes.ts b/routes/universityPublic.routes.ts index c641f85..f846ee9 100644 --- a/routes/universityPublic.routes.ts +++ b/routes/universityPublic.routes.ts @@ -1,7 +1,5 @@ import express from "express" -import { - createUniversity -} from "../controllers/university.controller" +import { createUniversity } from "../controllers/university.controller" const router = express.Router() diff --git a/templates/getAllScholarship.ts b/templates/getAllScholarship.ts index bb6367c..f247783 100644 --- a/templates/getAllScholarship.ts +++ b/templates/getAllScholarship.ts @@ -1,9 +1,10 @@ const headers = { - "Content-Type": "text/xml;charset=UTF-8", - "X-API-KEY": process.env.SOAP_API_KEY + "Content-Type": "text/xml;charset=UTF-8", + "X-API-KEY": process.env.SOAP_API_KEY } -const getAllScholarshipUrl = process.env.SOAP_URL + "/ws/ScholarshipService?wsdl" +const getAllScholarshipUrl = + process.env.SOAP_URL + "/ws/ScholarshipService?wsdl" const getAllScholarshipTemplate = ` <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"> @@ -15,7 +16,7 @@ const getAllScholarshipTemplate = ` ` export const getAllScholarships = { - getAllScholarshipUrl, - headers, - body: getAllScholarshipTemplate -} \ No newline at end of file + getAllScholarshipUrl, + headers, + body: getAllScholarshipTemplate +} diff --git a/templates/organization.ts b/templates/organization.ts index 807c163..97f3c63 100644 --- a/templates/organization.ts +++ b/templates/organization.ts @@ -2,8 +2,8 @@ import dotenv from "dotenv" dotenv.config() const headers = { - "Content-Type": "text/xml;charset=UTF-8", - "X-API-KEY": process.env.SOAP_API_KEY + "Content-Type": "text/xml;charset=UTF-8", + "X-API-KEY": process.env.SOAP_API_KEY } const url = process.env.SOAP_URL + "/ws/OrganizationRegistration?wsdl" @@ -30,13 +30,13 @@ const validateReferralCodeTemplate = ` ` export const createRESTId = { - url, - headers, - body: createRESTIdTemplate + url, + headers, + body: createRESTIdTemplate } export const validateReferralCode = { - url, - headers, - body: validateReferralCodeTemplate + url, + headers, + body: validateReferralCodeTemplate } diff --git a/templates/scholarship.ts b/templates/scholarship.ts index f0e3b00..dce58be 100644 --- a/templates/scholarship.ts +++ b/templates/scholarship.ts @@ -2,8 +2,8 @@ import dotenv from "dotenv" dotenv.config() const headers = { - "Content-Type": "text/xml;charset=UTF-8", - "X-API-KEY": process.env.SOAP_API_KEY + "Content-Type": "text/xml;charset=UTF-8", + "X-API-KEY": process.env.SOAP_API_KEY } const url = process.env.SOAP_URL + "/ws/ScholarshipService?wsdl" @@ -41,19 +41,19 @@ const viewScholarshipCountTemplate = ` ` export const getAllScholarship = { - url, - headers, - body: getAllScholarshipEnvelope + url, + headers, + body: getAllScholarshipEnvelope } export const setScholarshipREST = { - url, - headers, - body: setScholarshipRESTTemplate + url, + headers, + body: setScholarshipRESTTemplate } export const viewScholarshipCount = { - url, - headers, - body: viewScholarshipCountTemplate -} \ No newline at end of file + url, + headers, + body: viewScholarshipCountTemplate +} diff --git a/templates/scholarshipAcceptance.ts b/templates/scholarshipAcceptance.ts index 743bd88..e4cb429 100644 --- a/templates/scholarshipAcceptance.ts +++ b/templates/scholarshipAcceptance.ts @@ -2,8 +2,8 @@ import dotenv from "dotenv" dotenv.config() const headers = { - "Content-Type": "text/xml;charset=UTF-8", - "X-API-KEY": process.env.SOAP_API_KEY + "Content-Type": "text/xml;charset=UTF-8", + "X-API-KEY": process.env.SOAP_API_KEY } const url = process.env.SOAP_URL + "/ws/ScholarshipAcceptance?wsdl" @@ -38,22 +38,22 @@ const setScholarshipIDRESTTemplate = ` <scholarship_id_rest xmlns="">%d</scholarship_id_rest> </setScholarshipIDREST> </Body> -</Envelope>`; +</Envelope>` export const setAcceptance = { - url, - headers, - body: setAcceptanceTemplate + url, + headers, + body: setAcceptanceTemplate } export const setAcceptanceScholarshipIDREST = { - url, - headers, - body: setScholarshipIDRESTTemplate + url, + headers, + body: setScholarshipIDRESTTemplate } export const getAllScholarshipAcceptance = { - url, - headers, - body : getAllScholarshipAcceptanceTemplate -} \ No newline at end of file + url, + headers, + body: getAllScholarshipAcceptanceTemplate +} diff --git a/templates/student.ts b/templates/student.ts index 6c66b6e..18cb824 100644 --- a/templates/student.ts +++ b/templates/student.ts @@ -1,9 +1,10 @@ const headers = { - "Content-Type": "text/xml;charset=UTF-8", - "X-API-KEY": process.env.SOAP_API_KEY + "Content-Type": "text/xml;charset=UTF-8", + "X-API-KEY": process.env.SOAP_API_KEY } -const getStudentOfScholarshipURL = process.env.SOAP_URL + "/ws/ScholarshipAcceptance?wsdl" +const getStudentOfScholarshipURL = + process.env.SOAP_URL + "/ws/ScholarshipAcceptance?wsdl" const getStudentOfScholarshipTemplate = ` <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"> @@ -16,7 +17,7 @@ const getStudentOfScholarshipTemplate = ` ` export const getStudentOfScholarship = { - url : getStudentOfScholarshipURL, - headers : headers, - body: getStudentOfScholarshipTemplate -} \ No newline at end of file + url: getStudentOfScholarshipURL, + headers: headers, + body: getStudentOfScholarshipTemplate +} diff --git a/templates/university.ts b/templates/university.ts index 5f199dd..dd6c94f 100644 --- a/templates/university.ts +++ b/templates/university.ts @@ -4,8 +4,8 @@ dotenv.config() const url = process.env.SOAP_URL + "/ws/UniversityService?wsdl" const headers = { - "Content-Type": "text/xml;charset=UTF-8", - "X-API-KEY": process.env.SOAP_API_KEY + "Content-Type": "text/xml;charset=UTF-8", + "X-API-KEY": process.env.SOAP_API_KEY } const getAllUniversitiesTemplate = ` @@ -29,13 +29,13 @@ const createUniversityTemplate = ` ` export const getAllUniversities = { - url, - headers, - body: getAllUniversitiesTemplate + url, + headers, + body: getAllUniversitiesTemplate } export const createUniversity = { - url, - headers, - body: createUniversityTemplate + url, + headers, + body: createUniversityTemplate } -- GitLab