/**
  * Get a region model with at least a region id, region code and region name.
  *
  * @param int|null
  * @param string|null
  * @param string|null
  * @param string|null
  * @return \Magento\Directory\Model\Region|null
  */
 public function loadRegion($regionId = null, $regionCode = null, $regionName = null, $countryId = null)
 {
     // If all of the necessary data is already available, create and return
     // a new model with the provided data.
     if ($regionId && $regionCode && $regionName) {
         return $this->regionFactory->create(['data' => ['id' => $regionId, 'code' => $regionCode, 'name' => $regionName, 'country_id' => $countryId]]);
     }
     // Cannot load a region if there is not enough data to use to find it.
     // Need either a region id or a region code and country id or
     // region name and country id.
     if (!$this->canRegionBeLoaded($regionId, $regionCode, $regionName, $countryId)) {
         return null;
     }
     $region = $this->regionFactory->create();
     // Load the region by whatever data is available. Assume these to be
     // in order of most to least performant but
     if ($regionId) {
         $region->load($regionId);
     } elseif ($regionCode) {
         $region->loadByCode($regionCode, $countryId);
     } elseif ($regionName) {
         $region->loadByName($regionName, $countryId);
     }
     return $region;
 }
 /**
  * Retrieve generic object with all the misc store information values
  *
  * @param Store $store
  * @return DataObject
  */
 public function getStoreInformationObject(Store $store)
 {
     $info = new DataObject(['name' => $store->getConfig(self::XML_PATH_STORE_INFO_NAME), 'phone' => $store->getConfig(self::XML_PATH_STORE_INFO_PHONE), 'hours' => $store->getConfig(self::XML_PATH_STORE_INFO_HOURS), 'street_line1' => $store->getConfig(self::XML_PATH_STORE_INFO_STREET_LINE1), 'street_line2' => $store->getConfig(self::XML_PATH_STORE_INFO_STREET_LINE2), 'city' => $store->getConfig(self::XML_PATH_STORE_INFO_CITY), 'postcode' => $store->getConfig(self::XML_PATH_STORE_INFO_POSTCODE), 'region_id' => $store->getConfig(self::XML_PATH_STORE_INFO_REGION_CODE), 'country_id' => $store->getConfig(self::XML_PATH_STORE_INFO_COUNTRY_CODE), 'vat_number' => $store->getConfig(self::XML_PATH_STORE_INFO_VAT_NUMBER)]);
     if ($info->getRegionId()) {
         $info->setRegion($this->regionFactory->create()->load($info->getRegionId())->getName());
     }
     if ($info->getCountryId()) {
         $info->setCountry($this->countryFactory->create()->loadByCode($info->getCountryId())->getName());
     }
     return $info;
 }
Beispiel #3
0
 /**
  * Set region to the attribute
  *
  * @param \Magento\Framework\DataObject $object
  * @return $this
  */
 public function beforeSave($object)
 {
     if (is_numeric($object->getRegion())) {
         $region = $this->_regionFactory->create()->load((int) $object->getRegion());
         if ($region) {
             $object->setRegionId($region->getId());
             $object->setRegion($region->getCode());
         }
     }
     return $this;
 }
 /**
  * Create an address region for the region provided by name.
  *
  * @param string
  * @return CustomerRegion
  */
 protected function loadRegionByName($regionName, $countryId)
 {
     $directoryRegion = $this->directoryRegionFactory->create()->loadByName($regionName, $countryId);
     $customerRegion = $this->customerRegionFactory->create();
     $customerRegion->setRegionCode($directoryRegion->getCode())->setRegion($directoryRegion->getName())->setRegionID($directoryRegion->getRegionId());
     return $customerRegion;
 }
