52 lines
1.8 KiB
JavaScript
52 lines
1.8 KiB
JavaScript
const UserModel = require('../models/UserModel')
|
|
const FREE_LIFETIME_CREATION_LIMIT = 100
|
|
|
|
const canUseFreeCreation = (user) => {
|
|
const used = user?.lifetime_free_creations || 0
|
|
return used < FREE_LIFETIME_CREATION_LIMIT
|
|
}
|
|
|
|
const remainingFreeCreations = (user) => {
|
|
const used = user?.lifetime_free_creations || 0
|
|
return Math.max(0, FREE_LIFETIME_CREATION_LIMIT - used)
|
|
}
|
|
|
|
const consumeFreeCreation = async (user) => {
|
|
if (!canUseFreeCreation(user)) {
|
|
return {
|
|
ok: false,
|
|
message: `سقف ${FREE_LIFETIME_CREATION_LIMIT} ثبت رایگان (پروژه، بیلبورد و درخواست) به پایان رسیده است.`,
|
|
}
|
|
}
|
|
|
|
// updateOne + $inc (اتمیک، فقط همین فیلد) بهجای user.save() — save() کل سند رو
|
|
// ریولیدیت میکنه و برای کاربرهایی با مقدار نامعتبر در فیلدهای دیگه (مثلاً
|
|
// income_range) با ValidationError شکست میخوره
|
|
const res = await UserModel.updateOne(
|
|
{ _id: user._id, lifetime_free_creations: { $lt: FREE_LIFETIME_CREATION_LIMIT } },
|
|
{ $inc: { lifetime_free_creations: 1 } }
|
|
)
|
|
if (!res.modifiedCount) {
|
|
return {
|
|
ok: false,
|
|
message: `سقف ${FREE_LIFETIME_CREATION_LIMIT} ثبت رایگان (پروژه، بیلبورد و درخواست) به پایان رسیده است.`,
|
|
}
|
|
}
|
|
user.lifetime_free_creations = (user.lifetime_free_creations || 0) + 1
|
|
|
|
return { ok: true }
|
|
}
|
|
|
|
const freeCreationLimitResponse = () => ({
|
|
error: true,
|
|
message: `سقف ${FREE_LIFETIME_CREATION_LIMIT} ثبت رایگان (پروژه، بیلبورد و درخواست) به پایان رسیده است.`,
|
|
})
|
|
|
|
module.exports = {
|
|
FREE_LIFETIME_CREATION_LIMIT,
|
|
canUseFreeCreation,
|
|
remainingFreeCreations,
|
|
consumeFreeCreation,
|
|
freeCreationLimitResponse,
|
|
}
|