const Admin = require('../models/admin') const boom = require("boom"); const jwt = require('jsonwebtoken') const bcrypt = require('bcrypt') const fastify = require("fastify"); const { Tank, MotorData, IotData } = require('../models/tanks'); const { Deparments, City, Branch } = require('../models/Department'); const JWT_SECRET = 'your-secret-key'; async function generateCustomerId(role) { let adminId; let isUnique = false; let prefix; // Set the prefix based on the role switch (role) { case 'admin': prefix = 'AWSAD'; break; case 'sales': prefix = 'AWSSL'; break; case 'store': prefix = 'AWSST'; break; default: throw new Error('Invalid role for customer ID generation'); } while (!isUnique) { // Generate a random number or string for the customer ID const randomId = Math.floor(1000 + Math.random() * 9000).toString(); // Generates a random number between 1000 and 9999 adminId = `${prefix}${randomId}`; // Check for uniqueness in the Admin collection const existingAdmin = await Admin.findOne({ customerId }); if (!existingAdmin) { isUnique = true; // Exit the loop if the customer ID is unique } } return adminId; } exports.adminSignUp = async (request, reply) => { try { const { phone, username, password, role } = request.body; if (!username || username.trim() === '') { return reply.status(400).send({ message: 'Username is required' }); } // Validate role if (!role || !['admin', 'sales', 'store'].includes(role)) { return reply.status(400).send({ message: 'Invalid role. Must be either admin, sales, or store' }); } // Check if an admin with the same phone number or username already exists // const existingAdminUsername = await Admin.findOne({ username }); // const existingAdmin = await Admin.findOne({ phone }); // if (existingAdmin) { // return reply.status(400).send({ message: 'Phone already registered' }); // } // if (existingAdminUsername) { // return reply.status(400).send({ message: 'Username already registered' }); // } // Hash the password using bcrypt const hashedPassword = await bcrypt.hash(password, 10); const adminId = await generateCustomerId(role); // Assuming you have this function defined elsewhere //const building = 'ADMIN'; // You can customize this logic to derive from a parameter or a default value //const customerId = `AWSU${building}${c_id}`; // Construct the customer ID // Create a new admin object with the hashed password and role const admin = new Admin({ phone, username, password: hashedPassword, adminId, role }); // Save the new admin to the database await admin.save(); reply.send({ message: 'Admin Account Created Successfully' }); } catch (err) { reply.status(500).send({ message: err.message }); } }; exports.editAdmin = async (request, reply) => { try { const { customerId } = request.params; const { phone, username, picture, } = request.body; const existing = await Admin.findOne({ customerId }); if (!existing) { return reply.status(404).send({ message: 'City not found' }); } existing.phone = phone || existing.phone; existing.username = username || existing.username; existing.picture = picture || existing.picture; await existing.save(); reply.send({ message: 'Admin user updated successfully' }); } catch (err) { reply.status(500).send({ message: err.message }); } }; // Admin Login Function (With Phone Number) // exports.adminLogin = async (request, reply) => { // try { // const { phone, password } = request.body; // // Check if an admin with the phone number exists // const admin = await Admin.findOne({ phone }); // if (!admin) { // return reply.status(401).send({ message: 'Invalid phone number or password' }); // } // // Compare the password entered by the user with the hashed password stored in the database // const isPasswordValid = await bcrypt.compare(password, admin.password); // if (!isPasswordValid) { // return reply.status(401).send({ message: 'Invalid phone number or password' }); // } // // Generate a JWT token for the authenticated admin // const token = jwt.sign({ phone: admin.phone, role: 'admin' }, JWT_SECRET, { expiresIn: '1h' }); // return reply.send({ token, admin }); // } catch (err) { // reply.status(500).send({ message: err.message }); // } // }; exports.adminLogin = async (request, reply) => { try { const { phone, password } = request.body; // Check if an admin with the phone number exists const admin = await Admin.findOne({ phone }); if (!admin) { return reply.status(401).send({ simplydata: { error: true, message: "Invalid phone number or password", }, }); } // Compare the password entered by the user with the hashed password stored in the database const isPasswordValid = await bcrypt.compare(password, admin.password); if (!isPasswordValid) { return reply.status(401).send({ simplydata: { error: true, message: "Invalid phone number or password", }, }); } // Generate a JWT token for the authenticated admin const token = jwt.sign( { phone: admin.phone, role: admin.role }, JWT_SECRET, { expiresIn: "1h" } ); // Create the response payload const responsePayload = { simplydata: { error: false, apiversion: process.env.APIVERSION, access_token: token, phone: admin.phone, type: admin.role, customerId: admin.adminId || null, username: admin.username || null, }, }; // Send the response return reply.send(responsePayload); } catch (err) { reply.status(500).send({ simplydata: { error: true, message: err.message, }, }); } }; // adminController.js exports.editUserByCustomerId = async (req, reply) => { const { customerId } = req.params; const { phone, username, role, date } = req.body; try { const updatedUser = await Admin.findOneAndUpdate( { customerId: customerId }, { phone, username, role, date }, ); if (!updatedUser) { return reply.status(404).send({ success: false, message: "User not found" }); } return reply.send({ success: true, message: "User details updated successfully", data: updatedUser }); } catch (error) { return reply.status(500).send({ success: false, message: error.message }); } }; exports.deleteUserInfo = async (req, reply) => { try { const customerId = req.params.customerId; const tank = await Admin.findOneAndDelete({ customerId:customerId }); reply.send({ status_code: 200, message: 'Delete Sucessfully'}); // return tank; } catch (err) { throw boom.boomify(err); } }; exports.salesStoreLogin = async (request, reply) => { try { const { phone, password, role } = request.body; // Check if a user (sales or store) with the phone number and role exists const user = await Admin.findOne({ phone, role }); if (!user) { return reply.status(401).send({ message: 'Invalid phone number, password, or role' }); } // Compare the password entered by the user with the hashed password stored in the database const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return reply.status(401).send({ message: 'Invalid phone number, password, or role' }); } // Generate a JWT token for the authenticated user (with role sales or store) const token = jwt.sign({ phone: user.phone, role: user.role }, JWT_SECRET, { expiresIn: '1h' }); return reply.send({ token }); } catch (err) { reply.status(500).send({ message: err.message }); } }; exports.getUsersByRole = async (request, reply) => { try { const { role } = request.params; // Ensure the role is either 'sales' or 'store' if (!['sales', 'store'].includes(role)) { return reply.status(400).send({ message: 'Invalid role. Must be either sales or store.' }); } // Find users with the specific role (sales or store) const users = await Admin.find({ role }); // Send back the list of users reply.send(users); } catch (err) { reply.status(500).send({ message: err.message }); } }; exports.getUserByCustomerId = async (request, reply) => { try { const { customerId } = request.params; // Check if customerId is provided if (!customerId) { return reply.status(400).send({ message: 'Customer ID is required' }); } // Fetch the user from the database const user = await Admin.findOne({ customerId }); // If user not found, return a 404 response if (!user) { return reply.status(404).send({ message: 'User not found' }); } // Return the user data return reply.send(user); } catch (err) { return reply.status(500).send({ message: err.message }); } }; exports.createUser = async (request, reply) => { const { phone, password, role } = request.body; // Validate role (only sales or store) if (!['sales', 'store'].includes(role)) { return reply.status(400).send({ message: 'Invalid role. Must be either sales or store' }); } try { const existingUser = await Admin.findOne({ phone }); if (existingUser) { return reply.status(400).send({ message: 'User with this phone number already exists' }); } // Hash the password const hashedPassword = await bcrypt.hash(password, 10); // Create the new user const newUser = new Admin({ phone, password: hashedPassword, role, }); await newUser.save(); return reply.send({ message: 'User created successfully' }); } catch (err) { reply.status(500).send({ message: err.message }); } }; exports.integratingHardwareidToTank = async (request, reply) => { try { const { customerId, tankName,tankLocation,hardwareId,hardwareId_company,hardwareId_type } = request.body const tank = await Tank.findOneAndUpdate({customerId, tankName:tankName ,tankLocation:tankLocation.toLowerCase()}, { $set: { hardwareId: hardwareId,hardwareId_company:hardwareId_company,hardwareId_type:hardwareId_type } }); reply.send({ status_code: 200, message:`${hardwareId} set to ${tankName}` }); } catch (err) { reply.status(500).send({ message: err.message }) } } exports.getDepartmentDetailsByAdminAndName = async (req, reply) => { try { const { adminId } = req.params; const { departmentName, reportingManager } = req.body; if (!adminId) { return reply.status(400).send({ simplydata: { error: true, message: "adminId is required in path params" } }); } if (!departmentName || !reportingManager) { return reply.status(400).send({ simplydata: { error: true, message: "departmentName and reportingManager are required in body" } }); } // ✅ Find department by adminId, departmentName and reportingManager const department = await Deparments.findOne({ adminId, departmentName, reportingManager }).lean(); if (!department) { return reply.status(404).send({ simplydata: { error: true, message: "Department not found with given criteria" } }); } // ✅ Build response data const responseData = { phone: department.phone, firstName: department.firstName, lastName: department.lastName, email: department.email }; return reply.send({ simplydata: { error: false, message: "Department details fetched successfully", data: responseData } }); } catch (err) { console.error("Error fetching department details:", err); reply.status(500).send({ simplydata: { error: true, message: "Internal server error" } }); } }; exports.getAllCompanys = async (req, reply) => { try { const companyList = await City.find(); return reply.send({ status_code: 200, message: "Fetched successfully", data: companyList, }); } catch (err) { console.error("Error fetching ", err); return reply.status(500).send({ error: "Internal server error" }); } }; // exports.getBranchDetails = async (req, reply) => { // try { // const { officeName } = req.params; // const branchDetails = await Branch.find({ // officeName: { $regex: new RegExp(`^${officeName}$`, 'i') } // }); // return reply.send({ // status_code: 200, // message: "Fetched successfully", // data: branchDetails, // }); // } catch (err) { // console.error("Error fetching branch details:", err); // return reply.status(500).send({ error: "Internal server error" }); // } // }; // exports.getAllOffices = async (req, reply) => { // try { // const { officeName } = req.query; // let filter = {}; // if (officeName && officeName.toUpperCase() !== "ALL") { // // Partial and case-insensitive match // filter.officeName = { $regex: new RegExp(officeName, "i") }; // } // const offices = await Branch.find(filter).lean(); // return reply.code(200).send({ // status_code: 200, // message: "Fetched successfully", // data: offices // }); // } catch (error) { // console.error("Error fetching offices:", error); // return reply.code(500).send({ // status_code: 500, // message: "Internal server error" // }); // } // }; // exports.getAllOffices = async (req, reply) => { // try { // const { officeName } = req.query; // if (!officeName) { // return reply.code(400).send({ // status_code: 400, // message: "officeName query param is required" // }); // } // const nameRegex = new RegExp(officeName.trim(), "i"); // // Fetch head offices, branches, and departments // const [headOffices, branches, departments] = await Promise.all([ // City.find({ officeName: nameRegex }).lean(), // Branch.find({ officeName: nameRegex }).lean(), // Deparments.find({ officeName: nameRegex }).lean() // ]); // if (headOffices.length === 0 && branches.length === 0) { // return reply.code(404).send({ // status_code: 404, // message: "No offices found for the given officeName" // }); // } // const allOffices = []; // // Process head offices (with employee count) // headOffices.forEach(ho => { // const officeNameTrimmed = ho.officeName.trim().toLowerCase(); // // Get all department docs for this office // const matchingDepartments = departments.filter( // d => d.officeName?.trim().toLowerCase() === officeNameTrimmed // ); // // Count employees: 1 main person per doc + sub-team members // const employeeCount = matchingDepartments.reduce((count, dep) => { // const mainPerson = 1; // const subTeamCount = Array.isArray(dep?.team_member?.team_member) // ? dep.team_member.team_member.length // : 0; // return count + mainPerson + subTeamCount; // }, 0); // allOffices.push({ // officeType: "headOffice", // officeName: ho.officeName.trim(), // city: ho.city?.trim() || "", // cityId: ho.cityId || "", // employeeCount, // phone: ho.phone || "", // address: ho.office_address1 || "", // state: ho.state || "", // country: ho.country || "", // pincode: ho.pincode || "", // email: ho.email || "", // latitude:ho.latitude || "", // longitude: ho.longitude || "", // googleLocation: ho.googleLocation || "", // createdAt: ho.createdAt || "", // updatedAt: ho.updatedAt || "" // }); // }); // // Process branches (no employee count here) // branches.forEach(br => { // allOffices.push({ // officeType: "branch", // branchId: br.branchId || "", // officeName: br.officeName?.trim() || "", // city: br.city?.trim() || "", // zone: br.zone || "", // location: br.location || [], // phone: br.phone || "", // address: br.office_address1 || "", // address2: br.address2 || "", // state: br.state || "", // country: br.country || "", // pincode: br.pincode || "", // email: br.email || "", // contactPerson: br.nameoftheContactPerson || "", // latitude:br.latitude || "", // longitude: br.longitude || "", // googleLocation: br.googleLocation || "", // createdAt: br.createdAt || "", // updatedAt: br.updatedAt || "" // }); // }); // return reply.code(200).send({ // status_code: 200, // message: "Fetched successfully", // data: allOffices // }); // } catch (error) { // console.error("Error fetching city offices:", error); // return reply.code(500).send({ // status_code: 500, // message: "Internal server error" // }); // } // }; // exports.getAllOffices = async (req, reply) => { // try { // const { officeName } = req.query; // if (!officeName) { // return reply.code(400).send({ // status_code: 400, // message: "officeName query param is required" // }); // } // let headOffices, branches, departments; // if (officeName.trim().toUpperCase() === "ALL") { // // ✅ Fetch all without filtering // [headOffices, branches, departments] = await Promise.all([ // City.find().lean(), // Branch.find().lean(), // Deparments.find().lean() // ]); // } else { // const nameRegex = new RegExp(officeName.trim(), "i"); // [headOffices, branches, departments] = await Promise.all([ // City.find({ officeName: nameRegex }).lean(), // Branch.find({ officeName: nameRegex }).lean(), // Deparments.find({ officeName: nameRegex }).lean() // ]); // } // if (headOffices.length === 0 && branches.length === 0) { // return reply.code(404).send({ // status_code: 404, // message: "No offices found" // }); // } // const allOffices = []; // // Process head offices (with employee count) // headOffices.forEach(ho => { // const officeNameTrimmed = ho.officeName.trim().toLowerCase(); // // Get all department docs for this office // const matchingDepartments = departments.filter( // d => d.officeName?.trim().toLowerCase() === officeNameTrimmed // ); // // Count employees: 1 main person per doc + sub-team members // const employeeCount = matchingDepartments.reduce((count, dep) => { // const mainPerson = 1; // const subTeamCount = Array.isArray(dep?.team_member?.team_member) // ? dep.team_member.team_member.length // : 0; // return count + mainPerson + subTeamCount; // }, 0); // allOffices.push({ // officeType: "headOffice", // officeName: ho.officeName.trim(), // city: ho.city?.trim() || "", // cityId: ho.cityId || "", // employeeCount, // phone: ho.phone || "", // address: ho.office_address1 || "", // state: ho.state || "", // country: ho.country || "", // pincode: ho.pincode || "", // email: ho.email || "", // latitude: ho.latitude || "", // longitude: ho.longitude || "", // googleLocation: ho.googleLocation || "", // createdAt: ho.createdAt || "", // updatedAt: ho.updatedAt || "" // }); // }); // // Process branches (no employee count here) // branches.forEach(br => { // allOffices.push({ // officeType: "branch", // branchId: br.branchId || "", // officeName: br.officeName?.trim() || "", // city: br.city?.trim() || "", // zone: br.zone || "", // location: br.location || [], // phone: br.phone || "", // address: br.office_address1 || "", // address2: br.address2 || "", // state: br.state || "", // country: br.country || "", // pincode: br.pincode || "", // email: br.email || "", // contactPerson: br.nameoftheContactPerson || "", // latitude: br.latitude || "", // longitude: br.longitude || "", // googleLocation: br.googleLocation || "", // createdAt: br.createdAt || "", // updatedAt: br.updatedAt || "" // }); // }); // return reply.code(200).send({ // status_code: 200, // message: "Fetched successfully", // data: allOffices // }); // } catch (error) { // console.error("Error fetching city offices:", error); // return reply.code(500).send({ // status_code: 500, // message: "Internal server error" // }); // } // }; exports.getAllOffices = async (req, reply) => { try { const { officeName } = req.query; if (!officeName) { return reply.code(400).send({ status_code: 400, message: "officeName query param is required" }); } let headOffices, branches, departments; if (officeName.trim().toUpperCase() === "ALL") { // ✅ Fetch all without filtering [headOffices, branches, departments] = await Promise.all([ City.find().lean(), Branch.find().lean(), Deparments.find().lean() ]); } else { const nameRegex = new RegExp(officeName.trim(), "i"); [headOffices, branches, departments] = await Promise.all([ City.find({ officeName: nameRegex }).lean(), Branch.find({ officeName: nameRegex }).lean(), Deparments.find({ officeName: nameRegex }).lean() ]); } if (headOffices.length === 0 && branches.length === 0) { return reply.code(404).send({ status_code: 404, message: "No offices found" }); } // 🏢 Group by officeName const grouped = {}; // Head offices headOffices.forEach(ho => { const key = ho.officeName.trim().toLowerCase(); if (!grouped[key]) grouped[key] = []; const matchingDepartments = departments.filter( d => d.officeName?.trim().toLowerCase() === key ); const employeeCount = matchingDepartments.reduce((count, dep) => { const mainPerson = 1; const subTeamCount = Array.isArray(dep?.team_member?.team_member) ? dep.team_member.team_member.length : 0; return count + mainPerson + subTeamCount; }, 0); grouped[key].push({ officeType: "headOffice", officeName: ho.officeName.trim(), city: ho.city?.trim() || "", cityId: ho.cityId || "", employeeCount, phone: ho.phone || "", address: ho.office_address1 || "", address2: ho.address2 || "", state: ho.state || "", country: ho.country || "", pincode: ho.pincode || "", email: ho.email || "", latitude: ho.latitude || 0, longitude: ho.longitude || 0, googleLocation: ho.googleLocation || "", createdAt: ho.createdAt || "", updatedAt: ho.updatedAt || "" }); }); // Branches branches.forEach(br => { const key = br.officeName.trim().toLowerCase(); if (!grouped[key]) grouped[key] = []; const matchingDepartments = departments.filter( d => d.officeName?.trim().toLowerCase() === key && d.city === br.city ); const employeeCount = matchingDepartments.reduce((count, dep) => { const mainPerson = 1; const subTeamCount = Array.isArray(dep?.team_member?.team_member) ? dep.team_member.team_member.length : 0; return count + mainPerson + subTeamCount; }, 0); grouped[key].push({ officeType: "branchOffice", branchId: br.branchId || "", officeName: br.officeName?.trim() || "", city: br.city?.trim() || "", employeeCount, phone: br.phone || "", address: br.office_address1 || "", address2: br.address2 || "", state: br.state || "", country: br.country || "", pincode: br.pincode || "", email: br.email || "", contactPerson: br.nameoftheContactPerson || "", latitude: br.latitude || 0, longitude: br.longitude || 0, googleLocation: br.googleLocation || "", createdAt: br.createdAt || "", updatedAt: br.updatedAt || "" }); }); // Convert grouped object into array const result = Object.values(grouped).map(offices => ({ offices })); return reply.code(200).send({ status_code: 200, message: "Fetched successfully", data: result }); } catch (error) { console.error("Error fetching city offices:", error); return reply.code(500).send({ status_code: 500, message: "Internal server error" }); } }; exports.getAllOfficesByCity = async (req, reply) => { try { const { city } = req.query; if (!city) { return reply.code(400).send({ status_code: 400, message: "city query param is required", }); } const cityRegex = new RegExp(city.trim(), "i"); // 🔹 Step 1: Find all headOffices in this city const headOffices = await City.find({ city: cityRegex }).lean(); // 🔹 Step 2: Find all branchOffices in this city const branchMatches = await Branch.find({ city: cityRegex }).lean(); if (!headOffices.length && !branchMatches.length) { return reply.code(404).send({ status_code: 404, message: `No headOffice or branch found for city ${city}`, }); } // 🔹 Step 3: Collect all unique officeNames const officeNames = [ ...new Set([ ...headOffices.map((ho) => ho.officeName.trim()), ...branchMatches.map((br) => br.officeName.trim()), ]), ]; const finalResponse = []; // 🔹 Step 4: For each officeName, gather HO + Branches for (const name of officeNames) { const ho = await City.findOne({ officeName: new RegExp(name, "i"), }).lean(); // Get employee count for headOffice (if exists) let employeeCount = 0; if (ho) { const departments = await Deparments.find({ city: ho.city }).lean(); employeeCount = departments.reduce((count, dep) => { const mainPerson = 1; const subTeamCount = Array.isArray(dep?.team_member?.team_member) ? dep.team_member.team_member.length : 0; return count + mainPerson + subTeamCount; }, 0); } // Get all branches for this officeName const branches = await Branch.find({ officeName: new RegExp(name, "i"), }).lean(); const offices = []; // Add headOffice if found if (ho) { offices.push({ officeType: "headOffice", officeName: ho.officeName?.trim() || "", city: ho.city?.trim() || "", cityId: ho.cityId || "", employeeCount, phone: ho.phone || "", address: ho.office_address1 || "", address2: ho.address2 || "", state: ho.state || "", country: ho.country || "", pincode: ho.pincode || "", email: ho.email || "", latitude: ho.latitude || 0, longitude: ho.longitude || 0, googleLocation: ho.googleLocation || "", createdAt: ho.createdAt || "", updatedAt: ho.updatedAt || "", }); } // Add all branchOffices branches.forEach((br) => { offices.push({ officeType: "branchOffice", branchId: br.branchId || "", officeName: br.officeName?.trim() || "", city: br.city?.trim() || "", employeeCount, // using HO employee count (optional) phone: br.phone || "", address: br.office_address1 || "", address2: br.address2 || "", state: br.state || "", country: br.country || "", pincode: br.pincode || "", email: br.email || "", contactPerson: br.nameoftheContactPerson || "", latitude: br.latitude || 0, longitude: br.longitude || 0, googleLocation: br.googleLocation || "", createdAt: br.createdAt || "", updatedAt: br.updatedAt || "", }); }); finalResponse.push({ officeName: name, city, offices, }); } return reply.code(200).send({ status_code: 200, message: "Fetched successfully", data: finalResponse, }); } catch (error) { console.error("❌ Error in getAllOfficesByCity:", error); return reply.code(500).send({ status_code: 500, message: "Internal server error", error: error.message, }); } }; // exports.getAllOfficesByCity = async (req, reply) => { // try { // const { city } = req.query; // if (!city) { // return reply.code(400).send({ // status_code: 400, // message: "city query param is required" // }); // } // const cityRegex = new RegExp(city.trim(), "i"); // // 1) Find head offices (city schema) // const headOffices = await City.find({ city: cityRegex }).lean(); // if (!headOffices.length) { // return reply.code(404).send({ // status_code: 404, // message: `No head office found for city ${city}` // }); // } // // 2) Build response for each headOffice // const finalResponse = []; // for (const ho of headOffices) { // // (optional) Employee count logic // const departments = await Deparments.find({ city: ho.city }).lean(); // const employeeCount = departments.reduce((count, dep) => { // const mainPerson = 1; // const subTeamCount = Array.isArray(dep?.team_member?.team_member) // ? dep.team_member.team_member.length // : 0; // return count + mainPerson + subTeamCount; // }, 0); // // 3) Find branches with same officeName // const branches = await Branch.find({ // officeName: new RegExp(ho.officeName.trim(), "i") // }).lean(); // // 4) Construct office data // const offices = []; // // Head Office (from citySchema) // offices.push({ // officeType: "headOffice", // officeName: ho.officeName?.trim() || "", // city: ho.city?.trim() || "", // cityId: ho.cityId || "", // employeeCount, // phone: ho.phone || "", // address: ho.office_address1 || "", // address2: ho.address2 || "", // state: ho.state || "", // country: ho.country || "", // pincode: ho.pincode || "", // email: ho.email || "", // latitude: ho.latitude || 0, // longitude: ho.longitude || 0, // googleLocation: ho.googleLocation || "", // createdAt: ho.createdAt || "", // updatedAt: ho.updatedAt || "" // }); // // Branches (from branchSchema) // branches.forEach(br => { // offices.push({ // officeType: "branchOffice", // branchId: br.branchId || "", // officeName: br.officeName?.trim() || "", // city: br.city?.trim() || "", // employeeCount, // optional: same count or separate // phone: br.phone || "", // address: br.office_address1 || "", // address2: br.address2 || "", // state: br.state || "", // country: br.country || "", // pincode: br.pincode || "", // email: br.email || "", // contactPerson: br.nameoftheContactPerson || "", // latitude: br.latitude || 0, // longitude: br.longitude || 0, // googleLocation: br.googleLocation || "", // createdAt: br.createdAt || "", // updatedAt: br.updatedAt || "" // }); // }); // // 5) Push into final response // finalResponse.push({ // officeName: ho.officeName?.trim() || "", // city: ho.city?.trim() || "", // offices // }); // } // return reply.code(200).send({ // status_code: 200, // message: "Fetched successfully", // data: finalResponse // }); // } catch (error) { // console.error("❌ Error in getAllOfficesByCity:", error); // return reply.code(500).send({ // status_code: 500, // message: "Internal server error", // error: error.message // }); // } // }; // exports.getAllOfficesByCity = async (req, reply) => { // try { // const { city } = req.query; // if (!city) { // return reply.code(400).send({ // status_code: 400, // message: "city query param is required" // }); // } // const cityRegex = new RegExp(city.trim(), "i"); // // Fetch head offices, branches, and departments // const [headOffices, branches, departments] = await Promise.all([ // City.find({ city: cityRegex }).lean(), // Branch.find({ city: cityRegex }).lean(), // Deparments.find({ city: cityRegex }).lean() // ]); // if (!headOffices.length && !branches.length) { // return reply.code(404).send({ // status_code: 404, // message: `No offices found in city ${city}` // }); // } // const officeMap = new Map(); // // 🔹 Process Head Offices // headOffices.forEach(ho => { // const cityTrimmed = ho.city?.trim().toLowerCase(); // const matchingDepartments = departments.filter( // d => d.city?.trim().toLowerCase() === cityTrimmed // ); // // Count employees // const employeeCount = matchingDepartments.reduce((count, dep) => { // const mainPerson = 1; // const subTeamCount = Array.isArray(dep?.team_member?.team_member) // ? dep.team_member.team_member.length // : 0; // return count + mainPerson + subTeamCount; // }, 0); // const officeNameKey = ho.officeName?.trim().toLowerCase(); // if (!officeMap.has(officeNameKey)) { // officeMap.set(officeNameKey, { // officeName: ho.officeName?.trim() || "", // city: ho.city?.trim() || "", // offices: [] // }); // } // officeMap.get(officeNameKey).offices.push({ // officeType: "headOffice", // officeName: ho.officeName?.trim() || "", // city: ho.city?.trim() || "", // cityId: ho.cityId || "", // employeeCount, // phone: ho.phone || "", // address: ho.office_address1 || "", // state: ho.state || "", // country: ho.country || "", // pincode: ho.pincode || "", // email: ho.email || "", // latitude: ho.latitude || "", // longitude: ho.longitude || "", // googleLocation: ho.googleLocation || "", // createdAt: ho.createdAt || "", // updatedAt: ho.updatedAt || "" // }); // }); // // 🔹 Process Branches // branches.forEach(br => { // const officeNameKey = br.officeName?.trim().toLowerCase(); // if (!officeMap.has(officeNameKey)) { // officeMap.set(officeNameKey, { // officeName: br.officeName?.trim() || "", // city: br.city?.trim() || "", // offices: [] // }); // } // officeMap.get(officeNameKey).offices.push({ // officeType: "branch", // branchId: br.branchId || "", // officeName: br.officeName?.trim() || "", // city: br.city?.trim() || "", // zone: br.zone || "", // location: Array.isArray(br.location) ? br.location : [], // phone: br.phone || "", // address: br.office_address1 || "", // address2: br.address2 || "", // state: br.state || "", // country: br.country || "", // pincode: br.pincode || "", // email: br.email || "", // contactPerson: br.nameoftheContactPerson || "", // latitude: br.latitude || "", // longitude: br.longitude || "", // googleLocation: br.googleLocation || "", // createdAt: br.createdAt || "", // updatedAt: br.updatedAt || "" // }); // }); // // 🔹 Final grouped response // const finalResponse = Array.from(officeMap.values()); // return reply.code(200).send({ // status_code: 200, // message: "Fetched successfully", // data: finalResponse // }); // } catch (error) { // console.error("❌ Error in getAllOfficesByCity:", error); // return reply.code(500).send({ // status_code: 500, // message: "Internal server error", // error: error.message // }); // } // }; // exports.getAllOfficesByCity = async (req, reply) => { // try { // const { city } = req.query; // if (!city) { // return reply.code(400).send({ // status_code: 400, // message: "city query param is required" // }); // } // const cityRegex = new RegExp(city.trim(), "i"); // // Fetch head offices and branches in this city // const headOffices = await City.find({ city: cityRegex }).lean(); // const branches = await Branch.find({ city: cityRegex }).lean(); // if (!headOffices.length && !branches.length) { // return reply.code(404).send({ // status_code: 404, // message: `No offices found in city ${city}` // }); // } // // Group by officeName // const officeMap = new Map(); // // Process head offices // headOffices.forEach(ho => { // const key = ho.officeName?.trim().toLowerCase(); // if (!officeMap.has(key)) { // officeMap.set(key, { // officeName: ho.officeName?.trim() || "", // city: ho.city?.trim() || "", // headOffices: [] // }); // } // officeMap.get(key).headOffices.push({ // officeType: "headOffice", // city: ho.city?.trim() || "", // employeeCount: ho.employeeCount || 0, // phone: ho.phone || "", // address: ho.address || "", // state: ho.state || "", // country: ho.country || "", // pincode: ho.pincode || "", // email: ho.email || "" // }); // }); // // Process branches // branches.forEach(br => { // const key = br.officeName?.trim().toLowerCase(); // if (!officeMap.has(key)) { // officeMap.set(key, { // officeName: br.officeName?.trim() || "", // city: br.city?.trim() || "", // headOffices: [] // }); // } // officeMap.get(key).headOffices.push({ // officeType: "branch", // branchId: br.branchId || "", // city: br.city?.trim() || "", // zone: br.zone || "", // phone: br.phone || "", // address: br.address || "", // state: br.state || "" // }); // }); // // Final response array // const finalResponse = Array.from(officeMap.values()); // return reply.code(200).send({ // status_code: 200, // message: "Fetched successfully", // data: finalResponse // }); // } catch (err) { // console.error("❌ Error in getAllOfficesByCity:", err); // return reply.code(500).send({ // status_code: 500, // message: "Internal server error", // error: err.message // }); // } // }; // exports.getCityOffices = async (req, reply) => { // try { // const { officeName } = req.query; // if (!officeName) { // return reply.code(400).send({ // status_code: 400, // message: "officeName query param is required" // }); // } // // Regex filter for partial & case-insensitive match // const nameRegex = new RegExp(officeName.trim(), "i"); // // Step 1: Fetch head offices matching the officeName // const headOffices = await City.find({ officeName: nameRegex }).lean(); // // Step 2: Fetch branches matching the officeName // const branches = await Branch.find({ officeName: nameRegex }).lean(); // // Step 3: Fetch departments matching the officeName // const departments = await Deparments.find({ officeName: nameRegex }).lean(); // if (headOffices.length === 0 && branches.length === 0) { // return reply.code(404).send({ // status_code: 404, // message: "No offices found for the given officeName" // }); // } // // Step 4: Build city-wise result // const cityMap = {}; // headOffices.forEach(ho => { // const officeNameTrimmed = ho.officeName.trim(); // // Find department for this office to get employee count // const departmentDoc = departments.find( // d => // d.officeName && // d.officeName.trim().toLowerCase() === officeNameTrimmed.toLowerCase() // ); // const employeeCount = // departmentDoc?.team_member?.team_member?.length || 0; // cityMap[ho.city.trim().toLowerCase()] = { // city: ho.city.trim(), // headOffice: { // officeName: ho.officeName.trim(), // employeeCount, // phone: ho.phone || "", // address: ho.office_address1 || "", // state: ho.state || "", // country: ho.country || "", // pincode: ho.pincode || "", // email: ho.email || "" // }, // branches: [] // }; // }); // // Step 5: Attach branches // branches.forEach(br => { // const cityKey = br.city.trim().toLowerCase(); // if (!cityMap[cityKey]) { // cityMap[cityKey] = { // city: br.city.trim(), // headOffice: null, // branches: [] // }; // } // cityMap[cityKey].branches.push({ // officeName: br.officeName?.trim() || "", // location: br.location || [], // phone: br.phone || "", // address: br.address1 || "" // }); // }); // // Step 6: Convert to array // const result = Object.values(cityMap); // return reply.code(200).send({ // status_code: 200, // message: "Fetched successfully", // data: result // }); // } catch (error) { // console.error("Error fetching city offices:", error); // return reply.code(500).send({ // status_code: 500, // message: "Internal server error" // }); // } // }; // exports.getCityOffices = async (req, reply) => { // try { // const { officeName } = req.query; // if (!officeName) { // return reply.code(400).send({ // status_code: 400, // message: "officeName query param is required" // }); // } // const nameRegex = new RegExp(officeName.trim(), "i"); // // Step 1: Fetch head offices // const headOffices = await City.find({ officeName: nameRegex }).lean(); // // Step 2: Fetch branches // const branches = await Branch.find({ officeName: nameRegex }).lean(); // // Step 3: Fetch departments // const departments = await Deparments.find({ officeName: nameRegex }).lean(); // if (headOffices.length === 0 && branches.length === 0) { // return reply.code(404).send({ // status_code: 404, // message: "No offices found for the given officeName" // }); // } // const cityMap = {}; // headOffices.forEach(ho => { // const officeNameTrimmed = ho.officeName.trim(); // // Find department for this office to get employee count // const departmentDoc = departments.find( // d => d.officeName?.trim().toLowerCase() === officeNameTrimmed.toLowerCase() // ); // console.log("departmentDoc",departmentDoc) // const mainPersonCount = departmentDoc?.team_member?.main_person ? 1 : 0; // const subTeamCount = Array.isArray(departmentDoc?.team_member?.team_member) // ? departmentDoc.team_member.team_member.length // : 0; // const employeeCount = mainPersonCount + subTeamCount; // cityMap[ho.city.trim().toLowerCase()] = { // // cityId: ho.cityId || "", // added cityId // city: ho.city.trim(), // headOffice: { // officeName: ho.officeName.trim(), // cityId: ho.cityId || "", // added cityId // employeeCount, // phone: ho.phone || "", // address: ho.office_address1 || "", // state: ho.state || "", // country: ho.country || "", // pincode: ho.pincode || "", // email: ho.email || "" // }, // // branches: [] // }; // }); // // Step 5: Attach branches // branches.forEach(br => { // const cityKey = br.city.trim().toLowerCase(); // if (!cityMap[cityKey]) { // cityMap[cityKey] = { // //cityId: br.cityId || "", // city: br.city.trim(), // // headOffice: null, // branches: [] // }; // } // cityMap[cityKey].branches.push({ // branchId: br.branchId || "", // officeName: br.officeName?.trim() || "", // zone: br.zone || "", // location: br.location || [], // phone: br.phone || "", // address: br.office_address1 || "", // address2: br.address2 || "", // state: br.state || "", // country: br.country || "", // pincode: br.pincode || "", // email: br.email || "", // contactPerson: br.nameoftheContactPerson || "", // createdAt: br.createdAt || "", // updatedAt: br.updatedAt || "" // }); // }); // const result = Object.values(cityMap); // return reply.code(200).send({ // status_code: 200, // message: "Fetched successfully", // data: result // }); // } catch (error) { // console.error("Error fetching city offices:", error); // return reply.code(500).send({ // status_code: 500, // message: "Internal server error" // }); // } // }; exports.getCityOffices = async (req, reply) => { try { const { officeName } = req.query; if (!officeName) { return reply.code(400).send({ status_code: 400, message: "officeName query param is required" }); } const nameRegex = new RegExp(officeName.trim(), "i"); // Fetch head offices, branches, and departments const [headOffices, branches, departments] = await Promise.all([ City.find({ officeName: nameRegex }).lean(), Branch.find({ officeName: nameRegex }).lean(), Deparments.find({ officeName: nameRegex }).lean() ]); if (headOffices.length === 0 && branches.length === 0) { return reply.code(404).send({ status_code: 404, message: "No offices found for the given officeName" }); } const cityMap = {}; headOffices.forEach(ho => { const officeNameTrimmed = ho.officeName.trim().toLowerCase(); // Get all department docs for this office const matchingDepartments = departments.filter( d => d.officeName?.trim().toLowerCase() === officeNameTrimmed ); // Count employees: each department doc = 1 main person + sub-team members const employeeCount = matchingDepartments.reduce((count, dep) => { const mainPerson = 1; // the document itself const subTeamCount = Array.isArray(dep?.team_member?.team_member) ? dep.team_member.team_member.length : 0; return count + mainPerson + subTeamCount; }, 0); cityMap[ho.city.trim().toLowerCase()] = { city: ho.city.trim(), headOffice: { officeName: ho.officeName.trim(), cityId: ho.cityId || "", employeeCount, phone: ho.phone || "", address: ho.office_address1 || "", state: ho.state || "", country: ho.country || "", pincode: ho.pincode || "", email: ho.email || "" }, // branches: [] }; }); // Attach branches branches.forEach(br => { const cityKey = br.city.trim().toLowerCase(); if (!cityMap[cityKey]) { cityMap[cityKey] = { city: br.city.trim(), branches: [] }; } cityMap[cityKey].branches.push({ branchId: br.branchId || "", officeName: br.officeName?.trim() || "", zone: br.zone || "", location: br.location || [], phone: br.phone || "", address: br.office_address1 || "", address2: br.address2 || "", state: br.state || "", country: br.country || "", pincode: br.pincode || "", email: br.email || "", contactPerson: br.nameoftheContactPerson || "", createdAt: br.createdAt || "", updatedAt: br.updatedAt || "" }); }); return reply.code(200).send({ status_code: 200, message: "Fetched successfully", data: Object.values(cityMap) }); } catch (error) { console.error("Error fetching city offices:", error); return reply.code(500).send({ status_code: 500, message: "Internal server error" }); } }; exports.getOfficeDetails = async (req, reply) => { try { let { officeName, city } = req.params; if (!officeName || !city) { return reply.code(400).send({ message: "officeName and city are required." }); } // Normalize whitespace and case officeName = officeName.trim().replace(/\s+/g, ' '); city = city.trim().replace(/\s+/g, ' '); const filters = {}; if (officeName.toUpperCase() !== 'ALL') { filters.officeName = { $regex: new RegExp(officeName.replace(/\s+/g, '\\s*'), 'i') }; } if (city.toUpperCase() !== 'ALL') { filters.city = { $regex: new RegExp(city.replace(/\s+/g, '\\s*'), 'i') }; } // Query City collection const cityResults = await City.find(filters).lean(); // Query Branch collection const branchResults = await Branch.find(filters).lean(); const combinedResults = [...cityResults, ...branchResults]; if (combinedResults.length === 0) { return reply.status(404).send({ message: "No office details found for the given filters." }); } reply.send({ status_code: 200, message: "Office details fetched successfully.", data: combinedResults, }); } catch (error) { console.error("Error in getOfficeDetails:", error); reply.status(500).send({ status_code: 500, message: "Internal server error", error: error.message, }); } }; exports.adminEditTeamMember = async (request, reply) => { try { const { departmentId, teamMemberId } = request.params; const updateData = request.body; // Find the installation const installation = await Deparments.findOne({ departmentId }); if (!installation) { return reply.status(404).send({ simplydata: { error: true, message: "Installation not found", }, }); } // Find the team member let teamMember = installation.team_member.team_member.find( (member) => member.teamMemberId === teamMemberId ); if (!teamMember) { return reply.status(404).send({ simplydata: { error: true, message: "Team member not found", }, }); } // Update fields Object.assign(teamMember, updateData); // Save changes await installation.markModified("team_member.team_member"); await installation.save(); return reply.send({ simplydata: { error: false, message: "Team member updated successfully", }, }); } catch (err) { console.error("Error updating team member:", err); reply.status(500).send({ simplydata: { error: true, message: "Internal server error", }, }); } }; exports.AdmindeleteTeamMember = async (request, reply) => { try { const { departmentId, teamMemberId } = request.params; // Find the installation const installation = await Deparments.findOne({ departmentId }); if (!installation) { return reply.status(404).send({ simplydata: { error: true, message: "Installation not found", }, }); } // Find index of the team member const memberIndex = installation.team_member.team_member.findIndex( (member) => member.teamMemberId === teamMemberId ); if (memberIndex === -1) { return reply.status(404).send({ simplydata: { error: true, message: "Team member not found", }, }); } // Remove the team member from the array installation.team_member.team_member.splice(memberIndex, 1); // Save changes await installation.markModified("team_member.team_member"); await installation.save(); return reply.send({ simplydata: { error: false, message: "Team member deleted successfully", }, }); } catch (err) { console.error("Error deleting team member:", err); reply.status(500).send({ simplydata: { error: true, message: "Internal server error", }, }); } };