public function execute(CommandContext $context)
 {
     // Get input
     $requestId = $context->get('requestId');
     $participantId = $context->get('participantId');
     // Command for showing the request, redirected to on success/error
     $cmd = CommandFactory::getCommand('ShowManageRoomChange');
     $cmd->setRequestId($requestId);
     // Load the request
     $request = RoomChangeRequestFactory::getRequestById($requestId);
     // Load the participant
     $participant = RoomChangeParticipantFactory::getParticipantById($participantId);
     // Check permissions. Must be an RD for current bed, or an admin
     $rds = $participant->getFutureRdList();
     if (!in_array(UserStatus::getUsername(), $rds) && !Current_User::allow('hms', 'admin_approve_room_change')) {
         throw new PermissionException('You do not have permission to approve this room change.');
     }
     // Transition to CurrRdApproved
     $participant->transitionTo(new ParticipantStateFutureRdApproved($participant, time(), null, UserStatus::getUsername()));
     //TODO If all participants are approved, send notification to Housing
     if ($request->isApprovedByAllFutureRDs()) {
         HMS_Email::sendRoomChangeAdministratorNotice($request);
     }
     // Redirect to the manage request page
     $cmd->redirect();
 }
Example #2
0
 public function getMenuBlockView(Student $student)
 {
     PHPWS_Core::initModClass('hms', 'RoomChangeMenuBlockView.php');
     PHPWS_Core::initModClass('hms', 'HMS_Assignment.php');
     PHPWS_Core::initModClass('hms', 'RoomChangeRequestFactory.php');
     $assignment = HMS_Assignment::getAssignment($student->getUsername(), $this->term);
     $request = RoomChangeRequestFactory::getPendingByStudent($student, $this->term);
     return new RoomChangeMenuBlockView($student, $this->term, $this->getStartDate(), $this->getEndDate(), $assignment, $request);
 }
 public function execute(CommandContext $context)
 {
     $term = Term::getCurrentTerm();
     // Get the list of role memberships this user has
     // NB: This gets memberships for all terms.. must filter later
     $hms_perm = new HMS_Permission();
     $memberships = $hms_perm->getMembership('room_change_approve', NULL, UserStatus::getUsername());
     // Use the roles to instantiate a list of floors this user has access to
     $floors = array();
     foreach ($memberships as $member) {
         if ($member['class'] == 'hms_residence_hall') {
             $hall = new HMS_Residence_Hall($member['instance']);
             // Filter out halls that aren't in the current term
             if ($hall->getTerm() != $term) {
                 continue;
             }
             $floors = array_merge($floors, $hall->getFloors());
         } else {
             if ($member['class'] == 'hms_floor') {
                 $f = new HMS_Floor($member['instance']);
                 // Filter out floors that aren't in the current term
                 if ($f->getTerm() != $term) {
                     continue;
                 }
                 $floors[] = $f;
             } else {
                 throw new Exception('Unknown object type.');
             }
         }
     }
     if (empty($floors)) {
         PHPWS_Core::initModClass('hms', 'exception/PermissionException.php');
         NQ::simple('hms', hms\NotificationView::ERROR, "You do not have the 'RD' role on any residence halls or floors.");
         $cmd = CommandFactory::getCommand('ShowAdminMaintenanceMenu');
         $cmd->redirect();
     }
     // Remove duplicate floors
     $uniqueFloors = array();
     foreach ($floors as $floor) {
         $uniqueFloors[$floor->getId()] = $floor;
     }
     // Use the list of floors to get a unique list of hall names
     $hallNames = array();
     foreach ($uniqueFloors as $floor) {
         $hall = $floor->get_parent();
         $hallNames[$hall->getId()] = $hall->getHallName();
     }
     // Get the set of room changes which are not complete based on the floor list
     $needsApprovalChanges = RoomChangeRequestFactory::getRoomChangesNeedsApproval($term, $uniqueFloors);
     $approvedChanges = RoomChangeRequestFactory::getRoomChangesByFloor($term, $uniqueFloors, array('Approved'));
     $allPendingChanges = RoomChangeRequestFactory::getRoomChangesByFloor($term, $uniqueFloors, array('Pending', 'Hold'));
     $completedChanges = RoomChangeRequestFactory::getRoomChangesByFloor($term, $uniqueFloors, array('Complete'));
     $inactiveChanges = RoomChangeRequestFactory::getRoomChangesByFloor($term, $uniqueFloors, array('Cancelled', 'Denied'));
     $view = new RoomChangeApprovalView($needsApprovalChanges, $approvedChanges, $allPendingChanges, $completedChanges, $inactiveChanges, $hallNames, $term);
     $context->setContent($view->show());
 }
 public function execute(CommandContext $context)
 {
     $term = Term::getCurrentTerm();
     // Create the student
     $student = StudentFactory::getStudentByUsername(UserStatus::getUsername(), $term);
     // If the student has a pending request load it from the db
     $request = RoomChangeRequestFactory::getPendingByStudent($student, $term);
     $view = new RoomChangeRequestForm($student, $term);
     $context->setContent($view->show());
 }
 public function execute(CommandContext $context)
 {
     PHPWS_Core::initModClass('hms', 'RoomChangeRequestFactory.php');
     PHPWS_Core::initModClass('hms', 'RoomChangeManageView.php');
     $requestId = $context->get('requestId');
     if (!isset($requestId) || is_null($context)) {
         throw new InvalidArgumentException('Missing request id');
     }
     $request = RoomChangeRequestFactory::getRequestById($requestId);
     if (is_null($request) || $request === false) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Invalid room change request id.');
         $cmd = CommandFactory::getCommand('ShowAdminMaintenanceMenu');
         $cmd->redirect();
     }
     $view = new RoomChangeManageView($request);
     $context->setContent($view->show());
 }
 public function execute(CommandContext $context)
 {
     // Get input
     $requestId = $context->get('requestId');
     $participantId = $context->get('participantId');
     // Command for showing the request, redirected to on success/error
     $cmd = CommandFactory::getCommand('ShowManageRoomChange');
     $cmd->setRequestId($requestId);
     // Load the request
     $request = RoomChangeRequestFactory::getRequestById($requestId);
     // Load the participant
     $participant = RoomChangeParticipantFactory::getParticipantById($participantId);
     // Load the Student
     $student = StudentFactory::getStudentByBannerId($participant->getBannerId(), $request->getTerm());
     // Check permissions. Must be the participant or an admin
     if (UserStatus::getUsername() != $student->getUsername() && !Current_User::allow('hms', 'admin_approve_room_change')) {
         throw new PermissionException('You do not have permission to appove this room change.');
     }
     // Check for CAPTCHA if this is the student; admins don't need a CAPTCHA
     $captchaResult = Captcha::verify(true);
     if (UserStatus::getUsername() == $student->getUsername() && $captchaResult === false) {
         // Failed the captcha
         NQ::simple('hms', hms\NotificationView::ERROR, "You didn't type the magic words correctly. Please try again.");
         $cmd = CommandFactory::getCommand('ShowRoomChangeRequestApproval');
         $cmd->redirect();
     }
     // If there was a captcha, then log the activity
     if ($captchaResult !== false) {
         HMS_Activity_Log::log_activity(UserStatus::getUsername(), ACTIVITY_ROOM_CHANGE_AGREED, UserStatus::getUsername(FALSE), 'Request id: ' . $requestId . ' Captcha: ' . $captchaResult);
     }
     // Transition to StudentApproved state
     $participant->transitionTo(new ParticipantStateStudentApproved($participant, time(), null, UserStatus::getUsername()));
     // If all students have approved, notify RDs
     if ($request->isApprovedByAllParticipants()) {
         HMS_Email::sendRoomChangeCurrRDNotice($request);
     }
     // If the student is logged in, redirect to the main menu, other wise go back to the room change management view
     if (UserStatus::getUsername() == $student->getUsername()) {
         NQ::simple('hms', hms\NotificationView::SUCCESS, 'You have agreed to the room change request. You will be notified by email when the reqeust is approved or denied.');
         $menuCmd = CommandFactory::getCommand('ShowStudentMenu');
         $menuCmd->redirect();
     } else {
         $cmd->redirect();
     }
 }
 public function execute(CommandContext $context)
 {
     $requestId = $context->get('requestId');
     $reason = $context->get('cancel-reason');
     // Load the request
     $request = RoomChangeRequestFactory::getRequestById($requestId);
     // TODO Check permissions, based on state
     // Command for redirecting back to the request view on success or error
     $cmd = CommandFactory::getCommand('ShowManageRoomChange');
     $cmd->setRequestId($request->getId());
     // Make sure user gave a reason
     if (!isset($reason) or $reason == '') {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Please enter a cancellation reason.');
         $cmd->redirect();
     }
     // Set the denied reason
     $request->setDeniedReasonPublic($reason);
     $request->save();
     // Transition request to cancelled status
     $request->transitionTo(new RoomChangeStateCancelled($request, time(), null, UserStatus::getUsername()));
     // Transition all participants to cancelled
     // TODO... Do this in the cancelled transition?
     $participants = $request->getParticipants();
     foreach ($participants as $p) {
         $p->transitionTo(new ParticipantStateCancelled($p, time(), null, UserStatus::getUsername()));
         //Release the bed reservation, if any
         $bedId = $p->getToBed();
         if ($bedId != null) {
             $bed = new HMS_Bed($bedId);
             $bed->clearRoomChangeReserved();
             $bed->save();
         }
     }
     // Notify everyone involved
     try {
         PHPWS_Core::initModClass('hms', 'StudentFactory.php');
         $student = StudentFactory::getStudentByUsername(UserStatus::getUsername(), $request->getTerm());
     } catch (StudentNotFoundException $e) {
         $student = null;
     }
     PHPWS_Core::initModClass('hms', 'HMS_Email.php');
     HMS_Email::sendRoomChangeCancelledNotice($request, $student);
     $cmd->redirect();
 }
 public function execute(CommandContext $context)
 {
     if (!Current_User::allow('hms', 'admin_approve_room_change')) {
         PHPWS_Core::initModClasS('hms', 'exception/PermissionException.php');
         throw new PermissionException('You do not have permission to approve room changes.');
     }
     PHPWS_Core::initModClass('hms', 'RoomChangeRequestFactory.php');
     PHPWS_Core::initModClass('hms', 'RoomChangeApprovalView.php');
     $term = Term::getSelectedTerm();
     // Get all requests in the FutureRDApproved state (i.e. waiting on housing assignments office)
     $needsApprovalChanges = RoomChangeRequestFactory::getAllRoomChangesNeedsAdminApproval($term);
     // Get all requests that are Approved (in-progress)
     $allApproved = RoomChangeRequestFactory::getAllRoomChangesByState($term, array('Approved'));
     // Get all requests that are pending/in-progress, but not waiting on Housing
     $allPending = RoomChangeRequestFactory::getAllRoomChangesByState($term, array('Pending', 'Hold'));
     // Get all complete requests
     $allComplete = RoomChangeRequestFactory::getAllRoomChangesByState($term, array('Complete'));
     // Get all requests that are inactive (cancelled, denied, complete)
     $allInactive = RoomChangeRequestFactory::getAllRoomChangesByState($term, array('Cancelled', 'Denied'));
     $view = new RoomChangeApprovalView($needsApprovalChanges, $allApproved, $allPending, $allComplete, $allInactive, array('All Halls'), $term);
     $context->setContent($view->show());
 }
 public function execute(CommandContext $context)
 {
     // Get input
     $requestId = $context->get('requestId');
     $participantId = $context->get('participantId');
     // Load the request
     $request = RoomChangeRequestFactory::getRequestById($requestId);
     // Load the participant
     $participant = RoomChangeParticipantFactory::getParticipantById($participantId);
     // Load the Student
     $student = StudentFactory::getStudentByBannerId($participant->getBannerId(), $request->getTerm());
     // Check permissions. Must be the participant or an admin
     if (UserStatus::getUsername() != $student->getUsername() && !Current_User::allow('hms', 'admin_approve_room_change')) {
         throw new PermissionException('You do not have permission to decline this room change.');
     }
     // Check for CAPTCHA if this is the student; admins don't need a CAPTCHA
     $captchaResult = Captcha::verify(true);
     if ($captchaResult === false) {
         // Failed the captcha
         NQ::simple('hms', hms\NotificationView::ERROR, "You didn't type the magic words correctly. Please try again.");
         $cmd = CommandFactory::getCommand('ShowRoomChangeRequestApproval');
         $cmd->redirect();
     }
     HMS_Activity_Log::log_activity(UserStatus::getUsername(), ACTIVITY_ROOM_CHANGE_DECLINE, UserStatus::getUsername(FALSE), 'Request id: ' . $requestId . ' Captcha: ' . $captchaResult);
     // Transition request to cancelled status
     $request->transitionTo(new RoomChangeStateCancelled($request, time(), null, UserStatus::getUsername()));
     // Transition all participants to cancelled
     // TODO... Do this in the cancelled transition?
     $participants = $request->getParticipants();
     foreach ($participants as $p) {
         $p->transitionTo(new ParticipantStateCancelled($p, time(), null, UserStatus::getUsername()));
     }
     // TODO Notify everyone that the request was cancelled
     NQ::simple('hms', hms\NotificationView::SUCCESS, 'You have declined the room change request.');
     $menuCmd = CommandFactory::getCommand('ShowStudentMenu');
     $menuCmd->redirect();
 }
 public function execute(CommandContext $context)
 {
     // Get input
     $requestId = $context->get('requestId');
     $participantId = $context->get('participantId');
     // destinationBedId - This can be null for "swap" requests, because it's already known
     $toBedSelected = $context->get('bed_select');
     // Command for showing the request, redirected to on success/error
     $cmd = CommandFactory::getCommand('ShowManageRoomChange');
     $cmd->setRequestId($requestId);
     // Load the request
     $request = RoomChangeRequestFactory::getRequestById($requestId);
     // Load the participant
     $participant = RoomChangeParticipantFactory::getParticipantById($participantId);
     // Check permissions. Must be an RD for current bed, or an admin
     $rds = $participant->getCurrentRdList();
     if (!in_array(UserStatus::getUsername(), $rds) && !Current_User::allow('hms', 'admin_approve_room_change')) {
         throw new PermissionException('You do not have permission to approve this room change.');
     }
     // Check that a destination bed has already been set, or that the RD
     // has just selected a bed
     $toBedId = $participant->getToBed();
     if (is_null($toBedId) && $toBedSelected == '-1') {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Please select a destination bed.');
         $cmd->redirect();
     }
     // Set the selected bed, if needed
     if (is_null($toBedId) && $toBedSelected != '-1') {
         $bed = new HMS_Bed($toBedSelected);
         // Check that the bed isn't already reserved for a room change
         if ($bed->isRoomChangeReserved()) {
             NQ::simple('hms', hms\NotificationView::ERROR, 'The bed you selected is already reserved for a room change. Please choose a different bed.');
             $cmd->redirect();
         }
         // Reserve the bed for room change
         $bed->setRoomChangeReserved();
         $bed->save();
         // Save the bed to this participant
         $participant->setToBed($bed);
         $participant->save();
     }
     // Transition to CurrRdApproved
     $participant->transitionTo(new ParticipantStateCurrRdApproved($participant, time(), null, UserStatus::getUsername()));
     // If the future RD is the same as the current user Logged in, then go ahead and transition to FutureRdApproved too.
     //TODO
     if ($request->isApprovedByAllCurrentRDs()) {
         // If all Current RDs have approved, notify Future RDs
         HMS_Email::sendRoomChangeFutureRDNotice($request);
         // If all Current RDs have approved, notify future roommates
         foreach ($request->getParticipants() as $p) {
             $bed = new HMS_Bed($p->getToBed());
             $room = $bed->get_parent();
             foreach ($room->get_assignees() as $a) {
                 if ($a instanceof Student && $a->getBannerID() != $p->getBannerID()) {
                     HMS_Email::sendRoomChangePreliminaryRoommateNotice($a);
                 }
             }
         }
     }
     // Redirect to the manage request page
     $cmd->redirect();
 }
 public function execute(CommandContext $context)
 {
     // Get input
     $requestId = $context->get('requestId');
     // Get the current term
     $term = Term::getCurrentTerm();
     // Load the request
     $request = RoomChangeRequestFactory::getRequestById($requestId);
     // Load the participants
     $participants = $request->getParticipants();
     // Make sure everyone is checked into their current assignments
     if (!$request->allParticipantsCheckedIn()) {
         // Return the user to the room change request page
         // NB, don't need an error message here because it should already be printed
         // by the RoomChangeParticipantView.
         $cmd = CommandFactory::getCommand('ShowManageRoomChange');
         $cmd->setRequestId($requestId);
         $cmd->redirect();
     }
     // Transition the request to 'Approved'
     $request->transitionTo(new RoomChangeStateApproved($request, time(), null, UserStatus::getUsername()));
     // Remove each participants existing assignment
     foreach ($participants as $participant) {
         $bannerId = $participant->getBannerId();
         // Lookup the student
         $student = StudentFactory::getStudentByBannerId($bannerId, $term);
         // Save student object for later
         $this->students[$bannerId] = $student;
         // Save student's current assignment reason for later re-use
         $assignment = HMS_Assignment::getAssignmentByBannerId($bannerId, $term);
         //TODO - Student might not be assigned!!
         $this->assignmentReasons[$bannerId] = $assignment->getReason();
         // Remove existing assignment
         // TODO: Don't hard code refund percentage
         HMS_Assignment::unassignStudent($student, $term, 'Room Change Request Approved', UNASSIGN_CHANGE, 100);
     }
     // Create new assignments for each participant
     foreach ($participants as $participant) {
         // Grab the student object which was previously saved
         $student = $this->students[$participant->getBannerId()];
         // Create each new assignment
         HMS_Assignment::assignStudent($student, $term, null, $participant->getToBed(), BANNER_MEAL_STD, 'Room Change Approved', FALSE, $this->assignmentReasons[$bannerId]);
         // Release bed reservation
         $bed = new HMS_Bed($participant->getToBed());
         $bed->clearRoomChangeReserved();
         $bed->save();
     }
     // Transition each participant to 'In Process'
     foreach ($participants as $participant) {
         $participant->transitionTo(new ParticipantStateInProcess($participant, time(), null, UserStatus::getUsername()));
         // TODO: Send notifications
     }
     // Notify everyone that they can do the move
     HMS_Email::sendRoomChangeInProcessNotice($request);
     // Notify roommates that their circumstances are going to change
     foreach ($request->getParticipants() as $p) {
         $student = $this->students[$p->getBannerId()];
         // New Roommate
         $newbed = new HMS_Bed($p->getToBed());
         $newroom = $newbed->get_parent();
         foreach ($newroom->get_assignees() as $a) {
             if ($a instanceof Student && $a->getBannerID() != $p->getBannerID()) {
                 HMS_Email::sendRoomChangeApprovedNewRoommateNotice($a, $student);
             }
         }
         // Old Roommate
         $oldbed = new HMS_Bed($p->getFromBed());
         $oldroom = $oldbed->get_parent();
         foreach ($oldroom->get_assignees() as $a) {
             if ($a instanceof Student && $a->getBannerID() != $p->getBannerID()) {
                 HMS_Email::sendRoomChangeApprovedOldRoommateNotice($a, $student);
             }
         }
     }
     // Return the user to the room change request page
     $cmd = CommandFactory::getCommand('ShowManageRoomChange');
     $cmd->setRequestId($requestId);
     $cmd->redirect();
 }
 public function execute(CommandContext $context)
 {
     // Cmd to redirect to when we're done or upon error.
     $formCmd = CommandFactory::getCommand('ShowRoomChangeRequestForm');
     $menuCmd = CommandFactory::getCommand('ShowStudentMenu');
     // Get input
     $cellNum = $context->get('cell_num');
     $optOut = $context->get('cell_opt_out');
     $firstHallPref = $context->get('first_choice');
     $secondHallPref = $context->get('second_choice');
     $term = Term::getCurrentTerm();
     // Create the student object
     $student = StudentFactory::getStudentByUsername(UserStatus::getUsername(), $term);
     // Make sure the student is currently assigned
     $assignment = HMS_Assignment::getAssignmentByBannerId($student->getBannerId(), $term);
     if (is_null($assignment)) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'You are not currently assigned to a room, so you cannot request a room change.');
         $menuCmd->redirect();
     }
     // Get the HMS_Bed object corresponding to the student's current assignment
     $bed = $assignment->get_parent();
     $room = $bed->get_parent();
     // Check for an existing room change request
     $changeReq = RoomChangeRequestFactory::getPendingByStudent($student, $term);
     if (!is_null($changeReq)) {
         // has pending request
         NQ::simple('hms', hms\NotificationView::ERROR, 'You already have a pending room change request. You cannot submit another request until your pending request is processed.');
         $menuCmd->redirect();
     }
     // Check that a cell phone number was provided, or that the opt-out box was checked.
     if ((!isset($cellNum) || empty($cellNum)) && !isset($optOut)) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Please provide a cell phone number or check the box indicating you do not wish to provide it.');
         $formCmd->redirect();
     }
     // Check the format of the cell phone number
     if (isset($cellNum)) {
         // Filter out non-numeric characters
         $cellNum = preg_replace("/[^0-9]/", '', $cellNum);
     }
     $reason = $context->get('reason');
     // Make sure a 'reason' was provided.
     if (!isset($reason) || empty($reason)) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Please provide a brief explaniation of why you are requesting a room change.');
         $formCmd->redirect();
     }
     $type = $context->get('type');
     // Extra sanity checks if we're doing a switch
     if ($type == 'swap') {
         $switchUsername = $context->get('swap_with');
         // Can't switch with yourself
         if ($student->getUsername() == $switchUsername) {
             NQ::simple('hms', hms\NotificationView::ERROR, "You can't swtich rooms with yourself. Please choose someone other than yourself.");
             $formCmd->redirect();
         }
         // Load the other student
         try {
             $swapStudent = StudentFactory::getStudentByUsername($switchUsername, $term);
         } catch (StudentNotFoundException $e) {
             NQ::simple('hms', hms\NotificationView::ERROR, "Sorry, we could not find a student with the user name '{$switchUsername}'. Please double-check the user name of the student you would like to switch places with.");
             $formCmd->redirect();
         }
         // Make sure the student is assigned
         $swapAssignment = HMS_Assignment::getAssignmentByBannerId($swapStudent->getBannerId(), $term);
         if (is_null($swapAssignment)) {
             NQ::simple('hms', hms\NotificationView::ERROR, "{$swapStudent->getName()} is not currently assigned. Please choose another student to switch rooms with.");
             $formCmd->redirect();
         }
         // Make sure the other student's room is the same gender as this room
         $swapBed = $swapAssignment->get_parent();
         $swapRoom = $swapBed->get_parent();
         if ($swapRoom->getGender() != $room->getGender()) {
             NQ::simple('hms', hms\NotificationView::ERROR, "{$swapStudent->getName()} is assigned to a room of a different gender than you. Please choose student of the same gender as yourself to switch rooms with.");
             $formCmd->redirect();
         }
         // Check to see if the other student is already involved in a room change request
         $swapStudentReq = RoomChangeRequestFactory::getPendingByStudent($swapStudent, $term);
         if (!is_null($swapStudentReq)) {
             // has pending request
             NQ::simple('hms', hms\NotificationView::ERROR, 'The student you are requesting to swap with already has a pending room change request. You cannot request to swap with him/her until the pending request is processed.');
             $menuCmd->redirect();
         }
     }
     //create the request object
     $request = new RoomChangeRequest($term, $reason);
     $request->save();
     // Main participant
     $participant = new RoomChangeParticipant($request, $student, $bed);
     if (isset($cellNum)) {
         $participant->setCellPhone($cellNum);
     }
     // Switching to a different room, so set params on main participant
     if ($type == 'switch') {
         // preferences
         if (!empty($firstHallPref)) {
             $hall = new HMS_Residence_Hall($firstHallPref);
             if (!is_null($hall->getId())) {
                 $participant->setHallPref1($hall);
             }
         }
         if (!empty($secondHallPref)) {
             $hall = new HMS_Residence_Hall($secondHallPref);
             if (!is_null($hall->getId())) {
                 $participant->setHallPref2($hall);
             }
         }
         // Save the main participant and its state
         $participant->save();
         // No further approval is required so we skip a step
         HMS_Email::sendRoomChangeCurrRDNotice($request);
     } else {
         if ($type == 'swap') {
             // Swapping with another student, so handle the other particpant
             // Set main participant's toBed to other student's bed
             $participant->setToBed($swapBed);
             // Create the other participant
             $swapParticipant = new RoomChangeParticipant($request, $swapStudent, $swapBed);
             // Set other student's toBed to main participant's bed
             $swapParticipant->setToBed($bed);
             $swapParticipant->save();
             // Save the main participant and its state
             $participant->save();
             // Send "request needs your approval" to other students
             // TODO: When you add the ability to have many people on this request, you will
             //       need to put a foreach loop here or something.
             HMS_Email::sendRoomChangeParticipantNotice($participant, $swapParticipant);
         }
     }
     // Immediately transition to the StudentApproved state.
     $participant->transitionTo(new ParticipantStateStudentApproved($participant, time(), null, UserStatus::getUsername()));
     HMS_Activity_Log::log_activity(UserStatus::getUsername(), ACTIVITY_ROOM_CHANGE_SUBMITTED, UserStatus::getUsername(FALSE), $reason);
     // Email sender with acknowledgment
     HMS_Email::sendRoomChangeRequestReceivedConfirmation($student);
     if ($type == 'switch') {
         NQ::simple('hms', hms\NotificationView::SUCCESS, 'Your room change request has been received and is pending approval. You will be contacted by your Residence Director (RD) in the next 24-48 hours regarding your request.');
     } else {
         NQ::simple('hms', hms\NotificationView::SUCCESS, 'Your room change request has been received. The student(s) you selected to swap with must sign-in and agree to the request. It will then be forwarded to your Residence Director and the Housing Assignments Office for approval.');
     }
     $menuCmd->redirect();
 }
 public function execute(CommandContext $context)
 {
     // Check permissions
     if (!Current_User::allow('hms', 'checkin')) {
         PHPWS_Core::initModClass('hms', 'exception/PermissionException.php');
         throw new PermissionException('You do not have permission to checkin students.');
     }
     // Grab data from JSON source
     $bannerId = filter_input(INPUT_POST, 'bannerId', FILTER_VALIDATE_INT);
     $checkinId = filter_input(INPUT_POST, 'checkinId', FILTER_VALIDATE_INT);
     if (empty($bannerId)) {
         throw new InvalidArgumentException('Missing banner id.');
     }
     if (empty($checkinId)) {
         throw new InvalidArgumentException('Missing checkin id.');
     }
     // Check for key code
     //$keyCode = filter_input(INPUT_POST, 'keyCode',FILTER_SANITIZE_SPECIAL_CHARS);
     $keyCode = filter_input(INPUT_POST, 'keyCode', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/[^\\W]/')));
     $keyReturned = filter_input(INPUT_POST, 'keyReturned', FILTER_VALIDATE_BOOLEAN);
     if (!isset($keyReturned) || !isset($keyCode)) {
         throw new InvalidArgumentException('Missing key return information.');
     }
     if ($keyReturned == "1" && empty($keyCode)) {
         throw new InvalidArgumentException('Missing key code.');
     }
     $properCheckout = filter_input(INPUT_POST, 'properCheckout', FILTER_VALIDATE_BOOLEAN);
     $term = Term::getCurrentTerm();
     $this->term = $term;
     // Lookup the student
     $student = StudentFactory::getStudentByBannerId($bannerId, $term);
     // Get the existing check-in
     $checkin = CheckinFactory::getCheckinById($checkinId);
     // Make sure we found a check-in
     if (is_null($checkin)) {
         /*
         NQ::simple('hms', hms\NotificationView::ERROR, "Sorry, we couldn't find a corresponding check-in for this check-out.");
         $errorCmd = CommandFactory::getCommand('ShowCheckoutForm');
         $errorCmd->setBannerId($bannerId);
         $errorCmd->setHallId($hallId);
         $errorCmd->redirect();
         */
         throw new Exception('Could not find a corresponding checkin.');
     }
     // Create the bed
     $bed = BedFactory::getBedByPersistentId($checkin->getBedPersistentId(), $term);
     // Get the room
     $room = $bed->get_parent();
     /*****
      * Add new damages
      */
     $newDamages = filter_input(INPUT_POST, 'newDamage', FILTER_SANITIZE_SPECIAL_CHARS, FILTER_REQUIRE_ARRAY);
     if (!empty($newDamages)) {
         foreach ($newDamages as $dmg) {
             $this->addDamage($dmg, $room);
         }
     }
     /******
      * Complete the Checkout
      */
     // Set checkout date and user
     $checkin->setCheckoutDate(time());
     $checkin->setCheckoutBy(Current_User::getUsername());
     // Set the checkout code code, if any
     $checkin->setCheckoutKeyCode($keyCode);
     // Improper checkout handling
     if ($properCheckout == "1") {
         $checkin->setImproperCheckout(false);
     } else {
         $checkin->setImproperCheckout(true);
         $improperNote = filter_input(INPUT_POST, 'improperNote', FILTER_SANITIZE_SPECIAL_CHARS);
         // Add damage for improper checkout
         // TODO: Find a better way to handle the magic number for dmg type
         $dmg = array('damage_type' => 105, 'side' => 'both', 'note' => $improperNote, 'residents' => array(array('studentId' => $student->getBannerId(), 'selected' => true)));
         $this->addDamage($dmg, $room);
         // Add the improper checkout note
         $checkin->setImproperCheckoutNote($improperNote);
     }
     if ($keyReturned == "1") {
         $checkin->setKeyNotReturned(false);
     } else {
         $checkin->setKeyNotReturned(true);
         // Add a damage record for key not returned
         // TODO: Find a better way to handle the magic number for dmg type
         $dmg = array('damage_type' => 79, 'side' => 'both', 'note' => 'Key not returned.', 'residents' => array(array('studentId' => $student->getBannerId(), 'selected' => true)));
         $this->addDamage($dmg, $room);
     }
     // Save the check-in
     $checkin->save();
     // Add this to the activity log
     HMS_Activity_Log::log_activity($student->getUsername(), ACTIVITY_CHECK_OUT, UserStatus::getUsername(), $bed->where_am_i());
     // Generate the RIC
     PHPWS_Core::initModClass('hms', 'InfoCard.php');
     PHPWS_Core::initModClass('hms', 'InfoCardPdfView.php');
     $infoCard = new InfoCard($checkin);
     /*
      * Info card removed per #869
     $infoCardView = new InfoCardPdfView();
     $infoCardView->addInfoCard($infoCard);
     */
     // Send confirmation Email with the RIC form to the student
     PHPWS_Core::initModClass('hms', 'HMS_Email.php');
     HMS_Email::sendCheckoutConfirmation($student, $infoCard);
     /***** Room Change Request Handling *******/
     // Check if this checkout was part of a room change request
     PHPWS_Core::initModClass('hms', 'RoomChangeRequestFactory.php');
     PHPWS_Core::initModClass('hms', 'RoomChangeParticipantFactory.php');
     $request = RoomChangeRequestFactory::getRequestPendingCheckout($student, $term);
     if (!is_null($request)) {
         $participant = RoomChangeParticipantFactory::getParticipantByRequestStudent($request, $student);
         // Transition to StudentApproved state
         $participant->transitionTo(new ParticipantStateCheckedOut($participant, time(), null, UserStatus::getUsername()));
         // If all the participants are in CheckedOut state, then this room change is complete, so transition it
         if ($request->allParticipantsInState('CheckedOut')) {
             $request->transitionTo(new RoomChangeStateComplete($request, time(), null, UserStatus::getUsername()));
         }
     }
     // Cleanup and redirect
     NQ::simple('hms', hms\NotificationView::SUCCESS, 'Checkout successful.');
     NQ::close();
     exit;
 }