full
This commit is contained in:
68
utils/offerReplyGate.js
Normal file
68
utils/offerReplyGate.js
Normal file
@@ -0,0 +1,68 @@
|
||||
const OfferModel = require('../models/OfferModel')
|
||||
const WalletTransactionModel = require('../models/WalletTransactionModel')
|
||||
|
||||
const OFFER_REPLY_WINDOW_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
/**
|
||||
* Called whenever a chat message is sent. If there's a pending paid Offer
|
||||
* between these two users, tracks the requester's first direct message and
|
||||
* the receiver's reply — the receiver's 30% commission is only credited if
|
||||
* they reply within 24 hours of that first message.
|
||||
*/
|
||||
async function trackOfferMessageForCommission (io, senderId, receiverId) {
|
||||
try {
|
||||
const offer = await OfferModel.findOne({
|
||||
$or: [
|
||||
{ sender: senderId, receiver: receiverId },
|
||||
{ sender: receiverId, receiver: senderId }
|
||||
],
|
||||
commissionCredited: false,
|
||||
pendingCommissionAmount: { $gt: 0 }
|
||||
}).sort({ createdAt: -1 })
|
||||
|
||||
if (!offer) return
|
||||
|
||||
const isFromRequester = String(offer.sender) === String(senderId)
|
||||
|
||||
if (isFromRequester) {
|
||||
if (!offer.firstMessageAt) {
|
||||
offer.firstMessageAt = new Date()
|
||||
offer.replyDeadline = new Date(Date.now() + OFFER_REPLY_WINDOW_MS)
|
||||
await offer.save()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// پیام از طرف گیرنده — کسی که باید ظرف ۲۴ ساعت پاسخ بدهد
|
||||
if (!offer.firstMessageAt || offer.repliedAt) return
|
||||
if (new Date() > offer.replyDeadline) return
|
||||
|
||||
offer.repliedAt = new Date()
|
||||
offer.commissionCredited = true
|
||||
await offer.save()
|
||||
|
||||
await WalletTransactionModel.create({
|
||||
user: offer.receiver,
|
||||
bucket: 'gift',
|
||||
type: 'credit',
|
||||
amount: offer.pendingCommissionAmount,
|
||||
referenceType: 'payment',
|
||||
referenceId: offer._id,
|
||||
description: 'سهم دریافتی از درخواست همکاری (۳۰٪، پس از پاسخ بهموقع)'
|
||||
})
|
||||
|
||||
if (io) {
|
||||
try {
|
||||
io.to(`user:${String(offer.receiver)}`).emit('notification', {
|
||||
type: 'offer_commission',
|
||||
title: 'واریز سهم درخواست همکاری',
|
||||
description: 'با پاسخ بهموقع، ۳۰٪ مبلغ درخواست همکاری به کیف پول شما واریز شد.'
|
||||
})
|
||||
} catch (_) {}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('trackOfferMessageForCommission error:', error)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { trackOfferMessageForCommission, OFFER_REPLY_WINDOW_MS }
|
||||
Reference in New Issue
Block a user