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();
 }
Esempio n. 2
0
 public function __construct(Student $student, HMS_Bed $bed, $term, $checkinBy, $keyCode)
 {
     $this->setBannerId($student->getBannerId());
     $this->setBedPersistentId($bed->getPersistentId());
     $this->setBedId($bed->getId());
     $this->setTerm($term);
     $this->setRoomId($bed->get_parent()->getId());
     $this->setCheckinDate(time());
     $this->setCheckinby($checkinBy);
     $this->setKeyCode($keyCode);
 }
 public function show()
 {
     PHPWS_Core::initModClass('hms', 'HMS_Lottery.php');
     PHPWS_Core::initModClass('hms', 'HMS_Bed.php');
     PHPWS_Core::initModClass('hms', 'StudentFactory.php');
     PHPWS_Core::initModClass('hms', 'HMS_Util.php');
     # Get the roommate request record from the database
     $bed = new HMS_Bed($this->request['bed_id']);
     $room = $bed->get_parent();
     $tpl = array();
     $requestor = StudentFactory::getStudentByUsername($this->request['requestor'], $this->term);
     $tpl['REQUESTOR'] = $requestor->getName();
     $tpl['HALL_ROOM'] = $bed->where_am_i();
     # List all the students which will be assigned and their beds
     $beds = $room->get_beds();
     foreach ($beds as $bed) {
         $bed_row = array();
         # Check for an assignment
         $bed->loadAssignment();
         # Check for a reservation
         $reservation = $bed->get_lottery_reservation_info();
         $bed_row['BEDROOM_LETTER'] = $bed->bedroom_label;
         if ($bed->_curr_assignment != NULL) {
             # Bed is assigned
             $roommate = StudentFactory::getStudentByUsername($bed->_curr_assignment->asu_username, $this->term);
             $bed_row['TEXT'] = $roommate->getName();
         } else {
             if ($reservation != NULL) {
                 # Bed is reserved
                 $roommate = StudentFactory::getStudentByUsername($reservation['asu_username'], $this->term);
                 $bed_row['TEXT'] = $roommate->getName() . ' (reserved)';
             } else {
                 $bed_row['TEXT'] = 'Empty';
             }
         }
         $tpl['beds'][] = $bed_row;
     }
     $tpl['MEAL_PLAN'] = HMS_Util::formatMealOption($this->mealPlan);
     PHPWS_Core::initCoreClass('Captcha.php');
     $tpl['CAPTCHA'] = Captcha::get();
     $submitCmd = CommandFactory::getCommand('LotteryConfirmRoommateRequest');
     $submitCmd->setRequestId($this->request['id']);
     $submitCmd->setMealPlan($this->mealPlan);
     $form = new PHPWS_Form();
     $submitCmd->initForm($form);
     $form->addSubmit('confirm', 'Confirm Roommate');
     $form->mergeTemplate($tpl);
     $tpl = $form->getTemplate();
     Layout::addPageTitle("Lottery Confirm Roommate");
     return PHPWS_Template::process($tpl, 'hms', 'student/lottery_confirm_roommate_request.tpl');
 }
 public function execute(CommandContext $context)
 {
     PHPWS_Core::initModClass('hms', 'RoomDamageFactory.php');
     PHPWS_Core::initModClass('hms', 'HMS_Bed.php');
     $bedId = $context->get('bed_id');
     $bed = new HMS_Bed($bedId);
     $room = $bed->get_parent();
     // Get the damages for this student's room
     $damages = RoomDamageFactory::getDamagesByRoom($room);
     if ($damages == null) {
         $context->setContent(json_encode(array()));
         return;
     }
     $context->setContent(json_encode($damages));
 }
