Ejemplo n.º 1
0
 /**
  * Check that grid does not contain unnecessary totals row
  *
  * @param $from string
  * @param $to string
  * @param $expectedResult bool
  *
  * @dataProvider getCountTotalsDataProvider
  * @magentoDataFixture Magento/Reports/_files/orders.php
  */
 public function testGetCountTotals($from, $to, $expectedResult)
 {
     $block = $this->_createBlock();
     $filterData = new \Magento\Framework\Object();
     $filterData->setReportType('updated_at_order');
     $filterData->setPeriodType('day');
     $filterData->setData('from', $from);
     $filterData->setData('to', $to);
     $block->setFilterData($filterData);
     $block->toHtml();
     $this->assertEquals($block->getCountTotals(), $expectedResult);
 }
Ejemplo n.º 2
0
 /**
  * Attributes validation action
  *
  * @return void
  */
 public function execute()
 {
     $response = new \Magento\Framework\Object();
     $response->setError(false);
     $attributesData = $this->getRequest()->getParam('attributes', array());
     $data = new \Magento\Framework\Object();
     try {
         if ($attributesData) {
             foreach ($attributesData as $attributeCode => $value) {
                 $attribute = $this->_objectManager->get('Magento\\Eav\\Model\\Config')->getAttribute('catalog_product', $attributeCode);
                 if (!$attribute->getAttributeId()) {
                     unset($attributesData[$attributeCode]);
                     continue;
                 }
                 $data->setData($attributeCode, $value);
                 $attribute->getBackend()->validate($data);
             }
         }
     } catch (\Magento\Eav\Model\Entity\Attribute\Exception $e) {
         $response->setError(true);
         $response->setAttribute($e->getAttributeCode());
         $response->setMessage($e->getMessage());
     } catch (\Magento\Framework\Model\Exception $e) {
         $response->setError(true);
         $response->setMessage($e->getMessage());
     } catch (\Exception $e) {
         $this->messageManager->addException($e, __('Something went wrong while updating the product(s) attributes.'));
         $this->_view->getLayout()->initMessages();
         $response->setError(true);
         $response->setHtmlMessage($this->_view->getLayout()->getMessagesBlock()->getGroupedHtml());
     }
     $this->getResponse()->representJson($response->toJson());
 }
Ejemplo n.º 3
0
 /**
  * @param array $data
  * @param bool $result
  * @param array $messages
  *
  * @covers \Magento\Framework\View\Design\Theme\Validator::validate
  * @dataProvider dataProviderValidate
  */
 public function testValidate(array $data, $result, array $messages)
 {
     /** @var $themeMock \Magento\Framework\Object */
     $themeMock = new \Magento\Framework\Object();
     $themeMock->setData($data);
     $validator = new \Magento\Framework\View\Design\Theme\Validator();
     $this->assertEquals($result, $validator->validate($themeMock));
     $this->assertEquals($messages, $validator->getErrorMessages());
 }
Ejemplo n.º 4
0
 /**
  * @param array $actions
  * @return string
  */
 protected function _actionsToHtml(array $actions)
 {
     $html = [];
     $attributesObject = new \Magento\Framework\Object();
     foreach ($actions as $action) {
         $attributesObject->setData($action['@']);
         $html[] = '<a ' . $attributesObject->serialize() . '>' . $action['#'] . '</a>';
     }
     return implode('<span class="separator">&nbsp;|&nbsp;</span>', $html);
 }
Ejemplo n.º 5
0
 /**
  * Load data
  *
  * @param bool $printQuery
  * @param bool $logQuery
  * @return $this
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function loadData($printQuery = false, $logQuery = false)
 {
     if (!count($this->_items)) {
         $data = [['id' => 'sales', 'report' => __('Orders'), 'comment' => __('Total Ordered Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_ORDER_FLAG_CODE)], ['id' => 'tax', 'report' => __('Tax'), 'comment' => __('Order Taxes Report Grouped by Tax Rates'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_TAX_FLAG_CODE)], ['id' => 'shipping', 'report' => __('Shipping'), 'comment' => __('Total Shipped Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_SHIPPING_FLAG_CODE)], ['id' => 'invoiced', 'report' => __('Total Invoiced'), 'comment' => __('Total Invoiced VS Paid Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_INVOICE_FLAG_CODE)], ['id' => 'refunded', 'report' => __('Total Refunded'), 'comment' => __('Total Refunded Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_REFUNDED_FLAG_CODE)], ['id' => 'coupons', 'report' => __('Coupons'), 'comment' => __('Promotion Coupons Usage Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_COUPONS_FLAG_CODE)], ['id' => 'bestsellers', 'report' => __('Bestsellers'), 'comment' => __('Products Bestsellers Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_BESTSELLERS_FLAG_CODE)], ['id' => 'viewed', 'report' => __('Most Viewed'), 'comment' => __('Most Viewed Products Report'), 'updated_at' => $this->_getUpdatedAt(\Magento\Reports\Model\Flag::REPORT_PRODUCT_VIEWED_FLAG_CODE)]];
         foreach ($data as $value) {
             $item = new \Magento\Framework\Object();
             $item->setData($value);
             $this->addItem($item);
         }
     }
     return $this;
 }
Ejemplo n.º 6
0
 /**
  * Render options array as a HTML string
  *
  * @param array $actions
  * @return string
  */
 protected function _actionsToHtml(array $actions = [])
 {
     $html = [];
     $attributesObject = new \Magento\Framework\Object();
     if (empty($actions)) {
         $actions = $this->_actions;
     }
     foreach ($actions as $action) {
         $attributesObject->setData($action['@']);
         $html[] = '<a ' . $attributesObject->serialize() . '>' . $action['#'] . '</a>';
     }
     return implode('', $html);
 }
Ejemplo n.º 7
0
 /**
  * Test that Tax Rate applied only once
  *
  * @magentoAppIsolation enabled
  * @magentoDataFixture Magento/Tax/_files/tax_classes.php
  */
 public function testGetRate()
 {
     /** @var $objectManager \Magento\TestFramework\ObjectManager */
     $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
     $taxRule = $objectManager->get('Magento\\Framework\\Registry')->registry('_fixture/Magento_Tax_Model_Calculation_Rule');
     $customerTaxClasses = $taxRule->getCustomerTaxClassIds();
     $productTaxClasses = $taxRule->getProductTaxClassIds();
     $taxRate = $objectManager->get('Magento\\Framework\\Registry')->registry('_fixture/Magento_Tax_Model_Calculation_Rate');
     $data = new \Magento\Framework\Object();
     $data->setData(['tax_country_id' => 'US', 'taxregion_id' => '12', 'tax_postcode' => '5555', 'customer_class_id' => $customerTaxClasses[0], 'product_class_id' => $productTaxClasses[0]]);
     $taxCalculation = $objectManager->get('Magento\\Tax\\Model\\Resource\\Calculation');
     $this->assertEquals($taxRate->getRateIds(), $taxCalculation->getRate($data));
 }
