Varun 9 months ago
commit 25be89d52c

@ -10,7 +10,7 @@ const fastify = require("fastify")({
});
const { Counter} = require('../models/User')
const {Department, Desgination, City, Deparments} = require('../models/Department')
const {Department, Desgination, City, Deparments, Branch} = require('../models/Department')
// const generateDepartmentId = async (prefix) => {
// const result = await Counter.findOneAndUpdate(
// { _id: 'department_id' },
@ -27,6 +27,15 @@ const generateCityId = async () => {
{ upsert: true, new: true }
);
return result.seq;
};
const generateBranchId = async () => {
var result = await Counter.findOneAndUpdate(
{ _id: 'customer_id' },
{ $inc: { seq: 1 } },
{ upsert: true, new: true }
);
return result.seq;
};
// const generateDesginationId = async (prefix) => {
@ -67,6 +76,7 @@ const generateDepartmentId = async (city, departmentName) => {
pincode,
createdBy,
updatedBy,
email
} = request.body;
// Generate departmentId based on departmentName
@ -92,6 +102,7 @@ const generateDepartmentId = async (city, departmentName) => {
zone,
country,
pincode,
email,
// departmentName,
createdBy,
updatedBy,
@ -104,6 +115,64 @@ const generateDepartmentId = async (city, departmentName) => {
reply.status(500).send({ message: err.message });
}
};
exports.addBranch = async (request, reply) => {
try {
const {
phone,
land_line_number,
officeName,
location,
city,
state,
country,
zone,
office_address1,
address2,
pincode,
createdBy,
updatedBy,
email
} = request.body;
// Generate departmentId based on departmentName
// const prefix = departmentName.substring(0, 2).toUpperCase(); // Extract first two letters and convert to uppercase
const b_id = await generateBranchId();
const branchId = `AWBR${b_id}`;
// Check for existing department
const existingStore = await Branch.findOne({ branchId });
if (existingStore) {
return reply.status(400).send({ message: 'Branch is already registered' });
}
// Create new department
const branch = new Branch({
branchId,
phone,
land_line_number,
officeName,
location,
city,
office_address1,
address2,
state,
zone,
country,
pincode,
email,
// departmentName,
createdBy,
updatedBy,
});
await branch.save();
reply.send({ branch, message: 'Account Created Successfully' });
} catch (err) {
reply.status(500).send({ message: err.message });
}
};
// exports.getSinledepartmentData = async (req, reply) => {
// try {
// const { departmentId } = req.params;
@ -132,21 +201,24 @@ const generateDepartmentId = async (city, departmentName) => {
// }
// };
// exports.getallcities = async (req, reply) => {
// try {
// await City.find()
// .exec()
// .then((docs) => {
// reply.send({ status_code: 200, data: docs, count: docs.length });
// })
// .catch((err) => {
// console.log(err);
// reply.send({ error: err });
// });
// } catch (err) {
// throw boom.boomify(err);
// }
// };
exports.getallCompanyNames = async (req, reply) => {
try {
await City.find()
.select("officeName -_id") // Select only officeName and exclude _id
.exec()
.then((docs) => {
const officeNames = docs.map((doc) => doc.officeName); // Extract only officeName values
reply.send({ status_code: 200, data: officeNames, count: officeNames.length });
})
.catch((err) => {
console.log(err);
reply.send({ error: err });
});
} catch (err) {
throw boom.boomify(err);
}
};
// exports.getAllDepartmentsParticularFields = async (req, reply) => {
@ -188,13 +260,23 @@ const generateDepartmentId = async (city, departmentName) => {
}
};
exports.deleteBranchInfo = async (req, reply) => {
try {
const branchId = req.params.branchId;
const branch = await Branch.findOneAndDelete({ branchId:branchId });
reply.send({ status_code: 200, message: 'Delete Sucessfully', branch});
} catch (err) {
throw boom.boomify(err);
}
};
exports.editcity = async (request, reply) => {
try {
const { cityId } = request.params;
const {
// phone,
phone,
city,
state,
country,
@ -202,7 +284,8 @@ const generateDepartmentId = async (city, departmentName) => {
address1,
address2,
pincode,
// departmentName
email,
officeName
} = request.body;
@ -218,17 +301,18 @@ const generateDepartmentId = async (city, departmentName) => {
// }
// existing.phone = phone || existing.phone;
existing.phone = phone || existing.phone;
existing.city = city || existing.city;
existing.state = state || existing.state;
existing.country = country || existing.country;
existing.zone = zone || existing.zone;
// existing.departmentName = departmentName || existing.departmentName;
existing.officeName = officeName || existing.officeName;
existing.pincode = pincode || existing.pincode;
existing.address1 = address1 || existing.address1;
existing.address2 = address2 || existing.address2;
existing.email = email || existing.email;
await existing.save();
@ -239,6 +323,61 @@ const generateDepartmentId = async (city, departmentName) => {
}
};
exports.editBranch = async (request, reply) => {
try {
const { branchId } = request.params;
const {
phone,
land_line_number,
officeName,
city,
state,
country,
zone,
address1,
address2,
pincode,
email
// departmentName
} = request.body;
const existing = await Branch.findOne({ branchId });
if (!existing) {
return reply.status(404).send({ message: 'Branch not found' });
}
// const phoneExists = await Department.findOne({ phone, departmentId: { $ne: departmentId } });
// if (phoneExists) {
// return reply.status(400).send({ message: 'Phone is already registered to another user' });
// }
existing.phone = phone || existing.phone;
existing.land_line_number = land_line_number || existing.land_line_number;
existing.city = city || existing.city;
existing.state = state || existing.state;
existing.country = country || existing.country;
existing.zone = zone || existing.zone;
existing.officeName = officeName || existing.officeName;
existing.pincode = pincode || existing.pincode;
existing.address1 = address1 || existing.address1;
existing.address2 = address2 || existing.address2;
existing.email = email || existing.email;
await existing.save();
reply.send({ message: 'Branch user updated successfully' });
} catch (err) {
reply.status(500).send({ message: err.message });
}
};
// exports.addDesgination = async (request, reply) => {
// try {
@ -312,10 +451,14 @@ exports.addDepartment = async (request, reply) => {
try {
const {
phone,
officeName,
alternativeContactNumber,
gender,
personalEmail,
city,
personal_city,
reportingManager_mobile_number,
reportingManager_email,
firstName,
lastName,
departmentName,
@ -350,6 +493,10 @@ exports.addDepartment = async (request, reply) => {
const department = new Deparments({
departmentId,
alternativeContactNumber,
officeName,
reportingManager_mobile_number,
reportingManager_email,
personal_city,
gender,
city,
firstName,
@ -508,7 +655,12 @@ exports.addDepartment = async (request, reply) => {
address1,
address2,
pincode,
desginationName
desginationName,
personal_city,
reportingManager_mobile_number,
reportingManager_email,
officeName,
} = request.body;
@ -543,7 +695,10 @@ exports.addDepartment = async (request, reply) => {
existing.lastName = lastName || existing.lastName;
existing.departmentName = departmentName || existing.departmentName;
existing.reportingManager = reportingManager || existing.reportingManager
existing.personal_city = personal_city || existing.personal_city;
existing.reportingManager_mobile_number = reportingManager_mobile_number || existing.reportingManager_mobile_number;
existing.reportingManager_email = reportingManager_email || existing.reportingManager_email;
existing.officeName = officeName || existing.officeName
await existing.save();
@ -584,7 +739,7 @@ exports.addDepartment = async (request, reply) => {
const getLocationsByCityAndZone = async (city, zone) => {
try {
const result = await City.aggregate([
const result = await Branch.aggregate([
{
$project: {
city: { $toLower: { $trim: { input: "$city" } } }, // Normalize city name (lowercase & trim)
@ -721,7 +876,7 @@ exports.getZonebasedLocations = async (req, reply) => {
const getZonesByCitys = async (city) => {
try {
const result = await City.aggregate([
const result = await Branch.aggregate([
{
$project: {
city: { $trim: { input: "$city" } }, // Trim city field in DB
@ -784,35 +939,72 @@ exports.getZonebasedLocations = async (req, reply) => {
const getDepartmentsByName = async (departmentName) => {
// const getDepartmentsByName = async (departmentName, city) => {
// try {
// const result = await Deparments.find({
// departmentName: { $regex: `^${departmentName.trim()}$`, $options: "i" }, // Case-insensitive search
// city: { $regex: `^${city.trim()}$`, $options: "i" }, // Case-insensitive search
// }).lean(); // Convert to plain JSON
// return result;
// } catch (err) {
// console.error("Error fetching department data:", err);
// throw new Error("Error fetching department data.");
// }
// };
const getDepartmentsByName = async (departmentName, city) => {
try {
const result = await Deparments.find({
departmentName: { $regex: `^${departmentName}$`, $options: "i" }, // Case-insensitive search
});
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(err);
console.error("Error fetching department data:", err);
throw new Error("Error fetching department data.");
}
};
// API Route
exports.getDepartments = async (req, reply) => {
try {
const { departmentName } = req.params; // Get departmentName from request params
console.log("Request Params:", req.params); // Debugging log
let { departmentName, city } = req.params;
if (!departmentName || !city) {
return reply.status(400).send({ message: "Department Name and City are required." });
}
departmentName = departmentName.trim();
city = city.trim();
if (!departmentName) {
return reply.status(400).send({ message: "Department Name is required." });
const departments = await getDepartmentsByName(departmentName, city);
if (departments.length === 0) {
return reply.status(404).send({ message: "No departments found for the specified name and city." });
}
const departments = await getDepartmentsByName(departmentName);
reply.send({ status_code: 200, data: departments });
} catch (err) {
console.error("API Error:", err);
reply.status(500).send({ message: err.message });
}
};
const getDepartmentNames = async () => {
try {
@ -857,4 +1049,33 @@ exports.getZonebasedLocations = async (req, reply) => {
reply.status(500).send({ message: err.message });
}
};
exports.getCitiesByOfficeName = async (req, reply) => {
try {
let { officeName } = req.params;
// Trim and normalize spaces
officeName = officeName.trim().replace(/\s+/g, ' '); // Replace multiple spaces with one
const regexOfficeName = new RegExp(officeName.replace(/\s+/g, '\\s*'), "i");
// Debugging: Check all available office names in DB
console.log("All Cities with Office Name:", await City.find().select("officeName city").lean());
console.log("All Branches with Office Name:", await Branch.find().select("officeName city").lean());
// Query both collections with case-insensitive regex
const cityResults = await City.find({ officeName: { $regex: officeName, $options: "i" } }).select("city -_id").lean();
const branchResults = await Branch.find({ officeName: { $regex: officeName, $options: "i" } }).select("city -_id").lean();
// Extract and merge unique city names
const cityNames = [...new Set([...cityResults.map(c => c.city), ...branchResults.map(b => b.city)])];
console.log("Final City Results:", cityNames);
reply.send({ status_code: 200, data: cityNames });
} catch (err) {
console.error("Error fetching cities:", err);
reply.send({ error: err.message });
}
};

@ -11,6 +11,7 @@ const citySchema = new mongoose.Schema(
phone: { type: String, unique: true, trim: true },
office_address1: String,
officeName: { type: String },
email: { type: String },
address2: String,
pincode: { type: String },
zone: { type: String },
@ -38,13 +39,50 @@ const citySchema = new mongoose.Schema(
);
const branchSchema = new mongoose.Schema(
{
branchId:{type:String},
phone: { type: String, unique: true, trim: true },
land_line_number: { type: String, unique: true, trim: true },
office_address1: String,
officeName: { type: String },
email: { type: String },
address2: String,
pincode: { type: String },
zone: { type: String , default: "ALL"},
city: { type: String },
location: [{ type : String}],
state: String,
country: String,
services: { password: { bcrypt: String } },
createdAt: {
type: Date,
default: function () {
return Date.now();
},
},
createdBy: ObjectId,
updatedAt: {
type: Date,
default: function () {
return Date.now();
},
},
updatedBy: ObjectId,
},
{ versionKey: false }
);
const departmentsSchema = new mongoose.Schema(
{
departmentId:{type:String},
officeName: { type: String },
desginationName: { type: String },
phone: { type: String, unique: true, trim: true },
alternativeContactNumber : { type: String },
reportingManager : { type: String },
reportingManager_mobile_number : { type: String },
reportingManager_email : { type: String },
location: [{ type : String}],
firstName : { type: String },
gender: { type: String },
@ -57,6 +95,7 @@ const citySchema = new mongoose.Schema(
pincode: { type: String },
zone: { type: String },
city: { type: String },
personal_city: { type: String },
state: String,
country: String,
services: { password: { bcrypt: String } },
@ -81,6 +120,7 @@ const citySchema = new mongoose.Schema(
const City = mongoose.model('City', citySchema);
const Deparments = mongoose.model('Deparments', departmentsSchema);
const Branch = mongoose.model('Branch', branchSchema);
module.exports = { City,Deparments};
module.exports = { City,Deparments,Branch};

@ -20,6 +20,7 @@ module.exports = function (fastify, opts, next) {
items: { type: "string" },
},
state: { type: "string" },
email: { type: "string" },
country: { type: "string" },
office_address1: { type: "string" },
address2: { type: "string" },
@ -95,6 +96,23 @@ module.exports = function (fastify, opts, next) {
// handler: departmentController.getAllDepartmentsParticularFields,
// });
fastify.get("/api/getallcompanyNames", {
schema: {
tags: ["Department"],
description: "This is for Get all Company Name in city schema ",
summary: "This is for to Get all Company Name in city schema ",
security: [
{
basicAuth: [],
},
],
},
//preHandler: fastify.auth([fastify.authenticate]),
handler: departmentController.getallCompanyNames,
});
fastify.delete("/api/deletecity/:cityId", {
schema: {
description: "Delete a city by cityId",
@ -135,7 +153,7 @@ module.exports = function (fastify, opts, next) {
body: {
type: "object",
properties: {
// phone: { type: "string" },
phone: { type: "string" },
city: { type: "string" },
state: { type: "string" },
country: { type: "string" },
@ -143,7 +161,8 @@ module.exports = function (fastify, opts, next) {
address2: { type: "string" },
zone: { type: "string" },
pincode: { type: "string" },
departmentName: { type: "string" },
officeName: { type: "string" },
email: { type: "string" },
},
}
@ -158,7 +177,7 @@ module.exports = function (fastify, opts, next) {
schema: {
tags: ["Department"],
description: "This is for creating a new Team Member Account",
summary: "This is for creating a new Ream Member Account",
summary: "This is for creating a new Team Member Account",
body: {
type: "object",
//required: ["phone", "username", "password", "role"], // Add role to required fields
@ -181,6 +200,10 @@ module.exports = function (fastify, opts, next) {
lastName: { type: "string" },
reportingManager: { type: "string" },
email: { type: "string" },
personal_city: { type: "string"},
officeName: { type: "string"},
reportingManager_mobile_number: { type: "string"},
reportingManager_email: { type: "string"},
location: {
type: "array",
items: { type: "string" },
@ -340,6 +363,10 @@ module.exports = function (fastify, opts, next) {
departmentName: { type: "string" },
firstName: { type: "string" },
lastName: { type: "string" },
personal_city: { type: "string"},
officeName: { type: "string"},
reportingManager_mobile_number: { type: "string"},
reportingManager_email: { type: "string"},
},
}
@ -418,7 +445,7 @@ module.exports = function (fastify, opts, next) {
fastify.route({
method: "GET",
url: "/api/departmentNamebaselist/:departmentName",
url: "/api/departmentNamebaselist/:departmentName/:city",
schema: {
tags: ["Department"],
description: "Department name based list",
@ -427,6 +454,7 @@ module.exports = function (fastify, opts, next) {
type: "object",
properties: {
departmentName: { type: "string" },
city: { type: "string" },
},
},
},
@ -450,5 +478,124 @@ module.exports = function (fastify, opts, next) {
handler: departmentController.getAllDepartmentNames,
});
fastify.route({
method: "POST",
url: "/api/branchSignup",
schema: {
tags: ["Department"],
description: "This is for creating a new Branch account",
summary: "This is for creating a new Branch account",
body: {
type: "object",
properties: {
phone: { type: "string" },
land_line_number: { type: "string" },
city: { type: "string" },
officeName: { type: "string" },
location: {
type: "array",
items: { type: "string" },
},
state: { type: "string" },
email: { type: "string" },
country: { type: "string" },
office_address1: { type: "string" },
address2: { type: "string" },
zone: { type: "string" },
pincode: { type: "string" },
//departmentName: { type: "string" },
},
},
security: [
{
basicAuth: [],
},
],
},
handler: departmentController.addBranch,
});
fastify.delete("/api/deletebranch/:branchId", {
schema: {
description: "Delete a city by branchId",
tags: ["Department"],
summary: "Delete a user by branch",
params: {
type: "object",
properties: {
branchId: { type: "string" },
},
required: ["branchId"],
},
response: {
200: {
type: "object",
properties: {
success: { type: "boolean" },
message: { type: "string" },
}
}
}
},
handler: departmentController.deleteBranchInfo,
});
fastify.put('/api/editbranch/:branchId', {
schema: {
description: "Edit Branch details by branch",
tags: ["Department"],
summary: "Edit Branch details.",
params: {
type: "object",
properties: {
branchId: { type: "string" },
},
required: ["branchId"],
},
body: {
type: "object",
properties: {
phone: { type: "string" },
land_line_number: { type: "string" },
city: { type: "string" },
state: { type: "string" },
country: { type: "string" },
address1: { type: "string" },
address2: { type: "string" },
zone: { type: "string" },
pincode: { type: "string" },
officeName: { type: "string" },
email: { type: "string" },
},
}
},
handler: departmentController.editBranch,
});
fastify.get("/api/getCitiesByOfficeName/:officeName", {
schema: {
tags: ["Department"],
description: "This is for Get cities by OfficeName Data",
summary: "This is to Get cities by OfficeName Data",
params: {
type: "object",
properties: {
officeName: {
type: "string",
description: "officeName",
},
},
},
security: [
{
basicAuth: [],
},
],
},
handler: departmentController.getCitiesByOfficeName,
});
next();
};
Loading…
Cancel
Save