diff --git a/src/controllers/installationController.js b/src/controllers/installationController.js index 9cc9a505..c9ed074b 100644 --- a/src/controllers/installationController.js +++ b/src/controllers/installationController.js @@ -6232,12 +6232,11 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => { 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 - ); + const unresolvedIssues = supportRecord.issues?.filter( + (issue) => issue.resolved === false && issue.movedToCategory === false + ) || []; - // Step 2: Build set of hardwareIds already in categorizedIssues (moved) + // Create set of categorized hardwareIds (masters and slaves) const existingCategorizedHardwareIds = new Set(); (supportRecord.categorizedIssues || []).forEach(issue => { if (issue.hardwareId) existingCategorizedHardwareIds.add(issue.hardwareId.trim().toLowerCase()); @@ -6248,55 +6247,39 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => { } }); - // 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); - } + // Extract all unresolved hardwareIds + const hardwareIdsArray = new Set(); + unresolvedIssues.forEach((issue) => { + if (issue.hardwareId) hardwareIdsArray.add(issue.hardwareId.trim()); + if (Array.isArray(issue.hardwareIds)) { + issue.hardwareIds.forEach((id) => { + if (typeof id === "string") hardwareIdsArray.add(id.trim()); + }); } - } - - // 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); + const allHardwareIds = [...hardwareIdsArray]; - // Step 5: Find disconnected sensors - const disconnectedSensors = await Insensors.find({ + // Fetch disconnected sensors, excluding those already categorized + const disconnectedSensorsRaw = await Insensors.find({ connected_status: "disconnected", $or: [ - { connected_to: { $in: hardwareIdsArray } }, - { hardwareId: { $in: hardwareIdsArray } }, - { tankhardwareId: { $in: hardwareIdsArray } } + { connected_to: { $in: allHardwareIds } }, + { hardwareId: { $in: allHardwareIds } }, + { tankhardwareId: { $in: allHardwareIds } } ] }).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(); + const disconnectedSensors = disconnectedSensorsRaw.filter(sensor => { + const ids = [ + sensor.hardwareId?.trim().toLowerCase(), + sensor.connected_to?.trim().toLowerCase(), + sensor.tankhardwareId?.trim().toLowerCase() + ]; + return !ids.some(id => existingCategorizedHardwareIds.has(id)); + }); - // Step 7: Group by customer + // Map customerId -> Set of affected hardwareIds const customerHardwareMap = {}; for (const sensor of disconnectedSensors) { const custId = sensor.customerId; @@ -6306,30 +6289,19 @@ exports.getDisconnectedCustomerDetails = async (req, reply) => { 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() ]; - + + const isCategorizedMatch = [sensorHw, sensorConnected, sensorHardwareId].some(id => + id && existingCategorizedHardwareIds.has(id) + ); + if (isCategorizedMatch) continue; + if ( (sensorHw && allIssueHardwareIds.includes(sensorHw)) || (sensorConnected && allIssueHardwareIds.includes(sensorConnected)) || @@ -6342,94 +6314,53 @@ 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)]) - )); - - // 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; - } - } - } + const customerDetails = await User.find({ + customerId: { $in: Object.keys(customerHardwareMap) } + }).lean(); - 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 - } - }); - } + const customerResults = customerDetails.map((customer) => { + const affectedHardwareSet = customerHardwareMap[customer.customerId] || new Set(); + return { + customerId: customer.customerId, + buildingName: customer.buildingName || "", + location: customer.location || "", + username: customer.username || "", + firstName: customer.profile?.firstName || "", + lastName: customer.profile?.lastName || "", + phone: customer.phone || user.profile?.contactNumber || "", + email: customer.emails?.[0]?.email || "", + phoneVerified: customer.phoneVerified || false, + address1: customer.profile?.address1 || "", + address2: customer.profile?.address2 || "", + city: customer.profile?.city || "", + latitude: customer.latitude, + longitude: customer.longitude, + totalHardwareIdsCount: affectedHardwareSet.size, + hardwareIds: [...affectedHardwareSet] + }; + }); - return reply.send({ - status_code: 200, - data: response + return reply.code(200).send({ + success: true, + totalCustomers: customerResults.length, + customers: customerResults }); } catch (error) { - console.error("❌ Error fetching disconnected customer details:", error); - return reply.code(500).send({ error: "Internal server error" }); + console.error("Error in getDisconnectedCustomerDetails:", error); + return reply.code(500).send({ + success: false, + message: "Internal Server Error" + }); } }; + exports.getDisconnectedCustomerDetailsByTeamMemberId = async (req, reply) => { try { const { support_teamMemberId } = req.params;