ashok 10 months ago
commit 217a1aa89e

@ -6908,27 +6908,23 @@ const calculateConsumptionAndNotify = async () => {
exports.sendUserSetNotifications = async (request, reply) => { exports.sendUserSetNotifications = async (request, reply) => {
const { customerId, notificationTime } = request.body; const { customerId, notificationTime, allowNotifications } = request.body;
try { try {
const user = await User.findOneAndUpdate( const user = await User.findOneAndUpdate(
{ customerId }, { customerId },
{ notificationTime }, { notificationTime, allowNotifications },
{ new: true, upsert: true } // Create if not exists { new: true, upsert: true } // Create user if not exists
); );
await calculateWaterLevelAndNotify(); // This will only notify if notifications are allowed
// Optionally, call the notification calculation function after setting the time console.log(`User ${customerId} updated: Notification Time - ${notificationTime}, Allowed - ${allowNotifications}`);
// if (allowNotifications) {
// await calculateWaterLevelAndNotify(); // This will only notify if notifications are allowed
// }
return reply.send({ success: true, user }); return reply.send({ success: true, user });
} catch (error) { } catch (error) {
console.error("Error setting notification time:", error); console.error("Error setting notification time:", error);
return reply.status(500).send({ success: false, message: "Internal server error" }); return reply.status(500).send({ success: false, message: "Internal server error" });
} }
} };
// const calculateWaterLevelAndNotify = async () => { // const calculateWaterLevelAndNotify = async () => {
// try { // try {
@ -6984,6 +6980,7 @@ exports.sendUserSetNotifications = async (request, reply) => {
// console.error("Error in water level calculation:", err); // console.error("Error in water level calculation:", err);
// } // }
// }; // };
const calculateWaterLevelAndNotify = async () => { const calculateWaterLevelAndNotify = async () => {
try { try {
const now = moment(); const now = moment();
@ -6991,51 +6988,57 @@ const calculateWaterLevelAndNotify = async () => {
console.log(`Current time: ${currentTime}`); console.log(`Current time: ${currentTime}`);
// Get all users who have allowed notifications // Get all users who have allowed notifications and have set a notification time
const users = await User.find({ }); const users = await User.find({ allowNotifications: true, notificationTime: currentTime });
if (users.length === 0) {
console.log("No users to notify at this time.");
return;
}
// Iterate over each user
for (const user of users) { for (const user of users) {
const { customerId, notificationTime, fcmIds } = user; const { customerId, fcmIds } = user;
// Check if the user's notification time matches the current time if (!Array.isArray(fcmIds) || fcmIds.length === 0) {
if (currentTime === notificationTime) { console.log(`No valid FCM tokens for customer ID: ${customerId}`);
// Get tanks associated with the user continue;
const tanks = await Tank.find({ customerId }); }
for (const tank of tanks) { // Get tanks associated with the user
const { const tanks = await Tank.find({ customerId });
tankName,
tankLocation,
typeOfWater,
capacity,
waterlevel,
waterlevel_at_midnight,
} = tank;
// Remove commas before parsing numbers
const tankCapacity = parseFloat(capacity.replace(/,/g, '')) || 0;
const currentWaterLevel = parseFloat(waterlevel.replace(/,/g, '')) || 0;
const midnightWaterLevel = parseFloat(waterlevel_at_midnight.replace(/,/g, '')) || 0;
if (tankCapacity === 0) {
console.log(`Skipping tank ${tankName} due to zero capacity`);
continue;
}
const currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2); for (const tank of tanks) {
const waterUsedSinceMidnight = midnightWaterLevel - currentWaterLevel; const {
const waterUsedPercentageSinceMidnight = ((waterUsedSinceMidnight / tankCapacity) * 100).toFixed(2); tankName,
tankLocation,
typeOfWater,
capacity,
waterlevel,
waterlevel_at_midnight,
} = tank;
// Remove commas before parsing numbers
const tankCapacity = parseFloat(capacity.replace(/,/g, '')) || 0;
const currentWaterLevel = parseFloat(waterlevel.replace(/,/g, '')) || 0;
const midnightWaterLevel = parseFloat(waterlevel_at_midnight.replace(/,/g, '')) || 0;
if (tankCapacity === 0) {
console.log(`Skipping tank ${tankName} due to zero capacity`);
continue;
}
let notificationBody = const currentWaterLevelPercentage = ((currentWaterLevel / tankCapacity) * 100).toFixed(2);
`🛢️ Tank Name: ${tankName}\n` + const waterUsedSinceMidnight = midnightWaterLevel - currentWaterLevel;
`🏢 Location: ${tankLocation}\n` + const waterUsedPercentageSinceMidnight = ((waterUsedSinceMidnight / tankCapacity) * 100).toFixed(2);
`💧 Type of Water: ${typeOfWater}\n` +
`Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`;
await sendNotification(customerId, fcmIds, "Water Level Update", notificationBody); let notificationBody =
console.log("Notification sent for tank:", tankName); `🛢️ Tank Name: ${tankName}\n` +
} `🏢 Location: ${tankLocation}\n` +
`💧 Type of Water: ${typeOfWater}\n` +
`Current Water Level: ${currentWaterLevel} liters (${currentWaterLevelPercentage}%)\n`;
await sendNotification(customerId, fcmIds, "Water Level Update", notificationBody);
console.log("Notification sent for tank:", tankName);
} }
} }
@ -7045,6 +7048,13 @@ const calculateWaterLevelAndNotify = async () => {
} }
}; };
// Run the function every minute to check if any user needs a notification
cron.schedule('* * * * *', async () => {
console.log("Checking for user notification times...");
await calculateWaterLevelAndNotify();
}, {
timezone: "Asia/Kolkata",
});
@ -7062,12 +7072,12 @@ const calculateWaterLevelAndNotify = async () => {
// ); // );
// Schedule a function to run every minute // Schedule a function to run every minute
cron.schedule('* * * * *', async () => { // cron.schedule('* * * * *', async () => {
console.log("Checking for user notification times..."); // console.log("Checking for user notification times...");
await calculateWaterLevelAndNotify(); // await calculateWaterLevelAndNotify();
}, { // }, {
timezone: "Asia/Kolkata", // Specify the timezone // timezone: "Asia/Kolkata", // Specify the timezone
}); // });
// const updateStopTimeFormat = async () => { // const updateStopTimeFormat = async () => {
// try { // try {

@ -1328,31 +1328,21 @@ module.exports = function (fastify, opts, next) {
url: "/api/sendNotificationDaily", url: "/api/sendNotificationDaily",
schema: { schema: {
tags: ["Tank"], tags: ["Tank"],
summary: "This is for time based notification", summary: "This is for time-based notification",
body: { body: {
type: "object", type: "object",
properties: { properties: {
customerId: { customerId: { type: "string" },
type: "string", notificationTime: { type: "string" },
allowNotifications: { type: "boolean" },
},
notificationTime: {
type: "string",
},
// allowNotifications: {
// type: "boolean"
// }
}, },
required: ["customerId", "notificationTime", "allowNotifications"], // Ensures all fields are required
}, },
security: [ security: [{ basicAuth: [] }],
{
basicAuth: [],
},
],
}, },
//preHandler: fastify.auth([fastify.authenticate]),
handler: tanksController.sendUserSetNotifications, handler: tanksController.sendUserSetNotifications,
}); });
fastify.route({ fastify.route({
method: "POST", method: "POST",

Loading…
Cancel
Save