Beispiel #5
0
 /**
  * Get regions by region ID
  *
  * @param int $regionId
  * @param string $postalCode
  * @return String[]
  */
 private function _getRegionsByRegionId($regionId, $postalCode)
 {
     $regions = [];
     $regionCode = $this->_regionFactory->create()->load($regionId)->getCode();
     if ($regionCode !== null) {
         $regions = Zip::parseRegions($regionCode, $postalCode);
     }
     return $regions;
 }
 /**
  * Update region data
  *
  * @param array $attributeValues
  * @return void
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 protected function updateRegionData(&$attributeValues)
 {
     if (!empty($attributeValues['region_id'])) {
         $newRegion = $this->regionFactory->create()->load($attributeValues['region_id']);
         $attributeValues['region_code'] = $newRegion->getCode();
         $attributeValues['region'] = $newRegion->getDefaultName();
     }
     $regionData = [RegionInterface::REGION_ID => !empty($attributeValues['region_id']) ? $attributeValues['region_id'] : null, RegionInterface::REGION => !empty($attributeValues['region']) ? $attributeValues['region'] : null, RegionInterface::REGION_CODE => !empty($attributeValues['region_code']) ? $attributeValues['region_code'] : null];
     $region = $this->regionDataFactory->create();
     $this->dataObjectHelper->populateWithArray($region, $regionData, '\\Magento\\Customer\\Api\\Data\\RegionInterface');
     $attributeValues['region'] = $region;
 }
 /**
  * Return 2 letter state code if available, otherwise full region name
  *
  * @return null|string
  */
 public function getRegionCode()
 {
     if (is_string($this->getRegion())) {
         return $this->getRegion();
     }
     $model = $this->regionFactory->create()->load(!$this->getRegionId() && is_numeric($this->getRegion()) ? $this->getRegion() : $this->getRegionId());
     if ($model->getCountryId() == $this->getCountryId()) {
         return $model->getCode();
     } else {
         return null;
     }
 }
Beispiel #8
0
 /**
  * Prepare location settings and tax postcode before save rate
  *
  * @return \Magento\Tax\Model\Calculation\Rate
  * @throws \Magento\Framework\Exception\LocalizedException
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function beforeSave()
 {
     $isWrongRange = $this->getZipIsRange() && ($this->getZipFrom() === '' || $this->getZipTo() === '');
     $isEmptyValues = $this->getCode() === '' || $this->getTaxCountryId() === '' || $this->getRate() === '' || $this->getTaxPostcode() === '' && !$this->getZipIsRange();
     if ($isEmptyValues || $isWrongRange) {
         throw new \Magento\Framework\Exception\LocalizedException(__('Make sure all required information is valid.'));
     }
     if (!is_numeric($this->getRate()) || $this->getRate() < 0) {
         throw new \Magento\Framework\Exception\LocalizedException(__('The Rate Percent should be a positive number.'));
     }
     if ($this->getZipIsRange()) {
         $zipFrom = $this->getZipFrom();
         $zipTo = $this->getZipTo();
         if (strlen($zipFrom) > 9 || strlen($zipTo) > 9) {
             throw new \Magento\Framework\Exception\LocalizedException(__('Maximum zip code length is 9.'));
         }
         if (!is_numeric($zipFrom) || !is_numeric($zipTo) || $zipFrom < 0 || $zipTo < 0) {
             throw new \Magento\Framework\Exception\LocalizedException(__('Use digits only for the zip code.'));
         }
         if ($zipFrom > $zipTo) {
             throw new \Magento\Framework\Exception\LocalizedException(__('Range To should be equal or greater than Range From.'));
         }
         $this->setTaxPostcode($zipFrom . '-' . $zipTo);
     } else {
         $taxPostCode = $this->getTaxPostcode();
         if (strlen($taxPostCode) > 10) {
             $taxPostCode = substr($taxPostCode, 0, 10);
         }
         $this->setTaxPostcode($taxPostCode)->setZipIsRange(null)->setZipFrom(null)->setZipTo(null);
     }
     parent::beforeSave();
     $country = $this->getTaxCountryId();
     $region = $this->getTaxRegionId();
     /** @var $regionModel \Magento\Directory\Model\Region */
     $regionModel = $this->_regionFactory->create();
     $regionModel->load($region);
     if ($regionModel->getCountryId() != $country) {
         $this->setTaxRegionId('*');
     }
     return $this;
 }