Ejemplo n.º 8
0
 /**
  * @param array $indexValues
  * @param string $expectedResult
  * @dataProvider renderDataProvider
  */
 public function testRender($indexValues, $expectedResult)
 {
     $context = $this->getMockBuilder('\\Magento\\Backend\\Block\\Context')->disableOriginalConstructor()->getMock();
     $model = new \Magento\Indexer\Block\Backend\Grid\Column\Renderer\Status($context);
     $obj = new \Magento\Framework\Object();
     $obj->setGetter(null);
     $obj->setDefault('');
     $obj->setValue('');
     $obj->setIndex($indexValues[0]);
     $obj->setData($indexValues[0], $indexValues[0]);
     $model->setColumn($obj);
     $model->setIndex($indexValues[0]);
     $result = $model->render($obj);
     $this->assertEquals($result, '<span class="' . $expectedResult['class'] . '"><span>' . $expectedResult['text'] . '</span></span>');
 }
Ejemplo n.º 9
0
 /**
  * Retrieve count totals
  *
  * @param \Magento\Backend\Block\Widget\Grid $grid
  * @param string $from
  * @param string $to
  * @return \Magento\Framework\Object
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function countTotals($grid, $from, $to)
 {
     $columns = [];
     foreach ($grid->getColumns() as $col) {
         $columns[$col->getIndex()] = ["total" => $col->getTotal(), "value" => 0];
     }
     $count = 0;
     /**
      * This method doesn't work because of commit 6e15235, see MAGETWO-4751
      */
     $report = $grid->getCollection()->getReportFull($from, $to);
     foreach ($report as $item) {
         if ($grid->getSubReportSize() && $count >= $grid->getSubReportSize()) {
             continue;
         }
         $data = $item->getData();
         foreach ($columns as $field => $a) {
             if ($field !== '') {
                 $columns[$field]['value'] = $columns[$field]['value'] + (isset($data[$field]) ? $data[$field] : 0);
             }
         }
         $count++;
     }
     $data = [];
     foreach ($columns as $field => $a) {
         if ($a['total'] == 'avg') {
             if ($field !== '') {
                 if ($count != 0) {
                     $data[$field] = $a['value'] / $count;
                 } else {
                     $data[$field] = 0;
                 }
             }
         } elseif ($a['total'] == 'sum') {
             if ($field !== '') {
                 $data[$field] = $a['value'];
             }
         } elseif (strpos($a['total'], '/') !== false) {
             if ($field !== '') {
                 $data[$field] = 0;
             }
         }
     }
     $totals = new \Magento\Framework\Object();
     $totals->setData($data);
     return $totals;
 }
Ejemplo n.º 10
0
 public function testGetEntitySummary()
 {
     $productId = 6;
     $storeId = 4;
     $testSummaryData = ['test' => 'value'];
     $summary = new \Magento\Framework\Object();
     $summary->setData($testSummaryData);
     $product = $this->getMock('Magento\\Catalog\\Model\\Product', ['getId', 'setRatingSummary', '__wakeup'], [], '', false);
     $product->expects($this->once())->method('getId')->will($this->returnValue($productId));
     $product->expects($this->once())->method('setRatingSummary')->with($summary)->will($this->returnSelf());
     $summaryData = $this->getMock('Magento\\Review\\Model\\Review\\Summary', ['load', 'getData', 'setStoreId', '__wakeup'], [], '', false);
     $summaryData->expects($this->once())->method('setStoreId')->with($this->equalTo($storeId))->will($this->returnSelf());
     $summaryData->expects($this->once())->method('load')->with($this->equalTo($productId))->will($this->returnSelf());
     $summaryData->expects($this->once())->method('getData')->will($this->returnValue($testSummaryData));
     $this->summaryModMock->expects($this->once())->method('create')->will($this->returnValue($summaryData));
     $this->assertNull($this->review->getEntitySummary($product, $storeId));
 }
Ejemplo n.º 11
0
 /**
  * Tests \Magento\Framework\Object->hasDataChanges()
  */
 public function testHasDataChanges()
 {
     $this->assertFalse($this->_object->hasDataChanges());
     $this->_object->setData('key', 'value');
     $this->assertTrue($this->_object->hasDataChanges(), 'Data changed');
     $object = new \Magento\Framework\Object(['key' => 'value']);
     $object->setData('key', 'value');
     $this->assertFalse($object->hasDataChanges(), 'Data not changed');
     $object->setData(['key' => 'value']);
     $this->assertFalse($object->hasDataChanges(), 'Data not changed (array)');
     $object = new \Magento\Framework\Object();
     $object->unsetData();
     $this->assertFalse($object->hasDataChanges(), 'Unset data');
     $object = new \Magento\Framework\Object(['key' => null]);
     $object->setData('key', null);
     $this->assertFalse($object->hasDataChanges(), 'Null data');
 }
Ejemplo n.º 12
0
 /**
  * Post user question
  *
  * @return void
  * @throws \Exception
  */
 public function execute()
 {
     $post = $this->getRequest()->getPostValue();
     if (!$post) {
         $this->_redirect('*/*/');
         return;
     }
     $this->inlineTranslation->suspend();
     try {
         $postObject = new \Magento\Framework\Object();
         $postObject->setData($post);
         $error = false;
         if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
             $error = true;
         }
         if (!\Zend_Validate::is(trim($post['comment']), 'NotEmpty')) {
             $error = true;
         }
         if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
             $error = true;
         }
         if (\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
             $error = true;
         }
         if ($error) {
             throw new \Exception();
         }
         $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
         $transport = $this->_transportBuilder->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope))->setTemplateOptions(['area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])->setTemplateVars(['data' => $postObject])->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))->setReplyTo($post['email'])->getTransport();
         $transport->sendMessage();
         $this->inlineTranslation->resume();
         $this->messageManager->addSuccess(__('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.'));
         $this->_redirect('*/*/');
         return;
     } catch (\Exception $e) {
         $this->inlineTranslation->resume();
         $this->messageManager->addError(__('We can\'t process your request right now. Sorry, that\'s all we know.'));
         $this->_redirect('*/*/');
         return;
     }
 }
Ejemplo n.º 13
0
 /**
  * Report action init operations
  *
  * @param array|\Magento\Framework\Object $blocks
  * @return $this
  */
 public function _initReportAction($blocks)
 {
     if (!is_array($blocks)) {
         $blocks = [$blocks];
     }
     $requestData = $this->_objectManager->get('Magento\\Backend\\Helper\\Data')->prepareFilterString($this->getRequest()->getParam('filter'));
     $inputFilter = new \Zend_Filter_Input(['from' => $this->_dateFilter, 'to' => $this->_dateFilter], [], $requestData);
     $requestData = $inputFilter->getUnescaped();
     $requestData['store_ids'] = $this->getRequest()->getParam('store_ids');
     $params = new \Magento\Framework\Object();
     foreach ($requestData as $key => $value) {
         if (!empty($value)) {
             $params->setData($key, $value);
         }
     }
     foreach ($blocks as $block) {
         if ($block) {
             $block->setPeriodType($params->getData('period_type'));
             $block->setFilterData($params);
         }
     }
     return $this;
 }
