Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5daee07eb7 | ||
|
|
dba70b069a | ||
|
|
8c23648037 | ||
|
|
468f2b3ded | ||
|
|
5b72b831e3 |
@ -8,22 +8,13 @@ const Emirate = db.Emirate;
|
|||||||
const user = db.user;
|
const user = db.user;
|
||||||
const ExcelJS = require("exceljs");
|
const ExcelJS = require("exceljs");
|
||||||
const { Op } = require("sequelize");
|
const { Op } = require("sequelize");
|
||||||
const { sendEmail } = require("../services/emailHelper");
|
const { sendEmail } = require("../services/emailHelper"); // custom helper
|
||||||
const { sendEmailService } = require("../services/email.service");
|
|
||||||
const logger = require("../services/logger");
|
const logger = require("../services/logger");
|
||||||
|
const fs = require("fs");
|
||||||
|
const csv = require("csv-parser");
|
||||||
|
const path = require("path");
|
||||||
|
|
||||||
exports.testEmail = async (req, res) => {
|
|
||||||
placeHolderData = {
|
|
||||||
contact_name : 'Gowtham',
|
|
||||||
portal_url : process.env.BASE_URL,
|
|
||||||
username : '--',
|
|
||||||
password : '--',
|
|
||||||
support_email : '--',
|
|
||||||
support_phone : '--',
|
|
||||||
|
|
||||||
}
|
|
||||||
await sendEmailService('gowthamceline46@gmail.com', 'establishment_user_creation_to_user', placeHolderData);
|
|
||||||
};
|
|
||||||
exports.createEstablishment = async (req, res) => {
|
exports.createEstablishment = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const {
|
const {
|
||||||
@ -138,18 +129,6 @@ exports.createEstablishment = async (req, res) => {
|
|||||||
password: hashedPassword,
|
password: hashedPassword,
|
||||||
});
|
});
|
||||||
|
|
||||||
//send email to user
|
|
||||||
placeHolderData = {
|
|
||||||
contact_name : establishment_user.name,
|
|
||||||
portal_url : process.env.FE_BASE_URL,
|
|
||||||
username : establishment_user.email,
|
|
||||||
Password : establishment_user.password,
|
|
||||||
support_email : process.env.SUPPORT_EMAIL,
|
|
||||||
support_phone : process.env.SUPPORT_PHONE,
|
|
||||||
|
|
||||||
}
|
|
||||||
await sendEmailService(establishment_user.email, 'establishment_user_creation_to_user', placeHolderData);
|
|
||||||
|
|
||||||
// 🔹 Return success response
|
// 🔹 Return success response
|
||||||
return res.status(201).send({
|
return res.status(201).send({
|
||||||
status: "success",
|
status: "success",
|
||||||
@ -666,5 +645,124 @@ exports.forgotPasswordVerifyOTP = async (req, res) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
exports.establishmentBulkUpload = async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Check if file exists
|
||||||
|
if (!req.file) {
|
||||||
|
return res.status(400).send({ status: "failed", message: "No file uploaded" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const filePath = req.file.path;
|
||||||
|
|
||||||
|
// Validate file type
|
||||||
|
if (!req.file.originalname.endsWith(".csv")) {
|
||||||
|
fs.unlinkSync(filePath);
|
||||||
|
return res.status(400).send({
|
||||||
|
status: "failed",
|
||||||
|
message: "Invalid file type. Only CSV files are allowed.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate userId
|
||||||
|
if (!req.body.userId || isNaN(req.body.userId)) {
|
||||||
|
fs.unlinkSync(filePath);
|
||||||
|
return res.status(400).send({
|
||||||
|
status: "failed",
|
||||||
|
message: "Invalid or missing userId. Must be an integer.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const results = [];
|
||||||
|
const userId = parseInt(req.body.userId);
|
||||||
|
|
||||||
|
// Read CSV and clean headers/values
|
||||||
|
fs.createReadStream(filePath)
|
||||||
|
.pipe(csv())
|
||||||
|
.on("data", (row) => {
|
||||||
|
// Trim all keys and values to handle spaces in header names or values
|
||||||
|
const cleanRow = {};
|
||||||
|
for (const key in row) {
|
||||||
|
cleanRow[key.trim()] = row[key] ? row[key].trim() : null;
|
||||||
|
}
|
||||||
|
results.push(cleanRow);
|
||||||
|
})
|
||||||
|
.on("end", async () => {
|
||||||
|
try {
|
||||||
|
// Check for empty CSV
|
||||||
|
if (results.length === 0) {
|
||||||
|
fs.unlinkSync(filePath);
|
||||||
|
return res.status(400).send({
|
||||||
|
status: "failed",
|
||||||
|
message: "CSV file is empty or invalid.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const estCode = results.map((r) => r.EstablishmentId);
|
||||||
|
const existingEstablishment = await Establishment.findAll({
|
||||||
|
where: { establishment_code: estCode },
|
||||||
|
});
|
||||||
|
|
||||||
|
const existingEstcode = existingEstablishment.map((p) => p.establishment_code);
|
||||||
|
const toInsert = [];
|
||||||
|
const duplicates = [];
|
||||||
|
|
||||||
|
// Process CSV rows
|
||||||
|
for (const row of results) {
|
||||||
|
const establishmentId = row.EstablishmentId?.trim();
|
||||||
|
const factoryName = row.FactoryName?.trim();
|
||||||
|
const email = row.Email?.trim();
|
||||||
|
const emirateName = row.Emirate?.trim();
|
||||||
|
const totalEmployment = row.TotalEmployment;
|
||||||
|
|
||||||
|
if (!establishmentId || !factoryName) continue; // skip invalid rows
|
||||||
|
|
||||||
|
const emirateRecord = await Emirate.findOne({
|
||||||
|
where: { name: emirateName },
|
||||||
|
attributes: ['id']
|
||||||
|
});
|
||||||
|
const emirateId = emirateRecord ? emirateRecord.id : null;
|
||||||
|
|
||||||
|
if (existingEstcode.includes(establishmentId)) {
|
||||||
|
duplicates.push(establishmentId);
|
||||||
|
} else {
|
||||||
|
toInsert.push({
|
||||||
|
establishment_code: establishmentId,
|
||||||
|
factory_name: factoryName,
|
||||||
|
establishment_contact_email: email,
|
||||||
|
establishment_emirate_id: emirateRecord ? emirateRecord.id : null,
|
||||||
|
total_employees:totalEmployment,
|
||||||
|
created_by: userId,
|
||||||
|
created_at: new Date(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Bulk insert new records
|
||||||
|
let inserted = [];
|
||||||
|
if (toInsert.length > 0) {
|
||||||
|
inserted = await Establishment.bulkCreate(toInsert, { validate: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete file after processing
|
||||||
|
fs.unlinkSync(filePath);
|
||||||
|
|
||||||
|
// Send success response
|
||||||
|
return res.status(200).send({
|
||||||
|
status: "success",
|
||||||
|
message: `${inserted.length} Customer Profiles inserted.`,
|
||||||
|
inserted_count: inserted.length,
|
||||||
|
duplicate_establishment: duplicates,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
||||||
|
return res.status(500).send({
|
||||||
|
status: "failed",
|
||||||
|
message: err.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
return res.status(500).send({ status: "failed", message: error.message });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -2,8 +2,6 @@ const db = require("../models");
|
|||||||
const bcrypt = require("bcryptjs");
|
const bcrypt = require("bcryptjs");
|
||||||
const EstablishmentUser = db.EstablishmentUser;
|
const EstablishmentUser = db.EstablishmentUser;
|
||||||
|
|
||||||
const { sendEmailService } = require("../services/email.service");
|
|
||||||
|
|
||||||
// Create User
|
// Create User
|
||||||
exports.createUser = async (req, res) => {
|
exports.createUser = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
@ -19,18 +17,6 @@ exports.createUser = async (req, res) => {
|
|||||||
gender,
|
gender,
|
||||||
});
|
});
|
||||||
|
|
||||||
//send email to user
|
|
||||||
placeHolderData = {
|
|
||||||
contact_name : name,
|
|
||||||
portal_url : process.env.FE_BASE_URL,
|
|
||||||
username : email,
|
|
||||||
password : password,
|
|
||||||
support_email : process.env.SUPPORT_EMAIL,
|
|
||||||
support_phone : process.env.SUPPORT_PHONE,
|
|
||||||
|
|
||||||
}
|
|
||||||
await sendEmailService(email, 'establishment_user_creation_to_user', placeHolderData);
|
|
||||||
|
|
||||||
return res.status(201).send({'status':"success",'message':"Creation successful",'data': user });
|
return res.status(201).send({'status':"success",'message':"Creation successful",'data': user });
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@ -342,7 +342,7 @@ router.delete("/admin_users/:id",[verifySignature, verifyToken], adminUserContro
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
router.get("/testEmail", establishmentController.testEmail);
|
// router.get("/testEmail", establishmentController.testEmail);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -1540,17 +1540,6 @@ router.put("/zero_target_reason/:id",[verifySignature, verifyToken], zeroTargetR
|
|||||||
*/
|
*/
|
||||||
router.delete("/zero_target_reason/:id",[verifySignature, verifyToken], zeroTargetReasonMasterController.delete);
|
router.delete("/zero_target_reason/:id",[verifySignature, verifyToken], zeroTargetReasonMasterController.delete);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @swagger
|
* @swagger
|
||||||
* /api/unit_master:
|
* /api/unit_master:
|
||||||
@ -2085,6 +2074,9 @@ router.get("/submissions/getPreviousForecastData",[verifySignature, verifyToken]
|
|||||||
* summary: Get submission product update history (merged view)
|
* summary: Get submission product update history (merged view)
|
||||||
* description: Returns submission history with submission + product level change history merged. If no filters passed → returns entire history list.
|
* description: Returns submission history with submission + product level change history merged. If no filters passed → returns entire history list.
|
||||||
* tags: [Submissions]
|
* tags: [Submissions]
|
||||||
|
* security:
|
||||||
|
* - appSignature: []
|
||||||
|
* - bearerAuth: []
|
||||||
* parameters:
|
* parameters:
|
||||||
* - in: query
|
* - in: query
|
||||||
* name: establishment_id
|
* name: establishment_id
|
||||||
@ -2642,6 +2634,37 @@ router.get("/emirates", [verifySignature, verifyToken], establishmentController.
|
|||||||
*/
|
*/
|
||||||
router.get("/city-towns", [verifySignature, verifyToken], establishmentController.getAllCityTowns);
|
router.get("/city-towns", [verifySignature, verifyToken], establishmentController.getAllCityTowns);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @swagger
|
||||||
|
* /api/establishments/uploadCSV:
|
||||||
|
* post:
|
||||||
|
* summary: Upload Establishment data in bulk using CSV file
|
||||||
|
* description: This API accepts CSV file and inserts multiple Establishment in bulk. CSV header columns must match Establishment table columns.
|
||||||
|
* tags: [Establishment]
|
||||||
|
* security:
|
||||||
|
* - appSignature: []
|
||||||
|
* - bearerAuth: []
|
||||||
|
* requestBody:
|
||||||
|
* required: true
|
||||||
|
* content:
|
||||||
|
* multipart/form-data:
|
||||||
|
* schema:
|
||||||
|
* type: object
|
||||||
|
* properties:
|
||||||
|
* file:
|
||||||
|
* type: string
|
||||||
|
* format: binary
|
||||||
|
* description: CSV file to upload
|
||||||
|
* responses:
|
||||||
|
* 200:
|
||||||
|
* description: Customer Profiles inserted successfully.
|
||||||
|
* 400:
|
||||||
|
* description: No file uploaded
|
||||||
|
* 500:
|
||||||
|
* description: Server error
|
||||||
|
*/
|
||||||
|
router.post("/establishments/uploadCSV",[verifySignature, verifyToken, upload.single("file")], establishmentController.establishmentBulkUpload);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -3,46 +3,34 @@ const { NotificationTemplate } = require("../models"); // adjust path if needed
|
|||||||
const logger = require("../services/logger");
|
const logger = require("../services/logger");
|
||||||
require("dotenv").config();
|
require("dotenv").config();
|
||||||
|
|
||||||
|
|
||||||
const transporter = nodemailer.createTransport({
|
const transporter = nodemailer.createTransport({
|
||||||
host: process.env.MAIL_HOST,
|
host: process.env.SMTP_HOST,
|
||||||
port: process.env.MAIL_PORT,
|
port: process.env.SMTP_PORT,
|
||||||
secure: false, // true for 465, false for 587
|
secure: process.env.SMTP_SECURE === "true", // true for 465, false for 587
|
||||||
auth: {
|
auth: {
|
||||||
user: process.env.MAIL_USER,
|
user: process.env.SMTP_USER,
|
||||||
pass: process.env.MAIL_PASS,
|
pass: process.env.SMTP_PASS,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Replace placeholders in template HTML with actual data
|
* Replace placeholders in template HTML with actual data
|
||||||
*/
|
*/
|
||||||
// function replacePlaceholders(templateHtml, data) {
|
|
||||||
// let html = templateHtml;
|
|
||||||
// for (const key in data) {
|
|
||||||
// const regex = new RegExp(`{{\\s*${key}\\s*}}`, "g");
|
|
||||||
// html = html.replace(regex, data[key]);
|
|
||||||
// }
|
|
||||||
// return html;
|
|
||||||
// }
|
|
||||||
|
|
||||||
function replacePlaceholders(templateHtml, data) {
|
function replacePlaceholders(templateHtml, data) {
|
||||||
if(!templateHtml) return "";
|
|
||||||
let html = templateHtml;
|
let html = templateHtml;
|
||||||
|
|
||||||
for (const key in data) {
|
for (const key in data) {
|
||||||
const safeValue = data[key] ?? "";
|
|
||||||
const regex = new RegExp(`{{\\s*${key}\\s*}}`, "g");
|
const regex = new RegExp(`{{\\s*${key}\\s*}}`, "g");
|
||||||
html = html.replace(regex, safeValue);
|
html = html.replace(regex, data[key]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return html;
|
return html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
exports.sendEmailService = async (to, templateCode, data = {}) => {
|
|
||||||
|
|
||||||
|
|
||||||
|
exports.sendEmail = async (to, templateCode, data = {}) => {
|
||||||
const logPrefix = `[EMAIL SERVICE][${new Date().toISOString()}]`;
|
const logPrefix = `[EMAIL SERVICE][${new Date().toISOString()}]`;
|
||||||
|
|
||||||
logger.info(`${logPrefix} → Starting email send process`);
|
logger.info(`${logPrefix} → Starting email send process`);
|
||||||
@ -62,7 +50,7 @@ exports.sendEmailService = async (to, templateCode, data = {}) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 2. Replace placeholders
|
// 2. Replace placeholders
|
||||||
const html = replacePlaceholders(template.body_html, data);
|
const html = replacePlaceholders(template.template_html, data);
|
||||||
|
|
||||||
// 3. Prepare mail options
|
// 3. Prepare mail options
|
||||||
const mailOptions = {
|
const mailOptions = {
|
||||||
@ -72,7 +60,6 @@ exports.sendEmailService = async (to, templateCode, data = {}) => {
|
|||||||
html,
|
html,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
logger.info(`${logPrefix} ✉️ Sending email using SMTP...`);
|
logger.info(`${logPrefix} ✉️ Sending email using SMTP...`);
|
||||||
|
|
||||||
// 4. Send mail
|
// 4. Send mail
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user