public function execute(CommandContext $context)
 {
     PHPWS_Core::initModClass('hms', 'RoomDamageFactory.php');
     PHPWS_Core::initModClass('hms', 'StudentFactory.php');
     PHPWS_Core::initModClass('hms', 'HMS_Email.php');
     PHPWS_Core::initModClass('hms', 'CheckinFactory.php');
     PHPWS_Core::initModClass('hms', 'HMS_Bed.php');
     $term = Term::getSelectedTerm();
     // Get the total damages assessed for each student
     $damages = RoomDamageFactory::getAssessedDamagesStudentTotals($term);
     foreach ($damages as $dmg) {
         $student = StudentFactory::getStudentByBannerId($dmg['banner_id'], $term);
         // Get the student's last checkout
         // (NB: the damages may be for multiple check-outs,
         // but we'll just take the last one)
         $checkout = CheckinFactory::getLastCheckoutForStudent($student);
         $bed = new HMS_Bed($checkout->getBedId());
         $room = $bed->get_parent();
         $floor = $room->get_parent();
         $hall = $floor->get_parent();
         $coordinators = $hall->getCoordinators();
         if ($coordinators != null) {
             $coordinatorName = $coordinators[0]->getDisplayName();
             $coordinatorEmail = $coordinators[0]->getEmail();
         } else {
             $coordinatorName = '(No coordinator set for this hall.)';
             $coordinatorEmail = '(No coordinator set for this hall.)';
         }
         HMS_Email::sendDamageNotification($student, $term, $dmg['sum'], $coordinatorName, $coordinatorEmail);
     }
     // Show a success message and redirect back to the main admin menu
     NQ::simple('hms', hms\NotificationView::SUCCESS, 'Room damage noties sent.');
     $cmd = CommandFactory::getCommand('ShowAdminMaintenanceMenu');
     $cmd->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.');
     }
     $term = Term::getSelectedTerm();
     $bannerId = $context->get('bannerId');
     $hallId = $context->get('hallId');
     $errorCmd = CommandFactory::getCommand('ShowCheckinStart');
     if (!isset($bannerId) || is_null($bannerId) || $bannerId == '') {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Missing Banner ID.');
         $errorCmd->redirect();
     }
     if (!isset($hallId)) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Missing residence hall ID.');
         $errorCmd->redirect();
     }
     // Check the Banner ID
     if (preg_match("/[\\d]{9}/", $bannerId) == false) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Imporperly formatted Banner ID.');
         $errorCmd->redirect();
     }
     // Try to lookup the student in Banner
     try {
         $student = StudentFactory::getStudentByBannerId($bannerId, $term);
     } catch (StudentNotFoundException $e) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Could not locate a student with that Banner ID.');
         $errorCmd->redirect();
     }
     // Make sure the student is assigned in the current term
     $assignment = HMS_Assignment::getAssignmentByBannerId($bannerId, $term);
     if (!isset($assignment) || is_null($assignment)) {
         NQ::simple('hms', hms\NotificationView::ERROR, $student->getName() . ' is not assigned for ' . Term::toString($term) . '. Please contact the University Housing Assignments Office at 828-262-6111.');
         $errorCmd->redirect();
     }
     // Make sure the student's assignment matches the hall the user selected
     $bed = $assignment->get_parent();
     $room = $bed->get_parent();
     $floor = $room->get_parent();
     $hall = $floor->get_parent();
     if ($hallId != $hall->getId()) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Wrong hall! ' . $student->getName() . ' is assigned to ' . $assignment->where_am_i());
         $errorCmd->redirect();
     }
     // Load any existing check-in
     $checkin = CheckinFactory::getLastCheckinByBannerId($bannerId, $term);
     // If there is a checkin for the same bed, and the difference between the current time and the checkin time is
     // greater than 48 hours, then show an error.
     if (!is_null($checkin)) {
         $checkoutDate = $checkin->getCheckoutDate();
         if ($checkin->getBedId() == $bed->getId() && !isset($checkoutDate) && time() - $checkin->getCheckinDate() > Checkin::CHECKIN_TIMEOUT) {
             NQ::simple('hms', hms\NotificationView::ERROR, $student->getName() . ' has already checked in to ' . $assignment->where_am_i());
             $errorCmd->redirect();
         }
     }
     $view = new CheckinFormView($student, $assignment, $hall, $floor, $room, $checkin);
     $context->setContent($view->show());
 }
