/**
  * the singleton pattern
  *
  * @return HumanResources_Controller_ExtraFreeTime
  */
 public static function getInstance()
 {
     if (self::$_instance === NULL) {
         self::$_instance = new self();
     }
     return self::$_instance;
 }
 /**
 <<<<<<< HEAD
 * @see: https://forge.tine20.org/mantisbt/view.php?id=10122
 */
 public function testAlternatingContracts()
 {
     $date = Tinebase_DateTime::now()->setDate(2014, 1, 1)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0);
     $employee = $this->_getEmployee('unittest');
     $employee->employment_begin = clone $date;
     $contract1 = $this->_getContract();
     $contract1->start_date = clone $date;
     // 1.1.2014
     $date->addMonth(7)->subDay(1);
     $contract1->end_date = clone $date;
     // 31.7.2014
     $contract1->workingtime_json = '{"days": [8,8,8,8,8,0,0]}';
     $contract1->vacation_days = 27;
     $date->addDay(1);
     // 1.8.2014
     $contract2 = $this->_getContract();
     $contract2->start_date = clone $date;
     $contract2->workingtime_json = '{"days": [8,8,8,8,8,0,0]}';
     $contract2->vacation_days = 30;
     $recordData = $employee->toArray();
     $recordData['contracts'] = array($contract1->toArray(), $contract2->toArray());
     $recordData = $this->_json->saveEmployee($recordData);
     $recordData['vacation'] = array(array());
     $res = $this->_json->searchAccounts(array(array('field' => 'year', 'operator' => 'equals', 'value' => '2014')), array());
     $account = $res['results'][0];
     $date->subDay(1);
     // 31.7.2014
     $extraFreeTime = HumanResources_Controller_ExtraFreeTime::getInstance()->create(new HumanResources_Model_ExtraFreeTime(array('account_id' => $account['id'], 'days' => 4, 'expires' => clone $date, 'type' => 'payed')));
     $res = $this->_json->getFeastAndFreeDays($recordData['id'], 2014);
     // at this point, vacation days are not created, so the extra freetime is expired
     $this->assertEquals(28, $res['results']['remainingVacation']);
     // create vacation days
     $day = Tinebase_DateTime::now()->setDate(2014, 1, 2)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0);
     $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'vacation', 'status' => 'ACCEPTED', 'firstday_date' => $day->toString());
     $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()));
     $newFreeTime['days_count'] = 2;
     $newFreeTime['lastday_date'] = $day->toString();
     $this->_json->saveFreeTime($newFreeTime);
     // create vacation days
     $day = Tinebase_DateTime::now()->setDate(2014, 6, 10)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0);
     $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'vacation', 'status' => 'ACCEPTED', 'firstday_date' => $day->toString());
     $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()));
     $newFreeTime['days_count'] = 4;
     $newFreeTime['lastday_date'] = $day->toString();
     $this->_json->saveFreeTime($newFreeTime);
     // create vacation days
     $day = Tinebase_DateTime::now()->setDate(2014, 7, 28)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0);
     $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'vacation', 'status' => 'ACCEPTED', 'firstday_date' => $day->toString());
     $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()));
     $newFreeTime['days_count'] = 5;
     $newFreeTime['lastday_date'] = $day->toString();
     $this->_json->saveFreeTime($newFreeTime);
     // create sickness days
     $day = Tinebase_DateTime::now()->setDate(2014, 1, 21)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0);
     $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'sickness', 'status' => "EXCUSED", 'firstday_date' => $day->toString());
     $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()));
     $day->addDay(2);
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $day->addDay(2);
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $newFreeTime['freedays'][] = array('duration' => '1', 'date' => $day->addDay(1)->toString());
     $newFreeTime['days_count'] = 14;
     $newFreeTime['lastday_date'] = $day->toString();
     $this->_json->saveFreeTime($newFreeTime);
     // create sickness days
     $day = Tinebase_DateTime::now()->setDate(2014, 1, 6)->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0);
     $newFreeTime = array('account_id' => $account['id'], 'employee_id' => $recordData['id'], 'type' => 'sickness', 'status' => "UNEXCUSED", 'firstday_date' => $day->toString());
     $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()));
     $this->_json->saveFreeTime($newFreeTime);
     $res = $this->_json->getFeastAndFreeDays($recordData['id'], 2014);
     // at this point the extra freetime has been taken and is not expired
     // 28 + 4 - 11 = 21
     $this->assertEquals(21, $res['results']['remainingVacation']);
     $account = $this->_json->getAccount($account['id']);
     $this->assertEquals(32, $account['possible_vacation_days']);
     $this->assertEquals(0, $account['expired_vacation_days']);
     $this->assertEquals(21, $account['remaining_vacation_days']);
     $this->assertEquals(11, $account['taken_vacation_days']);
     $this->assertEquals(14, $account['excused_sickness']);
     $this->assertEquals(1, $account['unexcused_sickness']);
 }
 /**
  * returns feast days and freedays of an employee for the freetime edit dialog
  * 
  * @param string $_employeeId
  * @param integer $_year
  * @param string $_freeTimeId
  * @param string $_accountId
  */
 public function getFeastAndFreeDays($_employeeId, $_year = NULL, $_freeTimeId = NULL, $_accountId = NULL)
 {
     $cController = HumanResources_Controller_Contract::getInstance();
     $eController = HumanResources_Controller_Employee::getInstance();
     $aController = HumanResources_Controller_Account::getInstance();
     $ftController = HumanResources_Controller_FreeTime::getInstance();
     $fdController = HumanResources_Controller_FreeDay::getInstance();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' $_employeeId ' . $_employeeId . ' $_year ' . $_year . ' $_freeTimeId ' . $_freeTimeId . ' $_accountId ' . $_accountId);
     }
     // validate employeeId
     $employee = $eController->get($_employeeId);
     $_freeTimeId = strlen($_freeTimeId) == 40 ? $_freeTimeId : NULL;
     // set period to search for
     $minDate = Tinebase_DateTime::now()->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0);
     if ($_year && !$_freeTimeId) {
         $minDate->setDate($_year, 1, 1);
     } elseif ($_freeTimeId) {
         // if a freetime id is given, take the year of the freetime
         $myFreeTime = $ftController->get($_freeTimeId);
         $minDate->setDate($myFreeTime->firstday_date->format('Y'), 1, 1);
     } else {
         $minDate->setDate($minDate->format('Y'), 1, 1);
     }
     if (!$_accountId) {
         // find account
         $filter = new HumanResources_Model_AccountFilter(array(array('field' => 'year', 'operator' => 'equals', 'value' => intval($_year))));
         $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'employee_id', 'operator' => 'equals', 'value' => $_employeeId)));
         $account = $aController->search($filter)->getFirstRecord();
     } else {
         try {
             $account = $aController->get($_accountId);
         } catch (Exception $e) {
             // throws a few lines later: HumanResources_Exception_NoAccount
         }
     }
     if (!$account) {
         throw new HumanResources_Exception_NoAccount();
     }
     $accountYear = $account->year;
     $minAccountDate = Tinebase_DateTime::now()->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0);
     $minAccountDate->setDate($accountYear, 1, 1);
     $maxAccountDate = clone $minAccountDate;
     $maxAccountDate->addYear(1)->subSecond(1);
     $maxDate = clone $minDate;
     $maxDate->addYear(1)->subSecond(1);
     // find contracts of the account year
     $contracts = $cController->getValidContracts($minAccountDate, $maxAccountDate, $_employeeId);
     $contracts->sort('start_date', 'ASC');
     if ($contracts->count() < 1) {
         throw new HumanResources_Exception_NoContract();
     }
     $remainingVacation = 0;
     $contracts->setTimezone(Tinebase_Core::getUserTimezone());
     // find out total amount of vacation days for the different contracts
     foreach ($contracts as $contract) {
         $remainingVacation += $cController->calculateVacationDays($contract, $minDate, $maxDate);
     }
     $remainingVacation = round($remainingVacation, 0);
     $allVacation = $remainingVacation;
     // find contracts of the year in which the vacation days will be taken
     $contracts = $cController->getValidContracts($minDate, $maxDate, $_employeeId);
     $contracts->sort('start_date', 'ASC');
     $excludeDates = array();
     if ($contracts->count() < 1) {
         throw new HumanResources_Exception_NoContract();
     }
     $first = TRUE;
     $feastDays = array();
     $contracts->setTimezone(Tinebase_Core::getUserTimezone());
     // find out disabled days for the different contracts
     foreach ($contracts as $contract) {
         $json = $contract->getWorkingTimeJson();
         $startDay = $contract->start_date == NULL ? $minDate : $contract->start_date < $minDate ? $minDate : $contract->start_date;
         $stopDay = $contract->end_date == NULL ? $maxDate : $contract->end_date > $maxDate ? $maxDate : $contract->end_date;
         if ($first) {
             $firstDay = clone $startDay;
             $first = FALSE;
         }
         // find out weekdays to disable
         if (is_object($json)) {
             foreach ($json->days as $index => $hours) {
                 $hours = intval($hours);
                 if ($hours === 0) {
                     $day = clone $startDay;
                     $day->setWeekDay($index + 1);
                     while ($day->compare($stopDay) == -1) {
                         $exdate = clone $day;
                         $exdate->setTimezone(Tinebase_Core::getUserTimezone());
                         $excludeDates[] = $exdate;
                         $day->addWeek(1);
                     }
                 }
             }
         }
         // search feast days
         $feastDays = array_merge($cController->getFeastDays($contract, $startDay, $stopDay), $feastDays);
     }
     // set time to 0
     foreach ($feastDays as &$feastDay) {
         $feastDay->setTimezone(Tinebase_Core::getUserTimezone())->setTime(0, 0, 0);
     }
     // search free times for the account and the interval
     // prepare free time filter, add employee_id
     $freeTimeFilter = new HumanResources_Model_FreeTimeFilter(array(), 'AND');
     $freeTimeFilter->addFilter(new Tinebase_Model_Filter_Id(array('field' => 'employee_id', 'operator' => 'equals', 'value' => $_employeeId)));
     // don't search for freetimes belonging to the freetime handled itself
     if ($_freeTimeId) {
         $freeTimeFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'id', 'operator' => 'not', 'value' => $_freeTimeId)));
     }
     // prepare vacation times filter
     $vacationTimesFilter = clone $freeTimeFilter;
     $vacationTimesFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'type', 'operator' => 'equals', 'value' => 'vacation')));
     // search all vacation times belonging to the account, regardless which interval we want
     $accountFreeTimesFilter = clone $vacationTimesFilter;
     $accountFreeTimesFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'account_id', 'operator' => 'equals', 'value' => $account->getId())));
     $accountVacationTimeIds = $ftController->search($accountFreeTimesFilter)->id;
     // search all vacation times for the interval
     $fddMin = clone $minDate;
     $fddMin->subDay(1);
     $fddMax = clone $maxDate;
     $fddMax->addDay(1);
     $vacationTimesFilter->addFilter(new Tinebase_Model_Filter_Date(array('field' => 'firstday_date', 'operator' => 'after', 'value' => $fddMin)));
     $vacationTimesFilter->addFilter(new Tinebase_Model_Filter_Date(array('field' => 'firstday_date', 'operator' => 'before', 'value' => $fddMax)));
     $vacationTimes = $ftController->search($vacationTimesFilter);
     $acceptedVacationTimes = $vacationTimes->filter('status', 'ACCEPTED');
     // search all sickness times for the interval
     $sicknessTimesFilter = clone $freeTimeFilter;
     $sicknessTimesFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'type', 'operator' => 'equals', 'value' => 'sickness')));
     $sicknessTimesFilter->addFilter(new Tinebase_Model_Filter_Date(array('field' => 'firstday_date', 'operator' => 'after', 'value' => $fddMin)));
     $sicknessTimesFilter->addFilter(new Tinebase_Model_Filter_Date(array('field' => 'firstday_date', 'operator' => 'before', 'value' => $fddMax)));
     $sicknessTimes = $ftController->search($sicknessTimesFilter);
     // search free days belonging the found free times
     // prepare free day filter
     $freeDayFilter = new HumanResources_Model_FreeDayFilter(array(), 'AND');
     $freeDayFilter->addFilter(new Tinebase_Model_Filter_Int(array('field' => 'duration', 'operator' => 'equals', 'value' => 1)));
     // find vacation days belonging to the account (date doesn't matter, may be from another year, just count the days)
     if (count($accountVacationTimeIds)) {
         $accountFreeDayFilter = clone $freeDayFilter;
         $accountFreeDayFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'freetime_id', 'operator' => 'in', 'value' => $accountVacationTimeIds)));
         $remainingVacation = $remainingVacation - $fdController->search($accountFreeDayFilter)->count();
     }
     // find all vacation days of the period
     $vacationDayFilter = clone $freeDayFilter;
     $vacationDayFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'freetime_id', 'operator' => 'in', 'value' => $vacationTimes->id)));
     $vacationDays = $fdController->search($vacationDayFilter);
     // find out accepted vacation days. Vacation days will be substracted from remainingVacation only if they are accepted,
     // but they will be shown in the freetime edit dialog
     // TODO: discuss this
     $acceptedVacationDayFilter = clone $freeDayFilter;
     $acceptedVacationDayFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'freetime_id', 'operator' => 'in', 'value' => $acceptedVacationTimes->id)));
     $acceptedVacationDays = $fdController->search($acceptedVacationDayFilter);
     // calculate extra vacation days
     if ($account) {
         $filter = new HumanResources_Model_ExtraFreeTimeFilter(array());
         $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'account_id', 'operator' => 'equals', 'value' => $account->getId())));
         $account->extra_free_times = HumanResources_Controller_ExtraFreeTime::getInstance()->search($filter);
         $extraFreeTimes = $aController->calculateExtraFreeTimes($account, $acceptedVacationDays);
         $allVacation = $allVacation + $extraFreeTimes['remaining'];
         $remainingVacation = $remainingVacation + $extraFreeTimes['remaining'];
     } else {
         $extraFreeTimes = NULL;
     }
     // find all sickness days of the period
     $sicknessDayFilter = clone $freeDayFilter;
     $sicknessDayFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'freetime_id', 'operator' => 'in', 'value' => $sicknessTimes->id)));
     $sicknessDays = $fdController->search($sicknessDayFilter);
     $ownFreeDays = NULL;
     if ($_freeTimeId) {
         $ownFreeDaysFilter = clone $freeDayFilter;
         $ownFreeDaysFilter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'freetime_id', 'operator' => 'in', 'value' => array($_freeTimeId))));
         $ownFreeDays = $fdController->search($ownFreeDaysFilter);
         $remainingVacation = $remainingVacation - $ownFreeDays->count();
         $ownFreeDays = $ownFreeDays->toArray();
     }
     // TODO: remove results property, just return results array itself
     return array('results' => array('remainingVacation' => floor($remainingVacation), 'extraFreeTimes' => $extraFreeTimes, 'vacationDays' => $vacationDays->toArray(), 'sicknessDays' => $sicknessDays->toArray(), 'excludeDates' => $excludeDates, 'ownFreeDays' => $ownFreeDays, 'allVacation' => $allVacation, 'feastDays' => $feastDays, 'contracts' => $contracts->toArray(), 'employee' => $employee->toArray(), 'firstDay' => $firstDay, 'lastDay' => $stopDay));
 }
 /**
  * book remaining vacation days for the next year
  * 
  * @param array $accountIds
  * @return booleam
  */
 public function bookRemainingVacation($accountIds)
 {
     $filter = new HumanResources_Model_AccountFilter(array(array('field' => 'id', 'operator' => 'in', 'value' => $accountIds)));
     $accounts = $this->search($filter);
     $freeTimeController = HumanResources_Controller_FreeTime::getInstance();
     $freeDayController = HumanResources_Controller_FreeDay::getInstance();
     $configInstance = HumanResources_Config::getInstance();
     $extraFreeTimeController = HumanResources_Controller_ExtraFreeTime::getInstance();
     $db = method_exists($this->_backend, 'getAdapter') ? $this->_backend->getAdapter() : Tinebase_Core::getDb();
     $thisYear = (int) Tinebase_DateTime::now()->format('Y');
     try {
         foreach ($accounts as $account) {
             $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
             if ($account->year >= $thisYear) {
                 throw new HumanResources_Exception_RemainingNotBookable();
             }
             $data = $this->resolveVirtualFields($account);
             // do nothing if there are no remaining vacation days
             if ($data['remaining_vacation_days'] <= 0) {
                 continue;
             }
             $year = intval($account->year) + 1;
             // get account of next year
             $filter = new HumanResources_Model_AccountFilter(array(array('field' => 'year', 'operator' => 'equals', 'value' => $year)));
             $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'employee_id', 'operator' => 'equals', 'value' => $account->employee_id)));
             $result = $this->search($filter);
             if ($result->count() == 0) {
                 $ca = $this->createMissingAccounts($year, $account->employee_id);
                 $newAccount = $ca->getFirstRecord();
             } elseif ($result->count() > 1) {
                 throw new Tinebase_Exception_Record_NotAllowed('There is more than one account for the year ' . $year . '!');
             } else {
                 $newAccount = $result->getFirstRecord();
             }
             // create new extraFreetime for the new year
             $extraFreeTime = new HumanResources_Model_ExtraFreeTime(array('days' => $data['remaining_vacation_days'], 'account_id' => $newAccount->getId(), 'type' => 'PAYED', 'description' => 'Booked from last year', 'expires' => $configInstance->getVacationExpirationDate()));
             $extraFreeTimeController->create($extraFreeTime);
             // create freetimes for old year
             $freetime = $freeTimeController->create(new HumanResources_Model_FreeTime(array('type' => 'vacation', 'description' => 'Booked as extra freetime for next year.', 'status' => 'ACCEPTED', 'firstday_date' => NULL, 'employee_id' => $account->employee_id, 'account_id' => $account->getId())));
             $i = 0;
             while ($i < $data['remaining_vacation_days']) {
                 $freeDay = $freeDayController->create(new HumanResources_Model_FreeDay(array('freetime_id' => $freetime->getId(), 'duration' => 1, 'date' => null)));
                 $i++;
             }
         }
         Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
         return true;
     } catch (Exception $e) {
         Tinebase_TransactionManager::getInstance()->rollBack();
         throw $e;
     }
 }