/**
  * @link http://www.php.net/manual/en/class.exception.php
  */
 public function __construct($message = "", $code = 0, Exception $previous = null)
 {
     $this->_logger = Mage::helper('ebayenterprise_magelog');
     $this->_context = Mage::helper('ebayenterprise_magelog/context');
     /**
      * @note This runs counter to our styleguide because it is
      * itself an exception. Furthermore we want to be both
      * inescapable and verbose with critical exceptions.
      */
     $this->_logger->critical($message, $this->_context->getMetaData(__CLASS__, [], $previous));
     parent::__construct($message, $code, $previous);
 }
 /**
  * Build the given batches into feed files.
  * @param  array of EbayEnterprise_Catalog_Model_Pim_Batch $batches
  * @return self
  */
 protected function _buildBatches(array $batches)
 {
     try {
         foreach ($batches as $batch) {
             Mage::getModel('ebayenterprise_catalog/pim', array('batch' => $batch))->buildFeed();
         }
         $this->_updateCutoffDate();
     } catch (EbayEnterprise_Eb2cCore_Exception_InvalidXml $e) {
         $logMessage = 'Error building export feeds';
         $this->_logger->critical($logMessage, $this->_context->getMetaData(__CLASS__, [], $e));
     }
     return $this;
 }
 /**
  * attempt to undo an allocation
  *
  * @param EbayEnterprise_Inventory_Model_Allocation_Reservation
  */
 public function rollback(EbayEnterprise_Inventory_Model_Allocation_Reservation $reservation)
 {
     $api = $this->prepareApi();
     try {
         $this->prepareRequest($api, $reservation);
         $api->send();
         return;
     } catch (InvalidPayload $e) {
         $this->logger->warning('The allocation rollback response payload is invalid.', $this->logContext->getMetaData(__CLASS__, [], $e));
     } catch (NetworkError $e) {
         $this->logger->warning('Failed sending the allocation rollback request.', $this->logContext->getMetaData(__CLASS__, [], $e));
     } catch (UnsupportedOperation $e) {
         $this->logger->critical('Allocation rollback is unsupported in the currently configured SDK.', $this->logContext->getMetaData(__CLASS__, [], $e));
     } catch (UnsupportedHttpAction $e) {
         $this->logger->critical('Allocation rollback configured to use unsupported HTTP action.', $this->logContext->getMetaData(__CLASS__, [], $e));
     }
 }
 /**
  * fetch the tender type for the given card account
  *
  * @param string
  * @return string
  * @throws EbayEnterprise_GiftCard_Exception_TenderTypeLookupFailed_Exception
  *         if the tender type cannot be retrieved for the account
  */
 public function getTenderType()
 {
     try {
         $this->prepareApiForSend();
         $this->api->send();
         return $this->processResponse($this->api->getResponseBody());
     } catch (EbayEnterprise_GiftCard_Exception_TenderTypeLookupFailed_Exception $e) {
         $this->logger->error('The service reported the tender type lookup as unsuccessful.', $this->logContext->getMetaData(__CLASS__, [], $e));
     } catch (InvalidPayload $e) {
         $this->logger->warning('Either the request or the response for the tender type lookup contains invalid data.', $this->logContext->getMetaData(__CLASS__, [], $e));
     } catch (NetworkError $e) {
         $this->logger->warning('There was a network error when attempting to fetch the tender type', $this->logContext->getMetaData(__CLASS__, [], $e));
     } catch (UnsupportedOperation $e) {
         $this->logger->critical('The tender type lookup operation is unsupported in the current configuration.', $this->logContext->getMetaData(__CLASS__, [], $e));
     } catch (UnsupportedHttpAction $e) {
         $this->logger->critical('The tender type lookup is configured with an unsupported HTTP action', $this->logContext->getMetaData(__CLASS__, [], $e));
     }
     // we only care if we were able to get the tender type or not, so
     // boil all errors down to a single exception
     throw $this->createUnsuccessfulOperationException();
 }
 /**
  * get the locale code for the order
  *
  * @return string
  */
 protected function _getLocale()
 {
     $languageCode = $this->_coreHelper->getConfigModel()->setStore($this->_order->getStore())->languageCode;
     $splitCode = explode('-', $languageCode);
     if (!empty($splitCode[0]) && !empty($splitCode[1])) {
         $result = strtolower($splitCode[0]) . '_' . strtoupper($splitCode[1]);
     } else {
         $logData = ['order_id' => $this->_order->getIncrementId(), 'language_code' => $languageCode];
         $this->_logger->critical("The store for order '{order_id}' is configured with an invalid language code: '{language_code}'", $this->_logContext->getMetaData(__CLASS__, $logData));
         $result = '';
     }
     return $result;
 }
 /**
  * Determine the type of exception and logged it accordingly.
  *
  * @param  Exception
  * @return self
  */
 protected function _processException(Exception $e)
 {
     if ($e instanceof NetworkError) {
         $logMessage = "Caught a network error sending {$this->_getPayloadName()}. Will retry later.";
         $this->_logger->warning($logMessage, $this->_getLogContext($e));
     } elseif ($e instanceof UnsupportedOperation || $e instanceof UnsupportedHttpAction) {
         $logMessage = "{$this->_getPayloadName()} request could not be sent. Please check your configuration.";
         $this->_logger->critical($logMessage, $this->_getLogContext($e));
     } else {
         $logMessage = "Encountered a fatal error attempting to send {$this->_getPayloadName()} request.";
         $this->_logger->warning($logMessage, $this->_getLogContext($e));
     }
     return $this;
 }
 /**
  * fill out the request payload to send
  *
  * @param IBidirectionalApi
  * @param EbayEnterprise_Inventory_Model_Allocation_Item_Selector
  * @return self
  */
 protected function prepareRequest(IBidirectionalApi $api, EbayEnterprise_Inventory_Model_Allocation_Item_Selector $selector)
 {
     $this->logger->debug('Building inventory allocation request reservation id {reservation_id}', $this->logContext->getMetaData(__CLASS__, ['reservation_id' => $this->reservation->getId()]));
     try {
         $request = $api->getRequestBody();
         $builder = $this->createRequestBuilder($request, $selector, $this->reservation);
         $builder->buildOutRequest();
         $api->setRequestBody($request);
         return $this;
     } catch (UnsupportedOperation $e) {
         $this->logger->critical('The inventory allocation operation is unsupported in the current configuration. See exception log for more details.', $this->logContext->getMetaData(__CLASS__, ['exception_message' => $e->getMessage()]));
         $this->logger->logException($e, $this->logContext->getMetaData(__CLASS__, [], $e));
     }
     $this->handleAllocationFailure();
 }
 /**
  * Extract quantity results from the API response body.
  *
  * @param IBidirectionalApi
  * @param Mage_Sales_Model_Order_Quote_Item[]
  * @return EbayEnterprise_Inventory_Model_Quantity_Results
  */
 protected function _extractResponseResults(IBidirectionalApi $api, array $items)
 {
     try {
         $responseBody = $api->getResponseBody();
     } catch (UnsupportedOperation $e) {
         // This exception handling is probably not necessary but
         // is technically possible. If the sdk flow of
         // getRequest->setRequest->send->getResponse is followed,
         // which is is by the one public method of this class, this
         // exception should never be thrown in this instance. If it
         // were to be thrown at all by the SDK, it would have already
         // happened during the "send" step.
         $this->_logger->critical('Inventory quantity service response unsupported by SDK.', $this->_logContext->getMetaData(__CLASS__, [], $e));
         throw $this->_failQuantityCollection();
     }
     $responseParser = $this->_inventoryQuantityFactory->createResponseParser($responseBody);
     return $this->_inventoryQuantityFactory->createQuantityResults($responseParser->getQuantityResults(), $items);
 }
 /**
  * Extract tax records from the API response body for the quote.
  *
  * @param IBidirectionalApi
  * @param Mage_Sales_Model_Order_Quote
  * @return EbayEnterprise_Tax_Model_Result
  */
 protected function _extractResponseResults(IBidirectionalApi $api, Mage_Sales_Model_Quote $quote)
 {
     try {
         $responseBody = $api->getResponseBody();
     } catch (UnsupportedOperation $e) {
         // This exception handling is probably not necessary but
         // is technically possible. If the sdk flow of
         // getRequest->setRequest->send->getResponse is followed,
         // which is is by the one public method of this class, this
         // exception should never be thrown in this instance. If it
         // were to be thrown at all by the SDK, it would have already
         // happened during the "send" step.
         $this->logger->critical('Tax quote service response unsupported by SDK.', $this->logContext->getMetaData(__CLASS__, [], $e));
         throw $this->_failTaxCollection();
     }
     $responseParser = $this->taxFactory->createResponseQuoteParser($responseBody, $quote);
     return $this->taxFactory->createTaxResults($responseParser->getTaxRecords(), $responseParser->getTaxDuties(), $responseParser->getTaxFees());
 }
 /**
  * fill out the request payload to send
  *
  * @param IBidirectionalApi
  * @param EbayEnterprise_Inventory_Model_Allocation_Item_Selector
  * @return self
  */
 protected function prepareRequest(IBidirectionalApi $api, EbayEnterprise_Inventory_Model_Allocation_Item_Selector $selector)
 {
     $this->logger->debug('Building inventory allocation request reservation id {reservation_id}', $this->logContext->getMetaData(__CLASS__, ['reservation_id' => $this->reservation->getId()]));
     try {
         $request = $api->getRequestBody();
         $builder = $this->createRequestBuilder($request, $selector, $this->reservation);
         $builder->buildOutRequest();
         // rule out the possibility of exceptions from the request
         // being thrown during the send.
         $request->serialize();
         $api->setRequestBody($request);
         return $request;
     } catch (UnsupportedOperation $e) {
         $this->logger->critical('The allocation operation is unsupported by the currently configured SDK', $this->logContext->getMetaData(__CLASS__, [], $e));
     } catch (InvalidPayload $e) {
         $this->logger->error('The allocation request is invalid', $this->logContext->getMetaData(__CLASS__, [], $e));
     }
     $this->handleAllocationFailure();
 }
 /**
  * get all exported files and a list of acknowledgment files imported
  * loop through all the exported files and check if each exported files has an imported acknowledgment file
  * in the list of acknowledgment files, if the file is in the list of
  * acknowledgment file, then simply move the exported to export_archive and the acknowledgment file to import_archive
  * otherwise the exported file has no acknowledgment therefore, check the created time of
  * exported file if is greater than the configurable elapse time simply move it back to
  * out-box to be exported again, however if the elapse time is less than the configurable
  * simply ignore the file
  * @return self
  */
 public function process()
 {
     $exportedList = $this->_listFilesByCfgKey(self::CFG_EXPORTED_FEED_DIR);
     if (!empty($exportedList)) {
         $importedList = $this->_getImportedAckFiles();
         foreach ($exportedList as $exported) {
             $ack = $this->_getAck($exported, $importedList);
             if (!is_null($ack)) {
                 $this->_mvTo($exported, self::CFG_EXPORT_ARCHIVE)->_mvTo($ack, self::CFG_IMPORT_ARCHIVE);
             } elseif ($this->_isTimedOut($exported)) {
                 // create the error directory since it's not automatically created
                 // when processing the feeds
                 $this->_coreHelper->createDir($this->_buildPath(self::CFG_ERROR_DIRECTORY));
                 $this->_mvTo($exported, self::CFG_ERROR_DIRECTORY);
                 $this->_logger->critical('{file_name} was not acknowledged by Product Hub', $this->_context->getMetaData(__CLASS__, ['file_name' => $exported]));
             }
         }
     }
     return $this;
 }
 /**
  * Validate the SFTP configuration by first checking for any obviously invalid
  * settings - e.g. missing/empty values - then by making a test connection
  * using the given credential.
  *
  * @param string $host
  * @param string $username
  * @param string $privateKey
  * @param int $port
  * @return array
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function testSftpConnection($host, $username, $privateKey, $port)
 {
     try {
         $this->_validateSftpSettings($host, $username, $privateKey, $port);
     } catch (EbayEnterprise_Eb2cCore_Exception_Sftp_Configuration $e) {
         return ['message' => $e->getMessage(), 'success' => false];
     }
     $configMap = Mage::getSingleton('eb2ccore/config');
     $sftp = Mage::helper('filetransfer')->getProtocolModel($configMap->getPathForKey('sftp_config'));
     $sftp->getConfigModel()->setHost($host)->setUsername($username)->setPrivateKey($privateKey)->setPort($port);
     $helper = $this->_helper;
     $resp = [];
     // When the Net_SFTP instance failes to connect, it will trigger an error
     // instead of throwing an exception. Convert the error to an exception
     // so it can halt execution and be caught.
     set_error_handler(function ($errno, $errstr) {
         throw new EbayEnterprise_Eb2cCore_Exception_Sftp_Configuration($errstr);
     }, E_USER_NOTICE);
     try {
         $sftp->connect()->login();
     } catch (EbayEnterprise_Eb2cCore_Exception_Sftp_Configuration $e) {
         $this->_logger->critical($e->getMessage(), $this->_context->getMetaData(__CLASS__, [], $e));
         $resp = ['message' => $helper->__(self::INVALID_SFTP_CONNECTION), 'success' => false];
     } catch (EbayEnterprise_FileTransfer_Exception_Authentication $e) {
         $this->_logger->critical($e->getMessage(), $this->_context->getMetaData(__CLASS__, [], $e));
         $resp = ['message' => $helper->__(self::INVALID_SFTP_AUTHENTICATION_CONFIG), 'success' => false];
     }
     // Restore the error handler to get rid of the exception throwing one.
     restore_error_handler();
     // Final check, if the connection is logged in, everything went as planned
     // and the connection has been made. If not, and the reason for it has not
     // yet been dicovered by the exception handling above, just give a lame
     // indication that the connection could not be made.
     if ($sftp->isLoggedIn()) {
         $resp = ['message' => $helper->__(self::SFTP_CONNECTION_SUCCESS), 'success' => true];
     } elseif (empty($resp)) {
         $resp = ['message' => $helper->__(self::SFTP_CONNECTION_FAILED), 'success' => false];
     }
     return $resp;
 }