somewhere

This commit is contained in:
Swift
2023-08-17 13:05:51 +03:30
parent 30c7eb0e7b
commit 53843207cc
429 changed files with 117489 additions and 1 deletions
@@ -0,0 +1,112 @@
const User = require('../../models/User')
const ContactPageMessage = require('../../models/ContactPageMessage')
const TicketConversation = require('../../models/TicketConversation')
const Representation = require('../../models/Representation')
const PieceRequest = require('../../models/PieceRequest')
const OldPieceRequest = require('../../models/OldPieceRequest')
const BufferRequest = require('../../models/BufferRequest')
const GuaranteeReport = require('../../models/GuaranteeReport')
module.exports.getAllNotifs = async socket => {
try {
const allData = await Promise.all([
// unreadCuMsgs
ContactPageMessage.find({ read: false }),
// unreadTickets
TicketConversation.find({ messages: { $elemMatch: { isUser: true, read: false } } }),
// newCustomers
User.find({ scope: ['user'], seenByAdmin: false, confirmed: true }),
// newRepresentations
Representation.find({ status: 'registered' }),
// newPieceRequests
PieceRequest.find({ status: 'sent' }),
// newOldPieceRequests
OldPieceRequest.find({ status: 'sent' }),
// newBufferRequests
BufferRequest.find({ status: 'sent' }),
// newGuaranteeReports
GuaranteeReport.find({ status: 'sent', seen: false })
])
const unreadCuMsgs = allData[0]
const unreadTickets = allData[1]
const newCustomers = allData[2]
const newRepresentations = allData[3]
const newPieceRequests = allData[4]
const newOldPieceRequests = allData[5]
const newBufferRequests = allData[6]
const newGuaranteeReports = allData[7]
socket.emit(`admin:allNotifs`, {
unreadCuMsgs: unreadCuMsgs.length,
unreadTickets: unreadTickets.length,
newCustomers: newCustomers.length,
newRepresentations: newRepresentations.length,
newPieceRequests: newPieceRequests.length,
newOldPieceRequests: newOldPieceRequests.length,
newBufferRequests: newBufferRequests.length,
newGuaranteeReports: newGuaranteeReports.length
})
} catch (e) {
console.log(e)
}
}
module.exports.notifyAdmin = async type => {
try {
const io = global._io
const admin = io.of('/admin')
const data = { type }
if (type === 'updateNewCustomers') {
const newCustomers = await User.find({ scope: ['user'], seenByAdmin: false })
data.newCustomers = newCustomers.length
}
if (type === 'updateUnreadCuMsgs') {
const unreadCuMsgs = await ContactPageMessage.find({ read: false })
data.unreadCuMsgs = unreadCuMsgs.length
}
if (type === 'updateUnreadTickets') {
const unreadTickets = await TicketConversation.find({ messages: { $elemMatch: { isUser: true, read: false } } })
data.unreadTickets = unreadTickets.length
}
if (type === 'updateNewRepresentations') {
const newRepresentations = await Representation.find({ status: 'registered' })
data.newRepresentations = newRepresentations.length
}
if (type === 'updateNewPieceRequests') {
const newPieceRequests = await PieceRequest.find({ status: 'sent' })
data.newPieceRequests = newPieceRequests.length
}
if (type === 'updateNewOldPieceRequests') {
const newOldPieceRequests = await OldPieceRequest.find({ status: 'sent' })
data.newOldPieceRequests = newOldPieceRequests.length
}
if (type === 'updateNewBufferRequests') {
const newBufferRequests = await BufferRequest.find({ status: 'sent' })
data.newBufferRequests = newBufferRequests.length
}
if (type === 'updateNewGuaranteeReports') {
const newGuaranteeReports = await GuaranteeReport.find({ status: 'sent', seen: false })
data.newGuaranteeReports = newGuaranteeReports.length
}
admin.emit(`admin:notify`, data)
} catch (e) {
console.log(e)
}
}
@@ -0,0 +1,84 @@
const Transaction = require('../../models/Transaction')
const Announcement = require('../../models/Announcement')
module.exports.getAllNotifs = async socket => {
try {
const agentInbox = await Transaction.find({ agent_id: socket.agentId, seen: false })
socket.emit(`agent:allNotifs`, {
agentInbox: agentInbox.length
})
} catch (e) {
console.log(e)
}
}
module.exports.notifyAgent = async (type, agent_id) => {
try {
const io = global._io
const agent = io.of('/agent')
const data = { type }
if (type === 'updateAgentInbox') {
const agentInbox = await Transaction.find({ agent_id, seen: false })
data.agentInbox = agentInbox.length
}
agent.to(agent_id.toString()).emit(`agent:notify`, data)
} catch (e) {
console.log(e)
}
}
module.exports.notifyAllAgents = type => {
try {
const io = global._io
const agent = io.of('/agent')
const data = { type }
agent.emit('agent:notifyAll', data)
} catch (e) {
console.log(e)
}
}
module.exports.fetchAnnouncements = async socket => {
try {
const announcements = await Announcement.find({ expired: false, isForAgents: true })
const modifiedAnnouncements = []
let newAnnouncementsCount = 0
for await (const announcement of announcements) {
const notif = { ...announcement._doc, seen: true }
if (!notif.seenBy.includes(socket.userId)) {
notif.seen = false
newAnnouncementsCount++
}
delete notif.seenBy
delete notif.expired
delete notif.isForAgents
delete notif._creator
modifiedAnnouncements.push(notif)
}
socket.emit('agent:announcements', {
newAgentAnnosCount: newAnnouncementsCount,
agentAnnouncements: modifiedAnnouncements.reverse()
})
} catch (e) {
console.log(e)
}
}
module.exports.updateAnnouncement = async (socket, id) => {
try {
if (id) {
const announcment = await Announcement.findById(id)
if (!announcment) throw new Error('invalid announcemnet id')
if (!announcment.seenBy.includes(socket.userId)) announcment.seenBy.push(socket.userId)
await announcment.save()
socket.emit('agent:fetchNewAnnouncements')
}
} catch (e) {
console.log(e)
}
}
@@ -0,0 +1,98 @@
const TransactionDrafts = require('../../models/TransactionDraft')
const TicketConversation = require('../../models/TicketConversation')
const Announcement = require('../../models/Announcement')
module.exports.getAllNotifs = async socket => {
try {
const drafts = await TransactionDrafts.find({ user_id: socket.userId })
const unreadTickets = await TicketConversation.find({
user_id: socket.userId,
messages: { $elemMatch: { isUser: false, read: false } }
})
socket.emit(`user:allNotifs`, {
unreadTickets: unreadTickets.length,
draftsCount: drafts.length
})
} catch (e) {
console.log(e)
}
}
module.exports.notifyUser = async (type, user_id) => {
try {
const io = global._io
const user = io.of('/user')
const data = { type }
if (type === 'updateUnreadTickets') {
const unreadTickets = await TicketConversation.find({
user_id,
messages: { $elemMatch: { isUser: false, read: false } }
})
data.unreadTickets = unreadTickets.length
}
if (type === 'updateDraftsCount') {
const drafts = await TransactionDrafts.find({ user_id })
data.draftsCount = drafts.length
}
user.to(user_id.toString()).emit(`user:notify`, data)
} catch (e) {
console.log(e)
}
}
module.exports.notifyAllUsers = type => {
try {
const io = global._io
const user = io.of('/user')
const data = { type }
user.emit(`user:notifyAll`, data)
} catch (e) {
console.log(e)
}
}
module.exports.fetchAnnouncements = async socket => {
try {
const announcements = await Announcement.find({ expired: false, isForAgents: false })
const modifiedAnnouncements = []
let newAnnouncementsCount = 0
for await (const announcement of announcements) {
const notif = { ...announcement._doc, seen: true }
if (!notif.seenBy.includes(socket.userId)) {
notif.seen = false
newAnnouncementsCount++
}
delete notif.seenBy
delete notif.expired
delete notif.isForAgents
delete notif._creator
modifiedAnnouncements.push(notif)
}
socket.emit('user:announcements', {
newUserAnnosCount: newAnnouncementsCount,
userAnnouncements: modifiedAnnouncements.reverse()
})
} catch (e) {
console.log(e)
}
}
module.exports.updateAnnouncement = async (socket, id) => {
try {
if (id) {
const announcment = await Announcement.findById(id)
if (!announcment) throw new Error('invalid announcemnet id')
if (!announcment.seenBy.includes(socket.userId)) announcment.seenBy.push(socket.userId)
await announcment.save()
socket.emit('user:fetchNewAnnouncements')
}
} catch (e) {
console.log(e)
}
}
@@ -0,0 +1,67 @@
const jwt = require('jsonwebtoken')
const User = require('../../models/User')
const authentication = require('../../authentication')
module.exports.isAdmin = async (socket, next) => {
try {
const token = socket.handshake?.auth?.token
if (!token) throw new Error('unauthenticated')
// verifies secret and checks if the token is expired
const decodedToken = await jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey)
if (!decodedToken) throw new Error('unauthorized')
// find user
const user = await User.findById(decodedToken._id)
if (!user || !user.scope.includes('admin')) throw new Error('unauthorized')
socket.userId = decodedToken._id.toString()
return next()
} catch (e) {
// console.log('ws user middleware error --- ', e)
next(new Error(e))
}
}
module.exports.isUser = async (socket, next) => {
try {
const token = socket.handshake?.auth?.token
if (!token) throw new Error('unauthenticated')
// verifies secret and checks if the token is expired
const decodedToken = await jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey)
if (!decodedToken) throw new Error('unauthorized')
// find user
const user = await User.findById(decodedToken._id)
if (!user || !user.scope.includes('user')) throw new Error('unauthorized')
socket.userId = decodedToken._id.toString()
return next()
} catch (e) {
// console.log('ws user middleware error --- ', e)
next(new Error(e))
}
}
module.exports.isAgent = async (socket, next) => {
try {
const token = socket.handshake?.auth?.token
if (!token) throw new Error('unauthenticated')
// verifies secret and checks if the token is expired
const decodedToken = await jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey)
if (!decodedToken) throw new Error('unauthorized')
// find user
const user = await User.findById(decodedToken._id)
if (!user || !user.scope.includes('user')) throw new Error('unauthorized')
if (!user.isAgent) throw new Error('شما نماینده نیستید')
socket.userId = decodedToken._id.toString()
socket.agentId = user.representation_id.toString()
return next()
} catch (e) {
next(new Error(e))
}
}
@@ -0,0 +1,23 @@
const { isAdmin } = require('../middlewares/ws_authentication')
const adminEventsController = require('../controllers/admin_EventsController')
module.exports.adminNamespace = () => {
const io = global._io
const admin = io.of('/admin')
// admins middlewares
admin.use(isAdmin)
// attach events
admin.on('connection', socket => {
adminEventsController.getAllNotifs(socket)
/// /////////////////////////////////////////////////////// handle connection error
socket.on('connect_error', err => {
console.log(err.message)
})
/// ////////////////////////////////////////////////////// events
// socket.on('admin:getNotifs', () => adminEventsController.getAllNotifs(socket))
})
}
@@ -0,0 +1,25 @@
const { isAgent } = require('../middlewares/ws_authentication')
const agentEventsController = require('../controllers/agent_EventsController')
module.exports.agentNamespace = () => {
const io = global._io
const agent = io.of('/agent')
// agents middlewares
agent.use(isAgent)
// attach events
agent.on('connection', socket => {
socket.join(socket.agentId)
agentEventsController.getAllNotifs(socket)
/// /////////////////////////////////////////////////////// handle connection error
socket.on('connect_error', err => {
console.log(err.message)
})
/// ////////////////////////////////////////////////////// events
socket.on('agent:fetchAnnouncements', data => agentEventsController.fetchAnnouncements(socket))
socket.on('agent:updateAnnouncement', data => agentEventsController.updateAnnouncement(socket, data))
})
}
@@ -0,0 +1,25 @@
const { isUser } = require('../middlewares/ws_authentication')
const userEventsController = require('../controllers/user_EventsController')
module.exports.userNamespace = () => {
const io = global._io
const user = io.of('/user')
// users middlewares
user.use(isUser)
// attach events
user.on('connection', socket => {
socket.join(socket.userId)
userEventsController.getAllNotifs(socket)
/// /////////////////////////////////////////////////////// handle connection error
socket.on('connect_error', err => {
console.log(err.message)
})
/// ////////////////////////////////////////////////////// events
socket.on('user:fetchAnnouncements', data => userEventsController.fetchAnnouncements(socket))
socket.on('user:updateAnnouncement', data => userEventsController.updateAnnouncement(socket, data))
})
}
+23
View File
@@ -0,0 +1,23 @@
function init(server) {
// init params
const { WebSocketPort, NuxtPort, isProduction } = require('../_env')
const { userNamespace } = require('./namespaces/user_NameSpace')
const { agentNamespace } = require('./namespaces/agent_NameSpace')
const { adminNamespace } = require('./namespaces/admin_NameSpace')
const { Server } = require('socket.io')
const socketIO = require('socket.io')
// init ws
let io
if (isProduction) io = socketIO(server)
else io = new Server(WebSocketPort, { cors: { origin: '*' } })
console.log(`🟢 ~ WebSocket Server is listening on port ${isProduction ? NuxtPort : WebSocketPort}`)
global._io = io
// namespaces
userNamespace()
agentNamespace()
adminNamespace()
}
module.exports = init