Beispiel #9
0
 /**
  * Prepare location settings and tax postcode before save rate
  *
  * @return \Magento\Tax\Model\Calculation\Rate
  * @throws \Magento\Framework\Model\Exception
  */
 protected function _beforeSave()
 {
     $isWrongRange = $this->getZipIsRange() && ($this->getZipFrom() === '' || $this->getZipTo() === '');
     $isEmptyValues = $this->getCode() === '' || $this->getTaxCountryId() === '' || $this->getRate() === '' || $this->getTaxPostcode() === '' && !$this->getZipIsRange();
     if ($isEmptyValues || $isWrongRange) {
         throw new \Magento\Framework\Model\Exception(__('Please fill all required fields with valid information.'));
     }
     if (!is_numeric($this->getRate()) || $this->getRate() < 0) {
         throw new \Magento\Framework\Model\Exception(__('Rate Percent should be a positive number.'));
     }
     if ($this->getZipIsRange()) {
         $zipFrom = $this->getZipFrom();
         $zipTo = $this->getZipTo();
         if (strlen($zipFrom) > 9 || strlen($zipTo) > 9) {
             throw new \Magento\Framework\Model\Exception(__('Maximum zip code length is 9.'));
         }
         if (!is_numeric($zipFrom) || !is_numeric($zipTo) || $zipFrom < 0 || $zipTo < 0) {
             throw new \Magento\Framework\Model\Exception(__('Zip code should not contain characters other than digits.'));
         }
         if ($zipFrom > $zipTo) {
             throw new \Magento\Framework\Model\Exception(__('Range To should be equal or greater than Range From.'));
         }
         $this->setTaxPostcode($zipFrom . '-' . $zipTo);
     } else {
         $taxPostCode = $this->getTaxPostcode();
         if (strlen($taxPostCode) > 10) {
             $taxPostCode = substr($taxPostCode, 0, 10);
         }
         $this->setTaxPostcode($taxPostCode)->setZipIsRange(null)->setZipFrom(null)->setZipTo(null);
     }
     parent::_beforeSave();
     $country = $this->getTaxCountryId();
     $region = $this->getTaxRegionId();
     /** @var $regionModel \Magento\Directory\Model\Region */
     $regionModel = $this->_regionFactory->create();
     $regionModel->load($region);
     if ($regionModel->getCountryId() != $country) {
         $this->setTaxRegionId('*');
     }
     return $this;
 }
