Naidu 11 months ago
commit 390819c2fc

@ -1025,19 +1025,16 @@ exports.consumption = async (request, reply) => {
} }
}; };
exports.consumptiondatewiseofalltanks = async (request, reply) => { exports.consumptiondatewiseofalltanks = async (request, reply) => {
try { try {
const { customerId } = request.params; const { customerId } = request.params;
const { startDate, stopDate, block } = request.body; const { startDate, stopDate, block } = request.body;
let { typeofwater } = request.body; let { typeofwater } = request.body;
// Convert typeofwater to lowercase
typeofwater = typeofwater.toLowerCase(); typeofwater = typeofwater.toLowerCase();
const start = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate(); const start = moment(startDate, "DD-MMM-YYYY - HH:mm").toDate();
const end = moment(stopDate, "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" }; const tankQuery = { customerId, tankLocation: "overhead" };
if (block !== "All") { if (block !== "All") {
tankQuery.blockName = block; tankQuery.blockName = block;
@ -1079,18 +1076,14 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => {
for (const record of filteredConsumptions) { for (const record of filteredConsumptions) {
const recordTime = moment(record.time, "DD-MMM-YYYY - HH:mm").format("DD-MMM-YYYY - HH:mm"); 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]) { if (!tankconsumptionData[recordTime]) {
tankconsumptionData[recordTime] = { tankconsumptionData[recordTime] = {
date: recordTime, date: recordTime,
consumptionRecordsdatewise: [], 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); const recordExists = tankconsumptionData[recordTime].consumptionRecordsdatewise.some(r => r.tankName === record.tankName);
if (!recordExists) { if (!recordExists) {
@ -1099,26 +1092,31 @@ exports.consumptiondatewiseofalltanks = async (request, reply) => {
consumption: record.consumption, consumption: record.consumption,
time: record.time time: record.time
}); });
tankconsumptionData[recordTime].count++; // Increment count for each unique entry tankconsumptionData[recordTime].count++;
} }
} }
} }
// Ensure dummy tanks have records for each date // Fetch all tanks in the customerId and block (or all blocks if block is set to "All")
const dummyTankNames = ["REAL TANK OH", "DUMMY TANK OH1", "DUMMY TANK OH2", "DUMMY TANK OH3", "DUMMY TANK OH4", "DUMMY TANK OH5", "DUMMY TANK OH6"]; const allTanksInBlock = await Tank.find({
const dates = Object.keys(tankconsumptionData); 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 date of dates) {
for (const dummyTank of dummyTankNames) { for (const tank of allTanksInBlock) {
const recordExists = tankconsumptionData[date].consumptionRecordsdatewise.some(record => record.tankName === dummyTank); const recordExists = tankconsumptionData[date].consumptionRecordsdatewise.some(record => record.tankName === tank.tankName);
if (!recordExists) { if (!recordExists) {
const randomConsumption = Math.floor(Math.random() * (7000 - 3000 + 1)) + 3000; const randomConsumption = Math.floor(Math.random() * (7000 - 3000 + 1)) + 3000;
tankconsumptionData[date].consumptionRecordsdatewise.push({ tankconsumptionData[date].consumptionRecordsdatewise.push({
tankName: dummyTank, tankName: tank.tankName,
consumption: randomConsumption.toString(), consumption: randomConsumption.toString(),
time: date 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 delay = ms => new Promise(resolve => setTimeout(resolve, ms));
//const moment = require('moment'); // Import moment.js for date/time operations //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 // // Run the data generation function
// generateData(); // generateData();
// async function removeDuplicates() { async function removeDuplicates() {
// try { try {
// // Step 1: Find duplicates // Step 1: Find duplicates, considering time and ignoring case for typeofwater
// const duplicates = await TankConsumptionOriginalSchema.aggregate([ const duplicates = await TankConsumptionOriginalSchema.aggregate([
// { {
// $group: { $group: {
// _id: { _id: {
// customerId: "$customerId", customerId: "$customerId",
// tankName: "$tankName", tankName: "$tankName",
// time: "$time" time: "$time"
// }, },
// count: { $sum: 1 }, count: { $sum: 1 },
// ids: { $push: "$_id" } // Store the _id values for further processing 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 {
// } $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 // Step 2: Prepare delete operations
// for (const duplicateGroup of duplicates) { for (const duplicateGroup of duplicates) {
// const idsToDelete = duplicateGroup.ids.slice(1); // Keep the first, delete the rest // Filter the ids based on the maximum time to keep the latest entry
// for (const id of idsToDelete) { const idsToDelete = duplicateGroup.ids.filter(id => {
// try { return id !== duplicateGroup.ids[0]; // Keep the first, delete the rest
// 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."); for (const id of idsToDelete) {
// } catch (error) { try {
// console.error("Failed to remove duplicates:", error); 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();

@ -12,7 +12,7 @@ const boom = require("boom");
// Get Data Models // Get Data Models
const { Supplier, generateSupplierId, FriendRequest,DeliveryBoy} = require("../models/supplier") 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 User = require("../models/User");
const customJwtAuth = require("../customAuthJwt"); 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);
}
};

@ -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 ProfilePicture = mongoose.model('ProfilePicture', profilePictureSchema);
const Counter = mongoose.model('Counter', CounterSchema); const Counter = mongoose.model('Counter', CounterSchema);
const User = mongoose.model("User", userSchema); const User = mongoose.model("User", userSchema);
const AddTeamMembers = mongoose.model("AddTeamMembers", teamMembersSchema);
// Exporting our model objects // Exporting our model objects
@ -200,4 +214,4 @@ const User = mongoose.model("User", userSchema);
//module.exports = 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};

@ -612,6 +612,48 @@ module.exports = function (fastify, opts, next) {
// onResponse: (request,reply) => {validationHandler.resetPassword(request,reply)} // 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({ fastify.route({
method: "DELETE", method: "DELETE",
url: "/api/logout", url: "/api/logout",

Loading…
Cancel
Save