billwerk_subscriptions-1.x-dev/modules/billwerk_subscriptions_entities/src/Entity/BillwerkComponent.php
modules/billwerk_subscriptions_entities/src/Entity/BillwerkComponent.php
<?php
declare(strict_types=1);
namespace Drupal\billwerk_subscriptions_entities\Entity;
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 component (add-on) entity class.
*
* @ContentEntityType(
* id = "billwerk_component",
* label = @Translation("Billwerk Component (Add-on)"),
* label_collection = @Translation("Billwerk Components (Add-ons)"),
* label_singular = @Translation("Billwerk Component (Add-on)"),
* label_plural = @Translation("Billwerk Components (Add-ons)"),
* label_count = @PluralTranslation(
* singular = "@count Billwerk Components (Add-on)",
* plural = "@count Billwerk Components (Add-ons)",
* ),
* handlers = {
* "list_builder" = "Drupal\billwerk_subscriptions_entities\BillwerkComponentListBuilder",
* "views_data" = "Drupal\views\EntityViewsData",
* "access" = "Drupal\billwerk_subscriptions_entities\BillwerkComponentAccessControlHandler",
* "form" = {
* "add" = "Drupal\billwerk_subscriptions_entities\Form\BillwerkComponentForm",
* "edit" = "Drupal\billwerk_subscriptions_entities\Form\BillwerkComponentForm",
* "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
* "delete-multiple-confirm" = "Drupal\Core\Entity\Form\DeleteMultipleForm",
* },
* "route_provider" = {
* "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
* },
* },
* base_table = "billwerk_component",
* data_table = "billwerk_component_field_data",
* revision_table = "billwerk_component_revision",
* revision_data_table = "billwerk_component_field_revision",
* show_revision_ui = TRUE,
* translatable = TRUE,
* admin_permission = "administer billwerk_component",
* 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/component",
* "add-form" = "/admin/content/billwerk/component/add",
* "canonical" = "/admin/content/billwerk/component/{billwerk_component}",
* "edit-form" = "/admin/content/billwerk/component/{billwerk_component}/edit",
* "delete-form" = "/admin/content/billwerk/component/{billwerk_component}/delete",
* "delete-multiple-form" = "/admin/content/billwerk/component/delete-multiple",
* },
* field_ui_base_route = "entity.billwerk_component.settings",
* )
*/
final class BillwerkComponent extends BillwerkFeeEntityAbstract implements BillwerkSubscribeableEntityInterface {
use StringTranslationTrait;
/**
* {@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)
->addConstraint('UniqueField', [])
->addPropertyConstraints('value', ['Regex' => ['pattern' => '/^[a-z0-9_]+$/']])
->setDisplayOptions('form', [
'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' => -4,
])
->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 component 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 component 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 component (add-on) was created.'))
->setDisplayConfigurable('form', TRUE)
->setDisplayOptions('form', [
'type' => 'datetime_timestamp',
'weight' => 20,
])
->setDisplayOptions('view', [
'label' => 'above',
'type' => 'timestamp',
'weight' => 20,
'region' => 'hidden',
])
->setDisplayConfigurable('view', TRUE);
$fields['changed'] = BaseFieldDefinition::create('changed')
->setLabel(t('Changed'))
->setTranslatable(TRUE)
->setDescription(t('The time that the billwerk component (add-on) was last edited.'));
return $fields;
}
/**
* {@inheritDoc}
*/
protected function getBillwerkProductInfoType(): string {
return 'Components';
}
/**
* Get the Billwerk product info description for the given environment.
*/
public function getBillwerkProductInfoDescription(?string $environmentName = NULL): string {
$billwerkData = $this->getBillwerkProductInfo($environmentName);
return $billwerkData['Description'] ?? NULL;
}
/**
* Get the Billwerk product info component type for the given environment.
*/
public function getBillwerkProductInfoComponentType(?string $environmentName = NULL): string {
$billwerkData = $this->getBillwerkProductInfo($environmentName);
return $billwerkData['ComponentType'] ?? NULL;
}
/**
* Gets Billwerk product info recurring price cents for the given environment.
*/
public function getBillwerkProductInfoRecurringPriceCents(?string $environmentName = NULL): int {
$billwerkData = $this->getBillwerkProductInfo($environmentName);
// If PricePerUnit is empty, we can assume it's free.
return !empty($billwerkData['PricePerUnit']) ? (int) ($billwerkData['PricePerUnit'] * 100) : 0;
}
/**
* {@inheritDoc}
*/
public function isSubscribed(AccountProxyInterface $user): bool {
// The user is subscribed, if they has 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)) {
return FALSE;
}
return $user->isAuthenticated();
}
/**
* {@inheritDoc}
*/
public function accessUnsubscribe(AccountProxyInterface $user): bool {
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('Register 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' => [
'add-component' => $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;
}
}