Ejemplo n.º 14
0
 /**
  * Render single action as link html
  *
  * @param array $action
  * @param \Magento\Framework\Object $row
  * @return string
  */
 protected function _toLinkHtml($action, \Magento\Framework\Object $row)
 {
     $actionAttributes = new \Magento\Framework\Object();
     $actionCaption = '';
     $this->_transformActionData($action, $actionCaption, $row);
     if (isset($action['confirm'])) {
         $action['onclick'] = 'return window.confirm(\'' . addslashes($this->escapeHtml($action['confirm'])) . '\')';
         unset($action['confirm']);
     }
     $actionAttributes->setData($action);
     return '<a ' . $actionAttributes->serialize() . '>' . $actionCaption . '</a>';
 }
Ejemplo n.º 15
0
 /**
  * Process $buyRequest and sets its options before saving configuration to some product item.
  * This method is used to attach additional parameters to processed buyRequest.
  *
  * $params holds parameters of what operation must be performed:
  * - 'current_config', \Magento\Framework\Object or array - current buyRequest that configures product in this item,
  *   used to restore currently attached files
  * - 'files_prefix': string[a-z0-9_] - prefix that was added at frontend to names of file inputs,
  *   so they won't intersect with other submitted options
  *
  * @param \Magento\Framework\Object|array $buyRequest
  * @param \Magento\Framework\Object|array $params
  * @return \Magento\Framework\Object
  */
 public function addParamsToBuyRequest($buyRequest, $params)
 {
     if (is_array($buyRequest)) {
         $buyRequest = new \Magento\Framework\Object($buyRequest);
     }
     if (is_array($params)) {
         $params = new \Magento\Framework\Object($params);
     }
     // Ensure that currentConfig goes as \Magento\Framework\Object - for easier work with it later
     $currentConfig = $params->getCurrentConfig();
     if ($currentConfig) {
         if (is_array($currentConfig)) {
             $params->setCurrentConfig(new \Magento\Framework\Object($currentConfig));
         } elseif (!$currentConfig instanceof \Magento\Framework\Object) {
             $params->unsCurrentConfig();
         }
     }
     /*
      * Notice that '_processing_params' must always be object to protect processing forged requests
      * where '_processing_params' comes in $buyRequest as array from user input
      */
     $processingParams = $buyRequest->getData('_processing_params');
     if (!$processingParams || !$processingParams instanceof \Magento\Framework\Object) {
         $processingParams = new \Magento\Framework\Object();
         $buyRequest->setData('_processing_params', $processingParams);
     }
     $processingParams->addData($params->getData());
     return $buyRequest;
 }
Ejemplo n.º 16
0
 /**
  * Create item object from item data
  *
  * @param string $name
  * @param int $qty
  * @param float $amount
  * @param null|string $identifier
  * @return \Magento\Framework\Object
  */
 protected function _createItemFromData($name, $qty, $amount, $identifier = null)
 {
     $item = new \Magento\Framework\Object(['name' => $name, 'qty' => $qty, 'amount' => (double) $amount]);
     if ($identifier) {
         $item->setData('id', $identifier);
     }
     return $item;
 }
Ejemplo n.º 17
0
 /**
  * @return array
  */
 public function textExecuteFailedPlaceOrderDataProvider()
 {
     $objectFailed = new \Magento\Framework\Object();
     $objectFailed->setData('error', true);
     $objectFailed->setData('error_messages', __('Cannot place order.'));
     return [[['method' => 'authorizenet_directpost'], IframeConfigProvider::CHECKOUT_IDENTIFIER, 1, $objectFailed]];
 }
Ejemplo n.º 18
0
 /**
  * Post request to gateway and return response
  *
  * @param \Magento\Framework\Object $request
  * @return \Magento\Framework\Object
  * @throws \Exception
  */
 protected function _postRequest(\Magento\Framework\Object $request)
 {
     $debugData = array('request' => $request->getData());
     /** @var \Magento\Framework\HTTP\ZendClient $client */
     $client = $this->_httpClientFactory->create();
     $result = new \Magento\Framework\Object();
     $_config = array('maxredirects' => 5, 'timeout' => 30, 'verifypeer' => $this->getConfigData('verify_peer'));
     $_isProxy = $this->getConfigData('use_proxy', false);
     if ($_isProxy) {
         $_config['proxy'] = $this->getConfigData('proxy_host') . ':' . $this->getConfigData('proxy_port');
         //http://proxy.shr.secureserver.net:3128',
         $_config['httpproxytunnel'] = true;
         $_config['proxytype'] = CURLPROXY_HTTP;
     }
     $client->setUri($this->_getTransactionUrl())->setConfig($_config)->setMethod(\Zend_Http_Client::POST)->setParameterPost($request->getData())->setHeaders('X-VPS-VIT-CLIENT-CERTIFICATION-ID: 33baf5893fc2123d8b191d2d011b7fdc')->setHeaders('X-VPS-Request-ID: ' . $request->getRequestId())->setHeaders('X-VPS-CLIENT-TIMEOUT: ' . $this->_clientTimeout);
     try {
         /**
          * we are sending request to payflow pro without url encoding
          * so we set up _urlEncodeBody flag to false
          */
         $response = $client->setUrlEncodeBody(false)->request();
     } catch (\Exception $e) {
         $result->setResponseCode(-1)->setResponseReasonCode($e->getCode())->setResponseReasonText($e->getMessage());
         $debugData['result'] = $result->getData();
         $this->_debug($debugData);
         throw $e;
     }
     $response = strstr($response->getBody(), 'RESULT');
     $valArray = explode('&', $response);
     foreach ($valArray as $val) {
         $valArray2 = explode('=', $val);
         $result->setData(strtolower($valArray2[0]), $valArray2[1]);
     }
     $result->setResultCode($result->getResult())->setRespmsg($result->getRespmsg());
     $debugData['result'] = $result->getData();
     $this->_debug($debugData);
     return $result;
 }
