billwerk_subscriptions-1.x-dev/modules/billwerk_subscriptions_entities/src/Entity/BillwerkPlanVariant.php

modules/billwerk_subscriptions_entities/src/Entity/BillwerkPlanVariant.php
<?php

declare(strict_types=1);

namespace Drupal\billwerk_subscriptions_entities\Entity;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;

/**
 * Defines the billwerk plan variant entity class.
 *
 * @ContentEntityType(
 *   id = "billwerk_plan_variant",
 *   label = @Translation("Billwerk Plan-Variant"),
 *   label_collection = @Translation("Billwerk Plan-Variants"),
 *   label_singular = @Translation("Billwerk Plan-Variant"),
 *   label_plural = @Translation("Billwerk Plan-Variants"),
 *   label_count = @PluralTranslation(
 *     singular = "@count Billwerk Plan-Variants",
 *     plural = "@count Billwerk Plan-Variants",
 *   ),
 *   handlers = {
 *     "list_builder" = "Drupal\billwerk_subscriptions_entities\BillwerkPlanVariantListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" = "Drupal\billwerk_subscriptions_entities\BillwerkPlanVariantAccessControlHandler",
 *     "form" = {
 *       "add" = "Drupal\billwerk_subscriptions_entities\Form\BillwerkPlanVariantForm",
 *       "edit" = "Drupal\billwerk_subscriptions_entities\Form\BillwerkPlanVariantForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *       "delete-multiple-confirm" = "Drupal\Core\Entity\Form\DeleteMultipleForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "billwerk_plan_variant",
 *   data_table = "billwerk_plan_variant_field_data",
 *   revision_table = "billwerk_plan_variant_revision",
 *   revision_data_table = "billwerk_plan_variant_field_revision",
 *   show_revision_ui = TRUE,
 *   translatable = TRUE,
 *   admin_permission = "administer billwerk_plan_variant",
 *   entity_keys = {
 *     "id" = "id",
 *     "revision" = "revision_id",
 *     "langcode" = "langcode",
 *     "label" = "label",
 *     "uuid" = "uuid",
 *     "owner" = "uid",
 *     "machine_name" = "machine_name",
 *     "hidden" = "hidden",
 *     "role" = "role",
 *     "weight" = "weight",
 *     "billwerk_id_production" = "billwerk_id_production",
 *     "billwerk_id_sandbox" = "billwerk_id_sandbox",
 *   },
 *   revision_metadata_keys = {
 *     "revision_user" = "revision_uid",
 *     "revision_created" = "revision_timestamp",
 *     "revision_log_message" = "revision_log",
 *   },
 *   links = {
 *     "collection" = "/admin/content/billwerk/plan-variant",
 *     "add-form" = "/admin/content/billwerk/plan-variant/add",
 *     "canonical" = "/admin/content/billwerk/plan-variant/{billwerk_plan_variant}",
 *     "edit-form" = "/admin/content/billwerk/plan-variant/{billwerk_plan_variant}/edit",
 *     "delete-form" = "/admin/content/billwerk/plan-variant/{billwerk_plan_variant}/delete",
 *     "delete-multiple-form" = "/admin/content/billwerk/plan-variant/delete-multiple",
 *   },
 *   field_ui_base_route = "entity.billwerk_plan_variant.settings",
 * )
 */