Beispiel #3
0
 public function get($request)
 {
     $response = new Response($request);
     $response->code = Response::OK;
     $response->addHeader('content-type', 'application/json');
     $response->body = json_encode(CheckinFactory::getLatest());
     return $response;
 }
 public function execute(CommandContext $context)
 {
     PHPWS_Core::initModClass('hms', 'StudentFactory.php');
     PHPWS_Core::initModClass('hms', 'HMS_Assignment.php');
     PHPWS_Core::initModClass('hms', 'CheckinFactory.php');
     PHPWS_Core::initModClass('hms', 'RoomDamageFactory.php');
     PHPWS_Core::initModClass('hms', 'HMS_Residence_Hall.php');
     PHPWS_Core::initModClass('hms', 'HMS_Bed.php');
     PHPWS_Core::initModClass('hms', 'BedFactory.php');
     $term = Term::getCurrentTerm();
     $bannerId = $context->get('bannerId');
     $hallId = $context->get('hallId');
     $errorCmd = CommandFactory::getCommand('ShowCheckoutStart');
     if (!isset($bannerId) || is_null($bannerId) || $bannerId == '') {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Missing student ID.');
         $errorCmd->redirect();
     }
     if (!isset($hallId)) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Missing residence hall ID.');
         $errorCmd->redirect();
     }
     // If search string is all numeric, make sure it looks like a valid Banner ID
     if (is_numeric($bannerId) && preg_match("/[\\d]{9}/", $bannerId) == false) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Imporperly formatted Banner ID.');
         $errorCmd->redirect();
     }
     // Try to lookup the student in Banner
     try {
         // If it's all numeric assume it's a student ID, otherwise assume it's a username
         if (is_numeric($bannerId) && strlen((string) $bannerId) == 9) {
             $student = StudentFactory::getStudentByBannerId($bannerId, $term);
         } else {
             $student = StudentFactory::getStudentByUsername($bannerId, $term);
         }
     } catch (StudentNotFoundException $e) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Could not locate a student with that Banner ID.');
         $errorCmd->redirect();
     }
     // Find the earliest checkin that matches hall the user selected
     $hall = new HMS_Residence_Hall($hallId);
     $checkin = CheckinFactory::getPendingCheckoutForStudentByHall($student, $hall);
     if (!isset($checkin)) {
         NQ::simple('hms', hms\NotificationView::ERROR, "Sorry, we couldn't find a matching check-in at {$hall->getHallName()} for this student to check-out of.");
         $errorCmd->redirect();
     }
     $bed = BedFactory::getBedByPersistentId($checkin->getBedPersistentId(), $term);
     $room = $bed->get_parent();
     // Get the damages for this student's room
     $damages = RoomDamageFactory::getDamagesByRoom($room);
     PHPWS_Core::initModClass('hms', 'CheckoutFormView.php');
     $view = new CheckoutFormView($student, $hall, $room, $bed, $damages, $checkin);
     $context->setContent($view->show());
 }
 public function execute(CommandContext $context)
 {
     PHPWS_Core::initModClass('hms', 'InfoCardPdfView.php');
     PHPWS_Core::initModClass('hms', 'InfoCard.php');
     PHPWS_Core::initModClass('hms', 'CheckinFactory.php');
     $checkinId = $context->get('checkinId');
     $checkin = CheckinFactory::getCheckinById($checkinId);
     $infoCard = new InfoCard($checkin);
     $view = new InfoCardPdfView();
     $view->addInfoCard($infoCard);
     $view->getPdf()->output();
     exit;
 }
 public function execute(CommandContext $context)
 {
     // Load the checkin object
     $checkinId = $context->Get('checkinId');
     $checkin = CheckinFactory::getCheckinById($checkinId);
     if (!isset($checkin) || is_null($checkin)) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'There was an error while looking up this checkin. Please contact ESS.');
         $errCmd = CommandFactory::getCommand('ShowAdminMainMenu');
         $errCmd->redirect();
     }
     PHPWS_Core::initModClass('hms', 'CheckoutDocumentView.php');
     $view = new CheckoutDocumentView($checkin);
     $context->setContent($view->show());
 }
 public function execute(CommandContext $context)
 {
     $term = Term::getSelectedTerm();
     $checkins = CheckinFactory::getCheckinsOrderedByRoom($term);
     if (!isset($checkins) || count($checkins) <= 0) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'No check-ins were found for the selected term.');
         $cmd = CommandFactory::getCommand('ShowAdminMaintenanceMenu');
         $cmd->redirect();
     }
     $view = new InfoCardPdfView();
     foreach ($checkins as $checkin) {
         $infoCard = new InfoCard($checkin);
         $view->addInfoCard($infoCard);
     }
     $view->getPdf()->output();
     exit;
 }
 public function show()
 {
     javascript('jquery');
     javascript('jquery_ui');
     javascriptMod('hms', 'StudentProfile');
     $tpl = array();
     $tpl['USERNAME'] = $this->student->getUsername();
     if (Current_User::allow('hms', 'login_as_student')) {
         $loginAsStudent = CommandFactory::getCommand('LoginAsStudent');
         $loginAsStudent->setUsername($this->student->getUsername());
         $tpl['LOGIN_AS_STUDENT_URI'] = $loginAsStudent->getURI();
     }
     $tpl['BANNER_ID'] = $this->student->getBannerId();
     $tpl['NAME'] = $this->student->getFullName();
     $tpl['TERM'] = Term::getPrintableSelectedTerm();
     $tpl['GENDER'] = $this->student->getPrintableGender();
     $tpl['DOB'] = $this->student->getDOB();
     if (strtotime($this->student->getDOB()) < strtotime("-25 years")) {
         NQ::simple('hms', hms\NotificationView::WARNING, 'Student is 25 years old or older!');
     }
     $tpl['CLASS'] = $this->student->getPrintableClass();
     $tpl['TYPE'] = $this->student->getPrintableType();
     $tpl['STUDENT_LEVEL'] = $this->student->getPrintableLevel();
     $tpl['ADMISSION_DECISION'] = $this->student->getAdmissionDecisionCode();
     $tpl['INTERNATIONAL'] = $this->student->isInternational() ? 'Yes' : 'No';
     $tpl['HONORS'] = $this->student->isHonors() ? 'Yes' : 'No';
     $tpl['TEACHING_FELLOW'] = $this->student->isTeachingFellow() ? 'Yes' : 'No';
     $tpl['WATAUGA'] = $this->student->isWataugaMember() ? 'Yes' : 'No';
     if ($this->student->pinDisabled()) {
         NQ::simple('hms', hms\NotificationView::WARNING, "This student's PIN is disabled.");
     }
     try {
         $tpl['APPLICATION_TERM'] = Term::toString($this->student->getApplicationTerm());
     } catch (InvalidTermException $e) {
         NQ::simple('hms', hms\NotificationView::WARNING, 'Application term is bad or missing.');
         $tpl['APPLICATION_TERM'] = 'WARNING: Application Term is bad or missing: "' . $this->student->getApplicationTerm() . '"';
     }
     /*****************
      * Phone Numbers *
      *****************/
     $phoneNumberList = $this->student->getPhoneNumberList();
     if (isset($phoneNumberList) && !is_null($phoneNumberList)) {
         foreach ($this->student->getPhoneNumberList() as $phone_number) {
             $tpl['phone_number'][] = array('NUMBER' => $phone_number);
         }
     }
     /*************
      * Addresses *
      *************/
     foreach ($this->student->getAddressList() as $address) {
         //If it's not a PS or PR address, skip it
         if ($address->atyp_code != 'PR' && $address->atyp_code != 'PS') {
             continue;
         }
         switch ($address->atyp_code) {
             case 'PS':
                 $addr_type = 'Student Address';
                 break;
             case 'PR':
                 $addr_type = 'Permanent Residence Address';
                 break;
             default:
                 $addr_type = 'Unknown-type address';
         }
         $addr_array = array();
         $addr_array['ADDR_TYPE'] = $addr_type;
         $addr_array['ADDRESS_L1'] = $address->line1;
         if (isset($address->line2)) {
             $addr_array['ADDRESS_L2'] = $address->line2;
         }
         if (isset($address->line3)) {
             $addr_array['ADDRESS_L3'] = $address->line3;
         }
         $addr_array['CITY'] = $address->city;
         $addr_array['STATE'] = $address->state;
         $addr_array['ZIP'] = $address->zip;
         $tpl['addresses'][] = $addr_array;
     }
     /**************
      * Assignment *
      **************/
     if (!is_null($this->assignment)) {
         $reassignCmd = CommandFactory::getCommand('ShowAssignStudent');
         $reassignCmd->setUsername($this->student->getUsername());
         $unassignCmd = CommandFactory::getCommand('ShowUnassignStudent');
         $unassignCmd->setUsername($this->student->getUsername());
         $tpl['ASSIGNMENT'] = $this->assignment->where_am_i(true) . ' ' . $reassignCmd->getLink('Reassign') . ' ' . $unassignCmd->getLink('Unassign');
     } else {
         $assignCmd = CommandFactory::getCommand('ShowAssignStudent');
         $assignCmd->setUsername($this->student->getUsername());
         $tpl['NOT_ASSIGNED'] = $assignCmd->getURI();
     }
     /*************
      * Roommates
      *************/
     if (isset($this->roommates) && !empty($this->roommates)) {
         // Remember, student can only have one confirmed or pending request
         // but multiple assigned roommates
         if (isset($this->roommates['PENDING'])) {
             $tpl['pending'][]['ROOMMATE'] = $this->roommates['PENDING'];
         } else {
             if (isset($this->roommates['CONFIRMED'])) {
                 $tpl['confirmed'][]['ROOMMATE'] = $this->roommates['CONFIRMED'];
             } else {
                 if (isset($this->roommates['NO_BED_AVAILABLE'])) {
                     $tpl['error_status'][]['ROOMMATE'] = $this->roommates['NO_BED_AVAILABLE'];
                 } else {
                     if (isset($this->roommates['MISMATCHED_ROOMS'])) {
                         $tpl['error_status'][]['ROOMMATE'] = $this->roommates['MISMATCHED_ROOMS'];
                     }
                 }
             }
         }
         if (isset($this->roommates['ASSIGNED'])) {
             foreach ($this->roommates['ASSIGNED'] as $roommate) {
                 $tpl['assigned'][]['ROOMMATE'] = $roommate;
             }
         }
     }
     /**************
      * RLC Status *
      *************/
     $rlc_names = RlcFactory::getRlcList(Term::getSelectedTerm());
     $rlc_assignment = HMS_RLC_Assignment::getAssignmentByUsername($this->student->getUsername(), Term::getSelectedTerm());
     $rlc_application = HMS_RLC_Application::getApplicationByUsername($this->student->getUsername(), Term::getSelectedTerm());
     if (!is_null($rlc_assignment)) {
         $tpl['RLC_STATUS'] = "This student is assigned to: " . $rlc_names[$rlc_assignment->rlc_id];
     } else {
         if (!is_null($rlc_application)) {
             $rlcViewCmd = CommandFactory::getCommand('ShowRlcApplicationReView');
             $rlcViewCmd->setAppId($rlc_application->getId());
             $tpl['RLC_STATUS'] = "This student has a " . $rlcViewCmd->getLink('pending RLC application') . ".";
         } else {
             $tpl['RLC_STATUS'] = "This student is not in a Learning Community and has no pending application.";
         }
     }
     /*************************
      * Re-application status *
      *************************/
     $reapplication = HousingApplicationFactory::getAppByStudent($this->student, Term::getSelectedTerm());
     # If this is a re-application, then check the special interest group status
     # TODO: incorporate all this into the LotteryApplication class
     if ($reapplication !== FALSE && $reapplication instanceof LotteryApplication) {
         if (isset($reapplication->special_interest) && !is_null($reapplication->special_interest) && !empty($reapplication->special_interest)) {
             # Student has been approved for a special group
             # TODO: format the name according to the specific group (sororities, etc)
             $tpl['SPECIAL_INTEREST'] = $reapplication->special_interest . '(confirmed)';
         } else {
             # Check if the student selected a group on the application, but hasn't been approved
             if (!is_null($reapplication->sorority_pref)) {
                 $tpl['SPECIAL_INTEREST'] = $reapplication->sorority_pref . ' (pending)';
                 //}else if($reapplication->tf_pref == 1){
                 //$tpl['SPECIAL_INTEREST'] = 'Teaching Fellow (pending)';
             } else {
                 if ($reapplication->wg_pref == 1) {
                     $tpl['SPECIAL_INTEREST'] = 'Watauga Global (pending)';
                 } else {
                     if ($reapplication->honors_pref == 1) {
                         $tpl['SPECIAL_INTEREST'] = 'Honors (pending)';
                     } else {
                         if ($reapplication->rlc_interest == 1) {
                             $tpl['SPECIAL_INTEREST'] = 'RLC (pending)';
                         } else {
                             # Student didn't select anything
                             $tpl['SPECIAL_INTEREST'] = 'No';
                         }
                     }
                 }
             }
         }
     } else {
         # Not a re-application, so can't have a special group
         $tpl['SPECIAL_INTEREST'] = 'No';
     }
     /******************
      * Housing Waiver *
      *************/
     $tpl['HOUSING_WAIVER'] = $this->student->housingApplicationWaived() ? 'Yes' : 'No';
     if ($this->student->housingApplicationWaived()) {
         NQ::simple('hms', hms\NotificationView::WARNING, "This student's housing application has been waived for this term.");
     }
     /****************
      * Applications *
      *************/
     $appList = new ProfileHousingAppList($this->applications);
     $tpl['APPLICATIONS'] = $appList->show();
     /*********
      * Assignment History *
      *********/
     $historyArray = StudentAssignmentHistory::getAssignments($this->student->getBannerId());
     $historyView = new StudentAssignmentHistoryView($historyArray);
     $tpl['HISTORY'] = $historyView->show();
     /**********
      * Checkins
      */
     $checkins = CheckinFactory::getCheckinsForStudent($this->student);
     $checkinHistory = new CheckinHistoryView($checkins);
     $tpl['CHECKINS'] = $checkinHistory->show();
     /*********
      * Notes *
      *********/
     $addNoteCmd = CommandFactory::getCommand('AddNote');
     $addNoteCmd->setUsername($this->student->getUsername());
     $form = new PHPWS_Form('add_note_dialog');
     $addNoteCmd->initForm($form);
     $form->addTextarea('note');
     $form->addSubmit('Add Note');
     /********
      * Logs *
      ********/
     $everything_but_notes = HMS_Activity_Log::get_activity_list();
     unset($everything_but_notes[array_search(ACTIVITY_ADD_NOTE, $everything_but_notes)]);
     if (Current_User::allow('hms', 'view_activity_log') && Current_User::allow('hms', 'view_student_log')) {
         PHPWS_Core::initModClass('hms', 'HMS_Activity_Log.php');
         $activityLogPager = new ActivityLogPager($this->student->getUsername(), null, null, true, null, null, $everything_but_notes, true, 10);
         $activityNotePager = new ActivityLogPager($this->student->getUsername(), null, null, true, null, null, array(0 => ACTIVITY_ADD_NOTE), true, 10);
         $tpl['LOG_PAGER'] = $activityLogPager->show();
         $tpl['NOTE_PAGER'] = $activityNotePager->show();
         $logsCmd = CommandFactory::getCommand('ShowActivityLog');
         $logsCmd->setActeeUsername($this->student->getUsername());
         $tpl['LOG_PAGER'] .= $logsCmd->getLink('View more');
         $notesCmd = CommandFactory::getCommand('ShowActivityLog');
         $notesCmd->setActeeUsername($this->student->getUsername());
         $notesCmd->setActivity(array(0 => ACTIVITY_ADD_NOTE));
         $tpl['NOTE_PAGER'] .= $notesCmd->getLink('View more');
     }
     $tpl = array_merge($tpl, $form->getTemplate());
     // TODO logs
     // TODO tabs
     Layout::addPageTitle("Student Profile");
     return PHPWS_Template::process($tpl, 'hms', 'admin/StudentProfile.tpl');
 }
 public function allParticipantsCheckedIn()
 {
     // Make sure each participant is checked-into his/her current assignment
     foreach ($this->getParticipants() as $participant) {
         // Load the 'from' Bed object
         $bed = new HMS_Bed($participant->getFromBed());
         // Load the student
         $student = StudentFactory::getStudentByBannerId($participant->getBannerId(), Term::getSelectedTerm());
         // Search for the check-in
         $checkin = CheckinFactory::getCheckinByBed($student, $bed);
         if ($checkin == null || $checkin != null && $checkin->getCheckoutDate() != null) {
             return false;
         }
     }
     return true;
 }
 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.');
     }
     $bannerId = $context->get('bannerId');
     $hallId = $context->get('hallId');
     // Check for key code
     $keyCode = $context->get('key_code');
     if (!isset($keyCode) || $keyCode == '') {
         NQ::simple('hms', hms\NotificationView::ERROR, 'Please enter a key code.');
         $errorCmd = CommandFactory::getCommand('ShowCheckinForm');
         $errorCmd->setBannerId($bannerId);
         $errorCmd->setHallId($hallId);
         $errorCmd->redirect();
     }
     $term = Term::getSelectedTerm();
     // Lookup the student
     $student = StudentFactory::getStudentByBannerId($bannerId, $term);
     // Get the student's current assignment
     $assignment = HMS_Assignment::getAssignmentByBannerId($bannerId, $term);
     $bed = $assignment->get_parent();
     // Get the currently logged in user
     $currUser = Current_User::getUsername();
     // Check for an existing Check-in
     $checkin = CheckinFactory::getCheckinByBed($student, $bed);
     // If there's not already a checkin for this bed, create a new one
     if (is_null($checkin)) {
         $checkin = new Checkin($student, $bed, $term, $currUser, $keyCode);
     } else {
         if ($checkin->getBedId() == $bed->getId() && time() - $checkin->getCheckinDate() < Checkin::CHECKIN_TIMEOUT) {
             // Check-in already exists, and it's within the timout window, so we'll overwrite the existing checkin
             $updatedCheckin = new Checkin($student, $bed, $term, $currUser, $keyCode);
             $updatedCheckin->substitueForExistingCheckin($checkin);
             // Use the old checkin to replace this one
             $checkin = $updatedCheckin;
         } else {
             // There's an existing checkin, but it's after the timeout, so we need to make a new checkin
             $checkin = new Checkin($student, $bed, $term, $currUser, $keyCode);
         }
     }
     $checkin->save();
     // Add this to the activity log
     HMS_Activity_Log::log_activity($student->getUsername(), ACTIVITY_CHECK_IN, UserStatus::getUsername(), $assignment->where_am_i());
     // Generate the RIC
     PHPWS_Core::initModClass('hms', 'InfoCard.php');
     PHPWS_Core::initModClass('hms', 'InfoCardPdfView.php');
     $infoCard = new InfoCard($checkin);
     $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::sendCheckinConfirmation($student, $infoCard, $infoCardView);
     NQ::simple('hms', hms\NotificationView::SUCCESS, 'Checkin successful.');
     // Redirect to success page with option to print check-in document.
     $cmd = CommandFactory::getCommand('ShowCheckinDocument');
     $cmd->setBannerId($student->getBannerId());
     $cmd->setCheckinId($checkin->getId());
     $cmd->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;
 }
 public function show()
 {
     $tpl = array();
     // Student info
     $tpl['NAME'] = $this->student->getProfileLink();
     $tpl['BANNER_ID'] = $this->student->getBannerId();
     // Participant ID
     // $tpl['PARTICIPANT_ID'] = $this->participant->getId();
     $tpl['CELL_PHONE'] = $this->participant->getCellPhone();
     // Hall Preferences
     $pref1 = $this->participant->getHallPref1();
     $pref2 = $this->participant->getHallPref2();
     if (!is_null($pref1)) {
         $hall1 = new HMS_Residence_Hall($pref1);
         $hallName = $hall1->getHallName();
         // Check if there's also a second hall preference
         if (!is_null($pref2)) {
             $hall2 = new HMS_Residence_Hall($pref2);
             $hallName .= ', ' . $hall2->getHallName();
         }
         $tpl['HALL_PREF'] = $hallName;
     }
     // From bed
     $fromBed = new HMS_Bed($this->participant->getFromBed());
     $tpl['FROM_ROOM'] = $fromBed->where_am_i();
     // To bed
     $toBedId = $this->participant->getToBed();
     if (isset($toBedId)) {
         // If there's already a bed set, show the selected bed
         $toBed = new HMS_Bed($toBedId);
         $tpl['TO_ROOM'] = $toBed->where_am_i();
     }
     /**
      * Check to see if the state is already approved or completed
      */
     $requestState = $this->request->getState();
     if ($requestState instanceof RoomChangeStatePending || $requestState instanceof RoomChangeStateHold) {
         /**
          * Check that the participant is checked into their current assignment
          */
         $checkin = CheckinFactory::getCheckinByBed($this->student, $fromBed);
         if ($checkin == null || $checkin != null && $checkin->getCheckoutDate() != null) {
             NQ::simple('hms', hms\NotificationView::ERROR, "{$this->student->getName()} is not checked-in at his/her current assignment. This must be fixed before this room change can be given final approval.");
         }
     }
     /**
      * **
      * Show approval buttons based on participant's current state
      */
     $particpantState = $this->participant->getState();
     $form = new PHPWS_Form('participant_form');
     if ($particpantState instanceof ParticipantStateNew) {
         // Particpant is in new state, waiting on this student'a approval
         // If the student is logged in, or the user is an admin, show the approve button
         if (UserStatus::getUsername() == $this->student->getUsername() || Current_User::allow('hms', 'admin_approve_room_change')) {
             $approveCmd = CommandFactory::getCommand('RoomChangeStudentApprove');
             $approveCmd->setParticipantId($this->participant->getId());
             $approveCmd->setRequestId($this->request->getId());
             $approveCmd->initForm($form);
             $form->mergeTemplate($tpl);
             $tpl = $form->getTemplate();
             $tpl['APPROVE_BTN'] = '';
             // dummy tag for approve button
         }
     } else {
         if ($particpantState instanceof ParticipantStateStudentApproved) {
             // Participant is in StudentApproved state
             // Get current list of RDs for this participant
             $rds = $this->participant->getCurrentRdList();
             // If current user is an RD for the "from bed" or an admin
             if (in_array(UserStatus::getUsername(), $rds) || Current_User::allow('hms', 'admin_approve_room_change')) {
                 if (!isset($toBedId) && count($this->participants) == 1) {
                     /*
                      * If there's only one particpant and the toBed is not already set,
                      * and the currnent user if the participants current RD, then show the bed selector
                      *
                      * Limit to 1 participant since room selection is for room "switch" requests only, not swaps.
                      * For swaps, the destination bed is already known and is not editable.
                      */
                     // Show the "select a bed" dialog, values are loaded via AJAX
                     $form->addDropBox('bed_select', array('-1' => 'Loading...'));
                     $form->addHidden('gender', $this->student->getGender());
                 }
                 $approveCmd = CommandFactory::getCommand('RoomChangeCurrRdApprove');
                 $approveCmd->setParticipantId($this->participant->getId());
                 $approveCmd->setRequestId($this->request->getId());
                 $approveCmd->initForm($form);
                 $form->mergeTemplate($tpl);
                 $tpl = $form->getTemplate();
                 $tpl['APPROVE_BTN'] = '';
                 // dummy tag for approve button
             }
         } else {
             if ($particpantState instanceof ParticipantStateCurrRdApproved) {
                 // Current RD has approved, Future RD needs to approve
                 // If current user if future RD or admin, show the approve button
                 // Get list of future RDs for "to bed"
                 $rds = $this->participant->getFutureRdList();
                 // Only future RDs and admins can approve
                 if (in_array(UserStatus::getUsername(), $rds) || Current_User::allow('hms', 'admin_approve_room_change')) {
                     $approveCmd = CommandFactory::getCommand('RoomChangeFutureRdApprove');
                     $approveCmd->setParticipantId($this->participant->getId());
                     $approveCmd->setRequestId($this->request->getId());
                     $approveCmd->initForm($form);
                     $form->mergeTemplate($tpl);
                     $tpl = $form->getTemplate();
                     $tpl['APPROVE_BTN'] = '';
                 }
             }
         }
     }
     // Show the edit link for to room if request type is a "switch", user has permissions, and status allows it
     // TODO
     /*** Participant History ***/
     $states = RoomChangeParticipantStateFactory::getStateHistory($this->participant);
     if (!is_null($states)) {
         $stateRows = array();
         foreach ($states as $historyState) {
             $stateRows[] = array('STATE_NAME' => $historyState->getFriendlyName(), 'EFFECTIVE_DATE' => date('M j, Y g:ia', $historyState->getEffectiveDate()), 'COMMITTED_BY' => $historyState->getCommittedBy());
         }
     }
     $tpl['history_rows'] = $stateRows;
     return PHPWS_Template::process($tpl, 'hms', 'admin/roomChangeParticipantView.tpl');
 }