From 67fcbcfe67f2397b55dd97bc4dd43b7612ef93e7 Mon Sep 17 00:00:00 2001 From: pakash2003pramanick Date: Tue, 12 Aug 2025 20:40:46 +0530 Subject: [PATCH 01/13] added controllers for fetching attendance token and marking present --- controllers/auth/loginController.js | 2 ++ controllers/registration/addRegistration.js | 4 ++-- controllers/registration/registrationController.js | 4 +++- index.js | 10 +++++----- routes/api/forms/formRoutes.js | 12 +++++++++--- 5 files changed, 21 insertions(+), 11 deletions(-) diff --git a/controllers/auth/loginController.js b/controllers/auth/loginController.js index 03ed096..d2c0dea 100644 --- a/controllers/auth/loginController.js +++ b/controllers/auth/loginController.js @@ -12,6 +12,8 @@ const login = expressAsyncHandler(async (req, res, next) => { // const { email, password } = req.body; try { + + console.log("user ", req.user); // const user = await prisma.user.findUnique({ // where: { email } // }); diff --git a/controllers/registration/addRegistration.js b/controllers/registration/addRegistration.js index 167a321..de02884 100644 --- a/controllers/registration/addRegistration.js +++ b/controllers/registration/addRegistration.js @@ -1,5 +1,5 @@ const { PrismaClient, AccessTypes } = require("@prisma/client"); - const moment = require('moment-timezone'); +const moment = require('moment-timezone'); const prisma = new PrismaClient(); const { ApiError } = require("../../utils/error/ApiError"); const expressAsyncHandler = require("express-async-handler"); @@ -110,7 +110,7 @@ const addRegistration = expressAsyncHandler(async (req, res, next) => { user_id: req.user.id, user_email: req.user.email, date_time: moment().tz("Asia/Kolkata").format(), - amount : form?.info?.eventAmount || '0', + amount: form?.info?.eventAmount || '0', sections: sections }; console.log("sections Object : ", sectionsObject) diff --git a/controllers/registration/registrationController.js b/controllers/registration/registrationController.js index 056b1a6..30d549a 100644 --- a/controllers/registration/registrationController.js +++ b/controllers/registration/registrationController.js @@ -1,9 +1,11 @@ const { addRegistration } = require('./addRegistration'); const { getRegistrationCount } = require('./countRegistration'); const { downloadRegistration } = require('./downloadRegistration'); +const { getAttendanceCode } = require('./markAttendance'); module.exports = { addRegistration, downloadRegistration, - getRegistrationCount + getRegistrationCount, + getAttendanceCode, }; diff --git a/index.js b/index.js index eb1eb2e..98e99d7 100644 --- a/index.js +++ b/index.js @@ -113,9 +113,9 @@ app.use(express.urlencoded({ extended: true, limit: "16kb" })); app.use(cookieParser()); app.use(cors({ - origin: "*", - methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], - credentials: true, + origin: "*", + methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], + credentials: true, })); app.options('*', cors()); // handle preflight requests @@ -182,11 +182,11 @@ app.use(jsonParseErrorHandler); // Error-handling middleware - should be at the end app.use(errorHandler); -app.use('/keep-alive',(req,res) => { +app.use('/keep-alive', (req, res) => { res.sendStatus(200); // res.status(200).json({message : "Alive"}); }) -app.use('/',(req,res) => { +app.use('/', (req, res) => { res.sendStatus(404); }) // Start server diff --git a/routes/api/forms/formRoutes.js b/routes/api/forms/formRoutes.js index 3eed4d1..254643c 100644 --- a/routes/api/forms/formRoutes.js +++ b/routes/api/forms/formRoutes.js @@ -16,9 +16,9 @@ router.post('/contact', formController.contact); router.use(verifyToken); -router.use('/register', - checkAccess('USER'), - imageUpload.any(), +router.use('/register', + checkAccess('USER'), + imageUpload.any(), registrationController.addRegistration ); router.get( @@ -26,6 +26,12 @@ router.get( formController.analytics ) +router.get( + "/attendanceCode/:id", + checkAccess("USER"), + registrationController.getAttendanceCode +); + // router.get( // "/registrationCount", // checkAccess("MEMBER"), From 8796d3adcc4fc7060f4560cc456188112ac5bf7e Mon Sep 17 00:00:00 2001 From: pakash2003pramanick Date: Tue, 12 Aug 2025 22:24:12 +0530 Subject: [PATCH 02/13] updated attendance controllers --- controllers/registration/markAttendance.js | 160 +++++++++++++++++++++ prisma/schema/attendance.prisma | 19 +++ 2 files changed, 179 insertions(+) create mode 100644 controllers/registration/markAttendance.js create mode 100644 prisma/schema/attendance.prisma diff --git a/controllers/registration/markAttendance.js b/controllers/registration/markAttendance.js new file mode 100644 index 0000000..4b8f997 --- /dev/null +++ b/controllers/registration/markAttendance.js @@ -0,0 +1,160 @@ +const { ApiError } = require("../../utils/error/ApiError"); +const { PrismaClient } = require("@prisma/client"); +const prisma = new PrismaClient(); +const jwt = require("jsonwebtoken"); + + +const getAttendanceCode = async (req, res, next) => { + try { + const { id: formId } = req.params; + const { teamCode } = req.query; + const { id: userId } = req.user; + + + if (!formId || !userId) { + return next(new ApiError(400, "Form ID or User ID is missing.")); + } + + + let formRegistrationDetails = null; + // Fetching event details from the database + if (teamCode) { + formRegistrationDetails = await prisma.formRegistration.findFirst({ + where: { + formId, + teamCode, + } + }); + + console.log("formRegistrationDetails:", formRegistrationDetails); + } + else { + const allFormRegistrationDetails = await prisma.formRegistration.findMany({ + where: { + formId, + } + }); + + console.log("allFormRegistrationDetails:", allFormRegistrationDetails); + + + formRegistrationDetails = allFormRegistrationDetails.find(registration => registration.value.some(value => value.user_id === userId)); + + console.log("Filtered formRegistrationDetails:", formRegistrationDetails); + + + if (!formRegistrationDetails) { + return next(new ApiError(404, "Form registration not found for the user.")); + } + formRegistrationDetails = { + ...formRegistrationDetails + }; + } + + // If no registration details found, return an error + if (!formRegistrationDetails) { + return next(new ApiError(404, "Form registration not found.")); + } + + const info = formRegistrationDetails.value.find(value => value.user_id === userId); + + // Put in attendance db + const attendanceData = { + formId: formId, + userId: userId, + teamName: formRegistrationDetails.teamName, + teamCode: formRegistrationDetails.teamCode, + info, + }; + + // Create or update attendance record + const attendanceDetails = await prisma.attendance.upsert({ + where: { + formId_userId_teamCode: { + formId: attendanceData.formId, + userId: attendanceData.userId, + teamCode: attendanceData.teamCode, + } + }, + create: attendanceData, + update: attendanceData, + }) + + + // Create JWT token for QR code that expires in 20 minutes + const token = jwt.sign({ + attendanceToken: attendanceDetails.id, + }, process.env.JWT_SECRET, { expiresIn: '20m' }); + + // Return JWT token + return res.status(200).json({ + message: "Validation id generated successfully.", + attendanceToken: token, + }); + } catch (error) { + console.error('Error generating QR link:', error); + return next(new ApiError(error.statusCode || 500, error.message || "Internal Server Error", error)); + + + } +}; + + +const markAttendance = async (req, res, next) => { + const { token } = req.body; + + + if (!token) { + return next(new ApiError(400, "Attendance token is required.")); + } + try { + // Verify the JWT token + let decoded; + try { + decoded = jwt.verify(token, process.env.JWT_SECRET); + } catch (err) { + return next(new ApiError(401, "Invalid or expired attendance token.")); + } + const attendanceId = decoded.attendanceToken; + + if (!attendanceId) { + return next(new ApiError(400, "Attendance ID is missing in the token.")); + } + + // Check if the attendance ID is valid + const attendanceRecord = await prisma.attendance.findUnique({ + where: { id: attendanceId }, + }); + + // Check if the attendance is already marked + if (attendanceRecord?.isPresent) { + return next(new ApiError(400, "Attendance already marked.")); + } + + // Check if payment is verified + // if (!attendanceRecord?.isPaymentVerified) { + // return next(new ApiError(400, "Payment not verified for this attendance.")); + // } + + + // Mark attendance as present + const updatedAttendance = await prisma.attendance.update({ + where: { id: attendanceId }, + data: { isPresent: true }, + }); + + + res.status(200).json({ message: "Attendance marked successfully.", attendance: updatedAttendance }); + + + } catch (error) { + console.error('Error marking attendance:', error); + return next(new ApiError(error.statusCode || 500, error.message || "Internal Server Error", error)); + } +} + + +module.exports = { + getAttendanceCode, + markAttendance +}; diff --git a/prisma/schema/attendance.prisma b/prisma/schema/attendance.prisma new file mode 100644 index 0000000..bd1d340 --- /dev/null +++ b/prisma/schema/attendance.prisma @@ -0,0 +1,19 @@ +model attendance { + id String @id @default(auto()) @map("_id") @db.ObjectId + + userId String @db.ObjectId + + formId String @db.ObjectId + + teamName String + teamCode String + + isPresent Boolean @default(false) + isPaymentVerified Boolean @default(false) + + info Json + + @@map("attendance") + @@unique([formId, userId, teamCode]) +} + From 4258de3d3387ad763c4e6ee77d51e94be28c44c4 Mon Sep 17 00:00:00 2001 From: pakash2003pramanick Date: Tue, 12 Aug 2025 22:24:30 +0530 Subject: [PATCH 03/13] updated attendance controllers --- controllers/registration/markAttendance.js | 14 ++++++++++++-- controllers/registration/registrationController.js | 3 ++- routes/api/forms/formRoutes.js | 12 ++++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/controllers/registration/markAttendance.js b/controllers/registration/markAttendance.js index 4b8f997..a872f8e 100644 --- a/controllers/registration/markAttendance.js +++ b/controllers/registration/markAttendance.js @@ -101,7 +101,7 @@ const getAttendanceCode = async (req, res, next) => { const markAttendance = async (req, res, next) => { - const { token } = req.body; + const { formId, token } = req.body; if (!token) { @@ -113,7 +113,7 @@ const markAttendance = async (req, res, next) => { try { decoded = jwt.verify(token, process.env.JWT_SECRET); } catch (err) { - return next(new ApiError(401, "Invalid or expired attendance token.")); + return next(new ApiError(401, "Invalid or expired QR.")); } const attendanceId = decoded.attendanceToken; @@ -126,6 +126,16 @@ const markAttendance = async (req, res, next) => { where: { id: attendanceId }, }); + // If no attendance record found, return an error + if (!attendanceRecord) { + return next(new ApiError(404, "Attendance record not found.")); + } + + // Check if it belongs to the correct form + if (attendanceRecord.formId !== formId) { + return next(new ApiError(400, "QR does not belong to the specified form.")); + } + // Check if the attendance is already marked if (attendanceRecord?.isPresent) { return next(new ApiError(400, "Attendance already marked.")); diff --git a/controllers/registration/registrationController.js b/controllers/registration/registrationController.js index 30d549a..56b6241 100644 --- a/controllers/registration/registrationController.js +++ b/controllers/registration/registrationController.js @@ -1,11 +1,12 @@ const { addRegistration } = require('./addRegistration'); const { getRegistrationCount } = require('./countRegistration'); const { downloadRegistration } = require('./downloadRegistration'); -const { getAttendanceCode } = require('./markAttendance'); +const { getAttendanceCode, markAttendance } = require('./markAttendance'); module.exports = { addRegistration, downloadRegistration, getRegistrationCount, getAttendanceCode, + markAttendance }; diff --git a/routes/api/forms/formRoutes.js b/routes/api/forms/formRoutes.js index 254643c..3e4d797 100644 --- a/routes/api/forms/formRoutes.js +++ b/routes/api/forms/formRoutes.js @@ -32,6 +32,18 @@ router.get( registrationController.getAttendanceCode ); +router.post( + "/markAttendance", + // checkAccess([ + // "SENIOR_EXECUTIVE_TECHNICAL", + // "SENIOR_EXECUTIVE_CREATIVE", + // "SENIOR_EXECUTIVE_MARKETING", + // "SENIOR_EXECUTIVE_OPERATIONS", + // "SENIOR_EXECUTIVE_PR_AND_FINANCE", + // "SENIOR_EXECUTIVE_HUMAN_RESOURCE"]), + registrationController.markAttendance +); + // router.get( // "/registrationCount", // checkAccess("MEMBER"), From 46358a9eca4646bd06df668229d0764fee0df398 Mon Sep 17 00:00:00 2001 From: shing1Sks Date: Wed, 13 Aug 2025 00:47:27 +0530 Subject: [PATCH 04/13] export attendence controller --- controllers/registration/markAttendance.js | 366 +++++++++++------- .../registration/registrationController.js | 23 +- package-lock.json | 1 + routes/api/forms/formRoutes.js | 80 ++-- 4 files changed, 288 insertions(+), 182 deletions(-) diff --git a/controllers/registration/markAttendance.js b/controllers/registration/markAttendance.js index a872f8e..97402d9 100644 --- a/controllers/registration/markAttendance.js +++ b/controllers/registration/markAttendance.js @@ -2,169 +2,269 @@ const { ApiError } = require("../../utils/error/ApiError"); const { PrismaClient } = require("@prisma/client"); const prisma = new PrismaClient(); const jwt = require("jsonwebtoken"); - +const XLSX = require("xlsx"); const getAttendanceCode = async (req, res, next) => { - try { - const { id: formId } = req.params; - const { teamCode } = req.query; - const { id: userId } = req.user; - - - if (!formId || !userId) { - return next(new ApiError(400, "Form ID or User ID is missing.")); - } + try { + const { id: formId } = req.params; + const { teamCode } = req.query; + const { id: userId } = req.user; + if (!formId || !userId) { + return next(new ApiError(400, "Form ID or User ID is missing.")); + } - let formRegistrationDetails = null; - // Fetching event details from the database - if (teamCode) { - formRegistrationDetails = await prisma.formRegistration.findFirst({ - where: { - formId, - teamCode, - } - }); - - console.log("formRegistrationDetails:", formRegistrationDetails); + let formRegistrationDetails = null; + // Fetching event details from the database + if (teamCode) { + formRegistrationDetails = await prisma.formRegistration.findFirst({ + where: { + formId, + teamCode, + }, + }); + + console.log("formRegistrationDetails:", formRegistrationDetails); + } else { + const allFormRegistrationDetails = await prisma.formRegistration.findMany( + { + where: { + formId, + }, } - else { - const allFormRegistrationDetails = await prisma.formRegistration.findMany({ - where: { - formId, - } - }); - - console.log("allFormRegistrationDetails:", allFormRegistrationDetails); + ); + console.log("allFormRegistrationDetails:", allFormRegistrationDetails); - formRegistrationDetails = allFormRegistrationDetails.find(registration => registration.value.some(value => value.user_id === userId)); + formRegistrationDetails = allFormRegistrationDetails.find( + (registration) => + registration.value.some((value) => value.user_id === userId) + ); - console.log("Filtered formRegistrationDetails:", formRegistrationDetails); - - - if (!formRegistrationDetails) { - return next(new ApiError(404, "Form registration not found for the user.")); - } - formRegistrationDetails = { - ...formRegistrationDetails - }; - } - - // If no registration details found, return an error - if (!formRegistrationDetails) { - return next(new ApiError(404, "Form registration not found.")); - } - - const info = formRegistrationDetails.value.find(value => value.user_id === userId); - - // Put in attendance db - const attendanceData = { - formId: formId, - userId: userId, - teamName: formRegistrationDetails.teamName, - teamCode: formRegistrationDetails.teamCode, - info, - }; - - // Create or update attendance record - const attendanceDetails = await prisma.attendance.upsert({ - where: { - formId_userId_teamCode: { - formId: attendanceData.formId, - userId: attendanceData.userId, - teamCode: attendanceData.teamCode, - } - }, - create: attendanceData, - update: attendanceData, - }) - - - // Create JWT token for QR code that expires in 20 minutes - const token = jwt.sign({ - attendanceToken: attendanceDetails.id, - }, process.env.JWT_SECRET, { expiresIn: '20m' }); - - // Return JWT token - return res.status(200).json({ - message: "Validation id generated successfully.", - attendanceToken: token, - }); - } catch (error) { - console.error('Error generating QR link:', error); - return next(new ApiError(error.statusCode || 500, error.message || "Internal Server Error", error)); + console.log("Filtered formRegistrationDetails:", formRegistrationDetails); + if (!formRegistrationDetails) { + return next( + new ApiError(404, "Form registration not found for the user.") + ); + } + formRegistrationDetails = { + ...formRegistrationDetails, + }; + } + // If no registration details found, return an error + if (!formRegistrationDetails) { + return next(new ApiError(404, "Form registration not found.")); } -}; + const info = formRegistrationDetails.value.find( + (value) => value.user_id === userId + ); + + // Put in attendance db + const attendanceData = { + formId: formId, + userId: userId, + teamName: formRegistrationDetails.teamName, + teamCode: formRegistrationDetails.teamCode, + info, + }; + + // Create or update attendance record + const attendanceDetails = await prisma.attendance.upsert({ + where: { + formId_userId_teamCode: { + formId: attendanceData.formId, + userId: attendanceData.userId, + teamCode: attendanceData.teamCode, + }, + }, + create: attendanceData, + update: attendanceData, + }); + + // Create JWT token for QR code that expires in 20 minutes + const token = jwt.sign( + { + attendanceToken: attendanceDetails.id, + }, + process.env.JWT_SECRET, + { expiresIn: "20m" } + ); + + // Return JWT token + return res.status(200).json({ + message: "Validation id generated successfully.", + attendanceToken: token, + }); + } catch (error) { + console.error("Error generating QR link:", error); + return next( + new ApiError( + error.statusCode || 500, + error.message || "Internal Server Error", + error + ) + ); + } +}; const markAttendance = async (req, res, next) => { - const { formId, token } = req.body; - + const { formId, token } = req.body; + + if (!token) { + return next(new ApiError(400, "Attendance token is required.")); + } + try { + // Verify the JWT token + let decoded; + try { + decoded = jwt.verify(token, process.env.JWT_SECRET); + } catch (err) { + return next(new ApiError(401, "Invalid or expired QR.")); + } + const attendanceId = decoded.attendanceToken; - if (!token) { - return next(new ApiError(400, "Attendance token is required.")); + if (!attendanceId) { + return next(new ApiError(400, "Attendance ID is missing in the token.")); } - try { - // Verify the JWT token - let decoded; - try { - decoded = jwt.verify(token, process.env.JWT_SECRET); - } catch (err) { - return next(new ApiError(401, "Invalid or expired QR.")); - } - const attendanceId = decoded.attendanceToken; - if (!attendanceId) { - return next(new ApiError(400, "Attendance ID is missing in the token.")); - } + // Check if the attendance ID is valid + const attendanceRecord = await prisma.attendance.findUnique({ + where: { id: attendanceId }, + }); - // Check if the attendance ID is valid - const attendanceRecord = await prisma.attendance.findUnique({ - where: { id: attendanceId }, - }); + // If no attendance record found, return an error + if (!attendanceRecord) { + return next(new ApiError(404, "Attendance record not found.")); + } - // If no attendance record found, return an error - if (!attendanceRecord) { - return next(new ApiError(404, "Attendance record not found.")); - } + // Check if it belongs to the correct form + if (attendanceRecord.formId !== formId) { + return next( + new ApiError(400, "QR does not belong to the specified form.") + ); + } - // Check if it belongs to the correct form - if (attendanceRecord.formId !== formId) { - return next(new ApiError(400, "QR does not belong to the specified form.")); - } + // Check if the attendance is already marked + if (attendanceRecord?.isPresent) { + return next(new ApiError(400, "Attendance already marked.")); + } - // Check if the attendance is already marked - if (attendanceRecord?.isPresent) { - return next(new ApiError(400, "Attendance already marked.")); - } + // Check if payment is verified + // if (!attendanceRecord?.isPaymentVerified) { + // return next(new ApiError(400, "Payment not verified for this attendance.")); + // } + + // Mark attendance as present + const updatedAttendance = await prisma.attendance.update({ + where: { id: attendanceId }, + data: { isPresent: true }, + }); + + res.status(200).json({ + message: "Attendance marked successfully.", + attendance: updatedAttendance, + }); + } catch (error) { + console.error("Error marking attendance:", error); + return next( + new ApiError( + error.statusCode || 500, + error.message || "Internal Server Error", + error + ) + ); + } +}; - // Check if payment is verified - // if (!attendanceRecord?.isPaymentVerified) { - // return next(new ApiError(400, "Payment not verified for this attendance.")); - // } +const exportAttendance = async (req, res, next) => { + try { + const { id: formId } = req.params; + const { teamCode, format } = req.query; + if (!formId) { + return next(new ApiError(400, "Form ID is required.")); + } - // Mark attendance as present - const updatedAttendance = await prisma.attendance.update({ - where: { id: attendanceId }, - data: { isPresent: true }, - }); + // Build query + const whereClause = { formId }; + if (teamCode) whereClause.teamCode = teamCode; + // Fetch attendance records + const records = await prisma.attendance.findMany({ + where: whereClause, + }); - res.status(200).json({ message: "Attendance marked successfully.", attendance: updatedAttendance }); + if (!records.length) { + return next(new ApiError(404, "No attendance records found.")); + } + // Handle JSON format + if (!format || format === "json") { + let grouped; + + if (teamCode) { + grouped = [ + { + teamCode: teamCode, + members: records, + }, + ]; + } else { + grouped = Object.values( + records.reduce((acc, record) => { + if (!acc[record.teamCode]) { + acc[record.teamCode] = { + teamCode: record.teamCode, + members: [], + }; + } + acc[record.teamCode].members.push(record); + return acc; + }, {}) + ); + } + + return res.status(200).json(grouped); + } - } catch (error) { - console.error('Error marking attendance:', error); - return next(new ApiError(error.statusCode || 500, error.message || "Internal Server Error", error)); + // Handle XLSX format + if (format === "xlsx") { + // Add phoneNumber field placeholder + const withPhone = records.map((r) => ({ + ...r, + phoneNumber: "1234", + })); + + const worksheet = XLSX.utils.json_to_sheet(withPhone); + const workbook = XLSX.utils.book_new(); + XLSX.utils.book_append_sheet(workbook, worksheet, "Attendance"); + + const buffer = XLSX.write(workbook, { type: "buffer", bookType: "xlsx" }); + + res.setHeader( + "Content-Disposition", + `attachment; filename="attendance_${formId}.xlsx"` + ); + res.setHeader( + "Content-Type", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + ); + + return res.send(buffer); } -} + return next(new ApiError(400, "Invalid format. Supported: json, xlsx.")); + } catch (error) { + console.error(error); + next(new ApiError(500, "Server error.")); + } +}; module.exports = { - getAttendanceCode, - markAttendance + getAttendanceCode, + markAttendance, + exportAttendance, }; diff --git a/controllers/registration/registrationController.js b/controllers/registration/registrationController.js index 56b6241..a7b64bc 100644 --- a/controllers/registration/registrationController.js +++ b/controllers/registration/registrationController.js @@ -1,12 +1,17 @@ -const { addRegistration } = require('./addRegistration'); -const { getRegistrationCount } = require('./countRegistration'); -const { downloadRegistration } = require('./downloadRegistration'); -const { getAttendanceCode, markAttendance } = require('./markAttendance'); +const { addRegistration } = require("./addRegistration"); +const { getRegistrationCount } = require("./countRegistration"); +const { downloadRegistration } = require("./downloadRegistration"); +const { + getAttendanceCode, + markAttendance, + exportAttendance, +} = require("./markAttendance"); module.exports = { - addRegistration, - downloadRegistration, - getRegistrationCount, - getAttendanceCode, - markAttendance + addRegistration, + downloadRegistration, + getRegistrationCount, + getAttendanceCode, + markAttendance, + exportAttendance, }; diff --git a/package-lock.json b/package-lock.json index 85866d5..92b54f1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2206,6 +2206,7 @@ "version": "4.4.0", "resolved": "https://registry.npmjs.org/exceljs/-/exceljs-4.4.0.tgz", "integrity": "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==", + "license": "MIT", "dependencies": { "archiver": "^5.0.0", "dayjs": "^1.8.34", diff --git a/routes/api/forms/formRoutes.js b/routes/api/forms/formRoutes.js index 3e4d797..0504aa5 100644 --- a/routes/api/forms/formRoutes.js +++ b/routes/api/forms/formRoutes.js @@ -1,47 +1,47 @@ const express = require("express"); const router = express.Router(); -const formController = require('../../../controllers/forms/formController') -const registrationController = require('../../../controllers/registration/registrationController'); -const { verifyToken } = require('../../../middleware/verifyToken'); -const { checkAccess } = require('../../../middleware/access/checkAccess'); -const multer = require('multer'); -const { imageUpload } = require('../../../middleware/upload'); +const formController = require("../../../controllers/forms/formController"); +const registrationController = require("../../../controllers/registration/registrationController"); +const { verifyToken } = require("../../../middleware/verifyToken"); +const { checkAccess } = require("../../../middleware/access/checkAccess"); +const multer = require("multer"); +const { imageUpload } = require("../../../middleware/upload"); const upload = multer(); // Add validations // Define your form routes here -router.get('/getAllForms', formController.getAllForms) -router.post('/contact', formController.contact); +router.get("/getAllForms", formController.getAllForms); +router.post("/contact", formController.contact); + +router.get("/export-attendance/:id", registrationController.exportAttendance); router.use(verifyToken); -router.use('/register', - checkAccess('USER'), - imageUpload.any(), - registrationController.addRegistration +router.use( + "/register", + checkAccess("USER"), + imageUpload.any(), + registrationController.addRegistration ); -router.get( - "/getFormAnalytics/:id", - formController.analytics -) +router.get("/getFormAnalytics/:id", formController.analytics); router.get( - "/attendanceCode/:id", - checkAccess("USER"), - registrationController.getAttendanceCode + "/attendanceCode/:id", + checkAccess("USER"), + registrationController.getAttendanceCode ); router.post( - "/markAttendance", - // checkAccess([ - // "SENIOR_EXECUTIVE_TECHNICAL", - // "SENIOR_EXECUTIVE_CREATIVE", - // "SENIOR_EXECUTIVE_MARKETING", - // "SENIOR_EXECUTIVE_OPERATIONS", - // "SENIOR_EXECUTIVE_PR_AND_FINANCE", - // "SENIOR_EXECUTIVE_HUMAN_RESOURCE"]), - registrationController.markAttendance + "/markAttendance", + // checkAccess([ + // "SENIOR_EXECUTIVE_TECHNICAL", + // "SENIOR_EXECUTIVE_CREATIVE", + // "SENIOR_EXECUTIVE_MARKETING", + // "SENIOR_EXECUTIVE_OPERATIONS", + // "SENIOR_EXECUTIVE_PR_AND_FINANCE", + // "SENIOR_EXECUTIVE_HUMAN_RESOURCE"]), + registrationController.markAttendance ); // router.get( @@ -59,21 +59,21 @@ router.post( router.use(checkAccess("ADMIN")); router.post( - "/addForm", - imageUpload.fields([ - { name: "eventImg", maxCount: 1 }, - { name: "media", maxCount: 1 }, - ]), - formController.addForm + "/addForm", + imageUpload.fields([ + { name: "eventImg", maxCount: 1 }, + { name: "media", maxCount: 1 }, + ]), + formController.addForm ); router.delete("/deleteForm/:id", formController.deleteForm); router.put( - "/editForm/:id", - imageUpload.fields([ - { name: "eventImg", maxCount: 1 }, - { name: "media", maxCount: 1 }, - ]), - formController.editForm + "/editForm/:id", + imageUpload.fields([ + { name: "eventImg", maxCount: 1 }, + { name: "media", maxCount: 1 }, + ]), + formController.editForm ); router.get("/download/:id", registrationController.downloadRegistration); From c8ffb3872cb84576e0f39a28849bf169fd07fb11 Mon Sep 17 00:00:00 2001 From: shing1Sks Date: Wed, 13 Aug 2025 01:01:07 +0530 Subject: [PATCH 05/13] check access admin + color support for absenties --- controllers/registration/markAttendance.js | 89 ++++++++++++++-------- package-lock.json | 8 ++ routes/api/forms/formRoutes.js | 8 +- 3 files changed, 73 insertions(+), 32 deletions(-) diff --git a/controllers/registration/markAttendance.js b/controllers/registration/markAttendance.js index 97402d9..4459d60 100644 --- a/controllers/registration/markAttendance.js +++ b/controllers/registration/markAttendance.js @@ -2,7 +2,7 @@ const { ApiError } = require("../../utils/error/ApiError"); const { PrismaClient } = require("@prisma/client"); const prisma = new PrismaClient(); const jwt = require("jsonwebtoken"); -const XLSX = require("xlsx"); +const ExcelJS = require("exceljs"); const getAttendanceCode = async (req, res, next) => { try { @@ -181,18 +181,37 @@ const markAttendance = async (req, res, next) => { const exportAttendance = async (req, res, next) => { try { - const { id: formId } = req.params; + /************* ✨ Windsurf Command ⭐ *************/ + /** + * Exports attendance records for a specific form in either JSON or XLSX format. + * + * @param {Object} req - The request object. + * @param {Object} req.params - Parameters from the request URL. + * @param {string} req.params.id - The form ID to fetch attendance for. + * @param {Object} req.query - Query parameters from the request URL. + * @param {string} [req.query.teamCode] - Optional team code to filter attendance records. + * @param {string} [req.query.format] - The format of the export ('json' or 'xlsx'). Defaults to 'json'. + * @param {Object} res - The response object. + * @param {Function} next - The next middleware function. + * + * @returns {void} - Sends the attendance data in the specified format or an error message. + * + * @throws {ApiError} - Throws an error if the form ID is missing, no records are found, + * or an invalid format is specified. + */ + + /******* 53c09f81-5f5f-4dbd-abc3-c89f49f952d6 *******/ const { + id: formId, + } = req.params; const { teamCode, format } = req.query; if (!formId) { return next(new ApiError(400, "Form ID is required.")); } - // Build query const whereClause = { formId }; if (teamCode) whereClause.teamCode = teamCode; - // Fetch attendance records const records = await prisma.attendance.findMany({ where: whereClause, }); @@ -201,49 +220,60 @@ const exportAttendance = async (req, res, next) => { return next(new ApiError(404, "No attendance records found.")); } - // Handle JSON format + // JSON output (unchanged) if (!format || format === "json") { let grouped; - if (teamCode) { - grouped = [ - { - teamCode: teamCode, - members: records, - }, - ]; + grouped = [{ teamCode, members: records }]; } else { grouped = Object.values( records.reduce((acc, record) => { if (!acc[record.teamCode]) { - acc[record.teamCode] = { - teamCode: record.teamCode, - members: [], - }; + acc[record.teamCode] = { teamCode: record.teamCode, members: [] }; } acc[record.teamCode].members.push(record); return acc; }, {}) ); } - return res.status(200).json(grouped); } - // Handle XLSX format + // XLSX output with styling if (format === "xlsx") { - // Add phoneNumber field placeholder - const withPhone = records.map((r) => ({ - ...r, - phoneNumber: "1234", - })); - - const worksheet = XLSX.utils.json_to_sheet(withPhone); - const workbook = XLSX.utils.book_new(); - XLSX.utils.book_append_sheet(workbook, worksheet, "Attendance"); - - const buffer = XLSX.write(workbook, { type: "buffer", bookType: "xlsx" }); + const workbook = new ExcelJS.Workbook(); + const sheet = workbook.addWorksheet("Attendance"); + + // Define columns + sheet.columns = [ + { header: "User ID", key: "userId", width: 25 }, + { header: "Team Name", key: "teamName", width: 20 }, + { header: "Team Code", key: "teamCode", width: 15 }, + { header: "Present", key: "isPresent", width: 10 }, + { header: "Payment Verified", key: "isPaymentVerified", width: 20 }, + { header: "Phone Number", key: "phoneNumber", width: 15 }, + ]; + + // Add rows + style + records.forEach((r) => { + const row = sheet.addRow({ + ...r, + phoneNumber: "1234", + }); + + if (!r.isPresent) { + row.eachCell((cell) => { + cell.fill = { + type: "pattern", + pattern: "solid", + fgColor: { argb: "FFFFCCCC" }, // light red + }; + }); + } + }); + // Write buffer + const buffer = await workbook.xlsx.writeBuffer(); res.setHeader( "Content-Disposition", `attachment; filename="attendance_${formId}.xlsx"` @@ -252,7 +282,6 @@ const exportAttendance = async (req, res, next) => { "Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ); - return res.send(buffer); } diff --git a/package-lock.json b/package-lock.json index 92b54f1..06b43cd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -797,6 +797,7 @@ "version": "1.3.1", "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz", "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", + "license": "Apache-2.0", "engines": { "node": ">=0.8" } @@ -1331,6 +1332,7 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz", "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", + "license": "Apache-2.0", "dependencies": { "adler-32": "~1.3.0", "crc-32": "~1.2.0" @@ -1477,6 +1479,7 @@ "version": "1.15.0", "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", + "license": "Apache-2.0", "engines": { "node": ">=0.8" } @@ -2526,6 +2529,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz", "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", + "license": "Apache-2.0", "engines": { "node": ">=0.8" } @@ -5297,6 +5301,7 @@ "version": "0.11.2", "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz", "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", + "license": "Apache-2.0", "dependencies": { "frac": "~1.1.2" }, @@ -5704,6 +5709,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz", "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", + "license": "Apache-2.0", "engines": { "node": ">=0.8" } @@ -5712,6 +5718,7 @@ "version": "0.3.0", "resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz", "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", + "license": "Apache-2.0", "engines": { "node": ">=0.8" } @@ -5760,6 +5767,7 @@ "version": "0.18.5", "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz", "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", + "license": "Apache-2.0", "dependencies": { "adler-32": "~1.3.0", "cfb": "~1.2.1", diff --git a/routes/api/forms/formRoutes.js b/routes/api/forms/formRoutes.js index 0504aa5..39ea270 100644 --- a/routes/api/forms/formRoutes.js +++ b/routes/api/forms/formRoutes.js @@ -14,10 +14,14 @@ const upload = multer(); router.get("/getAllForms", formController.getAllForms); router.post("/contact", formController.contact); -router.get("/export-attendance/:id", registrationController.exportAttendance); - router.use(verifyToken); +router.get( + "/export-attendance/:id", + checkAccess("ADMIN"), + registrationController.exportAttendance +); + router.use( "/register", checkAccess("USER"), From 4075de25f03b5dde308521cdad8aaa5730bd26ba Mon Sep 17 00:00:00 2001 From: shing1Sks Date: Wed, 13 Aug 2025 12:10:56 +0530 Subject: [PATCH 06/13] line change support + removed some comments --- controllers/registration/markAttendance.js | 63 ++++++++++------------ 1 file changed, 27 insertions(+), 36 deletions(-) diff --git a/controllers/registration/markAttendance.js b/controllers/registration/markAttendance.js index 4459d60..36239b4 100644 --- a/controllers/registration/markAttendance.js +++ b/controllers/registration/markAttendance.js @@ -181,28 +181,7 @@ const markAttendance = async (req, res, next) => { const exportAttendance = async (req, res, next) => { try { - /************* ✨ Windsurf Command ⭐ *************/ - /** - * Exports attendance records for a specific form in either JSON or XLSX format. - * - * @param {Object} req - The request object. - * @param {Object} req.params - Parameters from the request URL. - * @param {string} req.params.id - The form ID to fetch attendance for. - * @param {Object} req.query - Query parameters from the request URL. - * @param {string} [req.query.teamCode] - Optional team code to filter attendance records. - * @param {string} [req.query.format] - The format of the export ('json' or 'xlsx'). Defaults to 'json'. - * @param {Object} res - The response object. - * @param {Function} next - The next middleware function. - * - * @returns {void} - Sends the attendance data in the specified format or an error message. - * - * @throws {ApiError} - Throws an error if the form ID is missing, no records are found, - * or an invalid format is specified. - */ - - /******* 53c09f81-5f5f-4dbd-abc3-c89f49f952d6 *******/ const { - id: formId, - } = req.params; + const { id: formId } = req.params; const { teamCode, format } = req.query; if (!formId) { @@ -254,22 +233,34 @@ const exportAttendance = async (req, res, next) => { { header: "Phone Number", key: "phoneNumber", width: 15 }, ]; - // Add rows + style - records.forEach((r) => { - const row = sheet.addRow({ - ...r, - phoneNumber: "1234", + // Group by teamCode + const grouped = records.reduce((acc, r) => { + if (!acc[r.teamCode]) acc[r.teamCode] = []; + acc[r.teamCode].push(r); + return acc; + }, {}); + + // Iterate each team and add rows + Object.keys(grouped).forEach((teamCode) => { + grouped[teamCode].forEach((r) => { + const row = sheet.addRow({ + ...r, + phoneNumber: "1234", + }); + + if (!r.isPresent) { + row.eachCell((cell) => { + cell.fill = { + type: "pattern", + pattern: "solid", + fgColor: { argb: "FFFFCCCC" }, // light red + }; + }); + } }); - if (!r.isPresent) { - row.eachCell((cell) => { - cell.fill = { - type: "pattern", - pattern: "solid", - fgColor: { argb: "FFFFCCCC" }, // light red - }; - }); - } + // Add a blank row for separation + sheet.addRow({}); }); // Write buffer From 9463e832a19f6e6790206b5f365a89ea4f433cdc Mon Sep 17 00:00:00 2001 From: pakash2003pramanick Date: Wed, 13 Aug 2025 12:12:08 +0530 Subject: [PATCH 07/13] local changes --- controllers/registration/addRegistration.js | 4 ---- controllers/registration/markAttendance.js | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/controllers/registration/addRegistration.js b/controllers/registration/addRegistration.js index de02884..272d814 100644 --- a/controllers/registration/addRegistration.js +++ b/controllers/registration/addRegistration.js @@ -116,10 +116,6 @@ const addRegistration = expressAsyncHandler(async (req, res, next) => { console.log("sections Object : ", sectionsObject) if (info.participationType !== "Individual") { - - console.log("related", relatedEventForm.info.eventTitle) - console.log("eventTitle", info.eventTitle) - console.log("count", form.formAnalytics[0]?.regUserEmails.length); teamCode = await generateTeamCode(relatedEventForm.info.eventTitle, info.eventTitle, form.formAnalytics[0]?.regUserEmails.length); diff --git a/controllers/registration/markAttendance.js b/controllers/registration/markAttendance.js index a872f8e..36d0bf7 100644 --- a/controllers/registration/markAttendance.js +++ b/controllers/registration/markAttendance.js @@ -44,7 +44,7 @@ const getAttendanceCode = async (req, res, next) => { if (!formRegistrationDetails) { - return next(new ApiError(404, "Form registration not found for the user.")); + return next(new ApiError(404, "User has not registered for this event.")); } formRegistrationDetails = { ...formRegistrationDetails From 0f1f9c487e6bda64464ad63546d4c38fc575a287 Mon Sep 17 00:00:00 2001 From: pakash2003pramanick Date: Wed, 13 Aug 2025 12:37:35 +0530 Subject: [PATCH 08/13] fixed regTeamMemEmails being null --- controllers/registration/getTeamDetails.js | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/controllers/registration/getTeamDetails.js b/controllers/registration/getTeamDetails.js index fdb86e5..561ed4d 100644 --- a/controllers/registration/getTeamDetails.js +++ b/controllers/registration/getTeamDetails.js @@ -8,11 +8,6 @@ const expressAsyncHandler = require("express-async-handler"); //@access Private (requires authentication) const getTeamDetails = expressAsyncHandler(async (req, res, next) => { try { - console.log("=== getTeamDetails called ==="); - console.log("Request params:", req.params); - console.log("Request user:", req.user); - console.log("User email:", req.user?.email); - const { formId } = req.params; const { email } = req.user; @@ -37,6 +32,10 @@ const getTeamDetails = expressAsyncHandler(async (req, res, next) => { } }); + if (!teamRegistration) { + return next(new ApiError(404, "No team registration found for this user in the specified form")); + } + const teamMembers = await prisma.user.findMany({ where: { email: { @@ -44,7 +43,6 @@ const getTeamDetails = expressAsyncHandler(async (req, res, next) => { } }, select: { - id: true, name: true, email: true, img: true, @@ -54,9 +52,6 @@ const getTeamDetails = expressAsyncHandler(async (req, res, next) => { } }); - - - // Check if this is a team event const isTeamEvent = teamRegistration.form.info.participationType === "Team"; From dcf47f6c71441636cdbe1cd232c65e737762bc5b Mon Sep 17 00:00:00 2001 From: shing1Sks Date: Wed, 13 Aug 2025 22:37:05 +0530 Subject: [PATCH 09/13] conditional chaining added for safety --- controllers/registration/addRegistration.js | 695 +++++++++++--------- 1 file changed, 384 insertions(+), 311 deletions(-) diff --git a/controllers/registration/addRegistration.js b/controllers/registration/addRegistration.js index de02884..a73342c 100644 --- a/controllers/registration/addRegistration.js +++ b/controllers/registration/addRegistration.js @@ -1,5 +1,5 @@ const { PrismaClient, AccessTypes } = require("@prisma/client"); -const moment = require('moment-timezone'); +const moment = require("moment-timezone"); const prisma = new PrismaClient(); const { ApiError } = require("../../utils/error/ApiError"); const expressAsyncHandler = require("express-async-handler"); @@ -8,343 +8,416 @@ const { sendMail } = require("../../utils/email/nodeMailer"); const loadTemplate = require("../../utils/email/loadTemplate"); const uploadImage = require("../../utils/image/uploadImage"); -const validateCurrentForm = expressAsyncHandler(async (form, user, userSubmittedSections) => { +const validateCurrentForm = expressAsyncHandler( + async (form, user, userSubmittedSections) => { const { info, sections, formAnalytics } = form; const { eventMaxReg, isRegistrationClosed, isEventPast, isPublic } = info; - if (isRegistrationClosed === 'true' || isEventPast === 'true') { - throw new ApiError(400, "Sorry ! Registration has been closed for this event. If you feel this is an error, kindly contact us on fedkiit@gmail.com"); + if (isRegistrationClosed === "true" || isEventPast === "true") { + throw new ApiError( + 400, + "Sorry ! Registration has been closed for this event. If you feel this is an error, kindly contact us on fedkiit@gmail.com" + ); } if (!isPublic && req.user.access != AccessTypes.ADMIN) { - throw new ApiError(401, "Registering to a private form is not allowed. If you feel this is an error, kindly contact us on fedkiit@gmail.com"); + throw new ApiError( + 401, + "Registering to a private form is not allowed. If you feel this is an error, kindly contact us on fedkiit@gmail.com" + ); } - console.log(formAnalytics[0]?.regUserEmails) - console.log(user.regForm) - const isAlreadyRegistered = formAnalytics[0]?.regUserEmails.includes(user.email) || user.regForm.includes(form._id); + console.log(formAnalytics[0]?.regUserEmails); + console.log(user.regForm); + const isAlreadyRegistered = + formAnalytics[0]?.regUserEmails.includes(user.email) || + user.regForm.includes(form._id); if (isAlreadyRegistered) { - throw new ApiError(400, "User has already registered for this form. If you feel this is an error, kindly contact us on fedkiit@gmail.com"); + throw new ApiError( + 400, + "User has already registered for this form. If you feel this is an error, kindly contact us on fedkiit@gmail.com" + ); } - console.log("Form analytics ", formAnalytics[0]) - if ((formAnalytics[0]?.regUserEmails?.length || formAnalytics[0]?.totalRegistrationCount || 0) >= ((parseInt(eventMaxReg)) || 1)) { - console.log((formAnalytics[0]?.regUserEmails?.length || formAnalytics[0]?.totalRegistrationCount) >= (parseInt(eventMaxReg) || 1)); - console.log(eventMaxReg); - console.log(parseInt(eventMaxReg)) - throw new ApiError(400, "Maximum registration limit reached. If you feel this is an error, kindly contact us on fedkiit@gmail.com"); + console.log("Form analytics ", formAnalytics[0]); + if ( + (formAnalytics[0]?.regUserEmails?.length || + formAnalytics[0]?.totalRegistrationCount || + 0) >= (parseInt(eventMaxReg) || 1) + ) { + console.log( + (formAnalytics[0]?.regUserEmails?.length || + formAnalytics[0]?.totalRegistrationCount) >= + (parseInt(eventMaxReg) || 1) + ); + console.log(eventMaxReg); + console.log(parseInt(eventMaxReg)); + throw new ApiError( + 400, + "Maximum registration limit reached. If you feel this is an error, kindly contact us on fedkiit@gmail.com" + ); } -}); - + } +); const addRegistration = expressAsyncHandler(async (req, res, next) => { - console.log("Entering add", req.body); - console.log(req.body) - - const { _id } = req.body; - let sections = req.body.sections; - sections = JSON.parse(sections); - console.log("un-filtered sections", sections); - - // Filter out null values from sections - sections = sections.filter(section => section !== null); - console.log("filtered sections", sections); - - if (!_id || !sections || !Array.isArray(sections)) { - return next(new ApiError(400, "All fields are required")); + console.log("Entering add", req.body); + console.log(req.body); + + const { _id } = req.body; + let sections = req.body.sections; + sections = JSON.parse(sections); + console.log("un-filtered sections", sections); + + // Filter out null values from sections + sections = sections.filter((section) => section !== null); + console.log("filtered sections", sections); + + if (!_id || !sections || !Array.isArray(sections)) { + return next(new ApiError(400, "All fields are required")); + } + + try { + const form = await prisma.form.findUnique({ + where: { id: _id }, + include: { formAnalytics: true }, + }); + console.log("Form fetched from the database", form); + + if (!form) { + return next(new ApiError(404, "Form not found")); } - try { - const form = await prisma.form.findUnique({ - where: { id: _id }, - include: { formAnalytics: true }, - }); - console.log("Form fetched from the database", form) + await validateCurrentForm(form, req.user, sections); + console.log("form validation passed"); + + const { info } = form; + const { relatedEvent } = info; + let teamName = [req.user.email.toUpperCase()]; + let teamCode = req.user.email; + let relatedEventForm = null; + let createTeamSection; + let joinTeamSection; + let teamExists; + let formTrackerTeamNameList = []; + + if (relatedEvent && relatedEvent !== "null" && relatedEvent !== null) { + relatedEventForm = await prisma.form.findUnique({ + where: { id: relatedEvent }, + include: { formAnalytics: true }, + }); + + if (!relatedEventForm) { + throw new ApiError(404, "Related Event not found"); + } + + // const userAlreadyRegisteredInRelatedForm = relatedEventForm.formAnalytics[0]?.regUserEmails?.includes(user.email); + // console.log(req.user.regForm.includes(form.relatedEvent)) + // console.log("related event regUserEmails", relatedEventForm.formAnalytics[0]?.regUserEmails) + + const userAlreadyRegisteredInRelatedForm = + req.user.regForm.includes(form.relatedEvent) || + relatedEventForm.formAnalytics[0]?.regUserEmails?.includes( + req.user.email + ); + + if (!userAlreadyRegisteredInRelatedForm) { + throw new ApiError( + 400, + `User must be registered in the related event : ${relatedEventForm.info.eventTitle}` + ); + } + console.log("related event check passed"); + } - if (!form) { - return next(new ApiError(404, "Form not found")); + let regTeamMemEmails = []; + // console.log("Team Name :", teamName) + // console.log("Team Code : ", teamCode) + console.log("setions : ", sections); + + const sectionsObject = { + user_name: req.user.name, + user_id: req.user.id, + user_email: req.user.email, + date_time: moment().tz("Asia/Kolkata").format(), + amount: form?.info?.eventAmount || "0", + sections: sections, + }; + console.log("sections Object : ", sectionsObject); + + if (info.participationType !== "Individual") { + console.log("related", relatedEventForm.info.eventTitle); + console.log("eventTitle", info.eventTitle); + console.log("count", form.formAnalytics[0]?.regUserEmails.length); + teamCode = await generateTeamCode( + relatedEventForm?.info.eventTitle, + info.eventTitle, + form.formAnalytics[0]?.regUserEmails.length + ); + + createTeamSection = sections.find( + (section) => section.name === "Create Team" + ); + joinTeamSection = !createTeamSection + ? sections.find((section) => section.name === "Join Team") + : null; + + if (createTeamSection) { + const teamNameField = createTeamSection.fields.find( + (field) => field.name === "Team Name" + ); + if (teamNameField) { + teamName = [teamNameField.value.toUpperCase().trim()]; + if (form.formAnalytics[0]?.regTeamNames.includes(teamName[0])) { + return next( + new ApiError( + 400, + "! This team name already taken !\n Please choose a different one." + ) + ); + } + regTeamMemEmails.push(req.user.email); + } else { + return next( + new ApiError(400, "Team Name field is required for Create Team") + ); } - - await validateCurrentForm(form, req.user, sections); - console.log('form validation passed'); - - const { info } = form; - const { relatedEvent } = info; - let teamName = [req.user.email.toUpperCase()]; - let teamCode = req.user.email; - let relatedEventForm = null; - let createTeamSection; - let joinTeamSection; - let teamExists; - let formTrackerTeamNameList = []; - - if (relatedEvent && relatedEvent !== "null" && relatedEvent !== null) { - relatedEventForm = await prisma.form.findUnique({ - where: { id: relatedEvent }, - include: { formAnalytics: true } - }); - - if (!relatedEventForm) { - throw new ApiError(404, "Related Event not found"); - } - - // const userAlreadyRegisteredInRelatedForm = relatedEventForm.formAnalytics[0]?.regUserEmails?.includes(user.email); - // console.log(req.user.regForm.includes(form.relatedEvent)) - // console.log("related event regUserEmails", relatedEventForm.formAnalytics[0]?.regUserEmails) - - const userAlreadyRegisteredInRelatedForm = req.user.regForm.includes(form.relatedEvent) || relatedEventForm.formAnalytics[0]?.regUserEmails?.includes(req.user.email); - - if (!userAlreadyRegisteredInRelatedForm) { - throw new ApiError(400, `User must be registered in the related event : ${relatedEventForm.info.eventTitle}`); - } - console.log("related event check passed"); + } else if (joinTeamSection) { + const teamCodeField = joinTeamSection.fields.find( + (field) => field.name === "Team Code" + ); + + if (teamCodeField) { + teamExists = await prisma.formRegistration.findUnique({ + where: { + formId_teamCode: { + formId: _id, + teamCode: teamCodeField.value, + }, + }, + }); + + if (!teamExists) { + console.log("Team does not exist"); + return next(new ApiError(404, "Invalid team code")); + } + + if ( + teamExists.regTeamMemEmails.length >= + (parseInt(info.maxTeamSize) || 1) + ) { + console.log("team full"); + return next(new ApiError(400, "This team is full")); + } + + // Log the teamExists object in a readable format + console.log("team Exists", JSON.stringify(teamExists, null, 2)); + + teamName = [teamExists.teamName]; + // console.log("team name array joining creating team", teamName) + // teamName = [...new Set([...teamName, ...(form.formAnalytics?.length > 0 ? form.formAnalytics[0].regTeamNames : [])])]; + console.log("team name before ", teamName); + console.log( + "existing team names", + form.formAnalytics?.length > 0 + ? form.formAnalytics[0].regTeamNames + : [] + ); + + // console.log("Team name array after joining team") + + teamCode = teamCodeField.value; + regTeamMemEmails = [...teamExists.regTeamMemEmails, req.user.email]; } - let regTeamMemEmails = []; - // console.log("Team Name :", teamName) - // console.log("Team Code : ", teamCode) - console.log("setions : ", sections); - - const sectionsObject = { - user_name: req.user.name, - user_id: req.user.id, - user_email: req.user.email, - date_time: moment().tz("Asia/Kolkata").format(), - amount: form?.info?.eventAmount || '0', - sections: sections - }; - console.log("sections Object : ", sectionsObject) - - if (info.participationType !== "Individual") { - - console.log("related", relatedEventForm.info.eventTitle) - console.log("eventTitle", info.eventTitle) - console.log("count", form.formAnalytics[0]?.regUserEmails.length); - teamCode = await generateTeamCode(relatedEventForm.info.eventTitle, info.eventTitle, form.formAnalytics[0]?.regUserEmails.length); - - - createTeamSection = sections.find(section => section.name === "Create Team"); - joinTeamSection = !createTeamSection ? sections.find(section => section.name === "Join Team") : null; - - - if (createTeamSection) { - const teamNameField = createTeamSection.fields.find(field => field.name === "Team Name"); - if (teamNameField) { - teamName = [teamNameField.value.toUpperCase().trim()]; - if (form.formAnalytics[0]?.regTeamNames.includes(teamName[0])) { - return next(new ApiError(400, "! This team name already taken !\n Please choose a different one.")); - } - regTeamMemEmails.push(req.user.email); - } else { - return next(new ApiError(400, "Team Name field is required for Create Team")); - } - } else if (joinTeamSection) { - const teamCodeField = joinTeamSection.fields.find(field => field.name === "Team Code"); - - if (teamCodeField) { - teamExists = await prisma.formRegistration.findUnique({ - where: { - formId_teamCode: { - formId: _id, - teamCode: teamCodeField.value - } - }, - }); - - if (!teamExists) { - console.log("Team does not exist"); - return next(new ApiError(404, "Invalid team code")); - } - - if (teamExists.regTeamMemEmails.length >= (parseInt(info.maxTeamSize) || 1)) { - console.log("team full"); - return next(new ApiError(400, "This team is full")); - } - - // Log the teamExists object in a readable format - console.log("team Exists", JSON.stringify(teamExists, null, 2)); - + // sections.user_id = req.user.id; + // sections.user_email = req.user.email; + // sections.user_name = req.user.name; - teamName = [teamExists.teamName]; - // console.log("team name array joining creating team", teamName) - // teamName = [...new Set([...teamName, ...(form.formAnalytics?.length > 0 ? form.formAnalytics[0].regTeamNames : [])])]; - console.log("team name before ", teamName) - console.log("existing team names", form.formAnalytics?.length > 0 ? form.formAnalytics[0].regTeamNames : []); - - // console.log("Team name array after joining team") - - teamCode = teamCodeField.value; - regTeamMemEmails = [...teamExists.regTeamMemEmails, req.user.email]; - } - - - // sections.user_id = req.user.id; - // sections.user_email = req.user.email; - // sections.user_name = req.user.name; - - - // sectionsObject.push({ sections }); - } - - } + // sectionsObject.push({ sections }); + } + } - formTrackerTeamNameList = [...new Set([...teamName, ...(form.formAnalytics?.length > 0 ? form.formAnalytics[0].regTeamNames : [])])]; - console.log("set data ", formTrackerTeamNameList); - console.log("reg team members ", regTeamMemEmails) - - //const paymentSection = sections.find(section => section.name === "Payment Details"); - //const paymentSectionInActualForm = form.sections.find(section => section.name === "Payment Details") - // if (paymentSectionInActualForm && paymentSection) { - // console.log("payment section is present in the form"); - // if (req.files?.length > 0) { - // console.log("files", req.files); - // const imagePath = req.files[0].path; - // const result = await uploadImage(imagePath, req.files[0].fieldname || "PaymentScreenshot"); - // console.log(result); - // sectionsObject.transactionScreenShot = result.secure_url; - - // const paymentScreenshotField = paymentSection.fields.find(field => field.name === "Payment Screenshot" && field.type === "image"); - - // if (paymentScreenshotField) { - // // Update the value of the "Payment Screenshot" field with the secure URL - // paymentScreenshotField.value = result.secure_url; - // console.log("Payment Screenshot field updated successfully."); - // } else { - // console.error("Payment Screenshot field not found."); - // } - - // } - // else { - // return next(new ApiError(400, "Kindly Attach Payment Screenshot")); - // } - // } else if (paymentSectionInActualForm && !paymentSection) { - // return next(new ApiError(400, "Kindly fill the Payment section")); - // } - - console.log(sectionsObject) - - const transaction = await prisma.$transaction(async (prisma) => { - - // Step 1 : ADD REGISTRATION - const registration = await prisma.formRegistration.upsert({ - where: { - formId_teamCode: { - formId: _id, - teamCode - } - }, - update: { - value: { push: sectionsObject }, - regTeamMemEmails: { - set: regTeamMemEmails, - }, - teamSize: { - increment: 1 - } - }, - create: { - formId: _id, - userId: req.user.id, - value: [sectionsObject], - regTeamMemEmails: [req.user.email], - teamSize: 1, - teamCode, - teamName: teamName[0], - } - }); - - // const updatedUser = await updateUser({ email: req.user.email }, { regForm: _id }); - - // Step 2 : UPDATE THE USER - const updatedUser = await prisma.user.update({ - where: { - email: req.user.email - }, - data: { - regForm: { - push: _id - } - } - }); - - // Step 3 : UPDATE FORM ANALYTICS - const updateFormRegistrationList = await prisma.registrationTracker.upsert({ - where: { - formId: _id - }, - update: { - regUserEmails: { - push: req.user.email - }, - regTeamNames: { set: formTrackerTeamNameList }, - totalRegistrationCount: { - increment: 1 - } - }, - create: { - formId: _id, - regUserEmails: [req.user.email], - regTeamNames: { set: formTrackerTeamNameList }, - totalRegistrationCount: 1 - } - }); - - return { registration, updatedUser, updateFormRegistrationList }; + formTrackerTeamNameList = [ + ...new Set([ + ...teamName, + ...(form.formAnalytics?.length > 0 + ? form.formAnalytics[0].regTeamNames + : []), + ]), + ]; + console.log("set data ", formTrackerTeamNameList); + console.log("reg team members ", regTeamMemEmails); + + //const paymentSection = sections.find(section => section.name === "Payment Details"); + //const paymentSectionInActualForm = form.sections.find(section => section.name === "Payment Details") + // if (paymentSectionInActualForm && paymentSection) { + // console.log("payment section is present in the form"); + // if (req.files?.length > 0) { + // console.log("files", req.files); + // const imagePath = req.files[0].path; + // const result = await uploadImage(imagePath, req.files[0].fieldname || "PaymentScreenshot"); + // console.log(result); + // sectionsObject.transactionScreenShot = result.secure_url; + + // const paymentScreenshotField = paymentSection.fields.find(field => field.name === "Payment Screenshot" && field.type === "image"); + + // if (paymentScreenshotField) { + // // Update the value of the "Payment Screenshot" field with the secure URL + // paymentScreenshotField.value = result.secure_url; + // console.log("Payment Screenshot field updated successfully."); + // } else { + // console.error("Payment Screenshot field not found."); + // } + + // } + // else { + // return next(new ApiError(400, "Kindly Attach Payment Screenshot")); + // } + // } else if (paymentSectionInActualForm && !paymentSection) { + // return next(new ApiError(400, "Kindly fill the Payment section")); + // } + + console.log(sectionsObject); + + const transaction = await prisma.$transaction(async (prisma) => { + // Step 1 : ADD REGISTRATION + const registration = await prisma.formRegistration.upsert({ + where: { + formId_teamCode: { + formId: _id, + teamCode, + }, + }, + update: { + value: { push: sectionsObject }, + regTeamMemEmails: { + set: regTeamMemEmails, + }, + teamSize: { + increment: 1, + }, + }, + create: { + formId: _id, + userId: req.user.id, + value: [sectionsObject], + regTeamMemEmails: [req.user.email], + teamSize: 1, + teamCode, + teamName: teamName[0], + }, + }); + + // const updatedUser = await updateUser({ email: req.user.email }, { regForm: _id }); + + // Step 2 : UPDATE THE USER + const updatedUser = await prisma.user.update({ + where: { + email: req.user.email, + }, + data: { + regForm: { + push: _id, + }, + }, + }); + + // Step 3 : UPDATE FORM ANALYTICS + const updateFormRegistrationList = + await prisma.registrationTracker.upsert({ + where: { + formId: _id, + }, + update: { + regUserEmails: { + push: req.user.email, + }, + regTeamNames: { set: formTrackerTeamNameList }, + totalRegistrationCount: { + increment: 1, + }, + }, + create: { + formId: _id, + regUserEmails: [req.user.email], + regTeamNames: { set: formTrackerTeamNameList }, + totalRegistrationCount: 1, + }, }); - - console.log(transaction.updatedUser); - console.log("regTracker", transaction.updateFormRegistrationList); - - res.json({ message: form.info.successMessage || "Registration successful", teamName: transaction.registration.teamName, teamCode: transaction.registration.teamCode, user: transaction.updatedUser }); - // const placeholder = { - // name: req.user.email, - // successMessage: info.successMessage - // } - // const template = loadTemplate( - // (info.participationType === "Team") ? teamRegSuccess : indvRegSuccess, - // placeholder - // ) - - - const subject = `Successfully registered on ${info.eventTitle}`; - let template; - const placeholders = { - eventName: info.eventTitle ? info.eventTitle : "", - teamName: transaction.registration.teamName ? transaction.registration.teamName : "", - name: req.user.name ? req.user.name : "", - teamCode: transaction.registration.teamCode ? transaction.registration.teamCode : "", - successMessage: info.successMessage - } - - //take content form the team - if (info.participationType === "Team") { - - template = loadTemplate('teamEventRegistrationSuccess', placeholders); - } - else { - template = loadTemplate('individualEventRegistrationSuccess', placeholders); - - } - // const textContent = `Registration successfull in ${info.eventTitle}`; - sendMail(req.user.email, subject, template); - } - catch (error) { - console.error("Error during registration:", error); - next(new ApiError(error.stausCode || 500, error.message || "Error during registration process", error)); + return { registration, updatedUser, updateFormRegistrationList }; + }); + + console.log(transaction.updatedUser); + console.log("regTracker", transaction.updateFormRegistrationList); + + res.json({ + message: form.info.successMessage || "Registration successful", + teamName: transaction.registration.teamName, + teamCode: transaction.registration.teamCode, + user: transaction.updatedUser, + }); + // const placeholder = { + // name: req.user.email, + // successMessage: info.successMessage + // } + // const template = loadTemplate( + // (info.participationType === "Team") ? teamRegSuccess : indvRegSuccess, + // placeholder + // ) + + const subject = `Successfully registered on ${info.eventTitle}`; + let template; + const placeholders = { + eventName: info.eventTitle ? info.eventTitle : "", + teamName: transaction.registration.teamName + ? transaction.registration.teamName + : "", + name: req.user.name ? req.user.name : "", + teamCode: transaction.registration.teamCode + ? transaction.registration.teamCode + : "", + successMessage: info.successMessage, + }; + + //take content form the team + if (info.participationType === "Team") { + template = loadTemplate("teamEventRegistrationSuccess", placeholders); + } else { + template = loadTemplate( + "individualEventRegistrationSuccess", + placeholders + ); } - + // const textContent = `Registration successfull in ${info.eventTitle}`; + sendMail(req.user.email, subject, template); + } catch (error) { + console.error("Error during registration:", error); + next( + new ApiError( + error.stausCode || 500, + error.message || "Error during registration process", + error + ) + ); + } }); - -const generateTeamCode = async (relatedFormName, currentFormName, existingTeamsCount = 0) => { - const relatedEventCode = relatedFormName?.slice(0, 2).toUpperCase(); - const currentFormCode = currentFormName?.slice(0, 2).toUpperCase(); - const teamCount = existingTeamsCount.toString().padStart(3, '0'); - const randomNum = Math.floor(1000 + Math.random() * 9000).toString(); - - const teamCode = `${relatedEventCode ? relatedEventCode + "-" : ""}${currentFormCode ? currentFormCode + "-" : ""}${teamCount}-${randomNum}`; - return teamCode; +const generateTeamCode = async ( + relatedFormName, + currentFormName, + existingTeamsCount = 0 +) => { + const relatedEventCode = relatedFormName?.slice(0, 2).toUpperCase(); + const currentFormCode = currentFormName?.slice(0, 2).toUpperCase(); + const teamCount = existingTeamsCount.toString().padStart(3, "0"); + const randomNum = Math.floor(1000 + Math.random() * 9000).toString(); + + const teamCode = `${relatedEventCode ? relatedEventCode + "-" : ""}${ + currentFormCode ? currentFormCode + "-" : "" + }${teamCount}-${randomNum}`; + return teamCode; }; module.exports = { addRegistration }; From 39f1b17f76011f38d10afe7e9c8da1b4ff6c22a3 Mon Sep 17 00:00:00 2001 From: shing1Sks Date: Wed, 13 Aug 2025 23:19:32 +0530 Subject: [PATCH 10/13] attendace schema update : markedAt added + getISTDateTime util added --- controllers/registration/markAttendance.js | 3 ++- prisma/schema/attendance.prisma | 19 ++++++++++--------- utils/datetime/getIST.js | 6 ++++++ 3 files changed, 18 insertions(+), 10 deletions(-) create mode 100644 utils/datetime/getIST.js diff --git a/controllers/registration/markAttendance.js b/controllers/registration/markAttendance.js index 36239b4..c81bc5f 100644 --- a/controllers/registration/markAttendance.js +++ b/controllers/registration/markAttendance.js @@ -1,5 +1,6 @@ const { ApiError } = require("../../utils/error/ApiError"); const { PrismaClient } = require("@prisma/client"); +const { getISTDateTime } = require("../../utils/datetime/getIST"); const prisma = new PrismaClient(); const jwt = require("jsonwebtoken"); const ExcelJS = require("exceljs"); @@ -160,7 +161,7 @@ const markAttendance = async (req, res, next) => { // Mark attendance as present const updatedAttendance = await prisma.attendance.update({ where: { id: attendanceId }, - data: { isPresent: true }, + data: { isPresent: true, markedAt: getISTDateTime() }, }); res.status(200).json({ diff --git a/prisma/schema/attendance.prisma b/prisma/schema/attendance.prisma index bd1d340..7ec6aee 100644 --- a/prisma/schema/attendance.prisma +++ b/prisma/schema/attendance.prisma @@ -1,19 +1,20 @@ model attendance { - id String @id @default(auto()) @map("_id") @db.ObjectId + id String @id @default(auto()) @map("_id") @db.ObjectId - userId String @db.ObjectId + userId String @db.ObjectId - formId String @db.ObjectId - - teamName String - teamCode String + formId String @db.ObjectId + + teamName String + teamCode String isPresent Boolean @default(false) isPaymentVerified Boolean @default(false) - info Json + info Json + + markedAt DateTime? - @@map("attendance") @@unique([formId, userId, teamCode]) + @@map("attendance") } - diff --git a/utils/datetime/getIST.js b/utils/datetime/getIST.js new file mode 100644 index 0000000..328af8b --- /dev/null +++ b/utils/datetime/getIST.js @@ -0,0 +1,6 @@ +function getISTDateTime(date = new Date()) { + const offset = 5.5 * 60 * 60 * 1000; + return new Date(date.getTime() + offset); +} + +module.exports = { getISTDateTime }; From 3b3c2cbac4e746e28eafc78f0a279318e6a510f7 Mon Sep 17 00:00:00 2001 From: shing1Sks Date: Wed, 13 Aug 2025 23:26:21 +0530 Subject: [PATCH 11/13] time column added for xlsx export --- controllers/registration/markAttendance.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/controllers/registration/markAttendance.js b/controllers/registration/markAttendance.js index c81bc5f..b8d30ed 100644 --- a/controllers/registration/markAttendance.js +++ b/controllers/registration/markAttendance.js @@ -232,6 +232,7 @@ const exportAttendance = async (req, res, next) => { { header: "Present", key: "isPresent", width: 10 }, { header: "Payment Verified", key: "isPaymentVerified", width: 20 }, { header: "Phone Number", key: "phoneNumber", width: 15 }, + { header: "Marked At (IST)", key: "markedAtIST", width: 25 }, ]; // Group by teamCode @@ -244,9 +245,18 @@ const exportAttendance = async (req, res, next) => { // Iterate each team and add rows Object.keys(grouped).forEach((teamCode) => { grouped[teamCode].forEach((r) => { + const istTime = r.markedAt + ? new Date(r.markedAt).toLocaleString("en-IN", { + timeZone: "Asia/Kolkata", + dateStyle: "medium", + timeStyle: "short", + }) + : ""; + const row = sheet.addRow({ ...r, phoneNumber: "1234", + markedAtIST: istTime, }); if (!r.isPresent) { From 65b6501e83c8aa7a4d42a06baea912edca38a9d5 Mon Sep 17 00:00:00 2001 From: shing1Sks Date: Thu, 14 Aug 2025 00:03:34 +0530 Subject: [PATCH 12/13] datetime fix for xlsx export --- controllers/registration/markAttendance.js | 12 +++--------- utils/datetime/formatIST.js | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 9 deletions(-) create mode 100644 utils/datetime/formatIST.js diff --git a/controllers/registration/markAttendance.js b/controllers/registration/markAttendance.js index b8d30ed..0b0c81b 100644 --- a/controllers/registration/markAttendance.js +++ b/controllers/registration/markAttendance.js @@ -4,6 +4,7 @@ const { getISTDateTime } = require("../../utils/datetime/getIST"); const prisma = new PrismaClient(); const jwt = require("jsonwebtoken"); const ExcelJS = require("exceljs"); +const formatIST = require("../../utils/datetime/formatIST.js"); const getAttendanceCode = async (req, res, next) => { try { @@ -242,21 +243,14 @@ const exportAttendance = async (req, res, next) => { return acc; }, {}); - // Iterate each team and add rows Object.keys(grouped).forEach((teamCode) => { grouped[teamCode].forEach((r) => { - const istTime = r.markedAt - ? new Date(r.markedAt).toLocaleString("en-IN", { - timeZone: "Asia/Kolkata", - dateStyle: "medium", - timeStyle: "short", - }) - : ""; + const readableTime = r.markedAt ? formatIST(r.markedAt) : ""; const row = sheet.addRow({ ...r, phoneNumber: "1234", - markedAtIST: istTime, + markedAtIST: readableTime, }); if (!r.isPresent) { diff --git a/utils/datetime/formatIST.js b/utils/datetime/formatIST.js new file mode 100644 index 0000000..98559ce --- /dev/null +++ b/utils/datetime/formatIST.js @@ -0,0 +1,19 @@ +const formatIST = (date) => { + if (!date) return ""; + + const d = new Date(date); // will parse ISO string but may shift to UTC internally + + const iso = date.toISOString + ? date.toISOString() + : new Date(date).toISOString(); + + // Convert from the raw ISO string without letting JS adjust timezone + // Extract manually from the original IST-stored date + const [y, m, dayTime] = iso.split("-"); + const [day, time] = dayTime.split("T"); + const hhmm = time.substring(0, 5); // "HH:MM" + + return `${day}-${m}-${y} ${hhmm}`; +}; + +module.exports = formatIST; From a25fd902e33eec980054e3ec5a8866369658eb12 Mon Sep 17 00:00:00 2001 From: Hardik Gupta Date: Thu, 14 Aug 2025 20:22:26 +0530 Subject: [PATCH 13/13] fixundefinednull --- controllers/registration/addRegistration.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/controllers/registration/addRegistration.js b/controllers/registration/addRegistration.js index 07f696a..118c94a 100644 --- a/controllers/registration/addRegistration.js +++ b/controllers/registration/addRegistration.js @@ -62,6 +62,7 @@ const validateCurrentForm = expressAsyncHandler( const addRegistration = expressAsyncHandler(async (req, res, next) => { console.log("Entering add", req.body); + console.log("User Info", req.user); console.log(req.body); const { _id } = req.body; @@ -133,7 +134,7 @@ const addRegistration = expressAsyncHandler(async (req, res, next) => { let regTeamMemEmails = []; // console.log("Team Name :", teamName) // console.log("Team Code : ", teamCode) - console.log("setions : ", sections); + // console.log("setions : ", sections); const sectionsObject = { user_name: req.user.name, @@ -144,11 +145,10 @@ const addRegistration = expressAsyncHandler(async (req, res, next) => { sections: sections, }; console.log("sections Object : ", sectionsObject); - + console.log(relatedEventForm); if (info.participationType !== "Individual") { - console.log("related", relatedEventForm.info.eventTitle); - console.log("eventTitle", info.eventTitle); - console.log("count", form.formAnalytics[0]?.regUserEmails.length); + + teamCode = await generateTeamCode( relatedEventForm?.info.eventTitle, info.eventTitle, @@ -309,8 +309,9 @@ const addRegistration = expressAsyncHandler(async (req, res, next) => { }, }); - // const updatedUser = await updateUser({ email: req.user.email }, { regForm: _id }); + + // const updatedUser = await updateUser({ email: req.user.email }, { regForm: _id }); // console.log("related", relatedEventForm.info.eventTitle) // console.log("eventTitle", info.eventTitle) // console.log("count", form.formAnalytics[0]?.regUserEmails.length); @@ -343,7 +344,7 @@ const addRegistration = expressAsyncHandler(async (req, res, next) => { }, }); - return { registration, updatedUser, updateFormRegistrationList }; + return { registration,updateFormRegistrationList }; }); console.log(transaction.updatedUser); @@ -417,4 +418,4 @@ const generateTeamCode = async ( return teamCode; }; -module.exports = { addRegistration }; +module.exports = { addRegistration }; \ No newline at end of file