create team member in admin and getAll departments

master^2
Bhaskar 2 months ago
parent cba2ce57ea
commit 6afecc2fec

@ -9,7 +9,7 @@ const { Tank, MotorData, IotData } = require('../models/tanks')
const JWT_SECRET = 'your-secret-key'; const JWT_SECRET = 'your-secret-key';
async function generateCustomerId(role) { async function generateCustomerId(role) {
let customerId; let adminId;
let isUnique = false; let isUnique = false;
let prefix; let prefix;
@ -31,7 +31,7 @@ async function generateCustomerId(role) {
while (!isUnique) { while (!isUnique) {
// Generate a random number or string for the customer ID // Generate a random number or string for the customer ID
const randomId = Math.floor(1000 + Math.random() * 9000).toString(); // Generates a random number between 1000 and 9999 const randomId = Math.floor(1000 + Math.random() * 9000).toString(); // Generates a random number between 1000 and 9999
customerId = `${prefix}${randomId}`; adminId = `${prefix}${randomId}`;
// Check for uniqueness in the Admin collection // Check for uniqueness in the Admin collection
const existingAdmin = await Admin.findOne({ customerId }); const existingAdmin = await Admin.findOne({ customerId });
if (!existingAdmin) { if (!existingAdmin) {
@ -39,7 +39,7 @@ async function generateCustomerId(role) {
} }
} }
return customerId; return adminId;
} }
@ -72,12 +72,12 @@ exports.adminSignUp = async (request, reply) => {
// Hash the password using bcrypt // Hash the password using bcrypt
const hashedPassword = await bcrypt.hash(password, 10); const hashedPassword = await bcrypt.hash(password, 10);
const customerId = await generateCustomerId(role); // Assuming you have this function defined elsewhere const adminId = await generateCustomerId(role); // Assuming you have this function defined elsewhere
//const building = 'ADMIN'; // You can customize this logic to derive from a parameter or a default value //const building = 'ADMIN'; // You can customize this logic to derive from a parameter or a default value
//const customerId = `AWSU${building}${c_id}`; // Construct the customer ID //const customerId = `AWSU${building}${c_id}`; // Construct the customer ID
// Create a new admin object with the hashed password and role // Create a new admin object with the hashed password and role
const admin = new Admin({ phone, username, password: hashedPassword, customerId, role }); const admin = new Admin({ phone, username, password: hashedPassword, adminId, role });
// Save the new admin to the database // Save the new admin to the database
await admin.save(); await admin.save();

@ -29,42 +29,44 @@ const generateTeamMemberId = async () => {
}; };
exports.createTeamMember = async (request, reply) => { exports.createTeamMember = async (req, reply) => {
try { try {
const { departmentId, firstName, phone, password,email,alternativePhone ,status} = request.body; const { adminId } = req.params;
const { departmentId, departmentName, firstName, phone, password, email, alternativePhone, status } = req.body;
// Check if installation exists if (!adminId) {
const installation = await Deparments.findOne({ departmentId }); return reply.status(400).send({ simplydata: { error: true, message: "adminId is required in path params" } });
}
if (!installation) { // Check if admin exists
return reply.status(404).send({ const admin = await Admin.findOne({ adminId });
simplydata: { if (!admin) {
error: true, return reply.status(404).send({ simplydata: { error: true, message: "Admin not found" } });
message: "Installation not found",
},
});
} }
// Check if phone number already exists in the team // Check if department exists
const existingMember = installation.team_member.team_member.find( const department = await Deparments.findOne({ departmentId });
(member) => member.phone === phone if (!department) {
); return reply.status(404).send({ simplydata: { error: true, message: "Department not found" } });
}
// ✅ Update adminId in department (if needed)
department.adminId = adminId;
// Check if phone already exists
const existingMember = department.team_member.team_member.find(member => member.phone === phone);
if (existingMember) { if (existingMember) {
return reply.status(400).send({ return reply.status(400).send({ simplydata: { error: true, message: "Phone number already exists in the team" } });
simplydata: {
error: true,
message: "Phone number already exists in the team",
},
});
} }
// Generate new teamMemberId
const c_id = await generateTeamMemberId();
const teamMemberId = `AWTM${c_id}`;
// Hash password // Hash password
const hashedPassword = await bcrypt.hash(password, 10); const hashedPassword = await bcrypt.hash(password, 10);
const c_id = await generateTeamMemberId(); // Create new member
const teamMemberId = `AWTM${c_id}`;
// Create new team member
const newTeamMember = { const newTeamMember = {
teamMemberId, teamMemberId,
firstName, firstName,
@ -72,32 +74,32 @@ exports.createTeamMember = async (request, reply) => {
email, email,
alternativePhone, alternativePhone,
installationTeamMemId: departmentId, installationTeamMemId: departmentId,
departmentId,
departmentName,
password: hashedPassword, password: hashedPassword,
status, status: status || "active",
}; };
// Add to team members array // Add to team_member array
installation.team_member.team_member.push(newTeamMember); department.team_member.team_member.push(newTeamMember);
await installation.save();
// ✅ Save the department with updated adminId and new member
await department.save();
return reply.send({ return reply.send({
simplydata: { simplydata: {
error: false, error: false,
message: "Team member created successfully", message: "Team member created successfully",
teamMemberId: newTeamMember.teamMemberId, teamMemberId: newTeamMember.teamMemberId,
}, }
}); });
} catch (err) { } catch (err) {
console.error("Error creating team member:", err); console.error("Error creating team member:", err);
reply.status(500).send({ reply.status(500).send({ simplydata: { error: true, message: "Internal server error" } });
simplydata: {
error: true,
message: "Internal server error",
},
});
} }
}; };
exports.getTeamMembers = async (request, reply) => { exports.getTeamMembers = async (request, reply) => {
@ -138,6 +140,50 @@ exports.createTeamMember = async (request, reply) => {
} }
}; };
exports.getAllDepartments = async (request, reply) => {
try {
const { departmentName } = request.params;
if (!departmentName) {
return reply.status(400).send({
simplydata: {
error: true,
message: "departmentName is required in path params",
},
});
}
// ✅ Find all departments matching departmentName
const departments = await Deparments.find({ departmentName }).lean();
if (!departments.length) {
return reply.status(404).send({
simplydata: {
error: true,
message: "No departments found with the given departmentName",
},
});
}
return reply.send({
simplydata: {
error: false,
message: "Departments retrieved successfully",
data: departments,
},
});
} catch (err) {
console.error("Error fetching departments:", err);
return reply.status(500).send({
simplydata: {
error: true,
message: "Internal server error",
},
});
}
};
// exports.assignTeamMemberToQuotation = async (request, reply) => { // exports.assignTeamMemberToQuotation = async (request, reply) => {
// try { // try {
// const { installationId } = request.params; // Get installationId from URL params // const { installationId } = request.params; // Get installationId from URL params
@ -5806,6 +5852,7 @@ exports.getIotDataByCustomerAndHardwareId = async (req, reply) => {
// }); // });
const cron = require("node-cron"); const cron = require("node-cron");
const Admin = require("../models/admin");
// const raiseATicketLikeLogic = async (customerId, connected_to) => { // const raiseATicketLikeLogic = async (customerId, connected_to) => {
// try { // try {

@ -102,6 +102,7 @@ const citySchema = new mongoose.Schema(
const departmentsSchema = new mongoose.Schema( const departmentsSchema = new mongoose.Schema(
{ {
adminId: String,
departmentId:{type:String}, departmentId:{type:String},
officeName: { type: String }, officeName: { type: String },
desginationName: { type: String }, desginationName: { type: String },
@ -140,6 +141,8 @@ const citySchema = new mongoose.Schema(
status: { type: String, default: "active" }, status: { type: String, default: "active" },
email: { type: String }, email: { type: String },
alternativePhone: { type: String }, alternativePhone: { type: String },
departmentId: String, // new
departmentName: String,
} }
], ],

@ -24,7 +24,7 @@ const adminSchema = new mongoose.Schema({
enum: ['admin', 'sales', 'store'], enum: ['admin', 'sales', 'store'],
default: 'sales', default: 'sales',
}, },
customerId: { adminId: {
type: String, type: String,
required: true, // Customer ID is now required required: true, // Customer ID is now required
unique: true, unique: true,

@ -2,29 +2,52 @@ const installationController = require("../controllers/installationController")
module.exports = function (fastify, opts, next) { module.exports = function (fastify, opts, next) {
fastify.post("/api/createTeamMember", { fastify.post("/api/createTeamMember/:adminId", {
schema: { schema: {
description: "Create a new team member under an installation", description: "Create a new team member under an admin",
tags: ["Installation"], tags: ["Admin"],
summary: "Create Team Member", summary: "Create Team Member",
params: {
type: "object",
properties: {
adminId: { type: "string", description: "Admin ID under whom to add the team member" }
},
required: ["adminId"]
},
body: { body: {
type: "object", type: "object",
required: ["departmentId", "firstName", "phone", "password"], required: ["departmentId", "departmentName", "firstName", "phone", "password"],
properties: { properties: {
departmentId: { type: "string", description: "Installation ID to associate the team member with" }, departmentId: { type: "string", description: "Department ID (installationId)" },
firstName: { type: "string", description: "Full name of the team member" }, departmentName: { type: "string", description: "Department name" },
phone: { type: "string", description: "Phone number of the team member" }, firstName: { type: "string" },
password: { type: "string", description: "Password for the team member" }, phone: { type: "string" },
alternativePhone: { type: "string", }, password: { type: "string" },
email: { type: "string", }, alternativePhone: { type: "string" },
status: { type: "string", }, email: { type: "string" },
status: { type: "string" },
}, },
}, },
}, },
handler: installationController.createTeamMember, handler: installationController.createTeamMember,
}); });
fastify.get("/api/getAllDepartments/:departmentName", {
schema: {
description: "Get full department details by department name",
tags: ["Admin"],
summary: "Get all department details",
params: {
type: "object",
properties: {
departmentName: { type: "string", description: "Department name to search" },
},
required: ["departmentName"],
},
},
handler: installationController.getAllDepartments,
});
fastify.get("/api/getTeamMembers/:departmentId", { fastify.get("/api/getTeamMembers/:departmentId", {
schema: { schema: {

Loading…
Cancel
Save