final class BillwerkPlanVariant extends BillwerkFeeEntityAbstract implements BillwerkSubscribeableEntityInterface {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage): void {
    parent::preSave($storage);
    if (!$this->getOwnerId()) {
      // If no owner has been set explicitly, make the anonymous user the owner.
      $this->setOwnerId(0);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {

    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setLabel(t('Label'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['machine_name'] = BaseFieldDefinition::create('string')
      ->setRevisionable(TRUE)
      ->setTranslatable(FALSE)
      ->setLabel(t('Machine name'))
      ->setDescription(t('The human readable machine name, typically set as external_id at Billwerk.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 256)
      // @todo Postponed on: https://www.drupal.org/node/3028311:
      // ->addConstraint('UniqueField', [])
      ->addPropertyConstraints('value', ['Regex' => ['pattern' => '/^[a-z0-9_]+$/']])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        // @todo Postponed on: https://www.drupal.org/node/3028311:
        // 'type' => 'machine_name',
        'weight' => -5,
        'settings' => [
          'source_field' => 'label',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -5,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setRevisionable(TRUE)
      ->setLabel(t('Status'))
      ->setDefaultValue(TRUE)
      ->setSetting('on_label', 'Enabled')
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => FALSE,
        ],
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'boolean',
        'label' => 'above',
        'weight' => -4,
        'settings' => [
          'format' => 'enabled-disabled',
        ],
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['hidden'] = BaseFieldDefinition::create('boolean')
      ->setRevisionable(TRUE)
      ->setLabel(t('Hidden'))
      ->setDescription(t('Allows hiding components that are available, but should not be shown for (public) booking'))
      ->setDefaultValue(FALSE)
      ->setSetting('on_label', 'Hidden')
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => FALSE,
        ],
        'weight' => -3,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'boolean',
        'label' => 'above',
        'weight' => -3,
        'settings' => [
          'format' => 'enabled-disabled',
        ],
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['role'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Role'))
      ->setDescription(t('The associated user role that is assigned to the user when this add-on is actively subscribed to.'))
      ->setSettings([
        'allowed_values' => \Drupal::service('billwerk_subscriptions_handler_default.billwerk_roles_manager')->getBillwerkRolesSelectOptions(),
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => -3,
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -3,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setRequired(TRUE);

    $fields['weight'] = BaseFieldDefinition::create('integer')
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setLabel(t('Weight'))
      ->setDescription(t('The weight in lists and tables. Lower weight is shown more prominent (top).'))
      ->setDisplayOptions('form', [
        'type' => 'number',
        'weight' => -2,
      ])
      ->setDefaultValue(0)
      ->setRequired(TRUE)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'number_integer',
        'label' => 'above',
        'weight' => -2,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['billwerk_id_production'] = BaseFieldDefinition::create('string')
      ->setRevisionable(TRUE)
      ->setTranslatable(FALSE)
      ->setLabel(t('Billwerk ID (Production)'))
      ->setDescription(t('The ID from Billwerk for this plan variant from the <em>production</em> environment. Connects the entity with the saas record.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -1,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -1,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['billwerk_id_sandbox'] = BaseFieldDefinition::create('string')
      ->setRevisionable(TRUE)
      ->setTranslatable(FALSE)
      ->setLabel(t('Billwerk ID (Sandbox)'))
      ->setDescription(t('The ID from Billwerk for this plan variant from the <em>sandbox</em> environment. Connects the entity with the saas record.'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 0,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['description'] = BaseFieldDefinition::create('text_long')
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setLabel(t('Description'))
      ->setDisplayOptions('form', [
        'type' => 'text_textarea',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'text_default',
        'label' => 'hidden',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setLabel(t('Author'))
      ->setSetting('target_type', 'user')
      ->setDefaultValueCallback(self::class . '::getDefaultEntityOwner')
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => 60,
          'placeholder' => '',
        ],
        'weight' => 15,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'inline',
        'type' => 'author',
        'weight' => 15,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setTranslatable(TRUE)
      ->setDescription(t('The time that the billwerk plan variant was created.'))
      ->setDisplayOptions('form', [
        'type' => 'datetime_timestamp',
        'weight' => 20,
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'timestamp',
        'weight' => 20,
        'region' => 'hidden',
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setTranslatable(TRUE)
      ->setDescription(t('The time that the billwerk plan variant was last edited.'));

    return $fields;
  }

  /**
   * Returns the BillwerkPlan.
   *
   * @return \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlan
   *   The BillwerkPlan entity.
   */
  public function getBillwerkPlan(): BillwerkPlan {
    /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlan $billwerkPlan */
    $billwerkPlanArray = $this->get('field_billwerk_plan')->referencedEntities();
    $billwerkPlan = reset($billwerkPlanArray);
    return $billwerkPlan;
  }

  /**
   * Returns the upgradable to BillwerkPlanVariants array.
   *
   * @return \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlanVariant[]
   *   The upgradable-to referenced entities.
   */
  public function getUpgradeableTo(): array {
    return $this->get('field_plan_variant_upgr_to')->referencedEntities();
  }

  /**
   * Returns the downgradeable to BillwerkPlanVariants array.
   *
   * @return \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlanVariant[]
   *   The downgradeable-to entities.
   */
  public function getDowngradeableTo(): array {
    return $this->get('field_plan_variant_downgr_to')->referencedEntities();
  }

  /**
   * Returns true if the given $billwerkPlanVariant would be an upgrade.
   *
   * This is for example needed to determine, if a selected plan switch
   * is an upgrade or a downgrade, because billed upgrades typically should
   * happen immediately, but downgrades should respect the contract end date.
   *
   * @param \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlanVariant $billwerkPlanVariant
   *   The BillwerkPlanVariant to check.
   */
  public function isUpgrade(BillwerkPlanVariant $billwerkPlanVariant): bool {
    $upgradeableToBillwerkPlanVariants = $this->getUpgradeableTo();
    foreach ($upgradeableToBillwerkPlanVariants as $upgradeableToBillwerkPlanVariant) {
      if ($billwerkPlanVariant->id() === $upgradeableToBillwerkPlanVariant->id()) {
        return TRUE;
      }
    }
    return FALSE;
  }

  /**
   * {@inheritDoc}
   */
  protected function getBillwerkProductInfoType(): string {
    return 'PlanVariants';
  }

  /**
   * {@inheritDoc}
   */
  public function getBillwerkProductInfoRecurringPriceCents(?string $environmentName = NULL): int {
    $billwerkData = $this->getBillwerkProductInfo($environmentName);
    // If RecurringPrice is an empty array, we can assume it's free.
    return !empty($billwerkData['RecurringPrice']['PricePerUnit']) ? (int) ($billwerkData['RecurringPrice']['PricePerUnit'] * 100) : 0;
  }

  /**
   * {@inheritDoc}
   */
  public function getBillwerkProductInfoOneOffPriceCents(?string $environmentName = NULL): int {
    $billwerkData = $this->getBillwerkProductInfo($environmentName);
    // If OneOffPrice is an empty array, we can assume it's free.
    return !empty($billwerkData['OneOffPrice']) ? $billwerkData['OneOffPrice'] * 100 : 0;
  }

  /**
   * {@inheritDoc}
   */
  public function getBillwerkProductInfoInternalName(?string $environmentName = NULL): string {
    $billwerkData = $this->getBillwerkProductInfo($environmentName);
    return $billwerkData['InternalName'] ?? NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function getBillwerkProductInfoExternalId(?string $environmentName = NULL): string {
    $billwerkData = $this->getBillwerkProductInfo($environmentName);
    return $billwerkData['ExternalId'] ?? NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function getBillwerkProductInfoDescription(?string $environmentName = NULL): string {
    $billwerkData = $this->getBillwerkProductInfo($environmentName);
    return $billwerkData['Description'] ?? NULL;
  }

  /**
   * {@inheritDoc}
   */
  public function isSubscribed(AccountProxyInterface $user): bool {
    // The user is subscribed, if they have the role of this component.
    return in_array($this->getRoleId(), $user->getRoles(TRUE));
  }

  /**
   * {@inheritDoc}
   */
  public function accessSubscribe(AccountProxyInterface $user): bool {
    if (!$this->isEnabled() || $this->isHidden() || $this->isSubscribed($user) || $user->isAnonymous()) {
      return FALSE;
    }

    $downgradeablePlanVariants = $this->getDowngradeableTo();
    foreach ($downgradeablePlanVariants as $planVariant) {
      /** @var \Drupal\billwerk_subscriptions_entities\Entity\BillwerkPlanVariant $planVariant */
      if ($planVariant->isSubscribed($user)) {
        return TRUE;
      }
    }

    return FALSE;
  }

  /**
   * {@inheritDoc}
   */
  public function accessUnsubscribe(AccountProxyInterface $user): bool {
    if (!$this->isEnabled() || $this->isHidden()) {
      // Do not show a button for disabled or hidden:
      return FALSE;
    }

    return $this->isSubscribed($user);
  }

  /**
   * {@inheritDoc}
   */
  public function buildSubscribeButton(
    AccountProxyInterface $user,
    bool $modal = FALSE,
    array $additionalClasses = ['secondary', 'expanded'],
  ): array {
    $build = [];

    // Anonymous user always see the trial button for all plans:
    if ($user->isAnonymous()) {
      $build = [
        '#type' => 'link',
        '#title' => $this->t('Try for free now!'),
        '#url' => Url::fromRoute('user.register'),
        '#attributes' => [
          'class' => ['button', ...$additionalClasses],
        ],
      ];
    }

    // Regular users only see the upgrade buttons they should:
    if ($this->accessSubscribe($user)) {
      $build = [
        '#type' => 'link',
        '#title' => $this->t('Manage subscriptions'),
        '#url' => Url::fromRoute('billwerk_subscriptions_manage.current_user_subscription', [], [
          'query' => [
            'planvariant' => $this->getMachineName(),
          ],
        ]),
        '#attributes' => [
          'class' => ['button', ...$additionalClasses],
        ],
      ];
    }

    // Add modal, if enabled:
    if ($modal && !empty($build)) {
      // Add modal classes and library, if enabled:
      $build['#attributes']['class'][] = 'use-ajax';
      $build['#attributes']['data-dialog-type'] = 'modal';
      $build['#attached']['library'][] = 'core/drupal.dialog.ajax';
    }

    // Cache by user.
    $build['#cache']['contexts'][] = 'user';

    // Add the cacheable dependencies:
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($build, $user);
    $renderer->addCacheableDependency($build, $this);

    return $build;
  }

}

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

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