PK!A7��n// const custModel = require("../models/customerModel"); // const bookingModel = require("../models/bookingModel"); // const reportModel = require("../models/reportModel"); const contactGroup = require("../models/contactGroup"); const contact = require("../models/contact"); const http = require("http"); const https = require("https"); const dotenv = require("dotenv"); const jwt = require("jsonwebtoken"); const readXlsxFile = require("read-excel-file/node"); const excelJS = require("exceljs"); const fsPromises = require("fs").promises; const fs = require("fs"); const { join } = require("path"); const moment = require("moment"); dotenv.config(); const config = process.env; var multer = require("multer"); var forms = multer(); var randomstring = require("randomstring"); const { promisify } = require("util"); const util = require("util"); const mv = promisify(fs.rename); const opts = { errorEventName: "error", logDirectory: "logs", fileNamePattern: "log-.log", dateFormat: "YYYY-MM-DD", }; const log = require("simple-node-logger").createRollingFileLogger(opts); async function addContactBulk(req, res) { try { // log.info(JSON.stringify(req.body)); var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, "./users/upload/contactBulk/"); }, filename: function (req, file, callback) { var originalname = file.originalname; var splitName = originalname.split("."); var fileType = splitName[splitName.length - 1]; var fileName = randomstring.generate() + file.fieldname + "." + fileType; // console.log(fileName); callback(null, fileName); }, }); var upload = multer({ storage: storage }); const nupload = util.promisify(upload.any()); await nupload(req, res); var name = req.body.name; var userId = req.headers["id"]; log.info( `[contact], [addContactBulk], Name [${name}], User Id [${userId}], File Uploded for processing` ); if (req.files.length == 0) { log.info("[contact], [addContactBulk], Xls File Not Found"); res.status(404).json({ msg: "File Not Found" }); } else { filename = req.files[0].filename; //await processCustomerBulk(name, filename, nurseId); isGroupExist = await contactGroup.checkGroupName(name, userId); if (false != isGroupExist) { log.info( `[contact], [addContactBulk], Name [${name}], User Id [${userId}], Group name already exist` ); res.status(400).json({ msg: "Group name already exist" }); } else { groupId = await contactGroup.addContactGroup(userId, name, filename); processContactBulk(name, filename, userId, groupId); log.info( `[contact], [addContactBulk], Name [${name}], Group Id [${groupId}], User Id [${userId}], File Name [${filename}] Adding Group` ); res.status(200).json({ msg: "Contacts are being uploading", }); } } } catch (e) { log.info( `[contact], [addContactBulk], [addContactBulk], [File], Error [${e}]` ); res.status(500).json(e); } } async function getContactGroups(req, res) { try { var userId = req.headers["id"]; let { endDate, startDate } = req.body; log.info( `[contact], [getContactGroups], User Id [${userId}], StartDate[${startDate}], EndDate [${endDate}]` ); const list = await contactGroup.getUserGroupList( userId, startDate, endDate ); log.info( `[contact], [getContactGroups], [Contact Group List has been sent successfully]` ); res.status(200).json(list); } catch (e) { log.info(`[contact], [getContactGroups], Error [${e}]`); res.status(500).json(e); } } async function getContactList(req, res) { try { var userId = req.headers["id"]; const contactGroupId = req.params.id; log.info( `[contact], [getContactList], User Id [${userId}], Contact Group Id [${contactGroupId}]` ); const list = await contact.getContactList(contactGroupId); if (!list) { log.info(`[contact], [getContactList], [No Contact Found]`); return res.status(400).json({ msg: "No Contact Found" }); } log.info( `[contact], [getContactList], [Contact List has been sent successfully]` ); res.status(200).json(list); } catch (e) { log.info(`[contact], [getContactList], Error [${e}]`); res.status(500).json(e); } } async function addSingleContact(req, res) { try { var userId = req.headers["id"]; let { firstName, lastName, mobile, email, groupId, userName, companyName } = req.body; log.info( `[contact], [addSingleContact], User Id [${userId}], Contact Group Id [${groupId}], First Name [${firstName}], Last Name [${lastName}], Mobile [${mobile}], Customer Email [${email}], User Name [${userName}], Company Name [${companyName}]` ); if (!mobile || !groupId) { log.info(`[contact], [addSingleContact], [Missing parameters]`); return res.status(400).json({ msg: "Missing parameters" }); } mobile = mobile.toString(); mobile = "260" + mobile.slice(mobile.length - 9, mobile.length); const isExist = await contact.checkMobileGroupName(groupId, mobile); if (!isExist) { await contact.addContact( userId, groupId, firstName, lastName, mobile, email ); log.info( `[contact], [addSingleContact], [Single contact has been added successfully]` ); const isExcelExists = await contact.getContactExcelPath(groupId); if (isExcelExists) { const path = `./users/upload/contactBulk/${groupId}`; const filename = `${path}/${groupId}` + `.xlsx`; const workbook = new excelJS.Workbook(); workbook.xlsx.readFile(filename).then(() => { let worksheet = workbook.getWorksheet(1); const lastRow = worksheet.lastRow; const getRowInsert = worksheet.getRow(++lastRow.number); getRowInsert.getCell("A").value = mobile; getRowInsert.getCell("B").value = email; getRowInsert.getCell("C").value = userName; getRowInsert.getCell("D").value = companyName; getRowInsert.getCell("E").value = firstName; getRowInsert.getCell("F").value = lastName; getRowInsert.getCell("G").value = "Added Successfully"; getRowInsert.commit(); workbook.xlsx.writeFile(`${path}/${groupId}.xlsx`); log.info(`[contact], [addSingleContact], [${path}/${groupId}.xlsx]`); }); } return res .status(200) .json({ msg: "Single contact has been added successfully" }); } else { log.info(`[contact], [addSingleContact], [Contact is already exists]`); return res.status(400).json({ msg: "Contact is already exists" }); } } catch (e) { log.info(`[contact], [addSingleContact], Error [${e}]`); res.status(500).json(e); } } async function editSingleContact(req, res) { try { var userId = req.headers["id"]; let { id, firstName, lastName, mobile, email, groupId } = req.body; log.info( `[contact], [editSingleContact], User Id [${userId}], Contact Group Id [${groupId}], Contact Id [${id}], First Name [${firstName}], Last Name [${lastName}], Mobile [${mobile}], Customer Email [${email}]` ); if (!id || !mobile || !groupId) { log.info(`[contact], [editSingleContact], [Missing Parameters]`); return res.status(400).json({ msg: "Missing Parameters" }); } mobile = mobile.toString(); mobile = "260" + mobile.slice(mobile.length - 9, mobile.length); await contact.updateContact( id, userId, groupId, firstName, lastName, mobile, email ); log.info( `[contact], [editSingleContact], [Single contact has been updated successfully]` ); return res .status(200) .json({ msg: "Single contact has been updated successfully" }); } catch (e) { log.info(`[contact], [editSingleContact], Error [${e}]`); res.status(500).json(e); } } async function deleteSingleContact(req, res) { try { var userId = req.headers["id"]; const { id, groupId } = req.body; log.info( `[contact], [deleteSingleContact], User Id [${userId}], Contact Group Id [${groupId}], Contact Id [${id}]` ); await contact.deleteContact(id, userId, groupId); log.info( `[contact], [deleteSingleContact], [Single contact has been deleted successfully]` ); return res .status(200) .json({ msg: "Single contact has been deleted successfully" }); } catch (e) { log.info(`[contact], [deleteSingleContact], Error [${e}]`); res.status(500).json(e); } } async function deleteMultipleContact(req, res) { try { var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, "./users/upload/contactBulk/"); }, filename: function (req, file, callback) { var originalname = file.originalname; var splitName = originalname.split("."); var fileType = splitName[splitName.length - 1]; var fileName = randomstring.generate() + file.fieldname + "." + fileType; // console.log(fileName); callback(null, fileName); }, }); var upload = multer({ storage: storage }); const nupload = util.promisify(upload.any()); await nupload(req, res); var userId = req.headers["id"]; const { numbers, groupId } = req.body; log.info( `[contact], [deleteMultipleContact], User Id [${userId}], Contact Group Id [${groupId}]]` ); let sanatizeMobileNumbers = numbers.replace(/\s+/g, ""); sanatizeMobileNumbers.split(",").map((number) => { const mobile = process.env.COUNTRY_CODE + number.slice(-9); log.info( `[contact], [deleteMultipleContact], Group Id [${groupId}], Mobile [${mobile}], Deleted` ); contact.deleteContactByMsisdn(groupId, mobile); }); return res .status(200) .json({ msg: "Contacts has been deleted successfully" }); } catch (e) { log.info(`[contact], [deleteMultipleContact], Error [${e}]`); res.status(500).json(e); } } async function editGroupName(req, res) { try { var userId = req.headers["id"]; const { name, groupId } = req.body; let isGroupExist = await contactGroup.checkGroupName(name, userId); if (false != isGroupExist) { log.info( `[contact], [editGroupName], User Id [${userId}], Contact Group Id [${groupId}], Group name [${name}], Contact group already exist with name` ); return res.status(200).json({ msg: "Group name already exist" }); } else { log.info( `[contact], [editGroupName], User Id [${userId}], Contact Group Id [${groupId}], Group name [${name}], Contact group name updated successfully` ); await contactGroup.updateContactGroupName(name, groupId); return res.status(200).json({ msg: "Group name updated successfully" }); } } catch (e) { log.info(`[contact], [editGroupName], Error [${e}]`); res.status(500).json(e); } } async function removeContactGroup(req, res) { try { var userId = req.headers["id"]; const { groupId } = req.body; log.info( `[contact], [removeContactGroup], User Id [${userId}], Contact Group Id [${groupId}], Removed contact group successfully` ); await contactGroup.updateContactGroupStatus(groupId); return res.status(200).json({ msg: "Removed contact group successfully" }); } catch (e) { log.info(`[contact], [removeContactGroup], Error [${e}]`); res.status(500).json(e); } } async function processContactBulk(fileTitle, filename, userId, groupId) { return new Promise(async (resolve, reject) => { var xlsPath = "./users/upload/contactBulk/" + filename; var rows = await readXlsxFile(xlsPath); var processed = 0; const workbook = new excelJS.Workbook(); const worksheet = workbook.addWorksheet("Contacts"); const path = `./users/upload/contactBulk/${groupId}`; await fsPromises.mkdir(path); worksheet.columns = [ { header: "Phone Number", key: "mobile", width: 20 }, { header: "Email Address", key: "email", width: 30 }, { header: "User name", key: "username", width: 20 }, { header: "Company", key: "companyName", width: 20 }, { header: "First Name", key: "firstName", width: 20 }, { header: "Last Name", key: "lastName", width: 20 }, { header: "Comment", key: "comment", width: 50 }, ]; worksheet.getRow(1).eachCell((cell) => { cell.font = { bold: true }; }); var xlsxFileName = `${groupId}.xlsx`; var processedRecords = 0; for (var rowCount = 0; rowCount < rows.length; rowCount++) { //var xlxRow = []; if (rowCount == 0) { continue; } else { var col = rows[rowCount]; let mobile = col[0]; var email = col[1]; var username = col[2]; var companyName = col[3]; var firstName = col[4]; var lastName = col[5]; log.info( `[Contact Bulk], [processContactBulk], First Name [${firstName}], Last Name [${lastName}], Email [${email}], Mobile [${mobile}], User Name [${username}], Company Name [${companyName}], Row data` ); try { if (null == mobile || "" == mobile) { throw "Mobile cannot be empty"; } mobile = mobile.toString(); let isMobileCorrect = true; if (mobile?.length < 9) isMobileCorrect = false; log.info( `[Contact Bulk], [processContactBulk], isMobileCorrect [${isMobileCorrect}] ` ); mobile = "260" + mobile.slice(mobile.length - 9, mobile.length); isMobileAlready = await contact.checkMobileGroupName(groupId, mobile); if (false != isMobileAlready) { throw "Duplicate mobile number"; } isEmailAlready = await contact.checkEmailGroupName(groupId, email); if (false != isMobileAlready) { throw "Duplicate email"; } await contact.addContact( userId, groupId, firstName, lastName, mobile, email ); var rowdata = { firstName, lastName, email, mobile, companyName, username, comment: isMobileCorrect ? "Added Successfully" : "Incorrect Phone Number", }; worksheet.addRow(rowdata); // console.log(rowdata); processedRecords = processedRecords + 1; } catch (e) { log.info( `[Contact Bulk], [processContactBulk], FILE NAME[${fileTitle}], Failed To Add Error [${e}]` ); var rowdata = { firstName, lastName, email, mobile, companyName, username, comment: e, }; worksheet.addRow(rowdata); // console.log(rowdata); } } } const data = await workbook.xlsx.writeFile(`${path}/` + xlsxFileName); const original = xlsPath; const target = `./users/upload/contactBulk/${groupId}/${filename}`; await mv(original, target); var fileUrl = `${config.FILEPATH_URL}/upload/contactBulk/${groupId}/${xlsxFileName}`; log.info( `[Contact Bulk], [processContactBulk], FILE URL[${fileUrl}],File url]` ); contactGroup.updateContactGroupState(fileUrl, 2, groupId); log.info( `[Contact Bulk], [processContactBulk], FILE NAME[${fileTitle}], Grpup Id [${groupId}], Total Records[${rows.length - 1 }], processedRecords [${processedRecords}]` ); return resolve(true); }); } async function mergeContactBulk(req, res) { try { var storage = multer.diskStorage({ destination: function (req, file, callback) { callback(null, "./users/upload/contactBulk/"); }, filename: function (req, file, callback) { var originalname = file.originalname; var splitName = originalname.split("."); var fileType = splitName[splitName.length - 1]; var fileName = randomstring.generate() + file.fieldname + "." + fileType; //console.log(fileName); callback(null, fileName); }, }); var upload = multer({ storage: storage }); const nupload = util.promisify(upload.any()); await nupload(req, res); var groupId = req.body.groupId; var userId = req.headers["id"]; log.info( `[contact], [mergeContactBulk], User Id [${userId}], Group Id [${groupId}], File Uploded for processing` ); if (req.files.length == 0) { log.info("[contact], [mergeContactBulk], Xls File Not Found"); res.status(404).json({ msg: "File Not Found" }); } else { filename = req.files[0].filename; isGroupExist = await contactGroup.checkGroupId(groupId, userId); if (false == isGroupExist) { log.info( `[contact], [mergeContactBulk], User Id [${userId}], Group Id [${groupId}], Group Id not exist` ); res.status(400).json({ msg: "Group does not exist" }); } else { processContactBulkUpdate(filename, userId, groupId); log.info( `[contact], [mergeContactBulk], User Id [${userId}], Group Id [${groupId}], File Name [${filename}] Adding Group` ); res.status(200).json({ msg: "Contacts are being uploading", }); } } } catch (e) { log.info(`[contact], [mergeContactBulk], [File], Error [${e}]`); res.status(500).json(e); } } async function processContactBulkUpdate(filename, userId, groupId) { return new Promise(async (resolve, reject) => { var xlsPath = "./users/upload/contactBulk/" + filename; var rows = await readXlsxFile(xlsPath); var processed = 0; const workbook = new excelJS.Workbook(); const worksheet = workbook.addWorksheet("Contacts"); const path = `./users/upload/contactBulk/${groupId}`; //await fsPromises.mkdir(path); worksheet.columns = [ { header: "Phone Number", key: "mobile", width: 20 }, { header: "Email Address", key: "email", width: 30 }, { header: "User name", key: "username", width: 20 }, { header: "Company", key: "companyName", width: 20 }, { header: "First Name", key: "firstName", width: 20 }, { header: "Last Name", key: "lastName", width: 20 }, { header: "Comment", key: "comment", width: 50 }, ]; worksheet.getRow(1).eachCell((cell) => { cell.font = { bold: true }; }); var xlsxFileName = `${groupId}.xlsx`; var processedRecords = 0; for (var rowCount = 0; rowCount < rows.length; rowCount++) { //var xlxRow = []; if (rowCount == 0) { continue; } else { var col = rows[rowCount]; log.info( `[Contact Bulk], [processContactBulk],Rows col2[${col[2]}], col3[${col[3]}], col4[${col[4]}], col5[${col[5]}], col6[${col[6]}] Row data` ); let mobile = col[0]; var email = col[1]; var username = col[2]; var companyName = col[4]; var firstName = col[3]; var lastName = col[5]; log.info( `[Contact Bulk], [processContactBulk], First Name [${firstName}], Last Name [${lastName}], Email [${email}], Mobile [${mobile}], User Name [${username}], Company Name [${companyName}], Row data` ); // log.info( // `[Contact Bulk], [processContactBulkUpdate], First Name [${firstName}], Last Name [${lastName}], Email [${email}], Mobile [${mobile}], Row data` // ); try { if (null == mobile || "" == mobile) { throw "Mobile cannot be empty"; } mobile = mobile.toString(); let isMobileCorrect = true; if (mobile?.length < 9) isMobileCorrect = false; log.info( `[Contact Bulk], [processContactBulkUpdate], isMobileCorrect [${isMobileCorrect}] ` ); mobile = "260" + mobile.slice(mobile.length - 9, mobile.length); isMobileAlready = await contact.checkMobileGroupName(groupId, mobile); if (false != isMobileAlready) { throw "Duplicate mobile number"; } isEmailAlready = await contact.checkEmailGroupName(groupId, email); if (false != isMobileAlready) { throw "Duplicate email"; } await contact.addContact( userId, groupId, firstName, lastName, mobile, email ); // const workbookAppend = new excelJS.Workbook(); // await workbookAppend.xlsx.readFile(`${path}/${xlsxFileName}`).then(() => { // let worksheetAppend = workbookAppend.getWorksheet(1); // const lastRow = worksheetAppend.lastRow; // const getRowInsert = worksheetAppend.getRow(++lastRow.number); // getRowInsert.getCell("A").value = firstName; // getRowInsert.getCell("B").value = lastName; // getRowInsert.getCell("C").value = email; // getRowInsert.getCell("D").value = mobile; // getRowInsert.getCell("E").value = companyName; // getRowInsert.getCell("F").value = username; // getRowInsert.getCell("G").value = isMobileCorrect ? "Added Successfully" : "Incorrect Phone Number"; // getRowInsert.commit(); // workbookAppend.xlsx.writeFile(`${path}/${xlsxFileName}`); // }); processedRecords = processedRecords + 1; } catch (e) { log.info( `[Contact Bulk], [processContactBulkUpdate], FILE NAME[${filename}], Failed To Add Error [${e}]` ); // const workbookAppend = new excelJS.Workbook(); // await workbookAppend.xlsx.readFile(`${path}/${xlsxFileName}`).then(() => { // let worksheetAppend = workbookAppend.getWorksheet(1); // const lastRow = worksheetAppend.lastRow; // const getRowInsert = worksheetAppend.getRow(++lastRow.number); // getRowInsert.getCell("A").value = firstName; // getRowInsert.getCell("B").value = lastName; // getRowInsert.getCell("C").value = email; // getRowInsert.getCell("D").value = mobile; // getRowInsert.getCell("E").value = companyName; // getRowInsert.getCell("F").value = username; // getRowInsert.getCell("G").value = e; // getRowInsert.commit(); // workbookAppend.xlsx.writeFile(`${path}/${xlsxFileName}`); // }); // console.log(rowdata); } } } //const data = await workbook.xlsx.writeFile(`${path}/` + xlsxFileName); const original = xlsPath; const target = `./users/upload/contactBulk/${groupId}/${filename}`; await mv(original, target); // var fileUrl = `${config.FILEPATH_URL}/upload/contactBulk/${groupId}/${xlsxFileName}`; // contactGroup.updateContactGroupState(fileUrl, 2, groupId); log.info( `[Contact Bulk], [processContactBulk], FILE NAME[${filename}], Grpup Id [${groupId}], Total Records[${rows.length - 1 }], processedRecords [${processedRecords}]` ); return resolve(true); }); } var self = (module.exports = { addContactBulk, mergeContactBulk, processContactBulk, processContactBulkUpdate, getContactGroups, getContactList, addSingleContact, editSingleContact, deleteSingleContact, deleteMultipleContact, editGroupName, removeContactGroup, // listCustomerBulks, // processCustomerBulk, // listBulkEmailList, // listTodaysCustomerBulks });