/**
  * @param bool $isMultiselect
  * @return array
  */
 public function toOptionArray($isMultiselect = false)
 {
     if (!$this->_options) {
         $countriesArray = $this->_countryCollectionFactory->create()->load()->toOptionArray(false);
         $this->_countries = [];
         foreach ($countriesArray as $a) {
             $this->_countries[$a['value']] = $a['label'];
         }
         $countryRegions = [];
         $regionsCollection = $this->_regionCollectionFactory->create()->load();
         foreach ($regionsCollection as $region) {
             $countryRegions[$region->getCountryId()][$region->getId()] = $region->getDefaultName();
         }
         uksort($countryRegions, [$this, 'sortRegionCountries']);
         $this->_options = [];
         foreach ($countryRegions as $countryId => $regions) {
             $regionOptions = [];
             foreach ($regions as $regionId => $regionName) {
                 $regionOptions[] = ['label' => $regionName, 'value' => $regionId];
             }
             $this->_options[] = ['label' => $this->_countries[$countryId], 'value' => $regionOptions];
         }
     }
     $options = $this->_options;
     if (!$isMultiselect) {
         array_unshift($options, ['value' => '', 'label' => '']);
     }
     return $options;
 }
Beispiel #2
0
 public function testGetRegionJson()
 {
     $countries = [new \Magento\Framework\DataObject(['country_id' => 'Country1']), new \Magento\Framework\DataObject(['country_id' => 'Country2'])];
     $countryIterator = new \ArrayIterator($countries);
     $this->_countryCollection->expects($this->atLeastOnce())->method('getIterator')->will($this->returnValue($countryIterator));
     $regions = [new \Magento\Framework\DataObject(['country_id' => 'Country1', 'region_id' => 'r1', 'code' => 'r1-code', 'name' => 'r1-name']), new \Magento\Framework\DataObject(['country_id' => 'Country1', 'region_id' => 'r2', 'code' => 'r2-code', 'name' => 'r2-name']), new \Magento\Framework\DataObject(['country_id' => 'Country2', 'region_id' => 'r3', 'code' => 'r3-code', 'name' => 'r3-name'])];
     $regionIterator = new \ArrayIterator($regions);
     $this->_regionCollection->expects($this->once())->method('addCountryFilter')->with(['Country1', 'Country2'])->will($this->returnSelf());
     $this->_regionCollection->expects($this->once())->method('load');
     $this->_regionCollection->expects($this->once())->method('getIterator')->will($this->returnValue($regionIterator));
     $expectedDataToEncode = ['config' => ['show_all_regions' => false, 'regions_required' => []], 'Country1' => ['r1' => ['code' => 'r1-code', 'name' => 'r1-name'], 'r2' => ['code' => 'r2-code', 'name' => 'r2-name']], 'Country2' => ['r3' => ['code' => 'r3-code', 'name' => 'r3-name']]];
     $this->jsonHelperMock->expects($this->once())->method('jsonEncode')->with(new \PHPUnit_Framework_Constraint_IsIdentical($expectedDataToEncode))->will($this->returnValue('encoded_json'));
     // Test
     $result = $this->_object->getRegionJson();
     $this->assertEquals('encoded_json', $result);
 }
 /**
  * @return RegionCollection
  * @removeCandidate
  */
 public function getRegionCollection()
 {
     if (!$this->_regionCollection) {
         $this->_regionCollection = $this->_regionCollectionFactory->create()->addCountryFilter($this->getAddress()->getCountryId())->load();
     }
     return $this->_regionCollection;
 }
Beispiel #4
0
 /**
  * Return list of country's regions as array
  *
  * @param bool $noEmpty
  * @param string|array|null $country
  * @return array
  */
 public function toOptionArray($noEmpty = false, $country = null)
 {
     /** @var $region \Magento\Directory\Model\ResourceModel\Region\Collection */
     $regionCollection = $this->_regionsFactory->create();
     $options = $regionCollection->addCountryFilter($country)->toOptionArray();
     if ($noEmpty) {
         unset($options[0]);
     } else {
         if ($options) {
             $options[0] = ['value' => '0', 'label' => '*'];
         } else {
             $options = [['value' => '0', 'label' => '*']];
         }
     }
     return $options;
 }
 /**
  * Returns region code by name
  *
  * @param string $region
  * @param string $countryId
  * @return string
  */
 public function getRegionIdByName($region, $countryId)
 {
     $collection = $this->regionCollectionFactory->create()->addRegionCodeOrNameFilter($region)->addCountryFilter($countryId);
     if ($collection->getSize()) {
         return $collection->getFirstItem()->getId();
     }
     return '';
 }
