Skip to content

Commit

Permalink
Merge pull request #21666 from eileenmcnaughton/ev
Browse files Browse the repository at this point in the history
 dev/core#348 Participant tokens on scheduled reminders
  • Loading branch information
colemanw authored Oct 2, 2021
2 parents 9cb2f53 + e80f226 commit abf64eb
Show file tree
Hide file tree
Showing 8 changed files with 298 additions and 120 deletions.
2 changes: 1 addition & 1 deletion CRM/Admin/Form/ScheduleReminders.php
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ public function listTokens() {
$tokenProcessor = new \Civi\Token\TokenProcessor(\Civi::dispatcher(), [
'controller' => get_class(),
'smarty' => FALSE,
'schema' => ['activityId'],
'schema' => ['activityId', 'participantId'],
]);
$tokens = $tokenProcessor->listTokens();

Expand Down
2 changes: 1 addition & 1 deletion CRM/Contact/Form/Task/EmailTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ protected function saveMessageTemplate($formValues) {
*
* @return array
*/
public function listTokens() {
public function listTokens(): array {
return CRM_Core_SelectValues::contactTokens();
}

Expand Down
82 changes: 80 additions & 2 deletions CRM/Core/EntityTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
*/

use Civi\Token\AbstractTokenSubscriber;
use Civi\Token\Event\TokenRegisterEvent;
use Civi\Token\Event\TokenValueEvent;
use Civi\Token\TokenRow;
use Civi\ActionSchedule\Event\MailingQueryEvent;
Expand All @@ -33,6 +34,27 @@ class CRM_Core_EntityTokens extends AbstractTokenSubscriber {
*/
protected $prefetch = [];

/**
* Register the declared tokens.
*
* @param \Civi\Token\Event\TokenRegisterEvent $e
* The registration event. Add new tokens using register().
*/
public function registerTokens(TokenRegisterEvent $e) {
if (!$this->checkActive($e->getTokenProcessor())) {
return;
}
foreach ($this->getAllTokens() as $name => $label) {
if (!in_array($name, $this->getHiddenTokens(), TRUE)) {
$e->register([
'entity' => $this->entity,
'field' => $name,
'label' => $label,
]);
}
}
}

/**
* @inheritDoc
* @throws \CRM_Core_Exception
Expand All @@ -56,6 +78,10 @@ public function evaluateToken(TokenRow $row, $entity, $field, $prefetch = NULL)
return $row->tokens($entity, $field, $this->getPseudoValue($split[0], $split[1], $this->getFieldValue($row, $split[0])));
}
if ($this->isCustomField($field)) {
$prefetchedValue = $this->getCustomFieldValue($this->getFieldValue($row, 'id'), $field);
if ($prefetchedValue) {
return $row->format('text/html')->tokens($entity, $field, $prefetchedValue);
}
return $row->customToken($entity, \CRM_Core_BAO_CustomField::getKeyID($field), $this->getFieldValue($row, 'id'));
}
if ($this->isMoneyField($field)) {
Expand Down Expand Up @@ -148,7 +174,7 @@ protected function getAllTokens(): array {
unset($basicTokens[$fieldName]);
}
}
return array_merge($basicTokens, $this->getPseudoTokens(), CRM_Utils_Token::getCustomFieldTokens($this->getApiEntityName()));
return array_merge($basicTokens, $this->getPseudoTokens(), $this->getBespokeTokens(), CRM_Utils_Token::getCustomFieldTokens($this->getApiEntityName()));
}

/**
Expand Down Expand Up @@ -246,6 +272,13 @@ public function getPseudoTokens(): array {
return $return;
}

/**
* Get any tokens with custom calculation.
*/
public function getBespokeTokens(): array {
return [];
}

/**
* Is this a field we should add pseudo-tokens to?
*
Expand All @@ -256,7 +289,7 @@ public function getPseudoTokens(): array {
* @param string $fieldName
*/
public function isAddPseudoTokens($fieldName): bool {
if ($fieldName === 'currency') {
if (in_array($fieldName, $this->getCurrencyFieldName())) {
// 'currency' is manually added to the skip list as an anomaly.
// name & label aren't that suitable for 'currency' (symbol, which
// possibly maps to 'abbr' would be) and we can't gather that
Expand Down Expand Up @@ -314,6 +347,9 @@ protected function getFieldValue(TokenRow $row, string $field) {
return $actionSearchResult->{$aliasedField};
}
$entityID = $row->context[$this->getEntityIDField()];
if ($field === 'id') {
return $entityID;
}
return $this->prefetch[$entityID][$field] ?? '';
}

Expand Down Expand Up @@ -353,6 +389,17 @@ public function alterActionScheduleQuery(MailingQueryEvent $e): void {
}
}

/**
* Get tokens to be suppressed from the widget.
*
* Note this is expected to be an interim function. Now we are no
* longer working around the parent function we can just define them once...
* with metadata, in a future refactor.
*/
protected function getHiddenTokens(): array {
return [];
}

/**
* Get tokens supporting the syntax we are migrating to.
*
Expand Down Expand Up @@ -488,4 +535,35 @@ public function getDependencies(): array {
return [];
}

/**
* Get the apiv4 style custom field name.
*
* @param int $id
*
* @return string
*/
protected function getCustomFieldName(int $id): string {
foreach ($this->getFieldMetadata() as $key => $field) {
if (($field['custom_field_id'] ?? NULL) === $id) {
return $key;
}
}
}

/**
* @param $entityID
* @param string $field eg. 'custom_1'
*
* @return array|string|void|null $mixed
*
* @throws \CRM_Core_Exception
*/
protected function getCustomFieldValue($entityID, string $field) {
$id = str_replace('custom_', '', $field);
$value = $this->prefetch[$entityID][$this->getCustomFieldName($id)] ?? NULL;
if ($value !== NULL) {
return CRM_Core_BAO_CustomField::displayValue($value, $id);
}
}

}
27 changes: 9 additions & 18 deletions CRM/Core/SelectValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -590,28 +590,19 @@ public static function contactTokens(): array {
/**
* Different type of Participant Tokens.
*
* @deprecated
*
* @return array
*/
public static function participantTokens(): array {
$tokens = [
'{participant.status_id}' => 'Status ID',
'{participant.role_id}' => 'Participant Role (ID)',
'{participant.register_date}' => 'Register date',
'{participant.source}' => 'Participant Source',
'{participant.fee_level}' => 'Fee level',
'{participant.fee_amount}' => 'Fee Amount',
'{participant.registered_by_id}' => 'Registered By Participant ID',
'{participant.transferred_to_contact_id}' => 'Transferred to Contact ID',
'{participant.role_id:label}' => 'Participant Role (label)',
'{participant.fee_label}' => 'Fee Label',
];
$customFields = CRM_Core_BAO_CustomField::getFields('Participant');

foreach ($customFields as $customField) {
$tokens['{participant.custom_' . $customField['id'] . '}'] = $customField['label'] . " :: " . $customField['groupTitle'];
$tokenProcessor = new TokenProcessor(Civi::dispatcher(), ['schema' => ['participantId']]);
$allTokens = $tokenProcessor->listTokens();
foreach (array_keys($allTokens) as $token) {
if (strpos($token, '{domain.') === 0) {
unset($allTokens[$token]);
}
}

return $tokens;
return $allTokens;
}

/**
Expand Down
63 changes: 63 additions & 0 deletions CRM/Event/ParticipantTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,22 @@
+--------------------------------------------------------------------+
*/

use Civi\Token\TokenRow;

/**
* Class CRM_Event_ParticipantTokens
*
* Generate "participant.*" tokens.
*/
class CRM_Event_ParticipantTokens extends CRM_Core_EntityTokens {

public static function getSubscribedEvents() {
$events = parent::getSubscribedEvents();
// Set the weight so it runs before event tokens.
$events['civi.token.eval'] = ['evaluateTokens', 400];
return $events;
}

/**
* Get the entity name for api v4 calls.
*
Expand All @@ -33,4 +42,58 @@ public function getCurrencyFieldName(): array {
return ['fee_currency'];
}

/**
* Get any tokens with custom calculation.
*/
public function getBespokeTokens(): array {
return ['balance' => ts('Event Balance')];
}

/**
* @inheritDoc
* @throws \CiviCRM_API3_Exception
*/
public function evaluateToken(TokenRow $row, $entity, $field, $prefetch = NULL) {
$this->prefetch = (array) $prefetch;
if (empty($row->context['eventId'])) {
$row->context['eventId'] = $this->getFieldValue($row, 'event_id');
}
if ($field === 'balance') {
// @todo - is this really a good idea to call this & potentially get the
// balance of the contribution attached to 'registered_by_id'
$info = \CRM_Contribute_BAO_Contribution::getPaymentInfo($this->getFieldValue($row, 'id'), 'event');
$balancePay = $info['balance'] ?? NULL;
$balancePay = \CRM_Utils_Money::format($balancePay);
$row->tokens($entity, $field, $balancePay);
return;
}
parent::evaluateToken($row, $entity, $field, $prefetch);
}

/**
* Do not show event id in the UI as event.id will also be available.
*
* Discount id is probably a bit esoteric.
*
* @return string[]
*/
protected function getHiddenTokens(): array {
return ['event_id', 'discount_id'];
}

/**
* Get entity fields that should not be exposed as tokens.
*
* @return string[]
*/
public function getSkippedFields(): array {
$fields = parent::getSkippedFields();
// Never add these 2 fields - may not be a stable part of the schema.
// This field is on it's way out of core.
$fields[] = 'cart_id';
// this will probably get schema changed out of the table at some point.
$fields[] = 'is_pay_later';
return $fields;
}

}
Loading

0 comments on commit abf64eb

Please sign in to comment.