Ejemplo n.º 1
0
 public function xSaveAction()
 {
     $this->request->defineParams(array('name' => array('type' => 'string', 'validator' => array(Scalr_Validator::NOEMPTY => true)), 'billingCode' => array('type' => 'string', 'validator' => array(Scalr_Validator::NOEMPTY => true, Scalr_Validator::ALPHANUM => true)), 'leadEmail' => array('type' => 'string', 'validator' => array(Scalr_Validator::NOEMPTY => true, Scalr_Validator::EMAIL => true))));
     if ($this->getParam('ccId')) {
         $cc = $this->getContainer()->analytics->ccs->get($this->getParam('ccId'));
         if (!$cc) {
             throw new Scalr_UI_Exception_NotFound();
         }
     } else {
         $cc = new CostCentreEntity();
     }
     if (!$this->request->validate()->isValid()) {
         $this->response->data($this->request->getValidationErrors());
         $this->response->failure();
         return;
     }
     $cc->name = $this->getParam('name');
     //Checks whether billing code specified in the request is already used in another Cost Centre
     $criteria = [['name' => CostCentrePropertyEntity::NAME_BILLING_CODE], ['value' => $this->getParam('billingCode')]];
     if ($cc->ccId !== null) {
         $criteria[] = ['ccId' => ['$ne' => $cc->ccId]];
     } else {
         //This is a new cost center.
         //We should set the email address and identifier of the user who creates the record.
         $cc->createdById = $this->user->id;
         $cc->createdByEmail = $this->user->getEmail();
     }
     $ccPropertyEntity = new CostCentrePropertyEntity();
     $record = $this->db->GetRow("\n            SELECT " . $cc->fields('c') . "\n            FROM " . $cc->table('c') . "\n            JOIN " . $ccPropertyEntity->table('cp') . " ON cp.cc_id = c.cc_id\n            WHERE " . $ccPropertyEntity->_buildQuery($criteria, 'AND', 'cp')['where'] . "\n            LIMIT 1\n        ");
     if ($record) {
         $found = new CostCentreEntity();
         $found->load($record);
     }
     if (!empty($found)) {
         throw new AnalyticsException(sprintf('Billing code "%s" is already used in Cost center "%s"', strip_tags($this->getParam('billingCode')), $found->name));
     }
     $this->db->BeginTrans();
     try {
         $cc->save();
         $cc->saveProperty(CostCentrePropertyEntity::NAME_BILLING_CODE, $this->getParam('billingCode'));
         $cc->saveProperty(CostCentrePropertyEntity::NAME_DESCRIPTION, $this->getParam('description'));
         $cc->saveProperty(CostCentrePropertyEntity::NAME_LEAD_EMAIL, $this->getParam('leadEmail'));
         $this->db->CommitTrans();
     } catch (Exception $e) {
         $this->db->RollbackTrans();
         throw $e;
     }
     $this->response->data(array('cc' => $this->getCostCenterData($cc, true)));
     $this->response->success('Cost center has been successfully saved');
 }