diff --git a/BaseProvider/Api/Data/QueueInterface.php b/BaseProvider/Api/Data/QueueInterface.php new file mode 100644 index 00000000..3db1a13a --- /dev/null +++ b/BaseProvider/Api/Data/QueueInterface.php @@ -0,0 +1,172 @@ +clientFactory = $clientFactory; + $this->responseFactory = $responseFactory; + $this->catchExceptions = true; + } + + /** + * Set ApiClient + * + * @param string $endPointBaseUrl + * @param string $accessToken + * @param string $responseType + * @param string $mode + * @param string $appName + * @param string $appVersion + * @param string $machineName + * @param string $authType + * @return ApiClient + */ + public function setClient( + string $endPointBaseUrl, + $accessToken = '', + $responseType = 'array', + $mode = 'sandbox', + $appName = '', + $appVersion = '1.0', + $machineName = 'localhost', + $authType = 'Bearer' + ) { + $this->endPointBaseUrl = $endPointBaseUrl; + $this->accessToken = $accessToken; + $this->responseType = $responseType; + $this->mode = $mode; + $this->appName = $appName; + $this->appVersion = $appVersion; + $this->machineName = $machineName; + $this->authType = $authType; + return $this; + } + + /** + * RestCall with provided params + * + * @param array $params + * @param string $requestMethod + * + * @throws \GuzzleHttp\Exception\GuzzleException + * @throws \Exception + */ + public function restCall( + array $params = [], + string $requestMethod = Request::HTTP_METHOD_GET, + $getArray = false + ) { + /** @var Client $client */ + $client = $this->clientFactory->create(['config' => [ + 'base_uri' => $this->endPointBaseUrl + ]]); + + if ($this->machineName == null) { + $this->machineName = ""; + } + + $params = $this->addHeaders($params); + // pass additional headers + if ($this->additionalParams) { + foreach ($this->additionalParams as $key => $value) { + $params['headers'][$key] = $value; + } + } + + $params['timeout'] = isset($params['timeout']) ? (int) $params['timeout'] : 1200; + + try { + $endPointUri = ''; + if (isset($params['endpoint']) && ($params['endpoint'] != '')) { + $endPointUri = $params['endpoint']; + } + $response = $client->request( + $requestMethod, + $endPointUri, + $params + ); + $body = (string) $response->getBody(); + $JsonBody = json_decode($body, $getArray); + if (($this->responseType == 'array') && (!is_null($JsonBody))) { + return $JsonBody; + } else { + return $body; + } + } catch (\Exception $e) { + if (!$this->catchExceptions) { + throw $e; + } + return $e->getMessage(); + } + } + + /** + * add headers + * + * @param array $params + * @return array + */ + protected function addHeaders($params) + { + if (!isset($params['headers']['Accept'])) { + $params['headers']['Accept'] = 'application/json'; + } + if (!isset($params['headers']['Content-Type'])) { + $params['headers']['Content-Type'] = 'application/json'; + } + if (!isset($params['headers']['Authorization'])) { + $params['headers']['Authorization'] = $this->authType . ' '; + if ($this->accessToken != '') { + $params['headers']['Authorization'] = $params['headers']['Authorization'] . $this->accessToken; + } + } + + if (!isset($params['headers']['X-Avalara-Client']) && $this->authType == 'Bearer') { + $params['headers']['X-Avalara-Client'] = "{$this->appName}; {$this->appVersion}; PhpRestClient; 20.12.1; {$this->machineName}"; + } + return $params; + } + + /** + * Configure this client to use the specified username/password security settings + * + * @param string $username The username for your AvaTax user account + * @param string $password The password for your AvaTax user account + * @return ApiClient + */ + public function withSecurity($username, $password) + { + $this->auth = [$username, $password]; + return $this; + } + + /** + * Configure this client to use Account ID / License Key security + * + * @param int $accountId The account ID for your AvaTax account + * @param string $licenseKey The private license key for your AvaTax account + * @return ApiClient + */ + public function withLicenseKey($accountId, $licenseKey) + { + $this->auth = [$accountId, $licenseKey]; + return $this; + } + + /** + * Set additional headers + * + * @param array $params + * @return ApiClient + */ + public function addtionalHeaders($params) + { + $this->additionalParams = $params; + return $this; + } + + /** + * Configure this client to use bearer token + * + * @param string $bearerToken The private bearer token for your AvaTax account + * @return ApiClient + */ + public function withBearerToken($bearerToken) + { + $this->auth = [$bearerToken]; + return $this; + } + + /** + * Configure this client to use Account ID / License Key security + * + * @param int $accountId The account ID for your AvaTax account + * @param string $licenseKey The private license key for your AvaTax account + * @return ApiClient + */ + public function withBasicToken($accountId, $licenseKey) + { + // Third element '3' added to the array to support multiple authentication methods + $this->auth = ['type', base64_encode($accountId . ":" . $licenseKey), '3']; + return $this; + } + + /** + * Configure the client to either catch web request exceptions and return a message or throw the exception + * + * @param bool $catchExceptions + * @return ApiClient + */ + public function withCatchExceptions($catchExceptions = true) + { + $this->catchExceptions = $catchExceptions; + return $this; + } + + /** + * Return the client object, for extended class(es) to retrive the client object + * + * @return ApiClient + */ + public function getClient() + { + return $this; + } +} diff --git a/BaseProvider/Helper/Application/Config.php b/BaseProvider/Helper/Application/Config.php new file mode 100644 index 00000000..71cc7a63 --- /dev/null +++ b/BaseProvider/Helper/Application/Config.php @@ -0,0 +1,59 @@ +scopeConfig->getValue(self::XML_PATH_APPLICATION_LOG_ENABLED); + } + + /** + * Return configured log detail + * + * @return int + */ + public function getLogMode() + { + return (int)$this->scopeConfig->getValue(self::XML_PATH_AVATAX_APPLICATION_LOG_MODE); + } + + /** + * Return configured log limit + * + * @return int + */ + public function getLogLimit() + { + return (int)$this->scopeConfig->getValue(self::XML_PATH_AVATAX_APPLICATION_LOG_LIMIT); + } +} diff --git a/BaseProvider/Helper/Config.php b/BaseProvider/Helper/Config.php new file mode 100644 index 00000000..f4b084d4 --- /dev/null +++ b/BaseProvider/Helper/Config.php @@ -0,0 +1,46 @@ +scopeConfig->getValue(self::XML_PATH_AVATAX_QUEUE_BATCH_SIZE); + } + + /** + * Return configured Queue limit + * + * @return int + */ + public function getQueueLimit() + { + return (int) $this->scopeConfig->getValue(self::XML_PATH_AVATAX_QUEUE_LIMIT); + } +} diff --git a/BaseProvider/Helper/Generic/Config.php b/BaseProvider/Helper/Generic/Config.php new file mode 100644 index 00000000..045c23d4 --- /dev/null +++ b/BaseProvider/Helper/Generic/Config.php @@ -0,0 +1,207 @@ + 'Performance', + self::API_LOG_TYPE_DEBUG => 'Debug', + self::API_LOG_TYPE_CONFIG => 'ConfigAudit' + ]; + + /** + * Api Log Levels + */ + const API_LOG_LEVEL = [ + self::API_LOG_LEVEL_ERROR => 'Error', + self::API_LOG_LEVEL_EXCEPTION => 'Exception', + self::API_LOG_LEVEL_INFO => 'Informational' + ]; + + /** + * Sandbox API URL for LOGGER + */ + const ENV_LOGGER_SANDBOX_BASE_URL = 'https://ceplogger.sbx.avalara.com'; + + /** + * Production API URL for LOGGER + */ + const ENV_LOGGER_PRODUCTION_BASE_URL = 'https://ceplogger.avalara.com'; + + /** + * Endpoint for logger + */ + const API_LOGGER_ENDPOINT = '/api/logger/'; + + /** + * String value of API mode + */ + const API_MODE_PRODUCTION = 'production'; + + /** + * String value of API mode + */ + const API_MODE_SANDBOX = 'sandbox'; + + /** + * ERP details of application + */ + const ERP_DETAILS = "MAGENTO"; + + /** + * @var TimezoneInterface + */ + protected $timeZone; + + /** + * @var UrlInterface + */ + protected $urlInterface; + + /** + * @var ProductMetadataInterface + */ + protected $mageMetadata = null; + + /** + * Class constructor + * + * @param Context $context + * @param TimezoneInterface $timeZone + */ + public function __construct( + Context $context, + TimezoneInterface $timeZone, + UrlInterface $urlInterface, + ProductMetadataInterface $mageMetadata + ) { + parent::__construct($context); + $this->timeZone = $timeZone; + $this->urlInterface = $urlInterface; + $this->mageMetadata = $mageMetadata; + } + + /** + * Returns current store time zone object + * + * @return TimezoneInterface + */ + public function getTimeZoneObject() + { + return $this->timeZone; + } + + /** + * Generate Avalara Application Name from a combination of Magento version number and Avalara module name + * Format: Magento 2.x Community - Avalara + * Limited to 50 characters to comply with API requirements + * + * @return string + */ + public function getApplicationName() + { + return substr($this->mageMetadata->getName(), 0, 7) . ' ' . // "Magento" - 8 chars + substr( + $this->mageMetadata->getVersion(), + 0, + 14 + ) . ' ' . // 2.x & " " - 50 - 8 - 13 - 14 = 15 chars + substr( + $this->mageMetadata->getEdition(), + 0, + 10 + ) . ' - ' . // "Community - "|"Enterprise - " - 13 chars + 'Avalara'; + } + + /** + * Get the base URL minus protocol and trailing slash, for use as machine name in API requests + * + * @return string + */ + public function getMachineName() + { + $domain = $this->urlInterface->getBaseUrl(); + $domain = preg_replace('#^https?://#', '', $domain); + return preg_replace('#/$#', '', $domain); + } + + /** + * Prepare Basic Auth Token + * + * @param string $accountSecret + * @param string $accountSecret + * @return string + */ + public function prepareBasicAuthToken($accountNumber, $accountSecret) + { + return base64_encode($accountNumber . ":" . $accountSecret); + } + + /** + * Validate Record + * + * @param $record array + * @return boolean + */ + public function validateRecord(array $record) + { + $exception = []; + + if (!isset($record['config'])) { + $exception[] = "Configuration parameters are missing for API Logging."; + } else { + if (!isset($record['config']['account_number'])) { + $exception[] = "account_number parameters is missing for API Logging."; + } + if (!(isset($record['config']['auth']) && $record['config']['auth'] == "Bearer") && !isset($record['config']['account_secret'])) { + $exception[] = "account_secret parameters is missing for API Logging."; + } + if (!isset($record['config']['connector_id'])) { + $exception[] = "connector_id parameters is missing for API Logging."; + } + if (!isset($record['config']['client_string'])) { + $exception[] = "client_string parameters is missing for API Logging."; + } + } + + if (empty($exception)) { + return true; + } + + return false; + } +} diff --git a/BaseProvider/LICENSE.txt b/BaseProvider/LICENSE.txt new file mode 100644 index 00000000..52ac7aeb --- /dev/null +++ b/BaseProvider/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright � 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/BaseProvider/Logger/ApplicationLogger.php b/BaseProvider/Logger/ApplicationLogger.php new file mode 100644 index 00000000..d4ae6527 --- /dev/null +++ b/BaseProvider/Logger/ApplicationLogger.php @@ -0,0 +1,41 @@ +addRecord(static::API_LOG, $message, $context); + } + + /** + * Adds a log record at the API_LOG level. + * + * This method allows for compatibility with common interfaces. + * + * @param string $message The log message + * @param array $context The log context + * @return bool Whether the record has been processed + */ + public function apiLog($message, array $context = array()) + { + return $this->addRecord(static::API_LOG, $message, $context); + } +} diff --git a/BaseProvider/Logger/Handler/Application/DbHandler.php b/BaseProvider/Logger/Handler/Application/DbHandler.php new file mode 100644 index 00000000..6bcc3e60 --- /dev/null +++ b/BaseProvider/Logger/Handler/Application/DbHandler.php @@ -0,0 +1,126 @@ +logFactory = $logFactory; + $this->loggerConfig = $config; + parent::__construct(Logger::DEBUG, true); + } + + /** + * Checks whether the given record will be handled by this handler. + * + * Uses the admin configuration settings to determine if the record should be handled + * + * @param array $record + * @return Boolean + */ + public function isHandling(array $record) : bool + { + return $this->loggerConfig->getLogEnabled() && ($this->loggerConfig->getLogMode() == LoggingMode::LOGGING_MODE_DB); + } + + /** + * Writes the log to the database by utilizing the Log model + * + * @param $record array + * @return void + */ + public function write(array $record) : void + { + parent::write($record); + # Log to database + /** @var \ClassyLlama\AvaTax\BaseProvider\Model\Log $log */ + $log = $this->logFactory->create(); + + $log->setData('level', isset($record['level_name']) ? $record['level_name'] : null); + $log->setData('message', isset($record['message']) ? $record['message'] : null); + + if (isset($record['extra']['store_id'])) { + $log->setData('store_id', $record['extra']['store_id']); + unset($record['extra']['store_id']); + } + if (isset($record['context']['extra']['class'])) { + $log->setData('source', $record['context']['extra']['class']); + } elseif (isset($record['extra']['class']) && isset($record['extra']['line'])) { + $log->setData('source', $record['extra']['class'] . " [line:" . $record['extra']['line'] . "]"); + } + + $log->setData('request', $this->getRequest($record)); + $log->setData('result', $this->getResult($record)); + $log->setData( + 'additional', + $this->getExtraVarExport($record) + ); + $log->save(); + } + + /** + * If the record contains a context key + * export the variable contents and return it + * + * @param array $record + * @return string + */ + protected function getContextVarExport(array $record) + { + $string = ""; + if (isset($record['context']) && count($record['context']) > 0) { + $string = 'context: ' . var_export($record['context'], true); + } + return $string; + } + + /** + * If the record contains a extra key in the context + * export the variable contents, return it, and remove the element from the context array + * + * @param array $record + * @return string + */ + protected function getExtraVarExport(array $record) + { + $string = ""; + if (isset($record['extra']) && count($record['extra']) > 0) { + $string = 'extra: ' . var_export($record['extra'], true); + } + return $string; + } +} diff --git a/BaseProvider/Logger/Handler/Application/FileHandler.php b/BaseProvider/Logger/Handler/Application/FileHandler.php new file mode 100644 index 00000000..4af48fba --- /dev/null +++ b/BaseProvider/Logger/Handler/Application/FileHandler.php @@ -0,0 +1,119 @@ +loggerConfig = $config; + $this->filesystem = $filesystem; + + parent::__construct( + $filesystem, + self::FILEPATH, + $this->getFileName() + ); + + // Set our custom formatter so that the context and extra parts of the record will print on multiple lines + $this->setFormatter(new LineFormatter()); + $introspectionProcessor = new IntrospectionProcessor(); + $webProcessor = new WebProcessor(); + $this->addExtraProcessors([$introspectionProcessor, $webProcessor]); + } + + public function getFileName() + { + return self::FILENAME . '-' . date('d-m-y') . ".log"; + } + + /** + * Checking config a value, and conditionally adding extra processors to the handler + * + * @param array $processors + */ + protected function addExtraProcessors(array $processors) + { + $this->processors = $processors; + } + + /** + * Checks whether the given record will be handled by this handler. + * + * Uses the admin configuration settings to determine if the record should be handled + * + * @param array $record + * @return Boolean + */ + public function isHandling(array $record) : bool + { + return $this->loggerConfig->getLogEnabled() && ($this->loggerConfig->getLogMode() == LoggingMode::LOGGING_MODE_FILE); + } + + /** + * Writes the log to the filesystem + * + * @param $record array + * @return void + */ + public function write(array $record) : void + { + // Custom parsing can be added here + parent::write($record); + } +} diff --git a/BaseProvider/Logger/Handler/BaseAbstractHandler.php b/BaseProvider/Logger/Handler/BaseAbstractHandler.php new file mode 100644 index 00000000..545f4511 --- /dev/null +++ b/BaseProvider/Logger/Handler/BaseAbstractHandler.php @@ -0,0 +1,127 @@ +setFormatter(new LineFormatter(null, null, true)); + $introspectionProcessor = new IntrospectionProcessor(); + $webProcessor = new WebProcessor(); + $this->addExtraProcessors([$introspectionProcessor, $webProcessor]); + } + + /** + * Checking config a value, and conditionally adding extra processors to the handler + * + * @param array $processors + */ + protected function addExtraProcessors(array $processors) + { + $this->processors = $processors; + } + + /** + * {@inheritdoc} + */ + public function handle(array $record) : bool + { + if (!$this->isHandling($record)) { + return false; + } + + $record = $this->processRecord($record); + #$record['formatted'] = $this->getFormatter()->format($record); + $record['formatted'] = $record; + $this->write($record); + + return false === $this->bubble; + } + + /** + * Write log + * + * @param $record array + * @return void + */ + public function write(array $record) + { + if (empty($record)) { + throw new AvalaraLoggerException(__('No record found for logging.')); + } + } + + /** + * If the record contains a request key in the context + * return it, and remove the element from the context array + * + * @param array $record + * @return string + */ + protected function getRequest(array $record) + { + $string = ""; + if (isset($record['context']['request'])) { + $string = $record['context']['request']; + unset($record['context']['request']); + } + return $string; + } + + /** + * If the record contains a result key in the context + * return it, and remove the element from the context array + * + * @param array $record + * @return string + */ + protected function getResult(array $record) + { + $string = ""; + if (isset($record['context']['result'])) { + $string = $record['context']['result']; + unset($record['context']['result']); + } + return $string; + } + + /** + * Processes a record. + * + * @param array $record + * @return array + */ + protected function processRecord(array $record) + { + if ($this->processors) { + foreach ($this->processors as $processor) { + $record = call_user_func($processor, $record); + } + } + return $record; + } +} diff --git a/BaseProvider/Logger/Handler/Generic/ApiHandler.php b/BaseProvider/Logger/Handler/Generic/ApiHandler.php new file mode 100644 index 00000000..6f2d38c3 --- /dev/null +++ b/BaseProvider/Logger/Handler/Generic/ApiHandler.php @@ -0,0 +1,174 @@ +queueProducer = $queueProducer; + $this->loggerConfig = $config; + parent::__construct(GenericLogger::API_LOG, true); + } + + /** + * @param $record array + * @return array + */ + private function getApiConfig(array $record) + { + $apiConfig = []; + + $context = isset($record['context']) ? $record['context'] : []; + + if (empty($context)) { + return $apiConfig; + } + + foreach ($context as $key=>$data) { + if (!is_array($data)) { + continue; + } + if (empty($data)) { + continue; + } + if (isset($data['config'])) { + $apiConfig = $data; + break; + } + } + + return $apiConfig; + } + + /** + * Send log to the third party using API + * + * @param $record array + * @return void + */ + public function write(array $record) : void + { + $apiConfig = $this->getApiConfig($record); + $isValid = $this->loggerConfig->validateRecord($apiConfig); + + if ($isValid) { + + $accountNumber = $apiConfig['config']['account_number']; + $accountSecret = isset($apiConfig['config']['account_secret']) ? $apiConfig['config']['account_secret'] : ''; + $connectorId = $apiConfig['config']['connector_id']; + $connectorString = $apiConfig['config']['client_string']; + + $currentMode = isset($apiConfig['config']['mode']) ? $apiConfig['config']['mode'] : Config::API_MODE_SANDBOX; + $connectorName = isset($apiConfig['config']['connector_name']) ? $apiConfig['config']['connector_name'] : 'Magento Connectors'; + $connectorVersion = isset($apiConfig['config']['connector_version']) ? $apiConfig['config']['connector_version'] : '1.0.0'; + $source = isset($apiConfig['config']['source']) ? $apiConfig['config']['source'] : 'ConfigurationPage'; + $operation = isset($apiConfig['config']['operation']) ? $apiConfig['config']['operation'] : 'Test Connection'; + $logType = isset($apiConfig['config']['log_type']) ? $apiConfig['config']['log_type'] : Config::API_LOG_TYPE_CONFIG; + $logType = Config::API_LOG_TYPE[$logType]; + $logLevel = isset($apiConfig['config']['log_level']) ? $apiConfig['config']['log_level'] : Config::API_LOG_LEVEL_INFO; + $logLevel = Config::API_LOG_LEVEL[$logLevel]; + $functionName = isset($apiConfig['config']['function_name']) ? $apiConfig['config']['function_name'] : __METHOD__ ; + $accessToken = isset($apiConfig['config']['access_token']) ? $apiConfig['config']['access_token'] : $this->loggerConfig->prepareBasicAuthToken($accountNumber, $accountSecret); + $endPointBaseUrl = Config::ENV_LOGGER_PRODUCTION_BASE_URL; + $endPointUri = isset($apiConfig['config']['uri']) ? $apiConfig['config']['uri'] : Config::API_LOGGER_ENDPOINT.$connectorId; + $authType = isset($apiConfig['config']['auth']) ? $apiConfig['config']['auth'] : 'Basic'; + $returnType = isset($apiConfig['config']['return_type']) ? $apiConfig['config']['return_type'] : 'array'; + $machineName = isset($apiConfig['config']['machine_name']) ? $apiConfig['config']['machine_name'] : $this->loggerConfig->getMachineName(); + $headers = isset($apiConfig['config']['extra_headers']) ? $apiConfig['config']['extra_headers'] : []; + $extraParams = isset($apiConfig['config']['extra_params']) ? $apiConfig['config']['extra_params'] : []; + $requestMethod = isset($apiConfig['config']['request_method']) ? $apiConfig['config']['request_method'] : Request::HTTP_METHOD_POST; + + if ($currentMode == Config::API_MODE_SANDBOX) { + $endPointBaseUrl = Config::ENV_LOGGER_SANDBOX_BASE_URL; + } + if (isset($apiConfig['config']['base_url'])) { + $endPointBaseUrl = $apiConfig['config']['base_url']; + } + + $params = [ + "Source" => $source, + "Operation" => $operation, + "Message" => isset($record['message']) ? $record['message'] : '', + "LogType" => $logType, + "LogLevel" => $logLevel, + "FunctionName" => $functionName + ]; + + $params["CallerAccuNum"] = $accountNumber; + $params["AvaTaxEnvironment"] = ucwords($currentMode); + $params["ERPDetails"] = Config::ERP_DETAILS; + $params["ConnectorName"] = $connectorName; + $params["ConnectorVersion"] = $connectorVersion; + $params["ClientString"] = $connectorString; + + if (!empty($extraParams)) { + $params = array_merge($params, $extraParams); + } + + $params = [ + 'query' => [], + 'body' => json_encode($params) + ]; + + if (!empty($headers)) { + $params = array_merge($params, $headers); + } + + $params['endpoint'] = $endPointUri; + + $queueClient = \ClassyLlama\AvaTax\BaseProvider\Model\Queue\Consumer\ApiLogConsumer::CLIENT; + $payload = [ + "setClient" => [ + $endPointBaseUrl, + $accessToken, + $returnType, + $currentMode, + $connectorName, + $connectorVersion, + $machineName, + $authType + ], + "restCall" => [ + $params, + $requestMethod + ] + ]; + $payload = json_encode($payload); + $this->queueProducer->addJob($queueClient, $payload); + } + } +} diff --git a/BaseProvider/Logger/Processor.php b/BaseProvider/Logger/Processor.php new file mode 100644 index 00000000..ca3a9a48 --- /dev/null +++ b/BaseProvider/Logger/Processor.php @@ -0,0 +1,55 @@ +storeManager = $storeManager; + } + + /** + * Retrieves the current Store ID from Magento and adds it to the record + * + * @param array $record + * @return array + */ + public function __invoke(array $record) + { + // get the store_id and add it to the record + $store = $this->storeManager->getStore(); + $record['extra']['store_id'] = $store->getId(); + + return $record; + } +} diff --git a/BaseProvider/Model/Config/Source/Application/LoggingMode.php b/BaseProvider/Model/Config/Source/Application/LoggingMode.php new file mode 100644 index 00000000..36971b1c --- /dev/null +++ b/BaseProvider/Model/Config/Source/Application/LoggingMode.php @@ -0,0 +1,40 @@ + self::LOGGING_MODE_DB, + 'label' => __('Database') + ], + [ + 'value' => self::LOGGING_MODE_FILE, + 'label' => __('File') + ] + ]; + } + + public function toArray() + { + return [self::LOGGING_MODE_DB => __('Database'),self::LOGGING_MODE_FILE => __('File')]; + } +} diff --git a/BaseProvider/Model/Config/Source/Queue/Status.php b/BaseProvider/Model/Config/Source/Queue/Status.php new file mode 100644 index 00000000..74bd7333 --- /dev/null +++ b/BaseProvider/Model/Config/Source/Queue/Status.php @@ -0,0 +1,46 @@ + __('New'), + self::STATUS_PROCESSING => __('Processing'), + self::STATUS_COMPLETED => __('Completed'), + self::STATUS_FAILED => __('Failed') + ]; + return $options; + } + + public function toOptionArray() + { + $options = $this->toArray(); + $decoratedOptions = []; + if (count($options) > 0) { + foreach ($options as $value=>$label) { + $decoratedOptions[] = ['value'=>$value, 'label'=>$label]; + } + } + return $decoratedOptions; + } +} diff --git a/BaseProvider/Model/Log.php b/BaseProvider/Model/Log.php new file mode 100644 index 00000000..17108878 --- /dev/null +++ b/BaseProvider/Model/Log.php @@ -0,0 +1,43 @@ +_init(\ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Log::class); + } +} diff --git a/BaseProvider/Model/Log/Clear.php b/BaseProvider/Model/Log/Clear.php new file mode 100644 index 00000000..ad86a0f7 --- /dev/null +++ b/BaseProvider/Model/Log/Clear.php @@ -0,0 +1,118 @@ +applicationLogger = $applicationLogger; + $this->applicationLoggerConfig = $applicationLoggerConfig; + $this->logCollFactory = $logCollFactory; + $this->dateTime = $dateTime; + } + + /** + * Initiates the clear logs and queue process + * + * @return void + */ + public function process() + { + $this->applicationLogger->debug(__('Initiating log clearing from cron job')); + $size = $this->clearDbLogs(); + $this->applicationLogger->debug( + __('Completed log clearing from cron job. Total Deleted: ' . $size), + [ + 'delete_count' => $size, + 'extra' => [ + 'class' => __METHOD__ + ] + ] + ); + } + + /** + * Clear Db logs + * + * @return int + */ + public function clearDbLogs() + { + $limit = $this->applicationLoggerConfig->getLogLimit(); + if ($limit == '') { + return 0; + } + $filteredDate = $this->getFilterDate($limit); + $logs = $this->logCollFactory->create() + ->addFieldToFilter('created_at', ['lteq' => $filteredDate]); + $size = 0; + /* echo $logs->getSelect()->__toString(); */ + foreach ($logs as $log) { + try { + $log->delete(); + $size++; + } catch(\Exception $e) { + $e->getMessage(); + } + } + return $size; + } + + private function getFilterDate($days) + { + if ($days == 0) { + return $this->dateTime->gmtDate('Y-m-d'); + } else { + return $this->dateTime->gmtDate('Y-m-d', strtotime('-' . $days . ' day')); + } + + } +} diff --git a/BaseProvider/Model/Queue.php b/BaseProvider/Model/Queue.php new file mode 100644 index 00000000..239888fe --- /dev/null +++ b/BaseProvider/Model/Queue.php @@ -0,0 +1,177 @@ +_init(\ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Queue::class); + } + + /** + * @inheritDoc + */ + public function getId(){ + return $this->getData(self::JOB_ID); + } + + /** + * @inheritDoc + */ + public function getClient() + { + return $this->getData(self::CLIENT); + } + + /** + * @inheritDoc + */ + public function getPayload() + { + return $this->getData(self::PAYLOAD); + } + + /** + * @inheritDoc + */ + public function getResponse() + { + return $this->getData(self::RESPONSE); + } + + /** + * @inheritDoc + */ + public function getStatus() + { + return $this->getData(self::STATUS); + } + + /** + * @inheritDoc + */ + public function getAttempt() + { + return $this->getData(self::ATTEMPT); + } + + /** + * @inheritDoc + */ + public function getCreationTime() + { + return $this->getData(self::CREATION_TIME); + } + + /** + * @inheritDoc + */ + public function getUpdateTime() + { + return $this->getData(self::UPDATE_TIME); + } + + /** + * @inheritDoc + */ + public function setId($id) + { + return $this->setData(self::JOB_ID, $id); + } + + /** + * @inheritDoc + */ + public function setClient($client) + { + return $this->setData(self::CLIENT, $client); + } + + /** + * @inheritDoc + */ + public function setPayload($payload) + { + return $this->setData(self::PAYLOAD, $payload); + } + + /** + * @inheritDoc + */ + public function setResponse($response) + { + return $this->setData(self::RESPONSE, $response); + } + + /** + * @inheritDoc + */ + public function setStatus($status) + { + return $this->setData(self::STATUS, $status); + } + + /** + * @inheritDoc + */ + public function setAttempt($attempt) + { + return $this->setData(self::ATTEMPT, $attempt); + } + + /** + * @inheritDoc + */ + public function setCreationTime($creationTime) + { + return $this->setData(self::CREATION_TIME, $creationTime); + } + + /** + * @inheritDoc + */ + public function setUpdateTime($updateTime) + { + return $this->setData(self::UPDATE_TIME, $updateTime); + } + + /** + * @inheritDoc + */ + public function getExtensionAttributes() + { + return $this->_getExtensionAttributes(); + } + + /** + * @inheritDoc + */ + public function setExtensionAttributes(\ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueExtensionInterface $extensionAttributes) + { + $this->_setExtensionAttributes($extensionAttributes); + } +} diff --git a/BaseProvider/Model/Queue/Clear.php b/BaseProvider/Model/Queue/Clear.php new file mode 100644 index 00000000..5af43f2f --- /dev/null +++ b/BaseProvider/Model/Queue/Clear.php @@ -0,0 +1,113 @@ +logger = $logger; + $this->queueConfig = $queueConfig; + $this->queueCollFactory = $queueCollFactory; + $this->dateTime = $dateTime; + } + + /** + * Initiates the clear queues and queue process + * + * @return void + */ + public function process() + { + $this->logger->debug(__('Initiating queue clearing from cron job')); + $size = $this->clearDbQueues(); + $this->logger->debug( + __('Completed queue clearing from cron job. Total Deleted: ' . $size), + [ + 'delete_count' => $size, + 'extra' => [ + 'class' => __METHOD__ + ] + ] + ); + } + + public function clearDbQueues() + { + $limit = $this->queueConfig->getQueueLimit(); + if ($limit == '') { + return 0; + } + $filteredDate = $this->getFilterDate($limit); + $queues = $this->queueCollFactory->create() + ->addFieldToFilter('creation_time', ['lteq' => $filteredDate]); + $size = 0; + foreach ($queues as $queue) { + try { + $queue->delete(); + $size++; + } catch(\Exception $e) { + $this->logger->debug($e->getMessage()); + } + } + return $size; + } + + private function getFilterDate($days) + { + if ($days == 0) { + return $this->dateTime->gmtDate('Y-m-d'); + } else { + return $this->dateTime->gmtDate('Y-m-d', strtotime('-' . $days . ' day')); + } + + } +} diff --git a/BaseProvider/Model/Queue/Consumer.php b/BaseProvider/Model/Queue/Consumer.php new file mode 100644 index 00000000..45beed64 --- /dev/null +++ b/BaseProvider/Model/Queue/Consumer.php @@ -0,0 +1,230 @@ +logger = $logger; + $this->queueConfig = $queueConfig; + $this->queueCollFactory = $queueCollFactory; + $this->processors = $processors; + $this->batchSize = $this->queueConfig->getBatchSize(); + } + + /** + * Initiates queue process + * + * @return void + */ + public function process() + { + $this->logger->debug(__('Initiating queue processing from cron job')); + $size = $this->consumeJobs(); + $this->logger->debug( + __('Completed queue processing from cron job.'), + [ + 'total_count' => $size, + 'extra' => [ + 'class' => __METHOD__ + ] + ] + ); + } + + /** + * @return array + */ + public function consumeJobs() + { + $processors = $this->processors; + $processedCount = []; + foreach ($processors as $client=>$processor) { + $queueJobs = $this->getNewJobs($processor); + if ($queueJobs->getSize()) { + $processedCount[$client] = $this->consumeClientJobs($processor, $queueJobs); + } else { + $processedCount[$client] = 0; + } + } + return $processedCount; + } + + /** + * @param DefaultConsumer $processor + * @param \ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Queue\Collection $queueJobs + * @return int + */ + public function consumeClientJobs(DefaultConsumer $processor, \ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Queue\Collection $queueJobs) + { + $counter = 0; + foreach($queueJobs as $queueJob) { + if ($counter >= $this->batchSize) { + break; + } + $queueJob = $this->acknowledgeJob($queueJob); + if ($queueJob) { + $response = ""; + try { + list($sucess, $response) = $processor->consume($queueJob); + if ($sucess) { + $this->markJobCompleted($queueJob, $response); + $counter++; + } else { + if ($queueJob->getAttempt() >= \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface::MAX_ATTEMPT) { + $this->markJobFailed($queueJob, $response); + } else { + $this->markJobNewForNextAttempt($queueJob, $response); + } + } + } catch (\Exception $e) { + if ($queueJob->getAttempt() >= \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface::MAX_ATTEMPT) { + $this->markJobFailed($queueJob, $response); + } else { + $this->markJobNewForNextAttempt($queueJob, $response); + } + + $this->logger->critical($e->getMessage()); + } + } + } + return $counter; + } + + /** + * @param DefaultConsumer $processor + * @return \ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Queue\Collection + */ + protected function getNewJobs(DefaultConsumer $processor) + { + return $processor->getJobs() + ->addFieldToFilter('status', ['eq' => \ClassyLlama\AvaTax\BaseProvider\Model\Config\Source\Queue\Status::STATUS_NEW]) + ->addFieldToFilter('attempt', ['lt' => \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface::MAX_ATTEMPT]); + } + + /** + * @param \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob + * @return \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface | boolean + */ + public function acknowledgeJob(\ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob) + { + try { + $queueJob->setStatus(\ClassyLlama\AvaTax\BaseProvider\Model\Config\Source\Queue\Status::STATUS_PROCESSING) + ->setAttempt($queueJob->getAttempt() + 1) + ->save(); + return $queueJob; + } catch (\Exception $e) { + $this->logger->critical($e->getMessage()); + } + return false; + } + + /** + * @param \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob + * @param string $response + * @return \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface | boolean + */ + public function markJobCompleted(\ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob, string $response) + { + try { + $queueJob->setStatus(\ClassyLlama\AvaTax\BaseProvider\Model\Config\Source\Queue\Status::STATUS_COMPLETED) + ->setResponse($response) + ->save(); + return $queueJob; + } catch (\Exception $e) { + $this->logger->critical($e->getMessage()); + } + return false; + } + + /** + * @param \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob + * @param string $response + * @return \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface | boolean + */ + public function markJobNewForNextAttempt(\ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob, string $response) + { + try { + $queueJob->setStatus(\ClassyLlama\AvaTax\BaseProvider\Model\Config\Source\Queue\Status::STATUS_NEW) + ->setResponse($response) + ->save(); + return $queueJob; + } catch (\Exception $e) { + $this->logger->critical($e->getMessage()); + } + return false; + + } + + /** + * @param \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob + * @param string $response + * @return \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface | boolean + */ + public function markJobFailed(\ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob, string $response) + { + try { + $queueJob->setStatus(\ClassyLlama\AvaTax\BaseProvider\Model\Config\Source\Queue\Status::STATUS_FAILED) + ->setResponse($response) + ->save(); + return $queueJob; + } catch (\Exception $e) { + $this->logger->critical($e->getMessage()); + } + return false; + + } +} diff --git a/BaseProvider/Model/Queue/Consumer/ApiLogConsumer.php b/BaseProvider/Model/Queue/Consumer/ApiLogConsumer.php new file mode 100644 index 00000000..5df6fbb3 --- /dev/null +++ b/BaseProvider/Model/Queue/Consumer/ApiLogConsumer.php @@ -0,0 +1,115 @@ +logger = $logger; + $this->genericConfig = $genericConfig; + $this->restClient = $restClient; + parent::__construct($logger, $queueConfig, $queueCollFactory); + } + + /** + * @inheritDoc + */ + public function consume(\ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob) + { + $success = true; + $response = []; + $payload = $queueJob->getPayload(); + $payload = json_decode($payload, true); + $client = $this->restClient; + if (count($payload) > 0) { + foreach($payload as $method=>$arguments) { + if (!in_array($method, $this->allowedRestMethods)) continue; + try { + if ($method == 'restCall') { + $response = call_user_func_array([$client, $method], $arguments); + $response = json_decode(json_encode($response), true); + if (!(is_array($response) && array_key_exists("error", $response) && $response['error'] == null)) { + $success = false; + } + } else { + call_user_func_array([$client, $method], $arguments); + } + } catch (\Exception $e) { + $response = [$e->getMessage()]; + $this->logger->debug("API LOG Error Response : ".json_encode($response)); + $success = false; + } + } + } + $response = json_encode($response); + return [$success, $response]; + } + +} diff --git a/BaseProvider/Model/Queue/Consumer/DefaultConsumer.php b/BaseProvider/Model/Queue/Consumer/DefaultConsumer.php new file mode 100644 index 00000000..0025ac39 --- /dev/null +++ b/BaseProvider/Model/Queue/Consumer/DefaultConsumer.php @@ -0,0 +1,84 @@ +logger = $logger; + $this->queueConfig = $queueConfig; + $this->queueCollFactory = $queueCollFactory; + $this->batchSize = $this->queueConfig->getBatchSize(); + } + + /** + * @param string $client + * @return \ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Queue\Collection + */ + public function getJobs($client = '') + { + if ($client == '') { + $client = $this->client; + } + return $this->queueCollFactory->create() + ->addFieldToFilter('client', ['eq' => $client]) + ->setCurPage(1) + ->setPageSize($this->batchSize); + } + + /** + * @param \ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob + * @return array + */ + public abstract function consume(\ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface $queueJob); +} diff --git a/BaseProvider/Model/Queue/Producer.php b/BaseProvider/Model/Queue/Producer.php new file mode 100644 index 00000000..dfa24a09 --- /dev/null +++ b/BaseProvider/Model/Queue/Producer.php @@ -0,0 +1,77 @@ +logger = $logger; + $this->queueConfig = $queueConfig; + $this->queueFactory = $queueFactory; + } + + /** + * Add queue job + * + * @param string $client + * @param string $payload + * @return boolean + */ + public function addJob($client, $payload) + { + try { + $queue = $this->queueFactory->create(); + $queue->setClient($client) + ->setPayload($payload) + ->setStatus(\ClassyLlama\AvaTax\BaseProvider\Model\Config\Source\Queue\Status::STATUS_NEW) + ->setAttempt(\ClassyLlama\AvaTax\BaseProvider\Api\Data\QueueInterface::MIN_ATTEMPT) + ->save(); + return true; + } catch (\Exception $e) { + $this->logger->critical($e->getMessage()); + throw $e; + } + return false; + } +} diff --git a/BaseProvider/Model/QueueRepository.php b/BaseProvider/Model/QueueRepository.php new file mode 100644 index 00000000..f6cdcb4d --- /dev/null +++ b/BaseProvider/Model/QueueRepository.php @@ -0,0 +1,73 @@ +QueueFactory = $QueueFactory; + $this->QueueCollectionFactory = $QueueCollectionFactory; + $this->searchResultFactory = $QueueSearchResultsInterfaceFactory; + $this->collectionProcessor = collectionProcessor; + } + + public function getList(SearchCriteriaInterface $searchCriteria) + { + $collection = $this->collectionFactory->create(); + $this->collectionProcessor->process($searchCriteria, $collection); + $searchResults = $this->searchResultFactory->create(); + + $searchResults->setSearchCriteria($searchCriteria); + $searchResults->setItems($collection->getItems()); + + return $searchResults; + } +} \ No newline at end of file diff --git a/BaseProvider/Model/QueueSearchResults.php b/BaseProvider/Model/QueueSearchResults.php new file mode 100644 index 00000000..3fe66950 --- /dev/null +++ b/BaseProvider/Model/QueueSearchResults.php @@ -0,0 +1,23 @@ +_init('baseprovider_logs', 'log_id'); + } +} diff --git a/BaseProvider/Model/ResourceModel/Log/Collection.php b/BaseProvider/Model/ResourceModel/Log/Collection.php new file mode 100644 index 00000000..dd9ebbca --- /dev/null +++ b/BaseProvider/Model/ResourceModel/Log/Collection.php @@ -0,0 +1,109 @@ +dateTime = $dateTime; + parent::__construct($entityFactory, $genericLogger, $fetchStrategy, $eventManager, $connection, $resource); + } + /** + * Initialize resource + * + * @return void + */ + protected function _construct() + { + $this->_init( + \ClassyLlama\AvaTax\BaseProvider\Model\Log::class, + \ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Log::class + ); + } + + /** + * Filter collection by created at date older than specified seconds before now + * + * @param int $secondsBeforeNow + * @return $this + */ + public function addCreatedAtBeforeFilter($secondsBeforeNow) + { + $datetime = new \DateTime('now', new \DateTimeZone('UTC')); + $storeInterval = new \DateInterval('PT' . $secondsBeforeNow . 'S'); + $datetime->sub($storeInterval); + $formattedDate = $this->dateTime->formatDate($datetime->getTimestamp()); + + $this->addFieldToFilter(Log::CREATED_AT_FIELD_NAME, ['lt' => $formattedDate]); + return $this; + } + + /** + * Get the log count for all log levels + * + * @return array + */ + public function getLevelSummaryCount() + { + $select = clone $this->getSelect(); + $connection = $this->getConnection(); + + $countExpr = new \Zend_Db_Expr("COUNT(*)"); + + $select->reset(\Magento\Framework\DB\Select::COLUMNS); + $select->columns([ + self::SUMMARY_COUNT_FIELD_NAME => $countExpr, + Log::LEVEL_FIELD_NAME => Log::LEVEL_FIELD_NAME + ]); + $select->group(Log::LEVEL_FIELD_NAME); + + return $connection->fetchAll($select); + } +} diff --git a/BaseProvider/Model/ResourceModel/Queue.php b/BaseProvider/Model/ResourceModel/Queue.php new file mode 100644 index 00000000..6b1808b9 --- /dev/null +++ b/BaseProvider/Model/ResourceModel/Queue.php @@ -0,0 +1,30 @@ +_init('baseprovider_queue_job', 'job_id'); + } +} diff --git a/BaseProvider/Model/ResourceModel/Queue/Collection.php b/BaseProvider/Model/ResourceModel/Queue/Collection.php new file mode 100644 index 00000000..b0acb131 --- /dev/null +++ b/BaseProvider/Model/ResourceModel/Queue/Collection.php @@ -0,0 +1,66 @@ +dateTime = $dateTime; + parent::__construct($entityFactory, $genericLogger, $fetchStrategy, $eventManager, $connection, $resource); + } + /** + * Initialize resource + * + * @return void + */ + protected function _construct() + { + $this->_init( + \ClassyLlama\AvaTax\BaseProvider\Model\Queue::class, + \ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Queue::class + ); + } +} diff --git a/BaseProvider/README.md b/BaseProvider/README.md new file mode 100644 index 00000000..23cbfca4 --- /dev/null +++ b/BaseProvider/README.md @@ -0,0 +1,13 @@ +# Magento 2 Avalara Base Provider Extension + +This extesion is for BaseProvider utility features like Queue etc... + +# Documentation + +# License + +This project is licensed under the Open Software License 3.0 (OSL-3.0). See included LICENSE file for full text of OSL-3.0 + +# Support + +Contact Avalara for any support requests, either via [their support email](support@avalara.com) or via [this page](https://salestax.avalara.com/contact-us/). diff --git a/BaseProvider/composer.json b/BaseProvider/composer.json new file mode 100644 index 00000000..a220ec71 --- /dev/null +++ b/BaseProvider/composer.json @@ -0,0 +1,19 @@ +{ + "name": "avalara/baseprovider", + "type": "magento2-module", + "version": "1.0.1", + "license": "OSL-3.0", + "description": "Avalara's AvaTax Base module", + "require": { + "magento/framework": "^100.1.0|101.0.*|>=102.0.0", + "php": ">=5.5.9" + }, + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Avalara\\BaseProvider\\": "" + } + } +} \ No newline at end of file diff --git a/BaseProvider/etc/config.xml b/BaseProvider/etc/config.xml new file mode 100644 index 00000000..370770ab --- /dev/null +++ b/BaseProvider/etc/config.xml @@ -0,0 +1,30 @@ + + + + + + + 0 + 10 + 0 + 0 + 1 + 0 + + + + \ No newline at end of file diff --git a/BaseProvider/etc/cron_groups.xml b/BaseProvider/etc/cron_groups.xml new file mode 100644 index 00000000..b6cddaa8 --- /dev/null +++ b/BaseProvider/etc/cron_groups.xml @@ -0,0 +1,27 @@ + + + + + 5 + 20 + 20 + 10 + 60 + 600 + 0 + + diff --git a/BaseProvider/etc/crontab.xml b/BaseProvider/etc/crontab.xml new file mode 100644 index 00000000..3276f22f --- /dev/null +++ b/BaseProvider/etc/crontab.xml @@ -0,0 +1,29 @@ + + + + + + */5 * * * * + + + 15 2 * * * + + + 15 2 * * * + + + diff --git a/BaseProvider/etc/db_schema.xml b/BaseProvider/etc/db_schema.xml new file mode 100644 index 00000000..b2a9c0ad --- /dev/null +++ b/BaseProvider/etc/db_schema.xml @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + +
+
\ No newline at end of file diff --git a/BaseProvider/etc/db_schema_whitelist.json b/BaseProvider/etc/db_schema_whitelist.json new file mode 100644 index 00000000..f3389890 --- /dev/null +++ b/BaseProvider/etc/db_schema_whitelist.json @@ -0,0 +1,46 @@ +{ + "baseprovider_queue_job": { + "column": { + "job_id": true, + "client": true, + "payload": true, + "response": true, + "status": true, + "attempt": true, + "creation_time": true, + "update_time": true + }, + "constraint": { + "PRIMARY": true + }, + "index": { + "AVATAX_QUEUE_JOB_CLIENT": true, + "AVATAX_QUEUE_JOB_STATUS": true, + "AVATAX_QUEUE_JOB_ATTEMPT": true, + "AVATAX_QUEUE_JOB_CLIENT_STATUS": true, + "AVATAX_QUEUE_JOB_CLIENT_ATTEMPT": true, + "AVATAX_QUEUE_JOB_STATUS_ATTEMPT": true, + "AVATAX_QUEUE_JOB_CLIENT_STATUS_ATTEMPT": true + } + }, + "baseprovider_logs": { + "column": { + "log_id": true, + "created_at": true, + "store_id": true, + "level": true, + "message": true, + "source": true, + "request": true, + "result": true, + "additional": true + }, + "index": { + "AVATAX_LOGS_CREATED_AT": true, + "AVATAX_LOGS_LEVEL_CREATED_AT": true + }, + "constraint": { + "PRIMARY": true + } + } +} \ No newline at end of file diff --git a/BaseProvider/etc/di.xml b/BaseProvider/etc/di.xml new file mode 100644 index 00000000..ce9d0a7a --- /dev/null +++ b/BaseProvider/etc/di.xml @@ -0,0 +1,82 @@ + + + + + + + + + + BaseProviderQueueGridDataProvider + + + + + + baseprovider_queue_job + ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Queue + + + + + Magento\Framework\Filesystem\Driver\File + + + + + generic_logger + + ClassyLlama\AvaTax\BaseProvider\Logger\Handler\Generic\ApiHandler + + + ClassyLlama\AvaTax\BaseProvider\Logger\Processor + + + + + + logger + + ClassyLlama\AvaTax\BaseProvider\Logger\Handler\Application\FileHandler + ClassyLlama\AvaTax\BaseProvider\Logger\Handler\Application\DbHandler + + + ClassyLlama\AvaTax\BaseProvider\Logger\Processor + + + + + + + AvaTaxLogGridDataProvider + + + + + + baseprovider_logs + ClassyLlama\AvaTax\BaseProvider\Model\ResourceModel\Log + + + + + + ClassyLlama\AvaTax\BaseProvider\Model\Queue\Consumer\ApiLogConsumer + + + + \ No newline at end of file diff --git a/BaseProvider/etc/module.xml b/BaseProvider/etc/module.xml new file mode 100644 index 00000000..7874eebc --- /dev/null +++ b/BaseProvider/etc/module.xml @@ -0,0 +1,20 @@ + + + + + + diff --git a/BaseProvider/registration.php b/BaseProvider/registration.php new file mode 100644 index 00000000..83d94bd6 --- /dev/null +++ b/BaseProvider/registration.php @@ -0,0 +1,22 @@ +getValue() != -1) { + $element->setReadonly(true); + } + $html = $element->getElementHtml(); + $html .= ''; + $html .= ""; + return $html; + } +} diff --git a/Block/Cart/CartTotalsProcessor.php b/Block/Cart/CartTotalsProcessor.php new file mode 100644 index 00000000..0eb3d53e --- /dev/null +++ b/Block/Cart/CartTotalsProcessor.php @@ -0,0 +1,35 @@ +scopeConfig->getValue(Config::XML_PATH_AVATAX_TAX_INCLUDED, ScopeInterface::SCOPE_STORES); + if ($taxIncluded) + $jsLayout['components']['block-totals']['children']['tax']['config']['title'] .= " (".__(Config::XML_SUFFIX_AVATAX_TAX_INCLUDED).")"; + return $jsLayout; + } +} \ No newline at end of file diff --git a/Block/Checkout/AddressValidationLayoutProcessor.php b/Block/Checkout/AddressValidationLayoutProcessor.php index 76263e1e..a394fa10 100644 --- a/Block/Checkout/AddressValidationLayoutProcessor.php +++ b/Block/Checkout/AddressValidationLayoutProcessor.php @@ -81,6 +81,11 @@ public function process($jsLayout) { $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children'] ['payment']['component'] = self::COMPONENT_PATH; } + + $taxIncluded = $this->config->getTaxationPolicy($this->storeManager->getStore()); + if ($taxIncluded) + $jsLayout['components']['checkout']['children']['sidebar']['children']['summary']['children']['totals']['children']['tax']['config']['title'] .= " (".__(Config::XML_SUFFIX_AVATAX_TAX_INCLUDED).")"; + } return $jsLayout; } diff --git a/Controller/Adminhtml/CompanyCodes/Get.php b/Controller/Adminhtml/CompanyCodes/Get.php index 30fde43a..d22aa79f 100644 --- a/Controller/Adminhtml/CompanyCodes/Get.php +++ b/Controller/Adminhtml/CompanyCodes/Get.php @@ -17,6 +17,7 @@ use ClassyLlama\AvaTax\Exception\AvataxConnectionException; use Magento\Framework\DataObject; +use ClassyLlama\AvaTax\Helper\ApiLog; class Get extends \Magento\Backend\App\Action { @@ -35,23 +36,31 @@ class Get extends \Magento\Backend\App\Action */ private $config; + /** + * @var ApiLog + */ + protected $apiLog; + /** * @param \Magento\Backend\App\Action\Context $context * @param \Magento\Framework\Controller\Result\JsonFactory $resultPageFactory * @param \ClassyLlama\AvaTax\Framework\Interaction\Rest\Company $company * @param \ClassyLlama\AvaTax\Helper\Config $config + * @param ApiLog $apiLog */ public function __construct( \Magento\Backend\App\Action\Context $context, \Magento\Framework\Controller\Result\JsonFactory $resultPageFactory, \ClassyLlama\AvaTax\Framework\Interaction\Rest\Company $company, - \ClassyLlama\AvaTax\Helper\Config $config + \ClassyLlama\AvaTax\Helper\Config $config, + ApiLog $apiLog ) { parent::__construct($context); $this->resultPageFactory = $resultPageFactory; $this->company = $company; $this->config = $config; + $this->apiLog = $apiLog; } /** @@ -77,6 +86,7 @@ public function execute() $scopeType = $postValue['scope_type'] === 'global' ? \Magento\Store\Model\ScopeInterface::SCOPE_STORE : $postValue['scope_type']; $currentCompanyId = $this->config->getCompanyId($scope, $scopeType, $isProduction); + $message = "Avatax API connection successful."; try { if (!isset($postValue['license_key'])) { @@ -89,9 +99,15 @@ public function execute() null, $isProduction ); + if (\count($companies) === 0) + $message = "Avatax API connection successful but no company created under current avatax account"; } catch (AvataxConnectionException $e) { - // If for any reason we couldn't get any companies, just ignore and no companies will be returned + $message = "Avatax API connection un-successful."; + } catch (\Exception $e) { + $message = "Avatax API connection un-successful."; } + if (isset($postValue['license_key'])) + $this->apiLog->testConnectionLog($message, $scope, $scopeType); if (\count($companies) === 0) { return $resultJson->setData( diff --git a/Framework/AppInterface.php b/Framework/AppInterface.php index 5134982a..190dcaad 100644 --- a/Framework/AppInterface.php +++ b/Framework/AppInterface.php @@ -20,7 +20,7 @@ interface AppInterface /** * Connector version */ - const APP_VERSION = '2.3.0'; + const APP_VERSION = '2.3.1'; /** * Avalara APP String */ diff --git a/Framework/Interaction/Line.php b/Framework/Interaction/Line.php index 8d189184..b85705a9 100644 --- a/Framework/Interaction/Line.php +++ b/Framework/Interaction/Line.php @@ -176,6 +176,11 @@ protected function convertInvoiceItemToData(\Magento\Sales\Api\Data\InvoiceItemI $itemData['itemCode'] = $item->getSku(); } + $taxIncluded = false; + if ($product) { + $taxIncluded = $this->config->getTaxationPolicy($storeId); + } + $data = [ 'store_id' => $storeId, 'mage_sequence_no' => $this->getLineNumber(), @@ -184,7 +189,7 @@ protected function convertInvoiceItemToData(\Magento\Sales\Api\Data\InvoiceItemI 'description' => $item->getName(), 'quantity' => $item->getQty(), 'amount' => $amount, - 'tax_included' => false, + 'tax_included' => $taxIncluded, 'ref_1' => $itemData['productRef1'], 'ref_2' => $itemData['productRef2'] ]; @@ -243,6 +248,11 @@ protected function convertCreditMemoItemToData(\Magento\Sales\Api\Data\Creditmem $itemData['itemCode'] = $item->getSku(); } + $taxIncluded = false; + if ($product) { + $taxIncluded = $this->config->getTaxationPolicy($storeId); + } + $data = [ 'store_id' => $storeId, 'mage_sequence_no' => $this->getLineNumber(), @@ -251,7 +261,7 @@ protected function convertCreditMemoItemToData(\Magento\Sales\Api\Data\Creditmem 'description' => $item->getName(), 'quantity' => $item->getQty(), 'amount' => $amount, - 'tax_included' => false, + 'tax_included' => $taxIncluded, 'ref_1' => $itemData['productRef1'], 'ref_2' => $itemData['productRef2'] ]; @@ -309,6 +319,12 @@ protected function convertTaxQuoteDetailsItemToData(\Magento\Tax\Api\Data\QuoteD $ref1 = $extensionAttributes ? $extensionAttributes->getAvataxRef1() : null; $ref2 = $extensionAttributes ? $extensionAttributes->getAvataxRef2() : null; + $taxIncluded = false; + if ($taxCode != $this->config->getShippingTaxCode($item->getStoreId())) + { + $taxIncluded = $this->config->getTaxationPolicy($item->getStoreId()); + } + $data = [ 'mage_sequence_no' => $item->getCode(), 'item_code' => $itemCode, @@ -316,7 +332,7 @@ protected function convertTaxQuoteDetailsItemToData(\Magento\Tax\Api\Data\QuoteD 'description' => $description, 'quantity' => $item->getQuantity(), 'amount' => $amount, - 'tax_included' => false, + 'tax_included' => $taxIncluded, 'ref_1' => $ref1, 'ref_2' => $ref2, ]; diff --git a/Framework/Interaction/Request/TaxComposite.php b/Framework/Interaction/Request/TaxComposite.php index 9c4ef46e..717268a0 100755 --- a/Framework/Interaction/Request/TaxComposite.php +++ b/Framework/Interaction/Request/TaxComposite.php @@ -19,6 +19,7 @@ use ClassyLlama\AvaTax\Framework\Interaction\Storage\ResultStorage; use Psr\Log\LoggerInterface; use ClassyLlama\AvaTax\Framework\Interaction\Request\Request as CreditmemoRequest; +use ClassyLlama\AvaTax\Helper\ApiLog; /** * Class TaxComposite @@ -44,6 +45,7 @@ class TaxComposite extends InteractionRestTax implements TaxCompositeInterface * @param RestConfig $restConfig * @param CustomsConfig $customsConfigHelper * @param Config $config + * @param ApiLog $apiLog */ public function __construct( ResultStorage $resultStorage, @@ -54,7 +56,8 @@ public function __construct( TaxResultFactory $taxResultFactory, RestConfig $restConfig, CustomsConfig $customsConfigHelper, - Config $config + Config $config, + ApiLog $apiLog ) { parent::__construct( $logger, @@ -64,7 +67,8 @@ public function __construct( $taxResultFactory, $restConfig, $customsConfigHelper, - $config + $config, + $apiLog ); $this->resultStorage = $resultStorage; } diff --git a/Framework/Interaction/Rest/Tax.php b/Framework/Interaction/Rest/Tax.php index 3519fe07..c55503a4 100644 --- a/Framework/Interaction/Rest/Tax.php +++ b/Framework/Interaction/Rest/Tax.php @@ -36,6 +36,7 @@ use Psr\Log\LoggerInterface; use ClassyLlama\AvaTax\Framework\Interaction\Rest\ClientPool; use ClassyLlama\AvaTax\Helper\CustomsConfig; +use ClassyLlama\AvaTax\Helper\ApiLog; class Tax extends Rest implements RestTaxInterface @@ -70,6 +71,11 @@ class Tax extends Rest */ private $config; + /** + * @var ApiLog + */ + protected $apiLog; + /** * @param LoggerInterface $logger * @param DataObjectFactory $dataObjectFactory @@ -79,6 +85,7 @@ class Tax extends Rest * @param RestConfig $restConfig * @param CustomsConfig $customsConfigHelper * @param Config $config + * @param ApiLog $apiLog */ public function __construct( LoggerInterface $logger, @@ -88,7 +95,8 @@ public function __construct( TaxResultFactory $taxResultFactory, RestConfig $restConfig, CustomsConfig $customsConfigHelper, - Config $config + Config $config, + ApiLog $apiLog ) { parent::__construct($logger, $dataObjectFactory, $clientPool); $this->transactionBuilderFactory = $transactionBuilderFactory; @@ -96,6 +104,7 @@ public function __construct( $this->restConfig = $restConfig; $this->customsConfigHelper = $customsConfigHelper; $this->config = $config; + $this->apiLog = $apiLog; } /** @@ -114,6 +123,13 @@ public function __construct( */ public function getTax( $request, $isProduction = null, $scopeId = null, $scopeType = \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $params = []) { + $exeEndTime = $apiStartTime = $apiEndTime = 0; + $exeStartTime = microtime(true); + $sendLog = true; + if ($request->hasCode()) { + $logContext = ['extra' => ['DocCode' => $request->getCode()]]; + } + $client = $this->getClient( $isProduction, $scopeId, $scopeType); $client->withCatchExceptions(false); @@ -128,6 +144,7 @@ public function getTax( $request, $isProduction = null, $scopeId = null, $scopeT $this->setTransactionDetails($transactionBuilder, $request); $this->setLineDetails($transactionBuilder, $request); + $logContext['extra']['LineCount'] = $transactionBuilder->getCurrentLineNumber() - 1; $this->setAddressDetails($transactionBuilder, $request); $resultObj = null; @@ -141,12 +158,17 @@ public function getTax( $request, $isProduction = null, $scopeId = null, $scopeT } try { + $apiStartTime = microtime(true); $resultObj = $transactionBuilder->create(); + $apiEndTime = microtime(true); } catch (\GuzzleHttp\Exception\RequestException $clientException) { + $sendLog = false; $this->handleException($clientException, $request); } + + $resultGeneric = $this->formatResult($resultObj); /** @var \ClassyLlama\AvaTax\Framework\Interaction\Rest\Tax\Result $result */ $result = $this->taxResultFactory->create(['data' => $resultGeneric->getData()]); @@ -159,6 +181,42 @@ public function getTax( $request, $isProduction = null, $scopeId = null, $scopeT */ $result->setRequest($request); + if ($sendLog) { + $exeEndTime = microtime(true); + $prefix = ''; + $eventBlock = ''; + $docType = ''; + switch ($request->getType()) { + case \Avalara\DocumentType::C_RETURNINVOICE : + $eventBlock = "CreditMemoPostCalculateTax"; + $docType = "REFUND"; + $prefix = 'CM'; + $logContext['extra']['DocCode'] = $prefix . $request->getPurchaseOrderNo() ; + break; + case \Avalara\DocumentType::C_SALESINVOICE : + $eventBlock = "InvoicePostCalculateTax"; + $docType = "INVOICE"; + $prefix = 'INV'; + $logContext['extra']['DocCode'] = $prefix . $request->getPurchaseOrderNo() ; + break; + case \Avalara\DocumentType::C_SALESORDER : + $eventBlock = "PostCalculateTax"; + $docType = "SalesOrder"; + break; + } + if (!empty($docType)) { + $log['DocCode'] = $request->getPurchaseOrderNo(); + $logContext['extra']['EventBlock'] = $eventBlock; + $logContext['extra']['DocType'] = $docType; + $logContext['extra']['ConnectorTime'] = ['start' => $exeStartTime, 'end' => $exeEndTime]; + $logContext['extra']['ConnectorLatency'] = ['start' => $apiStartTime, 'end' => $apiEndTime]; + $logContext['source'] = 'tax'; + $logContext['operation'] = 'calculateTax'; + $logContext['function_name'] = __METHOD__; + $this->apiLog->makeTransactionRequestLog($logContext, $scopeId, $scopeType); + } + } + return $result; } @@ -307,10 +365,18 @@ public function getTaxBatch( $scopeId = null, $scopeType = ScopeInterface::SCOPE_STORE ): Result { + $exeEndTime = $apiStartTime = $apiEndTime = 0; + $exeStartTime = microtime(true); + $sendLogs = true; $client = $this->getClient($isProduction, $scopeId, $scopeType); $client->withCatchExceptions(false); $transactions = []; + $logs = []; foreach ($requests as $request) { + $log = []; + $log['DocType'] = $request->getType(); + $log['DocCode'] = $request->getPurchaseOrderNo(); + $sendLog = true; $transactionBuilder = $this->transactionBuilderFactory->create([ 'client' => $client, 'companyCode' => $request->getCompanyCode(), @@ -321,7 +387,9 @@ public function getTaxBatch( $this->setTransactionDetails($transactionBuilder, $request); try { $this->setLineDetails($transactionBuilder, $request); + $log['LineCount'] = $transactionBuilder->getCurrentLineNumber() - 1; } catch (Exception $e) { + $sendLog = false; } $this->setAddressDetails($transactionBuilder, $request); $createAdjustmentRequest = $transactionBuilder->createAdjustmentRequest(null, null); @@ -331,6 +399,8 @@ public function getTaxBatch( $transaction = new TransactionBatchItemModel(); $transaction->createTransactionModel = $requestData; $transactions[] = $transaction; + if ($sendLog) + $logs[] = $log; } $transactionBatchRequestModel = new CreateTransactionBatchRequestModel(); $transactionBatchRequestModel->name = "Batch" . date("Y-m-d H:i:s"); @@ -338,8 +408,11 @@ public function getTaxBatch( $resultObj = null; try { + $apiStartTime = microtime(true); $resultObj = $client->createTransactionBatch($this->config->getCompanyId(), $transactionBatchRequestModel); + $apiEndTime = microtime(true); } catch (RequestException $clientException) { + $sendLogs = false; $this->handleException($clientException); } $resultGeneric = $this->formatResult($resultObj); @@ -352,6 +425,40 @@ public function getTaxBatch( */ $result->setRequest($transactionBatchRequestModel); + if ($sendLogs && count($logs) > 0) { + $exeEndTime = microtime(true); + foreach ($logs as $log) { + $prefix = ''; + $eventBlock = ''; + $docType = ''; + switch ($log['DocType']) { + case \Avalara\DocumentType::C_RETURNINVOICE : + $eventBlock = "BatchCreditMemoPostCalculateTax"; + $docType = "REFUND"; + $prefix = 'CM'; + break; + case \Avalara\DocumentType::C_SALESINVOICE : + $eventBlock = "BatchInvoicePostCalculateTax"; + $docType = "INVOICE"; + $prefix = 'INV'; + break; + } + if (empty($docType)) continue; + $logContext = []; + $logContext['extra']['DocCode'] = $prefix.$log['DocCode']; + $logContext['extra']['DocType'] = $docType; + if (isset($log['LineCount'])) + $logContext['extra']['LineCount'] = $log['LineCount']; + $logContext['extra']['EventBlock'] = $eventBlock; + $logContext['extra']['ConnectorTime'] = ['start' => $exeStartTime, 'end' => $exeEndTime]; + $logContext['extra']['ConnectorLatency'] = ['start' => $apiStartTime, 'end' => $apiEndTime]; + $logContext['source'] = 'tax'; + $logContext['operation'] = 'calculateTax'; + $logContext['function_name'] = __METHOD__; + $this->apiLog->makeTransactionRequestLog($logContext, $scopeId, $scopeType); + } + } + return $result; } } diff --git a/Framework/Interaction/TaxCalculation.php b/Framework/Interaction/TaxCalculation.php index 4b76e5d2..5a2a6b65 100644 --- a/Framework/Interaction/TaxCalculation.php +++ b/Framework/Interaction/TaxCalculation.php @@ -32,6 +32,7 @@ use Magento\Tax\Model\Config; use Magento\Tax\Model\TaxDetails\TaxDetails; use Magento\Framework\Api\DataObjectHelper; +use ClassyLlama\AvaTax\Helper\Config as AvaTaxHelper; class TaxCalculation extends \Magento\Tax\Model\TaxCalculation { @@ -65,6 +66,11 @@ class TaxCalculation extends \Magento\Tax\Model\TaxCalculation */ const DEFAULT_TAX_RATE = -0.001; + /** + * @var AvaTaxHelper + */ + protected $avaTaxHelper; + /** * Constructor * @@ -81,6 +87,7 @@ class TaxCalculation extends \Magento\Tax\Model\TaxCalculation * @param AppliedTaxRateInterfaceFactory $appliedTaxRateDataObjectFactory * @param QuoteDetailsItemExtensionFactory $extensionFactory * @param AppliedTaxRateExtensionFactory $appliedTaxRateExtensionFactory + * @param AvaTaxHelper $avaTaxHelper */ public function __construct( Calculation $calculation, @@ -95,7 +102,8 @@ public function __construct( AppliedTaxInterfaceFactory $appliedTaxDataObjectFactory, AppliedTaxRateInterfaceFactory $appliedTaxRateDataObjectFactory, QuoteDetailsItemExtensionFactory $extensionFactory, - AppliedTaxRateExtensionFactory $appliedTaxRateExtensionFactory + AppliedTaxRateExtensionFactory $appliedTaxRateExtensionFactory, + AvaTaxHelper $avaTaxHelper ) { $this->priceCurrency = $priceCurrency; @@ -103,6 +111,7 @@ public function __construct( $this->appliedTaxRateDataObjectFactory = $appliedTaxRateDataObjectFactory; $this->extensionFactory = $extensionFactory; $this->appliedTaxRateExtensionFactory = $appliedTaxRateExtensionFactory; + $this->avaTaxHelper = $avaTaxHelper; return parent::__construct( $calculation, @@ -289,6 +298,10 @@ protected function getTaxDetailsItem( * @see \Magento\Tax\Model\Calculation\AbstractAggregateCalculator::calculateWithTaxInPrice */ $discountTaxCompensationAmount = 0; + $taxIncluded = $this->avaTaxHelper->getTaxationPolicy($scope); + if ($taxIncluded && $rowTax > 0) { + $discountTaxCompensationAmount = -$rowTax; + } /** * The \Magento\Tax\Model\Calculation\AbstractAggregateCalculator::calculateWithTaxNotInPrice method that this diff --git a/Helper/ApiLog.php b/Helper/ApiLog.php new file mode 100644 index 00000000..6f1a30d7 --- /dev/null +++ b/Helper/ApiLog.php @@ -0,0 +1,304 @@ +(.*)<\/(.*)>/'; + + /** + * @var Config + */ + protected $config; + + /** + * @var GenericLogger + */ + protected $genericLogger; + + /** + * @param Config $config + * @param Context $context + * @param GenericLogger $genericLogger + */ + public function __construct(Config $config, Context $context, GenericLogger $genericLogger) + { + parent::__construct($context); + + $this->config = $config; + $this->genericLogger = $genericLogger; + } + + /** + * API Logging + * + * @param string $message + * @param array $context + * @param $scopeId|Null + * @param $scopeType|Null + * @return void + */ + public function apiLog(string $message, array $context = [], $scopeId = null, $scopeType = null) + { + if (strlen($message) > 0) { + $isProduction = $this->config->isProductionMode($scopeId, $scopeType); + $accountNumber = $this->config->getAccountNumber($scopeId, $scopeType, $isProduction); + $accountSecret = $this->config->getLicenseKey($scopeId, $scopeType, $isProduction); + $connectorId = self::CONNECTOR_ID; + $clientString = self::CONNECTOR_STRING; + $mode = $isProduction ? \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_MODE_PRODUCTION : \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_MODE_SANDBOX; + $connectorName = self::CONNECTOR_NAME; + $source = isset($context['config']['source']) ? $context['config']['source'] : 'MagentoPage'; + $operation = isset($context['config']['operation']) ? $context['config']['operation'] : 'MagentoOperation'; + $logType = isset($context['config']['log_type']) ? $context['config']['log_type'] : \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_LOG_TYPE_DEBUG; + $logLevel = isset($context['config']['log_level']) ? $context['config']['log_level'] : \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_LOG_LEVEL_INFO; + $functionName = isset($context['config']['function_name']) ? $context['config']['function_name'] : __METHOD__; + + $params = [ + 'config' => [ + 'account_number' => $accountNumber, + 'account_secret' => $accountSecret, + 'connector_id' => $connectorId, + 'client_string' => $clientString, + 'mode' => $mode, + 'connector_name' => $connectorName, + 'connector_version' => $clientString, + 'source' => $source, + 'operation' => $operation, + 'log_type' => $logType, + 'log_level' => $logLevel, + 'function_name' => $functionName, + 'extra_params' => isset($context['config']['extra_params']) ? $context['config']['extra_params'] : [] + ] + ]; + + $this->genericLogger->apiLog($message, [$params]); + } + } + + /** + * Log Connection with AvaTax + * + * @param string $message + * @param $scopeId + * @param $scopeType + * @return void + */ + public function testConnectionLog(string $message, $scopeId, $scopeType) + { + try { + $source = 'ConfigurationPage'; + $operation = 'Test Connection'; + $logType = \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_LOG_TYPE_CONFIG; + $logLevel = \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_LOG_LEVEL_INFO; + $functionName = __METHOD__; + $context = [ + 'config' => [ + 'source' => $source, + 'operation' => $operation, + 'log_type' => $logType, + 'log_level' => $logLevel, + 'function_name' => $functionName + ] + ]; + $this->apiLog($message, $context, $scopeId, $scopeType); + } catch(\Exception $e) { + //do nothing as this is internal logging + } + } + + /** + * configSaveLog API Logging + * + * @param $scopeId + * @param $scopeType + * @return void + */ + public function configSaveLog($scopeId, $scopeType) + { + try { + $message = ""; + $source = 'ConfigurationPage'; + $operation = 'ConfigChanges'; + $logType = \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_LOG_TYPE_CONFIG; + $logLevel = \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_LOG_LEVEL_INFO; + $functionName = __METHOD__; + $context = [ + 'config' => [ + 'source' => $source, + 'operation' => $operation, + 'log_type' => $logType, + 'log_level' => $logLevel, + 'function_name' => $functionName + ] + ]; + $data = $this->getConfigData($scopeId, $scopeType); + $message = json_encode($data); + $this->apiLog($message, $context, $scopeId, $scopeType); + } catch(\Exception $e) { + //do nothing as this is internal logging + } + } + + /** + * TransactionRequest API Logging + * + * @param array $logContext + * @param $scopeId + * @param $scopeType + * @return void + */ + public function makeTransactionRequestLog(array $logContext, $scopeId, $scopeType) + { + try { + $message = "Transaction Request Log"; + $source = isset($logContext['source']) ? $logContext['source'] : 'TransactionPage'; + $operation = isset($logContext['operation']) ? $logContext['operation'] : 'TransactionOperation'; + $logType = \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_LOG_TYPE_PERFORMANCE; + $logLevel = \ClassyLlama\AvaTax\BaseProvider\Helper\Generic\Config::API_LOG_LEVEL_INFO; + $functionName = isset($logContext['function_name']) ? $logContext['function_name'] : __METHOD__; + if (isset($logContext['extra']['ConnectorTime']) && isset($logContext['extra']['ConnectorLatency']) ) { + list($connectorTime, $latencyTime) = $this->getLatencyTimeAndConnectorTime($logContext['extra']); + unset($logContext['extra']['ConnectorTime']); + unset($logContext['extra']['ConnectorLatency']); + if (!is_null($connectorTime)) + $logContext['extra']['ConnectorTime'] = number_format($connectorTime, 2, '.', ','); + if (!is_null($latencyTime)) + $logContext['extra']['ConnectorLatency'] = number_format($latencyTime, 2, '.', ','); + } + $context = [ + 'config' => [ + 'source' => $source, + 'operation' => $operation, + 'log_type' => $logType, + 'log_level' => $logLevel, + 'function_name' => $functionName, + 'extra_params' => isset($logContext['extra']) ? $logContext['extra'] : [] + ] + ]; + $this->apiLog($message, $context, $scopeId, $scopeType); + } catch(\Exception $e) { + //do nothing as this is internal logging + } + } + + /** + * getConfigData function + * + * @param $scopeId + * @param $scopeType + * @return array + */ + private function getConfigData($store) + { + $configPaths = [ + "AvaTax - General" => "tax/avatax", + "AvaTax - Customs" => "tax/avatax_customs", + "AvaTax - Document Management" => "tax/avatax_document_management", + "AvaTax - Certificate Capture Management" => "tax/avatax_certificate_capture", + "AvaTax - Advanced" => "tax/avatax_advanced" + ]; + + foreach ($configPaths as $title=>$path) { + $groupData = $this->config->getConfigData($path, $store); + $data[$title] = $this->escapeAvaTaxData($groupData); + } + + if (isset($data["AvaTax - General"]["production_license_key"])) { + unset($data["AvaTax - General"]["production_license_key"]); + } + + if (isset($data["AvaTax - General"]["development_license_key"])) { + unset($data["AvaTax - General"]["development_license_key"]); + } + + return $data; + } + + /** + * escapeAvaTaxData function + * + * @param array $data + * @return array + */ + public function escapeAvaTaxData(array $data) + { + if (empty($data)) { + return $data; + } + foreach ($data as $key=>&$value) { + if (is_array($value)) { + $value = $this->escapeAvaTaxData($value); + } else { + /* To Exclude html value from log */ + if (preg_match(self::HTML_ESCAPE_PATTERN, $value)) { + unset($data[$key]); + } + } + } + + return $data; + } + + /** + * getLatencyTimeAndConnectorTime function + * + * @param array $logContext + * @return array + */ + public function getLatencyTimeAndConnectorTime(array $logContext) + { + $latencyTime = null; + $connectorTime = null; + $isSufficientData = 0; + if (empty($logContext)) { + return [$latencyTime, $connectorTime]; + } + if (isset($logContext['ConnectorTime']['start'])) { + $isSufficientData++; + } + if (isset($logContext['ConnectorTime']['end'])) { + $isSufficientData++; + } + if (isset($logContext['ConnectorLatency']['end'])) { + $isSufficientData++; + } + if (isset($logContext['ConnectorLatency']['end'])) { + $isSufficientData++; + } + if ($isSufficientData < 4) { + return [$latencyTime, $connectorTime]; + } + $connectorTime = $logContext['ConnectorTime']['end'] - $logContext['ConnectorTime']['start']; + $latencyTime = $logContext['ConnectorLatency']['end'] - $logContext['ConnectorLatency']['start']; + if ($latencyTime < 0) { + $latencyTime = 0; + } + $connectorTime = $connectorTime - $latencyTime; + return [$latencyTime, $connectorTime]; + } +} \ No newline at end of file diff --git a/Helper/Config.php b/Helper/Config.php index 12ba6e8b..5fa8f44c 100644 --- a/Helper/Config.php +++ b/Helper/Config.php @@ -40,6 +40,10 @@ class Config extends AbstractHelper */ const XML_PATH_AVATAX_MODULE_ENABLED = 'tax/avatax/enabled'; + const XML_PATH_AVATAX_TAX_INCLUDED = 'tax/avatax/tax_included'; + + const XML_SUFFIX_AVATAX_TAX_INCLUDED = "Included in Subtotal"; + const XML_PATH_AVATAX_TAX_MODE = 'tax/avatax/tax_mode'; const XML_PATH_AVATAX_COMMIT_SUBMITTED_TRANSACTIONS = 'tax/avatax/commit_submitted_transactions'; @@ -1299,4 +1303,19 @@ public function getConfigData($configPath, $store = null) $store ); } + + /** + * Get Taxation Policy + * + * @param null $store + * @return boolean + */ + public function getTaxationPolicy($store = null) + { + return (boolean)$this->scopeConfig->getValue( + self::XML_PATH_AVATAX_TAX_INCLUDED, + ScopeInterface::SCOPE_STORE, + $store + ); + } } diff --git a/Model/Config/Source/TaxIncluded.php b/Model/Config/Source/TaxIncluded.php new file mode 100644 index 00000000..bc019fdd --- /dev/null +++ b/Model/Config/Source/TaxIncluded.php @@ -0,0 +1,46 @@ + __('Net'), + self::GROSS => __('Gross') + ]; + } + + /** + * @return array + */ + public function toOptionArray() + { + $result = []; + $options = $this->toSourceArray(); + foreach ($options as $value=>$label) { + $result[] = ['value' => $value, 'label' => $label]; + } + return $result; + } +} diff --git a/Model/Tax/Sales/Total/Quote/Tax.php b/Model/Tax/Sales/Total/Quote/Tax.php index 73b2adaa..cd1db389 100644 --- a/Model/Tax/Sales/Total/Quote/Tax.php +++ b/Model/Tax/Sales/Total/Quote/Tax.php @@ -534,4 +534,40 @@ public function mapQuoteExtraTaxables( return $itemDataObjects; } + + /** + * @inheritDoc + */ + public function fetch(\Magento\Quote\Model\Quote $quote, \Magento\Quote\Model\Quote\Address\Total $total) + { + $totals = parent::fetch($quote, $total); + if (empty($totals)) { + return $totals; + } + $storeId = $quote->getStoreId(); + if (!$this->config->getTaxationPolicy($storeId)) { + return $totals; + } + foreach ($totals as &$total) { + if (isset($total['code']) && $total['code'] == 'tax') { + $total['title'] .= " (".__(Config::XML_SUFFIX_AVATAX_TAX_INCLUDED).")"; + } + } + return $totals; + } + + /** + * Get Tax label + * + * @return \Magento\Framework\Phrase + */ + public function getLabel() + { + if ($this->config->getTaxationPolicy()) { + return __('Tax')." (".__(Config::XML_SUFFIX_AVATAX_TAX_INCLUDED).")"; + } else { + return __('Tax'); + } + + } } diff --git a/Observer/ConfigSaveObserver.php b/Observer/ConfigSaveObserver.php index e6167ba9..d10c00f7 100644 --- a/Observer/ConfigSaveObserver.php +++ b/Observer/ConfigSaveObserver.php @@ -19,6 +19,7 @@ use ClassyLlama\AvaTax\Helper\Config; use ClassyLlama\AvaTax\Helper\CustomsConfig; use Magento\Framework\Event\ObserverInterface; +use ClassyLlama\AvaTax\Helper\ApiLog; /** * Class ConfigSaveObserver @@ -50,6 +51,11 @@ class ConfigSaveObserver implements ObserverInterface */ protected $customsConfig; + /** + * @var ApiLog + */ + protected $apiLog; + /** * Constructor * @@ -58,13 +64,15 @@ class ConfigSaveObserver implements ObserverInterface * @param CustomsConfig $customsConfig * @param \ClassyLlama\AvaTax\Helper\ModuleChecks $moduleChecks * @param RestInterface $interactionRest + * @param ApiLog $apiLog */ public function __construct( \Magento\Framework\Message\ManagerInterface $messageManager, Config $config, CustomsConfig $customsConfig, \ClassyLlama\AvaTax\Helper\ModuleChecks $moduleChecks, - RestInterface $interactionRest + RestInterface $interactionRest, + ApiLog $apiLog ) { $this->messageManager = $messageManager; @@ -72,6 +80,7 @@ public function __construct( $this->moduleChecks = $moduleChecks; $this->interactionRest = $interactionRest; $this->customsConfig = $customsConfig; + $this->apiLog = $apiLog; } /** @@ -101,6 +110,8 @@ public function execute(\Magento\Framework\Event\Observer $observer) $this->messageManager->addNotice($notice); } + $this->apiLog->configSaveLog($scopeId, $scopeType); + return $this; } diff --git a/Plugin/Model/Sales/Pdf/TaxPlugin.php b/Plugin/Model/Sales/Pdf/TaxPlugin.php index 74678423..9c7a700f 100644 --- a/Plugin/Model/Sales/Pdf/TaxPlugin.php +++ b/Plugin/Model/Sales/Pdf/TaxPlugin.php @@ -6,6 +6,7 @@ use Magento\Framework\Locale\FormatInterface; use Magento\Tax\Model\Config; use Magento\Tax\Model\Sales\Pdf\Tax; +use ClassyLlama\AvaTax\Helper\Config as AvaTaxHelperConfig; /** * Class TaxPlugin @@ -27,18 +28,26 @@ class TaxPlugin */ private $taxConfig; + /** + * @var AvaTaxHelperConfig + */ + private $avaTaxHelperConfig; + /** * TaxPlugin constructor. * * @param FormatInterface $format * @param Config $taxConfig + * @param AvaTaxHelperConfig $avaTaxHelperConfig */ public function __construct( FormatInterface $format, - Config $taxConfig + Config $taxConfig, + AvaTaxHelperConfig $avaTaxHelperConfig ) { $this->format = $format; $this->taxConfig = $taxConfig; + $this->avaTaxHelperConfig = $avaTaxHelperConfig; } /** @@ -58,6 +67,10 @@ public function afterGetTotalsForDisplay(Tax $subject, $totals) $store = $subject->getOrder()->getStore(); + $taxTitle = self::TOTAL_TAX_LABEL; + $taxIncluded = $this->avaTaxHelperConfig->getTaxationPolicy($store); + if ($taxIncluded) + $taxTitle .= " (".AvaTaxHelperConfig::XML_SUFFIX_AVATAX_TAX_INCLUDED.")"; if ($this->taxConfig->displaySalesFullSummary($store)) { $customDutyKey = array_search(GrandTotalDetailsSorter::CUSTOMS_RATE_TITLE, @@ -73,7 +86,7 @@ public function afterGetTotalsForDisplay(Tax $subject, $totals) $amount = $subject->getAmountPrefix() . $amount; } - $totalTax['label'] = $this->getTotalTaxLabel(self::TOTAL_TAX_LABEL, $subject); + $totalTax['label'] = $this->getTotalTaxLabel($taxTitle, $subject); $totalTax['amount'] = $amount; $result = array_merge([$customDuty], [$totalTax], $totals); @@ -81,7 +94,7 @@ public function afterGetTotalsForDisplay(Tax $subject, $totals) $customDutyKey = array_search(GrandTotalDetailsSorter::CUSTOMS_RATE_TITLE, array_column($subject->getFullTaxInfo(), 'title')); $totalTax['label'] = $this->getTotalTaxLabel(is_numeric($customDutyKey) - ? self::TOTAL_TAX_CUSTOM_LABEL : self::TOTAL_TAX_LABEL, $subject); + ? self::TOTAL_TAX_CUSTOM_LABEL : $taxTitle, $subject); $result = [$totalTax]; } diff --git a/composer.json b/composer.json index d1d98781..7f7da57f 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "avalara/avatax-magento", "type": "magento2-module", - "version": "2.3.0", + "version": "2.3.1", "license": "OSL-3.0", "description": "Magento module for Avalara's AvaTax suite of business tax calculation and processing services. Uses the AvaTax REST v2 API.", "require": { diff --git a/docs/getting-started.md b/docs/getting-started.md index 8be78788..86712495 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -44,7 +44,7 @@ For support with your AvaTax account, please visit [avalara.com/technical-suppor ### Supported Magento Versions -Refer to [README](https://github.com/astoundcommerce/avatax#magento-version-support) for supported versions/editions. +Refer to [README](https://marketplace.magento.com/avalara-avatax-magento.html#release_notes) for supported versions/editions. ### Installation @@ -57,20 +57,21 @@ This is the recommended installation method as it allows you to easily update th 1. Require the desired version of AvaTax. Latest version can be installed by running following command: ``` - composer require avalara/avatax-magento:2.3.0 + composer require avalara/avatax-magento:2.3.1 ``` 2. Setup the AvaTax module in magento ```bash bin/magento module:enable --clear-static-content ClassyLlama_AvaTax + bin/magento module:enable --clear-static-content Avalara_BaseProvider bin/magento setup:upgrade bin/magento setup:di:compile bin/magento setup:static-content:deploy bin/magento cache:flush ``` -3. If you are deploying the extension to a production environment, follow the [devdocs.magento.com deployment instructions](http://devdocs.magento.com/guides/v2.0/howdoi/deploy/deploy-to-prod.html#deploy-prod) +3. If you are deploying the extension to a production environment, follow the [devdocs.magento.com deployment instructions](https://experienceleague.adobe.com/docs/commerce-operations/performance-best-practices/deployment-flow.html) ### Configuration @@ -114,7 +115,7 @@ Solution: You'll need to install the PHP SoapClient library, per the [prerequisi ## Release Notes -See this page for release notes: [https://github.com/astoundcommerce/avatax/releases](https://github.com/astoundcommerce/avatax/releases) +See this page for release notes: [https://marketplace.magento.com/avalara-avatax-magento.html#release_notes](https://marketplace.magento.com/avalara-avatax-magento.html#release_notes) ## Pre-Launch Sales Record Cleanup @@ -125,11 +126,17 @@ If you have installed the AvaTax extension in a development/testing environment -- Truncate AvaTax tables TRUNCATE TABLE `avatax_queue`; TRUNCATE TABLE `avatax_log`; +TRUNCATE TABLE `baseprovider_queue_job`; ``` ## Uninstall Extension -1. Run this command in the root of your Magento installation directory: `bin/magento module:uninstall ClassyLlama_AvaTax` +1. Run this command in the root of your Magento installation directory: + + ```bash + bin/magento module:uninstall Avalara_BaseProvider + bin/magento module:uninstall ClassyLlama_AvaTax + ``` 2. If you installed the module using Composer, run these commands in the root of your Magento installation directory: @@ -143,6 +150,7 @@ TRUNCATE TABLE `avatax_log`; -- Remove AvaTax tables (these tables will be in the sales database in split-database mode) DROP TABLE `avatax_queue`; DROP TABLE `avatax_log`; + DROP TABLE `baseprovider_queue_job`; DROP TABLE `avatax_sales_creditmemo`; DROP TABLE `avatax_sales_invoice`; diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index fa17d8ec..87c3348a 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -38,7 +38,16 @@ --> - + + tax/avatax/tax_included + + ClassyLlama\AvaTax\Model\Config\Source\TaxIncluded + ClassyLlama\AvaTax\Block\Adminhtml\System\Config\TaxIncluded + + 1 + + + tax/avatax/tax_mode ClassyLlama\AvaTax\Model\Config\Source\TaxMode diff --git a/etc/config.xml b/etc/config.xml index 80b9fb1d..d466d06f 100755 --- a/etc/config.xml +++ b/etc/config.xml @@ -19,6 +19,7 @@ 0 + -1 3 1 CA,US diff --git a/etc/frontend/di.xml b/etc/frontend/di.xml index 37c1bef1..de9870d4 100644 --- a/etc/frontend/di.xml +++ b/etc/frontend/di.xml @@ -31,4 +31,11 @@ + + + + \ClassyLlama\AvaTax\Block\Cart\CartTotalsProcessor + + + diff --git a/registration.php b/registration.php index e52f4cb3..5157d218 100644 --- a/registration.php +++ b/registration.php @@ -18,4 +18,10 @@ \Magento\Framework\Component\ComponentRegistrar::LIBRARY, 'Avalara_AvaTax', $vendorPath . DIRECTORY_SEPARATOR . 'avalara' . DIRECTORY_SEPARATOR . 'avataxclient' -); \ No newline at end of file +); + +\Magento\Framework\Component\ComponentRegistrar::register( + \Magento\Framework\Component\ComponentRegistrar::MODULE, + 'Avalara_BaseProvider', + __DIR__ . DIRECTORY_SEPARATOR . 'BaseProvider' +); diff --git a/view/adminhtml/templates/order/create/totals/tax.phtml b/view/adminhtml/templates/order/create/totals/tax.phtml index 4ee4db6c..57304e51 100644 --- a/view/adminhtml/templates/order/create/totals/tax.phtml +++ b/view/adminhtml/templates/order/create/totals/tax.phtml @@ -8,6 +8,10 @@ use ClassyLlama\AvaTax\Plugin\Model\Quote\GrandTotalDetailsSorter; $taxAmount = $block->getTotal()->getValue(); $customDuty = false; $fullInfo = $block->getTotal()->getFullInfo(); +$taxTitle = __('Tax'); +$taxIncluded = $this->helper('ClassyLlama\AvaTax\Helper\Config')->getTaxationPolicy(); +if ($taxIncluded) + $taxTitle .= " (".__(\ClassyLlama\AvaTax\Helper\Config::XML_SUFFIX_AVATAX_TAX_INCLUDED).")"; ?> helper(\Magento\Tax\Helper\Data::class)->displayZeroTax()) || ($taxAmount > 0)) : global $taxIter; @@ -58,14 +62,14 @@ $fullInfo = $block->getTotal()->getFullInfo(); colspan="getColspan() ?>"> helper(\Magento\Tax\Helper\Data::class)->displayFullSummary()) : ?>
+ $taxTitle ?> + $taxTitle ?> diff --git a/view/adminhtml/templates/order/totals/tax.phtml b/view/adminhtml/templates/order/totals/tax.phtml index 6e54f13f..723f5844 100644 --- a/view/adminhtml/templates/order/totals/tax.phtml +++ b/view/adminhtml/templates/order/totals/tax.phtml @@ -19,6 +19,10 @@ $_source = $block->getSource(); $_order = $block->getOrder(); $_fullInfo = $block->getFullTaxInfo(); $customDuty = false; +$taxTitle = __('Tax'); +$taxIncluded = $this->helper('ClassyLlama\AvaTax\Helper\Config')->getTaxationPolicy(); +if ($taxIncluded) + $taxTitle .= " (".__(\ClassyLlama\AvaTax\Helper\Config::XML_SUFFIX_AVATAX_TAX_INCLUDED).")"; ?> @@ -75,14 +79,14 @@ $customDuty = false;
helper('Magento\Tax\Helper\Data')->displayFullSummary()): ?> + $taxTitle ?> + $taxTitle ?>
diff --git a/view/frontend/templates/order/tax.phtml b/view/frontend/templates/order/tax.phtml index 6dce5c85..0bd60b7f 100644 --- a/view/frontend/templates/order/tax.phtml +++ b/view/frontend/templates/order/tax.phtml @@ -16,6 +16,10 @@ $_fullInfo = $this->helper('Magento\Tax\Helper\Data')->getCalculatedTaxes($_sour global $taxIter; $taxIter++; $customDuty = false; +$taxTitle = __('Tax'); +$taxIncluded = $this->helper('ClassyLlama\AvaTax\Helper\Config')->getTaxationPolicy(); +if ($taxIncluded) + $taxTitle .= " (".__(\ClassyLlama\AvaTax\Helper\Config::XML_SUFFIX_AVATAX_TAX_INCLUDED).")"; ?> @@ -56,19 +60,19 @@ $customDuty = false; $block->getLabelProperties() ?> scope="row"> displayFullSummary()): ?>
+ $taxTitle ?> + $taxTitle ?> getValueProperties() ?> data-th="escapeHtml(__('Tax')) ?>"> + $block->getValueProperties() ?> data-th="escapeHtml($taxTitle) ?>"> displayFullSummary() && $customDuty): ?> formatPrice($_source->getTaxAmount() - $customDuty['tax_amount']) ?>