Beispiel #6
0
 /**
  * Load directory regions
  *
  * @return array
  */
 protected function loadDirectoryRegions()
 {
     $importRegions = [];
     /** @var $collection \Magento\Directory\Model\ResourceModel\Region\Collection */
     $collection = $this->regionCollectionFactory->create();
     foreach ($collection->getData() as $row) {
         $importRegions[$row['country_id']][$row['code']] = (int) $row['region_id'];
     }
     return $importRegions;
 }
 public function testGetRegionIdByName()
 {
     $regionCode = 'TX';
     $countryId = 'US';
     $regionId = 57;
     $regionCollectionMock = $this->getMockBuilder('\\Magento\\Directory\\Model\\ResourceModel\\Region\\Collection')->disableOriginalConstructor()->getMock();
     $this->regionCollectionFactoryMock->expects($this->once())->method('create')->willReturn($regionCollectionMock);
     $regionCollectionMock->expects($this->once())->method('addRegionCodeOrNameFilter')->with($regionCode)->willReturnSelf();
     $regionCollectionMock->expects($this->once())->method('addCountryFilter')->with($countryId)->willReturnSelf();
     $regionCollectionMock->expects($this->once())->method('getSize')->willReturn(1);
     $regionCollectionMock->expects($this->once())->method('getFirstItem')->willReturn(new \Magento\Framework\DataObject(['id' => $regionId]));
     $this->assertEquals($regionId, $this->block->getRegionIdByName($regionCode, $countryId));
 }
Beispiel #8
0
 /**
  * Retrieve regions data
  *
  * @return array
  */
 public function getRegionData()
 {
     $countryIds = [];
     foreach ($this->getCountryCollection() as $country) {
         $countryIds[] = $country->getCountryId();
     }
     $collection = $this->_regCollectionFactory->create();
     $collection->addCountryFilter($countryIds)->load();
     $regions = ['config' => ['show_all_regions' => $this->isShowNonRequiredState(), 'regions_required' => $this->getCountriesWithStatesRequired()]];
     foreach ($collection as $region) {
         /** @var $region \Magento\Directory\Model\Region */
         if (!$region->getRegionId()) {
             continue;
         }
         $regions[$region->getCountryId()][$region->getRegionId()] = ['code' => $region->getCode(), 'name' => (string) __($region->getName())];
     }
     return $regions;
 }
Beispiel #9
0
 /**
  * @return string
  */
 public function getRegionsJs()
 {
     \Magento\Framework\Profiler::start('TEST: ' . __METHOD__, ['group' => 'TEST', 'method' => __METHOD__]);
     $regionsJs = $this->getData('regions_js');
     if (!$regionsJs) {
         $countryIds = [];
         foreach ($this->getCountryCollection() as $country) {
             $countryIds[] = $country->getCountryId();
         }
         $collection = $this->_regionCollectionFactory->create()->addCountryFilter($countryIds)->load();
         $regions = [];
         foreach ($collection as $region) {
             if (!$region->getRegionId()) {
                 continue;
             }
             $regions[$region->getCountryId()][$region->getRegionId()] = ['code' => $region->getCode(), 'name' => $region->getName()];
         }
         $regionsJs = $this->_jsonEncoder->encode($regions);
     }
     \Magento\Framework\Profiler::stop('TEST: ' . __METHOD__);
     return $regionsJs;
 }
Beispiel #10
0
 /**
  * @return \Magento\Directory\Model\ResourceModel\Region\Collection
  */
 public function getRegionCollection()
 {
     $collection = $this->_regionCollectionFactory->create();
     $collection->addCountryFilter($this->getId());
     return $collection;
 }
