Exemple #1
0
 /**
  * Gets quarterly budget of specified year for the Project
  *
  * @param   int    $year   The year
  * @throws  \RuntimeException
  * @return  \Scalr\Model\Collections\ArrayCollection Returns collection of the QuarterlyBudgetEntity objects
  */
 public function getQuarterlyBudget($year)
 {
     if ($this->projectId === null) {
         throw new \RuntimeException(sprintf("Identifier of the project has not been initialized yet for %s", get_class($this)));
     }
     return QuarterlyBudgetEntity::getProjectBudget($year, $this->projectId);
 }
Exemple #2
0
 public function xSaveAction()
 {
     $this->request->defineParams(array('projectId' => ['type' => 'string'], 'year' => ['type' => 'int'], 'quarters' => ['type' => 'json'], 'selectedQuarter' => ['type' => 'string']));
     $year = $this->getParam('year');
     $selectedQuarter = $this->getParam('selectedQuarter');
     if ($selectedQuarter !== 'year' && ($selectedQuarter < 1 || $selectedQuarter > 4)) {
         throw new OutOfBoundsException(sprintf("Invalid selectedQuarter number."));
     }
     $quarterReq = [];
     foreach ($this->getParam('quarters') as $q) {
         if (!isset($q['quarter'])) {
             throw new InvalidArgumentException(sprintf("Missing quarter property for quarters data set in the request."));
         }
         if ($q['quarter'] < 1 || $q['quarter'] > 4) {
             throw new OutOfRangeException(sprintf("Quarter value should be between 1 and 4."));
         }
         if (!isset($q['budget'])) {
             throw new InvalidArgumentException(sprintf("Missing budget property for quarters data set in the request."));
         }
         $quarterReq[$q['quarter']] = $q;
     }
     if ($this->getParam('projectId')) {
         $subjectType = QuarterlyBudgetEntity::SUBJECT_TYPE_PROJECT;
         $subjectId = $this->getParam('projectId');
         $subjectEntity = ProjectEntity::findPk($subjectId);
         /* @var $subjectEntity ProjectEntity */
         if ($subjectEntity->accountId != $this->user->getAccountId() || $subjectEntity->shared != ProjectEntity::SHARED_WITHIN_ACCOUNT) {
             throw new Scalr_Exception_InsufficientPermissions();
         }
     } else {
         throw new InvalidArgumentException(sprintf('ProjectId must be provided with the request.'));
     }
     if (!preg_match("/^[[:xdigit:]-]{36}\$/", $subjectId)) {
         throw new InvalidArgumentException(sprintf("Invalid UUID has been passed."));
     }
     if (!preg_match('/^\\d{4}$/', $year)) {
         throw new InvalidArgumentException(sprintf("Invalid year has been passed."));
     }
     //Fetches the previous state of the entities from database
     $collection = QuarterlyBudgetEntity::getProjectBudget($year, $subjectId);
     $quarters = new Quarters(SettingEntity::getQuarters(true));
     //Updates|creates entities
     for ($quarter = 1; $quarter <= 4; ++$quarter) {
         if (!isset($quarterReq[$quarter])) {
             continue;
         }
         $period = $quarters->getPeriodForQuarter($quarter, $year);
         //Checks if period has already been closed and forbids update
         if ($period->end->format('Y-m-d') < gmdate('Y-m-d')) {
             continue;
         }
         $entity = current($collection->filterByQuarter($quarter));
         if ($entity instanceof QuarterlyBudgetEntity) {
             //We should update an entity
             $entity->budget = abs((double) $quarterReq[$quarter]['budget']);
         } else {
             //We should create a new one.
             $entity = new QuarterlyBudgetEntity($year, $quarter);
             $entity->subjectType = $subjectType;
             $entity->subjectId = $subjectId;
             $entity->budget = abs((double) $quarterReq[$quarter]['budget']);
         }
         $entity->save();
     }
     if ($selectedQuarter == 'year') {
         $selectedPeriod = $quarters->getPeriodForYear($year);
     } else {
         $selectedPeriod = $quarters->getPeriodForQuarter($selectedQuarter, $year);
     }
     $data = $this->getProjectData(ProjectEntity::findPk($subjectId), $selectedPeriod, true);
     $budgetInfo = $this->getBudgetInfo($year, $data['ccId'], $data['projectId']);
     $this->response->data(['data' => $data, 'budgetInfo' => $budgetInfo]);
     $this->response->success('Budget changes have been saved');
 }
