ashok 3 months ago
commit 48520b081f

@ -534,6 +534,65 @@ exports.assignTeamMemberToQuotation = async (request, reply) => {
// } // }
// }; // };
// exports.getQuotationsByInstallationAndTeamMember = async (request, reply) => {
// try {
// const { installationId, teamMemberId } = request.params;
// if (!installationId || !teamMemberId) {
// return reply.status(400).send({
// simplydata: {
// error: true,
// message: "Both installationId and teamMemberId are required",
// },
// });
// }
// // 🔹 Find quotations matching installationId and assignedTeamMembers
// const quotations = await Order.find({
// installationId,
// assignedTeamMembers: teamMemberId,
// }).lean(); // use lean() for performance, since we'll enrich manually
// if (!quotations || quotations.length === 0) {
// return reply.status(404).send({
// simplydata: {
// error: true,
// message: "No quotations found for this installation and team member",
// },
// });
// }
// // 🔹 Enrich each quotation with customer details
// const enrichedQuotations = await Promise.all(
// quotations.map(async (quotation) => {
// const customer = await User.findOne({ customerId: quotation.customerId }).lean();
// return {
// ...quotation,
// customer: customer || null, // attach under 'customer'
// };
// })
// );
// return reply.send({
// simplydata: {
// error: false,
// message: "Quotations fetched successfully",
// quotations: enrichedQuotations,
// },
// });
// } catch (err) {
// console.error("Error fetching quotations:", err);
// return reply.status(500).send({
// simplydata: {
// error: true,
// message: "Internal server error",
// },
// });
// }
// };
exports.getQuotationsByInstallationAndTeamMember = async (request, reply) => { exports.getQuotationsByInstallationAndTeamMember = async (request, reply) => {
try { try {
const { installationId, teamMemberId } = request.params; const { installationId, teamMemberId } = request.params;
@ -548,10 +607,10 @@ exports.getQuotationsByInstallationAndTeamMember = async (request, reply) => {
} }
// 🔹 Find quotations matching installationId and assignedTeamMembers // 🔹 Find quotations matching installationId and assignedTeamMembers
const quotations = await Order.find({ let quotations = await Order.find({
installationId, installationId,
assignedTeamMembers: teamMemberId, assignedTeamMembers: teamMemberId,
}).lean(); // use lean() for performance, since we'll enrich manually }).lean();
if (!quotations || quotations.length === 0) { if (!quotations || quotations.length === 0) {
return reply.status(404).send({ return reply.status(404).send({
@ -562,22 +621,43 @@ exports.getQuotationsByInstallationAndTeamMember = async (request, reply) => {
}); });
} }
// ✅ Filter: keep only quotations where at least one master_connections.work_status === 'active'
quotations = quotations.filter(q =>
Array.isArray(q.master_connections) &&
q.master_connections.some(mc => mc.work_status === 'active')
);
// If no quotations left after filtering, return empty list
if (!quotations.length) {
return reply.send({
simplydata: {
error: false,
message: "No active quotations found for this installation and team member",
quotations: [],
},
});
}
// 🔹 Enrich each quotation with customer details // 🔹 Enrich each quotation with customer details
const enrichedQuotations = await Promise.all( const enrichedQuotations = await Promise.all(
quotations.map(async (quotation) => { quotations.map(async (quotation) => {
const customer = await User.findOne({ customerId: quotation.customerId }).lean(); const customer = await User.findOne({ customerId: quotation.customerId }).lean();
// 🔹 Keep only active master_connections
const activeMasters = quotation.master_connections?.filter(mc => mc.work_status === 'active') || [];
return { return {
...quotation, ...quotation,
customer: customer || null, // attach under 'customer' master_connections: activeMasters,
customer: customer || null,
}; };
}) })
); );
return reply.send({ return reply.send({
simplydata: { simplydata: {
error: false, error: false,
message: "Quotations fetched successfully", message: "Active quotations fetched successfully",
quotations: enrichedQuotations, quotations: enrichedQuotations,
}, },
}); });

@ -2711,21 +2711,27 @@ exports.getOrdersByInstallationId = async (req, reply) => {
}; };
exports.getPendingOrdersByInstallationId = async (req, reply) => { exports.getPendingOrdersByInstallationAndTeamMember = async (req, reply) => {
try { try {
const { installationId } = req.params; const { installationId, teamMemberId } = req.params;
if (!installationId) { if (!installationId) {
return reply.status(400).send({ error: "installationId is required" }); return reply.status(400).send({ error: "installationId is required" });
} }
if (!teamMemberId) {
return reply.status(400).send({ error: "teamMemberId is required" });
}
// Fetch orders with the matching installationId // Fetch orders matching installationId and assignedTeamMembers
const orders = await Order.find({ installationId }); const orders = await Order.find({
installationId,
assignedTeamMembers: teamMemberId
});
if (!orders.length) { if (!orders.length) {
return reply.send({ return reply.send({
status_code: 200, status_code: 200,
message: "No orders found for this installation", message: "No orders found for this installation and team member",
data: [], data: [],
}); });
} }
@ -2739,22 +2745,23 @@ exports.getPendingOrdersByInstallationId = async (req, reply) => {
} }
} }
// Only keep one order per customerId
let uniqueOrders = Array.from(uniqueCustomersMap.values()); let uniqueOrders = Array.from(uniqueCustomersMap.values());
// ✅ Filter: keep only those where work_status is "pending" // ✅ Filter orders that have at least one pending master_connection
uniqueOrders = uniqueOrders.filter(order => order.work_status === 'pending'); uniqueOrders = uniqueOrders.filter(order =>
Array.isArray(order.master_connections) &&
order.master_connections.some(mc => mc.work_status === 'pending')
);
// If nothing left after filtering, return empty
if (!uniqueOrders.length) { if (!uniqueOrders.length) {
return reply.send({ return reply.send({
status_code: 200, status_code: 200,
message: "No pending orders found for this installation", message: "No pending orders found for this installation and team member",
data: [], data: [],
}); });
} }
// Enrich with customer and sensor info // Enrich and also filter master_connections inside each order
const ordersWithDetails = await Promise.all( const ordersWithDetails = await Promise.all(
uniqueOrders.map(async (order) => { uniqueOrders.map(async (order) => {
const customer = await User.findOne({ customerId: order.customerId }).lean(); const customer = await User.findOne({ customerId: order.customerId }).lean();
@ -2765,8 +2772,12 @@ exports.getPendingOrdersByInstallationId = async (req, reply) => {
status: "blocked", status: "blocked",
}).lean(); }).lean();
// Keep only master_connections with work_status === 'pending'
const pendingMasters = order.master_connections.filter(mc => mc.work_status === 'pending');
return { return {
...order.toObject(), ...order.toObject(),
master_connections: pendingMasters,
customer: customer || null, customer: customer || null,
allocated_sensors: allocatedSensors, allocated_sensors: allocatedSensors,
}; };
@ -2780,11 +2791,13 @@ exports.getPendingOrdersByInstallationId = async (req, reply) => {
}); });
} catch (err) { } catch (err) {
console.error("Error fetching orders:", err); console.error("Error fetching pending orders:", err);
return reply.status(500).send({ error: "Internal server error" }); return reply.status(500).send({ error: "Internal server error" });
} }
}; };
exports.getCompleteOrdersByInstallationId = async (req, reply) => { exports.getCompleteOrdersByInstallationId = async (req, reply) => {
try { try {
const { installationId } = req.params; const { installationId } = req.params;
@ -2991,7 +3004,7 @@ exports.getCompleteOrdersByInstallationId = async (req, reply) => {
exports.updateWorkStatusByInstallationId = async (req, reply) => { exports.updateWorkStatusByInstallationId = async (req, reply) => {
try { try {
const { installationId, customerId } = req.params; const { installationId, customerId, teamMemberId } = req.params;
const { work_status, hardwareId } = req.body; const { work_status, hardwareId } = req.body;
if (!installationId) { if (!installationId) {
@ -3000,6 +3013,9 @@ exports.updateWorkStatusByInstallationId = async (req, reply) => {
if (!customerId) { if (!customerId) {
return reply.status(400).send({ error: "customerId is required" }); return reply.status(400).send({ error: "customerId is required" });
} }
if (!teamMemberId) {
return reply.status(400).send({ error: "teamMemberId is required" });
}
if (!hardwareId) { if (!hardwareId) {
return reply.status(400).send({ error: "hardwareId is required" }); return reply.status(400).send({ error: "hardwareId is required" });
} }
@ -3007,36 +3023,47 @@ exports.updateWorkStatusByInstallationId = async (req, reply) => {
return reply.status(400).send({ error: "Valid work_status is required: active, pending or complete" }); return reply.status(400).send({ error: "Valid work_status is required: active, pending or complete" });
} }
// ✅ Correct query // ✅ Find orders that match installationId, customerId, assignedTeamMembers, and master_connections.hardwareId
const orders = await Order.find({ const orders = await Order.find({
installationId, installationId,
customerId, customerId,
assignedTeamMembers: teamMemberId,
'master_connections.hardwareId': hardwareId 'master_connections.hardwareId': hardwareId
}); });
if (!orders.length) { if (!orders.length) {
return reply.send({ return reply.send({
status_code: 200, status_code: 200,
message: "No orders found for this installation, customer and hardwareId", message: "No orders found for this installation, customer, team member, and hardwareId",
data: [], data: [],
}); });
} }
// Update work_status // 🔧 Update work_status in master_connections inside each order
for (const order of orders) { for (const order of orders) {
order.work_status = work_status; let modified = false;
if (Array.isArray(order.master_connections)) {
for (const mc of order.master_connections) {
if (mc.hardwareId === hardwareId) {
mc.work_status = work_status;
modified = true;
}
}
}
if (modified) {
await order.save(); await order.save();
} }
}
// Fetch updated orders // Fetch updated orders to return
const updatedOrders = await Order.find({ const updatedOrders = await Order.find({
installationId, installationId,
customerId, customerId,
'master_connections.hardwareId': hardwareId, assignedTeamMembers: teamMemberId,
work_status 'master_connections.hardwareId': hardwareId
}); }).lean();
// Enrich data // 🔹 Enrich each order with customer and allocated sensors
const ordersWithDetails = await Promise.all( const ordersWithDetails = await Promise.all(
updatedOrders.map(async (order) => { updatedOrders.map(async (order) => {
const customer = await User.findOne({ customerId: order.customerId }).lean(); const customer = await User.findOne({ customerId: order.customerId }).lean();
@ -3047,7 +3074,7 @@ exports.updateWorkStatusByInstallationId = async (req, reply) => {
}).lean(); }).lean();
return { return {
...order.toObject(), ...order,
customer: customer || null, customer: customer || null,
allocated_sensors: allocatedSensors, allocated_sensors: allocatedSensors,
}; };
@ -3056,7 +3083,7 @@ exports.updateWorkStatusByInstallationId = async (req, reply) => {
return reply.send({ return reply.send({
status_code: 200, status_code: 200,
message: `Orders updated to work_status '${work_status}' successfully`, message: `Orders updated: master_connections with hardwareId '${hardwareId}' now has work_status '${work_status}'`,
data: ordersWithDetails, data: ordersWithDetails,
}); });
@ -3071,6 +3098,7 @@ exports.updateWorkStatusByInstallationId = async (req, reply) => {
exports.getallocatedsensorstouser= async (req, reply) => { exports.getallocatedsensorstouser= async (req, reply) => {
try { try {
const { customerId } = req.params; const { customerId } = req.params;

@ -820,6 +820,7 @@ const orderSchema = new mongoose.Schema({
{ {
master_name: { type: String, default: null }, master_name: { type: String, default: null },
hardwareId: { type: String, default: null }, hardwareId: { type: String, default: null },
work_status: { type: String, enum: ['active', 'pending', 'complete'], default: 'active' },
slaves: { type: String, default: null }, slaves: { type: String, default: null },
location: { type: String, default: null }, location: { type: String, default: null },
googleLocation: { type: String, default: null }, googleLocation: { type: String, default: null },
@ -866,7 +867,6 @@ const orderSchema = new mongoose.Schema({
qutation_total_price: { type: String, default: null }, qutation_total_price: { type: String, default: null },
type: { type: String, default: null }, type: { type: String, default: null },
status: { type: String, default: "pending" }, status: { type: String, default: "pending" },
work_status: { type: String, enum: ['active', 'pending', 'complete'], default: 'active' },
quatation_status: { type: String, default: "pending" }, quatation_status: { type: String, default: "pending" },
}); });

@ -1992,7 +1992,7 @@ fastify.get("/api/ordersofinstall/:installationId", {
handler: storeController.getOrdersByInstallationId, handler: storeController.getOrdersByInstallationId,
}); });
fastify.get("/api/Pendingordersofinstall/:installationId", { fastify.get("/api/Pendingordersofinstall/:installationId/:teamMemberId", {
schema: { schema: {
tags: ["Installation"], tags: ["Installation"],
description: "Fetches orders based on installationId", description: "Fetches orders based on installationId",
@ -2001,7 +2001,7 @@ fastify.get("/api/Pendingordersofinstall/:installationId", {
type: "object", type: "object",
properties: { properties: {
installationId: { type: "string" }, installationId: { type: "string" },
//work_status: { type: "string"}, teamMemberId: { type: "string"},
//customerId: { type: "string"}, //customerId: { type: "string"},
}, },
// required: ["installationId"], // required: ["installationId"],
@ -2012,7 +2012,7 @@ fastify.get("/api/Pendingordersofinstall/:installationId", {
}, },
], ],
}, },
handler: storeController.getPendingOrdersByInstallationId, handler: storeController.getPendingOrdersByInstallationAndTeamMember,
}); });
@ -2040,7 +2040,7 @@ fastify.get("/api/Completeordersofinstall/:installationId", {
}); });
fastify.post( fastify.post(
'/api/orders/:installationId/:customerId', '/api/orders/:installationId/:customerId/:teamMemberId',
{ {
schema: { schema: {
tags: ["Installation"], tags: ["Installation"],
@ -2052,6 +2052,7 @@ fastify.post(
properties: { properties: {
installationId: { type: 'string' }, installationId: { type: 'string' },
customerId: { type: 'string' }, customerId: { type: 'string' },
teamMemberId: { type : 'string'}
}, },
}, },
body: { body: {

Loading…
Cancel
Save