Varun 8 months ago
commit 23a68c578a

@ -81,7 +81,9 @@ const generateDepartmentId = async (city, departmentName) => {
// Generate departmentId based on departmentName // Generate departmentId based on departmentName
// const prefix = departmentName.substring(0, 2).toUpperCase(); // Extract first two letters and convert to uppercase // 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 // Check for existing department
const existingStore = await City.findOne({ cityId }); const existingStore = await City.findOne({ cityId });
@ -953,27 +955,31 @@ exports.getZonebasedLocations = async (req, reply) => {
// } // }
// }; // };
const getDepartmentsByName = async (departmentName, city) => { // Updated helper function that accepts all three parameters
try { const getDepartmentsByName = async (officeName, city, departmentName) => {
const trimmedDepartment = departmentName.trim(); try {
const trimmedCity = city.trim(); // Trim all parameters
const trimmedOfficeName = officeName.trim();
const trimmedCity = city.trim();
const trimmedDepartment = departmentName.trim();
const query = { const query = {
departmentName: { $regex: trimmedDepartment, $options: "i" }, officeName: { $regex: trimmedOfficeName, $options: "i" },
city: { $regex: trimmedCity, $options: "i" } departmentName: { $regex: trimmedDepartment, $options: "i" },
}; city: { $regex: trimmedCity, $options: "i" }
};
console.log("MongoDB Query:", JSON.stringify(query, null, 2)); console.log("MongoDB Query:", JSON.stringify(query, null, 2));
const result = await Deparments.find(query).lean(); const result = await Deparments.find(query).lean();
console.log("Query Result:", result); console.log("Query Result:", result);
return result; return result;
} catch (err) { } catch (err) {
console.error("Error fetching department data:", err); console.error("Error fetching department data:", err);
throw new Error("Error fetching department data."); throw new Error("Error fetching department data.");
} }
}; };
// API Route // API Route
@ -981,19 +987,21 @@ exports.getZonebasedLocations = async (req, reply) => {
try { try {
console.log("Request Params:", req.params); // Debugging log console.log("Request Params:", req.params); // Debugging log
let { departmentName, city } = req.params; let { departmentName, city, officeName } = req.params;
if (!departmentName || !city) { if (!departmentName || !city || !officeName) {
return reply.status(400).send({ message: "Department Name and City are required." }); return reply.status(400).send({ message: "Department Name, City, and Office Name are required." });
} }
departmentName = departmentName.trim(); departmentName = departmentName.trim();
city = city.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) { 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 }); reply.send({ status_code: 200, data: departments });
@ -1079,3 +1087,47 @@ exports.getZonebasedLocations = async (req, reply) => {
} }
}; };
// 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 });
}
};

@ -616,6 +616,7 @@ const {Storage} = require('@google-cloud/storage');
const { Supplier, profilePictureSupplier } = require("./models/supplier"); const { Supplier, profilePictureSupplier } = require("./models/supplier");
const multer = require('fastify-multer'); const multer = require('fastify-multer');
const { ProfilePictureInstall, Install } = require("./models/store.js"); const { ProfilePictureInstall, Install } = require("./models/store.js");
const { TeamMemberProfilePicture, CompanyProfilePicture } = require("./models/Department.js");
fastify.register(require('fastify-formbody')); fastify.register(require('fastify-formbody'));
// fastify.register(multer.contentParser); // fastify.register(multer.contentParser);
// const multipart = require('fastify-multipart'); // 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) => { fastify.post('/api/uploads/:supplierId', async (request, reply) => {

@ -117,10 +117,52 @@ const citySchema = new mongoose.Schema(
{ versionKey: false } { 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 City = mongoose.model('City', citySchema);
const Deparments = mongoose.model('Deparments', departmentsSchema); const Deparments = mongoose.model('Deparments', departmentsSchema);
const Branch = mongoose.model('Branch', branchSchema); 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};

@ -445,7 +445,7 @@ module.exports = function (fastify, opts, next) {
fastify.route({ fastify.route({
method: "GET", method: "GET",
url: "/api/departmentNamebaselist/:departmentName/:city", url: "/api/departmentNamebaselist/:officeName/:city/:departmentName",
schema: { schema: {
tags: ["Department"], tags: ["Department"],
description: "Department name based list", description: "Department name based list",
@ -453,8 +453,9 @@ module.exports = function (fastify, opts, next) {
params: { params: {
type: "object", type: "object",
properties: { properties: {
departmentName: { type: "string" }, officeName: { type: "string" },
city: { type: "string" }, city: { type: "string" },
departmentName: { type: "string" },
}, },
}, },
}, },
@ -597,5 +598,24 @@ module.exports = function (fastify, opts, next) {
}, },
handler: departmentController.getCitiesByOfficeName, 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(); next();
}; };
Loading…
Cancel
Save