Beispiel #11
0
 /**
  * @return \Magento\Directory\Model\ResourceModel\Region\Collection
  */
 protected function _createRegionsCollection()
 {
     return $this->_regionsFactory->create();
 }
 /**
  * Address constructor.
  * @param Config $config
  * @param MetaDataObjectFactory $metaDataObjectFactory
  * @param AddressFactory $addressFactory
  * @param AddressServiceSoapFactory $addressServiceSoapFactory
  * @param RegionCollectionFactory $regionCollectionFactory
  * @param CustomerAddressInterfaceFactory $customerAddressFactory
  * @param QuoteAddressInterfaceFactory $quoteAddressFactory
  * @param OrderAddressInterfaceFactory $orderAddressFactory
  * @param DataObjectHelper $dataObjectHelper
  * @param \ClassyLlama\AvaTax\Model\Logger\AvaTaxLogger $avaTaxLogger
  */
 public function __construct(Config $config, MetaDataObjectFactory $metaDataObjectFactory, AddressFactory $addressFactory, AddressServiceSoapFactory $addressServiceSoapFactory, RegionCollectionFactory $regionCollectionFactory, CustomerAddressInterfaceFactory $customerAddressFactory, QuoteAddressInterfaceFactory $quoteAddressFactory, OrderAddressInterfaceFactory $orderAddressFactory, DataObjectHelper $dataObjectHelper, \ClassyLlama\AvaTax\Model\Logger\AvaTaxLogger $avaTaxLogger)
 {
     $this->config = $config;
     $this->metaDataObject = $metaDataObjectFactory->create(['metaDataProperties' => $this::$validFields]);
     $this->addressFactory = $addressFactory;
     $this->addressServiceSoapFactory = $addressServiceSoapFactory;
     $this->regionCollection = $regionCollectionFactory->create();
     $this->customerAddressFactory = $customerAddressFactory;
     $this->quoteAddressFactory = $quoteAddressFactory;
     $this->orderAddressFactory = $orderAddressFactory;
     $this->dataObjectHelper = $dataObjectHelper;
     $this->avaTaxLogger = $avaTaxLogger;
 }
Beispiel #13
0
 /**
  * @param \Magento\Framework\Stdlib\StringUtils $string
  * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
  * @param \Magento\ImportExport\Model\ImportFactory $importFactory
  * @param \Magento\ImportExport\Model\ResourceModel\Helper $resourceHelper
  * @param \Magento\Framework\App\ResourceConnection $resource
  * @param ProcessingErrorAggregatorInterface $errorAggregator
  * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  * @param \Magento\ImportExport\Model\Export\Factory $collectionFactory
  * @param \Magento\Eav\Model\Config $eavConfig
  * @param \Magento\CustomerImportExport\Model\ResourceModel\Import\Customer\StorageFactory $storageFactory
  * @param \Magento\Customer\Model\AddressFactory $addressFactory
  * @param \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionColFactory
  * @param \Magento\Customer\Model\CustomerFactory $customerFactory
  * @param \Magento\Customer\Model\ResourceModel\Address\CollectionFactory $addressColFactory
  * @param \Magento\Customer\Model\ResourceModel\Address\Attribute\CollectionFactory $attributesFactory
  * @param \Magento\Framework\Stdlib\DateTime $dateTime
  * @param array $data
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  */
 public function __construct(\Magento\Framework\Stdlib\StringUtils $string, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\ImportExport\Model\ImportFactory $importFactory, \Magento\ImportExport\Model\ResourceModel\Helper $resourceHelper, \Magento\Framework\App\ResourceConnection $resource, ProcessingErrorAggregatorInterface $errorAggregator, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\ImportExport\Model\Export\Factory $collectionFactory, \Magento\Eav\Model\Config $eavConfig, \Magento\CustomerImportExport\Model\ResourceModel\Import\Customer\StorageFactory $storageFactory, \Magento\Customer\Model\AddressFactory $addressFactory, \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionColFactory, \Magento\Customer\Model\CustomerFactory $customerFactory, \Magento\Customer\Model\ResourceModel\Address\CollectionFactory $addressColFactory, \Magento\Customer\Model\ResourceModel\Address\Attribute\CollectionFactory $attributesFactory, \Magento\Framework\Stdlib\DateTime $dateTime, array $data = [])
 {
     $this->_customerFactory = $customerFactory;
     $this->_addressFactory = $addressFactory;
     $this->_eavConfig = $eavConfig;
     $this->_resourceHelper = $resourceHelper;
     $this->dateTime = $dateTime;
     if (!isset($data['attribute_collection'])) {
         /** @var $attributeCollection \Magento\Customer\Model\ResourceModel\Address\Attribute\Collection */
         $attributeCollection = $attributesFactory->create();
         $attributeCollection->addSystemHiddenFilter()->addExcludeHiddenFrontendFilter();
         $data['attribute_collection'] = $attributeCollection;
     }
     parent::__construct($string, $scopeConfig, $importFactory, $resourceHelper, $resource, $errorAggregator, $storeManager, $collectionFactory, $eavConfig, $storageFactory, $data);
     $this->_addressCollection = isset($data['address_collection']) ? $data['address_collection'] : $addressColFactory->create();
     $this->_entityTable = isset($data['entity_table']) ? $data['entity_table'] : $addressFactory->create()->getResource()->getEntityTable();
     $this->_regionCollection = isset($data['region_collection']) ? $data['region_collection'] : $regionColFactory->create();
     $this->addMessageTemplate(self::ERROR_ADDRESS_ID_IS_EMPTY, __('Customer address id column is not specified'));
     $this->addMessageTemplate(self::ERROR_ADDRESS_NOT_FOUND, __('We can\'t find that customer address.'));
     $this->addMessageTemplate(self::ERROR_INVALID_REGION, __('Please enter a valid region.'));
     $this->addMessageTemplate(self::ERROR_DUPLICATE_PK, __('We found another row with this email, website and address ID combination.'));
     $this->_initAttributes();
     $this->_initAddresses()->_initCountryRegions();
 }
