From 1ec1a81033c26b25ae5cf180cfd6612e0eba36ff Mon Sep 17 00:00:00 2001 From: ROSHAN GARG Date: Tue, 8 Oct 2024 14:07:33 +0530 Subject: [PATCH] fcm token for RD --- resources/RD_Ordes/rdOrderController.js | 96 ++++++++++++++++--- .../RetailDistributerRoutes.js | 6 +- .../RetailDistributorController.js | 28 ++++++ 3 files changed, 115 insertions(+), 15 deletions(-) diff --git a/resources/RD_Ordes/rdOrderController.js b/resources/RD_Ordes/rdOrderController.js index fb7a411..3fca418 100644 --- a/resources/RD_Ordes/rdOrderController.js +++ b/resources/RD_Ordes/rdOrderController.js @@ -6,6 +6,7 @@ import { RdOrder } from "./rdOrderModal.js"; import { PDStock } from "../Stock/PdStockModel.js"; import { createKYC } from "../../Utils/rejectKyc.js"; import { Notification } from "../Notification/notificationModal.js"; +import { sendPushNotification } from "../../Utils/sendPushNotification.js"; // Controller to create a new order by RD export const createOrderRD = async (req, res) => { @@ -496,9 +497,30 @@ export const processOrder = async (req, res) => { // Only update order status if all items have been fully processed if (allItemsProcessed) { - order.status = "processing"; // All items are fully processed + order.status = "processing"; + await sendPushNotification( + order.addedBy?.fcm_token, + "Exciting news", + "Your order got processed" + ); + await Notification.create({ + title: "Exciting news", + msg: `Your order got processed`, + added_for: order.addedBy?._id, + }); + // All items are fully processed } else { - order.status = "pending"; // There are still remaining quantities + order.status = "pending"; + await sendPushNotification( + order.addedBy?.fcm_token, + "Exciting news", + "Some of your items got in processing " + ); + await Notification.create({ + title: "Exciting news", + msg: `Some of your items got in processing `, + added_for: order.addedBy?._id, + }); // There are still remaining quantities } // Add the invoice to the order @@ -751,7 +773,7 @@ export const getInvoiceDetailsByIdForPD = async (req, res) => { populate: { path: "addedBy", model: "RetailDistributor", - select: "name email mobile_number ", + select: "name email mobile_number fcm_token ", }, }); if (!invoice) { @@ -772,7 +794,7 @@ export const updateCourierStatusToDispatchedForPD = async (req, res) => { path: "orderId", populate: { path: "addedBy", - select: "email", + select: "email fcm_token", }, }); @@ -797,7 +819,16 @@ export const updateCourierStatusToDispatchedForPD = async (req, res) => { order.status = "dispatched"; await order.save(); } - + await sendPushNotification( + order.addedBy?.fcm_token, + "Exciting news", + "Order dispatched " + ); + await Notification.create({ + title: "Exciting news", + msg: `Order dispatched`, + added_for: order.addedBy?._id, + }); // Send email to the user await sendEmail({ to: `${order?.addedBy?.email}`, // Assuming 'addedBy' references the user who placed the order @@ -904,7 +935,7 @@ export const updateCourierStatusToDeliveredForPD = async (req, res) => { path: "orderId", populate: { path: "addedBy", - select: "email", + select: "email fcm_token", }, }); if (!invoice) { @@ -929,7 +960,16 @@ export const updateCourierStatusToDeliveredForPD = async (req, res) => { } // Get the userId from the order's addedBy const userId = order?.addedBy?._id; - + await sendPushNotification( + order?.addedBy?.fcm_token, + "Exciting news", + "Order Delivered " + ); + await Notification.create({ + title: "Exciting news", + msg: `Order Delivered `, + added_for: order?.addedBy?._id, + }); if (!userId) { return res.status(400).json({ error: "User not found for the order" }); } @@ -1219,6 +1259,16 @@ export const cancelOrderController = async (req, res) => { if (order.invoices.length === 0) { // If no invoices are associated with the order + await sendPushNotification( + order.addedBy?.fcm_token, + "Sorry! order cancelled fully.", + `Order has been cancelled due to ${cancellationReason}` + ); + await Notification.create({ + title: "Sorry! order cancelled fully.", + msg: `Order dispatched`, + added_for: order.addedBy?._id, + }); await sendEmail({ to: `${order.addedBy.email}`, // Change to your recipient from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender @@ -1335,6 +1385,18 @@ export const cancelOrderController = async (req, res) => { } }); } + await sendPushNotification( + order.addedBy?.fcm_token, + "Sorry! order cancelled partially.", + `Order has been cancelled due to ${ + cancellationReason ? cancellationReason : "some reason" + }` + ); + await Notification.create({ + title: "Sorry! order cancelled fully.", + msg: `Order dispatched`, + added_for: order.addedBy?._id, + }); await sendEmail({ to: `${order.addedBy.email}`, // Change to your recipient from: `${process.env.SEND_EMAIL_FROM}`, // Change to your verified sender @@ -1552,17 +1614,25 @@ export const getAllOrdersByDistributor = async (req, res) => { export const gettotalorderandvalueofrd = async (req, res) => { const { distributorId } = req.params; try { - const orders = await RdOrder.find({ addedBy: distributorId }).sort({ createdAt: -1 }); - + const orders = await RdOrder.find({ addedBy: distributorId }).sort({ + createdAt: -1, + }); + const totalOrders = orders.length; - const totalValue = orders.reduce((acc, order) => acc + order.grandTotal, 0).toFixed(2); - + const totalValue = orders + .reduce((acc, order) => acc + order.grandTotal, 0) + .toFixed(2); + // Get the date of the last order const lastPurchaseOrderDate = totalOrders > 0 ? orders[0].createdAt : null; - res.status(200).json({ totalOrders, totalValue: parseFloat(totalValue), lastPurchaseOrderDate }); + res.status(200).json({ + totalOrders, + totalValue: parseFloat(totalValue), + lastPurchaseOrderDate, + }); } catch (error) { console.error("Error fetching orders:", error); res.status(500).json({ message: "Server error", error }); } -}; \ No newline at end of file +}; diff --git a/resources/RetailDistributor/RetailDistributerRoutes.js b/resources/RetailDistributor/RetailDistributerRoutes.js index 5b10768..7034933 100644 --- a/resources/RetailDistributor/RetailDistributerRoutes.js +++ b/resources/RetailDistributor/RetailDistributerRoutes.js @@ -10,6 +10,7 @@ import { getmyProfileRD, getRDId, loginRD, + saveFCMTokenForRD, UpdateProfileRD, updateRDMapped, updateunmapRD, @@ -29,6 +30,7 @@ router.put( ChangePasswordRD ); router.patch("/rd-profile/update", isAuthenticatedRD, UpdateProfileRD); +router.post("/rd-save-fcm-token", isAuthenticatedRD, saveFCMTokenForRD); //admin and maping router .route("/getAllRD") @@ -37,7 +39,7 @@ router authorizeRoles("admin"), getAllRetailDistributorApproved ); - router +router .route("/getAllRDandorder") .get( isAuthenticatedUser, @@ -60,7 +62,7 @@ router router .route("/mapped/:id") .put(isAuthenticatedUser, authorizeRoles("admin"), updateRDMapped); - router +router .route("/unmap/:id") .patch(isAuthenticatedUser, authorizeRoles("admin"), updateunmapRD); export default router; diff --git a/resources/RetailDistributor/RetailDistributorController.js b/resources/RetailDistributor/RetailDistributorController.js index c9ac22e..989ead4 100644 --- a/resources/RetailDistributor/RetailDistributorController.js +++ b/resources/RetailDistributor/RetailDistributorController.js @@ -1366,3 +1366,31 @@ export const updateunmapRD = async (req, res) => { }); } }; + +export const saveFCMTokenForRD = async (req, res) => { + const { fcmToken } = req.body; + const userId = req.user._id; + + try { + // Fetch the current FCM token for the user + const user = await RetailDistributor.findById(userId); + + if (!user) { + return res.status(404).send("User not found"); + } + + // Check if the new FCM token is different from the current one + if (user.fcm_token && user.fcm_token === fcmToken) { + return res.status(200).send("FCM Token is already up to date"); + } + + // Update the FCM token + user.fcm_token = fcmToken; + await user.save(); + + res.status(200).send("FCM Token saved successfully"); + } catch (error) { + console.error("Error saving FCM Token:", error); + res.status(500).send("Internal Server Error"); + } +};