@@ -472,3 +472,95 @@ export const softDeleteDepartment = async (req, res, next) => {
472472 next ( error ) ;
473473 }
474474} ;
475+
476+ /**
477+ * @desc Restore a soft-deleted department
478+ * @route PATCH /api/department/:id/restore
479+ * @access Private (Owner or Admin only)
480+ */
481+ export const restoreDepartment = async ( req , res , next ) => {
482+ try {
483+ const { id } = req . params ;
484+ const { userId, role } = req . user ;
485+
486+ // 1. Check if department exists and is deleted
487+ const department = await prisma . department . findUnique ( {
488+ where : { id } ,
489+ include : {
490+ organization : true ,
491+ manager : true ,
492+ } ,
493+ } ) ;
494+
495+ if ( ! department ) {
496+ return res . status ( 404 ) . json ( {
497+ success : false ,
498+ message : 'Department not found' ,
499+ } ) ;
500+ }
501+
502+ if ( ! department . deletedAt ) {
503+ return res . status ( 400 ) . json ( {
504+ success : false ,
505+ message : 'Department is not deleted' ,
506+ } ) ;
507+ }
508+
509+ // 2. Verify permissions (Owner or Admin of the organization)
510+ // For ADMIN/OWNER, check if they belong to the department's organization
511+ const userInOrg = await prisma . user . findFirst ( {
512+ where : {
513+ id : userId ,
514+ organizationId : department . organizationId ,
515+ role : { in : [ 'ADMIN' , 'OWNER' ] } ,
516+ deletedAt : null ,
517+ } ,
518+ } ) ;
519+
520+ if ( ! userInOrg ) {
521+ return res . status ( 403 ) . json ( {
522+ success : false ,
523+ message :
524+ 'You do not have permission to restore departments in this organization' ,
525+ } ) ;
526+ }
527+
528+ // 3. Restore the department
529+ const restoredDepartment = await prisma . department . update ( {
530+ where : { id } ,
531+ data : {
532+ deletedAt : null ,
533+ } ,
534+ include : {
535+ organization : { select : { id : true , name : true } } ,
536+ manager : {
537+ select : { id : true , firstName : true , lastName : true , role : true } ,
538+ } ,
539+ users : {
540+ where : { deletedAt : null } ,
541+ select : {
542+ id : true ,
543+ firstName : true ,
544+ lastName : true ,
545+ email : true ,
546+ role : true ,
547+ } ,
548+ } ,
549+ teams : {
550+ select : {
551+ id : true ,
552+ name : true ,
553+ } ,
554+ } ,
555+ } ,
556+ } ) ;
557+
558+ return res . status ( 200 ) . json ( {
559+ success : true ,
560+ message : 'Department restored successfully' ,
561+ data : restoredDepartment ,
562+ } ) ;
563+ } catch ( error ) {
564+ next ( error ) ;
565+ }
566+ } ;
0 commit comments