billwerk_subscriptions-1.x-dev/src/Form/BillwerkUserRefreshSubscriptionForm.php

src/Form/BillwerkUserRefreshSubscriptionForm.php
<?php

declare(strict_types=1);

namespace Drupal\billwerk_subscriptions\Form;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\billwerk_subscriptions\Api;
use Drupal\billwerk_subscriptions\Subscriber;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Billwerk Subscriptions form.
 */
final class BillwerkUserRefreshSubscriptionForm extends FormBase {

  /**
   * The Billwerk API.
   *
   * @var \Drupal\billwerk_subscriptions\Api
   */
  public function __construct(
    protected readonly Api $api,
  ) {
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this form class.
    return new static(
    // Load the service required to construct this class.
    $container->get('billwerk_subscriptions.api')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'billwerk_subscriptions_billwerk_user_refresh_subscription';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?AccountInterface $user = NULL): array {
    if ($user) {
      $form_state->set('user', $user);

      $subscriber = Subscriber::load($user);
      if (!$subscriber->hasUserBillwerkContractId()) {
        $form['message'] = [
          '#type' => 'inline_template',
          '#template' => '<div class="messages messages--warning"><div class="message">This user does not have any Billwerk Contract ID set. Assign a Billwerk Contract ID and vice-versa add the Drupal user id (UID) in the Billwerk: "External Customer ID" field to connect the user account from both sides.</div></div>',
          '#context' => [],
        ];
        return $form;
      }

      $form['intro'] = [
        '#type' => 'container',
        'intro' => [
          '#prefix' => '<p><strong>',
          '#suffix' => '</strong></p>',
          '#markup' => $this->t('This administrative action will <em>not</em> change any data at Billwerk.<br />Only the Drupal user profile will be updated to match the current subscription.'),
        ],
        'description' => [
          '#prefix' => '<p>',
          '#suffix' => '</p>',
          '#markup' => $this->t('By pressing the "Refresh user subscription" Button, %user\'s (UID %uid) data will be refreshed from Billwerk. Applying the latest state from Billwerk Contract that can be associated with this user (e.g. active subscription status, user data and respective roles). What exactly happens is subject to the subscription handler implementation used.', [
            '%uid' => $user->id(),
            '%user' => $user->getDisplayName(),
          ]),
        ],
      ];

      // @improve We should better move this into a separate Billwerk API Debug Tab with separate permissions.
      $form['contract_information'] = [
        '#type' => 'inline_template',
        '#template' => '<h2>Billwerk API information:</h2>
          <dl>
            <dt>Environment:</dt>
            <dd>{{ environment }}</dd>
            <dt>Billwerk Contract ID (from Drupal user profile):</dt>
            <dd>{{ billwerkContractId }}</dd>
            <dt>Contract:</dt>
            <dd><pre><code>{{ contractData }}</code></pre></dd>
            <dt>Customer (Contract owner):</dt>
            <dd><pre><code>{{ customerData }}</code></pre></dd>
          </dl>',
        '#context' => [
          'environment' => $this->api->getEnvironment()->getEnvironmentName(),
          'billwerkContractId' => $subscriber->getUserBillwerkContractId(),
          'customerData' => json_encode($this->api->getCustomer($subscriber->getBillwerkCustomer()->getId()), JSON_PRETTY_PRINT),
          'contractData' => json_encode($this->api->getContractSubscriptions($subscriber->getUserBillwerkContractId()), JSON_PRETTY_PRINT),
        ],
      ];

      $form['actions'] = [
        '#type' => 'actions',
        'submit' => [
          '#type' => 'submit',
          '#value' => $this->t('Refresh user subscription'),
        ],
      ];
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $user = $form_state->get('user');
    $subscriber = Subscriber::load($user);
    $subscriber->refreshFromBillwerkContractSubscription();
    $this->messenger()->addStatus($this->t(
    "%user's subscription has been refreshed.",
    [
      '%user' => $user->getDisplayName(),
    ]
    ));
  }

  /**
   * Checks access for a specific request.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The subscriber user which is being viewed.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account, AccountInterface $user) {
    // Warning: $account is the current user accessing the controller!
    return AccessResult::allowedIfHasPermission($account, 'billwerk_subscriptions_manual_refresh_user_subscriptions')
      ->andIf(AccessResult::allowedIf(!$account->isAnonymous() && Subscriber::loadByDrupalUid((int) $user->id())->hasUserBillwerkContractId()));
  }

}

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

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