Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Msg template rendered content api #17162

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 19 additions & 26 deletions CRM/Activity/Form/Task/PDFLetterCommon.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
+--------------------------------------------------------------------+
*/

use Civi\Token\TokenProcessor;

/**
* This class provides the common functionality for creating PDF letter for
* activities.
Expand Down Expand Up @@ -42,35 +40,30 @@ public static function postProcess(&$form) {
* Produce the document from the activities
* This uses the new token processor
*
* @param array $activityIds array of activity ids
* @param string $html_message message text with tokens
* @param array $formValues formValues from the form
* @param array $activityIds array of activity ids
* @param string $html_message message text with tokens
* @param array $formValues formValues from the form
*
* @return array
*
* @return string
* @throws \API_Exception
*/
public static function createDocument($activityIds, $html_message, $formValues) {
$tp = self::createTokenProcessor();
$tp->addMessage('body_html', $html_message, 'text/html');

foreach ($activityIds as $activityId) {
$tp->addRow()->context('activity_id', $activityId);
$result = \Civi\Api4\MessageTemplate::render()
->addMessage(['string' => $html_message, 'format' => 'text/html', 'key' => 'html_string'])
->setEntity('Activity')
->setEntityIds(['Activity' => $activityIds])
->setCheckPermissions(FALSE)
->execute();
$html = [];
foreach ($result as $htmDetail) {
$html[] = $htmDetail['html_string'];
}
$tp->evaluate();

return self::renderFromRows($tp->getRows(), 'body_html', $formValues);
}

/**
* Create a token processor
*
* @return \Civi\Token\TokenProcessor
*/
public static function createTokenProcessor() {
return new TokenProcessor(\Civi::dispatcher(), [
'controller' => get_class(),
'smarty' => FALSE,
'schema' => ['activity_id'],
]);
if (!empty($formValues['is_unit_test'])) {
return $html;
}
self::outputFromHtml($html, $formValues);
}

}
27 changes: 0 additions & 27 deletions CRM/Core/Form/Task/PDFLetterCommon.php
Original file line number Diff line number Diff line change
Expand Up @@ -327,33 +327,6 @@ public static function formatMessage(&$message) {
$message = implode($newLineOperators['p']['oper'], $htmlMsg);
}

/**
* Render html from rows
*
* @param $rows
* @param string $msgPart
* The name registered with the TokenProcessor
* @param array $formValues
* The values submitted through the form
*
* @return array
* If formValues['is_unit_test'] is true, otherwise outputs document to browser
*/
public static function renderFromRows($rows, $msgPart, $formValues) {
$html = [];
foreach ($rows as $row) {
$html[] = $row->render($msgPart);
}

if (!empty($formValues['is_unit_test'])) {
return $html;
}

if (!empty($html)) {
self::outputFromHtml($formValues, $html);
}
}

