add delete option to roles

This commit is contained in:
yotakii
2026-03-02 10:44:23 +03:00
parent 5164f04b66
commit 0b886e81f0
6 changed files with 197 additions and 16 deletions

View File

@@ -145,6 +145,16 @@ class AdminController {
next(error);
}
}
async deletePosition(req: AuthRequest, res: Response, next: NextFunction) {
try {
const userId = req.user!.id;
await adminService.deletePosition(req.params.id, userId);
res.json(ResponseFormatter.success(null, 'Role deleted successfully'));
} catch (error) {
next(error);
}
}
}
export const adminController = new AdminController();
export const adminController = new AdminController();

View File

@@ -89,6 +89,15 @@ router.get(
adminController.getPositions
);
// Delete (soft delete) a role/position
router.delete(
'/positions/:id',
authorize('admin', 'roles', 'delete'),
param('id').isUUID(),
validate,
adminController.deletePosition
);
router.put(
'/positions/:id/permissions',
authorize('admin', 'roles', 'update'),
@@ -100,4 +109,4 @@ router.put(
adminController.updatePositionPermissions
);
export default router;
export default router;

View File

@@ -429,6 +429,57 @@ class AdminService {
return this.getPositions().then((pos) => pos.find((p) => p.id === positionId) || position);
}
/**
* Soft delete a role (Position).
* - Prevent deletion if the position is assigned to any employees.
* - Clean up position permissions.
*/
async deletePosition(positionId: string, deletedById: string) {
const position = await prisma.position.findUnique({
where: { id: positionId },
include: {
_count: { select: { employees: true } },
},
});
if (!position) {
throw new AppError(404, 'الدور غير موجود - Position not found');
}
if (position._count.employees > 0) {
throw new AppError(
400,
'لا يمكن حذف هذا الدور لأنه مرتبط بموظفين. قم بتغيير دور الموظفين أولاً - Cannot delete: position is assigned to employees'
);
}
// Soft delete the position
await prisma.position.update({
where: { id: positionId },
data: { isActive: false },
});
// Clean up permissions linked to this position
await prisma.positionPermission.deleteMany({
where: { positionId },
});
await AuditLogger.log({
entityType: 'POSITION',
entityId: positionId,
action: 'DELETE',
userId: deletedById,
changes: {
softDeleted: true,
title: position.title,
titleAr: position.titleAr,
code: position.code,
},
});
return { success: true };
}
}
export const adminService = new AdminService();
export const adminService = new AdminService();