search functionality add in get invoice of process,dispatch and delivered

This commit is contained in:
Sibunnayak 2024-09-24 11:11:07 +05:30
parent 13349cc82e
commit 2968131835

View File

@ -105,13 +105,14 @@ export const processOrder = async (req, res) => {
// If there are any exceeded items, return an error with their names // If there are any exceeded items, return an error with their names
if (exceededItems.length > 0) { if (exceededItems.length > 0) {
return res.status(400).json({ return res.status(400).json({
error: `The following items have more quantity than remaining in the order: ${exceededItems.join(", ")}`, error: `The following items have more quantity than remaining in the order: ${exceededItems.join(
", "
)}`,
}); });
} }
// Continue with the rest of the logic if no quantity limits are exceeded // Continue with the rest of the logic if no quantity limits are exceeded
// Generate unique invoice number // Generate unique invoice number
const existingInvoices = await Invoice.find({ orderId }); const existingInvoices = await Invoice.find({ orderId });
const invoiceNumber = existingInvoices.length + 1; const invoiceNumber = existingInvoices.length + 1;
@ -144,55 +145,54 @@ export const processOrder = async (req, res) => {
// Save the invoice // Save the invoice
const savedInvoice = await newInvoice.save(); const savedInvoice = await newInvoice.save();
// Update the order's order items with the remaining quantity // Update the order's order items with the remaining quantity
let allItemsProcessed = true; // Flag to check if all items are processed let allItemsProcessed = true; // Flag to check if all items are processed
order.orderItem.forEach((item) => { order.orderItem.forEach((item) => {
const invoicedItem = invoiceItems.find( const invoicedItem = invoiceItems.find(
(i) => i.productId.toString() === item.productId.toString() (i) => i.productId.toString() === item.productId.toString()
); );
// If the item was invoiced, update the remaining quantity // If the item was invoiced, update the remaining quantity
if (invoicedItem) { if (invoicedItem) {
// Deduct the processed quantity from remaining quantity // Deduct the processed quantity from remaining quantity
item.remainingQuantity -= invoicedItem.processquantity; item.remainingQuantity -= invoicedItem.processquantity;
// Ensure remaining quantity does not go negative // Ensure remaining quantity does not go negative
if (item.remainingQuantity < 0) { if (item.remainingQuantity < 0) {
item.remainingQuantity = 0; item.remainingQuantity = 0;
}
}
// Check if the remaining quantity is greater than 0, even for items not invoiced
if (item.remainingQuantity > 0) {
allItemsProcessed = false;
}
});
// Calculate total amount for pending items
let pendingTotalAmount = 0;
order.orderItem.forEach((item) => {
if (item.remainingQuantity > 0) {
const itemPendingSubtotal = item.price * item.remainingQuantity;
const itemPendingGST =
((item.price * item.GST) / 100) * item.remainingQuantity;
pendingTotalAmount += itemPendingSubtotal + itemPendingGST;
}
});
// Only update order status if all items have been fully processed
if (allItemsProcessed) {
order.status = "processing"; // All items are fully processed
} else {
order.status = "pending"; // There are still remaining quantities
} }
}
// Check if the remaining quantity is greater than 0, even for items not invoiced // Add the invoice to the order
if (item.remainingQuantity > 0) { order.invoices.push(savedInvoice._id);
allItemsProcessed = false;
}
});
// Calculate total amount for pending items
let pendingTotalAmount = 0;
order.orderItem.forEach((item) => {
if (item.remainingQuantity > 0) {
const itemPendingSubtotal = item.price * item.remainingQuantity;
const itemPendingGST =
((item.price * item.GST) / 100) * item.remainingQuantity;
pendingTotalAmount += itemPendingSubtotal + itemPendingGST;
}
});
// Only update order status if all items have been fully processed
if (allItemsProcessed) {
order.status = "processing"; // All items are fully processed
} else {
order.status = "pending"; // There are still remaining quantities
}
// Add the invoice to the order
order.invoices.push(savedInvoice._id);
// Save the updated order
await order.save();
// Save the updated order
await order.save();
// Prepare the email content // Prepare the email content
const processedItems = invoiceItems const processedItems = invoiceItems
@ -806,31 +806,47 @@ export const getProcessingInvoices = async (req, res) => {
try { try {
const page = parseInt(req.query.page, 10) || 1; const page = parseInt(req.query.page, 10) || 1;
const limit = parseInt(req.query.limit, 10) || 5; const limit = parseInt(req.query.limit, 10) || 5;
const { invoiceId, orderId } = req.query;
// Calculate the number of documents to skip
const skip = (page - 1) * limit; const skip = (page - 1) * limit;
// Get the total count of 'processing' invoices let query = { courierStatus: "processing" };
const totalInvoices = await Invoice.countDocuments({
courierStatus: "processing",
});
// Fetch the invoices with pagination if (invoiceId) {
const invoices = await Invoice.find({ courierStatus: "processing" }) query.invoiceId = { $regex: invoiceId, $options: "i" };
}
const invoices = await Invoice.find(query)
.sort({ createdAt: -1 }) .sort({ createdAt: -1 })
.skip(skip) .skip(skip)
.limit(limit); .limit(limit)
// Respond with the invoices and the total count .populate({
res.status(200).json({ path: "orderId",
totalCount: totalInvoices, select: "uniqueId",
currentPage: page, });
totalPages: Math.ceil(totalInvoices / limit),
invoices, if (orderId) {
}); const filteredInvoices = invoices.filter(invoice =>
invoice.orderId && invoice.orderId.uniqueId &&
invoice.orderId.uniqueId.toLowerCase().includes(orderId.toLowerCase())
);
res.status(200).json({
totalCount: filteredInvoices.length,
currentPage: page,
totalPages: Math.ceil(filteredInvoices.length / limit),
invoices: filteredInvoices,
});
} else {
res.status(200).json({
totalCount: invoices.length,
currentPage: page,
totalPages: Math.ceil(invoices.length / limit),
invoices,
});
}
} catch (error) { } catch (error) {
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
} }
}; };
export const getInvoiceDetailsById = async (req, res) => { export const getInvoiceDetailsById = async (req, res) => {
const { invoiceId } = req.params; const { invoiceId } = req.params;
@ -950,13 +966,14 @@ export const updateCourierStatusToDispatched = async (req, res) => {
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${ <td style="border: 1px solid #555; padding: 2px; text-align: center;">${
product.price product.price
}</td> }</td>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${ <td style="border: 1px solid #555; padding: 2px; text-align: center;">${(
((product.GST * product.price) / 100).toFixed(2) (product.GST * product.price) /
}</td> 100
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${ ).toFixed(2)}</td>
((product.price + (product.GST * product.price) / 100) * <td style="border: 1px solid #555; padding: 2px; text-align: center;">${(
product.processquantity).toFixed(2) (product.price + (product.GST * product.price) / 100) *
}</td> product.processquantity
).toFixed(2)}</td>
</tr> </tr>
` `
) )
@ -991,31 +1008,47 @@ export const getDispatchedInvoices = async (req, res) => {
try { try {
const page = parseInt(req.query.page, 10) || 1; const page = parseInt(req.query.page, 10) || 1;
const limit = parseInt(req.query.limit, 10) || 5; const limit = parseInt(req.query.limit, 10) || 5;
const { invoiceId, orderId } = req.query;
// Calculate the number of documents to skip
const skip = (page - 1) * limit; const skip = (page - 1) * limit;
// Get the total count of 'processing' invoices let query = { courierStatus: "dispatched" };
const totalInvoices = await Invoice.countDocuments({
courierStatus: "dispatched",
});
// Fetch the invoices with pagination if (invoiceId) {
const invoices = await Invoice.find({ courierStatus: "dispatched" }) query.invoiceId = { $regex: invoiceId, $options: "i" };
}
const invoices = await Invoice.find(query)
.sort({ createdAt: -1 }) .sort({ createdAt: -1 })
.skip(skip) .skip(skip)
.limit(limit); .limit(limit)
// Respond with the invoices and the total count .populate({
res.status(200).json({ path: "orderId",
totalCount: totalInvoices, select: "uniqueId",
currentPage: page, });
totalPages: Math.ceil(totalInvoices / limit),
invoices, if (orderId) {
}); const filteredInvoices = invoices.filter(invoice =>
invoice.orderId && invoice.orderId.uniqueId &&
invoice.orderId.uniqueId.toLowerCase().includes(orderId.toLowerCase())
);
res.status(200).json({
totalCount: filteredInvoices.length,
currentPage: page,
totalPages: Math.ceil(filteredInvoices.length / limit),
invoices: filteredInvoices,
});
} else {
res.status(200).json({
totalCount: invoices.length,
currentPage: page,
totalPages: Math.ceil(invoices.length / limit),
invoices,
});
}
} catch (error) { } catch (error) {
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
} }
}; };
export const updateCourierStatusToDelivered = async (req, res) => { export const updateCourierStatusToDelivered = async (req, res) => {
const { invoiceId } = req.params; const { invoiceId } = req.params;
@ -1107,22 +1140,23 @@ export const updateCourierStatusToDelivered = async (req, res) => {
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${ <td style="border: 1px solid #555; padding: 2px; text-align: center;">${
product.price product.price
}</td> }</td>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${ <td style="border: 1px solid #555; padding: 2px; text-align: center;">${(
((product.GST * product.price) / 100).toFixed(2) (product.GST * product.price) /
}</td> 100
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${ ).toFixed(2)}</td>
((product.price + (product.GST * product.price) / 100) * <td style="border: 1px solid #555; padding: 2px; text-align: center;">${(
product.processquantity).toFixed(2) (product.price + (product.GST * product.price) / 100) *
}</td> product.processquantity
).toFixed(2)}</td>
</tr> </tr>
` `
) )
.join("")} .join("")}
<tr> <tr>
<th colspan="7" style="border: 1px solid #555; padding: 2px; text-align: right;">Total Amount:</th> <th colspan="7" style="border: 1px solid #555; padding: 2px; text-align: right;">Total Amount:</th>
<td style="border: 1px solid #555; padding: 2px; text-align: center;">${ <td style="border: 1px solid #555; padding: 2px; text-align: center;">${invoice.invoiceAmount.toFixed(
invoice.invoiceAmount.toFixed(2) 2
}</td> )}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@ -1159,31 +1193,47 @@ export const getDeliveredInvoices = async (req, res) => {
try { try {
const page = parseInt(req.query.page, 10) || 1; const page = parseInt(req.query.page, 10) || 1;
const limit = parseInt(req.query.limit, 10) || 5; const limit = parseInt(req.query.limit, 10) || 5;
const { invoiceId, orderId } = req.query;
// Calculate the number of documents to skip
const skip = (page - 1) * limit; const skip = (page - 1) * limit;
// Get the total count of 'processing' invoices let query = { courierStatus: "delivered" };
const totalInvoices = await Invoice.countDocuments({
courierStatus: "delivered",
});
// Fetch the invoices with pagination if (invoiceId) {
const invoices = await Invoice.find({ courierStatus: "delivered" }) query.invoiceId = { $regex: invoiceId, $options: "i" };
}
const invoices = await Invoice.find(query)
.sort({ createdAt: -1 }) .sort({ createdAt: -1 })
.skip(skip) .skip(skip)
.limit(limit); .limit(limit)
// Respond with the invoices and the total count .populate({
res.status(200).json({ path: "orderId",
totalCount: totalInvoices, select: "uniqueId",
currentPage: page, });
totalPages: Math.ceil(totalInvoices / limit),
invoices, if (orderId) {
}); const filteredInvoices = invoices.filter(invoice =>
invoice.orderId && invoice.orderId.uniqueId &&
invoice.orderId.uniqueId.toLowerCase().includes(orderId.toLowerCase())
);
res.status(200).json({
totalCount: filteredInvoices.length,
currentPage: page,
totalPages: Math.ceil(filteredInvoices.length / limit),
invoices: filteredInvoices,
});
} else {
res.status(200).json({
totalCount: invoices.length,
currentPage: page,
totalPages: Math.ceil(invoices.length / limit),
invoices,
});
}
} catch (error) { } catch (error) {
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
} }
}; };
export const getDeliveredOrdersAdmin = async (req, res) => { export const getDeliveredOrdersAdmin = async (req, res) => {
try { try {
// Extract page and limit from query parameters // Extract page and limit from query parameters