Ejemplo n.º 19
0
 /**
  * Form array with appropriate structure for shipment request
  *
  * @param \Magento\Framework\Object $request
  * @return array
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 protected function _formShipmentRequest(\Magento\Framework\Object $request)
 {
     if ($request->getReferenceData()) {
         $referenceData = $request->getReferenceData() . $request->getPackageId();
     } else {
         $referenceData = 'Order #' . $request->getOrderShipment()->getOrder()->getIncrementId() . ' P' . $request->getPackageId();
     }
     $packageParams = $request->getPackageParams();
     $customsValue = $packageParams->getCustomsValue();
     $height = $packageParams->getHeight();
     $width = $packageParams->getWidth();
     $length = $packageParams->getLength();
     $weightUnits = $packageParams->getWeightUnits() == \Zend_Measure_Weight::POUND ? 'LB' : 'KG';
     $dimensionsUnits = $packageParams->getDimensionUnits() == \Zend_Measure_Length::INCH ? 'IN' : 'CM';
     $unitPrice = 0;
     $itemsQty = 0;
     $itemsDesc = [];
     $countriesOfManufacture = [];
     $productIds = [];
     $packageItems = $request->getPackageItems();
     foreach ($packageItems as $itemShipment) {
         $item = new \Magento\Framework\Object();
         $item->setData($itemShipment);
         $unitPrice += $item->getPrice();
         $itemsQty += $item->getQty();
         $itemsDesc[] = $item->getName();
         $productIds[] = $item->getProductId();
     }
     // get countries of manufacture
     $productCollection = $this->_productCollectionFactory->create()->addStoreFilter($request->getStoreId())->addFieldToFilter('entity_id', ['in' => $productIds])->addAttributeToSelect('country_of_manufacture');
     foreach ($productCollection as $product) {
         $countriesOfManufacture[] = $product->getCountryOfManufacture();
     }
     $paymentType = $request->getIsReturn() ? 'RECIPIENT' : 'SENDER';
     $requestClient = ['RequestedShipment' => ['ShipTimestamp' => time(), 'DropoffType' => $this->getConfigData('dropoff'), 'PackagingType' => $request->getPackagingType(), 'ServiceType' => $request->getShippingMethod(), 'Shipper' => ['Contact' => ['PersonName' => $request->getShipperContactPersonName(), 'CompanyName' => $request->getShipperContactCompanyName(), 'PhoneNumber' => $request->getShipperContactPhoneNumber()], 'Address' => ['StreetLines' => [$request->getShipperAddressStreet()], 'City' => $request->getShipperAddressCity(), 'StateOrProvinceCode' => $request->getShipperAddressStateOrProvinceCode(), 'PostalCode' => $request->getShipperAddressPostalCode(), 'CountryCode' => $request->getShipperAddressCountryCode()]], 'Recipient' => ['Contact' => ['PersonName' => $request->getRecipientContactPersonName(), 'CompanyName' => $request->getRecipientContactCompanyName(), 'PhoneNumber' => $request->getRecipientContactPhoneNumber()], 'Address' => ['StreetLines' => [$request->getRecipientAddressStreet()], 'City' => $request->getRecipientAddressCity(), 'StateOrProvinceCode' => $request->getRecipientAddressStateOrProvinceCode(), 'PostalCode' => $request->getRecipientAddressPostalCode(), 'CountryCode' => $request->getRecipientAddressCountryCode(), 'Residential' => (bool) $this->getConfigData('residence_delivery')]], 'ShippingChargesPayment' => ['PaymentType' => $paymentType, 'Payor' => ['AccountNumber' => $this->getConfigData('account'), 'CountryCode' => $this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId())]], 'LabelSpecification' => ['LabelFormatType' => 'COMMON2D', 'ImageType' => 'PNG', 'LabelStockType' => 'PAPER_8.5X11_TOP_HALF_LABEL'], 'RateRequestTypes' => ['ACCOUNT'], 'PackageCount' => 1, 'RequestedPackageLineItems' => ['SequenceNumber' => '1', 'Weight' => ['Units' => $weightUnits, 'Value' => $request->getPackageWeight()], 'CustomerReferences' => ['CustomerReferenceType' => 'CUSTOMER_REFERENCE', 'Value' => $referenceData], 'SpecialServicesRequested' => ['SpecialServiceTypes' => 'SIGNATURE_OPTION', 'SignatureOptionDetail' => ['OptionType' => $packageParams->getDeliveryConfirmation()]]]]];
     // for international shipping
     if ($request->getShipperAddressCountryCode() != $request->getRecipientAddressCountryCode()) {
         $requestClient['RequestedShipment']['CustomsClearanceDetail'] = ['CustomsValue' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $customsValue], 'DutiesPayment' => ['PaymentType' => $paymentType, 'Payor' => ['AccountNumber' => $this->getConfigData('account'), 'CountryCode' => $this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId())]], 'Commodities' => ['Weight' => ['Units' => $weightUnits, 'Value' => $request->getPackageWeight()], 'NumberOfPieces' => 1, 'CountryOfManufacture' => implode(',', array_unique($countriesOfManufacture)), 'Description' => implode(', ', $itemsDesc), 'Quantity' => ceil($itemsQty), 'QuantityUnits' => 'pcs', 'UnitPrice' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $unitPrice], 'CustomsValue' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $customsValue]]];
     }
     if ($request->getMasterTrackingId()) {
         $requestClient['RequestedShipment']['MasterTrackingId'] = $request->getMasterTrackingId();
     }
     // set dimensions
     if ($length || $width || $height) {
         $requestClient['RequestedShipment']['RequestedPackageLineItems']['Dimensions'] = [];
         $dimenssions =& $requestClient['RequestedShipment']['RequestedPackageLineItems']['Dimensions'];
         $dimenssions['Length'] = $length;
         $dimenssions['Width'] = $width;
         $dimenssions['Height'] = $height;
         $dimenssions['Units'] = $dimensionsUnits;
     }
     return $this->_getAuthDetails() + $requestClient;
 }
Ejemplo n.º 20
0
 /**
  * Get entity summary
  *
  * @param Product $product
  * @param int $storeId
  * @return void
  */
 public function getEntitySummary($product, $storeId = 0)
 {
     $summaryData = $this->_summaryModFactory->create()->setStoreId($storeId)->load($product->getId());
     $summary = new \Magento\Framework\Object();
     $summary->setData($summaryData->getData());
     $product->setRatingSummary($summary);
 }
Ejemplo n.º 21
0
 /**
  * Return Wysiwyg config as \Magento\Framework\Object
  *
  * Config options description:
  *
  * enabled:                 Enabled Visual Editor or not
  * hidden:                  Show Visual Editor on page load or not
  * use_container:           Wrap Editor contents into div or not
  * no_display:              Hide Editor container or not (related to use_container)
  * translator:              Helper to translate phrases in lib
  * files_browser_*:         Files Browser (media, images) settings
  * encode_directives:       Encode template directives with JS or not
  *
  * @param array|\Magento\Framework\Object $data Object constructor params to override default config values
  * @return \Magento\Framework\Object
  */
 public function getConfig($data = [])
 {
     $config = new \Magento\Framework\Object();
     $config->setData(['enabled' => $this->isEnabled(), 'hidden' => $this->isHidden(), 'use_container' => false, 'add_variables' => true, 'add_widgets' => true, 'no_display' => false, 'encode_directives' => true, 'directives_url' => $this->_backendUrl->getUrl('cms/wysiwyg/directive'), 'popup_css' => $this->_assetRepo->getUrl('mage/adminhtml/wysiwyg/tiny_mce/themes/advanced/skins/default/dialog.css'), 'content_css' => $this->_assetRepo->getUrl('mage/adminhtml/wysiwyg/tiny_mce/themes/advanced/skins/default/content.css'), 'width' => '100%', 'plugins' => []]);
     $config->setData('directives_url_quoted', preg_quote($config->getData('directives_url')));
     if ($this->_authorization->isAllowed('Magento_Cms::media_gallery')) {
         $config->addData(['add_images' => true, 'files_browser_window_url' => $this->_backendUrl->getUrl('cms/wysiwyg_images/index'), 'files_browser_window_width' => $this->_windowSize['width'], 'files_browser_window_height' => $this->_windowSize['height']]);
     }
     if (is_array($data)) {
         $config->addData($data);
     }
     if ($config->getData('add_variables')) {
         $settings = $this->_variableConfig->getWysiwygPluginSettings($config);
         $config->addData($settings);
     }
     if ($config->getData('add_widgets')) {
         $settings = $this->_widgetConfig->getPluginSettings($config);
         $config->addData($settings);
     }
     return $config;
 }
