Compare commits

..

17 Commits

@ -24,7 +24,7 @@ var termination = chalk.bold.magenta;
const databaseURLNew = "mongodb://35.207.198.4:27017/arminta-tank-db"; const databaseURLNew = "mongodb://35.207.198.4:27017/arminta-tank-db";
//const databaseURLNew = "mongodb://35.200.129.165:27017/health-care-db"; //const databaseURLNew = "mongodb://35.200.129.165:27017/health-care-db";
// const databaseURLNew = "mongodb://127.0.0.1:27017/arminta-tank-db"; //const databaseURLNew = "mongodb://127.0.0.1:27017/arminta-tank-db";
// Next line not used , or no need to pass default db in the mongo connection url. // Next line not used , or no need to pass default db in the mongo connection url.
const defaultDatabase = "arminta-tank-db"; const defaultDatabase = "arminta-tank-db";

@ -1290,6 +1290,30 @@ exports.getbatchnumbers = async (req, reply) => {
}; };
exports.getiots = async (req, reply) => {
try {
const storeId = req.params.storeId;
let type = req.params.type ? req.params.type.toUpperCase() : null; // Convert type to uppercase
let query = { storeId: storeId };
if (type !== "ALL") {
query.type = type;
}
// Fetch data based on the query
const result = await Insensors.find(query);
if (!result ) {
return reply.send({ status_code: 404, error: "not found" });
}
reply.send({ status_code: 200, data: result });
} catch (err) {
throw boom.boomify(err);
}
};
exports.getusersofParticularInstaller = async (req, reply) => { exports.getusersofParticularInstaller = async (req, reply) => {
try { try {
await User.find({installationId: req.query.InstallerId}) await User.find({installationId: req.query.InstallerId})

@ -1565,17 +1565,18 @@ admin.initializeApp({
// }); // });
eventEmitter.on('motorStart', async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName, startTime, motorOnType, stopCriteria) => { eventEmitter.on('motorStart', async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName, startTime, motorOnType, stopCriteria) => {
const message = `Water supply from '${blockName}' to '${tankName}' started at ${startTime} by '${motorOnType}' mode and will stop after ${stopCriteria}. Current Water Level: ${waterLevel} Ltrs.`; const message = `MotorId '${motorId}' Water supply from '${blockName}' to '${tankName}' started at ${startTime} by '${motorOnType}' mode and will stop after ${stopCriteria}. Current Water Level: ${waterLevel} Ltrs.`;
await sendNotification(fcmTokens, 'Motor Started', message); await sendNotification(fcmTokens, 'Motor Started', message);
}); });
// Emit motor stop event with motorId // Emit motor stop event with motorId
eventEmitter.on('motorStop', async (fcmTokens, timestamp, motorId, waterLevel, blockName, tankName,stopTime,motorOnType) => { eventEmitter.on('motorStop', async (fcmTokens, motorId, waterLevel, blockName, tankName, stopTime, motorOnType) => {
const message = `Water supply from '${blockName}' to '${tankName}' stopped at ${stopTime} by '${motorOnType}' mode. Current Water Level: ${waterLevel} Ltrs.`; const message = `MotorId '${motorId}' Water supply from '${blockName}' to '${tankName}' stopped at ${stopTime} by '${motorOnType}' mode. Current Water Level: ${waterLevel} Ltrs.`;
await sendNotification(fcmTokens, 'Motor Stopped', message); await sendNotification(fcmTokens, 'Motor Stopped', message);
}); });
// Event listener to handle notification // Event listener to handle notification
eventEmitter.on('sendLowWaterNotification', async (fcmToken, tankInfo) => { eventEmitter.on('sendLowWaterNotification', async (fcmToken, tankInfo) => {
const message = formatWaterLevelMessage(tankInfo, 'low'); const message = formatWaterLevelMessage(tankInfo, 'low');
@ -2027,50 +2028,50 @@ exports.motorAction = async (req, reply) => {
const currentWaterLevel = parseInt(receiverTank.waterlevel, 10); const currentWaterLevel = parseInt(receiverTank.waterlevel, 10);
const waterLevelThresholds = { low: 30, veryLow: 20, criticallyLow: 10 }; const waterLevelThresholds = { low: 30, veryLow: 20, criticallyLow: 10 };
// Check if the water level is below any of the thresholds // // Check if the water level is below any of the thresholds
if (currentWaterLevel < waterLevelThresholds.criticallyLow) { // if (currentWaterLevel < waterLevelThresholds.criticallyLow) {
if (!receiverTank.notificationSentCritical) { // if (!receiverTank.notificationSentCritical) {
eventEmitter.emit('sendCriticalLowWaterNotification', fcmToken, receiverTank); // eventEmitter.emit('sendCriticalLowWaterNotification', fcmToken, receiverTank);
await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentCritical: true } }); // await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentCritical: true } });
} // }
} else if (currentWaterLevel < waterLevelThresholds.veryLow) { // } else if (currentWaterLevel < waterLevelThresholds.veryLow) {
if (!receiverTank.notificationSentVeryLow) { // if (!receiverTank.notificationSentVeryLow) {
eventEmitter.emit('sendVeryLowWaterNotification', fcmToken, receiverTank); // eventEmitter.emit('sendVeryLowWaterNotification', fcmToken, receiverTank);
await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentVeryLow: true } }); // await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentVeryLow: true } });
} // }
} else if (currentWaterLevel < waterLevelThresholds.low) { // } else if (currentWaterLevel < waterLevelThresholds.low) {
if (!receiverTank.notificationSentLow) { // if (!receiverTank.notificationSentLow) {
eventEmitter.emit('sendLowWaterNotification', fcmToken, receiverTank); // eventEmitter.emit('sendLowWaterNotification', fcmToken, receiverTank);
await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentLow: true } }); // await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentLow: true } });
} // }
} // }
// Check for critical high water level // Check for critical high water level
if (currentWaterLevel >= criticalHighWaterThreshold) { // if (currentWaterLevel >= criticalHighWaterThreshold) {
if (!receiverTank.notificationSentCriticalHigh) { // if (!receiverTank.notificationSentCriticalHigh) {
eventEmitter.emit('sendCriticalHighWaterNotification', fcmToken, receiverTank); // eventEmitter.emit('sendCriticalHighWaterNotification', fcmToken, receiverTank);
await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentCriticalHigh: true } }); // await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentCriticalHigh: true } });
} // }
} // }
// Check for very high water level // // Check for very high water level
else if (currentWaterLevel >= veryHighWaterThreshold) { // else if (currentWaterLevel >= veryHighWaterThreshold) {
if (!receiverTank.notificationSentVeryHigh) { // if (!receiverTank.notificationSentVeryHigh) {
eventEmitter.emit('sendVeryHighWaterNotification', fcmToken, receiverTank); // eventEmitter.emit('sendVeryHighWaterNotification', fcmToken, receiverTank);
await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentVeryHigh: true } }); // await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentVeryHigh: true } });
} // }
} // }
// Check for high water level // // Check for high water level
else if (currentWaterLevel >= highWaterThreshold) { // else if (currentWaterLevel >= highWaterThreshold) {
if (!receiverTank.notificationSentHigh) { // if (!receiverTank.notificationSentHigh) {
eventEmitter.emit('sendHighWaterNotification', fcmToken, receiverTank); // eventEmitter.emit('sendHighWaterNotification', fcmToken, receiverTank);
await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentHigh: true } }); // await Tank.updateOne({ customerId, tankName: receiverTank.tankName }, { $set: { notificationSentHigh: true } });
} // }
} // }
// Determine the motor stop status based on the action // Determine the motor stop status based on the action
let motorStopStatus; let motorStopStatus;
const blockName = req.body.from || "Unknown Block"; // Provide a fallback if `from` is missing const blockName = req.body.from || "Unknown Block"; // Provide a fallback if `from` is missing
const tankName = req.body.to || "Unknown Tank"; // Provide a fallback if `to` is missing const tankName = req.body.to || "Unknown Tank"; // Provide a fallback if `to` is missing
const stopTime = req.body.stopTime || new Date().toISOString(); const stopTime = req.body.stopTime || new Date().toISOString();
const motorOnType = req.body.motor_on_type || "manual"; const motorOnType = req.body.motor_on_type || "application";
if (action === "start") { if (action === "start") {
motorStopStatus = "2"; motorStopStatus = "2";
@ -4659,6 +4660,8 @@ client.on('message', async (topic, message) => {
time time
})); }));
// Save IoT data for the received tanks // Save IoT data for the received tanks
const iotTankData = new IotData({ const iotTankData = new IotData({
hardwareId: hw_Id, // Updated variable name hardwareId: hw_Id, // Updated variable name
@ -4730,53 +4733,6 @@ client.on('message', async (topic, message) => {
const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name const inputConnection = motorTank.connections.inputConnections.find(conn => conn.motor_id === hw_Id); // Updated variable name
if (inputConnection) { if (inputConnection) {
inputConnection.motor_status = status; // Update motor status inputConnection.motor_status = status; // Update motor status
console.log(inputConnection.motor_stop_status,"inputConnection.motor_stop_status")
if (inputConnection.motor_stop_status === "1" && status === "2") {
console.log("got into forced manual")
console.log(inputConnection.motor_on_type,"before if motor on type")
// Check if motor_on_type is not already "forced_manual"
if (inputConnection.motor_on_type !== "forced_manual") {
inputConnection.motor_on_type = "forced_manual";
console.log("entered forced manual of if")
inputConnection.motor_stop_status = "2";
// Update startTime to the current time in the specified format
const currentTime = new Date();
const formattedTime = currentTime.toLocaleString('en-GB', {
day: '2-digit',
month: 'short',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).replace(',', '');
inputConnection.startTime = formattedTime;
}
}
if (inputConnection.motor_stop_status === "2" && status === "1") {
console.log("got into forced manual stop")
console.log(inputConnection.motor_on_type,"before if motor on type stop")
// Check if motor_on_type is not already "forced_manual"
if (inputConnection.motor_on_type = "forced_manual") {
inputConnection.motor_on_type = "manual";
console.log("entered forced manual of if of stop")
// Update startTime to the current time in the specified format
inputConnection.motor_stop_status = "1";
}
}
await motorTank.save(); // Save the updated tank await motorTank.save(); // Save the updated tank
} }
@ -4789,6 +4745,8 @@ client.on('message', async (topic, message) => {
}); });
// Function to publish motor stop status // Function to publish motor stop status
// exports.publishMotorStopStatus = async (motor_id, motor_stop_status) => { // exports.publishMotorStopStatus = async (motor_id, motor_stop_status) => {
// const payload = { // const payload = {
@ -5038,5 +4996,5 @@ async function removeDuplicates() {
} }
// Run the remove duplicates function // Run the remove duplicates function
removeDuplicates(); // removeDuplicates();
console.log("this is for testing autopush,line located in tankscontroller") console.log("this is for testing autopush,line located in tankscontroller")

@ -820,3 +820,114 @@ exports.updateTeamMember = async (req, reply) => {
throw boom.boomify(err); throw boom.boomify(err);
} }
}; };
exports.createstaff = async (request, reply) => {
try {
const { customerId } = request.params;
const { staff } = request.body;
if (!staff || !Array.isArray(staff)) {
return reply.status(400).send({ error: 'Invalid staff data provided' });
}
// Find user by customerId
const user = await User.findOne({ customerId });
if (!user) {
return reply.status(404).send({ error: 'Customer not found' });
}
// Validate each staff entry and append it to the user's staff array
const newStaff = staff.map((member) => ({
name: member.name || null,
phone: member.phone || null,
password: member.password || null,
status: "active", // Default status
}));
// Update the user document with the new staff members
user.staff.staff.push(...newStaff);
// Save the updated user document
await user.save();
reply.send({ message: 'Staff members added successfully', staff: user.staff.staff });
} catch (error) {
console.error('Error creating staff:', error);
reply.status(500).send({ error: 'An error occurred while adding staff' });
}
};
exports.editStaff = async (request, reply) => {
try {
const { customerId, phone } = request.params;
const { name, password } = request.body;
const user = await User.findOne({ customerId, "staff.staff.phone": phone });
if (!user) {
return reply.status(404).send({ error: 'Staff member not found' });
}
const staffMember = user.staff.staff.find(member => member.phone === phone);
staffMember.name = name || staffMember.name;
staffMember.password = password || staffMember.password;
await user.save();
reply.send({ message: 'Staff member updated successfully', staff: staffMember });
} catch (error) {
console.error('Error updating staff member:', error);
reply.status(500).send({ error: 'An error occurred while updating staff' });
}
};
exports.deleteStaff = async (request, reply) => {
try {
const { customerId, phone } = request.params;
const user = await User.findOne({ customerId });
if (!user) {
return reply.status(404).send({ error: 'Customer not found' });
}
const initialLength = user.staff.staff.length;
user.staff.staff = user.staff.staff.filter(member => member.phone !== phone);
if (initialLength === user.staff.staff.length) {
return reply.status(404).send({ error: 'Staff member not found' });
}
await user.save();
reply.send({ message: 'Staff member deleted successfully' });
} catch (error) {
console.error('Error deleting staff member:', error);
reply.status(500).send({ error: 'An error occurred while deleting staff' });
}
};
exports.blockStaff = async (request, reply) => {
try {
const { customerId, phone } = request.params;
const user = await User.findOne({ customerId, "staff.staff.phone": phone });
if (!user) {
return reply.status(404).send({ error: 'Staff member not found' });
}
const staffMember = user.staff.staff.find(member => member.phone === phone);
staffMember.status = 'blocked';
await user.save();
reply.send({ message: 'Staff member blocked successfully', staff: staffMember });
} catch (error) {
console.error('Error blocking staff member:', error);
reply.status(500).send({ error: 'An error occurred while blocking staff' });
}
};

@ -5,6 +5,8 @@ const Message = require("../models/Message");
const generator = require("generate-password"); const generator = require("generate-password");
const bcrypt = require("bcrypt"); const bcrypt = require("bcrypt");
const saltRounds = 10; const saltRounds = 10;
const jwt = require('jsonwebtoken')
const JWT_SECRET = 'your-secret-key';
// External Dependancies // External Dependancies
// offers http-friendly error objects. // offers http-friendly error objects.
@ -308,61 +310,212 @@ exports.fieldCheck = async (req, reply) => {
exports.verifyPhone = async (req, reply) => { exports.verifyPhone = async (req, reply) => {
console.log("-------------------------------------------------"); console.log("-------------------------------------------------");
try { try {
phone = req.body.phone; const { phone, phoneVerificationCode } = req.body;
phoneVerificationCode = req.body.phoneVerificationCode;
// check if user exists in the system. If user exists , display message that
// username is not available
console.log( console.log(
"this is the phone and verification code", "Received phone and verification code:",
phone, phone,
phoneVerificationCode phoneVerificationCode
); );
userExists = await User.findOne({
phone: phone, // Check if the user exists
phoneVerified: false, const userExists = await User.findOne({
phoneVerificationCode: phoneVerificationCode, phone,
phoneVerificationCode,
// phoneVerified: false,
}); });
console.log(userExists);
console.log("Matching user:", userExists);
if (userExists) { if (userExists) {
// update the phoneVerified flag to true. // Update the phoneVerified flag to true
const filter = { const filter = { phone, phoneVerificationCode };
phone: phone, const update = { $set: { phoneVerified: true } };
phoneVerificationCode: phoneVerificationCode,
}; const doc = await User.findOneAndUpdate(filter, update, { new: true });
const update = { phoneVerified: true };
const doc = await User.findOneAndUpdate(filter, update);
updatedUser = await User.findOne({ phone: phone });
if (updatedUser.phoneVerified) { console.log("Updated user:", doc);
reply.send('{"armintatankdata":{"error":false,"verified": true}}');
if (doc && doc.phoneVerified) {
reply.send({ doc,
armintatankdata: {
error: false,
verified: true,
},
});
} else { } else {
error = { reply.send({
armintatankdata: { armintatankdata: {
error: true, error: true,
code: 10005, code: 10005,
message: "10005 - Verification code entered cannot be validated.", message: "10005 - Verification code entered cannot be validated.",
}, },
}; });
req.body.regError = error;
reply.send(error);
} }
} else { } else {
error = { reply.send({
armintatankdata: { armintatankdata: {
error: true, error: true,
code: 10005, code: 10005,
message: "10005 - Verification code entered cannot be validated.", message: "10005 - Verification code entered cannot be validated.",
}, },
}; });
req.body.regError = error;
reply.send(error);
} }
} catch (err) { } catch (err) {
console.error("Error in verifyPhone:", err);
throw boom.boomify(err); throw boom.boomify(err);
} }
}; };
exports.changePassword = async (req, reply) => {
try {
const { phone, newPassword, confirmPassword } = req.body;
// Check if newPassword and confirmPassword match
if (newPassword !== confirmPassword) {
return reply.send({
armintatankdata: {
error: true,
code: 10010,
message: "Passwords do not match.",
},
});
}
// Hash the new password
const hash = await bcryptPassword(newPassword);
// Check if user exists
const userExists = await User.findOne({ phone });
if (!userExists) {
return reply.send({
armintatankdata: {
error: true,
code: 10009,
message: "User not found.",
},
});
}
// Update the password in the database
const updateResult = await User.updateOne(
{ phone },
{
$set: {
"services.password.bcrypt": hash,
oneTimePasswordSetFlag: false,
},
}
);
// Check the result of the update operation
if (updateResult.nModified > 0) {
// Fetch the updated user data (excluding password)
const updatedUser = await User.findOne({ phone }).select('-services.password.bcrypt');
// Generate a new token for the user
const token = jwt.sign(
{ id: updatedUser._id, phone: updatedUser.phone }, // You can include more user details if needed
JWT_SECRET, // Use your secret key from environment variables
{ expiresIn: '1h' } // Token expiration time
);
return reply.send({
simplydata: {
error: false,
passwordChanged: true,
userData: updatedUser, // Include updated user data
token, // Include the token in the response
message: "Password updated successfully.",
},
});
} else {
return reply.send({
simplydata: {
error: true,
code: 10011,
message: "Failed to update the password. Try again.",
},
});
}
} catch (err) {
console.error("Error in changePassword:", err);
throw boom.boomify(err);
}
};
exports.verifyOldNewPassword = async (req, reply) => {
try {
const { phone, oldPassword, newPassword } = req.body;
// Check if the user exists with the provided mobile number
const user = await User.findOne({ phone });
if (!user) {
return reply.send({
armintatankdata: {
error: true,
code: 10009,
message: "User not found.",
},
});
}
// Verify the old password
const isOldPasswordCorrect = await bcrypt.compare(oldPassword, user.services.password.bcrypt);
if (!isOldPasswordCorrect) {
return reply.send({
armintatankdata: {
error: true,
code: 10012,
message: "Old password is incorrect.",
},
});
}
// Hash the new password
const hashedNewPassword = await bcrypt.hash(newPassword, 10); // Ensure you use bcrypt.hash here
// Update the password in the database
const updateResult = await User.updateOne(
{ phone },
{
$set: {
"services.password.bcrypt": hashedNewPassword,
oneTimePasswordSetFlag: false,
},
}
);
// Check if the update was successful
if (updateResult.nModified > 0) {
// Fetch the updated user details to send back in the response
const updatedUser = await User.findOne({ phone }).select('-services.password.bcrypt'); // Exclude the password
return reply.send({
armintatankdata: {
error: false,
message: "Password changed successfully.",
updatedUser, // Include the updated user details
},
});
} else {
return reply.send({
armintatankdata: {
error: true,
code: 10011,
message: "Failed to update the password. Try again.",
},
});
}
} catch (err) {
console.error("Error in changePassword:", err);
throw boom.boomify(err);
}
};
exports.sendPhoneVerificationCode = async (req, reply) => { exports.sendPhoneVerificationCode = async (req, reply) => {
// Setting a regError in request so a user is not sent a verificaiton code if registration is not successful // Setting a regError in request so a user is not sent a verificaiton code if registration is not successful
// checkign if regError property is available in the req body, if it exists , do not send the message // checkign if regError property is available in the req body, if it exists , do not send the message
@ -603,7 +756,7 @@ exports.resetPassword = async (req, reply) => {
userExists = await User.findOne({ userExists = await User.findOne({
phone: phone, phone: phone,
// phoneVerificationCode: phoneVerificationCode, phoneVerificationCode: phoneVerificationCode,
}); });
console.log("userExists===", userExists); console.log("userExists===", userExists);
if (userExists) { if (userExists) {
@ -611,7 +764,7 @@ exports.resetPassword = async (req, reply) => {
const filter = { const filter = {
phone: phone, phone: phone,
//phoneVerificationCode: phoneVerificationCode, phoneVerificationCode: phoneVerificationCode,
}; };
console.log("filter", filter); console.log("filter", filter);

@ -41,6 +41,9 @@ const generateBookingId = async () => {
return result.seq; return result.seq;
}; };
const userSchema = new mongoose.Schema( const userSchema = new mongoose.Schema(
{ {
installationId:{type:String}, installationId:{type:String},
@ -57,6 +60,23 @@ const userSchema = new mongoose.Schema(
emails: [{ email: String, verified: { type: Boolean, default: false } }], emails: [{ email: String, verified: { type: Boolean, default: false } }],
services: { password: { bcrypt: String } }, services: { password: { bcrypt: String } },
survey_status:{ type:String,default: "pending" }, survey_status:{ type:String,default: "pending" },
staff: {
staff: [
{
name: { type: String },
phone: { type: String },
password: { type: String, default: null },
status: { type: String, default: "active" },
}
],
},
profile: { profile: {
role: [{ type: String, default: "user" }], role: [{ type: String, default: "user" }],
firstName: { type: String, default: null }, firstName: { type: String, default: null },

@ -1138,6 +1138,35 @@ fastify.get("/api/getbatchnumbers/:storeId/:type", {
handler: storeController.getbatchnumbers, handler: storeController.getbatchnumbers,
}); });
fastify.get("/api/getiots/:storeId/:type", {
schema: {
tags: ["Store-Data"],
description: "This is to Get iots of particular store",
summary: "This is to iots of particular store",
params: {
type: "object",
properties: {
storeId: {
type: "string",
description: "storeId",
},
type: {
type: "string",
description: "type",
},
},
required: ["storeId", "type"],
},
security: [
{
basicAuth: [],
},
],
},
// preHandler: fastify.auth([fastify.authenticate]),
handler: storeController.getiots,
});
fastify.post("/api/createquotationforSensor/:installationId", { fastify.post("/api/createquotationforSensor/:installationId", {
schema: { schema: {

@ -215,6 +215,82 @@ module.exports = function (fastify, opts, next) {
handler: validationHandler.verifyPhone, handler: validationHandler.verifyPhone,
}); });
fastify.route({
method: "POST",
url: "/api/forgot-change-password",
schema: {
tags: ["User"],
description: "After OTP validation Change user password using mobile number and confirmation.",
summary: "After OTP validation Change user password using mobile number and confirmation.",
body: {
type: "object",
required: ["phone", "newPassword", "confirmPassword"],
properties: {
phone: { type: "string" },
newPassword: { type: "string" },
confirmPassword: { type: "string"},
},
},
security: [
{
basicAuth: [],
},
],
},
handler: validationHandler.changePassword,
});
fastify.route({
method: "POST",
url: "/api/change-password",
schema: {
tags: ["User"],
description: "Users to change their password using mobile number, old password, and new password.",
summary: "Users to change their password using mobile number, old password, and new password.",
body: {
type: "object",
required: ["phone", "oldPassword", "newPassword"],
properties: {
phone: { type: "string"},
oldPassword: { type: "string"},
newPassword: { type: "string" },
//confirmPassword: { type: "string", minLength: 6 },
},
},
},
handler: validationHandler.verifyOldNewPassword, // Adjust the path to your handler
});
// fastify.route({
// method: "POST",
// url: "/api/forgotpassword",
// schema: {
// tags: ["User"],
// description: "This is for forget password for the User.",
// summary: "This is for forget User Password.",
// body: {
// type: "object",
// required: ["phone"],
// properties: {
// phone: { type: "string" },
// },
// },
// security: [
// {
// basicAuth: [],
// },
// ],
// },
// // preHandler: [validationHandler.],
// handler: userController.forgotPassword,
// onResponse: (request, reply) => {
// validationHandler.sendPasswordResetCode(request, reply);
// },
// });
fastify.route({ fastify.route({
method: "POST", method: "POST",
url: "/api/forgotpassword", url: "/api/forgotpassword",
@ -235,11 +311,7 @@ module.exports = function (fastify, opts, next) {
}, },
], ],
}, },
// preHandler: [validationHandler.],
handler: userController.forgotPassword, handler: userController.forgotPassword,
onResponse: (request, reply) => {
validationHandler.sendPasswordResetCode(request, reply);
},
}); });
@ -279,10 +351,10 @@ module.exports = function (fastify, opts, next) {
summary: "This is for Reset User Password.", summary: "This is for Reset User Password.",
body: { body: {
type: "object", type: "object",
required: ["phone", "resetPasswordCode", "newPassword"], //required: ["phone", "passwordResetCode", "newPassword"],
properties: { properties: {
phone: { type: "string" }, phone: { type: "string" },
resetPasswordCode: { type: "string" }, phoneVerificationCode: { type: "string" },
newPassword: { type: "string" }, newPassword: { type: "string" },
}, },
}, },
@ -719,5 +791,118 @@ module.exports = function (fastify, opts, next) {
}); });
fastify.route({
method: "POST",
url: "/api/createstaff/:customerId",
schema: {
tags: ["User"],
description: "This is for cretae New staff",
summary: "This is for cretae New staff",
params: {
required: ["customerId"],
type: "object",
properties: {
customerId: {
type: "string",
description: "customerId",
},
},
},
body: {
type: "object",
properties: {
staff: {
type: "array",
maxItems: 2500,
items: {
type: "object",
properties: {
name: { type: "string", default: null },
phone: { type: "string", default: null },
password:{ type: "string" ,default: null},
},
},
},
},
},
security: [
{
basicAuth: [],
},
],
},
//preHandler: fastify.auth([fastify.authenticate]),
handler: userController.createstaff,
});
fastify.route({
method: "PUT",
url: "/api/editstaff/:customerId/:phone",
schema: {
tags: ["User"],
description: "Edit an existing staff member",
params: {
type: "object",
properties: {
customerId: { type: "string", description: "Customer ID" },
phone: { type: "string", description: "Staff phone number" }
},
required: ["customerId", "phone"]
},
body: {
type: "object",
properties: {
name: { type: "string" },
password: { type: "string" }
},
required: ["name", "password"]
}
},
handler: userController.editStaff,
});
fastify.route({
method: "DELETE",
url: "/api/deletestaff/:customerId/:phone",
schema: {
tags: ["User"],
description: "Delete a staff member",
params: {
type: "object",
properties: {
customerId: { type: "string", description: "Customer ID" },
phone: { type: "string", description: "Staff phone number" }
},
required: ["customerId", "phone"]
}
},
handler: userController.deleteStaff,
});
fastify.route({
method: "PATCH",
url: "/api/blockstaff/:customerId/:phone",
schema: {
tags: ["User"],
description: "Block a staff member by phone",
params: {
type: "object",
properties: {
customerId: { type: "string", description: "Customer ID" },
phone: { type: "string", description: "Staff phone number" }
},
required: ["customerId", "phone"]
}
},
handler: userController.blockStaff,
});
next(); next();
}; };

Loading…
Cancel
Save