From cbde854051fd44a81ee2e25f8bca7698a8545598 Mon Sep 17 00:00:00 2001 From: elangptra Date: Wed, 11 Dec 2024 09:15:22 +0700 Subject: [PATCH] refactor: register student with excel --- controllers/auth/auth.js | 51 ++++++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/controllers/auth/auth.js b/controllers/auth/auth.js index 93175bd..a1ce378 100644 --- a/controllers/auth/auth.js +++ b/controllers/auth/auth.js @@ -621,7 +621,7 @@ export const registerStudentForAdminAndTeacher = async (req, res) => { return response(400, null, "NISN is required for students!", res); } - const EMAIL = `${NISN}@gmail.com`; + const EMAIL = `${NISN}@student.seals.com`; const PASSWORD = "12345678"; const transaction = await models.db.transaction(); @@ -768,17 +768,35 @@ export const registerStudentCSV = async (req, res) => { } const transaction = await models.db.transaction(); + const processed = []; + const duplicates = []; try { for (const student of students) { const { NISN, NAME_USERS } = student; - const EMAIL = `${NISN}@gmail.com`; + const EMAIL = `${NISN}@student.seals.com`; const PASSWORD = "12345678"; const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(PASSWORD, salt); + const existingUser = await models.User.findOne({ where: { EMAIL } }); + + if (existingUser) { + duplicates.push(student); + continue; + } + + const existingStudent = await models.Student.findOne({ + where: { NISN }, + }); + + if (existingStudent) { + duplicates.push(student); + continue; + } + const newUser = await models.User.create( { NAME_USERS, @@ -797,27 +815,26 @@ export const registerStudentCSV = async (req, res) => { }, { transaction } ); + + processed.push(student); } await transaction.commit(); - response(200, { success: true }, "Students registered successfully!", res); + + response( + 200, + { + success: true, + message: "Students registered successfully!", + processed, + duplicates, + }, + "Operation complete with some duplicates skipped.", + res + ); } catch (error) { console.error(error); - await transaction.rollback(); - - if (error.name === "SequelizeUniqueConstraintError") { - const field = error.original.sqlMessage.match(/for key '(.+)'/)[1]; - - if (field === "student_unique_nisn") { - return response(400, null, "Duplicate NISN found in file!", res); - } - - if (field === "user_unique_email") { - return response(400, null, "Duplicate email found in file!", res); - } - } - response(500, null, "Internal Server Error", res); } };