contacts_events-8.x-1.x-dev/src/PluginForm/ManualRefundPaymentAddForm.php

src/PluginForm/ManualRefundPaymentAddForm.php
<?php

namespace Drupal\contacts_events\PluginForm;

use Drupal\commerce_partial_payments\Form\TrackingElementTrait;
use Drupal\commerce_partial_payments\OrderItemTrackingInterface;
use Drupal\commerce_payment\PluginForm\ManualPaymentAddForm;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * The manual refund add form.
 */
class ManualRefundPaymentAddForm extends ManualPaymentAddForm implements ContainerInjectionInterface {

  use TrackingElementTrait;
  use MessengerTrait;

  /**
   * The order item payment tracker.
   *
   * @var \Drupal\commerce_partial_payments\OrderItemTrackingInterface
   */
  protected $paymentTracking;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $class = new static(
      $container->get('commerce_partial_payments.order_item_tracking')
    );
    $class->setStringTranslation($container->get('string_translation'));
    $class->setCurrencyFormatter($container->get('commerce_price.currency_formatter'));
    $class->setElementInfoManager($container->get('plugin.manager.element_info'));
    $class->setCurrentLocale($container->get('commerce.current_locale'));
    $class->setMessenger($container->get('messenger'));
    return $class;
  }

  /**
   * Constructor the manual refund payment add form.
   *
   * @param \Drupal\commerce_partial_payments\OrderItemTrackingInterface $payment_tracking
   *   The payment tracking service.
   */
  public function __construct(OrderItemTrackingInterface $payment_tracking) {
    $this->paymentTracking = $payment_tracking;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    /** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */
    $payment = $this->entity;
    $order = $payment->getOrder();

    // The payment amount should default to the paid so far.
    $paid = $order->getTotalPaid();
    $amount = $paid->isPositive() ? $paid : $paid->multiply(0);

    $form['amount']['#title'] = $this->t('Amount to refund');
    $form['amount']['#default_value'] = $amount->toArray();

    // Adjust the received label.
    $form['received']['#title'] = $this->t('The specified amount has already been sent.');

    $this->alterPartialPayments($form, $form_state);

    return $form;
  }

  /**
   * Alter the add payment form for partial payments.
   *
   * @param array $inline_form
   *   The inline form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @see \Drupal\commerce_partial_payments\Plugin\Commerce\InlineForm\PartialPaymentsGatewayForm::alterAddForm
   */
  protected function alterPartialPayments(array &$inline_form, FormStateInterface $form_state) {
    /** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */
    $payment = $this->entity;

    // Don't do anything if the field doesn't exist.
    if (!$payment->hasField('order_item_tracking')) {
      return;
    }

    $order = $payment->getOrder();
    $paid = $order->getTotalPaid();

    $this->swapAmountForAllocationChoice($inline_form, $this->t('refund'));

    // Get the current tracking for the order.
    $tracking = $this->paymentTracking->getTrackedAmountsForOrder($order);
    $default_value = [];
    /** @var \Drupal\commerce_price\Price|null $total */
    $total = NULL;
    foreach ($tracking as $target_id => $amount) {
      // Zero any negative amounts.
      if ($amount->isNegative()) {
        $amount = $amount->multiply('0');
      }

      // Track the total and add to the defaults.
      $total = $total ? $total->add($amount) : $amount;
      $default_value[] = ['target_id' => $target_id] + $amount->toArray();
    }

    // Add the refund in full option if there is a total paid on the order.
    if ($paid && $paid->isPositive()) {
      $full_label = $this->t('Refund the @paid paid.', [
        '@paid' => $this->currencyFormatter->format($paid->getNumber(), $paid->getCurrencyCode()),
      ]);
      TrackingElementTrait::addAllocationOption($inline_form['partial_payments_type'], 'full', $full_label, $paid, $default_value, -50);
      $inline_form['partial_payments_type']['#default_value'] = 'full';
    }
    // If this order has no total, warn that it's a free order.
    else {
      $this->messenger()->addWarning($this->t('There is no paid balance on this order.'));
    }

    // Add the specific tracking.
    $inline_form['order_item_tracking'] = [
      '#type' => 'commerce_partial_payments_tracked_amount',
      '#tracking' => $tracking,
      '#default_value' => $default_value,
      '#header' => [
        'label' => '',
        'price' => $this->t('Price'),
        'balance' => $this->t('Balance'),
        'number' => $this->t('Refund'),
      ],
      '#items' => [],
      '#empty' => $this->t('This order has no items.'),
      '#states' => [
        'visible' => [
          ':input[name="payment[partial_payments_type]"]' => ['value' => 'partial'],
        ],
        'required' => [
          ':input[name="payment[partial_payments_type]"]' => ['value' => 'partial'],
        ],
      ],
      '#weight' => 50,
    ];
    foreach ($order->getItems() as $item) {
      $inline_form['order_item_tracking']['#items'][$item->id()] = [
        'label' => $item->label(),
        'price' => $item->getAdjustedTotalPrice(),
      ];
    }

    // Set the order balance so we can dynamically show a warning.
    TrackingElementTrait::addTrackingJs($inline_form, [
      'warning' => $paid ? $paid->getNumber() : 0,
    ]);

    // Add the warning element, hidden by default.
    $inline_form['amount_warning'] = [
      '#theme_wrappers' => ['container'],
      '#weight' => 90,
      '#theme' => 'status_messages',
      '#message_list' => [
        'warning' => [
          $this->t('You are about to refund more than has been paid on the order.'),
        ],
      ],
      '#attributes' => [
        'class' => [
          'cpp-tracking-warning',
          'hidden',
        ],
      ],
    ];

    $inline_form['#cpp_validate'][] = '::buildPaymentTracking';
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc