Merge pull request #19494 from seamuslee001/apiv4_annon_access
[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 = NULL;
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() {
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() {
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
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) {
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 $form = new CRM_Contribute_Form_Task_PDFLetter();
212 $form->setContributionIds([$contributionId]);
213 $format = Civi::settings()->get('dateformatFull');
214 $date = CRM_Utils_Date::getToday();
215 $displayDate = CRM_Utils_Date::customFormat($date, $format);
216
217 $html = CRM_Contribute_Form_Task_PDFLetterCommon::postProcess($form, $formValues);
218 $expectedValues = [
219 'Hello Anthony',
220 '$ 100.00',
221 $displayDate,
222 'Donation',
223 'Domain Name - Default Domain Name',
224 ];
225
226 foreach ($expectedValues as $val) {
227 $this->assertTrue(strpos($html[$contributionId], $val) !== 0);
228 }
229 }
230 }
231
232 /**
233 * Test assignment of variables when using the group by function.
234 *
235 * We are looking to see that the contribution aggregate and contributions
236 * arrays reflect the most recent contact rather than a total aggregate,
237 * since we are using group by.
238 *
239 * @throws \CiviCRM_API3_Exception
240 * @throws \CRM_Core_Exception
241 */
242 public function testPostProcessGroupByContact(): void {
243 $this->createLoggedInUser();
244 $this->hookClass->setHook('civicrm_tokenValues', [$this, 'hook_aggregateTokenValues']);
245 $this->hookClass->setHook('civicrm_tokens', [$this, 'hook_tokens']);
246 $this->mut = new CiviMailUtils($this, TRUE);
247 $this->_individualId = $this->individualCreate();
248 $this->_individualId2 = $this->individualCreate();
249 $htmlMessage = "{aggregate.rendered_token}";
250 $formValues = [
251 'is_unit_test' => TRUE,
252 'group_by' => 'contact_id',
253 'html_message' => $htmlMessage,
254 'email_options' => 'both',
255 'subject' => 'Testy test test',
256 'from' => 'info@example.com',
257 ];
258
259 $contributionIDs = [];
260 $contribution = $this->callAPISuccess('Contribution', 'create', [
261 'contact_id' => $this->_individualId,
262 'total_amount' => 100,
263 'financial_type_id' => 'Donation',
264 'receive_date' => '2016-12-25',
265 ]);
266 $contributionIDs[] = $contribution['id'];
267 $contribution = $this->callAPISuccess('Contribution', 'create', [
268 'contact_id' => $this->_individualId2,
269 'total_amount' => 10,
270 'financial_type_id' => 'Donation',
271 'receive_date' => '2016-12-25',
272 ]);
273 $contributionIDs[] = $contribution['id'];
274
275 $contribution = $this->callAPISuccess('Contribution', 'create', [
276 'contact_id' => $this->_individualId2,
277 'total_amount' => 1,
278 'financial_type_id' => 'Donation',
279 'receive_date' => '2016-12-25',
280 ]);
281 $contributionIDs[] = $contribution['id'];
282
283 $form = new CRM_Contribute_Form_Task_PDFLetter();
284 $form->setContributionIds($contributionIDs);
285
286 $html = CRM_Contribute_Form_Task_PDFLetterCommon::postProcess($form, $formValues);
287 $this->assertEquals("<table border='1' cellpadding='2' cellspacing='0' class='table'>
288 <tbody>
289 <tr>
290 <th>Date</th>
291 <th>Amount</th>
292 <th>Financial Type</th>
293 <th>Source</th>
294 </tr>
295 <!--
296 -->
297 <tr>
298 <td>25 December 2016</td>
299 <td>$ 100.00</td>
300 <td>Donation</td>
301 <td></td>
302 </tr>
303 <!--
304 -->
305 <tr>
306 <td><strong>Total</strong></td>
307 <td><strong>$ 100.00</strong></td>
308 <td></td>
309 <td></td>
310 </tr>
311 </tbody>
312 </table>", $html[1]);
313 $this->assertEquals("<table border='1' cellpadding='2' cellspacing='0' class='table'>
314 <tbody>
315 <tr>
316 <th>Date</th>
317 <th>Amount</th>
318 <th>Financial Type</th>
319 <th>Source</th>
320 </tr>
321 <!--
322 -->
323 <tr>
324 <td>25 December 2016</td>
325 <td>$ 10.00</td>
326 <td>Donation</td>
327 <td></td>
328 </tr>
329 <!--
330 -->
331 <tr>
332 <td>25 December 2016</td>
333 <td>$ 1.00</td>
334 <td>Donation</td>
335 <td></td>
336 </tr>
337 <!--
338 -->
339 <tr>
340 <td><strong>Total</strong></td>
341 <td><strong>$ 11.00</strong></td>
342 <td></td>
343 <td></td>
344 </tr>
345 </tbody>
346 </table>", $html[2]);
347
348 $activities = $this->callAPISuccess('Activity', 'get', ['activity_type_id' => 'Print PDF Letter', 'sequential' => 1]);
349 $this->assertEquals(2, $activities['count']);
350 $this->assertEquals($html[1], $activities['values'][0]['details']);
351 $this->assertEquals($html[2], $activities['values'][1]['details']);
352 // Checking it is not called multiple times.
353 // once for each contact create + once for the activities.
354 $this->assertEquals(3, $this->hookTokensCalled);
355 $this->mut->checkAllMailLog($html);
356
357 }
358
359 /**
360 * Implements civicrm_tokens().
361 */
362 public function hook_tokens(&$tokens) {
363 $this->hookTokensCalled++;
364 $tokens['aggregate'] = ['rendered_token' => 'rendered_token'];
365 }
366
367 /**
368 * Get the html message.
369 *
370 * @return string
371 */
372 public function getHtmlMessage() {
373 return '{assign var=\'contact_aggregate\' value=0}
374 <table border=\'1\' cellpadding=\'2\' cellspacing=\'0\' class=\'table\'>
375 <tbody>
376 <tr>
377 <th>Date</th>
378 <th>Amount</th>
379 <th>Financial Type</th>
380 <th>Source</th>
381 </tr>
382 <!--
383 {foreach from=$contributions item=contribution}
384 {if $contribution.contact_id == $messageContactID}
385 {assign var=\'date\' value=$contribution.receive_date|date_format:\'%d %B %Y\'}
386 {assign var=contact_aggregate
387 value=$contact_aggregate+$contribution.total_amount}
388 -->
389 <tr>
390 <td>{$date}</td>
391 <td>{$contribution.total_amount|crmMoney}</td>
392 <td>{$contribution.financial_type}</td>
393 <td></td>
394 </tr>
395 <!--
396 {/if}
397 {/foreach}
398 -->
399 <tr>
400 <td><strong>Total</strong></td>
401 <td><strong>{$contact_aggregate|crmMoney}</strong></td>
402 <td></td>
403 <td></td>
404 </tr>
405 </tbody>
406 </table>';
407 }
408
409 /**
410 * Implements CiviCRM hook.
411 *
412 * @param array $values
413 * @param array $contactIDs
414 * @param null $job
415 * @param array $tokens
416 * @param null $context
417 */
418 public function hook_aggregateTokenValues(&$values, $contactIDs, $job = NULL, $tokens = [], $context = NULL) {
419 foreach ($contactIDs as $contactID) {
420 CRM_Core_Smarty::singleton()->assign('messageContactID', $contactID);
421 $values[$contactID]['aggregate.rendered_token'] = CRM_Core_Smarty::singleton()
422 ->fetch('string:' . $this->getHtmlMessage());
423 }
424 }
425
426 /**
427 * @param string $token
428 * @param string $entity
429 * @param string $textToSearch
430 * @param bool $expected
431 *
432 * @dataProvider isHtmlTokenInTableCellProvider
433 */
434 public function testIsHtmlTokenInTableCell($token, $entity, $textToSearch, $expected) {
435 $this->assertEquals($expected,
436 CRM_Contribute_Form_Task_PDFLetterCommon::isHtmlTokenInTableCell($token, $entity, $textToSearch)
437 );
438 }
439
440 public function isHtmlTokenInTableCellProvider() {
441 return [
442
443 'simplest TRUE' => [
444 'token',
445 'entity',
446 '<td>{entity.token}</td>',
447 TRUE,
448 ],
449
450 'simplest FALSE' => [
451 'token',
452 'entity',
453 '{entity.token}',
454 FALSE,
455 ],
456
457 'token between two tables' => [
458 'token',
459 'entity',
460 ' <table><tr><td>Top</td></tr></table>
461 {entity.token}
462 <table><tr><td>Bottom</td></tr></table>',
463 FALSE,
464 ],
465
466 'token in two tables' => [
467 'token',
468 'entity',
469 ' <table><tr><td>{entity.token}</td></tr><tr><td>foo</td></tr></table>
470 <table><tr><td>{entity.token}</td></tr><tr><td>foo</td></tr></table>',
471 TRUE,
472 ],
473
474 'token outside of table and inside of table' => [
475 'token',
476 'entity',
477 ' {entity.token}
478 <table><tr><td>{entity.token}</td></tr><tr><td>foo</td></tr></table>',
479 FALSE,
480 ],
481
482 'token inside more complicated table' => [
483 'token',
484 'entity',
485 ' <table><tr><td class="foo"><em>{entity.token}</em></td></tr></table>',
486 TRUE,
487 ],
488
489 'token inside something that looks like table cell' => [
490 'token',
491 'entity',
492 ' <tdata>{entity.token}</tdata>
493 <table><tr><td>Bottom</td></tr></table>',
494 FALSE,
495 ],
496
497 ];
498 }
499
500 /**
501 * @param array $entities
502 * @param \CRM_Core_Form $form
503 */
504 protected function setSearchSelection(array $entities, CRM_Core_Form $form): void {
505 $_SESSION['_' . $form->controller->_name . '_container']['values']['Search'] = [
506 'radio_ts' => 'ts_sel',
507 ];
508 foreach ($entities as $entityID) {
509 $_SESSION['_' . $form->controller->_name . '_container']['values']['Search']['mark_x_' . $entityID] = TRUE;
510 }
511 }
512
513 }