85 lines
2.6 KiB
JavaScript
85 lines
2.6 KiB
JavaScript
const Permission = require('./permissionModel')
|
|
const permissionsList = require('./permissionList')
|
|
const AppError = require('../../globalErrorHandler/AppError')
|
|
|
|
module.exports.syncPermissions = async () => {
|
|
try {
|
|
let createdCount = 0
|
|
let updatedCount = 0
|
|
|
|
for (const item of permissionsList) {
|
|
const existing = await Permission.findOne({ key: item.key })
|
|
if (!existing) {
|
|
await Permission.create({
|
|
englishName: item.englishName,
|
|
nativeName: item.nativeName,
|
|
key: item.key,
|
|
category: item.category,
|
|
isActive: true,
|
|
})
|
|
createdCount++
|
|
} else {
|
|
let changed = false
|
|
if (existing.englishName !== item.englishName) {
|
|
existing.englishName = item.englishName
|
|
changed = true
|
|
}
|
|
if (existing.nativeName !== item.nativeName) {
|
|
existing.nativeName = item.nativeName
|
|
changed = true
|
|
}
|
|
if (existing.category !== item.category) {
|
|
existing.category = item.category
|
|
changed = true
|
|
}
|
|
if (changed) {
|
|
await existing.save()
|
|
updatedCount++
|
|
}
|
|
}
|
|
}
|
|
|
|
console.log(`[Permissions] Sync complete: ${createdCount} created, ${updatedCount} updated.`)
|
|
} catch (error) {
|
|
console.error('[Permissions] Error during sync:', error.message)
|
|
}
|
|
}
|
|
|
|
module.exports.getAllPermissions = async () => {
|
|
return Permission.find({}).sort({ category: 1, englishName: 1 })
|
|
}
|
|
|
|
module.exports.createPermission = async (data) => {
|
|
return await Permission.create(data)
|
|
}
|
|
|
|
module.exports.getPermission = async (permissionId) => {
|
|
const permission = await Permission.findById(permissionId)
|
|
|
|
if (!permission) {
|
|
throw AppError('NoPermissionFound', 404, {})
|
|
}
|
|
|
|
return permission
|
|
}
|
|
|
|
module.exports.updatePermission = async (permissionId, data) => {
|
|
const permission = await Permission.findOneAndUpdate({ _id: permissionId }, data, { new: true })
|
|
|
|
if (!permission) {
|
|
throw AppError('NoPermissionFound', 404, {})
|
|
}
|
|
|
|
return permission
|
|
}
|
|
|
|
module.exports.deletePermission = async (permissionId) => {
|
|
const permission = await Permission.findOneAndDelete({ _id: permissionId })
|
|
|
|
if (!permission) {
|
|
throw AppError('NoPermissionFound', 404, {})
|
|
}
|
|
|
|
return null
|
|
}
|