/** * Retrive the list of enum by type * * @param string $type */ public function getEnum($type, $filters = array()) { /** * @var \Application\Model\Mapper\EnumeratedMapper */ $enumMapper = \Application\Model\Mapper\EnumeratedMapper::getInstance(); if (!$type) { throw new Exceptions\InvalidArgumentException("Enum type is mandatory"); } if ($filters && !is_array($filters)) { throw new Exceptions\InvalidArgumentException("filters is not an array"); } switch ($type) { case self::COUNTRY_ENUM_NAME: return $enumMapper->listCountry(); case self::CURRENCY_ENUM_NAME: return $enumMapper->listCurrency(); case self::LANGUAGE_ENUM_NAME: return $enumMapper->listLanguage(); case self::SECTOR_ENUM_NAME: return $enumMapper->listSector(); case self::STATUS_ENUM_NAME: return $enumMapper->listStatus(); case self::COMPANY_TYPE_ENUM_NAME: return $enumMapper->listCompanyType(); case self::TIME_ZONE_STATIC_ENUM_NAME: return $enumMapper->listStaticTimeZone(); case self::MNO_ENUM_NAME: return $enumMapper->listMNO(); default: // Get service provider id if (isset($filters['serviceProvider'])) { $orgId = $filters['serviceProvider']; } else { $org = \App::getOrgUserLogged(); $orgId = OrgService::getInstance()->getServiceProviderLevelId($org); } // Get enum by service provider switch ($type) { case self::RAID_ENUM_NAME: return $enumMapper->listRaid($orgId); case self::SERVICE_PROVIDER_ZONE_ENUM_NAME: $zones = $enumMapper->listServiceProviderZone($orgId); return $this->_filterDefaultValues($zones); case self::SERVICE_PROVIDER_DESTINATION_ENUM_NAME: $destinations = $enumMapper->listServiceProviderDestination($orgId); return $this->_filterDefaultValues($destinations); case self::TIME_ZONE_ENUM_NAME: return $enumMapper->listTimeZone($orgId); case self::SERVICE_PROVIDER_REGION_ENUM_NAME: $regions = $enumMapper->listServiceProviderRegion($orgId); return $this->_filterDefaultValues($regions); default: throw new AppEx\InvalidArgumentException("Enumerated " . $type . " doesn't exist"); } } }
public function existName($name, $type) { $filterList = array('name' => $name, 'type' => $type); $filterList = $this->buildFilterList($filterList, \App::getOrgUserLogged()); $items = $this->listAll(array('filterList' => $filterList))->getItems(); if (!empty($items)) { return true; } return false; }
/** * Validate that report organization is a customer * * @param array $params */ protected function _validateCustomerOrg(array &$params, $type = null) { $orgId = \App::getOrgUserLogged()->id; switch (Mapper\OrganizationMapper::getTypeByOrgId($orgId)) { case Model\Organization\OrgCustomerModel::ORG_TYPE: $params[ReportFilterFields::ORGANIZATION] = $orgId; break; case Model\Organization\OrgServiceProviderModel::ORG_TYPE: $this->_validateMandatoryParams($params, array(ReportFilterFields::ORGANIZATION)); break; } if (Mapper\OrganizationMapper::getTypeByOrgId($params[ReportFilterFields::ORGANIZATION]) !== Model\Organization\OrgCustomerModel::ORG_TYPE) { throw new InvalidArgumentException('Invalid parameter value: ' . ReportFilterFields::ORGANIZATION . '. Supported values are customer-xxxxx'); } }
/** * * @param string $filename */ public function uploadBulk($filename) { // Open file if (!stat($filename)) { throw new \Application\Exceptions\UnexpectedException("Error opening file {$filename}"); } $fd = fopen($filename, 'r'); $sep = \App_Parser_CsvParser::getCsvSeparator($fd); // Request $sims = array(); $validator = new SimBulkValidate(); $validHeaders = $this->getUploadBulkHeaders(); $filter = \Zend_Controller_Action_HelperBroker::getStaticHelper('FilterNotAllowedFields'); // CSV $header = fgetcsv($fd, 0, $sep); // Header $prows = 0; // Packet rows $irows = 1; // Iteration rows $nrows = 1; // Total rows $ncols = count($header); // Total columns $validH = false; foreach ($header as $h) { if (isset($validHeaders[$h])) { $validH = true; break; } } // Check lines readed if (!$validH) { \App::log()->debug("[UpdateBulk] No valid headers"); throw new ValidateException("No valid headers", ValidationCodes::FILE_NO_VALID_HEADERS); } if (in_array('locationManual_latitude', $header) && !in_array('locationManual_longitude', $header) || in_array('locationManual_longitude', $header) && !in_array('locationManual_latitude', $header)) { \App::log()->debug("[UpdateBulk] No valid headers: location requires latitude and longitude"); throw new ValidateException("No valid headers: location requires latitude and longitude", ValidationCodes::FILE_NO_VALID_HEADERS_LOCATION); } $bulkCount = \App::config('ericssonserviceCallItemCount', self::BULK_UPDATE_DEFAULT); // I'm not sure... I don't like it. set_time_limit(0); $watcher = $this->getMapper()->createFileWatcher(); $txId = uniqid("bulk"); $watcher->entityIds = array($txId); $watcher->params->action = "bulkSimUpdate"; WatcherService::getInstance()->create($watcher); $errors = array(); $warnings = array(); $ntxs = 0; // Rows while (($line = fgetcsv($fd, 0, $sep)) !== false) { // Next line has been readed $nrows++; // Check columns if (count($line) !== $ncols) { $errors[] = new Model\ErrorModel(array('line' => $nrows, 'description' => "Incorrect format (number of columns)", 'level' => Model\ErrorModel::ERROR_LEVEL_ERROR, 'code' => ValidationCodes::FILE_READING_ERR)); continue; } // Create sim $data = array(); foreach ($header as $key => $name) { // \App::log()->debug("[UpdateBulk] $name : $key"); if (!isset($validHeaders[$name])) { // Ignore invalid columns // \App::log()->warn("[UpdateBulk] Ignoring $name column"); continue; } $value = $line[$key]; if (preg_match('/^=\\"(?P<value>.*)\\"$/', $value, $matches)) { $value = $matches['value']; } // GLOBALPORTAL-28668 // if (!empty($value)) { // \App::log()->debug("[UpdateBulk] $name : $value"); if (isset($value) && (!empty($value) || is_numeric($value))) { // \App::log()->debug("[UpdateBulk] TRUE $name : $value"); // Remove field? // See SimBaseMapper _mapModelToEricssonModel method, // SimValidate and App_Validate_ReferenceIndex to understand it if ($value === '-' && $name !== 'staticIpApnIndex') { $value = ''; } // Process field if (strpos($name, 'apn_') !== false) { // In order to remove the current value of a SIM´s field, // the character - must be indicated $index = (int) substr($name, strlen('apn_apn')) - 1; $data['apns'][$index] = $value; } else { if (strpos($name, 'locationManual_') !== false) { $value = str_replace(',', '.', $value); if (!is_numeric($value)) { $warnings[] = new Model\ErrorModel(array('line' => $nrows, 'column' => $name, 'description' => "Invalid value", 'level' => Model\ErrorModel::ERROR_LEVEL_WARN, 'code' => ValidationCodes::INVALID_VALUE)); } else { $subname = substr($name, strlen('locationManual_')); $value = floatval(str_replace(',', '.', $value)); $data['locationManual'][$subname] = (int) round($value * pow(10, 6)); } } else { if ($name == 'LTE_status') { if ($value != SimModel::LTE_ACTIVE && $value != SimModel::LTE_INACTIVE) { $warnings[] = new Model\ErrorModel(array('line' => $nrows, 'column' => $name, 'description' => "Invalid value", 'level' => Model\ErrorModel::ERROR_LEVEL_WARN, 'code' => ValidationCodes::INVALID_VALUE)); } else { $data['lteEnabled'] = $value == SimModel::LTE_ACTIVE ? true : false; } } else { $data[$name] = $value; } } } } } // Create and validate sim $sim = new SimModel($data); $v = $this->validate($sim, false, $validator); if ($v === true) { // Backup id $ids = $sim->getIds(); $type = key($ids); $value = current($ids); //Inject organization $org = \App::getOrgUserLogged(); switch ($org->getType()) { case OrgMasterModel::ORG_TYPE: $sim->setMaster($org); break; case OrgServiceProviderModel::ORG_TYPE: $sim->setServiceProviderCommercial($org); $sim->setServiceProviderEnabler($org); break; case OrgCustomerModel::ORG_TYPE: $sim->setCustomer($org); break; case OrgAggregatorModel::ORG_TYPE: $sim->setAggregator($org); break; case OrgEndUserModel::ORG_TYPE: $sim->setEndUser($org); break; } // Filter by permissions $filter->direct('update_field', $sim); // Recover id and add sim to request $sim->{$type} = $value; $sims[] = $sim; $prows++; } else { \App::log()->warn("[UpdateBulk] Ignoring invalid sim: " . json_encode($v)); // Sending first validation error ONLY? foreach ($validator->getValidationCodes() as $field => $code) { $errors[] = new Model\ErrorModel(array('line' => $nrows, 'description' => $field, 'level' => Model\ErrorModel::ERROR_LEVEL_WARN, 'code' => $code ?: ValidationCodes::MODEL_SIM)); } } // Wait until packet is full if ($prows == $bulkCount) { // Send to Ericsson $this->_uploadBulk($sims, $errors, $irows, $nrows, $watcher); $ntxs++; // Reset packet list $sims = array(); $prows = 0; // Update CSV line position $irows = $nrows + 1; } } // Ensure all sims have been sent (last packet) if (!empty($sims)) { // Send to Ericsson $this->_uploadBulk($sims, $errors, $irows, $nrows, $watcher); $ntxs++; // Reset packet list (memory propouses) $sims = array(); } // Check lines readed if ($nrows < 2) { \App::log()->debug("[UpdateBulk] Ignoring empty file"); $watcher->delete(); throw new ValidateException("Missing file rows"); } $event = $this->getMapper()->constructEventToTransaction(); $event->entityId = $txId; // Add error code suffix if (isset($errors) && is_array($errors)) { foreach ($errors as $errMess) { require_once APPLICATION_PATH . '/modules/default/controllers/ErrorController.php'; $errMess->code = \ErrorController::finishErrorCode($errMess->code); } } $eventData = array('simParsed' => $nrows - 1); if (!empty($errors) || !empty($warnings)) { $eventData['hasFailures'] = true; if (!empty($errors)) { $eventData['message']['failed'] = $errors; } if (!empty($warnings)) { $eventData['message']['warnings'] = $warnings; } } else { $eventData['hasFailures'] = false; } $event->eventData = $eventData; $compressor = new ErrorModelCompressEvent(); $compressor->compress($event); WatcherService::getInstance()->publishEvent($event); $nerr = count($errors); \App::audit("Bulk update ({$nrows} sims in {$ntxs} requests with {$nerr} errors)", null); return $watcher->reload(); }
public function countSims($supervGroup) { $filterList = SimService::getInstance()->buildFilterList(array(SimFilterFields::SUPERVISION_GROUP => $supervGroup->getId())); $simList = SimService::getInstance()->listAll($filterList, array('count' => 1), null, \App::getOrgUserLogged()); return $simList->getCount(); }
/** * Builds a filter list based on params. * @param array $params * @return App_ListFilter | null */ public function buildFilterList(array $params) { $factory = new \App_ListFilter_FilterFactory(); $fields = UserFilterFields::getWhiteList(); if (!isset($params[UserFilterFields::ORGANIZATION_ID])) { $orgs = array(\App::getOrgUserLogged()->id); $orgService = OrgService::getInstance(); if ($childrenType = $orgService->getChildrenTypeByOrg(\App::getOrgUserLogged())) { $orgFilter = $orgService->buildFilterList(array('type' => $childrenType, OrgFilterFields::PARENT_ID => \App::getOrgUserLogged()->id)); $list = $orgService->listAll($childrenType, array('filterList' => $orgFilter, 'count' => 1000)); foreach ($list->getItems() as $item) { $orgs[] = $item->id; } } $params[UserFilterFields::ORGANIZATION_ID] = '[' . implode(',', $orgs) . ']'; } $factory->setWhiteList($fields); $sortingFields = UserSortingFields::getWhiteList(); $factory->setSortingWhiteList($sortingFields); $filterList = $factory->constructFilter($params); $filterList->addExtraData('filterType', 'user'); $filterList->setResourceId(UserFilterFields::getResourceId()); return $filterList->isValid() ? $filterList : null; }
/** * Builds a filter list based on params. * @param array $params * @return App_ListFilter | null */ public function buildFilterList(array $params) { if (!isset($params['type']) || !in_array($params['type'], array(OrgMasterModel::ORG_TYPE, OrgServiceProviderModel::ORG_TYPE, OrgCustomerModel::ORG_TYPE, OrgAggregatorModel::ORG_TYPE))) { return; } $orgType = $params['type']; unset($params['type']); if ($orgType === OrgServiceProviderModel::ORG_TYPE && \App::getOrgUserLogged()->getType() === OrgServiceProviderModel::ORG_TYPE) { if (!isset($params[ServiceProviderFilterFields::SERVICE_PROVIDER_ID_FOR_COMMERCIALS])) { $params[ServiceProviderFilterFields::SERVICE_PROVIDER_ID_FOR_COMMERCIALS] = \App::getOrgUserLogged()->id; } } $factory = new \App_ListFilter_FilterFactory(); $filterFieldsMap = array(OrgMasterModel::ORG_TYPE => '\\Application\\Model\\Filter\\Organization\\MasterFilterFields', OrgServiceProviderModel::ORG_TYPE => '\\Application\\Model\\Filter\\Organization\\ServiceProviderFilterFields', OrgCustomerModel::ORG_TYPE => '\\Application\\Model\\Filter\\Organization\\CustomerFilterFields', OrgAggregatorModel::ORG_TYPE => '\\Application\\Model\\Filter\\Organization\\AggregatorFilterFields'); $filterFieldsValidatorsMap = array(OrgMasterModel::ORG_TYPE => MasterFilterFields::getValidatorSpec(), OrgServiceProviderModel::ORG_TYPE => ServiceProviderFilterFields::getValidatorSpec(), OrgCustomerModel::ORG_TYPE => CustomerFilterFields::getValidatorSpec(), OrgAggregatorModel::ORG_TYPE => AggregatorFilterFields::getValidatorSpec()); if (isset($filterFieldsMap[$orgType])) { $class = $filterFieldsMap[$orgType]; $factory->setWhiteList($class::getWhiteList()); } $filterList = $factory->constructFilter($params); if (isset($class)) { $filterList->setResourceId($class::getResourceId()); } \App::log()->debug('Unused filters [' . implode(',', $factory->getUnusedList()) . ']'); $filterList->setValidators($filterFieldsValidatorsMap[$orgType]); return $filterList->isValid() ? $filterList : null; }