You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1123 lines
32 KiB

const boom = require("boom");
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const customJwtAuth = require("../customAuthJwt");
const fastify = require("fastify")({
logger: true,
//disableRequestLogging: true,
genReqId(req) {
// you get access to the req here if you need it - must be a synchronous function
return uuidv4();
},
});
const { Install, ProfilePictureInstall, SensorQuotation,generateinstallationId,Store,WaterLeverSensor,MotorSwitchSenso,Insensors} = require("../models/store");
const { User,Counter, generateBookingId,resetCounter,generateCustomerId,ProfilePicture} = require('../models/User')
exports.installSignUp = async (request, reply) => {
try {
const i_id = await generateinstallationId();
const installationId = `AWIN${i_id}`;
const {
// name,
phone,
address,
address1,
address2,
emails,
password,
profile,
team,
manager,
longitude,
latitude,
fcmId,
alternativeNumber,
firstName,
lastName,
city,
createdBy,
updatedBy,
} = request.body;
// Check if a user with the same phone number already exists
const existingInstall = await Install.findOne({ phone });
if (existingInstall) {
return reply.status(400).send({ message: 'Phone is already registered' });
}
// Hash the password using bcrypt
const hashedPassword = await bcrypt.hash(password, 10);
// Create a new install object with the hashed password and other details
const install = new Install({
// name,
installationId,
phone,
address,
address1,
address2,
emails,
services: { password: { bcrypt: hashedPassword } },
profile,
team,
manager,
longitude,
latitude,
fcmId,
alternativeNumber,
firstName,
lastName,
city,
createdBy,
updatedBy,
});
// Save the new install to the database
await install.save();
reply.send({ message: 'Install Account Created Successfully' });
} catch (err) {
reply.status(500).send({ message: err.message });
}
};
// exports.installLogin = async (request, reply) => {
// try {
// const { phone, password } = request.body;
// // Check if an install with the phone number exists
// const install = await Install.findOne({ phone });
// if (!install) {
// return reply.status(401).send({
// simplydata: {
// error: true,
// message: 'Invalid Phone or password'
// }
// });
// }
// // Compare the password entered by the user with the hashed password stored in the database
// const isPasswordValid = await bcrypt.compare(password, install.services.password.bcrypt);
// if (!isPasswordValid) {
// return reply.status(401).send({
// simplydata: {
// error: true,
// message: 'Invalid phone or password'
// }
// });
// }
// // Generate a JWT token for the authenticated install
// const token = fastify.jwt.sign({ phone: install.phone }, 'your_jwt_secret', { expiresIn: '30d' });
// // Fetch the profile picture if it exists
// const profilePicture = await ProfilePictureInstall.findOne({ customerId: install._id });
// const responsePayload = {
// simplydata: {
// error: false,
// apiversion: fastify.config.APIVERSION,
// access_token: token,
// email: install.emails,
// installationId: install.installationId,
// phone: install.phone,
// address1: install.address1,
// address2: install.address2,
// phoneVerified: install.phoneVerified,
// oneTimePasswordSetFlag: install.oneTimePasswordSetFlag,
// type: install.profile.role,
// fcmId: install.fcmId,
// team: install.team,
// city: install.city,
// manager: install.manager,
// firstName: install.firstName,
// lastName: install.lastName,
// address: install.address,
// alternativeNumber: install.alternativeNumber,
// }
// };
// if (profilePicture) {
// responsePayload.simplydata.picture = profilePicture.picture;
// }
// // Return the token and user details to the client
// return reply.send(responsePayload);
// } catch (err) {
// reply.status(500).send({
// simplydata: {
// error: true,
// message: err.message
// }
// });
// }
// };
exports.installationVerifyPhone = async (req, reply) => {
console.log("-------------------------------------------------");
try {
phone = req.body.phone;
phoneVerificationCode = req.body.phoneVerificationCode;
// check if user exists in the system. If user exists , display message that
// username is not available
console.log(
"this is the phone and verification code",
phone,
phoneVerificationCode
);
deliveryBoyExists = await Install.findOne({
phone: phone,
//phoneVerified: false,
phoneVerificationCode: phoneVerificationCode,
});
console.log(deliveryBoyExists);
if (deliveryBoyExists) {
// update the phoneVerified flag to true.
const filter = {
phone: phone,
phoneVerificationCode: phoneVerificationCode,
};
const update = { phoneVerified: true };
const doc = await Install.findOneAndUpdate(filter, update);
updatedDeliveryBoy = await Install.findOne({ phone: phone });
if (updatedDeliveryBoy.phoneVerified) {
loginObject = await supplierController.loginInstallation(req);
console.log("loginObject...", loginObject);
if (loginObject.same) {
const phoneVerified = loginObject.delivery.phoneVerified;
const oneTimePasswordSetFlag =
loginObject.delivery.oneTimePasswordSetFlag;
console.log(
"oneTimePasswordSetFlag is ......",
oneTimePasswordSetFlag,
typeof oneTimePasswordSetFlag,
typeof phoneVerified
);
if (!phoneVerified) {
reply.send({
simplydata: {
error: false,
phoneVerified: false,
phone: loginObject.delivery.phone,
oneTimePasswordSetFlag: oneTimePasswordSetFlag,
message: "Please Verify your phone number",
},
});
} else if (oneTimePasswordSetFlag) {
reply.send({
simplydata: {
error: false,
phoneVerified: phoneVerified,
phone: loginObject.delivery.phone,
oneTimePasswordSetFlag: true,
message: "Password must be reset",
},
});
} else {
const token = fastify.jwt.sign(
{
name: loginObject.delivery.name,
},
//expiresIn: expressed in seconds or a string describing a time span zeit/ms. Eg: 60, "2 days", "10h", "7d".
//A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc),
//otherwise milliseconds unit is used by default ("120" is equal to "120ms").
{ expiresIn: "30d" }
);
console.log(token, "..token");
var d_id = loginObject.delivery._id;
console.log(d_id, "deliveryId");
var profilePicture = await ProfilePictureInstall.findOne({
installationId: d_id,
});
// request.session.set('supplierId', loginObject.supplier._id)
if (!profilePicture) {
reply.send({
simplydata: {
error: false,
apiversion: fastify.config.APIVERSION,
access_token: token,
phone: loginObject.delivery.phone,
installationId: loginObject.delivery.installationId,
name: loginObject.delivery.name,
address: loginObject.delivery.address,
phoneVerified: loginObject.delivery.phoneVerified,
oneTimePasswordSetFlag:
loginObject.delivery.oneTimePasswordSetFlag,
},
});
}
if (profilePicture) {
reply.send({
simplydata: {
error: false,
apiversion: fastify.config.APIVERSION,
access_token: token,
picture: profilePicture.picture,
phone: loginObject.delivery.phone,
installationId: loginObject.delivery.installationId,
name: loginObject.delivery.name,
address: loginObject.delivery.address,
phoneVerified: loginObject.delivery.phoneVerified,
oneTimePasswordSetFlag:
loginObject.delivery.oneTimePasswordSetFlag,
},
});
}
}
} else {
error = {
simplydata: {
error: true,
code: 400,
message: "Invalid Details",
},
};
reply.send(error);
}
}
}else {
error = {
armintatankdata: {
error: true,
code: 10005,
message: "10005 - Verification code entered cannot be validated.",
},
};
req.body.regError = error;
reply.send(error);
}
} catch (err) {
throw boom.boomify(err);
}
};
const generateStoreId = async () => {
const result = await Counter.findOneAndUpdate(
{ _id: 'store_id' },
{ $inc: { seq: 1 } },
{ upsert: true, new: true }
);
return result.seq;
};
const saltRounds = 10;
async function bcryptPassword(password) {
encryptedPwd = bcrypt.hash(password, saltRounds);
return encryptedPwd;
}
async function bcryptComparePassword(pwd, encpassword) {
isSame = bcrypt.compare(pwd, encpassword);
return isSame;
}
exports.addStore = async (request, reply) => {
try {
const s_id = await generateStoreId();
const store_id = `AWIN${s_id}`;
const {
// name,
phone,
address,
address1,
address2,
emails,
password,
profile,
longitude,
latitude,
fcmId,
alternativeNumber,
firstName,
lastName,
city,
createdBy,
updatedBy,
} = request.body;
// Check if a user with the same phone number already exists
const existingStore = await Store.findOne({ phone });
if (existingStore) {
return reply.status(400).send({ message: 'Phone is already registered' });
}
// Hash the password using bcrypt
const hashedPassword = await bcrypt.hash(password, 10);
// Create a new install object with the hashed password and other details
const store = new Store({
// name,
store_id,
phone,
address,
address1,
address2,
emails,
services: { password: { bcrypt: hashedPassword } },
profile,
longitude,
latitude,
fcmId,
alternativeNumber,
firstName,
lastName,
city,
createdBy,
updatedBy,
});
// Save the new install to the database
await store.save();
reply.send({ message: 'Install Account Created Successfully' });
} catch (err) {
reply.status(500).send({ message: err.message });
}
}
// exports.addStore = async (req, reply) => {
// try {
// const { storename, password, phone, emails } = req.body;
// if (!emails) {
// return reply.status(400).send({ error: 'Email is required and cannot be null.' });
// }
// var s_id = await generateStoreId();
// var building = storename.slice(0, 3).toUpperCase();
// var store_id = `AWSST${building}${s_id}`;
// const s_data = {
// storeId: store_id,
// storename,
// emails: emails.trim(),
// password,
// phone,
// description: req.body.description,
// profile: {
// firstName: req.body.firstName,
// lastName: req.body.lastName,
// contactNumber: phone,
// alternativeContactNumber: req.body.alternativeContactNumber,
// office_address: req.body.office_address,
// country: req.body.country,
// state: req.body.state,
// city: req.body.city,
// zip: req.body.zip,
// },
// latitude: req.body.latitude,
// longitude: req.body.longitude,
// fcmId: req.body.fcmId,
// };
// var store = new Store(s_data);
// var storepass = password;
// // Store hash in your password DB.
// var hash = await bcryptPassword(storepass);
// if (hash) {
// store.services.password.bcrypt = hash;
// store.profile.role = req.body.role || ["store"];
// var insertedStore = await Store.save();
// if (insertedStore) {
// var retStore = {
// armintatankdata: {
// storename: insertedStore.storename,
// phone: insertedStore.phone,
// storeId: insertedStore.storeId,
// office_address: insertedStore.profile.office_address,
// emails: insertedStore.emails,
// profile: insertedStore.profile,
// latitude: insertedStore.latitude,
// longitude: insertedStore.longitude,
// fcmId: insertedStore.fcmId,
// description: insertedStore.description,
// },
// status_code: 200,
// };
// return reply.status(200).send(retStore);
// }
// }
// } catch (err) {
// if (err.code === 11000) {
// // Handle duplicate key error
// return reply.status(400).send({ error: 'Duplicate key error', message: err.message });
// }
// throw boom.boomify(err);
// }
// };
const generatewaterlevelsensorId = async () => {
const result = await Counter.findOneAndUpdate(
{ _id: 'waterlevelsensor_id' },
{ $inc: { seq: 1 } },
{ upsert: true, new: true }
);
return result.seq;
};
const generatewaterlevelslavesensorId = async () => {
const result = await Counter.findOneAndUpdate(
{ _id: 'waterlevelslavesensor_id' },
{ $inc: { seq: 1 } },
{ upsert: true, new: true }
);
return result.seq;
};
const moment = require('moment');
exports.createwaterlevelSensor = async (req, reply) => {
try {
const storeId = req.params.storeId
const { hardwareId,hardwareId_company, type, indate } = req.body;
var mater_seq_id = await generatewaterlevelsensorId();
const date = moment().format('MM-DD');
const prefix = 'AS' + date + 'MALOV1';
var masterId = `${prefix}${mater_seq_id}`;
const newSensor = new WaterLeverSensor({
storeId,
hardwareId,
masterId,
type,
indate
});
const savedSensor = await newSensor.save();
reply.code(200).send(savedSensor);
} catch (err) {
reply.code(500).send(err);
}
};
exports.editWaterLevelSensor = async (req, reply) => {
try {
const { storeId } = req.params;
const updates = req.body;
const updatedSensor = await WaterLeverSensor.findOneAndUpdate(
{ storeId:storeId,hardwareId: req.body.hardwareId },
updates,
{ new: true }
);
if (!updatedSensor) {
reply.code(404).send({ message: "Sensor not found" });
} else {
reply.code(200).send(updatedSensor);
}
} catch (err) {
reply.code(500).send(err);
}
};
exports.deleteWaterLevelSensor = async (req, reply) => {
try {
const { storeId } = req.params;
const deletedSensor = await WaterLeverSensor.findOneAndDelete(
{ storeId,hardwareId: req.body.hardwareId }
);
if (!deletedSensor) {
reply.code(404).send({ message: "Sensor not found" });
} else {
reply.code(200).send({ message: "Sensor deleted successfully" });
}
} catch (err) {
reply.code(500).send(err);
}
};
exports.installwaterlevelSensor = async (request, reply) => {
try {
const { storeId } = request.params;
const updateData = request.body;
// Find the document by hardwareId and update it with the fields received in the body
const updatedSensor = await WaterLeverSensor.findOneAndUpdate(
{ storeId:storeId,hardwareId: request.body.hardwareId, },
{ $set: updateData },
{ new: true } // Return the updated document
);
if (!updatedSensor) {
return reply.status(404).send({ error: 'Sensor not found' });
}
return reply.status(200).send(updatedSensor);
} catch (error) {
console.error(error);
return reply.status(500).send({ error: 'An error occurred while updating the sensor' });
}
};
exports.qccheckwaterlevelSensor = async (request, reply) => {
try {
const { hardwareId } = request.params;
const updateData = request.body;
// Find the document by hardwareId and update it with the fields received in the body
const updatedSensor = await WaterLeverSensor.findOneAndUpdate(
{ hardwareId: hardwareId },
{ $set: updateData },
{ new: true } // Return the updated document
);
if (!updatedSensor) {
return reply.status(404).send({ error: 'Sensor not found' });
}
return reply.status(200).send(updatedSensor);
} catch (error) {
console.error(error);
return reply.status(500).send({ error: 'An error occurred while updating the sensor' });
}
};
exports.getHardware = async (req, reply) => {
try {
await WaterLeverSensor.find({storeId: req.params.storeId})
.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.getHardwaremotorswitch = async (req, reply) => {
try {
await MotorSwitchSensor.find({storeId: req.params.storeId})
.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.getHardwareqc = async (req, reply) => {
try {
await WaterLeverSensor.find({storeId: req.params.storeId,hardwareId:req.body.hardwareId})
.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.addSlave = async (req, reply) => {
try {
const hardwareId = req.params.hardwareId;
const { tankhardwareId, type, indate, hardwareId_company } = req.body;
// Find the main hardware by hardwareId
const mainHardware = await WaterLeverSensor.findOne({ hardwareId });
if (!mainHardware) {
reply.code(404).send({ message: "Main hardware not found" });
return;
}
// Check if the slave's hardwareId already exists
const existingSlave = mainHardware.slaves.tankhardware.find(slave => slave.tankhardwareId === tankhardwareId);
if (existingSlave) {
reply.code(400).send({ message: "Slave hardware ID already exists for this main hardware" });
return;
}
var slave_seq_id = await generatewaterlevelslavesensorId();
const date = moment().format('MM-DD');
const prefix = 'AS' + date + 'SLAOV1';
var slaveId = `${prefix}${slave_seq_id}`;
// Create new slave
const newSlave = {
tankhardwareId,
slaveId: slaveId,
type,
indate,
hardwareId_company
};
// Add the new slave to the main hardware's slaves array
mainHardware.slaves.tankhardware.push(newSlave);
// Save the updated main hardware
const updatedHardware = await mainHardware.save();
reply.code(200).send(updatedHardware);
} catch (err) {
reply.code(500).send(err);
}
};
exports.editSlave = async (req, reply) => {
try {
const { hardwareId } = req.params;
const updates = req.body;
const mainHardware = await WaterLeverSensor.findOne({ hardwareId });
if (!mainHardware) {
reply.code(404).send({ message: "Main hardware not found" });
return;
}
const slaveIndex = mainHardware.slaves.tankhardware.findIndex(
(slave) => slave.tankhardwareId === req.body.tankhardwareId
);
if (slaveIndex === -1) {
reply.code(404).send({ message: "Slave not found" });
return;
}
mainHardware.slaves.tankhardware[slaveIndex] = {
...mainHardware.slaves.tankhardware[slaveIndex],
...updates,
};
const updatedHardware = await mainHardware.save();
reply.code(200).send(updatedHardware);
} catch (err) {
reply.code(500).send(err);
}
};
exports.deleteSlave = async (req, reply) => {
try {
const { hardwareId } = req.params;
const mainHardware = await WaterLeverSensor.findOne({ hardwareId });
if (!mainHardware) {
reply.code(404).send({ message: "Main hardware not found" });
return;
}
const slaveIndex = mainHardware.slaves.tankhardware.findIndex(
(slave) => slave.tankhardwareId === req.body.tankhardwareId
);
if (slaveIndex === -1) {
reply.code(404).send({ message: "Slave not found" });
return;
}
mainHardware.slaves.tankhardware.splice(slaveIndex, 1);
const updatedHardware = await mainHardware.save();
reply.code(200).send(updatedHardware);
} catch (err) {
reply.code(500).send(err);
}
};
exports.qccheckwaterlevelSensorSlave = async (request, reply) => {
try {
const { storeId } = request.params;
const updateData = request.body;
// Find the document by storeId and tankhardwareId, and update the corresponding slave
const updatedSensor = await WaterLeverSensor.findOneAndUpdate(
{
storeId: storeId,
hardwareId:request.body.hardwareId,
"slaves.tankhardware.tankhardwareId": request.body.tankhardwareId
},
{
$set: {
"slaves.tankhardware.$.qccheck": updateData.qccheck,
"slaves.tankhardware.$.qccheckdate": updateData.qccheckdate,
"slaves.tankhardware.$.qcby": updateData.qcby,
"slaves.tankhardware.$.comment": updateData.comment,
"slaves.tankhardware.$.outforrepairdate": updateData.outforrepairdate,
"slaves.tankhardware.$.sendto": updateData.sendto,
"slaves.tankhardware.$.repairfeedback": updateData.repairfeedback
}
},
{ new: true } // Return the updated document
);
if (!updatedSensor) {
return reply.status(404).send({ error: 'Slave not found' });
}
return reply.status(200).send(updatedSensor);
} catch (error) {
console.error(error);
return reply.status(500).send({ error: 'An error occurred while updating the slave' });
}
};
exports.installwaterlevelSensorSlave = async (request, reply) => {
try {
const { storeId } = request.params;
const { hardwareId, tankhardwareId, dateofinstallation, customerId, installedby } = request.body;
// Find the document by storeId and hardwareId, then update the specific slave with tankhardwareId
const updatedSensor = await WaterLeverSensor.findOneAndUpdate(
{
storeId: storeId,
hardwareId: hardwareId,
"slaves.tankhardware.tankhardwareId": tankhardwareId
},
{
$set: {
"slaves.tankhardware.$.dateofinstallation": dateofinstallation,
"slaves.tankhardware.$.customerId": customerId,
"slaves.tankhardware.$.installedby": installedby
}
},
{ new: true } // Return the updated document
);
if (!updatedSensor) {
return reply.status(404).send({ error: 'Sensor or Slave not found' });
}
return reply.status(200).send(updatedSensor);
} catch (error) {
console.error(error);
return reply.status(500).send({ error: 'An error occurred while installing the sensor' });
}
};
exports.getHardwareqcslave = async (req, reply) => {
try {
const { storeId } = req.params;
const { hardwareId, tankhardwareId } = req.body;
let query;
if (tankhardwareId) {
// If tankhardwareId is provided, query for the specific slave
query = {
storeId: storeId,
hardwareId: hardwareId,
"slaves.tankhardware.tankhardwareId": tankhardwareId,
};
} else {
// Otherwise, query for the main hardware
query = {
storeId: storeId,
hardwareId: hardwareId,
};
}
const docs = await WaterLeverSensor.find(query).exec();
if (docs.length === 0) {
return reply.status(404).send({ error: 'No hardware found' });
}
reply.send({ status_code: 200, data: docs, count: docs.length });
} catch (err) {
console.error(err);
reply.status(500).send({ error: 'An error occurred while retrieving the hardware QC data' });
}
};
exports.createmotorswitchSensor = async (req, reply) => {
try {
const storeId = req.params.storeId
const { motorId, type, indate } = req.body;
var mater_seq_id = await generatewaterlevelsensorId();
const date = moment().format('MM-DD');
const prefix = 'AS' + date + 'PSV1';
var masterId = `${prefix}${mater_seq_id}`;
const newSensor = new MotorSwitchSensor({
storeId,
motorId,
masterId,
type,
indate
});
const savedSensor = await newSensor.save();
reply.code(200).send(savedSensor);
} catch (err) {
reply.code(500).send(err);
}
};
exports.qccheckmotorswitch = async (request, reply) => {
try {
const { motorId } = request.params;
const updateData = request.body;
// Find the document by hardwareId and update it with the fields received in the body
const updatedSensor = await MotorSwitchSensor.findOneAndUpdate(
{ motorId: motorId },
{ $set: updateData },
{ new: true } // Return the updated document
);
if (!updatedSensor) {
return reply.status(404).send({ error: 'Sensor not found' });
}
return reply.status(200).send(updatedSensor);
} catch (error) {
console.error(error);
return reply.status(500).send({ error: 'An error occurred while updating the sensor' });
}
};
exports.installmotorswitch = async (request, reply) => {
try {
const { storeId } = request.params;
const updateData = request.body;
// Find the document by hardwareId and update it with the fields received in the body
const updatedSensor = await MotorSwitchSensor.findOneAndUpdate(
{ storeId:storeId,motorId: request.body.motorId, },
{ $set: updateData },
{ new: true } // Return the updated document
);
if (!updatedSensor) {
return reply.status(404).send({ error: 'Sensor not found' });
}
return reply.status(200).send(updatedSensor);
} catch (error) {
console.error(error);
return reply.status(500).send({ error: 'An error occurred while updating the sensor' });
}
};
exports.getpumpswitchqc = async (req, reply) => {
try {
await MotorSwitchSensor.find({storeId: req.params.storeId,motorId:req.body.motorId})
.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);
}
};
const generateBatchNo = (type, hardwareIdCompany) => {
const date = new Date();
const ddmmyy = `${date.getDate().toString().padStart(2, '0')}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getFullYear().toString().slice(-2)}`;
const companyPrefix = hardwareIdCompany.slice(0, 2).toUpperCase();
const randomNumbers = Math.floor(100 + Math.random() * 900).toString(); // 3 random digits
if (type === 'slave') {
return `SL${ddmmyy}${companyPrefix}${randomNumbers}`;
}
if (type === 'master') {
return `MA${ddmmyy}${companyPrefix}${randomNumbers}`;
}
if (type === 'motor_switch') {
return `MS${ddmmyy}${companyPrefix}${randomNumbers}`;
}
// Add other type conditions if needed
return null;
};
exports.createSensor = async (req, reply) => {
try {
const storeId = req.params.storeId;
const { indate, batchno, hardwareId_company, quantity, model, type } = req.body;
let finalBatchNo = batchno;
if (batchno === 'new') {
let isUnique = false;
while (!isUnique) {
finalBatchNo = generateBatchNo(type, hardwareId_company);
// Check for uniqueness
const existingBatchNo = await Insensors.findOne({ batchno: finalBatchNo });
if (!existingBatchNo) {
isUnique = true;
}
}
}
const date = moment().format('MM-DD');
let entries = [];
for (let i = 0; i < quantity; i++) {
const newSensor = {
storeId,
model,
batchno: finalBatchNo,
type,
indate,
hardwareId_company
};
entries.push(newSensor);
}
const savedSensors = await Insensors.insertMany(entries);
reply.code(200).send(savedSensors);
} catch (err) {
reply.code(500).send(err);
}
};
exports.getbatchnumbers = async (req, reply) => {
try {
await Insensors.distinct('batchno', { storeId: req.params.storeId })
.then((batchNumbers) => {
reply.send({ status_code: 200, data: batchNumbers, count: batchNumbers.length });
})
.catch((err) => {
console.log(err);
reply.send({ error: err });
});
} catch (err) {
reply.send({ error: err });
}
};
exports.getusersofParticularInstaller = async (req, reply) => {
try {
await User.find({installationId: req.query.InstallerId})
.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.createquotationforSensor = async (req, reply) => {
try {
// Extract parameters and body data from the request
const { installationId } = req.params;
const { customerId, masters, slaves, motor_switches, electricals } = req.body;
// Validate electricals field to ensure it's an array of objects
if (!Array.isArray(electricals) || electricals.some(e => typeof e !== 'object')) {
return reply.code(400).send({
success: false,
message: 'Invalid data format for electricals. It should be an array of objects with "name" and "type".'
});
}
// Create a new SensorQuotation document
const newQuotation = new SensorQuotation({
customerId: customerId,
installationId: installationId, // Using installationId for the field
masters,
slaves,
motor_switches,
electricals, // This will store the array of electrical items (objects)
});
// Save the document to the database
const savedQuotation = await newQuotation.save();
// Send a success response with the saved document
reply.code(201).send({
success: true,
message: 'Quotation for sensors created successfully.',
data: savedQuotation,
});
} catch (error) {
// Handle errors and send error response
console.error('Error creating quotation:', error);
reply.code(500).send({
success: false,
message: 'Failed to create quotation for sensors.',
error: error.message,
});
}
};