diff --git a/src/controllers/departmentController.js b/src/controllers/departmentController.js index 7343f0bc..7e8de3f5 100644 --- a/src/controllers/departmentController.js +++ b/src/controllers/departmentController.js @@ -81,7 +81,9 @@ const generateDepartmentId = async (city, departmentName) => { // Generate departmentId based on departmentName // const prefix = departmentName.substring(0, 2).toUpperCase(); // Extract first two letters and convert to uppercase - const cityId = await generateCityId(); + const c_id = await generateCityId(); + const cityId = `AWCI${c_id}`; + // Check for existing department const existingStore = await City.findOne({ cityId }); @@ -953,47 +955,53 @@ exports.getZonebasedLocations = async (req, reply) => { // } // }; - const getDepartmentsByName = async (departmentName, city) => { - try { - const trimmedDepartment = departmentName.trim(); - const trimmedCity = city.trim(); - - const query = { - departmentName: { $regex: trimmedDepartment, $options: "i" }, - city: { $regex: trimmedCity, $options: "i" } - }; - - console.log("MongoDB Query:", JSON.stringify(query, null, 2)); - - const result = await Deparments.find(query).lean(); - - console.log("Query Result:", result); - return result; - } catch (err) { - console.error("Error fetching department data:", err); - throw new Error("Error fetching department data."); - } - }; - +// Updated helper function that accepts all three parameters +const getDepartmentsByName = async (officeName, city, departmentName) => { + try { + // Trim all parameters + const trimmedOfficeName = officeName.trim(); + const trimmedCity = city.trim(); + const trimmedDepartment = departmentName.trim(); + + const query = { + officeName: { $regex: trimmedOfficeName, $options: "i" }, + departmentName: { $regex: trimmedDepartment, $options: "i" }, + city: { $regex: trimmedCity, $options: "i" } + }; + + console.log("MongoDB Query:", JSON.stringify(query, null, 2)); + + const result = await Deparments.find(query).lean(); + + console.log("Query Result:", result); + return result; + } catch (err) { + console.error("Error fetching department data:", err); + throw new Error("Error fetching department data."); + } +}; + // API Route exports.getDepartments = async (req, reply) => { try { console.log("Request Params:", req.params); // Debugging log - let { departmentName, city } = req.params; + let { departmentName, city, officeName } = req.params; - if (!departmentName || !city) { - return reply.status(400).send({ message: "Department Name and City are required." }); + if (!departmentName || !city || !officeName) { + return reply.status(400).send({ message: "Department Name, City, and Office Name are required." }); } departmentName = departmentName.trim(); city = city.trim(); + officeName = officeName.trim(); - const departments = await getDepartmentsByName(departmentName, city); + // Note the order: officeName, city, departmentName + const departments = await getDepartmentsByName(officeName, city, departmentName); if (departments.length === 0) { - return reply.status(404).send({ message: "No departments found for the specified name and city." }); + return reply.status(404).send({ message: "No departments found for the specified parameters." }); } reply.send({ status_code: 200, data: departments }); @@ -1078,4 +1086,48 @@ exports.getZonebasedLocations = async (req, reply) => { reply.send({ error: err.message }); } }; - \ No newline at end of file + + + // Helper function to fetch department names by city + const getDepartmentNamesByCity = async (city) => { + try { + const trimmedCity = city.trim(); + + // Allow for extra whitespace before or after the city value in the database + const query = { + city: { $regex: `^\\s*${trimmedCity}\\s*$`, $options: "i" } + }; + console.log("MongoDB Query:", JSON.stringify(query, null, 2)); + + const result = await Deparments.find(query) + .select("departmentName -_id") + .lean(); + + return result.map(doc => doc.departmentName); + } catch (error) { + console.error("Error fetching departments by city:", error); + throw new Error("Error fetching departments by city."); + } + }; + + +// API route handler +exports.getDepartmentsByCity = async (req, reply) => { + try { + const { city } = req.params; + if (!city || city.trim() === "") { + return reply.status(400).send({ message: "City is required." }); + } + + const departmentNames = await getDepartmentNamesByCity(city); + + if (departmentNames.length === 0) { + return reply.status(404).send({ message: "No departments found for the specified city." }); + } + + reply.send({ status_code: 200, data: departmentNames }); + } catch (error) { + console.error("API Error:", error); + reply.status(500).send({ message: error.message }); + } +}; diff --git a/src/index.js b/src/index.js index 8456bc61..456f613b 100644 --- a/src/index.js +++ b/src/index.js @@ -616,6 +616,7 @@ const {Storage} = require('@google-cloud/storage'); const { Supplier, profilePictureSupplier } = require("./models/supplier"); const multer = require('fastify-multer'); const { ProfilePictureInstall, Install } = require("./models/store.js"); +const { TeamMemberProfilePicture, CompanyProfilePicture } = require("./models/Department.js"); fastify.register(require('fastify-formbody')); // fastify.register(multer.contentParser); // const multipart = require('fastify-multipart'); @@ -740,6 +741,107 @@ fastify.register(require('fastify-multipart')); // } // }); +fastify.post('/api/uploads_team_member/:departmentId', async (request, reply) => { + try { + const departmentId = request.params.departmentId; + const data = await request.file(); + + // Generate a unique file name + const fileName = `${data.filename}`; + + // Define the destination bucket and file path + const bucketName = 'arminta_profile_pictures'; + const filePath = `arminta_team_member_profiles/${fileName}`; + + // Create a write stream to the destination file in the bucket + const writeStream = storage.bucket(bucketName).file(filePath).createWriteStream(); + + // Pipe the file data to the write stream + data.file.pipe(writeStream); + + writeStream.on('finish', async () => { + try { + // Make the uploaded file publicly accessible + await storage.bucket(bucketName).file(filePath).makePublic(); + + const publicUrl = `https://storage.googleapis.com/${bucketName}/${filePath}`; + + TeamMemberProfilePicture.findOneAndUpdate( + { departmentId }, + { picture: publicUrl }, + { new: true, upsert: true }, + (error, picture) => { + if (error) { + reply.code(500).send({ error: 'Failed to update database' }); + } else { + // Return the public URL + reply.send({ picture: publicUrl }); + } + } + ); + } catch (error) { + reply.code(500).send({ error: 'Failed to make file public' }); + } + }); + + writeStream.on('error', (err) => { + reply.code(500).send({ error: 'Failed to move file' }); + }); + } catch (err) { + reply.code(500).send({ error: 'An error occurred' }); + } +}); + +fastify.post('/api/uploads_company_profile/:cityId', async (request, reply) => { + try { + const cityId = request.params.cityId; + const data = await request.file(); + + // Generate a unique file name + const fileName = `${data.filename}`; + + // Define the destination bucket and file path + const bucketName = 'arminta_profile_pictures'; + const filePath = `arminta_company_profiles/${fileName}`; + + // Create a write stream to the destination file in the bucket + const writeStream = storage.bucket(bucketName).file(filePath).createWriteStream(); + + // Pipe the file data to the write stream + data.file.pipe(writeStream); + + writeStream.on('finish', async () => { + try { + // Make the uploaded file publicly accessible + await storage.bucket(bucketName).file(filePath).makePublic(); + + const publicUrl = `https://storage.googleapis.com/${bucketName}/${filePath}`; + + CompanyProfilePicture.findOneAndUpdate( + { cityId }, + { picture: publicUrl }, + { new: true, upsert: true }, + (error, picture) => { + if (error) { + reply.code(500).send({ error: 'Failed to update database' }); + } else { + // Return the public URL + reply.send({ picture: publicUrl }); + } + } + ); + } catch (error) { + reply.code(500).send({ error: 'Failed to make file public' }); + } + }); + + writeStream.on('error', (err) => { + reply.code(500).send({ error: 'Failed to move file' }); + }); + } catch (err) { + reply.code(500).send({ error: 'An error occurred' }); + } +}); fastify.post('/api/uploads/:supplierId', async (request, reply) => { diff --git a/src/models/Department.js b/src/models/Department.js index b91fdb81..273b47cf 100644 --- a/src/models/Department.js +++ b/src/models/Department.js @@ -116,11 +116,53 @@ const citySchema = new mongoose.Schema( }, { versionKey: false } ); + + const teamMemberProfilePictureSchema = new Schema({ + departmentId: { + type: String, + unique: true, + required: true + }, + picture: { + type: String, // Change the type to String + required: true, + validate: { + validator: function (value) { + const supportedFormats = ['jpg', 'jpeg', 'png']; + const fileExtension = value.split('.').pop().toLowerCase(); + return supportedFormats.includes(fileExtension); + }, + message: 'Picture must be a JPEG, PNG, or JPG image' + } + } + }); + + const companyProfilePictureSchema = new Schema({ + cityId: { + type: String, + unique: true, + required: true + }, + picture: { + type: String, // Change the type to String + required: true, + validate: { + validator: function (value) { + const supportedFormats = ['jpg', 'jpeg', 'png']; + const fileExtension = value.split('.').pop().toLowerCase(); + return supportedFormats.includes(fileExtension); + }, + message: 'Picture must be a JPEG, PNG, or JPG image' + } + } + }); const City = mongoose.model('City', citySchema); const Deparments = mongoose.model('Deparments', departmentsSchema); const Branch = mongoose.model('Branch', branchSchema); + const TeamMemberProfilePicture = mongoose.model('TeamMemberProfilePicture', teamMemberProfilePictureSchema); + const CompanyProfilePicture = mongoose.model('CompanyProfilePicture', companyProfilePictureSchema); - module.exports = { City,Deparments,Branch}; + module.exports = { City,Deparments,Branch,TeamMemberProfilePicture,CompanyProfilePicture}; diff --git a/src/routes/departmentRoute.js b/src/routes/departmentRoute.js index 82ff9012..e5e7f4b2 100644 --- a/src/routes/departmentRoute.js +++ b/src/routes/departmentRoute.js @@ -445,7 +445,7 @@ module.exports = function (fastify, opts, next) { fastify.route({ method: "GET", - url: "/api/departmentNamebaselist/:departmentName/:city", + url: "/api/departmentNamebaselist/:officeName/:city/:departmentName", schema: { tags: ["Department"], description: "Department name based list", @@ -453,8 +453,9 @@ module.exports = function (fastify, opts, next) { params: { type: "object", properties: { - departmentName: { type: "string" }, + officeName: { type: "string" }, city: { type: "string" }, + departmentName: { type: "string" }, }, }, }, @@ -597,5 +598,24 @@ module.exports = function (fastify, opts, next) { }, handler: departmentController.getCitiesByOfficeName, }); + + fastify.route({ + method: "GET", + url: "/api/departmentNameList/:city", + schema: { + tags: ["Department"], + description: "Get a list of department names for a given city", + summary: "Department names by city", + params: { + type: "object", + properties: { + city: { type: "string" } + }, + required: ["city"], + }, + }, + handler: departmentController.getDepartmentsByCity, + }); + next(); }; \ No newline at end of file