Esempio n. 5
0
 public function execute(CommandContext $context)
 {
     if (!UserStatus::isAdmin() || !Current_User::allow('hms', 'bed_view')) {
         PHPWS_Core::initModClass('hms', 'exception/PermissionException.php');
         throw new PermissionException('You do not have permission to view beds.');
     }
     // Check for a bed ID
     $bedId = $context->get('bed');
     if (!isset($bedId)) {
         throw new InvalidArgumentException('Missing bed ID.');
     }
     $bed = new HMS_Bed($bedId);
     if ($bed->term != Term::getSelectedTerm()) {
         $bedCmd = CommandFactory::getCommand('SelectBed');
         $bedCmd->setTitle('Edit a Bed');
         $bedCmd->setOnSelectCmd(CommandFactory::getCommand('EditBedView'));
         $bedCmd->redirect();
     }
     $room = $bed->get_parent();
     $floor = $room->get_parent();
     $hall = $floor->get_parent();
     $bedView = new BedView($hall, $floor, $room, $bed);
     $context->setContent($bedView->show());
 }
 public function show()
 {
     PHPWS_Core::initModClass('hms', 'HMS_Bed.php');
     PHPWS_Core::initModClass('hms', 'HMS_Lottery.php');
     PHPWS_Core::initModClass('hms', 'StudentFactory.php');
     # Get the roommate request record from the database
     $bed = new HMS_Bed($this->request['bed_id']);
     $room = $bed->get_parent();
     $tpl = array();
     $requestor = StudentFactory::getStudentByUsername($this->request['requestor'], $this->term);
     $tpl['REQUESTOR'] = $requestor->getName();
     $tpl['HALL_ROOM'] = $bed->where_am_i();
     # List all the students which will be assigned and their beds
     $beds = $room->get_beds();
     foreach ($beds as $bed) {
         $bed_row = array();
         # Check for an assignment
         $bed->loadAssignment();
         # Check for a reservation
         $reservation = $bed->get_lottery_reservation_info();
         $bed_row['BEDROOM_LETTER'] = $bed->bedroom_label;
         if ($bed->_curr_assignment != NULL) {
             # Bed is assigned
             $roommate = StudentFactory::getStudentByUsername($bed->_curr_assignment->asu_username, $this->term);
             $bed_row['TEXT'] = $roommate->getName();
         } else {
             if ($reservation != NULL) {
                 # Bed is reserved
                 $roommate = StudentFactory::getStudentByUsername($reservation['asu_username'], $this->term);
                 $bed_row['TEXT'] = $roommate->getName() . ' (reserved)';
             } else {
                 $bed_row['TEXT'] = 'Empty';
             }
         }
         $tpl['beds'][] = $bed_row;
     }
     // Check if the student has already completed a housing application
     if ($this->housingApplication != null) {
         // Housing application complete, go straight to confirming roommate
         $submitCmd = CommandFactory::getCommand('LotteryShowConfirmRoommateRequest');
         $submitCmd->setRequestId($this->request['id']);
     } else {
         // No housing application, goto self-select start page for contract and emg contact
         $submitCmd = CommandFactory::getCommand('RlcSelfAssignStart');
         $submitCmd->setTerm($this->term);
         $submitCmd->setRoommateRequestId($this->request['id']);
     }
     $denyCmd = CommandFactory::getCommand('LotteryShowDenyRoommateRequest');
     $denyCmd->setRequestId($this->request['id']);
     $form = new PHPWS_Form();
     $submitCmd->initForm($form);
     # Decide which meal plan drop box to show based on whether or not the chosen room
     # is in a hall which requires a meal plan
     $floor = $room->get_parent();
     $hall = $floor->get_parent();
     if ($hall->meal_plan_required == 0) {
         $form->addDropBox('meal_plan', array(BANNER_MEAL_NONE => _('None'), BANNER_MEAL_LOW => _('Low'), BANNER_MEAL_STD => _('Standard'), BANNER_MEAL_HIGH => _('High'), BANNER_MEAL_SUPER => _('Super')));
     } else {
         $form->addDropBox('meal_plan', array(BANNER_MEAL_LOW => _('Low'), BANNER_MEAL_STD => _('Standard'), BANNER_MEAL_HIGH => _('High'), BANNER_MEAL_SUPER => _('Super')));
         $form->setMatch('meal_plan', BANNER_MEAL_STD);
     }
     // Set meal plan drop down default to what the student selected on the housing re-application.
     if ($this->housingApplication != null) {
         $form->setMatch('meal_plan', $this->housingApplication->getMealPlan());
     }
     $form->addSubmit('accept', 'Accept Roommate');
     $form->addButton('reject', 'Deny Roommate');
     javascript('modules/hms/buttonAction', array('ID' => 'phpws_form_reject', 'URI' => $denyCmd->getURI()));
     $form->mergeTemplate($tpl);
     $tpl = $form->getTemplate();
     Layout::addPageTitle("Lottery Request Roommate");
     return PHPWS_Template::process($tpl, 'hms', 'student/lottery_roommate_request.tpl');
 }
 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)
 {
     if (!Current_User::allow('hms', 'assignment_notify')) {
         PHPWS_Core::initModClass('hms', 'exception/PermissionException.php');
         throw new PermissionException('You do not have permission to send assignment notifications.');
     }
     PHPWS_Core::initModClass('hms', 'Term.php');
     PHPWS_Core::initModClass('hms', 'HMS_Email.php');
     PHPWS_Core::initModClass('hms', 'HMS_Assignment.php');
     PHPWS_Core::initModClass('hms', 'HMS_Movein_Time.php');
     PHPWS_Core::initModClass('hms', 'StudentFactory.php');
     PHPWS_Core::initModClass('hms', 'HMS_RLC_Assignment.php');
     // Check if any move-in times are set for the selected term
     $moveinTimes = HMS_Movein_Time::get_movein_times_array(Term::getSelectedTerm());
     // If the array of move-in times ONLY has the zero-th element ['None'] then it's no good
     // Or, of course, if the array is null or emtpy it is no good
     if (count($moveinTimes) <= 1 || is_null($moveinTimes) || empty($moveinTimes)) {
         NQ::simple('hms', hms\NotificationView::ERROR, 'There are no move-in times set for ' . Term::getPrintableSelectedTerm());
         $context->goBack();
     }
     // Keep track of floors missing move-in times
     $missingMovein = array();
     $term = Term::getSelectedTerm();
     $db = new PHPWS_DB('hms_assignment');
     $db->addWhere('email_sent', 0);
     $db->addWhere('term', $term);
     $result = $db->getObjects("HMS_Assignment");
     if (PHPWS_Error::logIfError($result)) {
         throw new DatabaseException($result->toString());
     }
     foreach ($result as $assignment) {
         //get the students real name from their asu_username
         $student = StudentFactory::getStudentByUsername($assignment->getUsername(), $term);
         //get the location of their assignment
         PHPWS_Core::initModClass('hms', 'HMS_Bed.php');
         $bed = new HMS_Bed($assignment->getBedId());
         $room = $bed->get_parent();
         $location = $bed->where_am_i() . ' - Bedroom ' . $bed->bedroom_label;
         // Lookup the floor and hall to make sure the
         // assignment notifications flag is true for this hall
         $floor = $room->get_parent();
         $hall = $floor->get_parent();
         if ($hall->assignment_notifications == 0) {
             continue;
         }
         // Get the student type for determining move-in time
         $type = $student->getType();
         // Check for an accepted and confirmed RLC assignment
         $rlcAssignment = HMS_RLC_Assignment::getAssignmentByUsername($student->getUsername(), $term);
         // If there is an assignment, make sure the student "confirmed" the rlc invite
         if (!is_null($rlcAssignment)) {
             if ($rlcAssignment->getStateName() != 'confirmed' && $rlcAssignment->getStateName() != 'selfselect-assigned') {
                 $rlcAssignment = null;
             }
         }
         // Make sure this is re-initialized
         $moveinTimeId = null;
         $rlcSetMoveinTime = false;
         // Determine the move-in time
         if (!is_null($rlcAssignment)) {
             // If there is a 'confirmed' RLC assignment, use the RLC's move-in times
             $rlc = $rlcAssignment->getRlc();
             if ($type == TYPE_CONTINUING) {
                 $moveinTimeId = $rlc->getContinuingMoveinTime();
             } else {
                 if ($type == TYPE_TRANSFER) {
                     $moveinTimeId = $rlc->getTransferMoveinTime();
                 } else {
                     if ($type == TYPE_FRESHMEN) {
                         $moveinTimeId = $rlc->getFreshmenMoveinTime();
                     }
                 }
             }
         }
         // If there's a non-null move-in time ID at this point, then we know the RLC must have set it
         if (!is_null($moveinTimeId)) {
             $rlcSetMoveinTime = true;
         }
         // If the RLC didn't set a movein time, set it according to the floor
         // TODO: Find continuing students by checking the student's application term
         // against the term we're wending assignment notices for
         if (is_null($moveinTimeId)) {
             if ($type == TYPE_CONTINUING) {
                 $moveinTimeId = $assignment->get_rt_movein_time_id();
             } else {
                 if ($type == TYPE_TRANSFER) {
                     $moveinTimeId = $assignment->get_t_movein_time_id();
                 } else {
                     $moveinTimeId = $assignment->get_f_movein_time_id();
                 }
             }
         }
         // Check for missing move-in times
         if ($moveinTimeId == NULL) {
             //test($assignment, 1); // Will only happen if there's no move-in time set for the floor,student type
             // Lets only keep a set of the floors
             if (!in_array($floor, $missingMovein)) {
                 $missingMovein[] = $floor;
             }
             // Missing move-in time, so skip to the next assignment
             continue;
         }
         // TODO: Grab all the move-in times and index them in an array by ID so we don't have to query the DB every single time
         $movein_time_obj = new HMS_Movein_Time($moveinTimeId);
         $movein_time = $movein_time_obj->get_formatted_begin_end();
         // Add a bit of text if the move-in time was for an RLC
         if ($rlcSetMoveinTime) {
             $movein_time .= ' (for the ' . $rlc->get_community_name() . ' Residential Learning Community)';
         }
         //get the list of roommates
         $roommates = array();
         $beds = $room->get_beds();
         foreach ($beds as $bed) {
             $roommate = $bed->get_assignee();
             if ($roommate == false || is_null($roommate) || $roommate->getUsername() == $student->getUsername()) {
                 continue;
             }
             $roommates[] = $roommate->getFullName() . ' (' . $roommate->getUsername() . '@appstate.edu) - Bedroom ' . $bed->bedroom_label;
         }
         // Send the email
         HMS_Email::sendAssignmentNotice($student->getUsername(), $student->getName(), $term, $location, $roommates, $movein_time);
         // Mark the student as having received an email
         $db->reset();
         $db->addWhere('asu_username', $assignment->getUsername());
         $db->addWhere('term', $term);
         $db->addValue('email_sent', 1);
         $rslt = $db->update();
         if (PHPWS_Error::logIfError($rslt)) {
             throw new DatabaseException($result->toString());
         }
     }
     // Check for floors with missing move-in times.
     if (empty($missingMovein) || is_null($missingMovein)) {
         // Ther are none, so show a success message
         NQ::simple('hms', hms\NotificationView::SUCCESS, "Assignment notifications sent.");
     } else {
         // Show a warning for each floor that was missing a move-in time
         foreach ($missingMovein as $floor) {
             $hall = $floor->get_parent();
             $text = $floor->getLink($hall->getHallName() . " floor ") . " move-in times not set.";
             NQ::simple('hms', hms\NotificationView::WARNING, $text);
         }
     }
     $context->goBack();
 }
 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();
 }
