ashok 1 month ago
commit 57b4320685

@ -711,9 +711,6 @@ exports.getAllOffices = async (req, reply) => {
}
};
exports.getAllOfficesByCity = async (req, reply) => {
try {
const { city } = req.query;
@ -727,33 +724,49 @@ exports.getAllOfficesByCity = async (req, reply) => {
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()
]);
// 1) Try to find head offices directly in this city
let headOffices = await City.find({ city: cityRegex }).lean();
if (headOffices.length === 0 && branches.length === 0) {
// 2) If no head office, check if branch exists in that city
if (!headOffices.length) {
const branchMatches = await Branch.find({ city: cityRegex }).lean();
if (!branchMatches.length) {
return reply.code(404).send({
status_code: 404,
message: "No offices found for the given city"
message: `No headOffice or branch found for city ${city}`
});
}
const allOffices = [];
// Take officeName(s) from branch to find headOffice
const officeNames = [...new Set(branchMatches.map(b => b.officeName))];
// Process head offices
headOffices.forEach(ho => {
const cityTrimmed = ho.city?.trim().toLowerCase();
headOffices = await City.find({
officeName: { $in: officeNames }
}).lean();
// Get all department docs for this city
const matchingDepartments = departments.filter(
d => d.city?.trim().toLowerCase() === cityTrimmed
);
// If still no headOffice found, fallback to just using branch data
if (!headOffices.length) {
return reply.code(200).send({
status_code: 200,
message: "Fetched successfully (branch only, no headOffice found)",
data: branchMatches.map(br => ({
officeName: br.officeName,
city: br.city,
offices: [br]
}))
});
}
}
// Count employees
const employeeCount = matchingDepartments.reduce((count, dep) => {
// 3) Build response for each headOffice found
const finalResponse = [];
for (const ho of headOffices) {
// employee count
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
@ -761,7 +774,16 @@ exports.getAllOfficesByCity = async (req, reply) => {
return count + mainPerson + subTeamCount;
}, 0);
allOffices.push({
// find all branches for this officeName
const branches = await Branch.find({
officeName: new RegExp(ho.officeName.trim(), "i")
}).lean();
// build office array
const offices = [];
// head office
offices.push({
officeType: "headOffice",
officeName: ho.officeName?.trim() || "",
city: ho.city?.trim() || "",
@ -769,27 +791,26 @@ exports.getAllOfficesByCity = async (req, reply) => {
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 || "",
longitude: ho.longitude || "",
latitude: ho.latitude || 0,
longitude: ho.longitude || 0,
googleLocation: ho.googleLocation || "",
createdAt: ho.createdAt || "",
updatedAt: ho.updatedAt || ""
});
});
// Process branches
// branches
branches.forEach(br => {
allOffices.push({
officeType: "branch",
offices.push({
officeType: "branchOffice",
branchId: br.branchId || "",
officeName: br.officeName?.trim() || "",
city: br.city?.trim() || "",
zone: br.zone || "",
location: br.location || [],
employeeCount, // optional
phone: br.phone || "",
address: br.office_address1 || "",
address2: br.address2 || "",
@ -798,29 +819,375 @@ exports.getAllOfficesByCity = async (req, reply) => {
pincode: br.pincode || "",
email: br.email || "",
contactPerson: br.nameoftheContactPerson || "",
latitude: br.latitude || "",
longitude: br.longitude || "",
latitude: br.latitude || 0,
longitude: br.longitude || 0,
googleLocation: br.googleLocation || "",
createdAt: br.createdAt || "",
updatedAt: br.updatedAt || ""
});
});
finalResponse.push({
officeName: ho.officeName?.trim() || "",
city: ho.city?.trim() || "",
offices
});
}
return reply.code(200).send({
status_code: 200,
message: "Fetched successfully",
data: allOffices
data: finalResponse
});
} catch (error) {
console.error("Error fetching city offices by city:", error);
console.error("❌ Error in getAllOfficesByCity:", error);
return reply.code(500).send({
status_code: 500,
message : "Internal server error"
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) => {

Loading…
Cancel
Save