fcm token and notification section done
This commit is contained in:
parent
57d02d2c49
commit
62a4e904df
23
Utils/rejectKyc.js
Normal file
23
Utils/rejectKyc.js
Normal file
@ -0,0 +1,23 @@
|
||||
import SalesCoOrdinator from "../resources/SalesCoOrdinators/SalesCoOrdinatorModel.js";
|
||||
import TerritoryManager from "../resources/TerritoryManagers/TerritoryManagerModel.js";
|
||||
import { sendPushNotification } from "./sendPushNotification.js";
|
||||
|
||||
export const rejectKYC = async (userId, reason) => {
|
||||
// Try to find the user in SalesCoordinator model
|
||||
let user = await SalesCoOrdinator.findById(userId);
|
||||
if (!user) {
|
||||
// If not found, try to find the user in TerritoryManager model
|
||||
user = await TerritoryManager.findById(userId);
|
||||
}
|
||||
|
||||
// Get the user's FCM token
|
||||
const userToken = user ? user.fcm_token : null;
|
||||
|
||||
if (userToken) {
|
||||
// Send the push notification
|
||||
const message = `Your KYC has been rejected. Reason: ${reason}`;
|
||||
await sendPushNotification(userToken, message);
|
||||
} else {
|
||||
console.error("No FCM token found for user:", userId);
|
||||
}
|
||||
};
|
27
Utils/sendPushNotification.js
Normal file
27
Utils/sendPushNotification.js
Normal file
@ -0,0 +1,27 @@
|
||||
import admin from "firebase-admin";
|
||||
import serviceAccount from "../googlefirebasePushnotification.json" with { type: "json" };
|
||||
export const sendPushNotification = async (userToken, message) => {
|
||||
// const admin = require("firebase-admin");
|
||||
// const serviceAccount = require("./path/to/your-firebase-adminsdk.json");
|
||||
|
||||
if (!admin.apps.length) {
|
||||
admin.initializeApp({
|
||||
credential: admin.credential.cert(serviceAccount),
|
||||
});
|
||||
}
|
||||
|
||||
const payload = {
|
||||
notification: {
|
||||
title: "KYC Rejected ",
|
||||
body: message,
|
||||
},
|
||||
token: userToken
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await admin.messaging().send(message);
|
||||
console.log("Successfully sent message:", response);
|
||||
} catch (error) {
|
||||
console.error("Error sending message:", error);
|
||||
}
|
||||
};
|
15
app.js
15
app.js
@ -7,12 +7,20 @@ import bodyParser from "body-parser";
|
||||
import fileUpload from "express-fileupload"; // important pkg for file upload
|
||||
import cors from "cors";
|
||||
import cookieParser from "cookie-parser";
|
||||
|
||||
// firebase admin push notification
|
||||
import admin from "firebase-admin";
|
||||
import serviceAccount from "./googlefirebasePushnotification.json" with { type: "json" };
|
||||
// Design Router
|
||||
import designRoute from "./resources/Design/designRouter.js";
|
||||
app.use(express.json({ limit: "50mb" }));
|
||||
app.use(express.urlencoded({ extended: true, limit: "50mb" }));
|
||||
|
||||
//webhook call route according strip (webhook want raw data not json data)
|
||||
|
||||
admin.initializeApp({
|
||||
credential: admin.credential.cert(serviceAccount),
|
||||
});
|
||||
|
||||
app.use((req, res, next) => {
|
||||
if (req.originalUrl === "/api/order/webhook") {
|
||||
next();
|
||||
@ -175,6 +183,8 @@ import CouponRoute from "./resources/Affiliate&Coupon/Coupon/CouponRoute.js";
|
||||
import attendance from "./resources/Attendance/AttandanceRoute.js";
|
||||
//leave
|
||||
import leave from "./resources/Leaves/LeaveRoute.js";
|
||||
// Notification
|
||||
import notification from "./resources/Notification/notificationRoute.js"
|
||||
app.use("/api/v1", user);
|
||||
|
||||
//Product
|
||||
@ -239,6 +249,9 @@ app.use("/api/v1", attendance);
|
||||
//leave
|
||||
app.use("/api/v1", leave);
|
||||
|
||||
// notification route
|
||||
app.use("/api",notification)
|
||||
|
||||
//config specialty
|
||||
// app.use("/api/config/specialty", SpecialtiesRouter);
|
||||
//specialties
|
||||
|
13
googlefirebasePushnotification.json
Normal file
13
googlefirebasePushnotification.json
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"type": "service_account",
|
||||
"project_id": "cheminova-1fcf0",
|
||||
"private_key_id": "e24c0725eea690e134440543abc738e2ff4191d9",
|
||||
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCmhN9GjPZY8IpU\nf0O6h2oQWjyBtJBesaYrIwJnug/KW/3MvNreseHPZIOKv+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L3gzY2rjcDwDEjVuVFLKCffe4WuNXjw2VWYc44XSTMn8fo1OZWLvpHVvaVf\nII/2TlDqloVJK5qHypcSuhLWt0A5R1uIMIxVqWp1sJn1r7+UZqudLTwxAoGBAJ7q\nDJU6aN+mKJJZQal1rLAxxLTSGSKA30fz6grjwqChEY/XrI5mSfW9BK0+mvx7UYpO\nL/ZdLDgQGpm4lTaNBnakNEMxOm2eYX1Phz21j4Pcr735mZXFv22Z0i28NWHAzw3g\n5vTFtJkYArEQvKYlzewdzUSK1X3BhEQZvg3sSms9AoGAQBqZrUfjCcW5L6CQdELx\noQBNUttRHYTySBEaD4SGJJdGort/JGwbo0PhZIKTMNUuNrOaHHy/Bqv2HpKddlcN\nDS77Yk0wMVBQThl5udQu6Sjt5anbND5NXm+zkXLmze9sYzXqw0+5T/Zjfrcx7d+y\nrAsjNU7Z/smy8BUmUMi7Q6E=\n-----END PRIVATE KEY-----\n",
|
||||
"client_email": "firebase-adminsdk-kvvgg@cheminova-1fcf0.iam.gserviceaccount.com",
|
||||
"client_id": "105503935858227909571",
|
||||
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
||||
"token_uri": "https://oauth2.googleapis.com/token",
|
||||
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
||||
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-kvvgg%40cheminova-1fcf0.iam.gserviceaccount.com",
|
||||
"universe_domain": "googleapis.com"
|
||||
}
|
1158
package-lock.json
generated
1158
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -24,6 +24,7 @@
|
||||
"dotenv": "^16.0.1",
|
||||
"express": "^4.18.1",
|
||||
"express-fileupload": "^1.4.0",
|
||||
"firebase-admin": "^12.3.0",
|
||||
"generate-password": "^1.7.0",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"messagebird": "^4.0.1",
|
||||
|
@ -2,6 +2,9 @@ import mongoose from "mongoose";
|
||||
import cloudinary from "../../Utils/cloudinary.js";
|
||||
import { KYC } from "./KycModel.js";
|
||||
import User from "../user/userModel.js";
|
||||
import { rejectKYC } from "../../Utils/rejectKyc.js";
|
||||
import SalesCoOrdinator from "../SalesCoOrdinators/SalesCoOrdinatorModel.js";
|
||||
import TerritoryManager from "../TerritoryManagers/TerritoryManagerModel.js";
|
||||
|
||||
export const createKyc = async (req, res) => {
|
||||
const {
|
||||
@ -111,6 +114,7 @@ export const getAllKyc = async (req, res) => {
|
||||
try {
|
||||
// Fetch all KYC documents from the database
|
||||
// console.log("req came here ");
|
||||
// console.log(req.user._id);
|
||||
const kycs = await KYC.find({ principal_distributer: req.user._id })
|
||||
.populate("principal_distributer", "name")
|
||||
.populate("addedBy");
|
||||
@ -205,6 +209,7 @@ export const updateKycStatus = async (req, res) => {
|
||||
// Add rejection reason to notes if status is reject
|
||||
if (kyc.status === "reject" || status === "reject") {
|
||||
// kyc.rejection_reason = rejectionReason;
|
||||
await rejectKYC(req.user._id, rejectionReason);
|
||||
kyc.notes.push({
|
||||
message: rejectionReason,
|
||||
user: user,
|
||||
@ -238,3 +243,60 @@ export const getAllPrincipalDistributers = async (req, res) => {
|
||||
res.status(500).json({ message: "Server Error", error });
|
||||
}
|
||||
};
|
||||
|
||||
// Fcm token storing
|
||||
export const saveFCMTokenForSC = async (req, res) => {
|
||||
const { fcmToken } = req.body;
|
||||
const userId = req.user._id;
|
||||
|
||||
try {
|
||||
// Fetch the current FCM token for the user
|
||||
const user = await SalesCoOrdinator.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 === 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");
|
||||
}
|
||||
};
|
||||
|
||||
export const saveFCMTokenForTM = async (req, res) => {
|
||||
const { fcmToken } = req.body;
|
||||
const userId = req.user._id;
|
||||
|
||||
try {
|
||||
// Fetch the current FCM token for the user
|
||||
const user = await TerritoryManager.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 === 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");
|
||||
}
|
||||
};
|
||||
|
@ -9,6 +9,8 @@ import {
|
||||
getAllKycRejected,
|
||||
getAllPrincipalDistributers,
|
||||
getKycById,
|
||||
saveFCMTokenForSC,
|
||||
saveFCMTokenForTM,
|
||||
updateKycStatus,
|
||||
} from "./KycController.js";
|
||||
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
|
||||
@ -38,6 +40,7 @@ router
|
||||
|
||||
// sales coordinator routes && TM ROUTES
|
||||
router.route("/kyc/create/").post(isAuthenticatedSalesCoOrdinator, createKyc);
|
||||
|
||||
router
|
||||
.route("/kyc/create-tm/")
|
||||
.post(isAuthenticatedTerritoryManager, createKyc);
|
||||
@ -61,4 +64,11 @@ router
|
||||
router
|
||||
.route("/kyc/get-single-kyc-tm/:id")
|
||||
.get(isAuthenticatedSalesCoOrdinator, getKycById);
|
||||
|
||||
router
|
||||
.route("/kyc/save-fcm-sc/")
|
||||
.post(isAuthenticatedSalesCoOrdinator, saveFCMTokenForSC);
|
||||
router
|
||||
.route("/kyc/save-fcm-tm/")
|
||||
.post(isAuthenticatedSalesCoOrdinator, saveFCMTokenForTM);
|
||||
export default router;
|
||||
|
53
resources/Notification/notificationController.js
Normal file
53
resources/Notification/notificationController.js
Normal file
@ -0,0 +1,53 @@
|
||||
import { Notification } from "./notificationModal.js";
|
||||
|
||||
export const getNotification = async (req, res) => {
|
||||
try {
|
||||
// Ensure req.user._id is defined and valid
|
||||
if (!req.user || !req.user._id) {
|
||||
return res.status(400).json({ return_message: "Invalid user ID" });
|
||||
}
|
||||
|
||||
// Fetch notifications for the user
|
||||
const notifications = await Notification.find({ added_for: req.user._id });
|
||||
|
||||
if (notifications && notifications.length > 0) {
|
||||
return res
|
||||
.status(200)
|
||||
.json({ return_message: "Fetched notifications", notifications });
|
||||
}
|
||||
|
||||
return res.status(404).json({ return_message: "No notifications found" });
|
||||
} catch (error) {
|
||||
return res
|
||||
.status(500)
|
||||
.json({ return_message: "Something went wrong", error });
|
||||
}
|
||||
};
|
||||
|
||||
export const getSingleNotification = async (req, res) => {
|
||||
try {
|
||||
const notificationId = req.params.id;
|
||||
|
||||
// Validate notificationId
|
||||
if (!notificationId) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ return_message: "Notification ID is required" });
|
||||
}
|
||||
|
||||
// Fetch the notification by ID
|
||||
const notification = await Notification.findById(notificationId);
|
||||
|
||||
if (notification) {
|
||||
return res
|
||||
.status(200)
|
||||
.json({ return_message: "Fetched notification", notification });
|
||||
}
|
||||
|
||||
return res.status(404).json({ return_message: "Notification not found" });
|
||||
} catch (error) {
|
||||
return res
|
||||
.status(500)
|
||||
.json({ return_message: "Something went wrong", error });
|
||||
}
|
||||
};
|
31
resources/Notification/notificationModal.js
Normal file
31
resources/Notification/notificationModal.js
Normal file
@ -0,0 +1,31 @@
|
||||
import mongoose, { model, Schema } from "mongoose";
|
||||
|
||||
const notificationSchema = new Schema(
|
||||
{
|
||||
title: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
msg: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
Kyc_ref: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: "KYC",
|
||||
},
|
||||
added_for: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
refPath: "userType",
|
||||
required: true, // Assuming this should be required
|
||||
},
|
||||
userType: {
|
||||
type: String,
|
||||
required: true, // Assuming this should be required
|
||||
enum: ["SalesCoOrdinator", "TerritoryManager"],
|
||||
},
|
||||
},
|
||||
{ timestamps: true } // Adds createdAt and updatedAt timestamps
|
||||
);
|
||||
|
||||
export const Notification = model("Notification", notificationSchema);
|
24
resources/Notification/notificationRoute.js
Normal file
24
resources/Notification/notificationRoute.js
Normal file
@ -0,0 +1,24 @@
|
||||
import express from "express";
|
||||
import { isAuthenticatedSalesCoOrdinator } from "../../middlewares/SalesCoOrdinatorAuth.js";
|
||||
import { getNotification } from "./notificationController.js";
|
||||
import { isAuthenticatedTerritoryManager } from "../../middlewares/TerritoryManagerAuth.js";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router
|
||||
.route("/get-notification-sc")
|
||||
.get(isAuthenticatedSalesCoOrdinator, getNotification);
|
||||
|
||||
router
|
||||
.route("/get-notification-sc/:id")
|
||||
.get(isAuthenticatedSalesCoOrdinator, getNotification);
|
||||
|
||||
router
|
||||
.route("/get-notification-tm")
|
||||
.get(isAuthenticatedTerritoryManager, getNotification);
|
||||
|
||||
router
|
||||
.route("/get-notification-tm/:id")
|
||||
.get(isAuthenticatedTerritoryManager, getNotification);
|
||||
|
||||
export default router;
|
@ -47,6 +47,10 @@ const salescoordinatorSchema = new mongoose.Schema(
|
||||
unique: true,
|
||||
required: true,
|
||||
},
|
||||
fcm_token: {
|
||||
type: String,
|
||||
unique: true,
|
||||
},
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
@ -47,6 +47,10 @@ const territorymanagerSchema = new mongoose.Schema(
|
||||
unique: true,
|
||||
required: true,
|
||||
},
|
||||
fcm_token: {
|
||||
type: String,
|
||||
unique: true,
|
||||
},
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
Loading…
Reference in New Issue
Block a user