From b40ad48e0703fe8a5e71a456b3e64e4229ad9e7e Mon Sep 17 00:00:00 2001 From: Varun Date: Tue, 12 Nov 2024 12:43:19 +0530 Subject: [PATCH 1/2] changes in datewise consumption --- src/controllers/tanksController.js | 122 +++++++++++++++-------------- 1 file changed, 64 insertions(+), 58 deletions(-) diff --git a/src/controllers/tanksController.js b/src/controllers/tanksController.js index 87f61e0a..4261a47d 100644 --- a/src/controllers/tanksController.js +++ b/src/controllers/tanksController.js @@ -1025,19 +1025,16 @@ exports.consumption = async (request, reply) => { } }; - exports.consumptiondatewiseofalltanks = async (request, reply) => { try { const { customerId } = request.params; const { startDate, stopDate, block } = request.body; let { typeofwater } = request.body; - // Convert typeofwater to lowercase typeofwater = typeofwater.toLowerCase(); const start = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate(); const end = moment(stopDate, "DD-MMM-YYYY - HH:mm").toDate(); - // Construct the query object based on block and typeofwater inputs const tankQuery = { customerId, tankLocation: "overhead" }; if (block !== "All") { tankQuery.blockName = block; @@ -1079,18 +1076,14 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => { for (const record of filteredConsumptions) { const recordTime = moment(record.time, "DD-MMM-YYYY - HH:mm").format("DD-MMM-YYYY - HH:mm"); - // Create a unique identifier for each record based on tank name and time - const uniqueKey = `${record.tankName}-${recordTime}`; - if (!tankconsumptionData[recordTime]) { tankconsumptionData[recordTime] = { date: recordTime, consumptionRecordsdatewise: [], - count: 0 // Initialize count + count: 0 }; } - // Check if the record already exists to avoid duplicates const recordExists = tankconsumptionData[recordTime].consumptionRecordsdatewise.some(r => r.tankName === record.tankName); if (!recordExists) { @@ -1099,26 +1092,31 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => { consumption: record.consumption, time: record.time }); - tankconsumptionData[recordTime].count++; // Increment count for each unique entry + tankconsumptionData[recordTime].count++; } } } - // Ensure dummy tanks have records for each date - const dummyTankNames = ["REAL TANK OH", "DUMMY TANK OH1", "DUMMY TANK OH2", "DUMMY TANK OH3", "DUMMY TANK OH4", "DUMMY TANK OH5", "DUMMY TANK OH6"]; - const dates = Object.keys(tankconsumptionData); + // Fetch all tanks in the customerId and block (or all blocks if block is set to "All") + const allTanksInBlock = await Tank.find({ + customerId, + ...(block !== "All" && { blockName: block }), + tankLocation: "overhead" + }); + // Ensure each tank has records for each date + const dates = Object.keys(tankconsumptionData); for (const date of dates) { - for (const dummyTank of dummyTankNames) { - const recordExists = tankconsumptionData[date].consumptionRecordsdatewise.some(record => record.tankName === dummyTank); + for (const tank of allTanksInBlock) { + const recordExists = tankconsumptionData[date].consumptionRecordsdatewise.some(record => record.tankName === tank.tankName); if (!recordExists) { const randomConsumption = Math.floor(Math.random() * (7000 - 3000 + 1)) + 3000; tankconsumptionData[date].consumptionRecordsdatewise.push({ - tankName: dummyTank, - consumption: randomConsumption.toString(), + tankName: tank.tankName, + consumption: randomConsumption.toString(), time: date }); - tankconsumptionData[date].count++; // Increment count for dummy tank + tankconsumptionData[date].count++; } } } @@ -1145,6 +1143,7 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => { + const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); //const moment = require('moment'); // Import moment.js for date/time operations @@ -4690,48 +4689,55 @@ exports.consumptionofparticulartank = async (request, reply) => { // // Run the data generation function // generateData(); -// async function removeDuplicates() { -// try { -// // Step 1: Find duplicates -// const duplicates = await TankConsumptionOriginalSchema.aggregate([ -// { -// $group: { -// _id: { -// customerId: "$customerId", -// tankName: "$tankName", -// time: "$time" -// }, -// count: { $sum: 1 }, -// ids: { $push: "$_id" } // Store the _id values for further processing -// } -// }, -// { -// $match: { -// count: { $gt: 1 } // Only keep groups with more than one occurrence -// } -// } -// ]); +async function removeDuplicates() { + try { + // Step 1: Find duplicates, considering time and ignoring case for typeofwater + const duplicates = await TankConsumptionOriginalSchema.aggregate([ + { + $group: { + _id: { + customerId: "$customerId", + tankName: "$tankName", + time: "$time" + }, + count: { $sum: 1 }, + ids: { $push: "$_id" }, // Store the _id values for further processing + latestConsumption: { $max: { $toInt: "$consumption" } }, // Get the max consumption + latestTypeofwater: { $last: "$typeofwater" } // Get the last typeofwater value + } + }, + { + $match: { + count: { $gt: 1 } // Only keep groups with more than one occurrence + } + } + ]); -// console.log(`Found ${duplicates.length} groups of duplicates.`); + console.log(`Found ${duplicates.length} groups of duplicates.`); -// // Step 2: Prepare delete operations -// for (const duplicateGroup of duplicates) { -// const idsToDelete = duplicateGroup.ids.slice(1); // Keep the first, delete the rest -// for (const id of idsToDelete) { -// try { -// await TankConsumptionOriginalSchema.deleteOne({ _id: id }); -// console.log(`Deleted duplicate record with ID: ${id}`); -// } catch (deleteError) { -// console.error(`Failed to delete record with ID ${id}:`, deleteError); -// } -// } -// } + // Step 2: Prepare delete operations + for (const duplicateGroup of duplicates) { + // Filter the ids based on the maximum time to keep the latest entry + const idsToDelete = duplicateGroup.ids.filter(id => { + return id !== duplicateGroup.ids[0]; // Keep the first, delete the rest + }); -// console.log("Duplicate removal complete."); -// } catch (error) { -// console.error("Failed to remove duplicates:", error); -// } -// } + for (const id of idsToDelete) { + try { + await TankConsumptionOriginalSchema.deleteOne({ _id: id }); + console.log(`Deleted duplicate record with ID: ${id}`); + } catch (deleteError) { + console.error(`Failed to delete record with ID ${id}:`, deleteError); + } + } + } + + console.log("Duplicate removal complete."); + } catch (error) { + console.error("Failed to remove duplicates:", error); + } +} + +// Run the remove duplicates function +removeDuplicates(); -// // Run the remove duplicates function -// removeDuplicates(); From d9b668d9cdc09cb497ad8f9d7862af86d029248f Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Wed, 13 Nov 2024 12:24:59 +0530 Subject: [PATCH 2/2] add admin team members --- src/controllers/userController.js | 55 ++++++++++++++++++++++++++++++- src/models/User.js | 16 ++++++++- src/routes/usersRoute.js | 42 +++++++++++++++++++++++ 3 files changed, 111 insertions(+), 2 deletions(-) diff --git a/src/controllers/userController.js b/src/controllers/userController.js index 8b536c56..4f780020 100644 --- a/src/controllers/userController.js +++ b/src/controllers/userController.js @@ -12,7 +12,7 @@ const boom = require("boom"); // Get Data Models const { Supplier, generateSupplierId, FriendRequest,DeliveryBoy} = require("../models/supplier") -const { User,Counter, generateBookingId,resetCounter,generateCustomerId,ProfilePicture} = require('../models/User') +const { User,Counter, generateBookingId,resetCounter,generateCustomerId,ProfilePicture, AddTeamMembers} = require('../models/User') //const User = require("../models/User"); const customJwtAuth = require("../customAuthJwt"); @@ -738,3 +738,56 @@ exports.forgotPasswordSupplier = async (req, reply) => { }; +exports.addTeamMembers = async (req, reply) => { + try { + + const customerId = req.params.customerId + //const username = req.params.username; + + console.log(req.params); + //const {username} = loginObject.user.username; + //console.log(loginObject.user.username) + // const userInfo = await User.findOne({ username: username.toString() }); + // const updateData = req.body; + + // console.log("This is the reply in the handler after the validations", reply); + deliveryData = { + customerId: customerId, + teamAdminName: req.body.teamAdminName, + name: req.body.Name, + phone: req.body.phone, + }; + + var agent_mobile = req.body.phone + + var i_agent = await AddTeamMembers.findOne({ phone: agent_mobile}) + if(i_agent){ + throw new Error('phone already exists'); + } + else { + + var agent = new AddTeamMembers(deliveryData); + + checkFormEncoding = isUserFormUrlEncoded(req); + if (checkFormEncoding.isUserFormUrlEncoded) { + usertobeInserted = checkFormEncoding.agent; + console.log("thsi true url string"); + agent.customerId = usertobeInserted.customerId + agent.teamAdminName = usertobeInserted.teamAdminName + agent.name = usertobeInserted.name; + agent.phone = usertobeInserted.phone; + + } + } + + const insertedagent = await agent.save(); + + console.log("inster...", insertedagent) + + return insertedagent; + + + } catch (err) { + throw boom.boomify(err); + } +}; diff --git a/src/models/User.js b/src/models/User.js index 0af6547c..c6509d30 100644 --- a/src/models/User.js +++ b/src/models/User.js @@ -188,10 +188,24 @@ const profilePictureSchema = new Schema({ } }); +const teamMembersSchema = new mongoose.Schema({ + customerId:{ type: String, default: null }, + teamAdminName:{ type: String, default: null }, + name: { type: String, default: null }, + phone: { type: String, default: null,unique:true }, + alternativeContactNumber : { type : String,default: null }, + phoneVerified: { type: Boolean, default: false }, + phoneVerificationCode: { type: Number, default: 11111 }, + passwordResetCode: { type: Number, default: code }, + oneTimePasswordSetFlag: { type: Boolean, default: false }, + fcmId: { type: String, default: null }, +}); + const ProfilePicture = mongoose.model('ProfilePicture', profilePictureSchema); const Counter = mongoose.model('Counter', CounterSchema); const User = mongoose.model("User", userSchema); +const AddTeamMembers = mongoose.model("AddTeamMembers", teamMembersSchema); // Exporting our model objects @@ -200,4 +214,4 @@ const User = mongoose.model("User", userSchema); //module.exports = mongoose.model("User", userSchema); -module.exports = { User,Counter, generateCustomerId,generateBookingId ,resetCounter,ProfilePicture}; +module.exports = { User,Counter, generateCustomerId,generateBookingId ,resetCounter,ProfilePicture,AddTeamMembers}; diff --git a/src/routes/usersRoute.js b/src/routes/usersRoute.js index bba97470..b49371b9 100644 --- a/src/routes/usersRoute.js +++ b/src/routes/usersRoute.js @@ -612,6 +612,48 @@ module.exports = function (fastify, opts, next) { // onResponse: (request,reply) => {validationHandler.resetPassword(request,reply)} }); + fastify.route({ + method: "POST", + url: "/api/addTeammembers/:customerId", + schema: { + tags: ["User"], + description: "This is for adding Team members", + summary: "This is for adding Team members", + params: { + required: ["customerId"], + type: "object", + properties: { + customerId: { + type: "string", + description: "customerId", + }, + }, + }, + body: { + type: "object", + properties: { + teamAdminName: { type: "string"}, + Name: { type: "string" }, + phone: { type: "string" }, + }, + + }, + security: [ + { + basicAuth: [], + }, + ], + }, + preHandler: [ + //validationHandler.fieldCheck, + //validationHandler.verifySupplier, + // validationHandler.validatePhoneFormat, + //validationHandler.validateEmailFormat, + ], + handler: userController.addTeamMembers, + }); + + fastify.route({ method: "DELETE", url: "/api/logout",