Beispiel #10
0
 /**
  * Validate tax rate
  *
  * @param TaxRateDataObject $taxRate
  * @throws InputException
  * @return void
  *
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 private function validate(TaxRateDataObject $taxRate)
 {
     $exception = new InputException();
     $countryCode = $taxRate->getCountryId();
     if (!\Zend_Validate::is($countryCode, 'NotEmpty')) {
         $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'country_id']);
     } else {
         if (!\Zend_Validate::is($this->countryFactory->create()->loadByCode($countryCode)->getId(), 'NotEmpty')) {
             $exception->addError(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'country_id', 'value' => $countryCode]);
         }
     }
     $regionCode = $taxRate->getRegionId();
     if (\Zend_Validate::is($regionCode, 'NotEmpty') && !\Zend_Validate::is($this->regionFactory->create()->load($regionCode)->getId(), 'NotEmpty')) {
         $exception->addError(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'region_id', 'value' => $regionCode]);
     }
     if (!\Zend_Validate::is($taxRate->getPercentageRate(), 'NotEmpty')) {
         $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'percentage_rate']);
     }
     if (!\Zend_Validate::is(trim($taxRate->getCode()), 'NotEmpty')) {
         $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'code']);
     }
     if ($taxRate->getZipRange()) {
         $zipRangeFromTo = ['zip_from' => $taxRate->getZipRange()->getFrom(), 'zip_to' => $taxRate->getZipRange()->getTo()];
         foreach ($zipRangeFromTo as $key => $value) {
             if (!is_numeric($value) || $value < 0) {
                 $exception->addError(InputException::INVALID_FIELD_VALUE, ['fieldName' => $key, 'value' => $value]);
             }
         }
         if ($zipRangeFromTo['zip_from'] > $zipRangeFromTo['zip_to']) {
             $exception->addError('Range To should be equal or greater than Range From.');
         }
     } else {
         if (!\Zend_Validate::is(trim($taxRate->getPostcode()), 'NotEmpty')) {
             $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'postcode']);
         }
     }
     if ($exception->wasErrorAdded()) {
         throw $exception;
     }
 }
Beispiel #11
0
 /**
  * Validate tax rate
  *
  * @param \Magento\Tax\Api\Data\TaxRateInterface $taxRate
  * @throws InputException
  * @return void
  *
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 private function validate(\Magento\Tax\Api\Data\TaxRateInterface $taxRate)
 {
     $exception = new InputException();
     $countryCode = $taxRate->getTaxCountryId();
     if (!\Zend_Validate::is($countryCode, 'NotEmpty')) {
         $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'country_id']));
     } elseif (!\Zend_Validate::is($this->countryFactory->create()->loadByCode($countryCode)->getId(), 'NotEmpty')) {
         $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'country_id', 'value' => $countryCode]));
     }
     $regionCode = $taxRate->getTaxRegionId();
     // if regionCode eq 0 (all regions *), do not validate with existing region list
     if (\Zend_Validate::is($regionCode, 'NotEmpty') && $regionCode != "0" && !\Zend_Validate::is($this->regionFactory->create()->load($regionCode)->getId(), 'NotEmpty')) {
         $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'region_id', 'value' => $regionCode]));
     }
     if (!\Zend_Validate::is($taxRate->getRate(), 'NotEmpty')) {
         $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'percentage_rate']));
     }
     if (!\Zend_Validate::is(trim($taxRate->getCode()), 'NotEmpty')) {
         $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'code']));
     }
     if ($taxRate->getZipIsRange()) {
         $zipRangeFromTo = ['zip_from' => $taxRate->getZipFrom(), 'zip_to' => $taxRate->getZipTo()];
         foreach ($zipRangeFromTo as $key => $value) {
             if (!is_numeric($value) || $value < 0) {
                 $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => $key, 'value' => $value]));
             }
         }
         if ($zipRangeFromTo['zip_from'] > $zipRangeFromTo['zip_to']) {
             $exception->addError(__('Range To should be equal or greater than Range From.'));
         }
     } else {
         if (!\Zend_Validate::is(trim($taxRate->getTaxPostcode()), 'NotEmpty')) {
             $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'postcode']));
         }
     }
     if ($exception->wasErrorAdded()) {
         throw $exception;
     }
 }
Beispiel #12
0
 /**
  * @return \Magento\Directory\Model\Region
  */
 protected function _createRegionInstance()
 {
     return $this->_regionFactory->create();
 }
Beispiel #13
0
 /**
  * region_id workaround: PayPal requires state code, try to find one in the address
  *
  * @param \Magento\Framework\Object $address
  * @return string
  */
 protected function _lookupRegionCodeFromAddress(\Magento\Framework\Object $address)
 {
     $regionId = $address->getData('region_id');
     if ($regionId) {
         $region = $this->_regionFactory->create()->load($regionId);
         if ($region->getId()) {
             return $region->getCode();
         }
     }
     return '';
 }
 /**
  * Returns two digit region code if possible
  *
  * @param string $region
  * @param int|string $regionId
  * @return string
  */
 protected function convertRegionToCode($region, $regionId)
 {
     if (is_string($region) && strlen($region) == 2) {
         return $region;
     } else {
         $regionObj = $this->regionFactory->create()->load($regionId);
         if ($regionObj->getId()) {
             return $regionObj->getCode();
         }
     }
     return $region;
 }
