ashok 4 months ago
commit 1b32fed41f

@ -6219,225 +6219,14 @@ exports.getRemoveConnectedMastersWithSlaves = async (req, reply) => {
// };
// exports.getDisconnectedCustomerDetails = async (req, reply) => {
// try {
// const { supportId } = req.params;
// if (!supportId) {
// return reply.code(400).send({ error: "supportId is required" });
// }
// const supportRecord = await Support.findOne({ supportId }).lean();
// if (!supportRecord) {
// return reply.code(404).send({ message: "No support record found for this supportId" });
// }
// // Step 1: Filter unresolved and not moved issues
// const unresolvedIssues = (supportRecord.issues || []).filter(
// issue => issue.resolved === false && issue.movedToCategory !== true
// );
// // Step 2: Build set of hardwareIds already in categorizedIssues (moved)
// const existingCategorizedHardwareIds = new Set();
// (supportRecord.categorizedIssues || []).forEach(issue => {
// if (issue.hardwareId) existingCategorizedHardwareIds.add(issue.hardwareId.trim().toLowerCase());
// if (Array.isArray(issue.hardwareIds)) {
// issue.hardwareIds.forEach(id => {
// if (typeof id === "string") existingCategorizedHardwareIds.add(id.trim().toLowerCase());
// });
// }
// });
// // Step 3: Build list of hardwareIds in unresolved issues (excluding moved)
// const allHardwareIds = new Set();
// for (const issue of unresolvedIssues) {
// const issueHardwareId = issue.hardwareId?.trim().toLowerCase();
// const issueSlaveIds = issue.hardwareIds?.map(id => id?.trim().toLowerCase()) || [];
// if (issueHardwareId && !existingCategorizedHardwareIds.has(issueHardwareId)) {
// allHardwareIds.add(issueHardwareId);
// }
// for (const slaveId of issueSlaveIds) {
// if (slaveId && !existingCategorizedHardwareIds.has(slaveId)) {
// allHardwareIds.add(slaveId);
// }
// }
// }
// // Debug: Log issue hardware IDs being considered
// console.log("✅ All issue hardwareIds:", Array.from(allHardwareIds));
// // Step 4: If no valid hardware IDs left, stop
// if (allHardwareIds.size === 0) {
// return reply.code(404).send({ message: "No unresolved hardware IDs found in issues" });
// }
// const hardwareIdsArray = Array.from(allHardwareIds);
// // Step 5: Find disconnected sensors
// const disconnectedSensors = await Insensors.find({
// connected_status: "disconnected",
// $or: [
// { connected_to: { $in: hardwareIdsArray } },
// { hardwareId: { $in: hardwareIdsArray } },
// { tankhardwareId: { $in: hardwareIdsArray } }
// ]
// }).lean();
// // Debug: Log disconnected sensors found
// console.log("⚙️ Disconnected sensors matched:", disconnectedSensors.map(s => s.hardwareId));
// if (!disconnectedSensors.length) {
// return reply.code(404).send({ message: "No disconnected issues found" });
// }
// // Step 6: Get relevant customers
// const customerIds = [...new Set(disconnectedSensors.map(s => s.customerId))];
// const customers = await User.find({ customerId: { $in: customerIds } }).lean();
// // Step 7: Group by customer
// const customerHardwareMap = {};
// for (const sensor of disconnectedSensors) {
// const custId = sensor.customerId;
// if (!customerHardwareMap[custId]) {
// customerHardwareMap[custId] = new Set();
// }
// const sensorHw = sensor.tankhardwareId?.trim().toLowerCase();
// const sensorConnected = sensor.connected_to?.trim().toLowerCase();
// // for (const issue of unresolvedIssues) {
// // const allIssueHardwareIds = [
// // ...(issue.hardwareIds?.map(id => id?.trim().toLowerCase()) || []),
// // issue.hardwareId?.trim().toLowerCase()
// // ];
// // if (
// // (sensorHw && allIssueHardwareIds.includes(sensorHw)) ||
// // (sensorConnected && allIssueHardwareIds.includes(sensorConnected))
// // ) {
// // if (issue.hardwareId && !existingCategorizedHardwareIds.has(issue.hardwareId.trim().toLowerCase())) {
// // customerHardwareMap[custId].add(issue.hardwareId.trim().toLowerCase());
// // }
// // }
// // }
// const sensorHardwareId = sensor.hardwareId?.trim().toLowerCase();
// for (const issue of unresolvedIssues) {
// const allIssueHardwareIds = [
// ...(issue.hardwareIds?.map(id => id?.trim().toLowerCase()) || []),
// issue.hardwareId?.trim().toLowerCase()
// ];
// if (
// (sensorHw && allIssueHardwareIds.includes(sensorHw)) ||
// (sensorConnected && allIssueHardwareIds.includes(sensorConnected)) ||
// (sensorHardwareId && allIssueHardwareIds.includes(sensorHardwareId))
// ) {
// for (const hw of allIssueHardwareIds) {
// if (hw && !existingCategorizedHardwareIds.has(hw)) {
// customerHardwareMap[custId].add(hw);
// }
// }
// }
// }
// }
// // Debug: Log map of matched customer hardware
// console.log("📌 Customer hardware map:", Object.fromEntries(
// Object.entries(customerHardwareMap).map(([k, v]) => [k, Array.from(v)])
// ));
// // Step 8: Build final response
// const response = [];
// for (const user of customers) {
// const custId = user.customerId;
// const hardwareIdSet = customerHardwareMap[custId] || new Set();
// if (hardwareIdSet.size === 0) continue;
// const relatedIssues = unresolvedIssues.filter(issue => {
// const issueHw = issue.hardwareId?.trim().toLowerCase();
// const hardwareIds = issue.hardwareIds?.map(id => id?.trim().toLowerCase()) || [];
// const allIds = [issueHw, ...hardwareIds];
// return Array.from(hardwareIdSet).some(hw => allIds.includes(hw));
// });
// let latestIssueTime = null;
// for (const issue of relatedIssues) {
// if (issue.lastTicketRaisedAt) {
// const issueTime = new Date(issue.lastTicketRaisedAt);
// if (!latestIssueTime || issueTime > latestIssueTime) {
// latestIssueTime = issueTime;
// }
// }
// }
// response.push({
// customer: {
// customerId: custId,
// username: user.username || "",
// firstName: user.profile?.firstName || "",
// lastName: user.profile?.lastName || "",
// phone: user.phone || user.profile?.contactNumber || "",
// email: user.emails?.[0]?.email || "",
// phoneVerified: user.phoneVerified || false,
// address1: user.profile?.address1 || "",
// address2: user.profile?.address2 || "",
// city: user.profile?.city || "",
// state: user.profile?.state || "",
// country: user.profile?.country || "",
// zip: user.profile?.zip || "",
// notes: user.profile?.notes || "",
// latitude: user.latitude,
// longitude: user.longitude,
// fcmIds: (user.fcmIds || []).filter(fcm => typeof fcm === "string" && fcm.startsWith("d")),
// installationId: user.installationId || "",
// notificationPreferences: {
// allowNotifications: user.allowNotifications || false,
// automaticStartAndStopNotify: user.automaticStartAndStopNotify || false,
// manualStartAndStopNotify: user.manualStartAndStopNotify || false,
// criticalLowWaterAlert: user.criticalLowWaterAlert || false,
// lowWaterAlert: user.lowWaterAlert || false,
// notificationPreference: user.notificationPreference || "never"
// },
// surveyStatus: user.survey_status || "pending",
// buildingName: user.buildingName,
// stripePaymentStatus: user.stripePaymentStatus || false,
// stripeSubscriptionStatus: user.stripeSubscriptionStatus || false,
// createdAt: user.createdAt,
// updatedAt: user.updatedAt,
// lastTicketRaisedAt: latestIssueTime ? moment(latestIssueTime).format("YYYY-MM-DD HH:mm:ss") : null,
// totalHardwareIdsCount: hardwareIdSet.size
// }
// });
// }
// return reply.send({
// status_code: 200,
// data: response
// });
// } catch (error) {
// console.error("❌ Error fetching disconnected customer details:", error);
// return reply.code(500).send({ error: "Internal server error" });
// }
// };
exports.getDisconnectedCustomerDetails = async (req, reply) => {
try {
const { supportId } = req.params;
if (!supportId) {
return reply.code(400).send({ error: "supportId is required" });
}
const normalize = id => (typeof id === "string" ? id.trim().toLowerCase() : "");
const supportRecord = await Support.findOne({ supportId }).lean();
if (!supportRecord) {
return reply.code(404).send({ message: "No support record found for this supportId" });
@ -6451,17 +6240,19 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => {
// Step 2: Build set of hardwareIds already in categorizedIssues (moved)
const existingCategorizedHardwareIds = new Set();
(supportRecord.categorizedIssues || []).forEach(issue => {
if (issue.hardwareId) existingCategorizedHardwareIds.add(normalize(issue.hardwareId));
if (issue.hardwareId) existingCategorizedHardwareIds.add(issue.hardwareId.trim().toLowerCase());
if (Array.isArray(issue.hardwareIds)) {
issue.hardwareIds.forEach(id => existingCategorizedHardwareIds.add(normalize(id)));
issue.hardwareIds.forEach(id => {
if (typeof id === "string") existingCategorizedHardwareIds.add(id.trim().toLowerCase());
});
}
});
// Step 3: Build list of hardwareIds in unresolved issues (excluding moved)
const allHardwareIds = new Set();
for (const issue of unresolvedIssues) {
const issueHardwareId = normalize(issue.hardwareId);
const issueSlaveIds = (issue.hardwareIds || []).map(normalize);
const issueHardwareId = issue.hardwareId?.trim().toLowerCase();
const issueSlaveIds = issue.hardwareIds?.map(id => id?.trim().toLowerCase()) || [];
if (issueHardwareId && !existingCategorizedHardwareIds.has(issueHardwareId)) {
allHardwareIds.add(issueHardwareId);
@ -6474,6 +6265,7 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => {
}
}
// Debug: Log issue hardware IDs being considered
console.log("✅ All issue hardwareIds:", Array.from(allHardwareIds));
// Step 4: If no valid hardware IDs left, stop
@ -6493,6 +6285,7 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => {
]
}).lean();
// Debug: Log disconnected sensors found
console.log("⚙️ Disconnected sensors matched:", disconnectedSensors.map(s => s.hardwareId));
if (!disconnectedSensors.length) {
@ -6511,16 +6304,32 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => {
customerHardwareMap[custId] = new Set();
}
const sensorHw = normalize(sensor.tankhardwareId);
const sensorConnected = normalize(sensor.connected_to);
const sensorHardwareId = normalize(sensor.hardwareId);
const sensorHw = sensor.tankhardwareId?.trim().toLowerCase();
const sensorConnected = sensor.connected_to?.trim().toLowerCase();
// for (const issue of unresolvedIssues) {
// const allIssueHardwareIds = [
// ...(issue.hardwareIds?.map(id => id?.trim().toLowerCase()) || []),
// issue.hardwareId?.trim().toLowerCase()
// ];
// if (
// (sensorHw && allIssueHardwareIds.includes(sensorHw)) ||
// (sensorConnected && allIssueHardwareIds.includes(sensorConnected))
// ) {
// if (issue.hardwareId && !existingCategorizedHardwareIds.has(issue.hardwareId.trim().toLowerCase())) {
// customerHardwareMap[custId].add(issue.hardwareId.trim().toLowerCase());
// }
// }
// }
const sensorHardwareId = sensor.hardwareId?.trim().toLowerCase();
for (const issue of unresolvedIssues) {
const allIssueHardwareIds = [
normalize(issue.hardwareId),
...(issue.hardwareIds || []).map(normalize)
...(issue.hardwareIds?.map(id => id?.trim().toLowerCase()) || []),
issue.hardwareId?.trim().toLowerCase()
];
if (
(sensorHw && allIssueHardwareIds.includes(sensorHw)) ||
(sensorConnected && allIssueHardwareIds.includes(sensorConnected)) ||
@ -6533,8 +6342,11 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => {
}
}
}
}
// Debug: Log map of matched customer hardware
console.log("📌 Customer hardware map:", Object.fromEntries(
Object.entries(customerHardwareMap).map(([k, v]) => [k, Array.from(v)])
));
@ -6548,10 +6360,9 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => {
if (hardwareIdSet.size === 0) continue;
const relatedIssues = unresolvedIssues.filter(issue => {
const allIds = [
normalize(issue.hardwareId),
...(issue.hardwareIds || []).map(normalize)
];
const issueHw = issue.hardwareId?.trim().toLowerCase();
const hardwareIds = issue.hardwareIds?.map(id => id?.trim().toLowerCase()) || [];
const allIds = [issueHw, ...hardwareIds];
return Array.from(hardwareIdSet).some(hw => allIds.includes(hw));
});
@ -6617,6 +6428,8 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => {
};
exports.getDisconnectedCustomerDetailsByTeamMemberId = async (req, reply) => {
try {
const { support_teamMemberId } = req.params;
@ -7753,156 +7566,6 @@ exports.particularCategory = async (req, reply) => {
}
};
// exports.particularCategory = async (req, reply) => {
// try {
// const { supportId, category } = req.params;
// const { customerId: queryCustomerId } = req.query;
// if (!supportId || !category) {
// return reply.code(400).send({ error: "supportId and category are required" });
// }
// const support = await Support.findOne({ supportId }).lean();
// if (!support) {
// return reply.code(404).send({ message: "Support record not found" });
// }
// // Choose the appropriate array based on category
// let issues = [];
// if (category === "Resolved") {
// issues = (support.resolvedIssues || []).filter(issue => issue.category === "Resolved");
// } else {
// issues = (support.categorizedIssues || []).filter(issue => issue.category === category);
// }
// if (issues.length === 0) {
// return reply.code(404).send({ message: `No issues found for category: ${category}` });
// }
// const hardwareIds = [...new Set(issues.map(issue => issue.hardwareId).filter(Boolean))];
// if (hardwareIds.length === 0) {
// return reply.code(404).send({ message: "No hardware IDs found for these issues" });
// }
// let customerId = queryCustomerId;
// if (!customerId) {
// const sensors = await Insensors.find({ hardwareId: { $in: hardwareIds } }).lean();
// if (!sensors.length) {
// return reply.code(404).send({ message: "No sensors found matching these hardware IDs" });
// }
// customerId = sensors[0].customerId;
// if (!customerId) {
// return reply.code(404).send({ message: "Customer ID not found for these sensors" });
// }
// }
// const allRelatedSensors = await Insensors.find({
// customerId,
// hardwareId: { $in: hardwareIds }
// }).lean();
// if (!allRelatedSensors.length) {
// return reply.code(404).send({ message: "No sensors found for the provided customer and hardware IDs" });
// }
// const orders = await Order.find({ customerId }).lean();
// const orderMap = {};
// orders.forEach(order => {
// order.master_connections.forEach(conn => {
// orderMap[conn.hardwareId] = {
// masterName: conn.master_name || null,
// location: conn.location || null
// };
// });
// });
// const disconnectedIssues = [];
// const allMasters = allRelatedSensors.filter(i => i.type === "master");
// for (const master of allMasters) {
// const slaves = await Insensors.find({
// connected_to: master.hardwareId,
// customerId
// }).lean();
// const slaveDetails = await Promise.all(slaves.map(async (slave) => {
// const slaveHardwareId = slave.tankhardwareId;
// const tankInfo = await Tank.findOne({
// $or: [
// { hardwareId: slaveHardwareId },
// { tankhardwareId: slaveHardwareId }
// ]
// }).lean();
// const slaveComments = (support.comments || [])
// .filter(comment => comment.hardwareId === slave.hardwareId)
// .map(c => c.text);
// return {
// hardwareId: slave.tankhardwareId,
// tankName: slave.tankName || "",
// location: slave.tankLocation || "",
// connected_status: slave.connected_status,
// connected_lora_time: slave.connected_lora_time || "",
// connected_lora_date: slave.connected_lora_date || "",
// lora_last_check_time: slave.lora_last_check_time || null,
// lora_last_disconnect_time: slave.lora_last_disconnect_time || null,
// connected_to: slave.connected_to || "",
// masterName: orderMap[master.hardwareId]?.masterName || "",
// type: "slave",
// typeOfWater: tankInfo?.typeOfWater || "",
// support_lora_last_check_time: slave.support_lora_last_check_time || null,
// team_member_support_lora_last_check_time: slave.team_member_support_lora_last_check_time || null,
// comments: slaveComments
// };
// }));
// const masterComments = (support.comments || [])
// .filter(comment => comment.hardwareId === master.hardwareId)
// .map(c => c.text);
// disconnectedIssues.push({
// hardwareId: master.hardwareId,
// masterName: orderMap[master.hardwareId]?.masterName || "",
// location: orderMap[master.hardwareId]?.location || "",
// type: "master",
// connected_status: master.connected_status,
// gsm_last_check_time: master.gsm_last_check_time || null,
// gsm_last_disconnect_time: master.gsm_last_disconnect_time || null,
// connected_gsm_date: master.connected_gsm_date || "",
// connected_gsm_time: master.connected_gsm_time || "",
// connected_lora_date: master.connected_lora_date || "",
// connected_lora_time: master.connected_lora_time || "",
// support_gsm_last_check_time: master.support_gsm_last_check_time || null,
// team_member_support_gsm_last_check_time: master.team_member_support_gsm_last_check_time || null,
// connected_slave_count: slaveDetails.length,
// connected_slaves: slaveDetails,
// comments: masterComments,
// isDisconnected:
// master.connected_status === "disconnected" ||
// slaveDetails.some(slave => slave.connected_status === "disconnected")
// });
// }
// return reply.send({
// status_code: 200,
// supportId,
// customerId,
// totalMasters: disconnectedIssues.length,
// disconnectedIssues
// });
// } catch (err) {
// console.error("Error in particularCategory:", err);
// return reply.code(500).send({ error: "Internal server error" });
// }
// };

Loading…
Cancel
Save