public function getContent($params = array()) { $this->request->restrictAccess(Acl::RESOURCE_OWN_FARMS, Acl::PERM_FARMS_CREATE); $projects = []; if ($this->getContainer()->analytics->enabled && $this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)) { $costCenter = $this->getContainer()->analytics->ccs->get($this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)); $currentYear = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y'); $quarters = new Quarters(SettingEntity::getQuarters()); $currentQuarter = $quarters->getQuarterForDate(new \DateTime('now', new \DateTimeZone('UTC'))); if ($costCenter instanceof CostCentreEntity) { $projectsIterator = new SharedProjectsFilterIterator($costCenter->getProjects(), $costCenter->ccId, $this->user, $this->getEnvironment()); foreach ($projectsIterator as $item) { $quarterBudget = QuarterlyBudgetEntity::findOne([['year' => $currentYear], ['subjectType' => QuarterlyBudgetEntity::SUBJECT_TYPE_PROJECT], ['subjectId' => $item->projectId], ['quarter' => $currentQuarter]]); $projects[] = array('projectId' => $item->projectId, 'name' => $item->name, 'budgetRemain' => !is_null($quarterBudget) && $quarterBudget->budget > 0 ? max(0, round($quarterBudget->budget - $quarterBudget->cumulativespend)) : null); } //$costCentreName = $costCenter->name; $isLocked = $costCenter->getProperty(CostCentrePropertyEntity::NAME_LOCKED); $accountCcs = AccountCostCenterEntity::findOne([['accountId' => $this->environment->clientId], ['ccId' => $costCenter->ccId]]); if ($isLocked || !$accountCcs instanceof AccountCostCenterEntity) { $costCentreLocked = 1; } else { $costCentreLocked = 0; } } else { $costCentreName = ''; $costCentreLocked = 0; } } return ['costCenterLocked' => $costCentreLocked, 'projects' => $projects]; }
/** * Edit project action * * @param string $projectId * @throws Scalr_UI_Exception_NotFound */ public function editAction($projectId = null) { $scope = $this->request->getScope(); $this->request->restrictAccess(Acl::RESOURCE_ADMINISTRATION_ANALYTICS, Acl::PERM_ADMINISTRATION_ANALYTICS_MANAGE_PROJECTS); if (!empty($projectId)) { $project = $this->getContainer()->analytics->projects->get($projectId); if ($project->shared != ProjectEntity::SHARED_WITHIN_ACCOUNT || $project->accountId != $this->user->getAccountId()) { throw new Scalr_Exception_InsufficientPermissions(); } $cc = $project->getCostCenter(); $projectData = $this->getProjectData($project, true); //Check whether it can be removed try { $projectData['removable'] = $project->checkRemoval(); } catch (AnalyticsException $e) { $projectData['removable'] = false; $projectData['warning'] = $e->getMessage(); } } else { if ($scope == 'environment') { $cc = $this->getContainer()->analytics->ccs->get($this->getEnvironment()->getPlatformConfigValue(\Scalr_Environment::SETTING_CC_ID)); } $projectData = []; } $ccs = []; if ($scope == 'environment') { $accountCcs = AccountCostCenterEntity::findOne([['accountId' => $this->user->getAccountId()], ['ccId' => $cc->ccId]]); if ($accountCcs instanceof AccountCostCenterEntity) { $ccs[$cc->ccId] = ['ccId' => $cc->ccId, 'name' => $cc->name, 'billingCode' => $cc->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE)]; } } elseif ($scope == 'account') { foreach ($this->user->getEnvironments() as $row) { $env = \Scalr_Environment::init()->loadById($row['id']); $ccEntity = CostCentreEntity::findPk($env->getPlatformConfigValue(\Scalr_Environment::SETTING_CC_ID)); /* @var $ccEntity \Scalr\Stats\CostAnalytics\Entity\CostCentreEntity */ if ($ccEntity) { $accountCcs = AccountCostCenterEntity::findOne([['accountId' => $env->clientId], ['ccId' => $ccEntity->ccId]]); if ($accountCcs instanceof AccountCostCenterEntity) { $ccs[$ccEntity->ccId] = ['ccId' => $ccEntity->ccId, 'name' => $ccEntity->name, 'billingCode' => $ccEntity->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE)]; } } } } $this->response->page('ui/admin/analytics/projects/edit.js', array('project' => $projectData, 'ccs' => $ccs, 'scope' => 'account')); }
/** * @test */ public function textAccountComplex() { $ccsArch = $this->createCostCenter(['name' => $this->getTestName(), 'archived' => CostCentreEntity::ARCHIVED]); $ccs = $this->listCostCenters([], false); $adapter = $this->getAdapter('costCenter'); $filterable = $adapter->getRules()[ApiEntityAdapter::RULE_TYPE_FILTERABLE]; foreach ($ccs as $cc) { foreach ($filterable as $property) { $filterValue = $cc->{$property}; $listResult = $this->listCostCenters([$property => $filterValue], false); if (!static::isRecursivelyEmpty($filterValue)) { foreach ($listResult as $filtered) { $this->assertEquals($filterValue, $filtered->{$property}, "Property '{$property}' mismatch"); } } } $response = $this->getCostCenter($cc->id, false); $this->assertEquals(200, $response->status, $this->printResponseError($response)); /* @var $dbCc CostCentreEntity */ $dbCc = CostCentreEntity::findPk($cc->id); /* @var $acCs AccountCostCenterEntity */ $acCs = AccountCostCenterEntity::findOne([['ccId' => $dbCc->ccId]]); $this->assertFalse($dbCc->archived); $this->assertEquals($this->getUser()->accountId, $acCs->accountId); $this->assertObjectEqualsEntity($response->getBody()->data, $dbCc, $adapter); } $filterByName = $this->listCostCenters(['name' => $ccsArch->name], false); $this->assertNotEmpty($filterByName); foreach ($filterByName as $cc) { $this->assertObjectEqualsEntity($cc, $ccsArch, $adapter); $this->assertNotContains($cc, $ccs, "List of Cost Centers shouldn't have an archived project", false, false); } $filterByBillingCode = $this->listCostCenters(['billingCode' => $ccsArch->getProperty(CostCentrePropertyEntity::NAME_BILLING_CODE)], false); $this->assertNotEmpty($filterByBillingCode); foreach ($filterByBillingCode as $cc) { $this->assertObjectEqualsEntity($cc, $ccsArch, $adapter); $this->assertNotContains($cc, $ccs, "List of Cost Centers shouldn't have an archived project", false, false); } }
/** * xSaveAction * * @param string $ccId * @param string $projectId * @param string $name * @param string $description * @param string $billingCode * @param string $leadEmail * @param int $shared * @param int $accountId optional * @param bool $checkAccountAccessToCc optional * @param bool $grantAccountAccessToCc optional * @throws Scalr_Exception_InsufficientPermissions */ public function xSaveAction($ccId, $projectId, $name, $description, $billingCode, $leadEmail, $shared, $accountId = null, $checkAccountAccessToCc = true, $grantAccountAccessToCc = false) { $validator = new Validator(); $validator->validate($name, 'name', Validator::NOEMPTY); if ($projectId) { $project = $this->getContainer()->analytics->projects->get($projectId); if (!$project) { throw new Scalr_UI_Exception_NotFound(); } } else { $project = new ProjectEntity(); $project->createdById = $this->user->id; $project->createdByEmail = $this->user->getEmail(); $cc = $this->getContainer()->analytics->ccs->get($ccId); if (!$cc) { $validator->addError('ccId', 'Cost center ID should be set'); } $project->ccId = $ccId; } if ($shared == ProjectEntity::SHARED_WITHIN_ACCOUNT) { $project->shared = ProjectEntity::SHARED_WITHIN_ACCOUNT; $project->accountId = $accountId; } elseif ($shared == ProjectEntity::SHARED_WITHIN_CC) { $project->shared = ProjectEntity::SHARED_WITHIN_CC; $project->accountId = null; } else { throw new Scalr_UI_Exception_NotFound(); } if (!$validator->isValid($this->response)) { return; } if ($project->shared == ProjectEntity::SHARED_WITHIN_ACCOUNT) { if (!AccountCostCenterEntity::findOne([['accountId' => $project->accountId], ['ccId' => $ccId]])) { if ($checkAccountAccessToCc) { $this->response->data(['ccIsNotAllowedToAccount' => true]); $this->response->failure(); return; } elseif ($grantAccountAccessToCc) { //give account access to cc $accountCcEntity = new AccountCostCenterEntity($project->accountId, $ccId); $accountCcEntity->save(); } } } $project->name = $name; $this->db->BeginTrans(); try { $project->save(); //NOTE please take into account the presence of the usage->createHostedScalrAccountCostCenter() method $project->saveProperty(ProjectPropertyEntity::NAME_BILLING_CODE, $billingCode); $project->saveProperty(ProjectPropertyEntity::NAME_DESCRIPTION, $description); $project->saveProperty(ProjectPropertyEntity::NAME_LEAD_EMAIL, $leadEmail); $this->db->CommitTrans(); } catch (Exception $e) { $this->db->RollbackTrans(); throw $e; } $this->response->data(['project' => $this->getProjectData($project)]); $this->response->success('Project has been successfully saved'); }
public function create($name, $clientId) { $this->id = 0; $this->name = $name; $this->clientId = $clientId; $this->status = self::STATUS_ACTIVE; $this->save(); if (\Scalr::getContainer()->analytics->enabled) { //Default Cost Center for the new Environment is the first Cost Center //from the list of the Account Cost Centers $accountCcEntity = AccountCostCenterEntity::findOne([['accountId' => $clientId]]); if ($accountCcEntity instanceof AccountCostCenterEntity) { //Associates environment with the Cost Center $this->setPlatformConfig([Scalr_Environment::SETTING_CC_ID => $accountCcEntity->ccId]); //Fire event \Scalr::getContainer()->analytics->events->fireAssignCostCenterEvent($this, $accountCcEntity->ccId); } } return $this; }
/** * xMoveProjectsAction * * @param JsonData $projects Projects that should be moved * @throws AnalyticsException * @throws Exception * @throws \Scalr\Exception\ModelException */ public function xMoveProjectsAction(JsonData $projects = null) { $envChange = []; $accountChange = []; $projectChange = []; $ccEntityCache = []; $collisions = []; foreach ($projects as $project) { $projectEntity = ProjectEntity::findPk($project['projectId']); /* @var $projectEntity ProjectEntity */ if (empty($ccEntity)) { $ccEntity = $projectEntity->getCostCenter(); } if ($ccEntity->ccId == $project['ccId']) { continue; } if (empty($ccEntityCache[$project['ccId']])) { $newCcEntity = CostCentreEntity::findPk($project['ccId']); /* @var $newCcEntity CostCentreEntity */ if (!$newCcEntity) { throw new Exception(sprintf("Cost center with id %s has not been found.", $project['ccId']), 404); } $ccEntityCache[$project['ccId']] = $newCcEntity->ccId; } $farms[$projectEntity->projectId] = $projectEntity->getFarmsList(); foreach ($farms[$projectEntity->projectId] as $farmId => $farmName) { $farmEntity = Farm::findPk($farmId); /* @var $farmEntity Farm */ if (empty($accountChange[$farmEntity->accountId])) { $accountCss = AccountCostCenterEntity::findOne([['accountId' => $farmEntity->accountId], ['ccId' => $newCcEntity->ccId]]); if (!$accountCss) { $accountChange[$farmEntity->accountId] = $newCcEntity->ccId; } } if (empty($envChange[$farmEntity->envId])) { $project['name'] = $projectEntity->name; $envChange[$farmEntity->envId] = $project; } else { if ($envChange[$farmEntity->envId]['ccId'] != $project['ccId']) { if (!in_array($projectEntity->name, $collisions)) { $collisions[] = $projectEntity->name; } if (!in_array($envChange[$farmEntity->envId]['name'], $collisions)) { $collisions[] = $envChange[$farmEntity->envId]['name']; } continue; } } } $projectEntity->ccId = $project['ccId']; $projectChange[$projectEntity->projectId] = $projectEntity; } $remainningEnvs = []; $projectsCount = count($projectChange); if ($projectsCount) { if (isset($ccEntity)) { $envList = $ccEntity->getEnvironmentsList(); foreach ($envList as $envId => $name) { if (isset($envChange[$envId])) { $ccProjects = $this->getContainer()->analytics->projects->getUsedInEnvironment($envId); foreach ($ccProjects as $project) { /* @var $project ProjectEntity */ if (!isset($farms[$project->projectId])) { $farms[$project->projectId] = $project->getFarmsList(); } if (count($farms[$project->projectId]) > 0 && !isset($projectChange[$project->projectId])) { if (!in_array($envId, $remainningEnvs)) { $remainningEnvs[] = $envId; } } } } } } $this->db->BeginTrans(); try { foreach ($accountChange as $accountId => $ccId) { $accountCss = new AccountCostCenterEntity($accountId, $ccId); $accountCss->save(); } if (empty($remainningEnvs) && empty($collisions)) { foreach ($envChange as $envId => $data) { $envProp = EnvironmentProperty::findOne([['envId' => $envId], ['name' => EnvironmentProperty::SETTING_CC_ID]]); /* @var $envProp EnvironmentProperty */ $envProp->value = $data['ccId']; $envProp->save(); } } foreach ($projectChange as $project) { /* @var $project ProjectEntity */ $project->save(); } $this->db->CommitTrans(); } catch (Exception $e) { $this->db->RollbackTrans(); throw $e; } } if (count($collisions) > 0) { $this->response->warning(sprintf("%d Project%s %s been moved however collision occurred. Projects '%s' are used in the Farms from the same Environment however they have been moved to different Cost Centers.", $projectsCount, $projectsCount > 1 ? 's' : '', $projectsCount > 1 ? 'have' : 'has', implode("', '", $collisions))); } else { if (count($remainningEnvs) > 0) { $this->response->warning(sprintf("%d Project%s %s been moved however some Projects don't correspond to Cost Centers assigned to Environments '%s'.", $projectsCount, $projectsCount > 1 ? 's' : '', $projectsCount > 1 ? 'have' : 'has', implode("', '", $remainningEnvs))); } else { $this->response->success(sprintf("%d Project%s %s been moved to other Cost Center.", $projectsCount, $projectsCount > 1 ? 's' : '', $projectsCount > 1 ? 'have' : 'has')); } } }
private function getFarmCostData($farmId) { $result = []; $costCenter = $this->getContainer()->analytics->ccs->get($this->getEnvironment()->getPlatformConfigValue(Scalr_Environment::SETTING_CC_ID)); $currentYear = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Y'); $quarters = new Quarters(SettingEntity::getQuarters()); $currentQuarter = $quarters->getQuarterForDate(new \DateTime('now', new \DateTimeZone('UTC'))); $projects = []; if ($farmId) { $farm = DBFarm::LoadByID($farmId); $currentProjectId = $farm->GetSetting(Entity\FarmSetting::PROJECT_ID); $currentProject = ProjectEntity::findPk($currentProjectId); /* @var $currentProject ProjectEntity */ if (!empty($currentProject)) { $quarterBudget = QuarterlyBudgetEntity::findOne([['year' => $currentYear], ['subjectType' => QuarterlyBudgetEntity::SUBJECT_TYPE_PROJECT], ['subjectId' => $currentProject->projectId], ['quarter' => $currentQuarter]]); $projects[] = ['projectId' => $currentProject->projectId, 'name' => "{$currentProject->name} / {$currentProject->getCostCenter()->name}", 'budgetRemain' => !is_null($quarterBudget) && $quarterBudget->budget > 0 ? max(0, round($quarterBudget->budget - $quarterBudget->cumulativespend)) : null]; } $result['projectId'] = $farm->GetSetting(Entity\FarmSetting::PROJECT_ID); $result['farmCostMetering'] = $result['projectId'] ? $this->getContainer()->analytics->usage->getFarmCostMetering($this->user->getAccountId(), $farmId) : null; } if ($costCenter instanceof CostCentreEntity) { $projectsIterator = new SharedProjectsFilterIterator($costCenter->getProjects(), $costCenter->ccId, $this->user, $this->getEnvironment()); foreach ($projectsIterator as $item) { /* @var $item Scalr\Stats\CostAnalytics\Entity\ProjectEntity */ if (!empty($currentProjectId) && $item->projectId == $currentProjectId) { continue; } $quarterBudget = QuarterlyBudgetEntity::findOne([['year' => $currentYear], ['subjectType' => QuarterlyBudgetEntity::SUBJECT_TYPE_PROJECT], ['subjectId' => $item->projectId], ['quarter' => $currentQuarter]]); $projects[] = array('projectId' => $item->projectId, 'name' => "{$item->name} / {$costCenter->name}", 'budgetRemain' => !is_null($quarterBudget) && $quarterBudget->budget > 0 ? max(0, round($quarterBudget->budget - $quarterBudget->cumulativespend)) : null); } $costCentreName = $costCenter->name; $isLocked = $costCenter->getProperty(CostCentrePropertyEntity::NAME_LOCKED); $accountCcs = AccountCostCenterEntity::findOne([['accountId' => $this->environment->clientId], ['ccId' => $costCenter->ccId]]); if ($isLocked || !$accountCcs instanceof AccountCostCenterEntity) { $costCentreLocked = 1; } else { $costCentreLocked = 0; } } else { $costCentreName = ''; $costCentreLocked = 0; } $supportedClouds = $this->getContainer()->analytics->prices->getSupportedClouds(); $result['analytics'] = array('costCenterName' => $costCentreName, 'costCenterLocked' => $costCentreLocked, 'projects' => $projects, 'unsupportedClouds' => array_values(array_diff($this->environment->getEnabledPlatforms(), $supportedClouds))); return $result; }