Ejemplo n.º 22
0
 /**
  * Test decorateFilter()
  *
  * @param array $attributeData
  * @param string $backendType
  * @param array $columnValue
  * @dataProvider decorateFilterDataProvider
  */
 public function testDecorateFilter($attributeData, $backendType, $columnValue)
 {
     $value = '';
     $attribute = new \Magento\Eav\Model\Entity\Attribute($this->modelContext, $this->registry, $this->extensionFactory, $this->customAttributeFactory, $this->eavConfig, $this->eavTypeFactory, $this->storeManager, $this->resourceHelper, $this->universalFactory, $this->optionDataFactory, $this->dataObjectProcessor, $this->dataObjectHelper, $this->localeDate, $this->reservedAttributeList, $this->localeResolver, $this->resource, $this->resourceCollection);
     $attribute->setAttributeCode($attributeData['code']);
     $attribute->setFrontendInput($attributeData['input']);
     $attribute->setOptions($attributeData['options']);
     $attribute->setFilterOptions($attributeData['filter_options']);
     $attribute->setBackendType($backendType);
     $column = new \Magento\Framework\Object();
     $column->setData($columnValue, 'value');
     $isExport = true;
     $this->filter->decorateFilter($value, $attribute, $column, $isExport);
 }
Ejemplo n.º 23
0
 /**
  * Prepare fixture for exported address
  *
  * @param array $addressData
  * @return \Magento\Framework\Object
  */
 protected function _getExportedAddressFixture(array $addressData)
 {
     $addressDataKeys = ['firstname', 'lastname', 'street', 'city', 'telephone'];
     $result = array();
     foreach ($addressDataKeys as $key) {
         if (isset($addressData[$key])) {
             $result[$key] = 'exported' . $addressData[$key];
         }
     }
     $fixture = new \Magento\Framework\Object($result);
     $fixture->setExportedKeys($addressDataKeys);
     $fixture->setData('note', 'note');
     return $fixture;
 }
