const dayjs = require("dayjs");
const CounterModel = require("../../../models/counter.model");
const HealthInfoModel = require("../../../models/health-insurance-models/health-
info.model");
const { padStartZeroes, sleep } = require("../../../utils/fn");
const fs = require("fs");
const path = require("path");
const { addCoverAndBackPdf } = require("../../../services/calculate-api-service");
const { generatePDF } = require("../../../helpers/pdf.helper");
const environment = require("../../../utils/environment");
const HealthProposalModel =
require("../../../models/health-insurance-models/health-proposal.model");
const UserModel = require("../../../models/user.model");
const HealthQuoteModel =
require("../../../models/health-insurance-models/healthQuote.model");
const HealthLeadModel = require("../../../models/health-insurance-models/health-
lead.model");
const HealthMasterReferenceModel = require("../../../models/health-insurance-
models/healthMasterReference.model");
const { calculateHealthMatrix } =
require("../../../helpers/healthInsurance/healthMatrix");
const { sendErrorResponse, sendSuccessResponse } =
require("../../../utils/response");
const { c2smeQuotes } = require("../../../helpers/healthInsurance/healthQuoteAPI");
const mergePdfAndSendEmail = async (pdfRes) => {
try {
const { link, filename } = pdfRes;
const filePath = path.join(__dirname, "../../../public", link);
const fileContent = fs.readFileSync(filePath);
const fileBlob = new Blob([fileContent], {
type: "application/octet-stream",
});
const pdf = await addCoverAndBackPdf(
null,
"medical",
fileBlob,
{ filename: filename }
)
.then((response) => {
response.data.pipe(fs.createWriteStream(filePath));
return sleep(1500)
.then(() => filePath)
.catch((err) => { });
})
.catch((error) => {
console.error(error, "mergeerror");
});
return pdf;
} catch (error) {
console.log("Error: mergePdfAndSendEmail ==>", error);
}
};
// get quote list from admin side
exports.quotelistFromAdmin = async (req, res) => {
try {
const {
insurerType,
fullName,
countryCode,
mobileNumber,
email,
dateOfBirth,
nationality,
city,
salary,
gender,
maritalStatus,
spouseDetails,
kidsDetails,
otherFamilyDependentsDetails,
parentDetails,
domesticWorkerDetails,
preferenceDetails,
isPolicyExistInUAE,
currentInsurer,
currentInsurerExpiryDate,
regularMedication,
smoke,
hypertension,
diabetes,
height,
weight,
visaStatus,
source,
sales,
age
} = req.body;
const { _id: adminId } = req.user;
const { reqId } = req.query;
const getCustomerId = async () => {
const customer = await CounterModel.findByIdAndUpdate(
"customerId",
{
$inc: { seq: 1 },
},
{
upsert: true,
new: true,
}
);
const customerId =
"SHI" + dayjs().year() + padStartZeroes(customer?.seq, 6);
return customerId;
};
const customerId = await getCustomerId();
const userExist = await UserModel.findOne({ email: email, isParent:
true });
let userId;
if (!userExist) {
const newUser = new UserModel({
fullName: fullName,
email: email,
...(countryCode ? { countryCode: countryCode } : {}),
mobileNumber: mobileNumber,
dateOfBirth: dateOfBirth,
customerId: customerId,
nationality: nationality,
isParent: true,
age: age
});
const savedUser = await newUser.save();
userId = savedUser?._id;
} else {
const newUser = new UserModel({
fullName: fullName,
email: email,
...(countryCode ? { countryCode: countryCode } : {}),
mobileNumber: mobileNumber,
dateOfBirth: dateOfBirth,
customerId: customerId,
nationality: nationality,
isParent: false,
age: age,
isParent: false,
});
const savedUser = await newUser.save();
userId = savedUser?._id;
if (!userExist?.subUsersId?.includes(userId)) {
userExist.subUsersId.push(userId);
await userExist.save();
}
}
const healthGen = await CounterModel.findByIdAndUpdate(
"healthId",
{
$inc: { seq: 1 },
},
{
upsert: true,
new: true,
}
);
// const createProposal = await HealthProposalModel.findOneAndUpdate(
// {
// proposalId: proposalNo
// },
// {
// proposalStatus: "Un Attended",
// readStatus: false
// },
// {
// upsert: true,
// new: true
// }
// ).lean();
let SaveHealthInfo;
let proposalNo;
const existDetails = await HealthInfoModel.findOne({
insurerType: insurerType,
fullName: fullName,
mobileNumber: mobileNumber,
email: email,
nationality: nationality,
city: city,
salary: salary,
gender: gender,
maritalStatus: maritalStatus,
visaStatus: visaStatus
})
console.log(existDetails, "existDetails")
const paymentQuote = await HealthQuoteModel.findOne({ healthInfo:
existDetails?._id, paymentId: { $exists: true } });
if (existDetails && !paymentQuote) {
const updatedDetails = await HealthInfoModel.findByIdAndUpdate(
existDetails._id,
{
userId: userId,
insurerType: insurerType || null,
fullName: fullName || null,
mobileNumber: mobileNumber || null,
email: email || null,
dateOfBirth: dateOfBirth,
nationality: nationality || null,
visaType: "Self Visa",
city: city || null,
salary: salary || null,
gender: gender || null,
maritalStatus: maritalStatus || null,
spouseDetails: spouseDetails,
kidsDetails: kidsDetails,
otherFamilyDependentsDetails: otherFamilyDependentsDetails,
parentDetails: parentDetails,
domesticWorkerDetails: domesticWorkerDetails,
preferenceDetails: preferenceDetails || {
preferredHospital: "",
preferredCoPay: "",
dentalCoverage: false,
opticalCoverage: false
},
isPolicyExistInUAE: isPolicyExistInUAE,
currentInsurer: currentInsurer || null,
currentInsurerExpiryDate: currentInsurerExpiryDate,
regularMedication: regularMedication,
smoke: smoke,
hypertension: hypertension,
diabetes: diabetes,
height: height || null,
weight: weight || null,
// proposalNo: proposalNo,
visaStatus: visaStatus,
age: age
},
{
new: true
}
);
SaveHealthInfo = updatedDetails
proposalNo = updatedDetails?.proposalNo;
} else {
proposalNo =
"HI" + dayjs().year() + padStartZeroes(healthGen?.seq, 5);
console.log(proposalNo, "proposalNo")
const NewHealthInfo = new HealthInfoModel({
userId: userId,
insurerType: insurerType || null,
fullName: fullName || null,
mobileNumber: mobileNumber || null,
email: email || null,
dateOfBirth: dateOfBirth,
nationality: nationality || null,
visaType: "Self Visa",
city: city || null,
salary: salary || null,
gender: gender || null,
maritalStatus: maritalStatus || null,
spouseDetails: spouseDetails,
kidsDetails: kidsDetails,
otherFamilyDependentsDetails: otherFamilyDependentsDetails,
parentDetails: parentDetails,
domesticWorkerDetails: domesticWorkerDetails,
preferenceDetails: preferenceDetails || {
preferredHospital: "",
preferredCoPay: "",
dentalCoverage: false,
opticalCoverage: false
},
isPolicyExistInUAE: isPolicyExistInUAE,
currentInsurer: currentInsurer || null,
currentInsurerExpiryDate: currentInsurerExpiryDate,
regularMedication: regularMedication,
smoke: smoke,
hypertension: hypertension,
diabetes: diabetes,
height: height || null,
weight: weight || null,
proposalNo: proposalNo,
visaStatus: visaStatus,
age: age
// proposalId: createProposal?._id
});
SaveHealthInfo = await NewHealthInfo.save();
}
console.log(SaveHealthInfo, "SaveHealthInfo")
const hiVar = await HealthInfoModel.findById(SaveHealthInfo?._id).lean();
const variables = {
...hiVar,
todayDt: dayjs().format('DD/MM/YYYY'),
dateOfBirth: dayjs(hiVar?.dateOfBirth).format('DD/MM/YYYY'),
server: environment.server,
};
console.log(variables, "var");
const pdfRes = await generatePDF(
"../views/templates/health-lines.ejs",
variables,
proposalNo
);
await mergePdfAndSendEmail(pdfRes);
const updateHealthPdf = await HealthInfoModel.findByIdAndUpdate(
SaveHealthInfo?._id,
{
healthPdf: pdfRes
},
{
new: true
}
);
const healthInfoId = updateHealthPdf?._id;
let healthInfo = updateHealthPdf;
// let userDetails = savedUser;
await HealthQuoteModel.deleteMany({ proposalNo: healthInfo?.proposalNo,
paymentId: { $exists: false } });
await HealthLeadModel.deleteMany({ userId: userId });
healthInfo = await HealthInfoModel.findByIdAndUpdate(
healthInfoId,
{
userId: userId
},
{
new: true
}
);
const NewHealthRef = new HealthMasterReferenceModel({
healthInfoId: healthInfoId,
reqId: reqId,
proposalNo: healthInfo?.proposalNo,
userId: userId
});
const healthMasterReference = await NewHealthRef.save();
calculateHealthMatrix({
healthInfoId: healthInfoId,
healthMasterReference: healthMasterReference,
reqId: reqId,
adminId,
source
});
if (environment.c2csme.c2c === "1" && healthInfo?.city != "Ras Al Khaimah")
{
c2smeQuotes({
healthInfo: healthInfo,
healthMasterReference: healthMasterReference,
reqId: reqId,
adminId: adminId,
source: source
});
}
const createProposal = await HealthProposalModel.findOneAndUpdate(
{
proposalId: healthInfo?.proposalNo
},
{
proposalStatus: "Quoted",
readStatus: false,
userId: healthInfo?.userId,
healthInfo: healthInfo?._id,
adminId: adminId,
quotesCreatedAt: new Date(),
source: source,
refId: healthMasterReference?._id,
reqId: reqId,
sales: sales,
createdBy: adminId,
},
{
upsert: true,
new: true
}
).lean();
healthInfo = await HealthInfoModel.findByIdAndUpdate(
healthInfoId,
{
proposalId: createProposal?._id
},
{
new: true
}
);
sendSuccessResponse(res, {
data: {
message: "Request for quotes has been submitted.",
healthInfoId: healthInfoId,
reqId: reqId,
healthInfo: healthInfo,
internalRef: healthMasterReference?._id,
}
});
} catch (error) {
console.log("Error: quotelistFromAdmin ==>", error);
sendErrorResponse(res, error.message);
}
}
// exports.quotelistFromAdmin = async (req, res) => {
// try {
// const {
// insurerType, fullName, countryCode, mobileNumber, email,
// dateOfBirth, nationality, city, salary, gender, maritalStatus,
// spouseDetails, kidsDetails, otherFamilyDependentsDetails,
parentDetails,
// domesticWorkerDetails, preferenceDetails, isPolicyExistInUAE,
currentInsurer,
// currentInsurerExpiryDate, regularMedication, smoke, hypertension,
// diabetes, height, weight, visaStatus, source, sales, age
// } = req.body;
// const { _id: adminId } = req.user;
// const { reqId } = req.query;
// // Parallel fetch customerId and healthId
// const [customerCounter, healthCounter] = await Promise.all([
// CounterModel.findByIdAndUpdate("customerId", { $inc: { seq: 1 } }, {
upsert: true, new: true }),
// CounterModel.findByIdAndUpdate("healthId", { $inc: { seq: 1 } },
{ upsert: true, new: true }),
// ]);
// const customerId = "SHI" + dayjs().year() +
padStartZeroes(customerCounter?.seq, 6);
// const proposalNo = "HI" + dayjs().year() +
padStartZeroes(healthCounter?.seq, 5);
// // Check if parent user exists
// let userExist = await UserModel.findOne({ email: email, isParent:
true });
// let userId;
// if (!userExist) {
// const savedUser = await new UserModel({
// fullName, email, countryCode, mobileNumber,
// dateOfBirth, customerId, nationality, isParent: true, age
// }).save();
// userId = savedUser._id;
// } else {
// const childUser = await new UserModel({
// fullName, email, countryCode, mobileNumber,
// dateOfBirth, customerId, nationality, isParent: false, age
// }).save();
// userId = childUser._id;
// if (!userExist.subUsersId?.includes(userId)) {
// userExist.subUsersId.push(userId);
// await userExist.save();
// }
// }
// // Check for existing health info without payment
// let SaveHealthInfo = await HealthInfoModel.findOne({
// insurerType, fullName, mobileNumber, email, nationality,
// city, salary, gender, maritalStatus, visaStatus
// });
// const hasPaid = SaveHealthInfo
// ? await HealthQuoteModel.findOne({ healthInfo: SaveHealthInfo._id,
paymentId: { $exists: true } })
// : null;
// if (SaveHealthInfo && !hasPaid) {
// SaveHealthInfo = await
HealthInfoModel.findByIdAndUpdate(SaveHealthInfo._id, {
// userId: userId,
// dateOfBirth: dateOfBirth,
// spouseDetails: spouseDetails,
// kidsDetails: kidsDetails,
// otherFamilyDependentsDetails: otherFamilyDependentsDetails,
// parentDetails: parentDetails,
// domesticWorkerDetails: domesticWorkerDetails,
// preferenceDetails: preferenceDetails || {
// preferredHospital: "",
// preferredCoPay: "",
// dentalCoverage: false,
// opticalCoverage: false
// },
// isPolicyExistInUAE: isPolicyExistInUAE,
// currentInsurer: currentInsurer || null,
// currentInsurerExpiryDate: currentInsurerExpiryDate,
// regularMedication: regularMedication,
// smoke: smoke,
// hypertension: hypertension,
// diabetes: diabetes,
// height: height || null,
// weight: weight || null,
// age: age
// }, { new: true });
// } else {
// SaveHealthInfo = await new HealthInfoModel({
// userId: userId,
// insurerType: insurerType || null,
// fullName: fullName || null,
// mobileNumber: mobileNumber || null,
// email: email || null,
// dateOfBirth: dateOfBirth,
// nationality: nationality || null,
// visaType: "Self Visa",
// city: city || null,
// salary: salary || null,
// gender: gender || null,
// maritalStatus: maritalStatus || null,
// spouseDetails: spouseDetails,
// kidsDetails: kidsDetails,
// otherFamilyDependentsDetails: otherFamilyDependentsDetails,
// parentDetails: parentDetails,
// preferenceDetails: preferenceDetails || {
// preferredHospital: "",
// preferredCoPay: "",
// dentalCoverage: false,
// opticalCoverage: false
// },
// isPolicyExistInUAE: isPolicyExistInUAE,
// currentInsurer: currentInsurer || null,
// currentInsurerExpiryDate: currentInsurerExpiryDate,
// regularMedication: regularMedication,
// smoke: smoke,
// hypertension: hypertension,
// diabetes: diabetes,
// height: height || null,
// weight: weight || null,
// proposalNo: proposalNo,
// visaStatus: visaStatus,
// age: age
// }).save();
// }
// const variables = {
// ...SaveHealthInfo.toObject(),
// todayDt: dayjs().format("DD/MM/YYYY"),
// dateOfBirth: dayjs(SaveHealthInfo.dateOfBirth).format("DD/MM/YYYY"),
// server: environment.server,
// };
// // Run PDF and email async (don't block)
// generatePDF("../views/templates/health-lines.ejs", variables,
proposalNo)
// .then(async (pdfRes) => {
// await mergePdfAndSendEmail(pdfRes);
// await HealthInfoModel.findByIdAndUpdate(SaveHealthInfo._id,
{ healthPdf: pdfRes });
// }).catch(console.error);
// await Promise.all([
// HealthQuoteModel.deleteMany({ proposalNo, paymentId: { $exists:
false } }),
// HealthLeadModel.deleteMany({ userId }),
// ]);
// const healthMasterReference = await new HealthMasterReferenceModel({
// healthInfoId: SaveHealthInfo._id,
// reqId,
// proposalNo,
// userId
// }).save();
// calculateHealthMatrix({
// healthInfoId: SaveHealthInfo._id,
// healthMasterReference,
// reqId,
// adminId,
// source
// });
// if (environment.c2csme.c2c === "1" && SaveHealthInfo.city !== "Ras Al
Khaimah") {
// c2smeQuotes({
// healthInfo: SaveHealthInfo,
// healthMasterReference,
// reqId,
// adminId,
// source
// });
// }
// const createProposal = await HealthProposalModel.findOneAndUpdate(
// { proposalId: SaveHealthInfo?.proposalNo },
// {
// proposalStatus: "Quoted", readStatus: false,
// userId: SaveHealthInfo.userId, healthInfo: SaveHealthInfo._id,
// adminId, quotesCreatedAt: new Date(), source,
// refId: healthMasterReference._id, reqId, sales, createdBy:
adminId
// },
// { upsert: true, new: true }
// ).lean();
// console.log(createProposal, "createProposal");
// await HealthInfoModel.findByIdAndUpdate(SaveHealthInfo._id, {
// proposalId: createProposal._id
// });
// sendSuccessResponse(res, {
// data: {
// message: "Request for quotes has been submitted.",
// healthInfoId: SaveHealthInfo._id,
// reqId,
// healthInfo: SaveHealthInfo,
// internalRef: healthMasterReference._id
// }
// });
// } catch (error) {
// console.error("Error: quotelistFromAdmin ==>", error);
// sendErrorResponse(res, error.message);
// }
// };
// exports.quotelistFromAdmin = async (req, res) => {
// try {
// const {
// insurerType, fullName, countryCode, mobileNumber, email,
dateOfBirth,
// nationality, city, salary, gender, maritalStatus, spouseDetails,
kidsDetails,
// otherFamilyDependentsDetails, parentDetails, domesticWorkerDetails,
// preferenceDetails, isPolicyExistInUAE, currentInsurer,
// currentInsurerExpiryDate, regularMedication, smoke, hypertension,
// diabetes, height, weight, visaStatus, source, sales, age
// } = req.body;
// const { _id: adminId } = req.user;
// const { reqId } = req.query;
// const customer = await CounterModel.findByIdAndUpdate(
// "customerId",
// { $inc: { seq: 1 } },
// { upsert: true, new: true }
// );
// const customerId = "SHI" + dayjs().year() +
padStartZeroes(customer?.seq, 6);
// let userExist = await UserModel.findOne({ email, isParent:
true }).lean();
// let userId;
// if (!userExist) {
// const newUser = new UserModel({
// fullName, email, countryCode, mobileNumber, dateOfBirth,
// customerId, nationality, isParent: true, age
// });
// userId = (await newUser.save())._id;
// } else {
// const newUser = new UserModel({
// fullName, email, countryCode, mobileNumber, dateOfBirth,
// customerId, nationality, isParent: false, age
// });
// const savedUser = await newUser.save();
// userId = savedUser._id;
// if (!userExist?.subUsersId?.includes(userId)) {
// await UserModel.findByIdAndUpdate(userExist._id, {
// $push: { subUsersId: userId }
// });
// }
// }
// const healthGen = await CounterModel.findByIdAndUpdate(
// "healthId",
// { $inc: { seq: 1 } },
// { upsert: true, new: true }
// );
// const existDetails = await HealthInfoModel.findOne({
// insurerType, fullName, mobileNumber, email, nationality, city,
// salary, gender, maritalStatus, visaStatus
// }).lean();
// const paymentQuote = existDetails
// ? await HealthQuoteModel.findOne({
// healthInfo: existDetails._id,
// paymentId: { $exists: true }
// }).lean()
// : null;
// let SaveHealthInfo, proposalNo;
// if (existDetails && !paymentQuote) {
// SaveHealthInfo = await HealthInfoModel.findByIdAndUpdate(
// existDetails._id,
// {
// userId: userId,
// insurerType: insurerType || null,
// fullName: fullName || null,
// mobileNumber: mobileNumber || null,
// email: email || null,
// dateOfBirth: dateOfBirth,
// nationality: nationality || null,
// visaType: "Self Visa",
// city: city || null,
// salary: salary || null,
// gender: gender || null,
// maritalStatus: maritalStatus || null,
// spouseDetails: spouseDetails,
// kidsDetails: kidsDetails,
// otherFamilyDependentsDetails: otherFamilyDependentsDetails,
// parentDetails: parentDetails,
// domesticWorkerDetails: domesticWorkerDetails,
// preferenceDetails: preferenceDetails || {
// preferredHospital: "",
// preferredCoPay: "",
// dentalCoverage: false,
// opticalCoverage: false
// },
// isPolicyExistInUAE: isPolicyExistInUAE,
// currentInsurer: currentInsurer || null,
// currentInsurerExpiryDate: currentInsurerExpiryDate,
// regularMedication: regularMedication,
// smoke: smoke,
// hypertension: hypertension,
// diabetes: diabetes,
// height: height || null,
// weight: weight || null,
// proposalNo: proposalNo,
// visaStatus: visaStatus,
// age: age
// },
// { new: true }
// );
// proposalNo = SaveHealthInfo.proposalNo;
// } else {
// proposalNo = "HI" + dayjs().year() + padStartZeroes(healthGen?.seq,
5);
// const NewHealthInfo = new HealthInfoModel({
// userId: userId,
// insurerType: insurerType || null,
// fullName: fullName || null,
// mobileNumber: mobileNumber || null,
// email: email || null,
// dateOfBirth: dateOfBirth,
// nationality: nationality || null,
// visaType: "Self Visa",
// city: city || null,
// salary: salary || null,
// gender: gender || null,
// maritalStatus: maritalStatus || null,
// spouseDetails: spouseDetails,
// kidsDetails: kidsDetails,
// otherFamilyDependentsDetails: otherFamilyDependentsDetails,
// parentDetails: parentDetails,
// domesticWorkerDetails: domesticWorkerDetails,
// preferenceDetails: preferenceDetails || {
// preferredHospital: "",
// preferredCoPay: "",
// dentalCoverage: false,
// opticalCoverage: false
// },
// isPolicyExistInUAE: isPolicyExistInUAE,
// currentInsurer: currentInsurer || null,
// currentInsurerExpiryDate: currentInsurerExpiryDate,
// regularMedication: regularMedication,
// smoke: smoke,
// hypertension: hypertension,
// diabetes: diabetes,
// height: height || null,
// weight: weight || null,
// proposalNo: proposalNo,
// visaStatus: visaStatus,
// age: age
// });
// SaveHealthInfo = await NewHealthInfo.save();
// }
// const hiVar = await HealthInfoModel.findById(SaveHealthInfo._id).lean();
// const variables = {
// ...hiVar,
// todayDt: dayjs().format('DD/MM/YYYY'),
// dateOfBirth: dayjs(hiVar?.dateOfBirth).format('DD/MM/YYYY'),
// server: environment.server
// };
// const pdfRes = await generatePDF(
// "../views/templates/health-lines.ejs",
// variables,
// proposalNo
// );
// await mergePdfAndSendEmail(pdfRes);
// const updateHealthPdf = await HealthInfoModel.findByIdAndUpdate(
// SaveHealthInfo._id,
// { healthPdf: pdfRes },
// { new: true }
// );
// const healthInfoId = updateHealthPdf._id;
// await Promise.all([
// HealthQuoteModel.deleteMany({ proposalNo:
updateHealthPdf.proposalNo, paymentId: { $exists: false } }),
// HealthLeadModel.deleteMany({ userId }),
// HealthInfoModel.findByIdAndUpdate(healthInfoId, { userId })
// ]);
// const NewHealthRef = new HealthMasterReferenceModel({
// healthInfoId, reqId, proposalNo: updateHealthPdf.proposalNo, userId
// });
// const healthMasterReference = await NewHealthRef.save();
// calculateHealthMatrix({
// healthInfoId: healthInfoId,
// healthMasterReference: healthMasterReference,
// reqId: reqId,
// adminId,
// source
// });
// if (environment.c2csme.c2c === "1" && updateHealthPdf?.city != "Ras Al
Khaimah") {
// c2smeQuotes({
// healthInfoId: healthInfoId,
// healthMasterReference: healthMasterReference,
// reqId: reqId,
// adminId,
// source
// });
// }
// const createProposal = await HealthProposalModel.findOneAndUpdate(
// { proposalId: updateHealthPdf.proposalNo },
// {
// proposalStatus: "Quoted",
// readStatus: false,
// userId,
// healthInfo: updateHealthPdf._id,
// adminId,
// quotesCreatedAt: new Date(),
// source,
// refId: healthMasterReference._id,
// reqId,
// sales,
// createdBy: adminId
// },
// { upsert: true, new: true }
// ).lean();
// await HealthInfoModel.findByIdAndUpdate(healthInfoId, {
// proposalId: createProposal._id
// });
// sendSuccessResponse(res, {
// data: {
// message: "Request for quotes has been submitted.",
// healthInfoId,
// reqId,
// healthInfo: updateHealthPdf,
// internalRef: healthMasterReference._id
// }
// });
// } catch (error) {
// console.log("Error: quotelistFromAdmin ==>", error);
// sendErrorResponse(res, error.message);
// }
// };