Exemple #3
0
 /**
  * Gets project moving average to date
  *
  * @param   string|null $projectId    The identifier of the project
  * @param   string      $mode         The mode
  * @param   string      $date         The UTC date within period ('Y-m-d H:00')
  * @param   string      $startDate    The start date of the period in UTC ('Y-m-d')
  * @param   string      $endDate      The end date of the period in UTC ('Y-m-d')
  * @param   string      $ccId         optional The identifier of the cost center (It is used only when project is null)
  * @return  array       Returns project moving average to date
  * @throws  InvalidArgumentException
  * @throws  AnalyticsException
  */
 public function getProjectMovingAverageToDate($projectId, $mode, $date, $startDate, $endDate, $ccId = null)
 {
     $projectId = empty($projectId) ? null : $projectId;
     if (!preg_match('/^[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:00$/', $date)) {
         throw new InvalidArgumentException(sprintf("Invalid date:%s. 'YYYY-MM-DD HH:00' is expected.", strip_tags($date)));
     }
     if (!preg_match('/^[[:xdigit:]-]{36}$/', $projectId)) {
         throw new InvalidArgumentException(sprintf("Invalid identifier of the Project:%s. UUID is expected.", strip_tags($projectId)));
     }
     $iterator = ChartPeriodIterator::create($mode, $startDate, $endDate ?: null, 'UTC');
     //Interval which is used in the database query for grouping
     $queryInterval = preg_replace('/^1 /', '', $iterator->getInterval());
     if ($projectId !== null) {
         $project = ProjectEntity::findPk($projectId);
         if ($project === null) {
             if (empty($ccId)) {
                 throw new AnalyticsException(sprintf("Project %s does not exist. Please provide ccId.", $projectId));
             }
         } else {
             $ccId = $project->ccId;
         }
     }
     $data = $this->getRollingAvg(['projectId' => $projectId], $queryInterval, $date);
     $data['budgetUseToDate'] = null;
     $data['budgetUseToDatePct'] = null;
     //Does not calculate budget use to date for those cases
     if ($mode != 'custom' && $mode != 'year') {
         $pointPosition = $iterator->searchPoint($date);
         if ($pointPosition !== false) {
             $chartPoint = $iterator->current();
             //Gets the end date of the selected interval
             $end = clone $chartPoint->dt;
             if ($chartPoint->interval != '1 day') {
                 $end->modify("+" . $chartPoint->interval . " -1 day");
             }
             //Gets quarters config
             $quarters = new Quarters(SettingEntity::getQuarters());
             //Gets start and end of the quarter for the end date of the current interval
             $period = $quarters->getPeriodForDate($end);
             $data['year'] = $period->year;
             $data['quarter'] = $period->quarter;
             $data['quarterStartDate'] = $period->start->format('Y-m-d');
             $data['quarterEndDate'] = $period->end->format('Y-m-d');
             //Gets budgeted cost
             $budget = current(QuarterlyBudgetEntity::getProjectBudget($period->year, $projectId)->filterByQuarter($period->quarter));
             //If budget has not been set we should not calculate anything
             if ($budget instanceof QuarterlyBudgetEntity && round($budget->budget) > 0) {
                 $data['budget'] = round($budget->budget);
                 //Calculates usage from the start date of the quarter to date
                 $usage = $this->get(['projectId' => $projectId], $period->start, $end);
                 $data['budgetUseToDate'] = $usage['cost'];
                 $data['budgetUseToDatePct'] = $data['budget'] == 0 ? null : min(100, round($usage['cost'] / $data['budget'] * 100));
             }
         }
     }
     return ['data' => $data];
 }