Ejemplo n.º 24
0
 /**
  * Form XML for shipment request
  *
  * @param \Magento\Framework\Object $request
  * @return string
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 protected function _formShipmentRequest(\Magento\Framework\Object $request)
 {
     $packageParams = $request->getPackageParams();
     $height = $packageParams->getHeight();
     $width = $packageParams->getWidth();
     $length = $packageParams->getLength();
     $weightUnits = $packageParams->getWeightUnits() == \Zend_Measure_Weight::POUND ? 'LBS' : 'KGS';
     $dimensionsUnits = $packageParams->getDimensionUnits() == \Zend_Measure_Length::INCH ? 'IN' : 'CM';
     $itemsDesc = [];
     $itemsShipment = $request->getPackageItems();
     foreach ($itemsShipment as $itemShipment) {
         $item = new \Magento\Framework\Object();
         $item->setData($itemShipment);
         $itemsDesc[] = $item->getName();
     }
     $xmlRequest = $this->_xmlElFactory->create(['data' => '<?xml version = "1.0" ?><ShipmentConfirmRequest xml:lang="en-US"/>']);
     $requestPart = $xmlRequest->addChild('Request');
     $requestPart->addChild('RequestAction', 'ShipConfirm');
     $requestPart->addChild('RequestOption', 'nonvalidate');
     $shipmentPart = $xmlRequest->addChild('Shipment');
     if ($request->getIsReturn()) {
         $returnPart = $shipmentPart->addChild('ReturnService');
         // UPS Print Return Label
         $returnPart->addChild('Code', '9');
     }
     $shipmentPart->addChild('Description', substr(implode(' ', $itemsDesc), 0, 35));
     //empirical
     $shipperPart = $shipmentPart->addChild('Shipper');
     if ($request->getIsReturn()) {
         $shipperPart->addChild('Name', $request->getRecipientContactCompanyName());
         $shipperPart->addChild('AttentionName', $request->getRecipientContactPersonName());
         $shipperPart->addChild('ShipperNumber', $this->getConfigData('shipper_number'));
         $shipperPart->addChild('PhoneNumber', $request->getRecipientContactPhoneNumber());
         $addressPart = $shipperPart->addChild('Address');
         $addressPart->addChild('AddressLine1', $request->getRecipientAddressStreet());
         $addressPart->addChild('AddressLine2', $request->getRecipientAddressStreet2());
         $addressPart->addChild('City', $request->getRecipientAddressCity());
         $addressPart->addChild('CountryCode', $request->getRecipientAddressCountryCode());
         $addressPart->addChild('PostalCode', $request->getRecipientAddressPostalCode());
         if ($request->getRecipientAddressStateOrProvinceCode()) {
             $addressPart->addChild('StateProvinceCode', $request->getRecipientAddressStateOrProvinceCode());
         }
     } else {
         $shipperPart->addChild('Name', $request->getShipperContactCompanyName());
         $shipperPart->addChild('AttentionName', $request->getShipperContactPersonName());
         $shipperPart->addChild('ShipperNumber', $this->getConfigData('shipper_number'));
         $shipperPart->addChild('PhoneNumber', $request->getShipperContactPhoneNumber());
         $addressPart = $shipperPart->addChild('Address');
         $addressPart->addChild('AddressLine1', $request->getShipperAddressStreet());
         $addressPart->addChild('AddressLine2', $request->getShipperAddressStreet2());
         $addressPart->addChild('City', $request->getShipperAddressCity());
         $addressPart->addChild('CountryCode', $request->getShipperAddressCountryCode());
         $addressPart->addChild('PostalCode', $request->getShipperAddressPostalCode());
         if ($request->getShipperAddressStateOrProvinceCode()) {
             $addressPart->addChild('StateProvinceCode', $request->getShipperAddressStateOrProvinceCode());
         }
     }
     $shipToPart = $shipmentPart->addChild('ShipTo');
     $shipToPart->addChild('AttentionName', $request->getRecipientContactPersonName());
     $shipToPart->addChild('CompanyName', $request->getRecipientContactCompanyName() ? $request->getRecipientContactCompanyName() : 'N/A');
     $shipToPart->addChild('PhoneNumber', $request->getRecipientContactPhoneNumber());
     $addressPart = $shipToPart->addChild('Address');
     $addressPart->addChild('AddressLine1', $request->getRecipientAddressStreet1());
     $addressPart->addChild('AddressLine2', $request->getRecipientAddressStreet2());
     $addressPart->addChild('City', $request->getRecipientAddressCity());
     $addressPart->addChild('CountryCode', $request->getRecipientAddressCountryCode());
     $addressPart->addChild('PostalCode', $request->getRecipientAddressPostalCode());
     if ($request->getRecipientAddressStateOrProvinceCode()) {
         $addressPart->addChild('StateProvinceCode', $request->getRecipientAddressRegionCode());
     }
     if ($this->getConfigData('dest_type') == 'RES') {
         $addressPart->addChild('ResidentialAddress');
     }
     if ($request->getIsReturn()) {
         $shipFromPart = $shipmentPart->addChild('ShipFrom');
         $shipFromPart->addChild('AttentionName', $request->getShipperContactPersonName());
         $shipFromPart->addChild('CompanyName', $request->getShipperContactCompanyName() ? $request->getShipperContactCompanyName() : $request->getShipperContactPersonName());
         $shipFromAddress = $shipFromPart->addChild('Address');
         $shipFromAddress->addChild('AddressLine1', $request->getShipperAddressStreet1());
         $shipFromAddress->addChild('AddressLine2', $request->getShipperAddressStreet2());
         $shipFromAddress->addChild('City', $request->getShipperAddressCity());
         $shipFromAddress->addChild('CountryCode', $request->getShipperAddressCountryCode());
         $shipFromAddress->addChild('PostalCode', $request->getShipperAddressPostalCode());
         if ($request->getShipperAddressStateOrProvinceCode()) {
             $shipFromAddress->addChild('StateProvinceCode', $request->getShipperAddressStateOrProvinceCode());
         }
         $addressPart = $shipToPart->addChild('Address');
         $addressPart->addChild('AddressLine1', $request->getShipperAddressStreet1());
         $addressPart->addChild('AddressLine2', $request->getShipperAddressStreet2());
         $addressPart->addChild('City', $request->getShipperAddressCity());
         $addressPart->addChild('CountryCode', $request->getShipperAddressCountryCode());
         $addressPart->addChild('PostalCode', $request->getShipperAddressPostalCode());
         if ($request->getShipperAddressStateOrProvinceCode()) {
             $addressPart->addChild('StateProvinceCode', $request->getShipperAddressStateOrProvinceCode());
         }
         if ($this->getConfigData('dest_type') == 'RES') {
             $addressPart->addChild('ResidentialAddress');
         }
     }
     $servicePart = $shipmentPart->addChild('Service');
     $servicePart->addChild('Code', $request->getShippingMethod());
     $packagePart = $shipmentPart->addChild('Package');
     $packagePart->addChild('Description', substr(implode(' ', $itemsDesc), 0, 35));
     //empirical
     $packagePart->addChild('PackagingType')->addChild('Code', $request->getPackagingType());
     $packageWeight = $packagePart->addChild('PackageWeight');
     $packageWeight->addChild('Weight', $request->getPackageWeight());
     $packageWeight->addChild('UnitOfMeasurement')->addChild('Code', $weightUnits);
     // set dimensions
     if ($length || $width || $height) {
         $packageDimensions = $packagePart->addChild('Dimensions');
         $packageDimensions->addChild('UnitOfMeasurement')->addChild('Code', $dimensionsUnits);
         $packageDimensions->addChild('Length', $length);
         $packageDimensions->addChild('Width', $width);
         $packageDimensions->addChild('Height', $height);
     }
     // ups support reference number only for domestic service
     if ($this->_isUSCountry($request->getRecipientAddressCountryCode()) && $this->_isUSCountry($request->getShipperAddressCountryCode())) {
         if ($request->getReferenceData()) {
             $referenceData = $request->getReferenceData() . $request->getPackageId();
         } else {
             $referenceData = 'Order #' . $request->getOrderShipment()->getOrder()->getIncrementId() . ' P' . $request->getPackageId();
         }
         $referencePart = $packagePart->addChild('ReferenceNumber');
         $referencePart->addChild('Code', '02');
         $referencePart->addChild('Value', $referenceData);
     }
     $deliveryConfirmation = $packageParams->getDeliveryConfirmation();
     if ($deliveryConfirmation) {
         /** @var $serviceOptionsNode Element */
         $serviceOptionsNode = null;
         switch ($this->_getDeliveryConfirmationLevel($request->getRecipientAddressCountryCode())) {
             case self::DELIVERY_CONFIRMATION_PACKAGE:
                 $serviceOptionsNode = $packagePart->addChild('PackageServiceOptions');
                 break;
             case self::DELIVERY_CONFIRMATION_SHIPMENT:
                 $serviceOptionsNode = $shipmentPart->addChild('ShipmentServiceOptions');
                 break;
             default:
                 break;
         }
         if (!is_null($serviceOptionsNode)) {
             $serviceOptionsNode->addChild('DeliveryConfirmation')->addChild('DCISType', $packageParams->getDeliveryConfirmation());
         }
     }
     $shipmentPart->addChild('PaymentInformation')->addChild('Prepaid')->addChild('BillShipper')->addChild('AccountNumber', $this->getConfigData('shipper_number'));
     if ($request->getPackagingType() != $this->configHelper->getCode('container', 'ULE') && $request->getShipperAddressCountryCode() == self::USA_COUNTRY_ID && ($request->getRecipientAddressCountryCode() == 'CA' || $request->getRecipientAddressCountryCode() == 'PR')) {
         $invoiceLineTotalPart = $shipmentPart->addChild('InvoiceLineTotal');
         $invoiceLineTotalPart->addChild('CurrencyCode', $request->getBaseCurrencyCode());
         $invoiceLineTotalPart->addChild('MonetaryValue', ceil($packageParams->getCustomsValue()));
     }
     $labelPart = $xmlRequest->addChild('LabelSpecification');
     $labelPart->addChild('LabelPrintMethod')->addChild('Code', 'GIF');
     $labelPart->addChild('LabelImageFormat')->addChild('Code', 'GIF');
     $this->setXMLAccessRequest();
     $xmlRequest = $this->_xmlAccessRequest . $xmlRequest->asXml();
     return $xmlRequest;
 }
Ejemplo n.º 25
0
 /**
  * Javascript setup object for filebrowser instance
  *
  * @return string
  */
 public function getFilebrowserSetupObject()
 {
     $setupObject = new \Magento\Framework\Object();
     $setupObject->setData(['newFolderPrompt' => __('New Folder Name:'), 'deleteFolderConfirmationMessage' => __('Are you sure you want to delete this folder?'), 'deleteFileConfirmationMessage' => __('Are you sure you want to delete this file?'), 'targetElementId' => $this->getTargetElementId(), 'contentsUrl' => $this->getContentsUrl(), 'onInsertUrl' => $this->getOnInsertUrl(), 'newFolderUrl' => $this->getNewfolderUrl(), 'deleteFolderUrl' => $this->getDeletefolderUrl(), 'deleteFilesUrl' => $this->getDeleteFilesUrl(), 'headerText' => $this->getHeaderText(), 'showBreadcrumbs' => true]);
     return $this->jsonHelper->jsonEncode($setupObject);
 }
Ejemplo n.º 26
0
 /**
  * Perform actions after object save
  *
  * @param \Magento\Framework\Model\AbstractModel $object
  * @param string $attribute
  * @return $this
  * @throws \Exception
  */
 public function saveAttribute(\Magento\Framework\Model\AbstractModel $object, $attribute)
 {
     if ($attribute instanceof \Magento\Eav\Model\Entity\Attribute\AbstractAttribute) {
         $attribute = $attribute->getAttributeCode();
     }
     if (is_string($attribute)) {
         $attribute = array($attribute);
     }
     if (is_array($attribute) && !empty($attribute)) {
         $this->beginTransaction();
         try {
             $this->_beforeSaveAttribute($object, $attribute);
             $data = new \Magento\Framework\Object();
             foreach ($attribute as $code) {
                 $data->setData($code, $object->getData($code));
             }
             $updateArray = $this->_prepareDataForTable($data, $this->getMainTable());
             $this->_postSaveFieldsUpdate($object, $updateArray);
             if (!$object->getForceUpdateGridRecords() && count(array_intersect($this->getGridColumns(), $attribute)) > 0) {
                 $this->updateGridRecords($object->getId());
             }
             $this->_afterSaveAttribute($object, $attribute);
             $this->commit();
         } catch (\Exception $e) {
             $this->rollBack();
             throw $e;
         }
     }
     return $this;
 }