Beispiel #15
0
 /**
  * @return $this
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 protected function _prepareForm()
 {
     $taxRateId = $this->_coreRegistry->registry(RegistryConstants::CURRENT_TAX_RATE_ID);
     try {
         if ($taxRateId) {
             $taxRateDataObject = $this->_taxRateRepository->get($taxRateId);
         }
     } catch (NoSuchEntityException $e) {
         /* tax rate not found */
     }
     $sessionFormValues = (array) $this->_coreRegistry->registry(RegistryConstants::CURRENT_TAX_RATE_FORM_DATA);
     $formData = isset($taxRateDataObject) ? $this->extractTaxRateData($taxRateDataObject) : [];
     $formData = array_merge($formData, $sessionFormValues);
     if (isset($formData['zip_is_range']) && $formData['zip_is_range'] && !isset($formData['tax_postcode'])) {
         $formData['tax_postcode'] = $formData['zip_from'] . '-' . $formData['zip_to'];
     }
     /** @var \Magento\Framework\Data\Form $form */
     $form = $this->_formFactory->create();
     $countries = $this->_country->toOptionArray(false, 'US');
     unset($countries[0]);
     if (!isset($formData['tax_country_id'])) {
         $formData['tax_country_id'] = $this->_scopeConfig->getValue(\Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_COUNTRY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
     }
     if (!isset($formData['tax_region_id'])) {
         $formData['tax_region_id'] = $this->_scopeConfig->getValue(\Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_REGION, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
     }
     $regionCollection = $this->_regionFactory->create()->getCollection()->addCountryFilter($formData['tax_country_id']);
     $regions = $regionCollection->toOptionArray();
     if ($regions) {
         $regions[0]['label'] = '*';
     } else {
         $regions = [['value' => '', 'label' => '*']];
     }
     $legend = $this->getShowLegend() ? __('Tax Rate Information') : '';
     $fieldset = $form->addFieldset('base_fieldset', ['legend' => $legend, 'class' => 'form-inline']);
     if (isset($formData['tax_calculation_rate_id']) && $formData['tax_calculation_rate_id'] > 0) {
         $fieldset->addField('tax_calculation_rate_id', 'hidden', ['name' => 'tax_calculation_rate_id', 'value' => $formData['tax_calculation_rate_id']]);
     }
     $fieldset->addField('code', 'text', ['name' => 'code', 'label' => __('Tax Identifier'), 'title' => __('Tax Identifier'), 'class' => 'required-entry', 'required' => true]);
     $fieldset->addField('zip_is_range', 'checkbox', ['name' => 'zip_is_range', 'label' => __('Zip/Post is Range'), 'value' => '1']);
     if (!isset($formData['tax_postcode'])) {
         $formData['tax_postcode'] = $this->_scopeConfig->getValue(\Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_POSTCODE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
     }
     $fieldset->addField('tax_postcode', 'text', ['name' => 'tax_postcode', 'label' => __('Zip/Post Code'), 'note' => __("'*' - matches any; 'xyz*' - matches any that begins on 'xyz' and are not longer than %1.", $this->_taxData->getPostCodeSubStringLength())]);
     $fieldset->addField('zip_from', 'text', ['name' => 'zip_from', 'label' => __('Range From'), 'required' => true, 'maxlength' => 9, 'class' => 'validate-digits', 'css_class' => 'hidden']);
     $fieldset->addField('zip_to', 'text', ['name' => 'zip_to', 'label' => __('Range To'), 'required' => true, 'maxlength' => 9, 'class' => 'validate-digits', 'css_class' => 'hidden']);
     $fieldset->addField('tax_region_id', 'select', ['name' => 'tax_region_id', 'label' => __('State'), 'values' => $regions]);
     $fieldset->addField('tax_country_id', 'select', ['name' => 'tax_country_id', 'label' => __('Country'), 'required' => true, 'values' => $countries]);
     $fieldset->addField('rate', 'text', ['name' => 'rate', 'label' => __('Rate Percent'), 'title' => __('Rate Percent'), 'required' => true, 'class' => 'validate-not-negative-number']);
     $form->setAction($this->getUrl('tax/rate/save'));
     $form->setUseContainer(true);
     $form->setId(self::FORM_ELEMENT_ID);
     $form->setMethod('post');
     if (!$this->_storeManager->hasSingleStore()) {
         $form->addElement($this->_fieldsetFactory->create()->setLegend(__('Tax Titles')));
     }
     if (isset($formData['zip_is_range']) && $formData['zip_is_range']) {
         list($formData['zip_from'], $formData['zip_to']) = explode('-', $formData['tax_postcode']);
     }
     $form->setValues($formData);
     $this->setForm($form);
     $this->setChild('form_after', $this->getLayout()->createBlock('Magento\\Framework\\View\\Element\\Template')->setTemplate('Magento_Tax::rate/js.phtml'));
     return parent::_prepareForm();
 }