Esempio n. 10
0
 /**
  * Returns an array of users names who have access to approve room changes for the
  * given bed id.
  *
  * @param int $bedId
  * @return multitype:array
  */
 private function getApproverList($bedId)
 {
     $bed = new HMS_Bed($bedId);
     $room = $bed->get_parent();
     $floor = $room->get_parent();
     $hall = $floor->get_parent();
     $hms_perm = new HMS_Permission();
     $hallMembers = $hms_perm->getMembership('room_change_approve', $hall);
     $floorMembers = $hms_perm->getMembership('room_change_approve', $floor);
     $hallMembers = array_merge($hallMembers, $floorMembers);
     $users = array();
     if (sizeof($hallMembers) <= 0) {
         return $users;
     }
     foreach ($hallMembers as $member) {
         $users[] = $member['username'];
     }
     return array_unique($users);
 }
Esempio n. 11
0
 /**
  * Does all the checks necessary to assign a student and makes the assignment
  *
  * The $room_id and $bed_id fields are optional, but one or the other must be specificed
  *
  * @param Student $student
  * @param Integer $term
  * @param Integer $room_id
  * @param Integer $bed_id
  * @param Integer $meal_plan
  * @param String $notes
  * @param boolean $lottery
  * @param string $reason
  * @throws InvalidArgumentException
  * @throws AssignmentException
  * @throws DatabaseException
  * @throws Exception
  */
 public static function assignStudent(Student $student, $term, $room_id = NULL, $bed_id = NULL, $meal_plan, $notes = "", $lottery = FALSE, $reason)
 {
     /**
      * Can't check permissions here because there are some student-facing commands that needs to make assignments (e.g.
      * the lottery/re-application code)
      *
      * if(!UserStatus::isAdmin() || !Current_User::allow('hms', 'assignment_maintenance')) {
      * PHPWS_Core::initModClass('hms', 'exception/PermissionException.php');
      * throw new PermissionException('You are not allowed to edit student assignments.');
      * }
      */
     PHPWS_Core::initModClass('hms', 'HMS_Residence_Hall.php');
     PHPWS_Core::initModClass('hms', 'HMS_Floor.php');
     PHPWS_Core::initModClass('hms', 'HMS_Room.php');
     PHPWS_Core::initModClass('hms', 'HMS_Bed.php');
     PHPWS_Core::initModClass('hms', 'HMS_Activity_Log.php');
     PHPWS_Core::initModClass('hms', 'BannerQueue.php');
     PHPWS_Core::initModClass('hms', 'AssignmentHistory.php');
     PHPWS_Core::initModClass('hms', 'exception/AssignmentException.php');
     $username = $student->getUsername();
     // Make sure a username was entered
     if (!isset($username) || $username == '') {
         throw new InvalidArgumentException('Bad username.');
     }
     $username = strtolower($username);
     if ($student->getType() == TYPE_WITHDRAWN) {
         throw new AssignmentException('Invalid student type. Student is withdrawn.');
     }
     if (HMS_Assignment::checkForAssignment($username, $term)) {
         throw new AssignmentException('The student is already assigned.');
     }
     if (isset($bed_id)) {
         // A bed_id was given, so create that bed object
         $vacant_bed = new HMS_Bed($bed_id);
         if (!$vacant_bed) {
             throw new AssignmentException('Null bed object.');
         }
         // Get the room that this bed is in
         $room = $vacant_bed->get_parent();
     } else {
         if (isset($room_id)) {
             // A room_id was given, so create that room object
             $room = new HMS_Room($room_id);
             // And find a vacant bed in that room
             $beds = $room->getBedsWithVacancies();
             $vacant_bed = $beds[0];
         } else {
             // Both the bed and room IDs were null, so return an error
             throw new AssignmentException('No room nor bed specified.');
         }
     }
     if (!$room) {
         throw new AssignmentException('Null room object.');
     }
     // Make sure the room has a vacancy
     if (!$room->has_vacancy()) {
         throw new AssignmentException('The room is full.');
     }
     // Make sure the room is not offline
     if ($room->offline) {
         throw new AssignmentException('The room is offline');
     }
     // Double check that the bed is in the same term as we're being requested to assign for
     if ($vacant_bed->getTerm() != $term) {
         throw new AssignmentException('The bed\'s term and the assignment term do not match.');
     }
     // Double check that the resulting bed is empty
     if ($vacant_bed->get_number_of_assignees() > 0) {
         throw new AssignmentException('The bed is not empty.');
     }
     // Issue a warning if the bed was reserved for room change
     //TODO Move this to the room change view
     /*
     if ($vacant_bed->room_change_reserved != 0) {
         NQ::simple('hms', hms\NotificationView::WARNING, 'Room was reserved for room change');
     }
     */
     // Check that the room's gender and the student's gender match
     $student_gender = $student->getGender();
     if (is_null($student_gender)) {
         throw new AssignmentException('Student gender is null.');
     }
     // Genders must match unless the room is COED
     if ($room->getGender() != $student_gender && $room->getGender() != COED) {
         throw new AssignmentException('Room gender does not match the student\'s gender.');
     }
     // We probably shouldn't check permissions inside this method, since sometimes this can be
     // called from student-facing interfaces.. But, since I want to be really careful with co-ed rooms,
     // I'm going to take the extra step of making sure no students are putting themselves in co-ed rooms.
     if ($room->getGender() == COED && !Current_User::allow('hms', 'coed_assignment')) {
         throw new AssignmentException('You do not have permission to make assignments for Co-ed rooms.');
     }
     // Create the floor object
     $floor = $room->get_parent();
     if (!$floor) {
         throw new AssignmentException('Null floor object.');
     }
     // Create the hall object
     $hall = $floor->get_parent();
     if (!$hall) {
         throw new AssignmentException('Null hall object.');
     }
     if ($meal_plan == BANNER_MEAL_NONE) {
         $meal_plan = NULL;
     }
     // Determine which meal plan to use
     // If this is a freshmen student and they've somehow selected none or low, give them standard
     if ($student->getType() == TYPE_FRESHMEN && ($meal_plan == BANNER_MEAL_NONE || $meal_plan == BANNER_MEAL_LOW)) {
         $meal_plan = BANNER_MEAL_STD;
         // If a student is living in a dorm which requires a meal plan and they've selected none, give them low
     } else {
         if ($hall->meal_plan_required == 1 && $meal_plan == BANNER_MEAL_NONE) {
             $meal_plan = BANNER_MEAL_LOW;
         }
     }
     /**
      * ***************************
      * Temporary Assignment HACK *
      * ***************************
      */
     // Check for an assignment in the temp assignment table
     $db = new PHPWS_DB('hms_temp_assignment');
     $db->addWhere('banner_id', $student->getBannerId());
     $result = $db->select();
     if (PHPWS_Error::logIfError($result)) {
         throw new DatabaseException($result->toString());
     }
     if (sizeof($result) > 0) {
         // Queue an unassign for this student
         $soap = SOAP::getInstance(UserStatus::getUsername(), UserStatus::isAdmin() ? SOAP::ADMIN_USER : SOAP::STUDENT_USER);
         try {
             $soap->removeRoomAssignment($student->getBannerId(), $term, 'TMPR', $result[0]['room_number'], 100);
             // Hard-code to 100% refund
         } catch (Exception $e) {
             throw $e;
         }
         $db = new PHPWS_DB('hms_temp_assignment');
         $db->addValue('banner_id', null);
         $db->addWhere('room_number', $result[0]['room_number']);
         $db->update();
         if (PHPWS_Error::logIfError($result)) {
             throw new DatabaseException($result->toString());
         }
         NQ::simple('hms', hms\NotificationView::WARNING, 'Temporary assignment was removed.');
     }
     // Send this off to the queue for assignment in banner
     $banner_success = BannerQueue::queueAssignment($student, $term, $hall, $vacant_bed, 'HOME', $meal_plan);
     if ($banner_success !== TRUE) {
         throw new AssignmentException('Error while adding the assignment to the Banner queue.');
     }
     // Make the assignment in HMS
     $assignment = new HMS_Assignment();
     $assignment->setBannerId($student->getBannerId());
     $assignment->asu_username = $username;
     $assignment->bed_id = $vacant_bed->id;
     $assignment->term = $term;
     $assignment->letter_printed = 0;
     $assignment->email_sent = 0;
     $assignment->meal_option = $meal_plan;
     $assignment->reason = $reason;
     $assignment->application_term = $student->getApplicationTerm();
     $assignment->class = $student->getComputedClass($term);
     // If this was a lottery assignment, flag it as such
     if ($lottery) {
         $assignment->lottery = 1;
         if (!isset($reason)) {
             // Automatically tag reason as lottery
             $assignment->reason = ASSIGN_LOTTERY;
         }
     } else {
         $assignment->lottery = 0;
     }
     $result = $assignment->save();
     if (!$result || PHPWS_Error::logIfError($result)) {
         throw new DatabaseException($result->toString());
     }
     // Log the assignment
     HMS_Activity_Log::log_activity($username, ACTIVITY_ASSIGNED, UserStatus::getUsername(), $term . ' ' . $hall->hall_name . ' ' . $room->room_number . ' ' . $notes);
     // Insert assignment into History table
     AssignmentHistory::makeAssignmentHistory($assignment);
     // Look for roommates and flag their assignments as needing a new letter
     $room_id = $assignment->get_room_id();
     $room = new HMS_Room($room_id);
     // Go to the room level to get all the roommates
     $assignees = $room->get_assignees();
     // get an array of student objects for those assigned to this room
     if (sizeof($assignees) > 1) {
         foreach ($assignees as $roommate) {
             // Skip this student
             if ($roommate->getUsername() == $username) {
                 continue;
             }
             $roommate_assign = HMS_Assignment::getAssignment($roommate->getUsername(), $term);
             $roommate_assign->letter_printed = 0;
             $roommate_assign->email_sent = 0;
             $roommate_assign->save();
         }
     }
     // Return Sucess
     return true;
 }