/** * Pares delete data in the UI form * * @param mixed $postArr * @return Leave[] */ public function parseDeleteData($postArr) { $objLeave = null; if (isset($postArr['deletHoliday'])) { for ($i = 0; $i < count($postArr['deletHoliday']); $i++) { if (!empty($postArr['deletHoliday'][$i])) { $tmpObj = new Holidays(); $tmpObj->setHolidayId($postArr['deletHoliday'][$i]); $objLeave[] = $tmpObj; } } } return $objLeave; }
protected function display() { // Admins only if (Tools::isConnectedUser()) { $session_user = UserCache::getInstance()->getUser($_SESSION['userid']); if ($session_user->isTeamMember(Config::getInstance()->getValue(Config::id_adminTeamId))) { $this->smartyHelper->assign('defaultColor', Holidays::$defaultColor); if (isset($_POST['hol_color'])) { $formatedDate = Tools::getSecurePOSTStringValue('date'); $timestamp = Tools::date2timestamp($formatedDate); $hol_desc = Tools::getSecurePOSTStringValue('hol_desc'); $hol_color = Tools::getSecurePOSTStringValue('hol_color'); if (!Holidays::save($timestamp, $hol_desc, $hol_color)) { $this->smartyHelper->assign('error', T_("Couldn't add the holiday")); } } elseif (isset($_POST['hol_id'])) { $hol_id = Tools::getSecurePOSTIntValue('hol_id'); if (!Holidays::delete($hol_id)) { $this->smartyHelper->assign('error', T_("Couldn't remove the holiday")); } } $this->smartyHelper->assign('holidays', Holidays::getHolidays()); } } }
public function addSeason() { if (Auth::check()) { $inputs = Input::all(); //calculating for week startdate and endate mon-sun $startdate = Carbon::createFromFormat('m/d/Y', $inputs['startdate']); $startdate = $startdate->startOfWeek(); $enddate = Carbon::createFromFormat('m/d/Y', $inputs['enddate']); $enddate = $enddate->endofWeek(); //calculating for total sessions for selected days and getting data to insert to seasons $sessionno = $enddate->diffInHours($startdate); $sessionno = (floor($sessionno / 24) + 1) / 7; $adddata['startdate'] = $startdate->toDateString(); $adddata['enddate'] = $enddate->toDateString(); $adddata['seasonType'] = $inputs['seasonType']; $adddata['sessionno'] = $sessionno; $adddata['franchisee_id'] = Session::get('franchiseId'); $franchise_data = Franchisee::where('id', '=', $adddata['franchisee_id'])->get(); //getting data for inserting new season no $season_no = Seasons::where('franchisee_id', '=', $adddata['franchisee_id'])->max('season_no'); $adddata['season_name'] = $franchise_data[0]['franchisee_name'] . ' ' . 'Season' . ' ' . ($season_no + 1) . '-' . $inputs['seasonType']; $adddata['season_no'] = $season_no + 1; //adding the new season to season table $season_id = Seasons::addSeason($adddata); $season_data = Seasons::where('id', '=', $season_id)->get(); $season_data = $season_data[0]; // adding data to location table $location_data = Location::addLocation($inputs['location'], $season_id); // $season_data['discount_second_child']=$inputs['secondchilddiscount']; // $season_data['discount_second_class']=$inputs['secondclassdiscount']; //adding data to discount table and calculating holidays session // $discount_data=Discounts::createDiscountForSeason($season_data); $holiday; if ($inputs['title'][0] != '') { for ($i = 0; $i < count($inputs['title']); $i++) { $startdate = Carbon::createFromFormat('m/d/Y', $inputs['holidaystartdate'][$i]); $enddate = Carbon::createFromFormat('m/d/Y', $inputs['holidayenddate'][$i]); $startdate = $startdate->startOfWeek(); $enddate = $enddate->endofWeek(); $holiday[$i]['startdate'] = $startdate->toDateString(); $holiday[$i]['enddate'] = $enddate->toDateString(); $holiday[$i]['title'] = $inputs['title'][$i]; $sessionno = $enddate->diffInHours($startdate); $sessionno = (floor($sessionno / 24) + 1) / 7; $holiday[$i]['holidaysession'] = $sessionno; } //adding data to holiday table $holiday_data = Holidays::addSeasonHolidays($holiday, $season_data); //Calculating and updating back to seasons table $total_session = $adddata['sessionno']; $totalholiday = 0; foreach ($holiday as $vacation) { $totalholiday += $vacation['holidaysession']; } $seasonupdate = Seasons::find($season_id); $seasonupdate->session_no = $season_data['session_no'] - $totalholiday; $seasonupdate->save(); if ($seasonupdate) { return Response::json(array('status' => 'success', 'startdate' => $season_data['start_date'], 'enddate' => $season_data['end_date'], 'sessionafterholidays' => $season_data['session_no'] - $totalholiday)); } } else { if ($season_data) { $seasonupdate = Seasons::find($season_id); return Response::json(array('status' => 'success', 'startdate' => $season_data['start_date'], 'enddate' => $season_data['end_date'], 'sessionafterholidays' => $season_data['session_no'])); } else { return Response::json(array('status' => 'failure')); } } } }
/** * Display a listing of the resource. * * @return Response */ public function index() { // if (Auth::check()) { $currentPage = "CLASSES"; $mainMenu = "COURSES_MAIN"; $inputs = Input::all(); if (isset($inputs['startTime'])) { //$startDate = //date('Y-m-d', strtotime($season_data['end_date'])); $season_data = Seasons::where('id', '=', $inputs['selectSeason'])->get(); $season_data = $season_data[0]; $startDate = new Carbon(); $endDate = new Carbon(); $startDate = $startDate->createFromFormat('Y-m-d', $season_data['start_date']); $endDate = $endDate->createFromFormat('Y-m-d', $season_data['end_date']); //taking season start date, end date and making calculation to start to specific day(MON,TUE...) switch ($inputs['day']) { case 0: break; case 1: $startDate->addDays(1); break; case 2: $startDate->addDays(2); break; case 3: $startDate->addDays(3); break; case 4: $startDate->addDays(4); break; case 5: $startDate->addDays(5); break; case 6: $startDate->addDays(6); break; } switch ($inputs['day']) { case 0: $endDate->subDays(6); break; case 1: $endDate->subDays(5); break; case 2: $endDate->subDays(4); break; case 3: $endDate->subDays(3); break; case 4: $endDate->subDays(2); break; case 5: $endDate->subDays(1); break; case 6: break; } $date = $startDate->day; $yr = $startDate->year; $month = $startDate->month; $inputs['startDate'] = $date . '-' . $month . '-' . $yr; $courseId = $inputs['franchiseeCourse']; $classId = $inputs['className']; $startTime = $inputs['startTime']; $endTime = $inputs['endTime']; $leadInstructor = $inputs['leadInstructor']; $alternateInstructor = $inputs['alternateInstructor']; $day = date('N', strtotime($inputs['startDate'])); if (date('m', strtotime($inputs['startDate'])) >= 1 && date('m', strtotime($inputs['startDate'])) <= 1) { $endDateYear = date('Y', strtotime($inputs['startDate'])); } else { $endDateYear = date('Y', strtotime($inputs['startDate'])); $endDateYear = $endDateYear + 1; } /* echo $startDate.' = '.$endDate ;//Year.'-03-31'; exit(); */ $months = getMonthsBetweenDates($startDate, $endDate); //Year.'-03-31'); /* echo "<pre>"; print_r($months); echo "</pre>"; exit(); */ $i = 0; foreach ($months as $month) { $yearAndMonth = explode('-', $month['month']); $daysFound[$i] = getDaysFromMonth($yearAndMonth['1'], $yearAndMonth['0'], $day); $i++; } $timeString = date('Y-m-d', strtotime($inputs['startDate'])) . $inputs['startTime']; $timestamp = strtotime($timeString); $startTime24Hours = date('H:i:s', $timestamp); $timeString = $endDateYear . '-3-5 ' . $inputs['endTime']; $timestamp = strtotime($timeString); $endTime24Hours = date('H:i:s', $timestamp); $batchSlug = Courses::getBatchID($courseId, $classId, $startDate, null, $inputs['selectSeason']); $inputBatch['batchName'] = $batchSlug; $inputBatch['classId'] = $classId; $inputBatch['courseId'] = $courseId; $inputBatch['startDate'] = $startDate->toDateString(); $inputBatch['endDate'] = $endDate->toDateString(); $inputBatch['season_id'] = $inputs['selectSeason']; $inputBatch['preferredTime'] = $startTime24Hours; $inputBatch['preferredEndTime'] = $endTime24Hours; $inputBatch['leadInstructor'] = $leadInstructor; $inputBatch['alternateInstructor'] = $alternateInstructor; $inputBatch['location_id'] = $inputs['seasonLocation']; //$inputBatch['classAmount']=$inputs['eachClassAmount']; $newBatch = Batches::addBatches($inputBatch); /* $days = 1; foreach($daysFound as $monthdays){ foreach($monthdays as $dayFound){ if($days <= 40){ $batchScheduleInput['batchId'] = $newBatch->id; $batchScheduleInput['seasonId'] = $inputs['selectSeason']; $batchScheduleInput['scheduleDate'] = $dayFound; $batchScheduleInput['startTime'] = $startTime24Hours; $batchScheduleInput['endTime'] = $endTime24Hours; $batchScheduleInput['scheduleType']= 'class'; BatchSchedule::addSchedule($batchScheduleInput); } $days++; } } */ //calculating dates and adding all the dates to batchschedule for new batch $batch_schedule = new BatchSchedule(); do { $batchScheduleInput['batchId'] = $newBatch->id; $batchScheduleInput['seasonId'] = $inputs['selectSeason']; $batchScheduleInput['scheduleDate'] = $startDate->toDateString(); $batchScheduleInput['startTime'] = $startTime24Hours; $batchScheduleInput['endTime'] = $endTime24Hours; $batchScheduleInput['scheduleType'] = 'class'; BatchSchedule::addSchedule($batchScheduleInput); $startDate->addDays(7); } while ($startDate->eq($endDate) == FALSE); //for last date $batchScheduleInput['batchId'] = $newBatch->id; $batchScheduleInput['seasonId'] = $inputs['selectSeason']; $batchScheduleInput['scheduleDate'] = $startDate->toDateString(); $batchScheduleInput['startTime'] = $startTime24Hours; $batchScheduleInput['endTime'] = $endTime24Hours; $batchScheduleInput['scheduleType'] = 'class'; BatchSchedule::addSchedule($batchScheduleInput); //check for holidays if exists make if (Holidays::where('season_id', '=', $inputs['selectSeason'])->count() > 0) { $holiday_data = Holidays::where('season_id', '=', $inputs['selectSeason'])->select('startdate', 'enddate')->get(); for ($i = 0; $i < count($holiday_data); $i++) { DB::table('batch_schedule')->where('batch_id', '=', $newBatch->id)->whereBetween('schedule_date', array($holiday_data[$i]['startdate'], $holiday_data[$i]['enddate']))->update(array('holiday' => 1)); } } Session::flash('msg', "Batch added successfully."); return Redirect::to('batches'); } $franchiseeId = Session::get('franchiseId'); $season_display_data = Seasons::where('franchisee_id', '=', Session::get('franchiseId'))->orderBy('id', 'DESC')->get(); if (isset($season_display_data[0])) { $s_id = $season_display_data[0]['id']; $batches = Batches::getAllBatchesDatabySeasonId($franchiseeId, $s_id); for ($i = 0; $i < count($batches); $i++) { $batches[$i]['preferred_time'] = date("H:i", strtotime($batches[$i]['preferred_time'])); $batches[$i]['preferred_end_time'] = date("H:i", strtotime($batches[$i]['preferred_end_time'])); $location_data = Location::where('id', '=', $batches[$i]['location_id'])->get(); $batches[$i]['location_name'] = $location_data[0]['location_name']; $batches[$i]['created'] = date("Y-m-d", strtotime($batches[$i]['created_at'])); $batches[$i]['day'] = date('l', strtotime($batches[$i]['start_date'])); if ($batches[$i]['lead_instructor'] != '') { $user_data = User::find($batches[$i]['lead_instructor']); $batches[$i]['instructor_name'] = $user_data['first_name'] . '' . $user_data['last_name']; } else { $batches[$i]['instructor_name'] = ''; } $batches[$i]['count'] = StudentClasses::where('batch_id', '=', $batches[$i]['id'])->count(); } } $courseList = Courses::getFranchiseCoursesList($franchiseeId); $franchiseeCourses = Courses::getFranchiseCoursesList(Session::get('franchiseId')); $Instructors = User::getInstructors(); $dataToView = array('batches', 'courseList', 'currentPage', 'mainMenu', 'franchiseeCourses', 'mondays', 'Instructors'); return View::make('pages.batches.batchesfinal', compact($dataToView)); } else { return Redirect::to("/"); } }
/** * Find days which are not 'sat' or 'sun' or FixedHoliday and that have no timeTrack entry. * @param int $userid * @return number[] */ public function checkMissingDays($userid) { $holidays = Holidays::getInstance(); $missingDays = array(); $user1 = UserCache::getInstance()->getUser($userid); // REM: if $this->team_id not set, then team_id = -1 if ($this->team_id >= 0) { if (!$user1->isTeamDeveloper($this->team_id, $this->startTimestamp, $this->endTimestamp) && !$user1->isTeamManager($this->team_id, $this->startTimestamp, $this->endTimestamp)) { // User was not yet present return $missingDays; } $arrivalTimestamp = $user1->getArrivalDate($this->team_id); $departureTimestamp = $user1->getDepartureDate($this->team_id); } else { $arrivalTimestamp = $user1->getArrivalDate(); $departureTimestamp = $user1->getDepartureDate(); } // reduce timestamp if needed $startT = $arrivalTimestamp > $this->startTimestamp ? $arrivalTimestamp : $this->startTimestamp; $endT = $this->endTimestamp; if (0 != $departureTimestamp && $departureTimestamp < $this->endTimestamp) { $endT = $departureTimestamp; } $weekTimestamps = array(); $timestamp = $startT; while ($timestamp <= $endT) { // monday to friday if (NULL == $holidays->isHoliday($timestamp)) { $weekTimestamps[] = $timestamp; } $timestamp = strtotime("+1 day", $timestamp); } if (count($weekTimestamps) > 0) { $query = "SELECT DISTINCT date " . "FROM `codev_timetracking_table` " . "WHERE userid = {$userid} AND date IN (" . implode(', ', $weekTimestamps) . ");"; $result = SqlWrapper::getInstance()->sql_query($query); if (!$result) { echo "<span style='color:red'>ERROR: Query FAILED</span>"; exit; } $daysWithTimeTracks = array(); while ($row = SqlWrapper::getInstance()->sql_fetch_object($result)) { $daysWithTimeTracks[] = $row->date; } $missingDays = array_diff($weekTimestamps, $daysWithTimeTracks); } return $missingDays; }
public function displayDefineHolidays($modifier = "specific", $edit = false) { $this->_authenticateViewHoliday(); $record = null; if ($edit) { $holidayObj = new Holidays(); $record = $holidayObj->fetchHoliday($this->getId()); } switch ($modifier) { case "specific": $path = "/templates/leave/specificHolidaysDefine.php"; break; case "weekend": $path = "/templates/leave/weekendHolidaysDefine.php"; $weekendsObj = new Weekends(); $record = $weekendsObj->fetchWeek(); break; } $template = new TemplateMerger($record, $path); $modifier = $edit; $template->display($modifier); }
//function say($word) : string { // return "Hello, " . $word //} class Holidays implements HolidayInterface { protected $date; public function __construct($year = null) { $y = $year ?? date('Y'); /* * http://www.php.net/manual/en/datetimeimmutable.construct.php * only for php 5.5 and more */ $this->date = new DateTimeImmutable("January 1, {$y}"); } public function getMemorial() : DateTimeImmutable { return $this->date->modify('last Monday of May'); } public function getThanksgiving() : DateTimeImmutable { return $this->date->modify('fourth Thursday of November'); } } $holidays = new Holidays(2016); $memorial = $holidays->getMemorial(); echo $memorial->format('l, F j, Y') . '<br>'; $thanksgiving = $holidays->getThanksgiving(); echo $thanksgiving->format('l, F j, Y') . '<br>'; $blackFriday = $thanksgiving->modify('+1 day'); echo $blackFriday->format('l, F j, Y') . '<br>';
/** * @param int $month * @param int $year * @param Issue $issue The issue * @param TimeTrack[] $trackList * @return mixed[] */ private function getMonth($month, $year, Issue $issue, array $trackList) { $totalDuration = 0; // if no work done this month, do not display month $found = 0; foreach ($trackList as $tt) { if ($month == date('m', $tt->getDate()) && $year == date('Y', $tt->getDate())) { $found += 1; $totalDuration += $tt->getDuration(); } } if (0 == $found) { return NULL; } $monthTimestamp = mktime(0, 0, 0, $month, 1, $year); $monthFormated = Tools::formatDate("%B %Y", $monthTimestamp); $nbDaysInMonth = date("t", $monthTimestamp); $months = array(); for ($i = 1; $i <= $nbDaysInMonth; $i++) { if ($i < 10) { $months[] = "0" . $i; } else { $months[] = $i; } } $jobs = new Jobs(); $userList = $issue->getInvolvedUsers(); $users = NULL; $timeTracks = $issue->getTimeTracks(); foreach ($userList as $uid => $username) { $userTotalDuration = 0; // build $durationByDate[] for this user $durationByDate = array(); $jobColorByDate = array(); foreach ($timeTracks as $tt) { if ($tt->getUserId() == $uid) { $date = $tt->getDate(); if (array_key_exists($date, $durationByDate)) { $durationByDate[$date] += $tt->getDuration(); } else { $durationByDate[$date] = $tt->getDuration(); } $jobColorByDate[$date] = $jobs->getJobColor($tt->getJobId()); } } $usersDetails = NULL; for ($i = 1; $i <= $nbDaysInMonth; $i++) { $todayTimestamp = mktime(0, 0, 0, $month, $i, $year); if (array_key_exists($todayTimestamp, $durationByDate)) { $userTotalDuration += $durationByDate[$todayTimestamp]; $usersDetails[] = array("jobColor" => $jobColorByDate[$todayTimestamp], "jobDuration" => $durationByDate[$todayTimestamp]); } else { // if weekend or holiday, display gray $holidays = Holidays::getInstance(); $h = $holidays->isHoliday($todayTimestamp); if (NULL != $h) { $usersDetails[] = array("jobColor" => Holidays::$defaultColor, "jobDescription" => $h->description); } else { $usersDetails[] = array(); } } } $users[] = array("username" => $username, "jobs" => $usersDetails, 'totalDuration' => 0 == $userTotalDuration ? '' : $userTotalDuration); } return array("monthFormated" => $monthFormated, "totalDuration" => $totalDuration, "months" => $months, "users" => $users); }
/** * Returns the Estimated Date of Arrival, depending on user's holidays and other timetracks * * @param int $beginTimestamp the start day * @param int $availTimeOnBeginTimestamp On the start day, part of the day may already have * been spent on other issues. this param defines how much * time is left for this issue. * if NULL, use user->getAvailableTime($beginTimestamp) * @param int $userid if NULL, use assignedTo user * @return mixed[] array(endTimestamp, $availTimeOnEndTimestamp) * $availTimeOnEndTimestamp can be re-injected in the next call to this function */ public function computeEstimatedDateOfArrival($beginTimestamp, $availTimeOnBeginTimestamp = NULL, $userid = NULL) { // find user in charge of this issue if (NULL != $userid) { $user = UserCache::getInstance()->getUser($userid); } else { if (NULL != $this->getHandlerId()) { $user = UserCache::getInstance()->getUser($this->getHandlerId()); } else { // issue not assigned to anybody $user = NULL; } } // we need to be absolutely sure that time is 00:00:00 $timestamp = mktime(0, 0, 0, date("m", $beginTimestamp), date("d", $beginTimestamp), date("Y", $beginTimestamp)); $tmpDuration = $this->getDuration(); if (self::$logger->isDebugEnabled()) { self::$logger->debug("computeEstimatedDateOfArrival: user="******" tmpDuration = {$tmpDuration} begindate=" . date('Y-m-d', $timestamp)); } // first day depends only on $availTimeOnBeginTimestamp if (NULL == $availTimeOnBeginTimestamp) { $availTime = $user->getAvailableTime($timestamp); } else { $availTime = $availTimeOnBeginTimestamp; } $tmpDuration -= $availTime; if (self::$logger->isDebugEnabled()) { self::$logger->debug("computeEstimatedDateOfArrival: 1st " . date('Y-m-d', $timestamp) . " tmpDuration (-{$availTime}) = {$tmpDuration}"); } // --- next days while ($tmpDuration > 0) { $timestamp = strtotime("+1 day", $timestamp); if (NULL != $user) { $availTime = $user->getAvailableTime($timestamp); $tmpDuration -= $availTime; if (self::$logger->isDebugEnabled()) { self::$logger->debug("computeEstimatedDateOfArrival: " . date('Y-m-d', $timestamp) . " tmpDuration = {$tmpDuration}"); } } else { // if not assigned, just check for global holidays if (NULL == Holidays::getInstance()->isHoliday($timestamp)) { $tmpDuration -= 1; // it's not a holiday, so complete day available. } } } $endTimestamp = $timestamp; // if $tmpDuration < 0 this means that this issue will be finished before // the end of the day. So the backlog time must be reported to be available // fot the next issue to be worked on. $availTimeOnEndTimestamp = abs($tmpDuration); if (self::$logger->isDebugEnabled()) { self::$logger->debug("computeEstimatedDateOfArrival: {$this->bugId}.computeEstimatedEndTimestamp(" . date('Y-m-d', $beginTimestamp) . ", {$availTimeOnBeginTimestamp}, {$userid}) = [" . date('Y-m-d', $endTimestamp) . ",{$availTimeOnEndTimestamp}]"); } return array($endTimestamp, $availTimeOnEndTimestamp); }
public function getCottagelist() { $response = array(); $cottageType = Input::get('cottageType'); $date = date('Y-m-d', strtotime(Input::get('date'))); $month = date('m', strtotime(Input::get('date'))); $reserves = CottageReservation::where('reservation_date', '=', $date)->get(); $id = array(); if (!empty($reserves)) { foreach ($reserves as $reserve) { $chosenCottages = explode(",", $reserve['cottagelist_id']); foreach ($chosenCottages as $cottage) { if (!$cottage == "") { if (!in_array($cottage, $id)) { $id[count($id)] = $cottage; } } } } $weekDay = date('w', strtotime($date)); $holidayCheck = Holidays::where('date', '=', $date)->first(); //return count($holidayCheck); if ($month == 03 || $month == 04 || $month == 05) { $details = "Summer Season"; $season = 3; } elseif (!empty($holidayCheck)) { $details = $holidayCheck['holidays']; $season = 2; } elseif ($weekDay == 0 || $weekDay == 6) { $details = "Weekend"; $season = 2; } else { $details = "Regular Season"; $season = 1; } /* $response[] = array( "cottage_list"=>'', "name" =>'', "details"=>$details, "season" =>$season, );*/ $cottagelists = CottageList::where('cottage_id', '=', $cottageType)->get(); foreach ($cottagelists as $list) { if (!in_array($list['cottagelist_id'], $id)) { $response[] = array("cottage_list" => $list['cottagelist_id'], "name" => $list['cottagename'], "details" => $details, "season" => $season); } } return $response; } else { $getCottage_lists = CottageList::where('cottage_id', '=', $cottageType)->get(); foreach ($getCottage_lists as $list) { $response[] = array("cottage_list" => $list['cottagelist_id'], "name" => $list['cottagename']); } return $response; } }
/** * The singleton pattern * @static * @return Holidays */ public static function getInstance() { if (!isset(self::$instance)) { $c = __CLASS__; self::$instance = new $c(); } return self::$instance; }
/** * Calculates the time off for a particular date * * Return values: * Eg: Returns 1 for full day off, 0.5 for half day off, 0 for no off time * * @param String $date * @return integer $timeOff */ protected function _timeOffLength($date) { $timeOff = 0; if (isset($this->weekends[date('N', strtotime($date)) - 1])) { $timeOff = $this->weekends[date('N', strtotime($date)) - 1]->getLength(); } $holidaysObj = new Holidays(); $length = $holidaysObj->isHoliday($date); if ($length > $timeOff) { $timeOff = $length; } return $timeOff / 8; }
public function getSmartyVariables($isAjaxCall = false) { $usersActivities = array(); $totalLeave = 0; $totalExternal = 0; $totalElapsed = 0; $totalOther = 0; $totalSidetask = 0; foreach ($this->execData as $userid => $userActivity) { $user = UserCache::getInstance()->getUser($userid); $usersActivities[$user->getName()] = $userActivity; if (array_key_exists('leave', $userActivity)) { $totalLeave += $userActivity['leave']; } if (array_key_exists('external', $userActivity)) { $totalExternal += $userActivity['external']; } if (array_key_exists('elapsed', $userActivity)) { $totalElapsed += $userActivity['elapsed']; } if (array_key_exists('other', $userActivity)) { $totalOther += $userActivity['other']; } if ($this->showSidetasks && array_key_exists('sidetask', $userActivity)) { $totalSidetask += $userActivity['sidetask']; } } $totalActivity = array(); $totalActivity['leave'] = $totalLeave; $totalActivity['external'] = $totalExternal; $totalActivity['elapsed'] = $totalElapsed; $totalActivity['other'] = $totalOther; if ($this->showSidetasks) { $totalActivity['sidetask'] += $totalSidetask; } ksort($usersActivities); // table data $tableData = array('usersActivities' => $usersActivities, 'totalActivity' => $totalActivity, 'workdays' => Holidays::getInstance()->getWorkdays($this->startTimestamp, $this->endTimestamp)); // ------------------------ // pieChart data $jqplotData = array(T_('Elapsed') => $totalActivity['elapsed'], T_('Other') => $totalActivity['other'], T_('External') => $totalActivity['external'], T_('Inactivity') => $totalActivity['leave']); $formatedColors = array("#92C5FC", "#C2DFFF", "#75FFDA", "#A8FFBD"); if ($this->showSidetasks) { $jqplotData[T_('Waste')] = $totalActivity['sidetask']; $formatedColors[] = "#FFF494"; } else { } $seriesColors = '["' . implode('","', $formatedColors) . '"]'; // ["#FFCD85","#C2DFFF"] $smartyVariables = array('loadPerUserIndicator_tableData' => $tableData, 'loadPerUserIndicator_jqplotData' => empty($jqplotData) ? NULL : Tools::array2json($jqplotData), 'loadPerUserIndicator_colors' => $formatedColors, 'loadPerUserIndicator_jqplotSeriesColors' => $seriesColors, 'loadPerUserIndicator_startDate' => Tools::formatDate("%Y-%m-%d", $this->startTimestamp), 'loadPerUserIndicator_endDate' => Tools::formatDate("%Y-%m-%d", $this->endTimestamp)); if (false == $isAjaxCall) { $smartyVariables['loadPerUserIndicator_ajaxFile'] = self::getSmartySubFilename(); $smartyVariables['loadPerUserIndicator_ajaxPhpURL'] = self::getAjaxPhpURL(); } return $smartyVariables; }
<?php require_once '../../Holidays.class.php'; $extras = array('Fri. before Memorial Day' => array(-5, 1, 5, 5), 'Fri. after Thanksgiving' => array(+5, 4, 11, 4)); //Get the year from the request array $year = $_REQUEST['year']; //Instantiate the object $holidays = new Holidays($year, $extras); //set the content type header('Content-type: application/json'); //output the json echo $holidays->getJson(); exit;
public function init() { require "/apache/htdocs/Mobi-Demo/lib/old/holiday_data.php"; self::$holidays = array(); foreach($holiday_data as $year => $holidays) { $year_array = array(); for($cnt = 0; $cnt < count($holidays); $cnt += 2) { $year_array[ $holidays[$cnt] ] = $holidays[$cnt+1]; } self::$holidays[$year] = $year_array; } self::$time = time(); }
namespace Ventus\Calendar; //============================================================================================ // Session, configuration file, localization constructor //============================================================================================ require '../includes/php/bootstrap.php'; $SESSION = new \Zend_Session_Namespace('internal', true); if (!isset($SESSION->lang)) { $SESSION->lang = DEFAULT_LANGUAGE; } \Locale::setDefault($SESSION->lang); $l10n->setLanguage($SESSION->lang); //============================================================================================ // Model //============================================================================================ $hol = new Holidays($dbo); //============================================================================================ // Load the page requested by the user //============================================================================================ if (!isset($_GET['page'])) { $render = true; $thisPage = "Global"; $services = $hol->listServices(); $hlist = $hol->listHolidays(); $l10n->addResource(__DIR__ . '/l10n/holidays.json'); $l10n->localizeArray($services, 'service_name'); $l10n->localizeArray($hlist, 'emp_service'); $l10n->localizeArray($hlist, 'holiday_name'); $l10n->localizeArray($hlist, 'service_name'); $viewFile = 'views/holidays.php'; } elseif ($_GET['page'] === "add") {
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model = Holidays::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $model; }
public function getSmartyVariables($isAjaxCall = false) { $totalLoad = 0; foreach ($this->execData as $duration) { $totalLoad += $duration; } // table data $tableData = array('projectLoad' => $this->execData, 'totalLoad' => $totalLoad, 'workdays' => Holidays::getInstance()->getWorkdays($this->startTimestamp, $this->endTimestamp)); // ------------------------ // pieChart data $jqplotData = Tools::array2plot($this->execData); $smartyVariables = array('loadPerProjectIndicator_tableData' => $tableData, 'loadPerProjectIndicator_jqplotData' => empty($jqplotData) ? NULL : $jqplotData, 'loadPerProjectIndicator_startDate' => Tools::formatDate("%Y-%m-%d", $this->startTimestamp), 'loadPerProjectIndicator_endDate' => Tools::formatDate("%Y-%m-%d", $this->endTimestamp)); if (false == $isAjaxCall) { $smartyVariables['loadPerProjectIndicator_ajaxFile'] = self::getSmartySubFilename(); $smartyVariables['loadPerProjectIndicator_ajaxPhpURL'] = self::getAjaxPhpURL(); } return $smartyVariables; }
protected function display() { if (Tools::isConnectedUser()) { // only teamMembers & observers can access this page if (0 == $this->teamid || $this->session_user->isTeamCustomer($this->teamid)) { $this->smartyHelper->assign('accessDenied', TRUE); } else { $team = TeamCache::getInstance()->getTeam($this->teamid); // if first call to this page if (!array_key_exists('nextForm', $_POST)) { $activeMembers = $team->getActiveMembers(); if ($this->session_user->isTeamManager($this->teamid)) { $this->smartyHelper->assign('users', SmartyTools::getSmartyArray($activeMembers, $this->session_userid)); } else { // developper & manager can add timeTracks if (array_key_exists($this->session_userid, $activeMembers)) { $_POST['userid'] = $this->session_userid; $_POST['nextForm'] = "addHolidaysForm"; //$_POST['days'] = 'dayid'; } } } $nextForm = Tools::getSecurePOSTStringValue('nextForm', ''); if ($nextForm == "addHolidaysForm") { $userid = Tools::getSecurePOSTIntValue('userid', $this->session_userid); $managed_user = UserCache::getInstance()->getUser($userid); // dates $startdate = Tools::getSecurePOSTStringValue('startdate', date("Y-m-d")); $enddate = Tools::getSecurePOSTStringValue('enddate', ''); $defaultBugid = Tools::getSecurePOSTIntValue('bugid', 0); $action = Tools::getSecurePOSTStringValue('action', ''); $duration = Tools::getSecurePOSTNumberValue('duree', 0); if ("addHolidays" == $action) { // TODO add tracks ! $job = Tools::getSecurePOSTStringValue('job'); $duration = Tools::getSecurePOSTNumberValue('duree'); $holydays = Holidays::getInstance(); $keyvalue = Tools::getSecurePOSTStringValue('checkedDays'); $checkedDaysList = Tools::doubleExplode(':', ',', $keyvalue); $startTimestamp = Tools::date2timestamp($startdate); $endTimestamp = Tools::date2timestamp($enddate); // save to DB $weekday = date('l', strtotime($startdate)); $timestamp = $startTimestamp; while ($timestamp <= $endTimestamp) { // check if not a fixed holiday if (!$holydays->isHoliday($timestamp)) { // check existing timetracks on $timestamp and adjust duration $availabletime = $managed_user->getAvailableTime($timestamp); // not imput more than possible if ($duration >= $availabletime) { $imput = $availabletime; } else { $imput = $duration; } // check if weekday checkbox is checked if (1 == $checkedDaysList[$weekday]) { if ($duration > 0) { if (self::$logger->isDebugEnabled()) { self::$logger->debug(date("Y-m-d", $timestamp) . " duration {$imput} job {$job}"); } TimeTrack::create($managed_user->getId(), $defaultBugid, $job, $timestamp, $imput, $this->session_userid); } } } $timestamp = strtotime("+1 day", $timestamp); $weekday = date('l', strtotime(date("Y-m-d", $timestamp))); } // We redirect to holidays report, so the user can verify his holidays header('Location:holidays_report.php'); } $this->smartyHelper->assign('startDate', $startdate); $this->smartyHelper->assign('endDate', $enddate); if ($this->session_userid != $managed_user->getId()) { $this->smartyHelper->assign('otherrealname', $managed_user->getRealname()); } // Get Team SideTasks Project List $projList = $team->getProjects(true, false); foreach ($projList as $pid => $pname) { // we want only SideTasks projects try { if (!$team->isSideTasksProject($pid)) { unset($projList[$pid]); } } catch (Exception $e) { self::$logger->error("project {$pid}: " . $e->getMessage()); } } $extproj_id = Config::getInstance()->getValue(Config::id_externalTasksProject); $extProj = ProjectCache::getInstance()->getProject($extproj_id); $projList[$extproj_id] = $extProj->getName(); $defaultProjectid = Tools::getSecurePOSTIntValue('projectid', 0); if ($defaultBugid != 0 && $action == 'setBugId') { // find ProjectId to update categories $issue = IssueCache::getInstance()->getIssue($defaultBugid); $defaultProjectid = $issue->getProjectId(); } $this->smartyHelper->assign('projects', SmartyTools::getSmartyArray($projList, $defaultProjectid)); $this->smartyHelper->assign('issues', $this->getIssues($defaultProjectid, $projList, $extproj_id, $defaultBugid)); $this->smartyHelper->assign('jobs', $this->getJobs($defaultProjectid, $projList)); $this->smartyHelper->assign('duration', SmartyTools::getSmartyArray(TimeTrackingTools::getDurationList($team->getId()), $duration)); $this->smartyHelper->assign('userid', $managed_user->getId()); } } } }
public function displayDefineHolidays($modifier = "specific", $edit = false) { $this->_authenticateViewHoliday(); $record = null; if ($edit) { $holidayObj = new Holidays(); $record = $holidayObj->fetchHoliday($this->getId()); } switch ($modifier) { case "specific": $holiday = new Holidays(); $record['holidayList'] = $holiday->listHolidays(); $path = "/templates/leave/specificHolidaysDefine.php"; break; case "weekend": $path = "/templates/leave/weekendHolidaysDefine.php"; $weekendsObj = new Weekends(); $record = $weekendsObj->fetchWeek(); break; } $record['rights'] = $_SESSION['localRights']; $record['changeWeekends'] = Leave::isLeaveTableEmpty(); $template = new TemplateMerger($record, $path); $modifier = $edit; $template->display($modifier); }
/** * Get days for each users * @param int $month The month * @param int $year The year * @param int $teamid The team * @param User[] $users The users (User[id]) * @param int $nbDaysInMonth The number of days in a month * @param bool $isExternalTasks True if external tasks wanted, else false * @return mixed[string] */ function getDaysUsers($month, $year, $teamid, array $users, $nbDaysInMonth, $filters) { $holidays = Holidays::getInstance(); $isExternalTasks = $filters['isExternalTasks']; $isSidetasksInactivity = $filters['isSidetasksInactivity']; $startT = mktime(0, 0, 0, $month, 1, $year); $endT = mktime(23, 59, 59, $month, $nbDaysInMonth, $year); $smartyUsers = array(); foreach ($users as $user) { // if user was working on the project within the timestamp if ($user->isTeamDeveloper($teamid, $startT, $endT) || $user->isTeamManager($teamid, $startT, $endT)) { $arrivalDate = $user->getArrivalDate($teamid); $departureDate = $user->getDepartureDate($teamid); $timeTracks = $user->getTimeTracks($startT, $endT); $issueIds = array(); foreach ($timeTracks as $timeTrack) { $issueIds[] = $timeTrack->getIssueId(); } $daysOf = $user->getDaysOfInPeriod($timeTracks, $issueIds, $teamid); $astreintes = $user->getOnDutyTaskInMonth($teamid, $timeTracks, $issueIds); $externalTasks = $user->getExternalTasksInPeriod($timeTracks, $issueIds); $days = array(); for ($i = 1; $i <= $nbDaysInMonth; $i++) { $timestamp = mktime(0, 0, 0, $month, $i, $year); if ($timestamp < $arrivalDate || 0 != $departureDate && $timestamp > $departureDate) { $days[$i] = array("color" => 'D8D8D8', "title" => T_('User not in team')); } elseif (isset($externalTasks[$timestamp]) && NULL != $externalTasks[$timestamp]) { // always show inactivity tasks, // other externalTasks must only be displayed if $isExternalTasks if ('Inactivity' == $externalTasks[$timestamp]['type'] || $isExternalTasks) { $days[$i] = array("color" => $externalTasks[$timestamp]['color'], "align" => true, "title" => htmlentities($externalTasks[$timestamp]['title']), "value" => $externalTasks[$timestamp]['duration']); } } elseif (isset($astreintes[$timestamp]) && NULL != $astreintes[$timestamp]) { $days[$i] = array("color" => $astreintes[$timestamp]['color'], "align" => true, "value" => $astreintes[$timestamp]['duration'], "title" => htmlentities(T_($astreintes[$timestamp]['type']))); } elseif (isset($daysOf[$timestamp]) && NULL != $daysOf[$timestamp]) { if ($isSidetasksInactivity) { $days[$i] = array("color" => $daysOf[$timestamp]['color'], "align" => true, "title" => htmlentities($daysOf[$timestamp]['title']), "value" => $daysOf[$timestamp]['duration']); } } if (!isset($days[$i])) { // If weekend or holiday, display gray $timestamp = mktime(0, 0, 0, $month, $i, $year); $h = $holidays->isHoliday($timestamp); if (NULL != $h) { $days[$i] = array("color" => $h->color, "title" => htmlentities($h->description)); } else { $days[$i] = array(); } } } $smartyUsers[$user->getId()] = array('realname' => $user->getRealname(), 'username' => $user->getName(), 'days' => $days); } } return $smartyUsers; }
<?php namespace Ventus\Calendar; require '../includes/php/bootstrap.php'; //============================================================================================ // Model //============================================================================================ $hol = new Holidays($dbo); $department_ids = array('global' => array('department_id' => null, 'cfname' => 'SASS', 'clname' => '', 'description' => 'SASS Event'), 'access' => array('department_id' => SERVICE_ID_ACCESS, 'cfname' => 'Access', 'clname' => 'Service', 'description' => ''), 'counselling' => array('department_id' => SERVICE_ID_COUNSELLING, 'cfname' => 'Counselling', 'clname' => 'Service', 'description' => '')); $event_array = array(); if (isset($department_ids[$_GET['page']])) { $hols = array_filter($hol->listHolidayEvents($_GET['start'], $_GET['end']), function ($h) use($department_ids) { return $h['department_id'] === $department_ids[$_GET['page']]['department_id']; }); //Create the event array the itself holds event objects foreach ($hols as $h) { $event_array[] = array('id' => $h['holiday_id'], 'title' => "{$h['holiday_name_fr']} - {$h['holiday_name']}", 'start' => $h['holiday_start'], 'end' => $h['holiday_end'], 'className' => 'sassglobal', 'description' => $department_ids[$_GET['page']]['description'], 'sname' => ' ', 'estatus' => '', 'allDay' => false, 'cfname' => $department_ids[$_GET['page']]['cfname'], 'clname' => $department_ids[$_GET['page']]['clname'], 'color' => 'black', 'textColor' => 'white', 'borderColor' => 'black'); } } header('Content-Type: application/json; charset=utf-8'); echo json_encode($event_array); exit;
public function testGetHolidayForDate() { // exact day for recurring holiday $holiday = Holidays::getHolidayForDate(date('Y') . '-07-04'); $this->assertNotNull($holiday); $this->assertEquals('Independence', $holiday->getDescription()); $this->assertEquals(10, $holiday->getHolidayId()); $this->assertEquals(date('Y') . '-07-04', $holiday->getDate()); $this->assertEquals(Holidays::HOLIDAYS_RECURRING, $holiday->getRecurring()); $this->assertEquals(8, $holiday->getLength()); // next year for recurring holiday $holiday = Holidays::getHolidayForDate(date('Y') + 1 . '-07-04', true); $this->assertNotNull($holiday); $this->assertEquals('Independence', $holiday->getDescription()); $this->assertEquals(10, $holiday->getHolidayId()); $this->assertEquals(date('Y') . '-07-04', $holiday->getDate()); $this->assertEquals(Holidays::HOLIDAYS_RECURRING, $holiday->getRecurring()); $this->assertEquals(8, $holiday->getLength()); // previous year for recurring holiday $holiday = Holidays::getHolidayForDate(date('Y') - 1 . '-07-04', true); $this->assertNull($holiday); // exact day for non-recurring holiday $holiday = Holidays::getHolidayForDate(date('Y') . '-01-04'); $this->assertNotNull($holiday); $this->assertEquals('Poya', $holiday->getDescription()); $this->assertEquals(11, $holiday->getHolidayId()); $this->assertEquals(date('Y') . '-01-04', $holiday->getDate()); $this->assertEquals(Holidays::HOLIDAYS_NOT_RECURRING, $holiday->getRecurring()); $this->assertEquals(4, $holiday->getLength()); // next year for non-recurring holiday $holiday = Holidays::getHolidayForDate(date('Y') + 1 . '-01-04', true); $this->assertNull($holiday); // random non-holiday $holiday = Holidays::getHolidayForDate(date('Y') + 1 . '-03-04'); $this->assertNull($holiday); $holiday = Holidays::getHolidayForDate(date('Y') + 1 . '-03-04', true); $this->assertNull($holiday); }
/** * Builds an array of Holidays. * * @access private * @param resource $result * @return Holidays $objArr */ private static function _buildObjArr($result) { $objArr = null; if ($result) { while ($row = mysql_fetch_assoc($result)) { $tmpObjHolidays = new Holidays(); if (isset($row[self::HOLIDAYS_TABLE_HOLIDAY_ID])) { $tmpObjHolidays->setHolidayId($row[self::HOLIDAYS_TABLE_HOLIDAY_ID]); } if (isset($row[self::HOLIDAYS_TABLE_DESCRIPTION])) { $tmpObjHolidays->setDescription($row[self::HOLIDAYS_TABLE_DESCRIPTION]); } if (isset($row[self::HOLIDAYS_TABLE_DATE])) { $tmpObjHolidays->setDate($row[self::HOLIDAYS_TABLE_DATE]); } else { if (isset($row['a'])) { $tmpObjHolidays->setDate($row['a']); } } if (isset($row[self::HOLIDAYS_TABLE_RECURRING])) { $tmpObjHolidays->setRecurring($row[self::HOLIDAYS_TABLE_RECURRING]); } if (isset($row[self::HOLIDAYS_TABLE_LENGTH])) { $tmpObjHolidays->setLength($row[self::HOLIDAYS_TABLE_LENGTH]); } $objArr[] = $tmpObjHolidays; } } return $objArr; }
function ProjectWalker($devID, $fileSave, $projID) { global $sqlSess; global $repStartDate; global $numWeeks; global $startOfWeek; global $projTableAttr; global $projTable; global $showAsWeeks; global $showHoliday; global $byDeveloper; $h = new Holidays($repStartDate); $projRow = 3; $lastProj = 0; // The current week $repWeek = date("y", $startOfWeek) . date("W", $startOfWeek); $rowText = ""; if ($sqlSess) { // Get all the relavant tasks // Note tcmax is the most recent task completion estimate - needed to ensure that jobs which are completed earlier // than estimate are not included in later reports $sql = "select t.taskid, tc.completionid, t.taskname, t.developerid, u.name, u.username, t.createddate t_createddate,\r\n tc.statusid, tc.completiondate,tc.createddate tc_createddate, p.projectname, p.projectid, tc.commencedate\r\n from taskcompletion tc, task t, users u, project p, taskcompletion tcmax\r\n where tc.taskid=t.taskid and t.developerid = u.userid and p.projectid = t.projectid\r\n and tc.taskid = tcmax.taskid and tcmax.completionid = (select max(completionid) from taskcompletion where taskid=tc.taskid)\r\n and tc.completiondate >= '" . date("Y-m-d", $repStartDate) . "'\r\n and tcmax.completiondate >= '" . date("Y-m-d", $repStartDate) . "'"; if ($devID != "") { $sql = $sql . " and username = '******'"; } if ($projID != "") { $sql = $sql . " and p.projectid = {$projID}"; } if ($byDeveloper) { $sql = $sql . " order by u.name, p.projectid, t.createddate, tc.completionid"; } else { $sql = $sql . " order by p.projectid, t.createddate, tc.completionid"; } debug($sql); $taskRes = mysql_query($sql, $sqlSess); if ($taskRes) { $nextRow = mysql_fetch_array($taskRes); // Loop until all tasks are processed while ($nextRow) { // Create a header row for each project if ($nextRow['projectid'] != $lastProj) { // Project header spans the whole table $colSpan = $numWeeks * 2 + 2; $projTableAttr[] = array("class='pr' colspan='{$colSpan}'"); if ($fileSave) { $projTable[] = array($nextRow['projectname']); } else { // The project name + the edit and timesheet hyperlinks $projTable[] = array(MakeURL("matrix", "proj=" . $nextRow['projectid'], $nextRow['projectname']) . " (" . MakeURL("proj", "proj=" . $nextRow['projectid'], "Edit project") . ") " . "(" . MakeURL("projecttime", "proj=" . $nextRow['projectid'], "Timesheet") . ")"); } $lastProj = $nextRow['projectid']; $projRow++; } // Alternate color stripes if ($projRow % 2 == 0) { $pclass = "proj-e"; $lclass = "late-e"; $bclass = "block-e"; $sclass = "start-e"; $cclass = "comp-e"; } else { $pclass = "proj-o"; $lclass = "late-o"; $bclass = "block-o"; $sclass = "start-o"; $cclass = "comp-o"; } // Initialise matrix row for current project. classes for first two cells $tdAttr = "class='ind',class='de'"; if ($fileSave) { $rowText = $nextRow['taskname'] . "," . $nextRow['name']; } else { $rowText = "" . MakeURL("task", "task=" . $nextRow['taskid'], $nextRow['taskname']) . "," . MakeURL("matrix", "user="******"y", $repStartDate) . date("W", $repStartDate); // loop for each week in the report for ($i = 1; $i <= $numWeeks * 2; $i++) { $chClass = ""; // Don't check the next row if at the end of the result set if ($nextRow) { $checkNextRow = True; } else { $checkNextRow = False; } // Check the next completion estimate to see if it is for the current project // and was created during the current week in the report, If so loop until find // the most up to date estimate in the current week. // and check again. If not carry on using the currnet estimate. while ($checkNextRow) { if ($nextRow['taskid'] == $curRow['taskid'] and $cellWeek >= date("y", strtotime($nextRow['tc_createddate'])) . date("W", strtotime($nextRow['tc_createddate']))) { $chClass = " change"; $curRow = $nextRow; $nextRow = mysql_fetch_array($taskRes); if (!$nextRow) { $checkNextRow = false; } } else { $checkNextRow = false; } } // Get the started week, completed week and created week of the current completion estimate $compWeek = date("y", strtotime($curRow['completiondate'])) . date("W", strtotime($curRow['completiondate'])); $createWeek = date("y", strtotime($curRow['tc_createddate'])) . date("W", strtotime($curRow['tc_createddate'])); $st = strtotime($curRow['commencedate']); if ($st > 1) { $startWeek = date("y", $st) . date("W", $st); } else { $startWeek = $createWeek; } // Is the task active (in prgress or completed, not on hold or blocked) if ($curRow['statusid'] == 2 or $curRow['statusid'] == 5) { $taskActive = true; } else { $taskActive = false; } // Get the cell value (week number or date of estimate depending on display mode) // This will be used lower down to populate the cell if required if ($showAsWeeks) { $compStr = substr($compWeek, 2, 2); } else { $compStr = date("d", strtotime($curRow['completiondate'])) . "/" . date("m", strtotime($curRow['completiondate'])); } // If options are to show out of office, and user is out of office mark as out if ($showHoliday and $h->IsHoliday($curRow['developerid'], substr($cellWeek, 2, 2))) { $rowText = $rowText . ",Out"; if ($projRow % 2 == 0) { $tdAttr = $tdAttr . ",class='hol-e'"; } else { $tdAttr = $tdAttr . ",class='hol-o'"; } } else { // If the completion estimate was created after the current week or the current // week is in the future don't display a week number if ($cellWeek < $createWeek or $cellWeek > $repWeek) { $rowText = $rowText . ","; // If the current week is in the future, but inside the scope of the completion // estimate mark the cell as being in the project if ($cellWeek > $createWeek and $cellWeek <= $compWeek and $taskActive or $cellWeek >= $startWeek and $cellWeek <= $compWeek and !$taskActive) { if ($cellWeek > $createWeek) { $tdAttr = $tdAttr . ",class='{$pclass}'"; $rowText = $rowText . "*"; } else { $tdAttr = $tdAttr . ",class='{$sclass}'"; } } else { // If the current week is in the past, but inside the scope of the task // start date, mark the cell as being in the project if ($cellWeek < $startWeek or $cellWeek > $repWeek) { $tdAttr = $tdAttr . ","; } else { $tdAttr = $tdAttr . ",class='{$sclass}'"; } } } elseif ($cellWeek <= $compWeek) { $rowText = $rowText . "," . $compStr; switch ($curRow['statusid']) { case 1: // Not Started if ($cellWeek >= $startWeek) { $cellClass = $sclass; $rowText = $rowText . "N"; } else { $cellClass = ""; $rowText = $rowText . "n"; } break; case 2: // In progress $cellClass = $pclass; break; case 5: // completed $cellClass = $cclass; if ($cellWeek == $compWeek) { $rowText = $rowText . "c"; } break; case 4: // Blocked $cellClass = $bclass; $rowText = $rowText . "b"; break; default: $cellClass = ""; } if ($cellWeek == $repWeek) { $tdAttr = $tdAttr . ",class='{$cellClass} today{$chClass}'"; } else { $tdAttr = $tdAttr . ",class='{$cellClass}{$chClass}'"; } } elseif ($cellWeek > $compWeek && $cellWeek == $createWeek && $curRow['statusid'] == 5) { $tdAttr = $tdAttr . ",class='{$cclass}'"; $rowText = $rowText . "," . $compStr . "c"; } else { if ($curRow['statusid'] != 5) { $rowText = $rowText . "," . $compStr; if ($cellWeek == $repWeek) { $tdAttr = $tdAttr . ",class='{$lclass} today'"; } else { $tdAttr = $tdAttr . ",class='{$lclass}'"; } } else { $rowText = $rowText . ","; if ($cellWeek == $repWeek) { $tdAttr = $tdAttr . ",class='today'"; } else { $tdAttr = $tdAttr . ","; } } } } //$cellWeek++; $nxtDate = strtotime("+{$i} weeks", $repStartDate); $cellWeek = date("y", $nxtDate) . date("W", $nxtDate); } $projTableAttr[] = explode(",", $tdAttr); $projTable[] = explode(",", $rowText); $projRow++; } } } return $rowText; }
/** * @param TimeTracking $timeTracking * @param bool $isDetailed * @param int[] $weekDates * @return mixed[] */ private function getWeekDetails(TimeTracking $timeTracking, $isDetailed, $weekDates, $session_userid) { $team = TeamCache::getInstance()->getTeam($timeTracking->getTeamid()); $weekDetails = array(); $session_users = $team->getUsers(); foreach ($session_users as $session_user) { // if user was working on the project during the timestamp if ($session_user->isTeamDeveloper($timeTracking->getTeamid(), $timeTracking->getStartTimestamp(), $timeTracking->getEndTimestamp()) || $session_user->isTeamManager($timeTracking->getTeamid(), $timeTracking->getStartTimestamp(), $timeTracking->getEndTimestamp())) { // PERIOD week //$thisWeekId=date("W"); $weekTracks = $timeTracking->getWeekDetails($session_user->getId(), !$isDetailed); $holidays = Holidays::getInstance(); $weekJobDetails = array(); foreach ($weekTracks as $bugid => $jobList) { try { $issue = IssueCache::getInstance()->getIssue($bugid); } catch (Exception $e) { self::$logger->error("getWeekDetails() skip issue {$bugid} : " . $e->getMessage()); $weekJobDetails[] = array("description" => '<span class="error_font">' . $bugid . ' : ' . T_('Error: Task not found in Mantis DB !') . '</span>', "duration" => "!", "progress" => "!", "projectName" => "!", "targetVersion" => "!", "jobName" => "!", "daysDetails" => "!", "totalDuration" => "!"); continue; } $project = ProjectCache::getInstance()->getProject($issue->getProjectId()); if ($isDetailed) { $formatedJobList = implode(', ', array_keys($jobList)); $query = 'SELECT id, name FROM `codev_job_table` WHERE id IN (' . $formatedJobList . ');'; $result2 = SqlWrapper::getInstance()->sql_query($query); if (!$result2) { continue; } while ($row2 = SqlWrapper::getInstance()->sql_fetch_object($result2)) { $jobName = $row2->name; $dayList = $jobList[$row2->id]; $daysDetails = array(); $weekDuration = 0; for ($i = 1; $i <= 7; $i++) { $dayDetails = $this->getDaysDetails($i, $holidays, $weekDates, $dayList[$i]); $weekDuration += $dayDetails['duration']; $daysDetails[] = $dayDetails; } if (!$project->isSideTasksProject(array($team->getId())) && !$project->isExternalTasksProject()) { $tooltipAttr = $issue->getTooltipItems($team->getId(), $session_userid); // force some fields #$tooltipAttr[T_('Elapsed')] = $issue->getElapsed(); #$tooltipAttr[T_('Backlog')] = $issue->getDuration(); #$tooltipAttr[T_('Drift')] = $issue->getDrift(); #$tooltipAttr[T_('DriftColor')] = $issue->getDriftColor(); $infoTooltip = Tools::imgWithTooltip('images/b_info.png', $tooltipAttr); } else { $infoTooltip = NULL; } // prepare json data for the IssueNoteDialogbox $issueNoteData = $this->getIssueNoteTooltip($project, $team, $issue); $weekJobDetails[] = array('description' => SmartyTools::getIssueDescription($bugid, $issue->getTcId(), $issue->getSummary()), 'duration' => $issue->getDuration(), 'progress' => round(100 * $issue->getProgress()), 'projectName' => $issue->getProjectName(), 'targetVersion' => $issue->getTargetVersion(), 'jobName' => $jobName, 'daysDetails' => $daysDetails, 'totalDuration' => $weekDuration, 'infoTooltip' => $infoTooltip, 'issueNoteId' => $issueNoteData['id'], 'noteTooltip' => $issueNoteData['tooltip']); } } else { // for each day, concat jobs duration $daysDetails = array(); $weekDuration = 0; for ($i = 1; $i <= 7; $i++) { $duration = 0; foreach ($jobList as $dayList) { if (array_key_exists($i, $dayList)) { $duration += $dayList[$i]; } } if ($duration == 0) { $duration = ""; } $dayDetails = $this->getDaysDetails($i, $holidays, $weekDates, $duration); $weekDuration += $dayDetails['duration']; $daysDetails[] = $dayDetails; } if (!$project->isSideTasksProject(array($team->getId())) && !$project->isExternalTasksProject()) { $tooltipAttr = $issue->getTooltipItems($team->getId(), $session_userid); // force some fields #$tooltipAttr[T_('Elapsed')] = $issue->getElapsed(); #$tooltipAttr[T_('Backlog')] = $issue->getDuration(); #$tooltipAttr[T_('Drift')] = $issue->getDrift(); #$tooltipAttr[T_('DriftColor')] = $issue->getDriftColor(); $infoTooltip = Tools::imgWithTooltip('images/b_info.png', $tooltipAttr); } else { $infoTooltip = NULL; } // prepare json data for the IssueNoteDialogbox $issueNoteData = $this->getIssueNoteTooltip($project, $team, $issue); $weekJobDetails[] = array('description' => SmartyTools::getIssueDescription($bugid, $issue->getTcId(), $issue->getSummary()), 'duration' => $issue->getDuration(), 'progress' => round(100 * $issue->getProgress()), 'projectName' => $issue->getProjectName(), 'daysDetails' => $daysDetails, 'totalDuration' => $weekDuration, 'infoTooltip' => $infoTooltip, 'issueNoteId' => $issueNoteData['id'], 'noteTooltip' => $issueNoteData['tooltip']); } } if (!empty($weekJobDetails)) { $weekDetails[] = array('name' => $session_user->getName(), 'realname' => $session_user->getRealname(), 'forecastWorkload' => $session_user->getForecastWorkload(), 'weekDates' => array(Tools::formatDate("%A\n%d %b", $weekDates[1]), Tools::formatDate("%A\n%d %b", $weekDates[2]), Tools::formatDate("%A\n%d %b", $weekDates[3]), Tools::formatDate("%A\n%d %b", $weekDates[4]), Tools::formatDate("%A\n%d %b", $weekDates[5])), 'weekEndDates' => array(Tools::formatDate("%A\n%d %b", $weekDates[6]), Tools::formatDate("%A\n%d %b", $weekDates[7])), 'weekJobDetails' => $weekJobDetails); } } } return $weekDetails; }
?> "> <input type="text" name="year" id="year" /> <input type="submit" name="submit" value="Go" /> </form> <hr /> <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $year = $_REQUEST['year']; if (empty($year) || !is_numeric($year)) { ?> <p>Invalid Date Input</p> <?php } else { require_once '../../Holidays.class.php'; $holidays = new Holidays($year); ?> <h1>Holidays for <?php echo $year; ?> </h1> <h2>Observed Dates</h2> <table> <tr> <th>Holiday</th> <th>Observed Date</th> </tr> <?php foreach ($holidays as $name => $date) { ?> <tr>
public function testUpdateHolidaysForLeavesOnDelete() { $dbConnection = new DMLFunctions(); Holidays::updateHolidaysForLeavesOnDelete(date('Y-m-d', time() - 3600 * 24 * 2), '8'); $query = "SELECT leave_id, leave_status FROM hs_hr_leave WHERE leave_id = 11 "; $result = $dbConnection->executeQuery($query); $row = $dbConnection->dbObject->getArray($result); $this->assertEquals(5, $row['leave_status'], 'Invalid status'); Holidays::updateHolidaysForLeavesOnDelete(date('Y-m-d', time() + 3600 * 24 * 3), '8'); $query = "SELECT leave_id, leave_status FROM hs_hr_leave WHERE leave_id = 13 "; $result = $dbConnection->executeQuery($query); $row = $dbConnection->dbObject->getArray($result); $this->assertEquals(1, $row['leave_status'], 'Invalid status'); }
?> <option value="<?php echo $key; ?> "><?php echo $value; ?> </option> <?php } } ?> </select> <?php } else { $holiday = Holidays::getHolidayForDate($record->getLeaveDate()); if (!empty($holiday) && is_a($holiday, 'Holidays')) { echo $holiday->getDescription(); } else { echo $lang_Leave_Closed; } ?> <input type="hidden" name="cmbStatus[]" value="<?php echo $record->getLeaveStatus(); ?> " /> <?php } ?> <?php } else {
public static function getHolidayDatabySeasonId($seasonId) { return Holidays::where('season_id', '=', $seasonId)->get(); }