/**
* List the available tokens
* @return array of token name => label
Expand Down
173 changes: 173 additions & 0 deletions Civi/Api4/Action/MessageTemplate/Render.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
<?php


namespace Civi\Api4\Action\MessageTemplate;

use Civi\Api4\Generic\Result;
use Civi\Token\TokenProcessor;

/**
* Class Render.
*
* Get the content of an email for the given template text, rendering tokens.
*
* @method int setMessageTemplateId(int $messageTemplateID) Set Message Template ID.
* @method int getMessageTemplateId(int $messageTemplateID) Get Message Template ID.
* @method string setMessageSubject(string $messageSubject) Set Message Subject
* @method string getMessageSubject(string $messageSubject) Get Message Subject
* @method string setMessageHtml(string $messageHtml) Set Message Html
* @method string getMessageHtml string $messageHtml) Get Message Html
* @method string setMessageText(string $messageHtml) Set Message Text
* @method string getMessageText string $messageHtml) Get Message Text
* @method string getMessages(array $stringToParse) Get array of adhoc strings to parse.
* @method string setMessages(array $stringToParse) Set array of adhoc strings to parse.
* @method array setEntity(string $entity) Set entity.
* @method array getEntity(string $entity) Get entity.
* @method array setEntityIds(array $entityIds) Set entity IDs
* @method array getEntityIds(array $entityIds) Get entity IDs
*/
class Render extends \Civi\Api4\Generic\AbstractAction {

/**
* ID of message template.
*
* It is necessary to pass this or at least one string.
*
* @var int
*/
protected $messageTemplateId;

/**
* Ad hoc html strings to parse.
*
* Array of adhoc strings arrays to pass e.g
* [
* ['string' => 'Dear {contact.first_name}', 'format' => 'text/html', 'key' => 'greeting'],
* ['string' => 'Also known as {contact.first_name}', 'format' => 'text/plain', 'key' => 'nick_name'],
* ]
*
* If no provided the key will default to 'string' and the format will default to 'text'
*
* @var array
*/
protected $messages = [];

/**
* String to be returned as the subject.
*
* @var string
*/
protected $messageSubject;

/**
* String to be returned as the subject.
*
* @var string
*/
protected $messageText;

/**
* String to be returned as the subject.
*
* @var string
*/
protected $messageHtml;

/**
* Entity for which tokens need to be resolved.
*
* This is required if tokens related to the entity are to be parsed and the entity cannot
* be derived from the message_template.
*
* Only Activity is currently supported in this initial implementation.
*
* @var string
*
* @options Activity
*
*/
protected $entity;

/**
* An array of one of more ids for which the html should be rendered.
*
* These will be the keys of the returned results.
*
* @var array
*/
protected $entityIds = [];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If $entity is single-valued then this should probably be as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No - one entity - ie Activity - but many ids - results in a row per id returned - that is how it's used in the PdfTemplate code - which might be printing multiple pdfs for multiple activities


/**
* @inheritDoc
*/
public function _run(Result $result) {
$tokenProcessor = new TokenProcessor(\Civi::dispatcher(), [
'controller' => get_class(),
'smarty' => FALSE,
// Only activities, for now.... @todo - extend...
'schema' => [$this->getEntity() => $this->getEntityKey()],
]);

foreach ($this->getEntityIds() as $entity => $ids) {
foreach ($this->getStringsToParse() as $fieldKey => $textField) {
if (empty($textField['string'])) {
continue;
}
foreach ($ids as $id) {
$tokenProcessor->addRow()->context($this->getEntityKey(), $id);
$tokenProcessor->addMessage($fieldKey, $textField['string'], $textField['format']);
$tokenProcessor->evaluate();
foreach ($tokenProcessor->getRows() as $row) {
/* @var \Civi\Token\TokenRow $row */
$result[$id][$fieldKey] = $row->render($fieldKey);
}
}
}

}
}

/**
* Array holding
* - string String to parse, required
* - key Key to key by in results, defaults to 'string'
* - format - format passed to token providers.
*
* @param array $stringDetails
*
* @return \Civi\Api4\Action\MessageTemplate\Render
*/
public function addMessage(array $stringDetails) {
$this->messages[] = $stringDetails;
return $this;
}

/**
* Get the strings to render civicrm tokens for.
*
* @return array
*/
protected function getStringsToParse(): array {
$textFields = [
'msg_html' => ['string' => $this->getMessageHtml(), 'format' => 'text/html', 'key' => 'msg_html'],
'msg_subject' => ['string' => $this->getMessageSubject(), 'format' => 'text/plain', 'key' => 'msg_subject'],
'msg_text' => ['string' => $this->getMessageText(), 'format' => 'text/plain', 'key' => 'msg_text'],
];
foreach ($this->getMessages() as $message) {
$message['key'] = $message['key'] ?? 'string';
$message['format'] = $message['format'] ?? 'text/plain';
$textFields[$message['key']] = $message;
}
return $textFields;
}

/**
* Get the key to use for the entity ID field.
*
* @return string
*/
protected function getEntityKey(): string {
return strtolower($this->getEntity()) . '_id';
}

}
2 changes: 0 additions & 2 deletions Civi/Api4/Generic/AbstractAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
* $Id$
*
*/

namespace Civi\Api4\Generic;
Expand Down
9 changes: 9 additions & 0 deletions Civi/Api4/MessageTemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,13 @@
*/
class MessageTemplate extends Generic\DAOEntity {

/**
* @return \Civi\Api4\Action\MessageTemplate\Render
*
* @throws \API_Exception
*/
public static function render() {
return new Action\MessageTemplate\Render(__CLASS__, __FUNCTION__);
}

}
15 changes: 12 additions & 3 deletions tests/phpunit/CRM/Activity/Form/Task/PDFLetterCommonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public function tearDown() {
*
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
* @throws \API_Exception
*/
public function testCreateDocumentBasicTokens() {
$activity = $this->activityCreate();
Expand All @@ -44,11 +45,19 @@ public function testCreateDocumentBasicTokens() {
}
}

/**
* Test custom field tokens are rendered.
*
* @throws \API_Exception
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
public function testCreateDocumentCustomFieldTokens() {
// Set up custom group, and field
// returns custom_group_id, custom_field_id, custom_field_option_group_id, custom_field_group_options
$cg = $this->entityCustomGroupWithSingleStringMultiSelectFieldCreate("MyCustomField", "ActivityTest.php");
$cg = $this->entityCustomGroupWithSingleStringMultiSelectFieldCreate('MyCustomField', 'ActivityTest.php');
$cf = 'custom_' . $cg['custom_field_id'];
$activities = [];
foreach (array_keys($cg['custom_field_group_options']) as $option) {
$activity = $this->activityCreate([$cf => $option]);
$activities[] = [
Expand All @@ -61,11 +70,11 @@ public function testCreateDocumentCustomFieldTokens() {
$activityIds = CRM_Utils_Array::collect('id', $activities);
$output = CRM_Activity_Form_Task_PDFLetterCommon::createDocument($activityIds, $html_message, ['is_unit_test' => TRUE]);
// Should have one row of output per activity
$this->assertEquals(count($activities), count($output));
$this->assertCount(count($activities), $output);

// Check each line has the correct substitution
foreach ($output as $key => $line) {
$this->assertEquals($line, "Custom: " . $cg['custom_field_group_options'][$activities[$key]['option']]);
$this->assertEquals($line, 'Custom: ' . $cg['custom_field_group_options'][$activities[$key]['option']]);
}
}

Expand Down