Beispiel #14
0
 public function uploadAndImport(\Magento\Framework\DataObject $object)
 {
     $csvFile = $_FILES["groups"]["tmp_name"]["matrixrate"]["fields"]["import"]["value"];
     if (!empty($csvFile)) {
         $csv = trim(file_get_contents($csvFile));
         $table = $this->getMainTable();
         $websiteModel = $this->_storeManager->getWebsite($object->getScopeId());
         $websiteId = (int) $websiteModel->getId();
         $this->_importWebsiteId = (int) $websiteModel->getId();
         $this->_importUniqueHash = [];
         $this->_importErrors = [];
         $this->_importedRows = 0;
         /*
          getting condition name from post instead of the following commented logic
         */
         if ($object->getData('groups/matrixrate/fields/condition_name/inherit') == '1') {
             $conditionName = (string) $this->_coreConfig->getValue('carriers/matrixrate/condition_name', 'default');
         } else {
             $conditionName = $object->getData('groups/matrixrate/fields/condition_name/value');
         }
         $conditionFullName = $this->_getConditionFullName($conditionName);
         if (!empty($csv)) {
             $exceptions = array();
             $csvLines = explode("\n", $csv);
             $csvLine = array_shift($csvLines);
             $csvLine = $this->_getCsvValues($csvLine);
             if (count($csvLine) < 7) {
                 $exceptions[0] = __('Invalid Matrix Rates File Format');
             }
             $countryCodes = array();
             $regionCodes = array();
             foreach ($csvLines as $k => $csvLine) {
                 $csvLine = $this->_getCsvValues($csvLine);
                 if (count($csvLine) > 0 && count($csvLine) < 7) {
                     $exceptions[0] = __('Invalid Matrix Rates File Format');
                 } else {
                     $countryCodes[] = $csvLine[0];
                     $regionCodes[] = $csvLine[1];
                 }
             }
             if (empty($exceptions)) {
                 $data = array();
                 $countryCodesToIds = array();
                 $regionCodesToIds = array();
                 $countryCodesIso2 = array();
                 /** @var $collection \Magento\Directory\Model\ResourceModel\Country\Collection */
                 $collection = $this->_countryCollectionFactory->create();
                 $collection->addCountryCodeFilter($countryCodes);
                 foreach ($collection->getData() as $row) {
                     $countryCodesToIds[$row['iso2_code']] = $row['country_id'];
                     $countryCodesToIds[$row['iso3_code']] = $row['country_id'];
                     $countryCodesIso2[] = $row['iso2_code'];
                 }
                 /** @var $collection \Magento\Directory\Model\ResourceModel\Region\Collection */
                 $collection = $this->_regionCollectionFactory->create()->addRegionCodeFilter($regionCodes)->addCountryFilter($countryCodesIso2);
                 foreach ($collection->getData() as $row) {
                     $regionCodesToIds[$row['country_id']][$row['code']] = (int) $row['region_id'];
                 }
                 foreach ($csvLines as $k => $csvLine) {
                     $csvLine = $this->_getCsvValues($csvLine);
                     if (empty($countryCodesToIds) || !array_key_exists($csvLine[0], $countryCodesToIds)) {
                         $countryId = '0';
                         if ($csvLine[0] != '*' && $csvLine[0] != '') {
                             $exceptions[] = __('Invalid Country "%s" in the Row #%s', $csvLine[0], $k + 1);
                         }
                     } else {
                         $countryId = $countryCodesToIds[$csvLine[0]];
                     }
                     if (!isset($countryCodesToIds[$csvLine[0]]) || !isset($regionCodesToIds[$countryCodesToIds[$csvLine[0]]]) || !array_key_exists($csvLine[1], $regionCodesToIds[$countryCodesToIds[$csvLine[0]]])) {
                         $regionId = '0';
                         if ($csvLine[1] != '*' && $csvLine[1] != '') {
                             $exceptions[] = __('Invalid Region/State "%s" in the Row #%s', $csvLine[1], $k + 1);
                         }
                     } else {
                         $regionId = $regionCodesToIds[$countryCodesToIds[$csvLine[0]]][$csvLine[1]];
                     }
                     if (count($csvLine) == 9) {
                         // we are searching for postcodes in ranges & including cities
                         if ($csvLine[2] == '*' || $csvLine[2] == '') {
                             $city = '';
                         } else {
                             $city = $csvLine[2];
                         }
                         if ($csvLine[3] == '*' || $csvLine[3] == '') {
                             $zip = '';
                         } else {
                             $zip = $csvLine[3];
                         }
                         if ($csvLine[4] == '*' || $csvLine[4] == '') {
                             $zip_to = '';
                         } else {
                             $zip_to = $csvLine[4];
                         }
                         if (!$this->_isPositiveDecimalNumber($csvLine[5]) || $csvLine[5] == '*' || $csvLine[5] == '') {
                             $exceptions[] = __('Invalid %s From "%s" in the Row #%s', $conditionFullName, $csvLine[5], $k + 1);
                         } else {
                             $csvLine[5] = (double) $csvLine[5];
                         }
                         if (!$this->_isPositiveDecimalNumber($csvLine[6])) {
                             $exceptions[] = __('Invalid %s To "%s" in the Row #%s', $conditionFullName, $csvLine[6], $k + 1);
                         } else {
                             $csvLine[6] = (double) $csvLine[6];
                         }
                         $data[] = array('website_id' => $websiteId, 'dest_country_id' => $countryId, 'dest_region_id' => $regionId, 'dest_city' => $city, 'dest_zip' => $zip, 'dest_zip_to' => $zip_to, 'condition_name' => $conditionName, 'condition_from_value' => $csvLine[5], 'condition_to_value' => $csvLine[6], 'price' => $csvLine[7], 'cost' => 0, 'delivery_type' => $csvLine[8]);
                     } else {
                         if ($csvLine[2] == '*' || $csvLine[2] == '') {
                             $zip = '';
                         } else {
                             $zip = $csvLine[2] . "%";
                         }
                         $city = '';
                         $zip_to = '';
                         if (!$this->_isPositiveDecimalNumber($csvLine[3]) || $csvLine[3] == '*' || $csvLine[3] == '') {
                             $exceptions[] = __('Invalid %s From "%s" in the Row #%s', $conditionFullName, $csvLine[3], $k + 1);
                         } else {
                             $csvLine[3] = (double) $csvLine[3];
                         }
                         if (!$this->_isPositiveDecimalNumber($csvLine[4])) {
                             $exceptions[] = __('Invalid %s To "%s" in the Row #%s', $conditionFullName, $csvLine[4], $k + 1);
                         } else {
                             $csvLine[4] = (double) $csvLine[4];
                         }
                         $data[] = array('website_id' => $websiteId, 'dest_country_id' => $countryId, 'dest_region_id' => $regionId, 'dest_city' => $city, 'dest_zip' => $zip, 'dest_zip_to' => $zip_to, 'condition_name' => $conditionName, 'condition_from_value' => $csvLine[3], 'condition_to_value' => $csvLine[4], 'price' => $csvLine[5], 'cost' => 0, 'delivery_type' => $csvLine[6]);
                     }
                     $dataDetails[] = array('country' => $csvLine[0], 'region' => $csvLine[1]);
                 }
             }
             if (empty($exceptions)) {
                 $connection = $this->getConnection();
                 $condition = array($connection->quoteInto('website_id = ?', $websiteId), $connection->quoteInto('condition_name = ?', $conditionName));
                 $connection->delete($table, $condition);
                 //foreach ($data as $k => $dataLine) {
                 try {
                     foreach ($data as $v) {
                         $data2[] = array_values($v);
                     }
                     $this->_saveImportData($data2);
                 } catch (\Exception $e) {
                     //$connection->rollback();
                     $this->_logger->critical($e);
                     $exceptions[] = __($e->__toString());
                     //__('Duplicate Row #%s (Country "%s", Region/State "%s", City "%s", Zip From "%s", Zip To "%s", Delivery Type "%s", Value From "%s" and Value To "%s")', ($k + 1), $dataDetails[$k]['country'], $dataDetails[$k]['region'], $dataLine['dest_city'], $dataLine['dest_zip'], $dataLine['dest_zip_to'], $dataLine['delivery_type'], $dataLine['condition_from_value'], $dataLine['condition_to_value']);
                 }
                 //}
             }
             if (!empty($exceptions)) {
                 throw new \Magento\Framework\Exception\LocalizedException(__(implode("\n", $exceptions)));
             }
         }
     }
 }