You are here

class Avatax in Drupal Commerce Connector for AvaTax 8

Same name in this branch
  1. 8 src/Avatax.php \Drupal\commerce_avatax\Avatax
  2. 8 src/Plugin/Commerce/TaxType/Avatax.php \Drupal\commerce_avatax\Plugin\Commerce\TaxType\Avatax

Provides the AvaTax remote tax type.

Plugin annotation


@CommerceTaxType(
  id = "avatax",
  label = "AvaTax",
)

Hierarchy

Expanded class hierarchy of Avatax

File

src/Plugin/Commerce/TaxType/Avatax.php, line 24

Namespace

Drupal\commerce_avatax\Plugin\Commerce\TaxType
View source
class Avatax extends RemoteTaxTypeBase {

  /**
   * The AvaTax library.
   *
   * @var \Drupal\commerce_avatax\AvataxLibInterface
   */
  protected $avataxLib;

  /**
   * Config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Constructs a new AvaTax object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
   *   The event dispatcher.
   * @param \Drupal\commerce_avatax\AvataxLibInterface $avatax_lib
   *   The AvaTax library.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EventDispatcherInterface $event_dispatcher, AvataxLibInterface $avatax_lib, ConfigFactoryInterface $config_factory) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $event_dispatcher);
    $this->avataxLib = $avatax_lib;
    $this->configFactory = $config_factory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('event_dispatcher'), $container
      ->get('commerce_avatax.avatax_lib'), $container
      ->get('config.factory'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'display_inclusive' => FALSE,
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function applies(OrderInterface $order) {
    $config = $this->configFactory
      ->get('commerce_avatax.settings');
    return !$config
      ->get('disable_tax_calculation');
  }

  /**
   * {@inheritdoc}
   */
  public function apply(OrderInterface $order) {
    $response_body = $this->avataxLib
      ->transactionsCreate($order);

    // Do not go further unless there have been lines added.
    if (empty($response_body['lines'])) {
      return;
    }
    $currency_code = $order
      ->getTotalPrice() ? $order
      ->getTotalPrice()
      ->getCurrencyCode() : $order
      ->getStore()
      ->getDefaultCurrencyCode();
    $adjustments = [];
    $applied_adjustments = [];
    foreach ($response_body['lines'] as $tax_adjustment) {
      $label = isset($tax_adjustment['details'][0]['taxName']) ? Html::escape($tax_adjustment['details'][0]['taxName']) : $this
        ->t('Sales tax');
      $adjustments[$tax_adjustment['lineNumber']] = [
        'amount' => $tax_adjustment['tax'],
        'label' => $label,
      ];
    }

    // Add tax adjustments to order items.
    foreach ($order
      ->getItems() as $order_item) {
      if (!isset($adjustments[$order_item
        ->uuid()])) {
        continue;
      }
      $order_item
        ->addAdjustment(new Adjustment([
        'type' => 'tax',
        'label' => $adjustments[$order_item
          ->uuid()]['label'],
        'amount' => new Price((string) $adjustments[$order_item
          ->uuid()]['amount'], $currency_code),
        'source_id' => $this->pluginId . '|' . $this->parentEntity
          ->id(),
      ]));
      $applied_adjustments[$order_item
        ->uuid()] = $order_item
        ->uuid();
    }

    // If we still have Tax adjustments to apply, add a single one to the order.
    $remaining_adjustments = array_diff_key($adjustments, $applied_adjustments);
    if (!$remaining_adjustments) {
      return;
    }
    $tax_adjustment_total = NULL;

    // Calculate the total Tax adjustment to add.
    foreach ($remaining_adjustments as $remaining_adjustment) {
      $adjustment_amount = new Price((string) $remaining_adjustment['amount'], $currency_code);
      $tax_adjustment_total = $tax_adjustment_total ? $tax_adjustment_total
        ->add($adjustment_amount) : $adjustment_amount;
    }
    $order
      ->addAdjustment(new Adjustment([
      'type' => 'tax',
      'label' => $this
        ->t('Sales tax'),
      'amount' => $tax_adjustment_total,
      'source_id' => $this->pluginId . '|' . $this->parentEntity
        ->id(),
    ]));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Avatax::$avataxLib protected property The AvaTax library.
Avatax::$configFactory protected property Config factory.
Avatax::applies public function Checks whether the tax type applies to the given order. Overrides TaxTypeBase::applies
Avatax::apply public function Applies the tax type to the given order. Overrides TaxTypeInterface::apply
Avatax::create public static function Creates an instance of the plugin. Overrides TaxTypeBase::create
Avatax::defaultConfiguration public function Gets default configuration for this plugin. Overrides TaxTypeBase::defaultConfiguration
Avatax::__construct public function Constructs a new AvaTax object. Overrides TaxTypeBase::__construct
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TaxTypeBase::$entityId Deprecated protected property The ID of the parent config entity.
TaxTypeBase::$entityTypeManager protected property The entity type manager.
TaxTypeBase::$eventDispatcher protected property The event dispatcher.
TaxTypeBase::$parentEntity protected property The parent config entity.
TaxTypeBase::$profiles protected property A cache of prepared customer profiles, keyed by order ID.
TaxTypeBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 6
TaxTypeBase::buildCustomerProfile protected function Builds a customer profile for the given order.
TaxTypeBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
TaxTypeBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
TaxTypeBase::getLabel public function Gets the tax type label. Overrides TaxTypeInterface::getLabel
TaxTypeBase::getTaxableType protected function Gets the taxable type for the given order item.
TaxTypeBase::getWeight public function Gets the tax type weight. Overrides TaxTypeInterface::getWeight
TaxTypeBase::isDisplayInclusive public function Gets whether the tax type is display inclusive. Overrides TaxTypeInterface::isDisplayInclusive
TaxTypeBase::resolveCustomerProfile protected function Resolves the customer profile for the given order item.
TaxTypeBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 1
TaxTypeBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm 1
TaxTypeBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 1
TaxTypeBase::__sleep public function Overrides DependencySerializationTrait::__sleep
TaxTypeBase::__wakeup public function Overrides DependencySerializationTrait::__wakeup