diff --git a/src/controllers/departmentController.js b/src/controllers/departmentController.js index 04897cc7..4719cbb5 100644 --- a/src/controllers/departmentController.js +++ b/src/controllers/departmentController.js @@ -684,4 +684,55 @@ exports.addDepartment = async (request, reply) => { reply.status(500).send({ message: err.message }); } }; + + + const getZonesByCitys = async (city) => { + try { + const result = await City.aggregate([ + { + $unwind: "$city" // Convert location array into separate documents + }, + { + $match: { + city: { $regex: `^${city}$`, $options: "i" }, // Match city case-insensitively + }, + }, + { + $group: { + _id: { + $toUpper: { $trim: { input: "$city" } } // Normalize city name + }, + zones: { $addToSet: "$zone" } // Collect unique zones + }, + }, + { + $project: { + _id: 0, // Exclude _id + city: "$_id", // Return city name + zones: 1, // Return collected zones + }, + }, + ]); + + return result; + } catch (err) { + console.error(err); + throw new Error("Error fetching zones."); + } + }; + + exports.getZonesByCity = async (req, reply) => { + try { + const { city } = req.params; + + if (!city) { + return reply.status(400).send({ message: "City is required." }); + } + + const zones = await getZonesByCitys(city); + reply.send({ status_code: 200, data: zones }); + } catch (err) { + reply.status(500).send({ message: err.message }); + } + }; \ No newline at end of file diff --git a/src/routes/departmentRoute.js b/src/routes/departmentRoute.js index dff9a456..3c483985 100644 --- a/src/routes/departmentRoute.js +++ b/src/routes/departmentRoute.js @@ -399,6 +399,21 @@ module.exports = function (fastify, opts, next) { handler:departmentController.getLocationsByZone }); - + fastify.route({ + method: "GET", + url: "/api/zonebasedcity/:city", + schema: { + tags: ["Department"], + description: "Get the zones by city", + summary: "Get the zones by city", + params: { + type: "object", + properties: { + city: { type: "string" }, + }, + }, + }, + handler:departmentController.getZonesByCity + }); next(); }; \ No newline at end of file