Ejemplo n.º 27
0
 /**
  * Retrieve table status
  *
  * @param string $tableName
  * @return \Magento\Framework\Object|bool
  */
 public function getTableStatus($tableName)
 {
     $row = $this->_write->showTableStatus($tableName);
     if ($row) {
         $statusObject = new \Magento\Framework\Object();
         $statusObject->setIdFieldName('name');
         foreach ($row as $field => $value) {
             $statusObject->setData(strtolower($field), $value);
         }
         $cntRow = $this->_write->fetchRow($this->_write->select()->from($tableName, 'COUNT(1) as rows'));
         $statusObject->setRows($cntRow['rows']);
         return $statusObject;
     }
     return false;
 }
Ejemplo n.º 28
0
 /**
  * Return widget XML configuration as \Magento\Framework\Object and makes some data preparations
  *
  * @param string $type Widget type
  * @return \Magento\Framework\Object
  */
 public function getConfigAsObject($type)
 {
     $widget = $this->getWidgetByClassType($type);
     $object = new \Magento\Framework\Object();
     if ($widget === null) {
         return $object;
     }
     $widget = $this->_getAsCanonicalArray($widget);
     // Save all nodes to object data
     $object->setType($type);
     $object->setData($widget);
     // Correct widget parameters and convert its data to objects
     $params = $object->getData('parameters');
     $newParams = array();
     if (is_array($params)) {
         $sortOrder = 0;
         foreach ($params as $key => $data) {
             if (is_array($data)) {
                 $data['key'] = $key;
                 $data['sort_order'] = isset($data['sort_order']) ? (int) $data['sort_order'] : $sortOrder;
                 // prepare values (for drop-dawns) specified directly in configuration
                 $values = array();
                 if (isset($data['values']) && is_array($data['values'])) {
                     foreach ($data['values'] as $value) {
                         if (isset($value['label']) && isset($value['value'])) {
                             $values[] = $value;
                         }
                     }
                 }
                 $data['values'] = $values;
                 // prepare helper block object
                 if (isset($data['helper_block'])) {
                     $helper = new \Magento\Framework\Object();
                     if (isset($data['helper_block']['data']) && is_array($data['helper_block']['data'])) {
                         $helper->addData($data['helper_block']['data']);
                     }
                     if (isset($data['helper_block']['type'])) {
                         $helper->setType($data['helper_block']['type']);
                     }
                     $data['helper_block'] = $helper;
                 }
                 $newParams[$key] = new \Magento\Framework\Object($data);
                 $sortOrder++;
             }
         }
     }
     uasort($newParams, array($this, '_sortParameters'));
     $object->setData('parameters', $newParams);
     return $object;
 }
