Merge pull request #19806 from eileenmcnaughton/msg_compat
[civicrm-core.git] / tests / phpunit / CRM / Contribute / Form / Task / PDFLetterCommonTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Test APIv3 civicrm_contribute_* functions
14 *
15 * @package CiviCRM_APIv3
16 * @subpackage API_Contribution
17 * @group headless
18 */
19 class CRM_Contribute_Form_Task_PDFLetterCommonTest extends CiviUnitTestCase {
20
21 protected $_individualId;
22
23 protected $_docTypes;
24
25 protected $_contactIds;
26
27 /**
28 * Count how many times the hookTokens is called.
29 *
30 * This only needs to be called once, check refactoring doesn't change this.
31 *
32 * @var int
33 */
34 protected $hookTokensCalled = 0;
35
36 protected function setUp(): void {
37 parent::setUp();
38 $this->_individualId = $this->individualCreate(['first_name' => 'Anthony', 'last_name' => 'Collins']);
39 $this->_docTypes = CRM_Core_SelectValues::documentApplicationType();
40 }
41
42 /**
43 * Clean up after each test.
44 *
45 * @throws \CRM_Core_Exception
46 */
47 public function tearDown(): void {
48 $this->quickCleanUpFinancialEntities();
49 $this->quickCleanup(['civicrm_uf_match']);
50 CRM_Utils_Hook::singleton()->reset();
51 }
52
53 /**
54 * Test thank you send with grouping.
55 *
56 * @throws \CRM_Core_Exception
57 * @throws \CiviCRM_API3_Exception
58 */
59 public function testGroupedThankYous(): void {
60 $this->ids['Contact'][0] = $this->individualCreate();
61 $this->createLoggedInUser();
62 $contribution1ID = $this->callAPISuccess('Contribution', 'create', [
63 'contact_id' => $this->ids['Contact'][0],
64 'total_amount' => '60',
65 'financial_type_id' => 'Donation',
66 'currency' => 'USD',
67 'receive_date' => '2021-01-01 13:21',
68 ])['id'];
69 $contribution2ID = $this->callAPISuccess('Contribution', 'create', [
70 'contact_id' => $this->ids['Contact'][0],
71 'total_amount' => '70',
72 'financial_type_id' => 'Donation',
73 'receive_date' => '2021-02-01 2:21',
74 'currency' => 'USD',
75 ])['id'];
76 $form = $this->getFormObject('CRM_Contribute_Form_Task_PDFLetter', [
77 'campaign_id' => '',
78 'subject' => '',
79 'format_id' => '',
80 'paper_size' => 'letter',
81 'orientation' => 'portrait',
82 'metric' => 'in',
83 'margin_left' => '0.75',
84 'margin_right' => '0.75',
85 'margin_top' => '0.75',
86 'margin_bottom' => '0.75',
87 'document_type' => 'pdf',
88 'html_message' => '{contribution.currency} * {contribution.total_amount} * {contribution.receive_date}',
89 'template' => '',
90 'saveTemplateName' => '',
91 'from_email_address' => '185',
92 'thankyou_update' => '1',
93 'group_by' => 'contact_id',
94 'group_by_separator' => 'comma',
95 'email_options' => '',
96 ]);
97 $this->setSearchSelection([$contribution1ID, $contribution2ID], $form);
98 $form->preProcess();
99 try {
100 $form->postProcess();
101 }
102 catch (CRM_Core_Exception_PrematureExitException $e) {
103 $this->assertContains('USD, USD * $ 60.00, $ 70.00 * January 1st, 2021 1:21 PM, February 1st, 2021 2:21 AM', $e->errorData['html']);
104 }
105 }
106
107 /**
108 * Test the buildContributionArray function.
109 *
110 * @throws \CRM_Core_Exception|\CiviCRM_API3_Exception
111 */
112 public function testBuildContributionArray(): void {
113 $this->_individualId = $this->individualCreate();
114
115 $customGroup = $this->callAPISuccess('CustomGroup', 'create', [
116 'title' => 'Test Custom Set for Contribution',
117 'extends' => 'Contribution',
118 'is_active' => TRUE,
119 ]);
120 $params = [
121 'custom_group_id' => $customGroup['id'],
122 'label' => 'Text field',
123 'html_type' => 'Text',
124 'data_type' => 'String',
125 'weight' => 1,
126 'is_active' => 1,
127 ];
128 $customField = $this->callAPISuccess('CustomField', 'create', $params);
129 $customFieldKey = 'custom_' . $customField['id'];
130 $campaignTitle = 'Test Campaign ';
131
132 $params = [
133 'contact_id' => $this->_individualId,
134 'total_amount' => 6,
135 'campaign_id' => $this->campaignCreate(['title' => $campaignTitle], FALSE),
136 'financial_type_id' => 'Donation',
137 $customFieldKey => 'Text_' . substr(sha1(rand()), 0, 7),
138 ];
139 $contributionIDs = $returnProperties = [];
140 $result = $this->callAPISuccess('Contribution', 'create', $params);
141 $contributionIDs[] = $result['id'];
142 $this->hookClass->setHook('civicrm_tokenValues', [$this, 'hookTokenValues']);
143
144 // assume that there are two token {contribution.financial_type} and
145 // {contribution.custom_N} in message content
146 $messageToken = [
147 'contribution' => [
148 'financial_type',
149 'payment_instrument',
150 'campaign',
151 $customFieldKey,
152 ],
153 ];
154
155 [$contributions, $contacts] = CRM_Contribute_Form_Task_PDFLetterCommon::buildContributionArray('contact_id', $contributionIDs, $returnProperties, TRUE, TRUE, $messageToken, 'test', '**', FALSE);
156
157 $this->assertEquals('Anthony', $contacts[$this->_individualId]['first_name']);
158 $this->assertEquals('emo', $contacts[$this->_individualId]['favourite_emoticon']);
159 $this->assertEquals('Donation', $contributions[$result['id']]['financial_type']);
160 $this->assertEquals($campaignTitle, $contributions[$result['id']]['campaign']);
161 $this->assertEquals('Check', $contributions[$result['id']]['payment_instrument']);
162 // CRM-20359: assert that contribution custom field token is rightfully replaced by its value
163 $this->assertEquals($params[$customFieldKey], $contributions[$result['id']][$customFieldKey]);
164
165 $this->customFieldDelete($customField['id']);
166 $this->customGroupDelete($customGroup['id']);
167 }
168
169 /**
170 * Implement token values hook.
171 *
172 * @param array $details
173 * @param array $contactIDs
174 * @param int $jobID
175 * @param array $tokens
176 * @param string $className
177 */
178 public function hookTokenValues(&$details, $contactIDs, $jobID, $tokens, $className): void {
179 foreach ($details as $index => $detail) {
180 $details[$index]['favourite_emoticon'] = 'emo';
181 }
182 }
183
184 /**
185 * Test contribution token replacement in
186 * html returned by postProcess function.
187 *
188 * @throws \CiviCRM_API3_Exception
189 * @throws \CRM_Core_Exception
190 */
191 public function testPostProcess(): void {
192 $this->createLoggedInUser();
193 $this->_individualId = $this->individualCreate();
194 foreach (['docx', 'odt'] as $docType) {
195 $formValues = [
196 'is_unit_test' => TRUE,
197 'group_by' => NULL,
198 'document_file' => [
199 'name' => __DIR__ . "/sample_documents/Template.$docType",
200 'type' => $this->_docTypes[$docType],
201 ],
202 ];
203
204 $contributionParams = [
205 'contact_id' => $this->_individualId,
206 'total_amount' => 100,
207 'financial_type_id' => 'Donation',
208 ];
209 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
210 $contributionId = $contribution['id'];
211 /* @var $form CRM_Contribute_Form_Task_PDFLetter */
212 $form = $this->getFormObject('CRM_Contribute_Form_Task_PDFLetter');
213 $form->setContributionIds([$contributionId]);
214 $format = Civi::settings()->get('dateformatFull');
215 $date = CRM_Utils_Date::getToday();
216 $displayDate = CRM_Utils_Date::customFormat($date, $format);
217
218 $html = CRM_Contribute_Form_Task_PDFLetterCommon::postProcess($form, $formValues);
219 $expectedValues = [
220 'Hello Anthony',
221 '$ 100.00',
222 $displayDate,
223 'Donation',
224 'Domain Name - Default Domain Name',
225 ];
226
227 foreach ($expectedValues as $val) {
228 $this->assertTrue(strpos($html[$contributionId], $val) !== 0);
229 }
230 }
231 }
232
233 /**
234 * Test assignment of variables when using the group by function.
235 *
236 * We are looking to see that the contribution aggregate and contributions
237 * arrays reflect the most recent contact rather than a total aggregate,
238 * since we are using group by.
239 *
240 * @throws \CiviCRM_API3_Exception
241 * @throws \CRM_Core_Exception
242 */
243 public function testPostProcessGroupByContact(): void {
244 $this->createLoggedInUser();
245 $this->hookClass->setHook('civicrm_tokenValues', [$this, 'hook_aggregateTokenValues']);
246 $this->hookClass->setHook('civicrm_tokens', [$this, 'hook_tokens']);
247 $this->mut = new CiviMailUtils($this, TRUE);
248 $this->_individualId = $this->individualCreate();
249 $this->_individualId2 = $this->individualCreate();
250 $htmlMessage = "{aggregate.rendered_token}";
251 $formValues = [
252 'is_unit_test' => TRUE,
253 'group_by' => 'contact_id',
254 'html_message' => $htmlMessage,
255 'email_options' => 'both',
256 'subject' => 'Testy test test',
257 'from' => 'info@example.com',
258 ];
259
260 $contributionIDs = [];
261 $contribution = $this->callAPISuccess('Contribution', 'create', [
262 'contact_id' => $this->_individualId,
263 'total_amount' => 100,
264 'financial_type_id' => 'Donation',
265 'receive_date' => '2016-12-25',
266 ]);
267 $contributionIDs[] = $contribution['id'];
268 $contribution = $this->callAPISuccess('Contribution', 'create', [
269 'contact_id' => $this->_individualId2,
270 'total_amount' => 10,
271 'financial_type_id' => 'Donation',
272 'receive_date' => '2016-12-25',
273 ]);
274 $contributionIDs[] = $contribution['id'];
275
276 $contribution = $this->callAPISuccess('Contribution', 'create', [
277 'contact_id' => $this->_individualId2,
278 'total_amount' => 1,
279 'financial_type_id' => 'Donation',
280 'receive_date' => '2016-12-25',
281 ]);
282 $contributionIDs[] = $contribution['id'];
283
284 /* @var \CRM_Contribute_Form_Task_PDFLetter $form */
285 $form = $this->getFormObject('CRM_Contribute_Form_Task_PDFLetter');
286 $form->setContributionIds($contributionIDs);
287
288 $html = CRM_Contribute_Form_Task_PDFLetterCommon::postProcess($form, $formValues);
289 $this->assertEquals("<table border='1' cellpadding='2' cellspacing='0' class='table'>
290 <tbody>
291 <tr>
292 <th>Date</th>
293 <th>Amount</th>
294 <th>Financial Type</th>
295 <th>Source</th>
296 </tr>
297 <!--
298 -->
299 <tr>
300 <td>25 December 2016</td>
301 <td>$ 100.00</td>
302 <td>Donation</td>
303 <td></td>
304 </tr>
305 <!--
306 -->
307 <tr>
308 <td><strong>Total</strong></td>
309 <td><strong>$ 100.00</strong></td>
310 <td></td>
311 <td></td>
312 </tr>
313 </tbody>
314 </table>", $html[1]);
315 $this->assertEquals("<table border='1' cellpadding='2' cellspacing='0' class='table'>
316 <tbody>
317 <tr>
318 <th>Date</th>
319 <th>Amount</th>
320 <th>Financial Type</th>
321 <th>Source</th>
322 </tr>
323 <!--
324 -->
325 <tr>
326 <td>25 December 2016</td>
327 <td>$ 10.00</td>
328 <td>Donation</td>
329 <td></td>
330 </tr>
331 <!--
332 -->
333 <tr>
334 <td>25 December 2016</td>
335 <td>$ 1.00</td>
336 <td>Donation</td>
337 <td></td>
338 </tr>
339 <!--
340 -->
341 <tr>
342 <td><strong>Total</strong></td>
343 <td><strong>$ 11.00</strong></td>
344 <td></td>
345 <td></td>
346 </tr>
347 </tbody>
348 </table>", $html[2]);
349
350 $activities = $this->callAPISuccess('Activity', 'get', ['activity_type_id' => 'Print PDF Letter', 'sequential' => 1]);
351 $this->assertEquals(2, $activities['count']);
352 $this->assertEquals($html[1], $activities['values'][0]['details']);
353 $this->assertEquals($html[2], $activities['values'][1]['details']);
354 // Checking it is not called multiple times.
355 // once for each contact create + once for the activities.
356 $this->assertEquals(3, $this->hookTokensCalled);
357 $this->mut->checkAllMailLog($html);
358
359 }
360
361 /**
362 * Implements civicrm_tokens().
363 */
364 public function hook_tokens(&$tokens) {
365 $this->hookTokensCalled++;
366 $tokens['aggregate'] = ['rendered_token' => 'rendered_token'];
367 }
368
369 /**
370 * Get the html message.
371 *
372 * @return string
373 */
374 public function getHtmlMessage() {
375 return '{assign var=\'contact_aggregate\' value=0}
376 <table border=\'1\' cellpadding=\'2\' cellspacing=\'0\' class=\'table\'>
377 <tbody>
378 <tr>
379 <th>Date</th>
380 <th>Amount</th>
381 <th>Financial Type</th>
382 <th>Source</th>
383 </tr>
384 <!--
385 {foreach from=$contributions item=contribution}
386 {if $contribution.contact_id == $messageContactID}
387 {assign var=\'date\' value=$contribution.receive_date|date_format:\'%d %B %Y\'}
388 {assign var=contact_aggregate
389 value=$contact_aggregate+$contribution.total_amount}
390 -->
391 <tr>
392 <td>{$date}</td>
393 <td>{$contribution.total_amount|crmMoney}</td>
394 <td>{$contribution.financial_type}</td>
395 <td></td>
396 </tr>
397 <!--
398 {/if}
399 {/foreach}
400 -->
401 <tr>
402 <td><strong>Total</strong></td>
403 <td><strong>{$contact_aggregate|crmMoney}</strong></td>
404 <td></td>
405 <td></td>
406 </tr>
407 </tbody>
408 </table>';
409 }
410
411 /**
412 * Implements CiviCRM hook.
413 *
414 * @param array $values
415 * @param array $contactIDs
416 * @param null $job
417 * @param array $tokens
418 * @param null $context
419 */
420 public function hook_aggregateTokenValues(&$values, $contactIDs, $job = NULL, $tokens = [], $context = NULL) {
421 foreach ($contactIDs as $contactID) {
422 CRM_Core_Smarty::singleton()->assign('messageContactID', $contactID);
423 $values[$contactID]['aggregate.rendered_token'] = CRM_Core_Smarty::singleton()
424 ->fetch('string:' . $this->getHtmlMessage());
425 }
426 }
427
428 /**
429 * @param string $token
430 * @param string $entity
431 * @param string $textToSearch
432 * @param bool $expected
433 *
434 * @dataProvider isHtmlTokenInTableCellProvider
435 */
436 public function testIsHtmlTokenInTableCell($token, $entity, $textToSearch, $expected) {
437 $this->assertEquals($expected,
438 CRM_Contribute_Form_Task_PDFLetterCommon::isHtmlTokenInTableCell($token, $entity, $textToSearch)
439 );
440 }
441
442 public function isHtmlTokenInTableCellProvider() {
443 return [
444
445 'simplest TRUE' => [
446 'token',
447 'entity',
448 '<td>{entity.token}</td>',
449 TRUE,
450 ],
451
452 'simplest FALSE' => [
453 'token',
454 'entity',
455 '{entity.token}',
456 FALSE,
457 ],
458
459 'token between two tables' => [
460 'token',
461 'entity',
462 ' <table><tr><td>Top</td></tr></table>
463 {entity.token}
464 <table><tr><td>Bottom</td></tr></table>',
465 FALSE,
466 ],
467
468 'token in two tables' => [
469 'token',
470 'entity',
471 ' <table><tr><td>{entity.token}</td></tr><tr><td>foo</td></tr></table>
472 <table><tr><td>{entity.token}</td></tr><tr><td>foo</td></tr></table>',
473 TRUE,
474 ],
475
476 'token outside of table and inside of table' => [
477 'token',
478 'entity',
479 ' {entity.token}
480 <table><tr><td>{entity.token}</td></tr><tr><td>foo</td></tr></table>',
481 FALSE,
482 ],
483
484 'token inside more complicated table' => [
485 'token',
486 'entity',
487 ' <table><tr><td class="foo"><em>{entity.token}</em></td></tr></table>',
488 TRUE,
489 ],
490
491 'token inside something that looks like table cell' => [
492 'token',
493 'entity',
494 ' <tdata>{entity.token}</tdata>
495 <table><tr><td>Bottom</td></tr></table>',
496 FALSE,
497 ],
498
499 ];
500 }
501
502 /**
503 * @param array $entities
504 * @param \CRM_Core_Form $form
505 */
506 protected function setSearchSelection(array $entities, CRM_Core_Form $form): void {
507 $_SESSION['_' . $form->controller->_name . '_container']['values']['Search'] = [
508 'radio_ts' => 'ts_sel',
509 ];
510 foreach ($entities as $entityID) {
511 $_SESSION['_' . $form->controller->_name . '_container']['values']['Search']['mark_x_' . $entityID] = TRUE;
512 }
513 }
514
515 }