const db = require('../config/database');
const nodemailer = require('nodemailer');
const sender_mail = process.env.mail;
const sender_app_password = process.env.apppassword;
const back_url = process.env.BACK_URL;
const jwt = require("jsonwebtoken");
const bcrypt = require('bcrypt');
const transporter = nodemailer.createTransport({
host: "smtp.zoho.com",
port: 465,
secure: true,
auth: {
user: "no-reply@spurrin.com", // Your Zoho email address
pass: "8TFvKswgH69Y", // Your Zoho App Password (not your account password)
},
// tls: {
// rejectUnauthorized: false, // Allow self-signed certificates
// minVersion: "TLSv1.2"
// }
});
// Create a new record
exports.createExcelEntry = async (req, res) => {
try {
const requestorRole = req.user.role;
const uploaded_by = req.user.id;
const { hospital_id, hospital_code } = req.user;
if (!['Superadmin', 'Admin', 8, 7].includes(requestorRole)) {
return res.status(403).json({ error: 'Access denied. Only Superadmin and Admin can do this action.' });
}
const hospitalUsersQuery = `
SELECT *
FROM hospital_users
WHERE hospital_id = ?
`;
const hospitalUserResult = await db.query(hospitalUsersQuery, [hospital_id]);
if (!hospitalUserResult || hospitalUserResult.length === 0) {
return res.status(404).json({ error: 'Hospital not found for the given hospital_id' });
}
// Ensure the request body is an array
if (!Array.isArray(req.body)) {
return res.status(400).json({ error: "Invalid data format. Expected an array." });
}
const hospitalQuery = `
SELECT *
FROM hospitals
WHERE hospital_code = ?
`;
const hospitalResult = await db.query(hospitalQuery, [hospital_code]);
sendEmails(req.body, hospitalResult, back_url);
const query = `
INSERT INTO hospital_users
(hospital_code, hospital_id, email, hash_password, role_id, is_default_admin, requires_onboarding, password_reset_required, profile_photo_url, phone_number, bio, status, name, department, location, mobile_number)
VALUES ?
`;
// insert into hospital_users
const values_hospital_users = await Promise.all(req.body.map(async (item) => {
const hashedPassword = await bcrypt.hash(item.password, 10); // Hash the password
return [
hospital_code,
hospital_id,
item.email,
hashedPassword, // Use the hashed password here
item.role,
0,
hospitalUserResult[0].requires_onboarding,
hospitalUserResult[0].password_reset_required,
hospitalUserResult[0].profile_photo_url,
item.phonenumber,
hospitalUserResult[0].bio,
hospitalUserResult[0].status,
item.name,
item.department,
item.location,
item.phonenumber
];
}));
const result = await db.query(query, [values_hospital_users]);
console.log("result---", result)
// Generate and update refresh tokens for each inserted user
// Get the first inserted ID and calculate subsequent IDs
const firstInsertedId = result.insertId;
const numberOfInsertedRows = result.affectedRows;
await Promise.all(
req.body.map(async (item, index) => {
const insertedUserId = firstInsertedId + index; // Calculate user ID
const refreshTokenPayload = {
id: insertedUserId,
email: item.email,
role: item.role,
};
const refreshToken = jwt.sign(
refreshTokenPayload,
process.env.JWT_REFRESH_TOKEN_SECRET
);
const updateRefreshTokenQuery = `UPDATE hospital_users SET refresh_token = ? WHERE id = ?`;
await db.query(updateRefreshTokenQuery, [refreshToken, insertedUserId]);
})
);
// Constructing bulk insert query keeping a copy of uploaded users
res.status(201).json({ message: "Records added successfully!" });
} catch (error) {
console.error("Error inserting data:", error.message);
res.status(500).json({ error: error.message });
}
};
// Retrieve all records
async function sendEmails(users, hospitalResult, back_url) {
for (const user of users) {
const mailOptions = {
from: "no-reply@spurrin.com", // Sender's email
to: user.email, // Unique recipient email
subject: 'Spurrinai Login Credentials', // Email subject
html: `
Welcome to Spurrinai
|
|
Greetings, ${user.name},
Congratulations! Your hospital, ${hospitalResult[0].name_hospital}, has been successfully onboarded to Spurrinai. We are excited to have you on board and look forward to supporting your hospital's needs.
Please find your hospital's login credentials below:
| Hospital Name |
${hospitalResult[0].name_hospital} |
| Domain |
${hospitalResult[0].subdomain} |
| Username |
${user.email} |
| Temporary Password |
${user.password} |
For security reasons, we recommend changing your password immediately after logging in.
|
|
`
};
try {
await transporter.sendMail(mailOptions);
} catch (error) {
console.error(`Error sending email to ${user.email_id}:`, error);
}
}
}