Ejemplo n.º 29
0
 /**
  * Form XML for international shipment request
  * As integration guide it is important to follow appropriate sequence for tags e.g.: <FromLastName /> must be
  * after <FromFirstName />
  *
  * @param \Magento\Framework\Object $request
  * @return string
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 protected function _formIntlShipmentRequest(\Magento\Framework\Object $request)
 {
     $packageParams = $request->getPackageParams();
     $height = $packageParams->getHeight();
     $width = $packageParams->getWidth();
     $length = $packageParams->getLength();
     $girth = $packageParams->getGirth();
     $packageWeight = $request->getPackageWeight();
     if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::POUND) {
         $packageWeight = $this->_carrierHelper->convertMeasureWeight($request->getPackageWeight(), $packageParams->getWeightUnits(), \Zend_Measure_Weight::POUND);
     }
     if ($packageParams->getDimensionUnits() != \Zend_Measure_Length::INCH) {
         $length = round($this->_carrierHelper->convertMeasureDimension($packageParams->getLength(), $packageParams->getDimensionUnits(), \Zend_Measure_Length::INCH));
         $width = round($this->_carrierHelper->convertMeasureDimension($packageParams->getWidth(), $packageParams->getDimensionUnits(), \Zend_Measure_Length::INCH));
         $height = round($this->_carrierHelper->convertMeasureDimension($packageParams->getHeight(), $packageParams->getDimensionUnits(), \Zend_Measure_Length::INCH));
     }
     if ($packageParams->getGirthDimensionUnits() != \Zend_Measure_Length::INCH) {
         $girth = round($this->_carrierHelper->convertMeasureDimension($packageParams->getGirth(), $packageParams->getGirthDimensionUnits(), \Zend_Measure_Length::INCH));
     }
     $container = $request->getPackagingType();
     switch ($container) {
         case 'VARIABLE':
             $container = 'VARIABLE';
             break;
         case 'FLAT RATE ENVELOPE':
             $container = 'FLATRATEENV';
             break;
         case 'FLAT RATE BOX':
             $container = 'FLATRATEBOX';
             break;
         case 'RECTANGULAR':
             $container = 'RECTANGULAR';
             break;
         case 'NONRECTANGULAR':
             $container = 'NONRECTANGULAR';
             break;
         default:
             $container = 'VARIABLE';
     }
     $shippingMethod = $request->getShippingMethod();
     list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode());
     // the wrap node needs for remove xml declaration above
     $xmlWrap = $this->_xmlElFactory->create(['data' => '<?xml version = "1.0" encoding = "UTF-8"?><wrap/>']);
     $method = '';
     $service = $this->getCode('service_to_code', $shippingMethod);
     if ($service == 'Priority') {
         $method = 'Priority';
         $rootNode = 'PriorityMailIntlRequest';
         $xml = $xmlWrap->addChild($rootNode);
     } else {
         if ($service == 'First Class') {
             $method = 'FirstClass';
             $rootNode = 'FirstClassMailIntlRequest';
             $xml = $xmlWrap->addChild($rootNode);
         } else {
             $method = 'Express';
             $rootNode = 'ExpressMailIntlRequest';
             $xml = $xmlWrap->addChild($rootNode);
         }
     }
     $xml->addAttribute('USERID', $this->getConfigData('userid'));
     $xml->addAttribute('PASSWORD', $this->getConfigData('password'));
     $xml->addChild('Option');
     $xml->addChild('Revision', self::DEFAULT_REVISION);
     $xml->addChild('ImageParameters');
     $xml->addChild('FromFirstName', $request->getShipperContactPersonFirstName());
     $xml->addChild('FromLastName', $request->getShipperContactPersonLastName());
     $xml->addChild('FromFirm', $request->getShipperContactCompanyName());
     $xml->addChild('FromAddress1', $request->getShipperAddressStreet2());
     $xml->addChild('FromAddress2', $request->getShipperAddressStreet1());
     $xml->addChild('FromCity', $request->getShipperAddressCity());
     $xml->addChild('FromState', $request->getShipperAddressStateOrProvinceCode());
     $xml->addChild('FromZip5', $fromZip5);
     $xml->addChild('FromZip4', $fromZip4);
     $xml->addChild('FromPhone', $request->getShipperContactPhoneNumber());
     if ($method != 'FirstClass') {
         if ($request->getReferenceData()) {
             $referenceData = $request->getReferenceData() . ' P' . $request->getPackageId();
         } else {
             $referenceData = $request->getOrderShipment()->getOrder()->getIncrementId() . ' P' . $request->getPackageId();
         }
         $xml->addChild('FromCustomsReference', 'Order #' . $referenceData);
     }
     $xml->addChild('ToFirstName', $request->getRecipientContactPersonFirstName());
     $xml->addChild('ToLastName', $request->getRecipientContactPersonLastName());
     $xml->addChild('ToFirm', $request->getRecipientContactCompanyName());
     $xml->addChild('ToAddress1', $request->getRecipientAddressStreet1());
     $xml->addChild('ToAddress2', $request->getRecipientAddressStreet2());
     $xml->addChild('ToCity', $request->getRecipientAddressCity());
     $xml->addChild('ToProvince', $request->getRecipientAddressStateOrProvinceCode());
     $xml->addChild('ToCountry', $this->_getCountryName($request->getRecipientAddressCountryCode()));
     $xml->addChild('ToPostalCode', $request->getRecipientAddressPostalCode());
     $xml->addChild('ToPOBoxFlag', 'N');
     $xml->addChild('ToPhone', $request->getRecipientContactPhoneNumber());
     $xml->addChild('ToFax');
     $xml->addChild('ToEmail');
     if ($method != 'FirstClass') {
         $xml->addChild('NonDeliveryOption', 'Return');
     }
     if ($method == 'FirstClass') {
         if (stripos($shippingMethod, 'Letter') !== false) {
             $xml->addChild('FirstClassMailType', 'LETTER');
         } else {
             if (stripos($shippingMethod, 'Flat') !== false) {
                 $xml->addChild('FirstClassMailType', 'FLAT');
             } else {
                 $xml->addChild('FirstClassMailType', 'PARCEL');
             }
         }
     }
     if ($method != 'FirstClass') {
         $xml->addChild('Container', $container);
     }
     $shippingContents = $xml->addChild('ShippingContents');
     $packageItems = $request->getPackageItems();
     // get countries of manufacture
     $countriesOfManufacture = [];
     $productIds = [];
     foreach ($packageItems as $itemShipment) {
         $item = new \Magento\Framework\Object();
         $item->setData($itemShipment);
         $productIds[] = $item->getProductId();
     }
     $productCollection = $this->_productCollectionFactory->create()->addStoreFilter($request->getStoreId())->addFieldToFilter('entity_id', ['in' => $productIds])->addAttributeToSelect('country_of_manufacture');
     foreach ($productCollection as $product) {
         $countriesOfManufacture[$product->getId()] = $product->getCountryOfManufacture();
     }
     $packagePoundsWeight = $packageOuncesWeight = 0;
     // for ItemDetail
     foreach ($packageItems as $itemShipment) {
         $item = new \Magento\Framework\Object();
         $item->setData($itemShipment);
         $itemWeight = $item->getWeight() * $item->getQty();
         if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::POUND) {
             $itemWeight = $this->_carrierHelper->convertMeasureWeight($itemWeight, $packageParams->getWeightUnits(), \Zend_Measure_Weight::POUND);
         }
         if (!empty($countriesOfManufacture[$item->getProductId()])) {
             $countryOfManufacture = $this->_getCountryName($countriesOfManufacture[$item->getProductId()]);
         } else {
             $countryOfManufacture = '';
         }
         $itemDetail = $shippingContents->addChild('ItemDetail');
         $itemDetail->addChild('Description', $item->getName());
         $ceiledQty = ceil($item->getQty());
         if ($ceiledQty < 1) {
             $ceiledQty = 1;
         }
         $individualItemWeight = $itemWeight / $ceiledQty;
         $itemDetail->addChild('Quantity', $ceiledQty);
         $itemDetail->addChild('Value', $item->getCustomsValue() * $item->getQty());
         list($individualPoundsWeight, $individualOuncesWeight) = $this->_convertPoundOunces($individualItemWeight);
         $itemDetail->addChild('NetPounds', $individualPoundsWeight);
         $itemDetail->addChild('NetOunces', $individualOuncesWeight);
         $itemDetail->addChild('HSTariffNumber', 0);
         $itemDetail->addChild('CountryOfOrigin', $countryOfManufacture);
         list($itemPoundsWeight, $itemOuncesWeight) = $this->_convertPoundOunces($itemWeight);
         $packagePoundsWeight += $itemPoundsWeight;
         $packageOuncesWeight += $itemOuncesWeight;
     }
     $additionalPackagePoundsWeight = floor($packageOuncesWeight / self::OUNCES_POUND);
     $packagePoundsWeight += $additionalPackagePoundsWeight;
     $packageOuncesWeight -= $additionalPackagePoundsWeight * self::OUNCES_POUND;
     if ($packagePoundsWeight + $packageOuncesWeight / self::OUNCES_POUND < $packageWeight) {
         list($packagePoundsWeight, $packageOuncesWeight) = $this->_convertPoundOunces($packageWeight);
     }
     $xml->addChild('GrossPounds', $packagePoundsWeight);
     $xml->addChild('GrossOunces', $packageOuncesWeight);
     if ($packageParams->getContentType() == 'OTHER' && $packageParams->getContentTypeOther() != null) {
         $xml->addChild('ContentType', $packageParams->getContentType());
         $xml->addChild('ContentTypeOther ', $packageParams->getContentTypeOther());
     } else {
         $xml->addChild('ContentType', $packageParams->getContentType());
     }
     $xml->addChild('Agreement', 'y');
     $xml->addChild('ImageType', 'PDF');
     $xml->addChild('ImageLayout', 'ALLINONEFILE');
     if ($method == 'FirstClass') {
         $xml->addChild('Container', $container);
     }
     // set size
     if ($packageParams->getSize()) {
         $xml->addChild('Size', $packageParams->getSize());
     }
     // set dimensions
     $xml->addChild('Length', $length);
     $xml->addChild('Width', $width);
     $xml->addChild('Height', $height);
     if ($girth) {
         $xml->addChild('Girth', $girth);
     }
     $xml = $xmlWrap->{$rootNode}->asXML();
     return $xml;
 }
Ejemplo n.º 30
0
 /**
  * Return widget XML configuration as \Magento\Framework\Object and makes some data preparations
  *
  * @param string $type Widget type
  * @return \Magento\Framework\Object
  */
 public function getConfigAsObject($type)
 {
     $widget = $this->getWidgetByClassType($type);
     $object = new \Magento\Framework\Object();
     if ($widget === null) {
         return $object;
     }
     $widget = $this->getAsCanonicalArray($widget);
     // Save all nodes to object data
     $object->setType($type);
     $object->setData($widget);
     // Correct widget parameters and convert its data to objects
     $newParams = $this->prepareWidgetParameters($object);
     $object->setData('parameters', $newParams);
     return $object;
 }