Merge pull request #21139 from totten/master-msgtpl-class
[civicrm-core.git] / tests / phpunit / api / v3 / ContributionTest.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 use Civi\Api4\ActivityContact;
13 use Civi\Api4\Contribution;
14 use Civi\Api4\PriceField;
15 use Civi\Api4\PriceFieldValue;
16 use Civi\Api4\PriceSet;
17
18 /**
19 * Test APIv3 civicrm_contribute_* functions
20 *
21 * @package CiviCRM_APIv3
22 * @subpackage API_Contribution
23 * @group headless
24 */
25 class api_v3_ContributionTest extends CiviUnitTestCase {
26
27 use CRMTraits_Profile_ProfileTrait;
28 use CRMTraits_Custom_CustomDataTrait;
29 use CRMTraits_Financial_OrderTrait;
30 use CRMTraits_Financial_TaxTrait;
31 use CRMTraits_Financial_PriceSetTrait;
32
33 protected $_individualId;
34 protected $_contribution;
35 protected $_financialTypeId = 1;
36 protected $entity = 'Contribution';
37 protected $_params;
38 protected $_ids = [];
39 protected $_pageParams = [];
40
41 /**
42 * Payment processor ID (dummy processor).
43 *
44 * @var int
45 */
46 protected $paymentProcessorID;
47
48 /**
49 * Parameters to create payment processor.
50 *
51 * @var array
52 */
53 protected $_processorParams = [];
54
55 /**
56 * ID of created event.
57 *
58 * @var int
59 */
60 protected $_eventID;
61
62 /**
63 * @var CiviMailUtils
64 */
65 protected $mut;
66
67 /**
68 * Should financials be checked after the test but before tear down.
69 *
70 * @var bool
71 */
72 protected $isValidateFinancialsOnPostAssert = TRUE;
73
74 /**
75 * Setup function.
76 */
77 public function setUp(): void {
78 parent::setUp();
79
80 $this->_apiversion = 3;
81 $this->_individualId = $this->individualCreate();
82 $this->_params = [
83 'contact_id' => $this->_individualId,
84 'receive_date' => '20120511',
85 'total_amount' => 100.00,
86 'financial_type_id' => $this->_financialTypeId,
87 'non_deductible_amount' => 10.00,
88 'fee_amount' => 5.00,
89 'net_amount' => 95.00,
90 'source' => 'SSF',
91 'contribution_status_id' => 1,
92 ];
93 $this->_processorParams = [
94 'domain_id' => 1,
95 'name' => 'Dummy',
96 'payment_processor_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', 'Dummy'),
97 'financial_account_id' => 12,
98 'is_active' => 1,
99 'user_name' => '',
100 'url_site' => 'http://dummy.com',
101 'url_recur' => 'http://dummy.com',
102 'billing_mode' => 1,
103 ];
104 $this->paymentProcessorID = $this->processorCreate();
105 $this->_pageParams = [
106 'title' => 'Test Contribution Page',
107 'financial_type_id' => 1,
108 'currency' => 'USD',
109 'financial_account_id' => 1,
110 'payment_processor' => $this->paymentProcessorID,
111 'is_active' => 1,
112 'is_allow_other_amount' => 1,
113 'min_amount' => 10,
114 'max_amount' => 1000,
115 ];
116 }
117
118 /**
119 * Clean up after each test.
120 *
121 * @throws \API_Exception
122 * @throws \CRM_Core_Exception
123 */
124 public function tearDown(): void {
125 $this->quickCleanUpFinancialEntities();
126 $this->quickCleanup(['civicrm_uf_match'], TRUE);
127 $financialAccounts = $this->callAPISuccess('FinancialAccount', 'get', ['return' => 'name']);
128 foreach ($financialAccounts['values'] as $financialAccount) {
129 if ($financialAccount['name'] === 'Test Tax financial account ' || $financialAccount['name'] === 'Test taxable financial Type') {
130 $entityFinancialTypes = $this->callAPISuccess('EntityFinancialAccount', 'get', [
131 'financial_account_id' => $financialAccount['id'],
132 ]);
133 foreach ($entityFinancialTypes['values'] as $entityFinancialType) {
134 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialType['id']]);
135 }
136 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
137 }
138 }
139 $this->restoreUFGroupOne();
140 parent::tearDown();
141 }
142
143 /**
144 * Test Get.
145 */
146 public function testGetContribution(): void {
147 $this->enableTaxAndInvoicing();
148 $p = [
149 'contact_id' => $this->_individualId,
150 'receive_date' => '2010-01-20',
151 'total_amount' => 100.00,
152 'financial_type_id' => $this->_financialTypeId,
153 'non_deductible_amount' => 10.00,
154 'fee_amount' => 5.00,
155 'net_amount' => 95.00,
156 'trxn_id' => 23456,
157 'invoice_id' => 78910,
158 'source' => 'SSF',
159 'contribution_status_id' => 'Completed',
160 ];
161 $this->_contribution = $this->callAPISuccess('contribution', 'create', $p);
162
163 $params = [
164 'contribution_id' => $this->_contribution['id'],
165 'return' => array_merge(['invoice_number', 'contribution_source'], array_keys($p)),
166 ];
167
168 $contributions = $this->callAPIAndDocument('Contribution', 'get', $params, __FUNCTION__, __FILE__);
169
170 $this->assertEquals(1, $contributions['count']);
171 $contribution = $contributions['values'][$contributions['id']];
172 $this->assertEquals($this->_individualId, $contribution['contact_id']);
173 $this->assertEquals(1, $contribution['financial_type_id']);
174 $this->assertEquals(100.00, $contribution['total_amount']);
175 $this->assertEquals(10.00, $contribution['non_deductible_amount']);
176 $this->assertEquals(5.00, $contribution['fee_amount']);
177 $this->assertEquals(95.00, $contribution['net_amount']);
178 $this->assertEquals(23456, $contribution['trxn_id']);
179 $this->assertEquals(78910, $contribution['invoice_id']);
180 $this->assertRegExp('/INV_\d+/', $contribution['invoice_number']);
181 $this->assertEquals('SSF', $contribution['contribution_source']);
182 $this->assertEquals('Completed', $contribution['contribution_status']);
183 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
184 $p['trxn_id'] = '3847';
185 $p['invoice_id'] = '3847';
186
187 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
188
189 // Now we have 2 - test getcount.
190 $contribution = $this->callAPISuccess('contribution', 'getcount');
191 $this->assertEquals(2, $contribution);
192 // Test id only format.
193 $contribution = $this->callAPISuccess('contribution', 'get', [
194 'id' => $this->_contribution['id'],
195 'format.only_id' => 1,
196 ]);
197 $this->assertEquals($this->_contribution['id'], $contribution, print_r($contribution, TRUE));
198 // Test id only format.
199 $contribution = $this->callAPISuccess('contribution', 'get', [
200 'id' => $contribution2['id'],
201 'format.only_id' => 1,
202 ]);
203 $this->assertEquals($contribution2['id'], $contribution);
204 // Test id as field.
205 $contribution = $this->callAPISuccess('contribution', 'get', [
206 'id' => $this->_contribution['id'],
207 ]);
208 $this->assertEquals(1, $contribution['count']);
209
210 // Test get by contact id works.
211 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId]);
212
213 $this->assertEquals(2, $contribution['count']);
214 $this->callAPISuccess('Contribution', 'Delete', [
215 'id' => $this->_contribution['id'],
216 ]);
217 $this->callAPISuccess('Contribution', 'Delete', [
218 'id' => $contribution2['id'],
219 ]);
220 }
221
222 /**
223 * Test that test contributions can be retrieved.
224 *
225 * @throws \CRM_Core_Exception
226 */
227 public function testGetTestContribution(): void {
228 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params, ['is_test' => 1]));
229 $this->callAPISuccessGetSingle('Contribution', ['is_test' => 1]);
230 }
231
232 /**
233 * Test Creating a check contribution with original check_number field
234 *
235 * @throws \CRM_Core_Exception
236 */
237 public function testCreateCheckContribution(): void {
238 $params = $this->_params;
239 $params['contribution_check_number'] = 'bouncer';
240 $params['payment_instrument_id'] = 'Check';
241 $params['cancel_date'] = 'yesterday';
242 $params['receipt_date'] = 'yesterday';
243 $params['thankyou_date'] = 'yesterday';
244 $params['revenue_recognition_date'] = 'yesterday';
245 $params['amount_level'] = 'Unreasonable';
246 $params['cancel_reason'] = 'You lose sucker';
247 $params['creditnote_id'] = 'sudo rm -rf';
248 $address = $this->callAPISuccess('Address', 'create', [
249 'street_address' => 'Knockturn Alley',
250 'contact_id' => $this->_individualId,
251 'location_type_id' => 'Home',
252 ]);
253 $params['address_id'] = $address['id'];
254 $contributionPage = $this->contributionPageCreate();
255 $params['contribution_page_id'] = $contributionPage['id'];
256 $params['campaign_id'] = $this->campaignCreate();
257 $contributionID = $this->contributionCreate($params);
258 $getResult = $this->callAPISuccess('Contribution', 'get', [
259 'id' => $contributionID,
260 'return' => 'check_number',
261 ])['values'][$contributionID];
262 $this->assertEquals('bouncer', $getResult['check_number']);
263 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
264 'entity_id' => $contributionID,
265 'entity_table' => 'civicrm_contribution',
266 'return' => 'financial_trxn_id',
267 ]);
268 foreach ($entityFinancialTrxn['values'] as $eft) {
269 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'get', [
270 'id' => $eft['financial_trxn_id'],
271 'return' => 'check_number',
272 ]);
273 $this->assertEquals('bouncer', $financialTrxn['values'][$financialTrxn['id']]['check_number']);
274 }
275 }
276
277 /**
278 * Test the 'return' param works for all fields.
279 */
280 public function testGetContributionReturnFunctionality(): void {
281 $params = $this->_params;
282 $params['contribution_check_number'] = 'bouncer';
283 $params['payment_instrument_id'] = 'Check';
284 $params['cancel_date'] = 'yesterday';
285 $params['receipt_date'] = 'yesterday';
286 $params['thankyou_date'] = 'yesterday';
287 $params['revenue_recognition_date'] = 'yesterday';
288 $params['amount_level'] = 'Unreasonable';
289 $params['cancel_reason'] = 'You lose sucker';
290 $params['creditnote_id'] = 'sudo rm -rf';
291 $address = $this->callAPISuccess('Address', 'create', [
292 'street_address' => 'Knockturn Alley',
293 'contact_id' => $this->_individualId,
294 'location_type_id' => 'Home',
295 ]);
296 $params['address_id'] = $address['id'];
297 $contributionPage = $this->contributionPageCreate();
298 $params['contribution_page_id'] = $contributionPage['id'];
299 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
300 'contact_id' => $this->_individualId,
301 'frequency_interval' => 1,
302 'amount' => 5,
303 ]);
304 $params['contribution_recur_id'] = $contributionRecur['id'];
305
306 $params['campaign_id'] = $this->campaignCreate();
307
308 $contributionID = $this->contributionCreate($params);
309
310 // update contribution with invoice number
311 $params = array_merge($params, [
312 'id' => $contributionID,
313 'invoice_number' => Civi::settings()->get('invoice_prefix') . $contributionID,
314 'trxn_id' => 12345,
315 'invoice_id' => 6789,
316 ]);
317 $contributionID = $this->contributionCreate($params);
318
319 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID]);
320 $this->assertEquals('bouncer', $contribution['check_number']);
321 $this->assertEquals('bouncer', $contribution['contribution_check_number']);
322
323 $fields = CRM_Contribute_BAO_Contribution::fields();
324 // Do not check for tax_amount as this test has not enabled invoicing
325 // & hence it is not reliable.
326 unset($fields['tax_amount']);
327 // Re-add these 2 to the fields to check. They were locked in but the metadata changed so we
328 // need to specify them.
329 $fields['address_id'] = $fields['contribution_address_id'];
330 $fields['check_number'] = $fields['contribution_check_number'];
331
332 $fieldsLockedIn = [
333 'contribution_id', 'contribution_contact_id', 'financial_type_id', 'contribution_page_id',
334 'payment_instrument_id', 'receive_date', 'non_deductible_amount', 'total_amount',
335 'fee_amount', 'net_amount', 'trxn_id', 'invoice_id', 'currency', 'contribution_cancel_date', 'cancel_reason',
336 'receipt_date', 'thankyou_date', 'contribution_source', 'amount_level', 'contribution_recur_id',
337 'is_test', 'is_pay_later', 'contribution_status_id', 'address_id', 'check_number', 'contribution_campaign_id',
338 'creditnote_id', 'revenue_recognition_date', 'decoy',
339 ];
340 $missingFields = array_diff($fieldsLockedIn, array_keys($fields));
341 // If any of the locked in fields disappear from the $fields array we need to make sure it is still
342 // covered as the test contract now guarantees them in the return array.
343 $this->assertEquals([28 => 'decoy'], $missingFields, 'A field which was covered by the test contract has changed.');
344 foreach ($fields as $fieldName => $fieldSpec) {
345 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => $fieldName]);
346 $returnField = $fieldName;
347 if ($returnField === 'contribution_contact_id') {
348 $returnField = 'contact_id';
349 }
350 $this->assertTrue((!empty($contribution[$returnField]) || $contribution[$returnField] === "0"), $returnField);
351 }
352 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
353 'entity_id' => $contributionID,
354 'entity_table' => 'civicrm_contribution',
355 'return' => 'financial_trxn_id',
356 ]);
357 foreach ($entityFinancialTrxn['values'] as $eft) {
358 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'get', ['id' => $eft['financial_trxn_id'], 'return' => 'check_number']);
359 $this->assertEquals('bouncer', $financialTrxn['values'][$financialTrxn['id']]['check_number']);
360 }
361 }
362
363 /**
364 * Test cancel reason works as a filter.
365 *
366 * @throws \CRM_Core_Exception
367 */
368 public function testFilterCancelReason(): void {
369 $params = $this->_params;
370 $params['cancel_date'] = 'yesterday';
371 $params['cancel_reason'] = 'You lose sucker';
372 $this->callAPISuccess('Contribution', 'create', $params);
373 $params = $this->_params;
374 $params['cancel_date'] = 'yesterday';
375 $params['cancel_reason'] = 'You are a winner';
376 $this->callAPISuccess('Contribution', 'create', $params);
377 $this->callAPISuccessGetCount('Contribution', ['cancel_reason' => 'You are a winner'], 1);
378 }
379
380 /**
381 * We need to ensure previous tested api contract behaviour still works.
382 *
383 * @throws \CRM_Core_Exception
384 */
385 public function testGetContributionLegacyBehaviour(): void {
386 $p = [
387 'contact_id' => $this->_individualId,
388 'receive_date' => '2010-01-20',
389 'total_amount' => 100.00,
390 'contribution_type_id' => $this->_financialTypeId,
391 'non_deductible_amount' => 10.00,
392 'fee_amount' => 5.00,
393 'net_amount' => 95.00,
394 'trxn_id' => 23456,
395 'invoice_id' => 78910,
396 'source' => 'SSF',
397 'contribution_status_id' => 1,
398 ];
399 $this->_contribution = $this->callAPISuccess('Contribution', 'create', $p);
400
401 $params = [
402 'contribution_id' => $this->_contribution['id'],
403 'return' => array_keys($p),
404 ];
405 $params['return'][] = 'financial_type_id';
406 $params['return'][] = 'contribution_source';
407 $contribution = $this->callAPISuccess('Contribution', 'get', $params);
408
409 $this->assertEquals(1, $contribution['count']);
410 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
411 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], $this->_financialTypeId);
412 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_type_id'], $this->_financialTypeId);
413 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
414 $this->assertEquals($contribution['values'][$contribution['id']]['non_deductible_amount'], 10.00);
415 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 5.00);
416 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 95.00);
417 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 23456);
418 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 78910);
419 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_source'], 'SSF');
420 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Completed');
421
422 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
423 $p['trxn_id'] = '3847';
424 $p['invoice_id'] = '3847';
425
426 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
427
428 // now we have 2 - test getcount
429 $contribution = $this->callAPISuccess('contribution', 'getcount', []);
430 $this->assertEquals(2, $contribution);
431 //test id only format
432 $contribution = $this->callAPISuccess('contribution', 'get', [
433 'id' => $this->_contribution['id'],
434 'format.only_id' => 1,
435 ]);
436 $this->assertEquals($this->_contribution['id'], $contribution, print_r($contribution, TRUE));
437 //test id only format
438 $contribution = $this->callAPISuccess('contribution', 'get', [
439 'id' => $contribution2['id'],
440 'format.only_id' => 1,
441 ]);
442 $this->assertEquals($contribution2['id'], $contribution);
443 $contribution = $this->callAPISuccess('contribution', 'get', [
444 'id' => $this->_contribution['id'],
445 ]);
446 //test id as field
447 $this->assertEquals(1, $contribution['count']);
448 // $this->assertEquals($this->_contribution['id'], $contribution['id'] ) ;
449 //test get by contact id works
450 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId]);
451
452 $this->assertEquals(2, $contribution['count']);
453 $this->callAPISuccess('Contribution', 'Delete', [
454 'id' => $this->_contribution['id'],
455 ]);
456 $this->callAPISuccess('Contribution', 'Delete', [
457 'id' => $contribution2['id'],
458 ]);
459 }
460
461 /**
462 * Create an contribution_id=FALSE and financial_type_id=Donation.
463 */
464 public function testCreateEmptyContributionIDUseDonation() {
465 $params = [
466 'contribution_id' => FALSE,
467 'contact_id' => 1,
468 'total_amount' => 1,
469 'check_permissions' => FALSE,
470 'financial_type_id' => 'Donation',
471 ];
472 $this->callAPISuccess('contribution', 'create', $params);
473 }
474
475 /**
476 * Check with complete array + custom field.
477 *
478 * Note that the test is written on purpose without any
479 * variables specific to participant so it can be replicated into other entities
480 * and / or moved to the automated test suite
481 *
482 * @throws \CRM_Core_Exception
483 */
484 public function testCreateWithCustom(): void {
485 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__, __FILE__);
486
487 $params = $this->_params;
488 $params['custom_' . $ids['custom_field_id']] = "custom string";
489
490 $result = $this->callAPIAndDocument($this->entity, 'create', $params, __FUNCTION__, __FILE__);
491 $this->assertEquals($result['id'], $result['values'][$result['id']]['id']);
492 $check = $this->callAPISuccess($this->entity, 'get', [
493 'return.custom_' . $ids['custom_field_id'] => 1,
494 'id' => $result['id'],
495 ]);
496 $this->assertEquals('custom string', $check['values'][$check['id']]['custom_' . $ids['custom_field_id']]);
497 }
498
499 /**
500 * Check with complete array + custom field.
501 *
502 * Note that the test is written on purpose without any
503 * variables specific to participant so it can be replicated into other
504 * entities and / or moved to the automated test suite
505 *
506 * @throws \CRM_Core_Exception
507 */
508 public function testCreateGetFieldsWithCustom(): void {
509 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__, __FILE__);
510 $idsContact = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__, 'ContactTest.php');
511 $result = $this->callAPISuccess('Contribution', 'getfields', []);
512 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $result['values']);
513 $this->assertArrayNotHasKey('custom_' . $idsContact['custom_field_id'], $result['values']);
514 $this->customFieldDelete($ids['custom_field_id']);
515 $this->customGroupDelete($ids['custom_group_id']);
516 $this->customFieldDelete($idsContact['custom_field_id']);
517 $this->customGroupDelete($idsContact['custom_group_id']);
518 }
519
520 /**
521 * Test creating a contribution without skipLineItems.
522 *
523 * @throws \CRM_Core_Exception
524 */
525 public function testCreateContributionNoLineItems(): void {
526 // Turn off this validation as this test results in invalid
527 // financial entities.
528 $this->isValidateFinancialsOnPostAssert = FALSE;
529 $params = [
530 'contact_id' => $this->_individualId,
531 'receive_date' => '20120511',
532 'total_amount' => 100.00,
533 'financial_type_id' => $this->_financialTypeId,
534 'payment_instrument_id' => 1,
535 'non_deductible_amount' => 10.00,
536 'fee_amount' => 50.00,
537 'net_amount' => 90.00,
538 'trxn_id' => 12345,
539 'invoice_id' => 67890,
540 'source' => 'SSF',
541 'contribution_status_id' => 1,
542 'skipLineItem' => 1,
543 ];
544
545 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
546 $financialItems = $this->callAPISuccess('FinancialItem', 'get', ['return' => 'transaction_date']);
547 foreach ($financialItems['values'] as $financialItem) {
548 $this->assertEquals(date('Y-m-d H:i:s', strtotime($contribution['values'][$contribution['id']]['receive_date'])), date('Y-m-d H:i:s', strtotime($financialItem['transaction_date'])));
549 }
550 $this->callAPISuccessGetCount('LineItem', [
551 'entity_id' => $contribution['id'],
552 'entity_table' => 'civicrm_contribution',
553 'sequential' => 1,
554 ], 0);
555 }
556
557 /**
558 * Test checks that passing in line items suppresses the create mechanism.
559 *
560 * @throws \CRM_Core_Exception
561 */
562 public function testCreateContributionChainedLineItems(): void {
563 $params = [
564 'contact_id' => $this->_individualId,
565 'receive_date' => '20120511',
566 'total_amount' => 100.00,
567 'financial_type_id' => $this->_financialTypeId,
568 'payment_instrument_id' => 1,
569 'non_deductible_amount' => 10.00,
570 'fee_amount' => 50.00,
571 'net_amount' => 90.00,
572 'trxn_id' => 12345,
573 'invoice_id' => 67890,
574 'source' => 'SSF',
575 'contribution_status_id' => 'Pending',
576 'skipLineItem' => 1,
577 'api.line_item.create' => [
578 [
579 'price_field_id' => 1,
580 'qty' => 2,
581 'line_total' => '20',
582 'unit_price' => '10',
583 ],
584 [
585 'price_field_id' => 1,
586 'qty' => 1,
587 'line_total' => '80',
588 'unit_price' => '80',
589 ],
590 ],
591 ];
592
593 $description = 'Create Contribution with Nested Line Items.';
594 $subFile = 'CreateWithNestedLineItems';
595 $contribution = $this->callAPIAndDocument('Contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subFile);
596
597 $this->callAPISuccessGetCount('LineItem', [
598 'entity_id' => $contribution['id'],
599 'contribution_id' => $contribution['id'],
600 'entity_table' => 'civicrm_contribution',
601 'sequential' => 1,
602 ], 2);
603 }
604
605 /**
606 * @throws \CRM_Core_Exception
607 */
608 public function testCreateContributionOffline(): void {
609 $params = [
610 'contact_id' => $this->_individualId,
611 'receive_date' => '20120511',
612 'total_amount' => 100.00,
613 'financial_type_id' => 1,
614 'trxn_id' => 12345,
615 'invoice_id' => 67890,
616 'source' => 'SSF',
617 'contribution_status_id' => 1,
618 'sequential' => 1,
619 ];
620
621 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
622 $this->assertEquals($this->_individualId, $contribution['contact_id']);
623 $this->assertEquals(100.00, $contribution['total_amount']);
624 $this->assertEquals(1, $contribution['financial_type_id']);
625 $this->assertEquals(12345, $contribution['trxn_id']);
626 $this->assertEquals(67890, $contribution['invoice_id']);
627 $this->assertEquals('SSF', $contribution['source']);
628 $this->assertEquals(1, $contribution['contribution_status_id']);
629 $lineItems = $this->callAPISuccess('LineItem', 'get', [
630 'entity_id' => $contribution['id'],
631 'contribution_id' => $contribution['id'],
632 'entity_table' => 'civicrm_contribution',
633 'sequential' => 1,
634 'return' => ['entity_id', 'contribution_id'],
635 ]);
636 $this->assertEquals(1, $lineItems['count']);
637 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
638 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
639 $this->_checkFinancialRecords($contribution, 'offline');
640 $this->contributionGetnCheck($params, $contribution['id']);
641 }
642
643 /**
644 * Test create with valid payment instrument.
645 *
646 * @throws \CRM_Core_Exception
647 */
648 public function testCreateContributionWithPaymentInstrument(): void {
649 $params = $this->_params + ['payment_instrument' => 'EFT'];
650 $contribution = $this->callAPISuccess('contribution', 'create', $params);
651 $contribution = $this->callAPISuccess('contribution', 'get', [
652 'sequential' => 1,
653 'id' => $contribution['id'],
654 'return' => 'payment_instrument',
655 ]);
656 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
657 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
658
659 $this->callAPISuccess('Contribution', 'create', [
660 'id' => $contribution['id'],
661 'payment_instrument' => 'Credit Card',
662 ]);
663 $contribution = $this->callAPISuccess('Contribution', 'get', [
664 'sequential' => 1,
665 'id' => $contribution['id'],
666 'return' => 'payment_instrument',
667 ]);
668 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
669 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
670 }
671
672 /**
673 * @throws \CRM_Core_Exception
674 */
675 public function testGetContributionByPaymentInstrument(): void {
676 $params = $this->_params + ['payment_instrument' => 'EFT'];
677 $params2 = $this->_params + ['payment_instrument' => 'Cash'];
678 $this->callAPISuccess('contribution', 'create', $params);
679 $this->callAPISuccess('contribution', 'create', $params2);
680 $contribution = $this->callAPISuccess('Contribution', 'get', [
681 'sequential' => 1,
682 'contribution_payment_instrument' => 'Cash',
683 'return' => 'payment_instrument',
684 ]);
685 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
686 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
687 $this->assertEquals(1, $contribution['count']);
688 $contribution = $this->callAPISuccess('Contribution', 'get', ['sequential' => 1, 'payment_instrument' => 'Cash', 'return' => 'payment_instrument']);
689 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
690 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
691 $this->assertEquals(1, $contribution['count']);
692 $contribution = $this->callAPISuccess('Contribution', 'get', [
693 'sequential' => 1,
694 'payment_instrument_id' => 5,
695 'return' => 'payment_instrument',
696 ]);
697 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
698 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
699 $this->assertEquals(1, $contribution['count']);
700 $contribution = $this->callAPISuccess('Contribution', 'get', [
701 'sequential' => 1,
702 'payment_instrument' => 'EFT',
703 'return' => 'payment_instrument',
704 ]);
705 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
706 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
707 $this->assertEquals(1, $contribution['count']);
708 $contribution = $this->callAPISuccess('contribution', 'create', [
709 'id' => $contribution['id'],
710 'payment_instrument' => 'Credit Card',
711 'return' => 'payment_instrument',
712 ]);
713 $contribution = $this->callAPISuccess('Contribution', 'get', [
714 'sequential' => 1,
715 'id' => $contribution['id'],
716 'return' => 'payment_instrument',
717 ]);
718 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
719 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
720 $this->assertEquals(1, $contribution['count']);
721 }
722
723 /**
724 * CRM-16227 introduces invoice_id as a parameter.
725 *
726 * @throws \CRM_Core_Exception
727 */
728 public function testGetContributionByInvoice(): void {
729 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params, ['invoice_id' => 'curly']));
730 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params), ['invoice_id' => 'churlish']);
731 $this->callAPISuccessGetCount('Contribution', [], 2);
732 $this->callAPISuccessGetCount('Contribution', ['invoice_id' => 'curly'], 1);
733 }
734
735 /**
736 * Check the credit note retrieval is case insensitive.
737 *
738 * @throws \CRM_Core_Exception
739 */
740 public function testGetCreditNoteCaseInsensitive(): void {
741 $this->contributionCreate(['contact_id' => $this->_individualId]);
742 $this->contributionCreate(['creditnote_id' => 'cN1234', 'contact_id' => $this->_individualId, 'invoice_id' => 91011, 'trxn_id' => 456]);
743 $contribution = $this->callAPISuccess('Contribution', 'getsingle', ['creditnote_id' => 'CN1234', 'return' => 'creditnote_id']);
744 $this->assertEquals('cN1234', $contribution['creditnote_id']);
745 }
746
747 /**
748 * Test retrieval by total_amount works.
749 *
750 * @throws \CRM_Core_Exception
751 */
752 public function testGetContributionByTotalAmount(): void {
753 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params, ['total_amount' => '5']));
754 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params, ['total_amount' => '10']));
755 $this->callAPISuccessGetCount('Contribution', ['total_amount' => 10], 1);
756 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 6]], 1);
757 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 0]], 2);
758 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => -5]], 2);
759 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['<' => 0]], 0);
760 $this->callAPISuccessGetCount('Contribution', [], 2);
761 }
762
763 /**
764 * @dataProvider createLocalizedContributionDataProvider
765 *
766 * @param float|int|string $totalAmount
767 * @param string $decimalPoint
768 * @param string $thousandSeparator
769 * @param string $currency
770 * @param bool $expectedResult
771 *
772 * @throws \CRM_Core_Exception
773 */
774 public function testCreateLocalizedContribution($totalAmount, string $decimalPoint, string $thousandSeparator, string $currency, bool $expectedResult): void {
775 $this->setDefaultCurrency($currency);
776 $this->setMonetaryDecimalPoint($decimalPoint);
777 $this->setMonetaryThousandSeparator($thousandSeparator);
778
779 $_params = [
780 'contact_id' => $this->_individualId,
781 'receive_date' => '20120511',
782 'total_amount' => $totalAmount,
783 'financial_type_id' => $this->_financialTypeId,
784 'contribution_status_id' => 1,
785 ];
786
787 if ($expectedResult) {
788 $this->callAPISuccess('Contribution', 'create', $_params);
789 }
790 else {
791 $this->callAPIFailure('Contribution', 'create', $_params);
792 }
793 }
794
795 /**
796 * @return array
797 */
798 public function createLocalizedContributionDataProvider(): array {
799 return [
800 [10, '.', ',', 'USD', TRUE],
801 ['145.0E+3', '.', ',', 'USD', FALSE],
802 ['10', '.', ',', 'USD', TRUE],
803 [-10, '.', ',', 'USD', TRUE],
804 ['-10', '.', ',', 'USD', TRUE],
805 ['-10foo', '.', ',', 'USD', FALSE],
806 ['-10.0345619', '.', ',', 'USD', TRUE],
807 ['-10.010,4345619', '.', ',', 'USD', TRUE],
808 ['10.0104345619', '.', ',', 'USD', TRUE],
809 ['-0', '.', ',', 'USD', TRUE],
810 ['-.1', '.', ',', 'USD', TRUE],
811 ['.1', '.', ',', 'USD', TRUE],
812 // Test currency symbols too, default locale uses $, so if we wanted to test others we'd need to reconfigure locale
813 ['$1,234,567.89', '.', ',', 'USD', TRUE],
814 ['-$1,234,567.89', '.', ',', 'USD', TRUE],
815 ['$-1,234,567.89', '.', ',', 'USD', TRUE],
816 // This is the float format. Encapsulated in strings
817 ['1234567.89', '.', ',', 'USD', TRUE],
818 // This is the float format.
819 [1234567.89, '.', ',', 'USD', TRUE],
820 // Test EURO currency
821 ['€1,234,567.89', '.', ',', 'EUR', TRUE],
822 ['-€1,234,567.89', '.', ',', 'EUR', TRUE],
823 ['€-1,234,567.89', '.', ',', 'EUR', TRUE],
824 // This is the float format. Encapsulated in strings
825 ['1234567.89', '.', ',', 'EUR', TRUE],
826 // This is the float format.
827 [1234567.89, '.', ',', 'EUR', TRUE],
828 // Test Norwegian KR currency
829 ['kr1,234,567.89', '.', ',', 'NOK', TRUE],
830 ['kr 1,234,567.89', '.', ',', 'NOK', TRUE],
831 ['-kr1,234,567.89', '.', ',', 'NOK', TRUE],
832 ['-kr 1,234,567.89', '.', ',', 'NOK', TRUE],
833 ['kr-1,234,567.89', '.', ',', 'NOK', TRUE],
834 ['kr -1,234,567.89', '.', ',', 'NOK', TRUE],
835 // This is the float format. Encapsulated in strings
836 ['1234567.89', '.', ',', 'NOK', TRUE],
837 // This is the float format.
838 [1234567.89, '.', ',', 'NOK', TRUE],
839 // Test different localization options: , as decimal separator and dot as thousand separator
840 ['$1.234.567,89', ',', '.', 'USD', TRUE],
841 ['-$1.234.567,89', ',', '.', 'USD', TRUE],
842 ['$-1.234.567,89', ',', '.', 'USD', TRUE],
843 ['1.234.567,89', ',', '.', 'USD', TRUE],
844 // This is the float format. Encapsulated in strings
845 ['1234567.89', ',', '.', 'USD', TRUE],
846 // This is the float format.
847 [1234567.89, ',', '.', 'USD', TRUE],
848 ['$1,234,567.89', ',', '.', 'USD', FALSE],
849 ['-$1,234,567.89', ',', '.', 'USD', FALSE],
850 ['$-1,234,567.89', ',', '.', 'USD', FALSE],
851 // Now with a space as thousand separator
852 ['$1 234 567,89', ',', ' ', 'USD', TRUE],
853 ['-$1 234 567,89', ',', ' ', 'USD', TRUE],
854 ['$-1 234 567,89', ',', ' ', 'USD', TRUE],
855 ['1 234 567,89', ',', ' ', 'USD', TRUE],
856 // This is the float format. Encapsulated in strings
857 ['1234567.89', ',', ' ', 'USD', TRUE],
858 // This is the float format.
859 [1234567.89, ',', ' ', 'USD', TRUE],
860 ];
861 }
862
863 /**
864 * Create test with unique field name on source.
865 */
866 public function testCreateContributionSource() {
867
868 $params = [
869 'contact_id' => $this->_individualId,
870 'receive_date' => date('Ymd'),
871 'total_amount' => 100.00,
872 'financial_type_id' => $this->_financialTypeId,
873 'payment_instrument_id' => 1,
874 'non_deductible_amount' => 10.00,
875 'fee_amount' => 50.00,
876 'net_amount' => 90.00,
877 'trxn_id' => 12345,
878 'invoice_id' => 67890,
879 'contribution_source' => 'SSF',
880 'contribution_status_id' => 1,
881 ];
882
883 $contribution = $this->callAPISuccess('contribution', 'create', $params);
884 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
885 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
886 }
887
888 /**
889 * Create test with unique field name on source.
890 *
891 * @param string $thousandSeparator
892 * punctuation used to refer to thousands.
893 *
894 * @dataProvider getThousandSeparators
895 */
896 public function testCreateDefaultNow($thousandSeparator) {
897 $this->setCurrencySeparators($thousandSeparator);
898 $params = $this->_params;
899 unset($params['receive_date'], $params['net_amount']);
900
901 $params['total_amount'] = $this->formatMoneyInput(5000.77);
902 $params['fee_amount'] = $this->formatMoneyInput(.77);
903 $params['skipCleanMoney'] = FALSE;
904
905 $contribution = $this->callAPISuccess('contribution', 'create', $params);
906 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
907 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receive_date'])));
908 $this->assertEquals(5000.77, $contribution['total_amount'], 'failed to handle ' . $this->formatMoneyInput(5000.77));
909 $this->assertEquals(.77, $contribution['fee_amount']);
910 $this->assertEquals(5000, $contribution['net_amount']);
911 }
912
913 /**
914 * Create test with unique field name on source.
915 */
916 public function testCreateContributionNullOutThankyouDate() {
917
918 $params = $this->_params;
919 $params['thankyou_date'] = 'yesterday';
920
921 $contribution = $this->callAPISuccess('contribution', 'create', $params);
922 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
923 $this->assertEquals(date('Y-m-d', strtotime('yesterday')), date('Y-m-d', strtotime($contribution['thankyou_date'])));
924
925 $params['thankyou_date'] = 'null';
926 $contribution = $this->callAPISuccess('contribution', 'create', $params);
927 $this->assertTrue(empty($contribution['thankyou_date']));
928 }
929
930 /**
931 * Create test with unique field name on source.
932 */
933 public function testCreateContributionSourceInvalidContact() {
934
935 $params = [
936 'contact_id' => 999,
937 'receive_date' => date('Ymd'),
938 'total_amount' => 100.00,
939 'financial_type_id' => $this->_financialTypeId,
940 'payment_instrument_id' => 1,
941 'non_deductible_amount' => 10.00,
942 'fee_amount' => 50.00,
943 'net_amount' => 90.00,
944 'trxn_id' => 12345,
945 'invoice_id' => 67890,
946 'contribution_source' => 'SSF',
947 'contribution_status_id' => 1,
948 ];
949
950 $this->callAPIFailure('contribution', 'create', $params, 'contact_id is not valid : 999');
951 }
952
953 /**
954 * Test note created correctly.
955 *
956 * @throws \CRM_Core_Exception
957 */
958 public function testCreateContributionWithNote(): void {
959 $description = 'Demonstrates creating contribution with Note Entity.';
960 $subFile = 'ContributionCreateWithNote';
961 $params = [
962 'contact_id' => $this->_individualId,
963 'receive_date' => '2012-01-01',
964 'total_amount' => 100.00,
965 'financial_type_id' => $this->_financialTypeId,
966 'payment_instrument_id' => 1,
967 'non_deductible_amount' => 10.00,
968 'fee_amount' => 50.00,
969 'net_amount' => 90.00,
970 'trxn_id' => 12345,
971 'invoice_id' => 67890,
972 'source' => 'SSF',
973 'contribution_status_id' => 1,
974 'note' => 'my contribution note',
975 ];
976
977 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subFile);
978 $result = $this->callAPISuccess('note', 'get', [
979 'entity_table' => 'civicrm_contribution',
980 'entity_id' => $contribution['id'],
981 'sequential' => 1,
982 'return' => 'note',
983 ]);
984 $this->assertEquals('my contribution note', $result['values'][0]['note']);
985 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
986 }
987
988 /**
989 * @throws \CRM_Core_Exception
990 */
991 public function testCreateContributionWithNoteUniqueNameAliases(): void {
992 $params = [
993 'contact_id' => $this->_individualId,
994 'receive_date' => '2012-01-01',
995 'total_amount' => 100.00,
996 'financial_type_id' => $this->_financialTypeId,
997 'payment_instrument_id' => 1,
998 'non_deductible_amount' => 10.00,
999 'fee_amount' => 50.00,
1000 'net_amount' => 90.00,
1001 'trxn_id' => 12345,
1002 'invoice_id' => 67890,
1003 'source' => 'SSF',
1004 'contribution_status_id' => 1,
1005 'contribution_note' => 'my contribution note',
1006 ];
1007
1008 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1009 $result = $this->callAPISuccess('note', 'get', [
1010 'entity_table' => 'civicrm_contribution',
1011 'entity_id' => $contribution['id'],
1012 'sequential' => 1,
1013 'return' => 'note',
1014 ]);
1015 $this->assertEquals('my contribution note', $result['values'][0]['note']);
1016 }
1017
1018 /**
1019 * This is the test for creating soft credits.
1020 */
1021 public function testCreateContributionWithSoftCredit() {
1022 $description = "Demonstrates creating contribution with SoftCredit.";
1023 $subfile = "ContributionCreateWithSoftCredit";
1024 $contact2 = $this->callAPISuccess('Contact', 'create', [
1025 'display_name' => 'superman',
1026 'contact_type' => 'Individual',
1027 ]);
1028 $softParams = [
1029 'contact_id' => $contact2['id'],
1030 'amount' => 50,
1031 'soft_credit_type_id' => 3,
1032 ];
1033
1034 $params = $this->_params + ['soft_credit' => [1 => $softParams]];
1035 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subfile);
1036 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1037
1038 $this->assertEquals($softParams['contact_id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1039 $this->assertEquals($softParams['amount'], $result['values'][0]['soft_credit'][1]['amount']);
1040 $this->assertEquals($softParams['soft_credit_type_id'], $result['values'][0]['soft_credit'][1]['soft_credit_type']);
1041
1042 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1043 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1044 }
1045
1046 public function testCreateContributionWithSoftCreditDefaults() {
1047 $description = "Demonstrates creating contribution with Soft Credit defaults for amount and type.";
1048 $subfile = "ContributionCreateWithSoftCreditDefaults";
1049 $contact2 = $this->callAPISuccess('Contact', 'create', [
1050 'display_name' => 'superman',
1051 'contact_type' => 'Individual',
1052 ]);
1053 $params = $this->_params + [
1054 'soft_credit_to' => $contact2['id'],
1055 ];
1056 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subfile);
1057 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1058
1059 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1060 // Default soft credit amount = contribution.total_amount
1061 $this->assertEquals($this->_params['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
1062 $this->assertEquals(CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"), $result['values'][0]['soft_credit'][1]['soft_credit_type']);
1063
1064 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1065 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1066 }
1067
1068 /**
1069 * Test creating contribution with Soft Credit by passing in honor_contact_id.
1070 */
1071 public function testCreateContributionWithHonoreeContact() {
1072 $description = "Demonstrates creating contribution with Soft Credit by passing in honor_contact_id.";
1073 $subfile = "ContributionCreateWithHonoreeContact";
1074 $contact2 = $this->callAPISuccess('Contact', 'create', [
1075 'display_name' => 'superman',
1076 'contact_type' => 'Individual',
1077 ]);
1078 $params = $this->_params + [
1079 'honor_contact_id' => $contact2['id'],
1080 ];
1081 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__, __FILE__, $description, $subfile);
1082 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1083
1084 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1085 // Default soft credit amount = contribution.total_amount
1086 // Legacy mode in create api (honor_contact_id param) uses the standard "In Honor of" soft credit type
1087 $this->assertEquals($this->_params['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
1088 $softCreditValueTypeID = $result['values'][0]['soft_credit'][1]['soft_credit_type'];
1089 $this->assertEquals('in_honor_of', CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $softCreditValueTypeID));
1090
1091 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1092 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1093 }
1094
1095 /**
1096 * Test using example code.
1097 */
1098 public function testContributionCreateExample() {
1099 //make sure at least on page exists since there is a truncate in tear down
1100 $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1101 require_once 'api/v3/examples/Contribution/Create.ex.php';
1102 $result = contribution_create_example();
1103 $id = $result['id'];
1104 $expectedResult = contribution_create_expectedresult();
1105 $this->checkArrayEquals($expectedResult, $result);
1106 $this->contributionDelete($id);
1107 }
1108
1109 /**
1110 * Function tests that additional financial records are created when fee amount is recorded.
1111 */
1112 public function testCreateContributionWithFee() {
1113 $params = [
1114 'contact_id' => $this->_individualId,
1115 'receive_date' => '20120511',
1116 'total_amount' => 100.00,
1117 'fee_amount' => 50,
1118 'financial_type_id' => 1,
1119 'trxn_id' => 12345,
1120 'invoice_id' => 67890,
1121 'source' => 'SSF',
1122 'contribution_status_id' => 1,
1123 ];
1124
1125 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1126 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
1127 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1128 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 50.00);
1129 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 50.00);
1130 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1131 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1132 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1133 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1134 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
1135
1136 $lineItems = $this->callAPISuccess('line_item', 'get', [
1137
1138 'entity_id' => $contribution['id'],
1139 'entity_table' => 'civicrm_contribution',
1140 'sequential' => 1,
1141 'return' => ['entity_id', 'contribution_id'],
1142 ]);
1143 $this->assertEquals(1, $lineItems['count']);
1144 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
1145 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
1146 $this->callAPISuccessGetCount('line_item', [
1147
1148 'entity_id' => $contribution['id'],
1149 'contribution_id' => $contribution['id'],
1150 'entity_table' => 'civicrm_contribution',
1151 'sequential' => 1,
1152 ], 1);
1153 $this->_checkFinancialRecords($contribution, 'feeAmount');
1154 }
1155
1156 /**
1157 * Function tests that additional financial records are created when online
1158 * contribution is created.
1159 *
1160 * @throws \CRM_Core_Exception
1161 * @throws \CiviCRM_API3_Exception
1162 */
1163 public function testCreateContributionOnline(): void {
1164 CRM_Financial_BAO_PaymentProcessor::create($this->_processorParams);
1165 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1166 $this->assertAPISuccess($contributionPage);
1167 $params = [
1168 'contact_id' => $this->_individualId,
1169 'receive_date' => '20120511',
1170 'total_amount' => 100.00,
1171 'financial_type_id' => 1,
1172 'contribution_page_id' => $contributionPage['id'],
1173 'payment_processor' => $this->paymentProcessorID,
1174 'trxn_id' => 12345,
1175 'invoice_id' => 67890,
1176 'source' => 'SSF',
1177 'contribution_status_id' => 1,
1178
1179 ];
1180
1181 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
1182 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
1183 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1184 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1185 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1186 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1187 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1188 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
1189 $contribution['payment_instrument_id'] = $this->callAPISuccessGetValue('PaymentProcessor', [
1190 'id' => $this->paymentProcessorID,
1191 'return' => 'payment_instrument_id',
1192 ]);
1193 $this->_checkFinancialRecords($contribution, 'online');
1194 }
1195
1196 /**
1197 * Check handling of financial type.
1198 *
1199 * In the interests of removing financial type / contribution type checks from
1200 * legacy format function lets test that the api is doing this for us
1201 */
1202 public function testCreateInvalidFinancialType(): void {
1203 $params = $this->_params;
1204 $params['financial_type_id'] = 99999;
1205 $this->callAPIFailure($this->entity, 'create', $params);
1206 }
1207
1208 /**
1209 * Check handling of financial type.
1210 *
1211 * In the interests of removing financial type / contribution type checks from
1212 * legacy format function lets test that the api is doing this for us
1213 *
1214 * @throws \CRM_Core_Exception
1215 */
1216 public function testValidNamedFinancialType() {
1217 $params = $this->_params;
1218 $params['financial_type_id'] = 'Donation';
1219 $this->callAPISuccess($this->entity, 'create', $params);
1220 }
1221
1222 /**
1223 * Tests that additional financial records are created.
1224 *
1225 * Checks when online contribution with pay later option is created
1226 *
1227 * @throws \CRM_Core_Exception
1228 */
1229 public function testCreateContributionPayLaterOnline(): void {
1230 $this->_pageParams['is_pay_later'] = 1;
1231 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1232 $this->assertAPISuccess($contributionPage);
1233 $params = [
1234 'contact_id' => $this->_individualId,
1235 'receive_date' => '20120511',
1236 'total_amount' => 100.00,
1237 'financial_type_id' => 1,
1238 'contribution_page_id' => $contributionPage['id'],
1239 'trxn_id' => 12345,
1240 'is_pay_later' => 1,
1241 'invoice_id' => 67890,
1242 'source' => 'SSF',
1243 'contribution_status_id' => 'Pending',
1244
1245 ];
1246
1247 $contribution = $this->callAPIAndDocument('Contribution', 'create', $params, __FUNCTION__, __FILE__);
1248 $contribution = $contribution['values'][$contribution['id']];
1249 $this->assertEquals($contribution['contact_id'], $this->_individualId);
1250 $this->assertEquals($contribution['total_amount'], 100.00);
1251 $this->assertEquals($contribution['financial_type_id'], 1);
1252 $this->assertEquals($contribution['trxn_id'], 12345);
1253 $this->assertEquals($contribution['invoice_id'], 67890);
1254 $this->assertEquals($contribution['source'], 'SSF');
1255 $this->assertEquals($contribution['contribution_status_id'], 2);
1256 $this->_checkFinancialRecords($contribution, 'payLater');
1257 }
1258
1259 /**
1260 * Function tests that additional financial records are created for online contribution with pending option.
1261 */
1262 public function testCreateContributionPendingOnline() {
1263 CRM_Financial_BAO_PaymentProcessor::create($this->_processorParams);
1264 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams);
1265 $this->assertAPISuccess($contributionPage);
1266 $params = [
1267 'contact_id' => $this->_individualId,
1268 'receive_date' => '20120511',
1269 'total_amount' => 100.00,
1270 'financial_type_id' => 1,
1271 'contribution_page_id' => $contributionPage['id'],
1272 'trxn_id' => 12345,
1273 'invoice_id' => 67890,
1274 'source' => 'SSF',
1275 'contribution_status_id' => 2,
1276 ];
1277
1278 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1279 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId);
1280 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1281 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1282 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1283 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1284 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1285 $this->assertEquals(2, $contribution['values'][$contribution['id']]['contribution_status_id']);
1286 $this->_checkFinancialRecords($contribution, 'pending');
1287 }
1288
1289 /**
1290 * Test that BAO defaults work.
1291 *
1292 * @throws \CRM_Core_Exception
1293 */
1294 public function testCreateBAODefaults() {
1295 unset($this->_params['contribution_source_id'], $this->_params['payment_instrument_id']);
1296 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params);
1297 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
1298 'id' => $contribution['id'],
1299 'api.contribution.delete' => 1,
1300 'return' => ['contribution_status_id', 'payment_instrument'],
1301 ]);
1302 $this->assertEquals(1, $contribution['contribution_status_id']);
1303 $this->assertEquals('Check', $contribution['payment_instrument']);
1304 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1305 }
1306
1307 /**
1308 * Test that getsingle can be chained with delete.
1309 *
1310 * @throws CRM_Core_Exception
1311 */
1312 public function testDeleteChainedGetSingle() {
1313 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params);
1314 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
1315 'id' => $contribution['id'],
1316 'api.contribution.delete' => 1,
1317 'return' => 'id',
1318 ]);
1319 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1320 }
1321
1322 /**
1323 * Function tests that line items, financial records are updated when contribution amount is changed.
1324 *
1325 * @throws \CRM_Core_Exception
1326 */
1327 public function testCreateUpdateContributionChangeTotal() {
1328 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
1329 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1330
1331 'entity_id' => $contribution['id'],
1332 'entity_table' => 'civicrm_contribution',
1333 'sequential' => 1,
1334 'return' => 'line_total',
1335 ]);
1336 $this->assertEquals('100.00', $lineItems);
1337 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1338 // Financial trxn SUM = 100 + 5 (fee)
1339 $this->assertEquals('105.00', $trxnAmount);
1340 $newParams = [
1341
1342 'id' => $contribution['id'],
1343 'total_amount' => '125',
1344 ];
1345 $contribution = $this->callAPISuccess('Contribution', 'create', $newParams);
1346
1347 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1348
1349 'entity_id' => $contribution['id'],
1350 'entity_table' => 'civicrm_contribution',
1351 'sequential' => 1,
1352 'return' => 'line_total',
1353 ]);
1354
1355 $this->assertEquals('125.00', $lineItems);
1356 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1357
1358 // Financial trxn SUM = 125 + 5 (fee).
1359 $this->assertEquals('130.00', $trxnAmount);
1360 $this->assertEquals('125.00', $this->_getFinancialItemAmount($contribution['id']));
1361 }
1362
1363 /**
1364 * Function tests that line items, financial records are updated when pay later contribution is received.
1365 */
1366 public function testCreateUpdateContributionPayLater() {
1367 $contribParams = [
1368 'contact_id' => $this->_individualId,
1369 'receive_date' => '2012-01-01',
1370 'total_amount' => 100.00,
1371 'financial_type_id' => $this->_financialTypeId,
1372 'payment_instrument_id' => 1,
1373 'contribution_status_id' => 2,
1374 'is_pay_later' => 1,
1375
1376 ];
1377 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1378
1379 $newParams = array_merge($contribParams, [
1380 'id' => $contribution['id'],
1381 'contribution_status_id' => 1,
1382 ]);
1383 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1384 $contribution = $contribution['values'][$contribution['id']];
1385 $this->assertEquals($contribution['contribution_status_id'], '1');
1386 $this->_checkFinancialItem($contribution['id'], 'paylater');
1387 $this->_checkFinancialTrxn($contribution, 'payLater');
1388 }
1389
1390 /**
1391 * Function tests that financial records are updated when Payment Instrument is changed.
1392 */
1393 public function testCreateUpdateContributionPaymentInstrument() {
1394 $instrumentId = $this->_addPaymentInstrument();
1395 $contribParams = [
1396 'contact_id' => $this->_individualId,
1397 'total_amount' => 100.00,
1398 'financial_type_id' => $this->_financialTypeId,
1399 'payment_instrument_id' => 4,
1400 'contribution_status_id' => 1,
1401
1402 ];
1403 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1404
1405 $newParams = array_merge($contribParams, [
1406 'id' => $contribution['id'],
1407 'payment_instrument_id' => $instrumentId,
1408 ]);
1409 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1410 $this->assertAPISuccess($contribution);
1411 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId);
1412
1413 // cleanup - delete created payment instrument
1414 $this->_deletedAddedPaymentInstrument();
1415 }
1416
1417 /**
1418 * Function tests that financial records are updated when Payment Instrument is changed when amount is negative.
1419 */
1420 public function testCreateUpdateNegativeContributionPaymentInstrument() {
1421 $instrumentId = $this->_addPaymentInstrument();
1422 $contribParams = [
1423 'contact_id' => $this->_individualId,
1424 'total_amount' => -100.00,
1425 'financial_type_id' => $this->_financialTypeId,
1426 'payment_instrument_id' => 4,
1427 'contribution_status_id' => 1,
1428
1429 ];
1430 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1431
1432 $newParams = array_merge($contribParams, [
1433 'id' => $contribution['id'],
1434 'payment_instrument_id' => $instrumentId,
1435 ]);
1436 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1437 $this->assertAPISuccess($contribution);
1438 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId, -100);
1439
1440 // cleanup - delete created payment instrument
1441 $this->_deletedAddedPaymentInstrument();
1442 }
1443
1444 /**
1445 * Function tests that financial records are added when Contribution is Refunded.
1446 *
1447 * @throws \CRM_Core_Exception
1448 */
1449 public function testCreateUpdateContributionRefund() {
1450 $contributionParams = [
1451 'contact_id' => $this->_individualId,
1452 'receive_date' => '2012-01-01',
1453 'total_amount' => 100.00,
1454 'financial_type_id' => $this->_financialTypeId,
1455 'payment_instrument_id' => 4,
1456 'contribution_status_id' => 1,
1457 'trxn_id' => 'original_payment',
1458 ];
1459 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
1460 $newParams = array_merge($contributionParams, [
1461 'id' => $contribution['id'],
1462 'contribution_status_id' => 'Refunded',
1463 'cancel_date' => '2015-01-01 09:00',
1464 'refund_trxn_id' => 'the refund',
1465 ]);
1466
1467 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1468 $this->_checkFinancialTrxn($contribution, 'refund');
1469 $this->_checkFinancialItem($contribution['id'], 'refund');
1470 $this->assertEquals('original_payment', $this->callAPISuccessGetValue('Contribution', [
1471 'id' => $contribution['id'],
1472 'return' => 'trxn_id',
1473 ]));
1474 }
1475
1476 /**
1477 * Refund a contribution for a financial type with a contra account.
1478 *
1479 * CRM-17951 the contra account is a financial account with a relationship to a
1480 * financial type. It is not always configured but should be reflected
1481 * in the financial_trxn & financial_item table if it is.
1482 *
1483 * @throws \CRM_Core_Exception
1484 */
1485 public function testCreateUpdateChargebackContributionDefaultAccount() {
1486 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params);
1487 $this->callAPISuccess('Contribution', 'create', [
1488 'id' => $contribution['id'],
1489 'contribution_status_id' => 'Chargeback',
1490 ]);
1491 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1492
1493 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1494 'contribution_id' => $contribution['id'],
1495 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1496 ]);
1497 $this->assertEquals(1, $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1498 $this->callAPISuccessGetSingle('FinancialTrxn', [
1499 'total_amount' => -100,
1500 'status_id' => 'Chargeback',
1501 'to_financial_account_id' => 6,
1502 ]);
1503 }
1504
1505 /**
1506 * Refund a contribution for a financial type with a contra account.
1507 *
1508 * CRM-17951 the contra account is a financial account with a relationship to a
1509 * financial type. It is not always configured but should be reflected
1510 * in the financial_trxn & financial_item table if it is.
1511 *
1512 * @throws \CRM_Core_Exception
1513 */
1514 public function testCreateUpdateChargebackContributionCustomAccount() {
1515 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1516 'name' => 'Chargeback Account',
1517 'is_active' => TRUE,
1518 ]);
1519
1520 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1521 'entity_id' => $this->_financialTypeId,
1522 'entity_table' => 'civicrm_financial_type',
1523 'account_relationship' => 'Chargeback Account is',
1524 'financial_account_id' => 'Chargeback Account',
1525 ]);
1526
1527 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params);
1528 $this->callAPISuccess('Contribution', 'create', [
1529 'id' => $contribution['id'],
1530 'contribution_status_id' => 'Chargeback',
1531 ]);
1532 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1533
1534 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1535 'contribution_id' => $contribution['id'],
1536 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1537 ]);
1538 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1539
1540 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1541 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1542 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1543 }
1544
1545 /**
1546 * Refund a contribution for a financial type with a contra account.
1547 *
1548 * CRM-17951 the contra account is a financial account with a relationship to a
1549 * financial type. It is not always configured but should be reflected
1550 * in the financial_trxn & financial_item table if it is.
1551 */
1552 public function testCreateUpdateRefundContributionConfiguredContraAccount() {
1553 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1554 'name' => 'Refund Account',
1555 'is_active' => TRUE,
1556 ]);
1557
1558 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1559 'entity_id' => $this->_financialTypeId,
1560 'entity_table' => 'civicrm_financial_type',
1561 'account_relationship' => 'Credit/Contra Revenue Account is',
1562 'financial_account_id' => 'Refund Account',
1563 ]);
1564
1565 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params);
1566 $this->callAPISuccess('Contribution', 'create', [
1567 'id' => $contribution['id'],
1568 'contribution_status_id' => 'Refunded',
1569 ]);
1570
1571 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1572 'contribution_id' => $contribution['id'],
1573 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1574 ]);
1575 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1576
1577 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1578 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1579 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1580 }
1581
1582 /**
1583 * Function tests that trxn_id is set when passed in.
1584 *
1585 * Here we ensure that the civicrm_financial_trxn.trxn_id & the civicrm_contribution.trxn_id are set
1586 * when trxn_id is passed in.
1587 */
1588 public function testCreateUpdateContributionRefundTrxnIDPassedIn() {
1589 $contributionParams = [
1590 'contact_id' => $this->_individualId,
1591 'receive_date' => '2012-01-01',
1592 'total_amount' => 100.00,
1593 'financial_type_id' => $this->_financialTypeId,
1594 'payment_instrument_id' => 4,
1595 'contribution_status_id' => 1,
1596 'trxn_id' => 'original_payment',
1597 ];
1598 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1599 $newParams = array_merge($contributionParams, [
1600 'id' => $contribution['id'],
1601 'contribution_status_id' => 'Refunded',
1602 'cancel_date' => '2015-01-01 09:00',
1603 'trxn_id' => 'the refund',
1604 ]);
1605
1606 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1607 $this->_checkFinancialTrxn($contribution, 'refund');
1608 $this->_checkFinancialItem($contribution['id'], 'refund');
1609 $this->assertEquals('the refund', $this->callAPISuccessGetValue('Contribution', [
1610 'id' => $contribution['id'],
1611 'return' => 'trxn_id',
1612 ]));
1613 }
1614
1615 /**
1616 * Function tests that trxn_id is set when passed in.
1617 *
1618 * Here we ensure that the civicrm_contribution.trxn_id is set
1619 * when trxn_id is passed in but if refund_trxn_id is different then that
1620 * is kept for the refund transaction.
1621 */
1622 public function testCreateUpdateContributionRefundRefundAndTrxnIDPassedIn() {
1623 $contributionParams = [
1624 'contact_id' => $this->_individualId,
1625 'receive_date' => '2012-01-01',
1626 'total_amount' => 100.00,
1627 'financial_type_id' => $this->_financialTypeId,
1628 'payment_instrument_id' => 4,
1629 'contribution_status_id' => 1,
1630 'trxn_id' => 'original_payment',
1631 ];
1632 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1633 $newParams = array_merge($contributionParams, [
1634 'id' => $contribution['id'],
1635 'contribution_status_id' => 'Refunded',
1636 'cancel_date' => '2015-01-01 09:00',
1637 'trxn_id' => 'cont id',
1638 'refund_trxn_id' => 'the refund',
1639 ]);
1640
1641 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1642 $this->_checkFinancialTrxn($contribution, 'refund');
1643 $this->_checkFinancialItem($contribution['id'], 'refund');
1644 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1645 'id' => $contribution['id'],
1646 'return' => 'trxn_id',
1647 ]));
1648 }
1649
1650 /**
1651 * Function tests that refund_trxn_id is set when passed in empty.
1652 *
1653 * Here we ensure that the civicrm_contribution.trxn_id is set
1654 * when trxn_id is passed in but if refund_trxn_id isset but empty then that
1655 * is kept for the refund transaction.
1656 */
1657 public function testCreateUpdateContributionRefundRefundNullTrxnIDPassedIn() {
1658 $contributionParams = [
1659 'contact_id' => $this->_individualId,
1660 'receive_date' => '2012-01-01',
1661 'total_amount' => 100.00,
1662 'financial_type_id' => $this->_financialTypeId,
1663 'payment_instrument_id' => 4,
1664 'contribution_status_id' => 1,
1665 'trxn_id' => 'original_payment',
1666 ];
1667 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1668 $newParams = array_merge($contributionParams, [
1669 'id' => $contribution['id'],
1670 'contribution_status_id' => 'Refunded',
1671 'cancel_date' => '2015-01-01 09:00',
1672 'trxn_id' => 'cont id',
1673 'refund_trxn_id' => '',
1674 ]);
1675
1676 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1677 $this->_checkFinancialTrxn($contribution, 'refund', NULL, ['trxn_id' => NULL]);
1678 $this->_checkFinancialItem($contribution['id'], 'refund');
1679 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1680 'id' => $contribution['id'],
1681 'return' => 'trxn_id',
1682 ]));
1683 }
1684
1685 /**
1686 * Function tests invalid contribution status change.
1687 */
1688 public function testCreateUpdateContributionInValidStatusChange() {
1689 $contribParams = [
1690 'contact_id' => 1,
1691 'receive_date' => '2012-01-01',
1692 'total_amount' => 100.00,
1693 'financial_type_id' => 1,
1694 'payment_instrument_id' => 1,
1695 'contribution_status_id' => 1,
1696 ];
1697 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1698 $newParams = array_merge($contribParams, [
1699 'id' => $contribution['id'],
1700 'contribution_status_id' => 2,
1701 ]);
1702 $this->callAPIFailure('contribution', 'create', $newParams, ts('Cannot change contribution status from Completed to Pending.'));
1703
1704 }
1705
1706 /**
1707 * Function tests that financial records are added when Pending Contribution is Canceled.
1708 *
1709 * @throws \CRM_Core_Exception
1710 */
1711 public function testCreateUpdateContributionCancelPending() {
1712 $contribParams = [
1713 'contact_id' => $this->_individualId,
1714 'receive_date' => '2012-01-01',
1715 'total_amount' => 100.00,
1716 'financial_type_id' => $this->_financialTypeId,
1717 'payment_instrument_id' => 1,
1718 'contribution_status_id' => 2,
1719 'is_pay_later' => 1,
1720
1721 ];
1722 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1723 $newParams = array_merge($contribParams, [
1724 'id' => $contribution['id'],
1725 'contribution_status_id' => 3,
1726 'cancel_date' => '2012-02-02 09:00',
1727 ]);
1728 //Check if trxn_date is same as cancel_date.
1729 $checkTrxnDate = [
1730 'trxn_date' => '2012-02-02 09:00:00',
1731 ];
1732 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1733 $this->_checkFinancialTrxn($contribution, 'cancelPending', NULL, $checkTrxnDate);
1734 $this->_checkFinancialItem($contribution['id'], 'cancelPending');
1735 }
1736
1737 /**
1738 * Function tests that financial records are added when Financial Type is Changed.
1739 *
1740 * @throws \CRM_Core_Exception
1741 */
1742 public function testCreateUpdateContributionChangeFinancialType() {
1743 $contribParams = [
1744 'contact_id' => $this->_individualId,
1745 'receive_date' => '2012-01-01',
1746 'total_amount' => 100.00,
1747 'financial_type_id' => 1,
1748 'payment_instrument_id' => 1,
1749 'contribution_status_id' => 1,
1750
1751 ];
1752 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1753 $newParams = array_merge($contribParams, [
1754 'id' => $contribution['id'],
1755 'financial_type_id' => 3,
1756 ]);
1757 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1758 $this->_checkFinancialTrxn($contribution, 'changeFinancial');
1759 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1760 }
1761
1762 /**
1763 * Function tets that financial records are correctly added when financial type is changed
1764 *
1765 * @throws \CRM_Core_Exception
1766 */
1767 public function testCreateUpdateContributionWithFeeAmountChangeFinancialType() {
1768 $contribParams = [
1769 'contact_id' => $this->_individualId,
1770 'receive_date' => '2012-01-01',
1771 'total_amount' => 100.00,
1772 'fee_amount' => 0.57,
1773 'financial_type_id' => 1,
1774 'payment_instrument_id' => 1,
1775 'contribution_status_id' => 1,
1776
1777 ];
1778 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1779 $newParams = array_merge($contribParams, [
1780 'id' => $contribution['id'],
1781 'financial_type_id' => 3,
1782 ]);
1783 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1784 $this->_checkFinancialTrxn($contribution, 'changeFinancial', NULL, ['fee_amount' => '-0.57', 'net_amount' => '-99.43']);
1785 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1786 }
1787
1788 /**
1789 * Test that update does not change status id CRM-15105.
1790 */
1791 public function testCreateUpdateWithoutChangingPendingStatus() {
1792 $contribution = $this->callAPISuccess('contribution', 'create', array_merge($this->_params, ['contribution_status_id' => 2]));
1793 $this->callAPISuccess('contribution', 'create', ['id' => $contribution['id'], 'source' => 'new source']);
1794 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1795 'id' => $contribution['id'],
1796 'api.contribution.delete' => 1,
1797 ]);
1798 $this->assertEquals(2, $contribution['contribution_status_id']);
1799 }
1800
1801 /**
1802 * Test Updating a Contribution.
1803 *
1804 * CHANGE: we require the API to do an incremental update
1805 */
1806 public function testCreateUpdateContribution() {
1807 $contributionID = $this->contributionCreate([
1808 'contact_id' => $this->_individualId,
1809 'trxn_id' => 212355,
1810 'financial_type_id' => $this->_financialTypeId,
1811 'invoice_id' => 'old_invoice',
1812 ]);
1813 $old_params = [
1814 'contribution_id' => $contributionID,
1815 ];
1816 $original = $this->callAPISuccess('contribution', 'get', $old_params);
1817 $this->assertEquals($original['id'], $contributionID);
1818 //set up list of old params, verify
1819
1820 //This should not be required on update:
1821 $old_contact_id = $original['values'][$contributionID]['contact_id'];
1822 $old_payment_instrument = $original['values'][$contributionID]['instrument_id'];
1823 $old_fee_amount = $original['values'][$contributionID]['fee_amount'];
1824 $old_source = $original['values'][$contributionID]['contribution_source'];
1825
1826 $old_trxn_id = $original['values'][$contributionID]['trxn_id'];
1827 $old_invoice_id = $original['values'][$contributionID]['invoice_id'];
1828
1829 //check against values in CiviUnitTestCase::createContribution()
1830 $this->assertEquals($old_contact_id, $this->_individualId);
1831 $this->assertEquals($old_fee_amount, 5.00);
1832 $this->assertEquals($old_source, 'SSF');
1833 $this->assertEquals($old_trxn_id, 212355);
1834 $this->assertEquals($old_invoice_id, 'old_invoice');
1835 $params = [
1836 'id' => $contributionID,
1837 'contact_id' => $this->_individualId,
1838 'total_amount' => 105.00,
1839 'fee_amount' => 7.00,
1840 'financial_type_id' => $this->_financialTypeId,
1841 'non_deductible_amount' => 22.00,
1842 'contribution_status_id' => 1,
1843 'note' => 'Donating for Noble Cause',
1844 ];
1845
1846 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1847
1848 $new_params = [
1849 'contribution_id' => $contribution['id'],
1850 ];
1851 $contribution = $this->callAPISuccessGetSingle('contribution', $new_params);
1852
1853 $this->assertEquals($contribution['contact_id'], $this->_individualId);
1854 $this->assertEquals($contribution['total_amount'], 105.00);
1855 $this->assertEquals($contribution['financial_type_id'], $this->_financialTypeId);
1856 $this->assertEquals($contribution['financial_type'], 'Donation');
1857 $this->assertEquals($contribution['instrument_id'], $old_payment_instrument);
1858 $this->assertEquals($contribution['non_deductible_amount'], 22.00);
1859 $this->assertEquals($contribution['fee_amount'], 7.00);
1860 $this->assertEquals($contribution['trxn_id'], $old_trxn_id);
1861 $this->assertEquals($contribution['invoice_id'], $old_invoice_id);
1862 $this->assertEquals($contribution['contribution_source'], $old_source);
1863 $this->assertEquals($contribution['contribution_status'], 'Completed');
1864
1865 $this->assertEquals($contribution['net_amount'], $contribution['total_amount'] - $contribution['fee_amount']);
1866
1867 $params = [
1868 'contribution_id' => $contributionID,
1869 ];
1870 $result = $this->callAPISuccess('contribution', 'delete', $params);
1871 $this->assertAPISuccess($result);
1872 }
1873
1874 /**
1875 * Check that net_amount is updated when a contribution is updated.
1876 *
1877 * Update fee amount AND total amount, just fee amount, just total amount
1878 * and neither to check that net_amount is keep updated.
1879 */
1880 public function testUpdateContributionNetAmountVariants() {
1881 $contributionID = $this->contributionCreate(['contact_id' => $this->individualCreate()]);
1882
1883 $this->callAPISuccess('Contribution', 'create', [
1884 'id' => $contributionID,
1885 'total_amount' => 90,
1886 'fee_amount' => 6,
1887 ]);
1888 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1889 'id' => $contributionID,
1890 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1891 ]);
1892 $this->assertEquals(6, $contribution['fee_amount']);
1893 $this->assertEquals(90, $contribution['total_amount']);
1894 $this->assertEquals(84, $contribution['net_amount']);
1895
1896 $this->callAPISuccess('Contribution', 'create', [
1897 'id' => $contributionID,
1898 'fee_amount' => 3,
1899 ]);
1900 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1901 'id' => $contributionID,
1902 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1903 ]);
1904 $this->assertEquals(3, $contribution['fee_amount']);
1905 $this->assertEquals(90, $contribution['total_amount']);
1906 $this->assertEquals(87, $contribution['net_amount']);
1907
1908 $this->callAPISuccess('Contribution', 'create', [
1909 'id' => $contributionID,
1910 'total_amount' => 200,
1911 ]);
1912 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1913 'id' => $contributionID,
1914 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1915 ]);
1916 $this->assertEquals(3, $contribution['fee_amount']);
1917 $this->assertEquals(200, $contribution['total_amount']);
1918 $this->assertEquals(197, $contribution['net_amount']);
1919
1920 $this->callAPISuccess('Contribution', 'create', [
1921 'id' => $contributionID,
1922 'payment_instrument' => 'Cash',
1923 ]);
1924 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1925 'id' => $contributionID,
1926 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1927 ]);
1928 $this->assertEquals(3, $contribution['fee_amount']);
1929 $this->assertEquals(200, $contribution['total_amount']);
1930 $this->assertEquals(197, $contribution['net_amount']);
1931 }
1932
1933 /**
1934 * Attempt (but fail) to delete a contribution without parameters.
1935 */
1936 public function testDeleteEmptyParamsContribution() {
1937 $params = [];
1938 $this->callAPIFailure('contribution', 'delete', $params);
1939 }
1940
1941 public function testDeleteWrongParamContribution() {
1942 $params = [
1943 'contribution_source' => 'SSF',
1944 ];
1945 $this->callAPIFailure('contribution', 'delete', $params);
1946 }
1947
1948 public function testDeleteContribution() {
1949 $contributionID = $this->contributionCreate([
1950 'contact_id' => $this->_individualId,
1951 'financial_type_id' => $this->_financialTypeId,
1952 ]);
1953 $params = [
1954 'id' => $contributionID,
1955 ];
1956 $this->callAPIAndDocument('contribution', 'delete', $params, __FUNCTION__, __FILE__);
1957 }
1958
1959 /**
1960 * Test civicrm_contribution_search with empty params.
1961 *
1962 * All available contributions expected.
1963 */
1964 public function testSearchEmptyParams() {
1965 $params = [];
1966
1967 $p = [
1968 'contact_id' => $this->_individualId,
1969 'receive_date' => date('Ymd'),
1970 'total_amount' => 100.00,
1971 'financial_type_id' => $this->_financialTypeId,
1972 'non_deductible_amount' => 10.00,
1973 'fee_amount' => 5.00,
1974 'net_amount' => 95.00,
1975 'trxn_id' => 23456,
1976 'invoice_id' => 78910,
1977 'source' => 'SSF',
1978 'contribution_status_id' => 1,
1979 ];
1980 $contribution = $this->callAPISuccess('contribution', 'create', $p);
1981
1982 $result = $this->callAPISuccess('contribution', 'get', $params);
1983 // We're taking the first element.
1984 $res = $result['values'][$contribution['id']];
1985
1986 $this->assertEquals($p['contact_id'], $res['contact_id']);
1987 $this->assertEquals($p['total_amount'], $res['total_amount']);
1988 $this->assertEquals($p['financial_type_id'], $res['financial_type_id']);
1989 $this->assertEquals($p['net_amount'], $res['net_amount']);
1990 $this->assertEquals($p['non_deductible_amount'], $res['non_deductible_amount']);
1991 $this->assertEquals($p['fee_amount'], $res['fee_amount']);
1992 $this->assertEquals($p['trxn_id'], $res['trxn_id']);
1993 $this->assertEquals($p['invoice_id'], $res['invoice_id']);
1994 $this->assertEquals($p['source'], $res['contribution_source']);
1995 // contribution_status_id = 1 => Completed
1996 $this->assertEquals('Completed', $res['contribution_status']);
1997
1998 $this->contributionDelete($contribution['id']);
1999 }
2000
2001 /**
2002 * Test civicrm_contribution_search. Success expected.
2003 */
2004 public function testSearch() {
2005 $p1 = [
2006 'contact_id' => $this->_individualId,
2007 'receive_date' => date('Ymd'),
2008 'total_amount' => 100.00,
2009 'financial_type_id' => $this->_financialTypeId,
2010 'non_deductible_amount' => 10.00,
2011 'contribution_status_id' => 1,
2012 ];
2013 $contribution1 = $this->callAPISuccess('contribution', 'create', $p1);
2014
2015 $p2 = [
2016 'contact_id' => $this->_individualId,
2017 'receive_date' => date('Ymd'),
2018 'total_amount' => 200.00,
2019 'financial_type_id' => $this->_financialTypeId,
2020 'non_deductible_amount' => 20.00,
2021 'trxn_id' => 5454565,
2022 'invoice_id' => 1212124,
2023 'fee_amount' => 50.00,
2024 'net_amount' => 60.00,
2025 'contribution_status_id' => 2,
2026 ];
2027 $contribution2 = $this->callAPISuccess('contribution', 'create', $p2);
2028
2029 $params = [
2030 'contribution_id' => $contribution2['id'],
2031 ];
2032 $result = $this->callAPISuccess('contribution', 'get', $params);
2033 $res = $result['values'][$contribution2['id']];
2034
2035 $this->assertEquals($p2['contact_id'], $res['contact_id']);
2036 $this->assertEquals($p2['total_amount'], $res['total_amount']);
2037 $this->assertEquals($p2['financial_type_id'], $res['financial_type_id']);
2038 $this->assertEquals($p2['net_amount'], $res['net_amount']);
2039 $this->assertEquals($p2['non_deductible_amount'], $res['non_deductible_amount']);
2040 $this->assertEquals($p2['fee_amount'], $res['fee_amount']);
2041 $this->assertEquals($p2['trxn_id'], $res['trxn_id']);
2042 $this->assertEquals($p2['invoice_id'], $res['invoice_id']);
2043 $this->assertEquals(CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'), $res['contribution_status_id']);
2044
2045 $this->contributionDelete($contribution1['id']);
2046 $this->contributionDelete($contribution2['id']);
2047 }
2048
2049 /**
2050 * Test completing a transaction via the API.
2051 *
2052 * Note that we are creating a logged in user because email goes out from
2053 * that person
2054 */
2055 public function testCompleteTransaction() {
2056 $mut = new CiviMailUtils($this, TRUE);
2057 $this->swapMessageTemplateForTestTemplate();
2058 $this->createLoggedInUser();
2059 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
2060 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2061 $this->callAPISuccess('contribution', 'completetransaction', [
2062 'id' => $contribution['id'],
2063 ]);
2064 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2065 $this->assertEquals('SSF', $contribution['contribution_source']);
2066 $this->assertEquals('Completed', $contribution['contribution_status']);
2067 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
2068 $mut->checkMailLog([
2069 'email:::anthony_anderson@civicrm.org',
2070 'is_monetary:::1',
2071 'amount:::100.00',
2072 'currency:::USD',
2073 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2074 "receipt_date:::\n",
2075 'contributeMode:::notify',
2076 'title:::Contribution',
2077 'displayName:::Mr. Anthony Anderson II',
2078 'contributionStatus:::Completed',
2079 ]);
2080 $mut->stop();
2081 $this->revertTemplateToReservedTemplate();
2082 }
2083
2084 /**
2085 * Test completing a transaction via the API with a non-USD transaction.
2086 */
2087 public function testCompleteTransactionEuro() {
2088 $mut = new CiviMailUtils($this, TRUE);
2089 $this->swapMessageTemplateForTestTemplate();
2090 $this->createLoggedInUser();
2091 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'currency' => 'EUR']);
2092 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2093
2094 $this->callAPISuccess('contribution', 'completetransaction', [
2095 'id' => $contribution['id'],
2096 ]);
2097
2098 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2099 $this->assertEquals('SSF', $contribution['contribution_source']);
2100 $this->assertEquals('Completed', $contribution['contribution_status']);
2101 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
2102
2103 $entityFinancialTransactions = $this->getFinancialTransactionsForContribution($contribution['id']);
2104 $entityFinancialTransaction = reset($entityFinancialTransactions);
2105 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', ['id' => $entityFinancialTransaction['financial_trxn_id']]);
2106 $this->assertEquals('EUR', $financialTrxn['currency']);
2107
2108 $mut->checkMailLog([
2109 'email:::anthony_anderson@civicrm.org',
2110 'is_monetary:::1',
2111 'amount:::100.00',
2112 'currency:::EUR',
2113 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2114 "receipt_date:::\n",
2115 'contributeMode:::notify',
2116 'title:::Contribution',
2117 'displayName:::Mr. Anthony Anderson II',
2118 'contributionStatus:::Completed',
2119 ]);
2120 $mut->stop();
2121 $this->revertTemplateToReservedTemplate();
2122 }
2123
2124 /**
2125 * Test to ensure mail is sent for pay later
2126 *
2127 * @throws \CRM_Core_Exception
2128 * @throws \API_Exception
2129 */
2130 public function testPayLater(): void {
2131 $mut = new CiviMailUtils($this, TRUE);
2132 $this->swapMessageTemplateForTestTemplate();
2133 $this->createLoggedInUser();
2134 $contributionPageID = $this->createQuickConfigContributionPage();
2135
2136 $params = [
2137 'id' => $contributionPageID,
2138 'price_' . $this->ids['PriceField']['basic'] => $this->ids['PriceFieldValue']['basic'],
2139 'contact_id' => $this->_individualId,
2140 'email-5' => 'anthony_anderson@civicrm.org',
2141 'payment_processor_id' => 0,
2142 'currencyID' => 'USD',
2143 'is_pay_later' => 1,
2144 'invoiceID' => 'f28e1ddc86f8c4a0ff5bcf46393e4bc8',
2145 'description' => 'Online Contribution: Help Support CiviCRM!',
2146 ];
2147 $this->callAPISuccess('ContributionPage', 'submit', $params);
2148
2149 $mut->checkMailLog([
2150 'is_pay_later:::1',
2151 'email:::anthony_anderson@civicrm.org',
2152 'pay_later_receipt:::This is a pay later receipt',
2153 'displayName:::Mr. Anthony Anderson II',
2154 'contributionPageId:::' . $contributionPageID,
2155 'title:::Test Contribution Page',
2156 'amount:::100',
2157 ]);
2158 $mut->stop();
2159 $this->revertTemplateToReservedTemplate();
2160 }
2161
2162 /**
2163 * Test to check whether contact billing address is used when no contribution address
2164 */
2165 public function testBillingAddress() {
2166 $mut = new CiviMailUtils($this, TRUE);
2167 $this->swapMessageTemplateForTestTemplate();
2168 $this->createLoggedInUser();
2169
2170 //Scenario 1: When Contact don't have any address
2171 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
2172 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2173 $this->callAPISuccess('contribution', 'completetransaction', [
2174 'id' => $contribution['id'],
2175 ]);
2176 $mut->checkMailLog([
2177 'address:::',
2178 ]);
2179
2180 // Scenario 2: Contribution using address
2181 $address = $this->callAPISuccess('address', 'create', [
2182 'street_address' => 'contribution billing st',
2183 'location_type_id' => 2,
2184 'contact_id' => $this->_params['contact_id'],
2185 ]);
2186 $params = array_merge($this->_params, [
2187 'contribution_status_id' => 2,
2188 'address_id' => $address['id'],
2189 ]
2190 );
2191 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2192 $this->callAPISuccess('contribution', 'completetransaction', [
2193 'id' => $contribution['id'],
2194 ]);
2195 $mut->checkMailLog([
2196 'address:::contribution billing st',
2197 ]);
2198
2199 // Scenario 3: Contribution wtth no address but contact has a billing address
2200 $this->callAPISuccess('address', 'create', [
2201 'id' => $address['id'],
2202 'street_address' => 'is billing st',
2203 'contact_id' => $this->_params['contact_id'],
2204 ]);
2205 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
2206 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2207 $this->callAPISuccess('contribution', 'completetransaction', [
2208 'id' => $contribution['id'],
2209 ]);
2210 $mut->checkMailLog([
2211 'address:::is billing st',
2212 ]);
2213
2214 $mut->stop();
2215 $this->revertTemplateToReservedTemplate();
2216 }
2217
2218 /**
2219 * Test completing a transaction via the API.
2220 *
2221 * Note that we are creating a logged in user because email goes out from
2222 * that person
2223 */
2224 public function testCompleteTransactionFeeAmount() {
2225 $this->createLoggedInUser();
2226 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
2227 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2228 $this->callAPISuccess('contribution', 'completetransaction', [
2229 'id' => $contribution['id'],
2230 'fee_amount' => '.56',
2231 'trxn_id' => '7778888',
2232 ]);
2233 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id'], 'sequential' => 1]);
2234 $this->assertEquals('Completed', $contribution['contribution_status']);
2235 $this->assertEquals('7778888', $contribution['trxn_id']);
2236 $this->assertEquals('0.56', $contribution['fee_amount']);
2237 $this->assertEquals('99.44', $contribution['net_amount']);
2238 }
2239
2240 /**
2241 * CRM-19126 Add test to verify when complete transaction is called tax
2242 * amount is not changed.
2243 *
2244 * We start of with a pending contribution.
2245 * - total_amount (input) = 100
2246 * - total_amount post save (based on tax being added) = 105
2247 * - net_amount = 95
2248 * - fee_amount = 5
2249 * - non_deductible_amount = 10
2250 * - tax rate = 5%
2251 * - tax_amount = 5
2252 * - sum of (calculated) line items = 105
2253 *
2254 * Note the fee_amount should really be set when the payment is received
2255 * and whatever the non_deductible amount is, it is ignored.
2256 *
2257 * The fee amount when the payment comes in is 6 rather than 5. The net_amount
2258 * and fee_amount should change, but not the total_amount or
2259 * the line items.
2260 *
2261 * @param string $thousandSeparator
2262 * punctuation used to refer to thousands.
2263 *
2264 * @throws \API_Exception
2265 * @throws \CRM_Core_Exception
2266 * @dataProvider getThousandSeparators
2267 */
2268 public function testCheckTaxAmount(string $thousandSeparator): void {
2269 $this->setCurrencySeparators($thousandSeparator);
2270 $this->createFinancialTypeWithSalesTax();
2271 $financialTypeId = $this->ids['FinancialType']['taxable'];
2272
2273 $contributionID = $this->callAPISuccess('Order', 'create',
2274 array_merge($this->_params, ['financial_type_id' => $financialTypeId])
2275 )['id'];
2276 $contributionPrePayment = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => ['tax_amount', 'total_amount']]);
2277 $this->validateAllContributions();
2278 $this->callAPISuccess('Contribution', 'completetransaction', [
2279 'id' => $contributionID,
2280 'trxn_id' => '777788888',
2281 'fee_amount' => '6.00',
2282 'sequential' => 1,
2283 ]);
2284 $contributionPostPayment = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => ['tax_amount', 'fee_amount', 'net_amount']]);
2285 $this->assertEquals(4.76, $contributionPrePayment['tax_amount']);
2286 $this->assertEquals(4.76, $contributionPostPayment['tax_amount']);
2287 $this->assertEquals('6.00', $contributionPostPayment['fee_amount']);
2288 $this->assertEquals('94.00', $contributionPostPayment['net_amount']);
2289 $this->validateAllContributions();
2290 $this->validateAllPayments();
2291 }
2292
2293 /**
2294 * Test repeat contribution successfully creates line item.
2295 *
2296 * @throws \CRM_Core_Exception
2297 */
2298 public function testRepeatTransaction(): void {
2299 $originalContribution = $this->setUpRepeatTransaction([], 'single');
2300 $this->callAPISuccess('contribution', 'repeattransaction', [
2301 'original_contribution_id' => $originalContribution['id'],
2302 'contribution_status_id' => 'Completed',
2303 'trxn_id' => 4567,
2304 ]);
2305 $lineItemParams = [
2306 'entity_id' => $originalContribution['id'],
2307 'sequential' => 1,
2308 'return' => [
2309 'entity_table',
2310 'qty',
2311 'unit_price',
2312 'line_total',
2313 'label',
2314 'financial_type_id',
2315 'deductible_amount',
2316 'price_field_value_id',
2317 'price_field_id',
2318 ],
2319 ];
2320 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2321 'entity_id' => $originalContribution['id'],
2322 ]));
2323 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2324 'entity_id' => $originalContribution['id'] + 1,
2325 ]));
2326 unset($lineItem1['values'][0]['id'], $lineItem1['values'][0]['entity_id']);
2327 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2328 $this->assertEquals($lineItem1['values'][0], $lineItem2['values'][0]);
2329 $this->_checkFinancialRecords([
2330 'id' => $originalContribution['id'] + 1,
2331 'payment_instrument_id' => $this->callAPISuccessGetValue('PaymentProcessor', [
2332 'id' => $originalContribution['payment_processor_id'],
2333 'return' => 'payment_instrument_id',
2334 ]),
2335 ], 'online');
2336 }
2337
2338 /**
2339 * Test custom data is copied over from the template transaction.
2340 *
2341 * (Over time various discussions have deemed this to be the most recent one, allowing
2342 * users to alter custom data going forwards. This is implemented for line items already.
2343 *
2344 * @throws \API_Exception
2345 * @throws \CRM_Core_Exception
2346 */
2347 public function testRepeatTransactionWithCustomData(): void {
2348 $this->createCustomGroupWithFieldOfType(['extends' => 'Contribution', 'name' => 'Repeat'], 'text');
2349 $originalContribution = $this->setUpRepeatTransaction([], 'single', [$this->getCustomFieldName('text') => 'first']);
2350 $this->callAPISuccess('contribution', 'repeattransaction', [
2351 'contribution_recur_id' => $originalContribution['contribution_recur_id'],
2352 'contribution_status_id' => 'Completed',
2353 'trxn_id' => 'my_trxn',
2354 ]);
2355
2356 $contribution = Contribution::get()
2357 ->addWhere('trxn_id', '=', 'my_trxn')
2358 ->addSelect('Custom_Group.Enter_text_here')
2359 ->addSelect('id')
2360 ->execute()->first();
2361 $this->assertEquals('first', $contribution['Custom_Group.Enter_text_here']);
2362
2363 Contribution::update()->setValues(['Custom_Group.Enter_text_here' => 'second'])->addWhere('id', '=', $contribution['id'])->execute();
2364
2365 $this->callAPISuccess('contribution', 'repeattransaction', [
2366 'original_contribution_id' => $originalContribution['id'],
2367 'contribution_status_id' => 'Completed',
2368 'trxn_id' => 'number_3',
2369 ]);
2370
2371 $contribution = Contribution::get()
2372 ->addWhere('trxn_id', '=', 'number_3')
2373 ->setSelect(['id', 'Custom_Group.Enter_text_here'])
2374 ->execute()->first();
2375 $this->assertEquals('second', $contribution['Custom_Group.Enter_text_here']);
2376 }
2377
2378 /**
2379 * Test repeat contribution successfully creates line items (plural).
2380 *
2381 * @throws \CRM_Core_Exception
2382 */
2383 public function testRepeatTransactionLineItems(): void {
2384 // CRM-19309
2385 $originalContribution = $this->setUpRepeatTransaction([], 'multiple');
2386 $this->callAPISuccess('contribution', 'repeattransaction', [
2387 'original_contribution_id' => $originalContribution['id'],
2388 'contribution_status_id' => 'Completed',
2389 'trxn_id' => 1234,
2390 ]);
2391
2392 $lineItemParams = [
2393 'entity_id' => $originalContribution['id'],
2394 'sequential' => 1,
2395 'return' => [
2396 'entity_table',
2397 'qty',
2398 'unit_price',
2399 'line_total',
2400 'label',
2401 'financial_type_id',
2402 'deductible_amount',
2403 'price_field_value_id',
2404 'price_field_id',
2405 ],
2406 ];
2407 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2408 'entity_id' => $originalContribution['id'],
2409 'options' => ['sort' => 'qty'],
2410 ]))['values'];
2411 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2412 'entity_id' => $originalContribution['id'] + 1,
2413 'options' => ['sort' => 'qty'],
2414 ]))['values'];
2415
2416 // unset id and entity_id for all of them to be able to compare the lineItems:
2417 unset($lineItem1[0]['id'], $lineItem1[0]['entity_id']);
2418 unset($lineItem2[0]['id'], $lineItem2[0]['entity_id']);
2419 $this->assertEquals($lineItem1[0], $lineItem2[0]);
2420
2421 unset($lineItem1[1]['id'], $lineItem1[1]['entity_id']);
2422 unset($lineItem2[1]['id'], $lineItem2[1]['entity_id']);
2423 $this->assertEquals($lineItem1[1], $lineItem2[1]);
2424
2425 // CRM-19309 so in future we also want to:
2426 // check that financial_line_items have been created for entity_id 3 and 4;
2427
2428 $this->callAPISuccessGetCount('FinancialItem', ['description' => 'Sales Tax', 'amount' => 0], 0);
2429 }
2430
2431 /**
2432 * Test repeat contribution successfully creates is_test transaction.
2433 *
2434 * @throws \CRM_Core_Exception
2435 */
2436 public function testRepeatTransactionIsTest(): void {
2437 $this->_params['is_test'] = 1;
2438 $originalContribution = $this->setUpRepeatTransaction(['is_test' => 1], 'single');
2439
2440 $this->callAPISuccess('contribution', 'repeattransaction', [
2441 'original_contribution_id' => $originalContribution['id'],
2442 'contribution_status_id' => 'Completed',
2443 'trxn_id' => '1234',
2444 ]);
2445 $this->callAPISuccessGetCount('Contribution', ['contribution_test' => 1], 2);
2446 }
2447
2448 /**
2449 * Test repeat contribution passed in status.
2450 *
2451 * @throws \CRM_Core_Exception
2452 */
2453 public function testRepeatTransactionPassedInStatus(): void {
2454 $originalContribution = $this->setUpRepeatTransaction([], 'single');
2455
2456 $this->callAPISuccess('contribution', 'repeattransaction', [
2457 'original_contribution_id' => $originalContribution['id'],
2458 'contribution_status_id' => 'Pending',
2459 'trxn_id' => 1234,
2460 ]);
2461 $this->callAPISuccessGetCount('Contribution', ['contribution_status_id' => 2], 1);
2462 }
2463
2464 /**
2465 * Test repeat contribution accepts recur_id instead of
2466 * original_contribution_id.
2467 *
2468 * @throws \CRM_Core_Exception
2469 */
2470 public function testRepeatTransactionAcceptRecurID(): void {
2471 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2472 'contact_id' => $this->_individualId,
2473 'installments' => '12',
2474 'frequency_interval' => '1',
2475 'amount' => '100',
2476 'contribution_status_id' => 1,
2477 'start_date' => '2012-01-01 00:00:00',
2478 'currency' => 'USD',
2479 'frequency_unit' => 'month',
2480 'payment_processor_id' => $this->paymentProcessorID,
2481 ]);
2482 $this->callAPISuccess('contribution', 'create', array_merge(
2483 $this->_params,
2484 ['contribution_recur_id' => $contributionRecur['id']])
2485 );
2486
2487 $this->callAPISuccess('contribution', 'repeattransaction', [
2488 'contribution_recur_id' => $contributionRecur['id'],
2489 'contribution_status_id' => 'Completed',
2490 'trxn_id' => 1234,
2491 ]);
2492
2493 }
2494
2495 /**
2496 * CRM-19873 Test repeattransaction if contribution_recur_id is a test.
2497 *
2498 * @throws \CRM_Core_Exception
2499 */
2500 public function testRepeatTransactionTestRecurId() {
2501 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
2502 'contact_id' => $this->_individualId,
2503 'frequency_interval' => '1',
2504 'amount' => '1.00',
2505 'contribution_status_id' => 1,
2506 'start_date' => '2017-01-01 00:00:00',
2507 'currency' => 'USD',
2508 'frequency_unit' => 'month',
2509 'payment_processor_id' => $this->paymentProcessorID,
2510 'is_test' => 1,
2511 ]);
2512 $this->callAPISuccess('contribution', 'create', array_merge(
2513 $this->_params,
2514 [
2515 'contribution_recur_id' => $contributionRecur['id'],
2516 'is_test' => 1,
2517 ])
2518 );
2519
2520 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2521 'contribution_recur_id' => $contributionRecur['id'],
2522 'contribution_status_id' => 'Completed',
2523 'trxn_id' => 'magic_number',
2524 ]);
2525
2526 $this->assertEquals($contributionRecur['values'][1]['is_test'], $repeatedContribution['values'][2]['is_test']);
2527 }
2528
2529 /**
2530 * CRM-19945 Tests that Contribute.repeattransaction renews a membership when contribution status=Completed
2531 *
2532 * @throws \CRM_Core_Exception
2533 */
2534 public function testRepeatTransactionMembershipRenewCompletedContribution(): void {
2535 [$originalContribution, $membership] = $this->setUpAutoRenewMembership();
2536
2537 $this->callAPISuccess('Contribution', 'repeattransaction', [
2538 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2539 'contribution_status_id' => 'Failed',
2540 ]);
2541
2542 $this->callAPISuccess('membership', 'create', [
2543 'id' => $membership['id'],
2544 'end_date' => 'yesterday',
2545 'status_id' => 'Expired',
2546 ]);
2547
2548 $contribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
2549 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2550 'contribution_status_id' => 'Completed',
2551 'trxn_id' => 'bobsled',
2552 ]);
2553
2554 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
2555 'id' => $membership['id'],
2556 'return' => 'status_id',
2557 ]);
2558
2559 $membership = $this->callAPISuccess('membership', 'get', [
2560 'id' => $membership['id'],
2561 ]);
2562
2563 $this->assertEquals('New', CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
2564
2565 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2566 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2567 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2568 }
2569
2570 /**
2571 * This is one of those tests that locks in existing behaviour.
2572 *
2573 * I feel like correct behaviour is arguable & has been discussed in the past. However, if the membership has
2574 * a date which says it should be expired then the result of repeattransaction is to push that date
2575 * to be one membership term from 'now' with status 'new'.
2576 */
2577 public function testRepeattransactionRenewMembershipOldMembership() {
2578 $entities = $this->setUpAutoRenewMembership();
2579 $newStatusID = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'New');
2580 $membership = $this->callAPISuccess('Membership', 'create', [
2581 'id' => $entities[1]['id'],
2582 'join_date' => '4 months ago',
2583 'start_date' => '3 months ago',
2584 'end_date' => '2 months ago',
2585 ]);
2586 $membership = $membership['values'][$membership['id']];
2587
2588 // This status does not appear to be calculated at all and is set to 'new'. Feels like a bug.
2589 $this->assertEquals($newStatusID, $membership['status_id']);
2590
2591 // So it seems renewing this expired membership results in it's new status being current and it being pushed to a future date
2592 $this->callAPISuccess('Contribution', 'repeattransaction', ['original_contribution_id' => $entities[0]['id'], 'contribution_status_id' => 'Completed']);
2593 $membership = $this->callAPISuccessGetSingle('Membership', ['id' => $membership['id']]);
2594 // If this date calculation winds up being flakey the spirit of the test would be maintained by just checking
2595 // date is greater than today.
2596 $this->assertEquals(date('Y-m-d', strtotime('+ 1 month -1 day')), $membership['end_date']);
2597 $this->assertEquals($newStatusID, $membership['membership_type_id']);
2598 }
2599
2600 /**
2601 * CRM-19945 Tests that Contribute.repeattransaction DOES NOT renew a membership when contribution status=Failed
2602 *
2603 * @dataProvider contributionStatusProvider
2604 *
2605 * @throws \CRM_Core_Exception
2606 */
2607 public function testRepeatTransactionMembershipRenewContributionNotCompleted($contributionStatus): void {
2608 // Completed status should renew so we don't test that here
2609 // In Progress status was never actually intended to be available for contributions.
2610 // Partially paid is not valid.
2611 if (in_array($contributionStatus['name'], ['Completed', 'In Progress', 'Partially paid'])) {
2612 return;
2613 }
2614 [$originalContribution, $membership] = $this->setUpAutoRenewMembership();
2615
2616 $this->callAPISuccess('Contribution', 'repeattransaction', [
2617 'original_contribution_id' => $originalContribution['id'],
2618 'contribution_status_id' => 'Completed',
2619 ]);
2620
2621 $this->callAPISuccess('membership', 'create', [
2622 'id' => $membership['id'],
2623 'end_date' => 'yesterday',
2624 'status_id' => 'Expired',
2625 ]);
2626
2627 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2628 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2629 'contribution_status_id' => $contributionStatus['name'],
2630 'trxn_id' => 'bobsled',
2631 ]);
2632
2633 $updatedMembership = $this->callAPISuccess('membership', 'getsingle', ['id' => $membership['id']]);
2634
2635 $dateTime = new DateTime('yesterday');
2636 $this->assertEquals($dateTime->format('Y-m-d'), $updatedMembership['end_date']);
2637 $this->assertEquals(CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', 'Expired'), $updatedMembership['status_id']);
2638
2639 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2640 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2641 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2642 }
2643
2644 /**
2645 * Dataprovider provides contribution status as [optionvalue=>contribution_status_name]
2646 * FIXME: buildOptions seems to die in CRM_Core_Config::_construct when in test mode.
2647 *
2648 * @return array
2649 * @throws \CiviCRM_API3_Exception
2650 */
2651 public function contributionStatusProvider() {
2652 $contributionStatuses = civicrm_api3('OptionValue', 'get', [
2653 'return' => ["id", "name"],
2654 'option_group_id' => "contribution_status",
2655 ]);
2656 foreach ($contributionStatuses['values'] as $statusName) {
2657 $statuses[] = [$statusName];
2658 }
2659 return $statuses;
2660 }
2661
2662 /**
2663 * CRM-16397 test appropriate action if total amount has changed for single
2664 * line items.
2665 *
2666 * @throws \CRM_Core_Exception
2667 */
2668 public function testRepeatTransactionAlteredAmount(): void {
2669 $paymentProcessorID = $this->paymentProcessorCreate();
2670 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2671 'contact_id' => $this->_individualId,
2672 'installments' => '12',
2673 'frequency_interval' => '1',
2674 'amount' => '500',
2675 'contribution_status_id' => 1,
2676 'start_date' => '2012-01-01 00:00:00',
2677 'currency' => 'USD',
2678 'frequency_unit' => 'month',
2679 'payment_processor_id' => $paymentProcessorID,
2680 ]);
2681 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2682 $this->_params,
2683 [
2684 'contribution_recur_id' => $contributionRecur['id'],
2685 ])
2686 );
2687
2688 $this->callAPISuccess('contribution', 'repeattransaction', [
2689 'original_contribution_id' => $originalContribution['id'],
2690 'contribution_status_id' => 'Completed',
2691 'trxn_id' => 1234,
2692 'total_amount' => '400',
2693 'fee_amount' => 50,
2694 ]);
2695
2696 $lineItemParams = [
2697 'entity_id' => $originalContribution['id'],
2698 'sequential' => 1,
2699 'return' => [
2700 'entity_table',
2701 'qty',
2702 'unit_price',
2703 'line_total',
2704 'label',
2705 'financial_type_id',
2706 'deductible_amount',
2707 'price_field_value_id',
2708 'price_field_id',
2709 ],
2710 ];
2711 $this->callAPISuccessGetSingle('contribution', [
2712 'total_amount' => 400,
2713 'fee_amount' => 50,
2714 'net_amount' => 350,
2715 ]);
2716 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2717 'entity_id' => $originalContribution['id'],
2718 ]));
2719 $expectedLineItem = array_merge(
2720 $lineItem1['values'][0], [
2721 'line_total' => '400.00',
2722 'unit_price' => '400.00',
2723 ]
2724 );
2725
2726 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2727 'entity_id' => $originalContribution['id'] + 1,
2728 ]));
2729
2730 unset($expectedLineItem['id'], $expectedLineItem['entity_id'], $lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2731 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2732 }
2733
2734 /**
2735 * Test financial_type_id override behaviour with a single line item.
2736 *
2737 * CRM-17718 a passed in financial_type_id is allowed to override the
2738 * original contribution where there is only one line item.
2739 *
2740 * @throws \CRM_Core_Exception
2741 */
2742 public function testRepeatTransactionPassedInFinancialType() {
2743 $originalContribution = $this->setUpRecurringContribution();
2744
2745 $this->callAPISuccess('Contribution', 'repeattransaction', [
2746 'original_contribution_id' => $originalContribution['id'],
2747 'contribution_status_id' => 'Completed',
2748 'trxn_id' => 12345,
2749 'financial_type_id' => 2,
2750 ]);
2751 $lineItemParams = [
2752 'entity_id' => $originalContribution['id'],
2753 'sequential' => 1,
2754 'return' => [
2755 'entity_table',
2756 'qty',
2757 'unit_price',
2758 'line_total',
2759 'label',
2760 'financial_type_id',
2761 'deductible_amount',
2762 'price_field_value_id',
2763 'price_field_id',
2764 ],
2765 ];
2766
2767 $this->callAPISuccessGetSingle('Contribution', [
2768 'total_amount' => 100,
2769 'financial_type_id' => 2,
2770 ]);
2771 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2772 'entity_id' => $originalContribution['id'],
2773 ]));
2774 $expectedLineItem = array_merge(
2775 $lineItem1['values'][0], [
2776 'line_total' => '100.00',
2777 'unit_price' => '100.00',
2778 'financial_type_id' => 2,
2779 'contribution_type_id' => 2,
2780 ]
2781 );
2782 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2783 'entity_id' => $originalContribution['id'] + 1,
2784 ]));
2785 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2786 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2787 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2788 }
2789
2790 /**
2791 * Test Contribution with Order api.
2792 *
2793 * @throws \CRM_Core_Exception|\CiviCRM_API3_Exception
2794 */
2795 public function testContributionOrder() {
2796 $this->createContributionAndMembershipOrder();
2797 $contribution = $this->callAPISuccess('contribution', 'get')['values'][$this->ids['Contribution'][0]];
2798 $this->assertEquals('Pending Label**', $contribution['contribution_status']);
2799 $membership = $this->callAPISuccessGetSingle('Membership', ['contact_id' => $this->ids['Contact']['order']]);
2800
2801 $this->callAPISuccess('Payment', 'create', [
2802 'contribution_id' => $this->ids['Contribution'][0],
2803 'payment_instrument_id' => 'Check',
2804 'total_amount' => 300,
2805 ]);
2806 $contribution = $this->callAPISuccess('contribution', 'get')['values'][$this->ids['Contribution'][0]];
2807 $this->assertEquals('Completed', $contribution['contribution_status']);
2808
2809 $lineItem = $this->callAPISuccess('LineItem', 'get', [
2810 'sequential' => 1,
2811 'contribution_id' => $this->ids['Contribution'][0],
2812 ])['values'];
2813 $this->assertCount(2, $lineItem);
2814 $this->assertEquals($this->ids['Contribution'][0], $lineItem[0]['entity_id']);
2815 $this->assertEquals('civicrm_contribution', $lineItem[0]['entity_table']);
2816 $this->assertEquals($this->ids['Contribution'][0], $lineItem[0]['contribution_id']);
2817 $this->assertEquals($this->ids['Contribution'][0], $lineItem[1]['contribution_id']);
2818 $this->assertEquals('100.00', $lineItem[0]['line_total']);
2819 $this->assertEquals('200.00', $lineItem[1]['line_total']);
2820 $this->assertEquals($membership['id'], $lineItem[1]['entity_id']);
2821 $this->assertEquals('civicrm_membership', $lineItem[1]['entity_table']);
2822 }
2823
2824 /**
2825 * Test financial_type_id override behaviour with a single line item.
2826 *
2827 * CRM-17718 a passed in financial_type_id is not allowed to override the
2828 * original contribution where there is more than one line item.
2829 *
2830 * @throws \CRM_Core_Exception
2831 */
2832 public function testRepeatTransactionPassedInFinancialTypeTwoLineItems(): void {
2833 $this->_params = $this->getParticipantOrderParams();
2834 $originalContribution = $this->setUpRecurringContribution();
2835
2836 $this->callAPISuccess('Contribution', 'repeattransaction', [
2837 'original_contribution_id' => $originalContribution['id'],
2838 'contribution_status_id' => 'Completed',
2839 'trxn_id' => 'repeat',
2840 'financial_type_id' => 2,
2841 ]);
2842
2843 // Retrieve the new contribution and note the financial type passed in has been ignored.
2844 $contribution = $this->callAPISuccessGetSingle('Contribution', [
2845 'trxn_id' => 'repeat',
2846 ]);
2847 $this->assertEquals(4, $contribution['financial_type_id']);
2848
2849 $lineItems = $this->callAPISuccess('line_item', 'get', [
2850 'entity_id' => $contribution['id'],
2851 ])['values'];
2852 foreach ($lineItems as $lineItem) {
2853 $this->assertNotEquals(2, $lineItem['financial_type_id']);
2854 }
2855 }
2856
2857 /**
2858 * CRM-17718 test appropriate action if financial type has changed for single
2859 * line items.
2860 *
2861 * @throws \CRM_Core_Exception
2862 */
2863 public function testRepeatTransactionUpdatedFinancialType(): void {
2864 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2865
2866 $this->callAPISuccess('contribution', 'repeattransaction', [
2867 'contribution_recur_id' => $originalContribution['id'],
2868 'contribution_status_id' => 'Completed',
2869 'trxn_id' => 234,
2870 ]);
2871 $lineItemParams = [
2872 'entity_id' => $originalContribution['id'],
2873 'sequential' => 1,
2874 'return' => [
2875 'entity_table',
2876 'qty',
2877 'unit_price',
2878 'line_total',
2879 'label',
2880 'financial_type_id',
2881 'deductible_amount',
2882 'price_field_value_id',
2883 'price_field_id',
2884 ],
2885 ];
2886
2887 $this->callAPISuccessGetSingle('contribution', [
2888 'total_amount' => 100,
2889 'financial_type_id' => 2,
2890 ]);
2891 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2892 'entity_id' => $originalContribution['id'],
2893 ]))['values'][0];
2894 $expectedLineItem = array_merge(
2895 $lineItem1, [
2896 'line_total' => '100.00',
2897 'unit_price' => '100.00',
2898 'financial_type_id' => 2,
2899 'contribution_type_id' => 2,
2900 ]
2901 );
2902
2903 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2904 'entity_id' => $originalContribution['id'] + 1,
2905 ]));
2906 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2907 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2908 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2909 }
2910
2911 /**
2912 * CRM-16397 test appropriate action if campaign has been passed in.
2913 */
2914 public function testRepeatTransactionPassedInCampaign() {
2915 $paymentProcessorID = $this->paymentProcessorCreate();
2916 $campaignID = $this->campaignCreate();
2917 $campaignID2 = $this->campaignCreate();
2918 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2919 'contact_id' => $this->_individualId,
2920 'installments' => '12',
2921 'frequency_interval' => '1',
2922 'amount' => '100',
2923 'contribution_status_id' => 1,
2924 'start_date' => '2012-01-01 00:00:00',
2925 'currency' => 'USD',
2926 'frequency_unit' => 'month',
2927 'payment_processor_id' => $paymentProcessorID,
2928 ]);
2929 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2930 $this->_params,
2931 [
2932 'contribution_recur_id' => $contributionRecur['id'],
2933 'campaign_id' => $campaignID,
2934 ])
2935 );
2936
2937 $this->callAPISuccess('contribution', 'repeattransaction', [
2938 'original_contribution_id' => $originalContribution['id'],
2939 'contribution_status_id' => 'Completed',
2940 'trxn_id' => 2345,
2941 'campaign_id' => $campaignID2,
2942 ]);
2943
2944 $this->callAPISuccessGetSingle('contribution', [
2945 'total_amount' => 100,
2946 'campaign_id' => $campaignID2,
2947 ]);
2948 }
2949
2950 /**
2951 * CRM-17718 campaign stored on contribution recur gets priority.
2952 *
2953 * This reflects the fact we permit people to update them.
2954 *
2955 * @throws \CRM_Core_Exception
2956 */
2957 public function testRepeatTransactionUpdatedCampaign(): void {
2958 $paymentProcessorID = $this->paymentProcessorCreate();
2959 $campaignID = $this->campaignCreate();
2960 $campaignID2 = $this->campaignCreate();
2961 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2962 'contact_id' => $this->_individualId,
2963 'installments' => '12',
2964 'frequency_interval' => '1',
2965 'amount' => '100',
2966 'contribution_status_id' => 1,
2967 'start_date' => '2012-01-01 00:00:00',
2968 'currency' => 'USD',
2969 'frequency_unit' => 'month',
2970 'payment_processor_id' => $paymentProcessorID,
2971 'campaign_id' => $campaignID,
2972 ]);
2973 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2974 $this->_params,
2975 [
2976 'contribution_recur_id' => $contributionRecur['id'],
2977 'campaign_id' => $campaignID2,
2978 ])
2979 );
2980
2981 $this->callAPISuccess('contribution', 'repeattransaction', [
2982 'original_contribution_id' => $originalContribution['id'],
2983 'contribution_status_id' => 'Completed',
2984 'trxn_id' => 789,
2985 ]);
2986
2987 $this->callAPISuccessGetSingle('Contribution', [
2988 'total_amount' => 100,
2989 'campaign_id' => $campaignID,
2990 ]);
2991 }
2992
2993 /**
2994 * CRM-20685 Repeattransaction produces incorrect Financial Type ID (in
2995 * specific circumstance) - if number of lineItems = 1.
2996 *
2997 * This case happens when the line item & contribution do not have the same
2998 * type in his initiating transaction.
2999 *
3000 * @throws \CRM_Core_Exception
3001 */
3002 public function testRepeatTransactionUpdatedFinancialTypeAndNotEquals(): void {
3003 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
3004 // This will made the trick to get the not equals behaviour.
3005 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 4]);
3006 $this->callAPISuccess('contribution', 'repeattransaction', [
3007 'contribution_recur_id' => $originalContribution['id'],
3008 'contribution_status_id' => 'Completed',
3009 'trxn_id' => 1234,
3010 ]);
3011 $lineItemParams = [
3012 'entity_id' => $originalContribution['id'],
3013 'sequential' => 1,
3014 'return' => [
3015 'entity_table',
3016 'qty',
3017 'unit_price',
3018 'line_total',
3019 'label',
3020 'financial_type_id',
3021 'deductible_amount',
3022 'price_field_value_id',
3023 'price_field_id',
3024 ],
3025 ];
3026 $this->callAPISuccessGetSingle('contribution', [
3027 'total_amount' => 100,
3028 'financial_type_id' => 2,
3029 ]);
3030 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
3031 'entity_id' => $originalContribution['id'],
3032 ]));
3033 $expectedLineItem = array_merge(
3034 $lineItem1['values'][0], [
3035 'line_total' => '100.00',
3036 'unit_price' => '100.00',
3037 'financial_type_id' => 4,
3038 'contribution_type_id' => 4,
3039 ]
3040 );
3041
3042 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
3043 'entity_id' => $originalContribution['id'] + 1,
3044 ]));
3045 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 1]);
3046 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
3047 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
3048 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
3049 }
3050
3051 /**
3052 * Test completing a transaction does not 'mess' with net amount (CRM-15960).
3053 */
3054 public function testCompleteTransactionNetAmountOK() {
3055 $this->createLoggedInUser();
3056 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
3057 unset($params['net_amount']);
3058 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3059 $this->callAPISuccess('contribution', 'completetransaction', [
3060 'id' => $contribution['id'],
3061 ]);
3062 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
3063 $this->assertEquals('Completed', $contribution['contribution_status']);
3064 $this->assertTrue(($contribution['total_amount'] - $contribution['net_amount']) == $contribution['fee_amount']);
3065 }
3066
3067 /**
3068 * CRM-14151 - Test completing a transaction via the API.
3069 */
3070 public function testCompleteTransactionWithReceiptDateSet() {
3071 $this->swapMessageTemplateForTestTemplate();
3072 $mut = new CiviMailUtils($this, TRUE);
3073 $this->createLoggedInUser();
3074 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
3075 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3076 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id'], 'trxn_date' => date('Y-m-d')]);
3077 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'sequential' => 1]);
3078 $this->assertEquals('Completed', $contribution['values'][0]['contribution_status']);
3079 // Make sure receive_date is original date and make sure payment date is today
3080 $this->assertEquals('2012-05-11', date('Y-m-d', strtotime($contribution['values'][0]['receive_date'])));
3081 $payment = $this->callAPISuccess('payment', 'get', ['contribution_id' => $contribution['id'], 'sequential' => 1]);
3082 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($payment['values'][0]['trxn_date'])));
3083 $mut->checkMailLog([
3084 'Receipt - Contribution',
3085 'receipt_date:::' . date('Ymd'),
3086 ]);
3087 $mut->stop();
3088 $this->revertTemplateToReservedTemplate();
3089 }
3090
3091 /**
3092 * CRM-1960 - Test to ensure that completetransaction respects the is_email_receipt setting
3093 */
3094 public function testCompleteTransactionWithEmailReceiptInput() {
3095 $contributionPage = $this->createReceiptableContributionPage();
3096
3097 $this->_params['contribution_page_id'] = $contributionPage['id'];
3098 $params = array_merge($this->_params, ['contribution_status_id' => 2]);
3099 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3100 // Complete the transaction overriding is_email_receipt to = FALSE
3101 $this->callAPISuccess('contribution', 'completetransaction', [
3102 'id' => $contribution['id'],
3103 'trxn_date' => date('2011-04-09'),
3104 'trxn_id' => 'kazam',
3105 'is_email_receipt' => 0,
3106 ]);
3107 // Check if a receipt was issued
3108 $receipt_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receipt_date']);
3109 $this->assertEquals('', $receipt_date);
3110 }
3111
3112 /**
3113 * Test that $is_recur is assigned to the receipt.
3114 */
3115 public function testCompleteTransactionForRecurring() {
3116 $this->mut = new CiviMailUtils($this, TRUE);
3117 $this->swapMessageTemplateForTestTemplate();
3118 $recurring = $this->setUpRecurringContribution();
3119 $contributionPage = $this->createReceiptableContributionPage(['is_recur' => TRUE, 'recur_frequency_unit' => 'month', 'recur_interval' => 1]);
3120
3121 $this->_params['contribution_page_id'] = $contributionPage['id'];
3122 $this->_params['contribution_recur_id'] = $recurring['id'];
3123
3124 $contribution = $this->setUpForCompleteTransaction();
3125
3126 $this->callAPISuccess('contribution', 'completetransaction', [
3127 'id' => $contribution['id'],
3128 'trxn_date' => date('2011-04-09'),
3129 'trxn_id' => 'kazam',
3130 'is_email_receipt' => 1,
3131 ]);
3132
3133 $this->mut->checkMailLog([
3134 'is_recur:::1',
3135 'cancelSubscriptionUrl:::' . CIVICRM_UF_BASEURL,
3136 ]);
3137 $this->mut->stop();
3138 $this->revertTemplateToReservedTemplate();
3139 }
3140
3141 /**
3142 * CRM-19710 - Test to ensure that completetransaction respects the input for
3143 * is_email_receipt setting.
3144 *
3145 * If passed in it will override the default from contribution page.
3146 *
3147 * @throws \CRM_Core_Exception
3148 */
3149 public function testCompleteTransactionWithEmailReceiptInputTrue(): void {
3150 $mut = new CiviMailUtils($this, TRUE);
3151 $this->createLoggedInUser();
3152 $contributionPageParams = ['is_email_receipt' => 0];
3153 // Create a Contribution Page with is_email_receipt = FALSE
3154 $contributionPageID = $this->createQuickConfigContributionPage($contributionPageParams);
3155 $this->_params['contribution_page_id'] = $contributionPageID;
3156 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
3157 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3158 // Complete the transaction overriding is_email_receipt to = TRUE
3159 $this->callAPISuccess('contribution', 'completetransaction', [
3160 'id' => $contribution['id'],
3161 'is_email_receipt' => 1,
3162 ]);
3163 $mut->checkMailLog([
3164 'Contribution Information',
3165 ]);
3166 $mut->stop();
3167 }
3168
3169 /**
3170 * Complete the transaction using the template with all the possible.
3171 */
3172 public function testCompleteTransactionWithTestTemplate() {
3173 $this->swapMessageTemplateForTestTemplate();
3174 $contribution = $this->setUpForCompleteTransaction();
3175 $this->callAPISuccess('contribution', 'completetransaction', [
3176 'id' => $contribution['id'],
3177 'trxn_date' => date('2011-04-09'),
3178 'trxn_id' => 'kazam',
3179 ]);
3180 $receive_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receive_date']);
3181 $this->mut->checkMailLog([
3182 'email:::anthony_anderson@civicrm.org',
3183 'is_monetary:::1',
3184 'amount:::100.00',
3185 'currency:::USD',
3186 'receive_date:::' . date('Ymd', strtotime($receive_date)),
3187 'receipt_date:::' . date('Ymd'),
3188 'contributeMode:::notify',
3189 'title:::Contribution',
3190 'displayName:::Mr. Anthony Anderson II',
3191 'trxn_id:::kazam',
3192 'contactID:::' . $this->_params['contact_id'],
3193 'contributionID:::' . $contribution['id'],
3194 'financialTypeId:::1',
3195 'financialTypeName:::Donation',
3196 ]);
3197 $this->mut->stop();
3198 $this->revertTemplateToReservedTemplate();
3199 }
3200
3201 /**
3202 * Complete the transaction using the template with all the possible.
3203 */
3204 public function testCompleteTransactionContributionPageFromAddress() {
3205 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
3206 'receipt_from_name' => 'Mickey Mouse',
3207 'receipt_from_email' => 'mickey@mouse.com',
3208 'title' => "Test Contribution Page",
3209 'financial_type_id' => 1,
3210 'currency' => 'NZD',
3211 'goal_amount' => 50,
3212 'is_pay_later' => 1,
3213 'is_monetary' => TRUE,
3214 'is_email_receipt' => TRUE,
3215 ]);
3216 $this->_params['contribution_page_id'] = $contributionPage['id'];
3217 $contribution = $this->setUpForCompleteTransaction();
3218 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id']]);
3219 $this->mut->checkMailLog([
3220 'mickey@mouse.com',
3221 'Mickey Mouse <',
3222 ]);
3223 $this->mut->stop();
3224 }
3225
3226 /**
3227 * Test completing first transaction in a recurring series.
3228 *
3229 * The status should be set to 'in progress' and the next scheduled payment date calculated.
3230 *
3231 * @dataProvider getScheduledDateData
3232 *
3233 * @param array $dataSet
3234 *
3235 * @throws \Exception
3236 */
3237 public function testCompleteTransactionSetStatusToInProgress($dataSet) {
3238 $paymentProcessorID = $this->paymentProcessorCreate();
3239 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
3240 'contact_id' => $this->_individualId,
3241 'installments' => '2',
3242 'frequency_interval' => '1',
3243 'amount' => '500',
3244 'contribution_status_id' => 'Pending',
3245 'start_date' => '2012-01-01 00:00:00',
3246 'currency' => 'USD',
3247 'frequency_unit' => 'month',
3248 'payment_processor_id' => $paymentProcessorID,
3249 ], $dataSet['data']));
3250 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
3251 $this->_params,
3252 [
3253 'contribution_recur_id' => $contributionRecur['id'],
3254 'contribution_status_id' => 'Pending',
3255 'receive_date' => $dataSet['receive_date'],
3256 ])
3257 );
3258 $this->callAPISuccess('Contribution', 'completetransaction', [
3259 'id' => $contribution,
3260 'receive_date' => $dataSet['receive_date'],
3261 ]);
3262 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3263 'id' => $contributionRecur['id'],
3264 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
3265 ]);
3266 $this->assertEquals(5, $contributionRecur['contribution_status_id']);
3267 $this->assertEquals($dataSet['expected'], $contributionRecur['next_sched_contribution_date']);
3268 $this->callAPISuccess('Contribution', 'create', array_merge(
3269 $this->_params,
3270 [
3271 'contribution_recur_id' => $contributionRecur['id'],
3272 'contribution_status_id' => 'Completed',
3273 ]
3274 ));
3275 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3276 'id' => $contributionRecur['id'],
3277 'return' => ['contribution_status_id'],
3278 ]);
3279 $this->assertEquals(1, $contributionRecur['contribution_status_id']);
3280 }
3281
3282 /**
3283 * Get dates for testing.
3284 *
3285 * @return array
3286 */
3287 public function getScheduledDateData() {
3288 $result = [];
3289 $result[]['2016-08-31-1-month'] = [
3290 'data' => [
3291 'start_date' => '2016-08-31',
3292 'frequency_interval' => 1,
3293 'frequency_unit' => 'month',
3294 ],
3295 'receive_date' => '2016-08-31',
3296 'expected' => '2016-10-01 00:00:00',
3297 ];
3298 $result[]['2012-01-01-1-month'] = [
3299 'data' => [
3300 'start_date' => '2012-01-01',
3301 'frequency_interval' => 1,
3302 'frequency_unit' => 'month',
3303 ],
3304 'receive_date' => '2012-01-01',
3305 'expected' => '2012-02-01 00:00:00',
3306 ];
3307 $result[]['2012-01-01-1-month'] = [
3308 'data' => [
3309 'start_date' => '2012-01-01',
3310 'frequency_interval' => 1,
3311 'frequency_unit' => 'month',
3312 ],
3313 'receive_date' => '2012-02-29',
3314 'expected' => '2012-03-29 00:00:00',
3315 ];
3316 $result['receive_date_includes_time']['2012-01-01-1-month'] = [
3317 'data' => [
3318 'start_date' => '2012-01-01',
3319 'frequency_interval' => 1,
3320 'frequency_unit' => 'month',
3321 'next_sched_contribution_date' => '2012-02-29',
3322 ],
3323 'receive_date' => '2012-02-29 16:00:00',
3324 'expected' => '2012-03-29 00:00:00',
3325 ];
3326 return $result;
3327 }
3328
3329 /**
3330 * Test completing a pledge with the completeTransaction api..
3331 *
3332 * Note that we are creating a logged in user because email goes out from
3333 * that person.
3334 */
3335 public function testCompleteTransactionUpdatePledgePayment() {
3336 $this->swapMessageTemplateForTestTemplate();
3337 $mut = new CiviMailUtils($this, TRUE);
3338 $mut->clearMessages();
3339 $this->createLoggedInUser();
3340 $contributionID = $this->createPendingPledgeContribution();
3341 $this->callAPISuccess('contribution', 'completetransaction', [
3342 'id' => $contributionID,
3343 'trxn_date' => '1 Feb 2013',
3344 ]);
3345 $pledge = $this->callAPISuccessGetSingle('Pledge', [
3346 'id' => $this->_ids['pledge'],
3347 ]);
3348 $this->assertEquals('Completed', $pledge['pledge_status']);
3349
3350 $status = $this->callAPISuccessGetValue('PledgePayment', [
3351 'pledge_id' => $this->_ids['pledge'],
3352 'return' => 'status_id',
3353 ]);
3354 $this->assertEquals(1, $status);
3355 $mut->checkMailLog([
3356 'amount:::500.00',
3357 // The `receive_date` should remain as it was created.
3358 // TODO: the latest payment transaction date (and maybe other details,
3359 // such as amount and payment instrument) would be a useful token to make
3360 // available.
3361 'receive_date:::20120511000000',
3362 "receipt_date:::\n",
3363 ]);
3364 $mut->stop();
3365 $this->revertTemplateToReservedTemplate();
3366 }
3367
3368 /**
3369 * Test completing a transaction with an event via the API.
3370 *
3371 * Note that we are creating a logged in user because email goes out from
3372 * that person
3373 *
3374 * @throws \CRM_Core_Exception
3375 */
3376 public function testCompleteTransactionWithParticipantRecord(): void {
3377 $mut = new CiviMailUtils($this, TRUE);
3378 $mut->clearMessages();
3379 $this->_individualId = $this->createLoggedInUser();
3380 $this->_params['source'] = 'Online Event Registration: Annual CiviCRM meet';
3381 $contributionID = $this->createPendingParticipantContribution();
3382 $this->createJoinedProfile(['entity_id' => $this->_ids['event']['test'], 'entity_table' => 'civicrm_event']);
3383 $this->createJoinedProfile(['entity_id' => $this->_ids['event']['test'], 'entity_table' => 'civicrm_event', 'weight' => 2], ['name' => 'post_1', 'title' => 'title_post_2', 'frontend_title' => 'public 2']);
3384 $this->createJoinedProfile(['entity_id' => $this->_ids['event']['test'], 'entity_table' => 'civicrm_event', 'weight' => 3], ['name' => 'post_2', 'title' => 'title_post_3', 'frontend_title' => 'public 3']);
3385 $this->eliminateUFGroupOne();
3386
3387 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contributionID]);
3388 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => ['contribution_source']]);
3389 $this->assertEquals('Online Event Registration: Annual CiviCRM meet', $contribution['contribution_source']);
3390 $participantStatus = $this->callAPISuccessGetValue('participant', [
3391 'id' => $this->_ids['participant'],
3392 'return' => 'participant_status_id',
3393 ]);
3394 $this->assertEquals(1, $participantStatus);
3395
3396 //Assert only three activities are created.
3397 $activities = $this->callAPISuccess('Activity', 'get', [
3398 'contact_id' => $this->_individualId,
3399 ])['values'];
3400
3401 $this->assertCount(3, $activities);
3402 $activityNames = array_count_values(CRM_Utils_Array::collect('activity_name', $activities));
3403 // record two activities before and after completing payment for Event registration
3404 $this->assertEquals(2, $activityNames['Event Registration']);
3405 // update the original 'Contribution' activity created after completing payment
3406 $this->assertEquals(1, $activityNames['Contribution']);
3407
3408 $mut->checkMailLog([
3409 'Annual CiviCRM meet',
3410 'Event',
3411 'This is a confirmation that your registration has been received and your status has been updated to Registered.',
3412 'First Name: Logged In',
3413 'Public title',
3414 'public 2',
3415 'public 3',
3416 ], ['Back end title', 'title_post_2', 'title_post_3']);
3417 $mut->stop();
3418 }
3419
3420 /**
3421 * Test membership is renewed when transaction completed.
3422 *
3423 * @throws \API_Exception
3424 */
3425 public function testCompleteTransactionMembershipPriceSet(): void {
3426 $this->createPriceSetWithPage('membership');
3427 $this->createInitialPaidMembership();
3428 $membership = $this->callAPISuccess('Membership', 'getsingle', [
3429 'id' => $this->getMembershipID(),
3430 'status_id' => 'Grace',
3431 'return' => ['end_date'],
3432 ]);
3433 $this->assertEquals(date('Y-m-d', strtotime('yesterday')), $membership['end_date']);
3434
3435 $this->createSubsequentPendingMembership();
3436 $this->callAPISuccess('Payment', 'create', [
3437 'contribution_id' => $this->getContributionID('second'),
3438 'total_amount' => 20,
3439 ]);
3440 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3441 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 2 year')), $membership['end_date']);
3442 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3443 'membership_id' => $this->getMembershipID(),
3444 ]);
3445 $this->assertEquals(4, $logs['count']);
3446 //Assert only three activities are created.
3447 $activityNames = (array) ActivityContact::get(FALSE)
3448 ->addWhere('contact_id', '=', $this->_ids['contact'])
3449 ->addSelect('activity_id.activity_type_id:name')->execute()->indexBy('activity_id.activity_type_id:name');
3450 $this->assertArrayHasKey('Contribution', $activityNames);
3451 $this->assertArrayHasKey('Membership Signup', $activityNames);
3452 $this->assertArrayHasKey('Change Membership Status', $activityNames);
3453 }
3454
3455 /**
3456 * Test if renewal activity is create after changing Pending contribution to
3457 * Completed via offline
3458 *
3459 * @throws \CRM_Core_Exception
3460 * @throws \CRM_Core_Exception
3461 * @throws \CiviCRM_API3_Exception
3462 */
3463 public function testPendingToCompleteContribution(): void {
3464 $this->createPriceSetWithPage('membership');
3465 $this->setUpPendingContribution($this->_ids['price_field_value'][0]);
3466 $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids['membership']]);
3467 // Case 1: Assert that Membership Signup Activity is created on Pending to Completed Contribution via backoffice
3468 $activity = $this->callAPISuccess('Activity', 'get', [
3469 'activity_type_id' => 'Membership Signup',
3470 'source_record_id' => $this->_ids['membership'],
3471 'status_id' => 'Scheduled',
3472 ]);
3473 $this->assertEquals(1, $activity['count']);
3474
3475 // change pending contribution to completed
3476 $form = new CRM_Contribute_Form_Contribution();
3477
3478 $form->_params = [
3479 'id' => $this->getContributionID(),
3480 'total_amount' => 20,
3481 'net_amount' => 20,
3482 'fee_amount' => 0,
3483 'financial_type_id' => 1,
3484 'contact_id' => $this->_individualId,
3485 'contribution_status_id' => 1,
3486 'billing_middle_name' => '',
3487 'billing_last_name' => 'Adams',
3488 'billing_street_address-5' => '790L Lincoln St S',
3489 'billing_city-5' => 'Mary knoll',
3490 'billing_state_province_id-5' => 1031,
3491 'billing_postal_code-5' => 10545,
3492 'billing_country_id-5' => 1228,
3493 'frequency_interval' => 1,
3494 'frequency_unit' => 'month',
3495 'installments' => '',
3496 'hidden_AdditionalDetail' => 1,
3497 'hidden_Premium' => 1,
3498 'from_email_address' => '"civi45" <civi45@civicrm.com>',
3499 'receipt_date' => '',
3500 'receipt_date_time' => '',
3501 'payment_processor_id' => $this->paymentProcessorID,
3502 'currency' => 'USD',
3503 'contribution_page_id' => $this->_ids['contribution_page'],
3504 'source' => 'Membership Signup and Renewal',
3505 ];
3506
3507 $form->testSubmit($form->_params, CRM_Core_Action::UPDATE);
3508
3509 // Case 2: After successful payment for Pending backoffice there are three activities created
3510 // 2.a Update status of existing Scheduled Membership Signup (created in step 1) to Completed
3511 $activity = $this->callAPISuccess('Activity', 'get', [
3512 'activity_type_id' => 'Membership Signup',
3513 'source_record_id' => $this->getMembershipID(),
3514 'status_id' => 'Completed',
3515 ]);
3516 $this->assertEquals(1, $activity['count']);
3517 // 2.b Contribution activity created to record successful payment
3518 $activity = $this->callAPISuccess('Activity', 'get', [
3519 'activity_type_id' => 'Contribution',
3520 'source_record_id' => $this->getContributionID(),
3521 'status_id' => 'Completed',
3522 ]);
3523 $this->assertEquals(1, $activity['count']);
3524
3525 // 2.c 'Change membership type' activity created to record Membership status change from Grace to Current
3526 $activity = $this->callAPISuccess('Activity', 'get', [
3527 'activity_type_id' => 'Change Membership Status',
3528 'source_record_id' => $this->getMembershipID(),
3529 'status_id' => 'Completed',
3530 ]);
3531 $this->assertEquals(1, $activity['count']);
3532 $this->assertEquals('Status changed from Pending to New', $activity['values'][$activity['id']]['subject']);
3533 $membershipLogs = $this->callAPISuccess('MembershipLog', 'get', ['sequential' => 1])['values'];
3534 $this->assertEquals('Pending', CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipLogs[0]['status_id']));
3535 $this->assertEquals('New', CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipLogs[1]['status_id']));
3536 //Create another pending contribution for renewal
3537 $this->setUpPendingContribution($this->_ids['price_field_value'][0], 'second', [], ['entity_id' => $this->getMembershipID()], ['id' => $this->getMembershipID()]);
3538
3539 //Update it to Failed.
3540 $form->_params['id'] = $this->getContributionID('second');
3541 $form->_params['contribution_status_id'] = 4;
3542
3543 $form->testSubmit($form->_params, CRM_Core_Action::UPDATE);
3544 //Existing membership should not get updated to expired.
3545 $membership = $this->callAPISuccess('Membership', 'getsingle', ['id' => $this->_ids['membership']]);
3546 $this->assertNotEquals(4, $membership['status_id']);
3547 }
3548
3549 /**
3550 * Test membership is renewed for 2 terms when transaction completed based on the line item having 2 terms as qty.
3551 *
3552 * Also check that altering the qty for the most recent contribution results in repeattransaction picking it up.
3553 */
3554 public function testCompleteTransactionMembershipPriceSetTwoTerms(): void {
3555 $this->createPriceSetWithPage('membership');
3556 $this->createInitialPaidMembership();
3557 $this->createSubsequentPendingMembership();
3558
3559 $this->callAPISuccess('Payment', 'create', [
3560 'contribution_id' => $this->getContributionID('second'),
3561 'total_amount' => 20,
3562 ]);
3563
3564 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->getMembershipID()]);
3565 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 2 years')), $membership['end_date']);
3566
3567 $paymentProcessorID = $this->paymentProcessorAuthorizeNetCreate();
3568
3569 $contributionRecurID = $this->callAPISuccess('ContributionRecur', 'create', ['contact_id' => $membership['contact_id'], 'payment_processor_id' => $paymentProcessorID, 'amount' => 20, 'frequency_interval' => 1])['id'];
3570 $this->callAPISuccess('Contribution', 'create', ['id' => $this->getContributionID(), 'contribution_recur_id' => $contributionRecurID]);
3571 $this->callAPISuccess('contribution', 'repeattransaction', ['contribution_recur_id' => $contributionRecurID, 'contribution_status_id' => 'Completed']);
3572 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->getMembershipID()]);
3573 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 4 years')), $membership['end_date']);
3574
3575 // Update the most recent contribution to have a qty of 1 in it's line item and then repeat, expecting just 1 year to be added.
3576 $contribution = Contribution::get()->setOrderBy(['id' => 'DESC'])->setSelect(['id'])->execute()->first();
3577 CRM_Core_DAO::executeQuery('UPDATE civicrm_line_item SET price_field_value_id = ' . $this->_ids['price_field_value'][0] . ' WHERE contribution_id = ' . $contribution['id']);
3578 $this->callAPISuccess('contribution', 'repeattransaction', ['contribution_recur_id' => $contributionRecurID, 'contribution_status_id' => 'Completed']);
3579 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->_ids['membership']]);
3580 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 5 years')), $membership['end_date']);
3581 }
3582
3583 public function cleanUpAfterPriceSets() {
3584 $this->quickCleanUpFinancialEntities();
3585 $this->contactDelete($this->_ids['contact']);
3586 }
3587
3588 /**
3589 * Set up a pending transaction with a specific price field id.
3590 *
3591 * @param int $priceFieldValueID
3592 * @param string $key
3593 * @param array $contributionParams
3594 * @param array $lineParams
3595 * @param array $membershipParams
3596 */
3597 public function setUpPendingContribution(int $priceFieldValueID, string $key = 'first', array $contributionParams = [], array $lineParams = [], array $membershipParams = []): void {
3598 $contactID = $this->individualCreate();
3599 $membershipParams = array_merge([
3600 'contact_id' => $contactID,
3601 'membership_type_id' => $this->_ids['membership_type'],
3602 ], $membershipParams);
3603 if ($key === 'first') {
3604 // If we want these after the initial we will set them.
3605 $membershipParams['start_date'] = 'yesterday - 1 year';
3606 $membershipParams['end_date'] = 'yesterday';
3607 $membershipParams['join_date'] = 'yesterday - 1 year';
3608 }
3609 $contribution = $this->callAPISuccess('Order', 'create', array_merge([
3610 'domain_id' => 1,
3611 'contact_id' => $contactID,
3612 'receive_date' => date('Ymd'),
3613 'total_amount' => 20.00,
3614 'financial_type_id' => 1,
3615 'payment_instrument_id' => 'Credit Card',
3616 'non_deductible_amount' => 10.00,
3617 'source' => 'SSF',
3618 'contribution_page_id' => $this->_ids['contribution_page'],
3619 'line_items' => [
3620 [
3621 'line_item' => [
3622 array_merge([
3623 'price_field_id' => $this->_ids['price_field'][0],
3624 'qty' => 1,
3625 'entity_table' => 'civicrm_membership',
3626 'unit_price' => 20,
3627 'line_total' => 20,
3628 'financial_type_id' => 1,
3629 'price_field_value_id' => $priceFieldValueID,
3630 ], $lineParams),
3631 ],
3632 'params' => $membershipParams,
3633 ],
3634 ],
3635 ], $contributionParams));
3636
3637 $this->_ids['contact'] = $contactID;
3638 $this->ids['contribution'][$key] = $contribution['id'];
3639 $this->_ids['membership'] = $this->callAPISuccessGetValue('MembershipPayment', ['return' => 'membership_id', 'contribution_id' => $contribution['id']]);
3640 }
3641
3642 /**
3643 * Test sending a mail via the API.
3644 *
3645 * @throws \CRM_Core_Exception
3646 */
3647 public function testSendMail(): void {
3648 $mut = new CiviMailUtils($this, TRUE);
3649 $orderParams = $this->_params;
3650 $orderParams['contribution_status_id'] = 'Pending';
3651 $orderParams['api.PaymentProcessor.pay'] = [
3652 'payment_processor_id' => $this->paymentProcessorID,
3653 'credit_card_type' => 'Visa',
3654 'credit_card_number' => 41111111111111,
3655 'amount' => 5,
3656 ];
3657
3658 $order = $this->callAPISuccess('Order', 'create', $orderParams);
3659 $this->callAPISuccess('Payment', 'create', ['total_amount' => 5, 'is_send_notification' => 0, 'order_id' => $order['id']]);
3660 $address = $this->callAPISuccess('Address', 'create', ['contribution_id' => $order['id'], 'name' => 'bob', 'contact_id' => 1, 'street_address' => 'blah']);
3661 $this->callAPISuccess('Contribution', 'create', ['id' => $order['id'], 'address_id' => $address['id']]);
3662 $this->callAPISuccess('contribution', 'sendconfirmation', [
3663 'id' => $order['id'],
3664 'receipt_from_email' => 'api@civicrm.org',
3665 ]);
3666 $mut->checkMailLog([
3667 '$ 100.00',
3668 'Contribution Information',
3669 ], [
3670 'Event',
3671 ]);
3672
3673 $this->checkCreditCardDetails($mut, $order['id']);
3674 $mut->stop();
3675 $tplVars = CRM_Core_Smarty::singleton()->get_template_vars();
3676 $this->assertEquals('bob', $tplVars['billingName']);
3677 }
3678
3679 /**
3680 * Test sending a mail via the API.
3681 * This simulates webform_civicrm using pay later contribution page
3682 *
3683 * @throws \CRM_Core_Exception
3684 * @throws \CiviCRM_API3_Exception
3685 */
3686 public function testSendConfirmationPayLater(): void {
3687 $mut = new CiviMailUtils($this, TRUE);
3688 // Create contribution page
3689 $pageParams = [
3690 'title' => 'Webform Contributions',
3691 'financial_type_id' => 1,
3692 'contribution_type_id' => 1,
3693 'is_confirm_enabled' => 1,
3694 'is_pay_later' => 1,
3695 'pay_later_text' => 'I will send payment by cheque',
3696 'pay_later_receipt' => 'Send your cheque payable to "CiviCRM LLC" to the office',
3697 ];
3698 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', $pageParams);
3699
3700 // Create pay later contribution
3701 $contribution = $this->callAPISuccess('Order', 'create', [
3702 'contact_id' => $this->_individualId,
3703 'financial_type_id' => 1,
3704 'is_pay_later' => 1,
3705 'contribution_status_id' => 2,
3706 'contribution_page_id' => $contributionPage['id'],
3707 'total_amount' => '10.00',
3708 'line_items' => [
3709 [
3710 'line_item' => [
3711 [
3712 'entity_table' => 'civicrm_contribution',
3713 'label' => 'My lineitem label',
3714 'qty' => 1,
3715 'unit_price' => '10.00',
3716 'line_total' => '10.00',
3717 ],
3718 ],
3719 ],
3720 ],
3721 ]);
3722
3723 // Create email
3724 try {
3725 civicrm_api3('contribution', 'sendconfirmation', [
3726 'id' => $contribution['id'],
3727 'receipt_from_email' => 'api@civicrm.org',
3728 ]);
3729 }
3730 catch (Exception $e) {
3731 // Need to figure out how to stop this some other day
3732 // We don't care about the Payment Processor because this is Pay Later
3733 // The point of this test is to check we get the pay_later version of the mail
3734 if ($e->getMessage() !== "Undefined variable: CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage") {
3735 throw $e;
3736 }
3737 }
3738
3739 // Retrieve mail & check it has the pay_later_receipt info
3740 $mut->getMostRecentEmail('raw');
3741 $mut->checkMailLog([
3742 (string) 10,
3743 $pageParams['pay_later_receipt'],
3744 ], [
3745 'Event',
3746 ]);
3747 $this->checkReceiptDetails($mut, $contributionPage['id'], $contribution['id'], $pageParams);
3748 $mut->stop();
3749 }
3750
3751 /**
3752 * Check credit card details in sent mail via API
3753 *
3754 * @param CiviMailUtils $mut
3755 * @param int $contributionID Contribution ID
3756 *
3757 * @throws \CRM_Core_Exception
3758 */
3759 public function checkCreditCardDetails($mut, $contributionID) {
3760 $this->callAPISuccess('contribution', 'create', $this->_params);
3761 $this->callAPISuccess('contribution', 'sendconfirmation', [
3762 'id' => $contributionID,
3763 'receipt_from_email' => 'api@civicrm.org',
3764 'payment_processor_id' => $this->paymentProcessorID,
3765 ]);
3766 $mut->checkMailLog([
3767 // billing header
3768 'Billing Name and Address',
3769 // billing name
3770 'anthony_anderson@civicrm.org',
3771 ], [
3772 'Event',
3773 ]);
3774 }
3775
3776 /**
3777 * Check receipt details in sent mail via API
3778 *
3779 * @param CiviMailUtils $mut
3780 * @param int $pageID Page ID
3781 * @param int $contributionID Contribution ID
3782 * @param array $pageParams
3783 *
3784 * @throws \CRM_Core_Exception
3785 */
3786 public function checkReceiptDetails($mut, $pageID, $contributionID, $pageParams): void {
3787 $pageReceipt = [
3788 'receipt_from_name' => 'Page FromName',
3789 'receipt_from_email' => 'page_from@email.com',
3790 'cc_receipt' => 'page_cc@email.com',
3791 'receipt_text' => 'Page Receipt Text',
3792 'pay_later_receipt' => $pageParams['pay_later_receipt'],
3793 ];
3794 $customReceipt = [
3795 'receipt_from_name' => 'Custom FromName',
3796 'receipt_from_email' => 'custom_from@email.com',
3797 'cc_receipt' => 'custom_cc@email.com',
3798 'receipt_text' => 'Test Custom Receipt Text',
3799 'pay_later_receipt' => 'Mail your check to test@example.com within 3 business days.',
3800 ];
3801 $this->callAPISuccess('ContributionPage', 'create', array_merge([
3802 'id' => $pageID,
3803 'is_email_receipt' => 1,
3804 ], $pageReceipt));
3805
3806 $this->callAPISuccess('contribution', 'sendconfirmation', array_merge([
3807 'id' => $contributionID,
3808 'payment_processor_id' => $this->paymentProcessorID,
3809 ], $customReceipt));
3810
3811 //Verify if custom receipt details are present in email.
3812 //Page receipt details shouldn't be included.
3813 $mut->checkMailLog(array_values($customReceipt), array_values($pageReceipt));
3814 }
3815
3816 /**
3817 * Test sending a mail via the API.
3818 */
3819 public function testSendMailEvent() {
3820 $mut = new CiviMailUtils($this, TRUE);
3821 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
3822 $event = $this->eventCreate([
3823 'is_email_confirm' => 1,
3824 'confirm_from_email' => 'test@civicrm.org',
3825 ]);
3826 $this->_eventID = $event['id'];
3827 $participantParams = [
3828 'contact_id' => $this->_individualId,
3829 'event_id' => $this->_eventID,
3830 'status_id' => 1,
3831 'role_id' => 1,
3832 // to ensure it matches later on
3833 'register_date' => '2007-07-21 00:00:00',
3834 'source' => 'Online Event Registration: API Testing',
3835
3836 ];
3837 $participant = $this->callAPISuccess('participant', 'create', $participantParams);
3838 $this->callAPISuccess('participant_payment', 'create', [
3839 'participant_id' => $participant['id'],
3840 'contribution_id' => $contribution['id'],
3841 ]);
3842 $this->callAPISuccess('contribution', 'sendconfirmation', [
3843 'id' => $contribution['id'],
3844 'receipt_from_email' => 'api@civicrm.org',
3845 ]);
3846
3847 $mut->checkMailLog([
3848 'Annual CiviCRM meet',
3849 'Event',
3850 'To: "Mr. Anthony Anderson II" <anthony_anderson@civicrm.org>',
3851 ], []);
3852 $mut->stop();
3853 }
3854
3855 /**
3856 * This function does a GET & compares the result against the $params.
3857 *
3858 * Use as a double check on Creates.
3859 *
3860 * @param array $params
3861 * @param int $id
3862 * @param bool $delete
3863 *
3864 * @throws \CRM_Core_Exception
3865 */
3866 public function contributionGetnCheck(array $params, int $id, bool $delete = TRUE): void {
3867 $contribution = $this->callAPISuccess('Contribution', 'Get', [
3868 'id' => $id,
3869 'return' => array_merge(['contribution_source'], array_keys($params)),
3870 ]);
3871 if ($delete) {
3872 $this->callAPISuccess('contribution', 'delete', ['id' => $id]);
3873 }
3874 $this->assertAPISuccess($contribution, 0);
3875 $values = $contribution['values'][$contribution['id']];
3876 $params['receive_date'] = date('Y-m-d H:i:s', strtotime($params['receive_date']));
3877 // this is not returned in id format
3878 unset($params['payment_instrument_id']);
3879 $params['contribution_source'] = $params['source'];
3880 unset($params['source'], $params['sequential']);
3881 foreach ($params as $key => $value) {
3882 $this->assertEquals($value, $values[$key], $key . " value: $value doesn't match " . print_r($values, TRUE));
3883 }
3884 }
3885
3886 /**
3887 * Create a pending contribution & linked pending pledge record.
3888 *
3889 * @throws \CRM_Core_Exception
3890 */
3891 public function createPendingPledgeContribution() {
3892
3893 $pledgeID = $this->pledgeCreate(['contact_id' => $this->_individualId, 'installments' => 1, 'amount' => 500]);
3894 $this->_ids['pledge'] = $pledgeID;
3895 $contribution = $this->callAPISuccess('Contribution', 'create', array_merge($this->_params, [
3896 'contribution_status_id' => 'Pending',
3897 'total_amount' => 500,
3898 ]));
3899 $paymentID = $this->callAPISuccessGetValue('PledgePayment', [
3900 'options' => ['limit' => 1],
3901 'return' => 'id',
3902 ]);
3903 $this->callAPISuccess('PledgePayment', 'create', [
3904 'id' => $paymentID,
3905 'contribution_id' =>
3906 $contribution['id'],
3907 'status_id' => 'Pending',
3908 'scheduled_amount' => 500,
3909 ]);
3910
3911 return $contribution['id'];
3912 }
3913
3914 /**
3915 * Create a pending contribution & linked pending participant record (along
3916 * with an event).
3917 *
3918 * @throws \CRM_Core_Exception
3919 */
3920 public function createPendingParticipantContribution() {
3921 $this->_ids['event']['test'] = $this->eventCreate(['is_email_confirm' => 1, 'confirm_from_email' => 'test@civicrm.org'])['id'];
3922 $participantID = $this->participantCreate(['event_id' => $this->_ids['event']['test'], 'status_id' => 6, 'contact_id' => $this->_individualId]);
3923 $this->_ids['participant'] = $participantID;
3924 $params = array_merge($this->_params, ['contact_id' => $this->_individualId, 'contribution_status_id' => 2, 'financial_type_id' => 'Event Fee']);
3925 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3926 $this->callAPISuccess('participant_payment', 'create', [
3927 'contribution_id' => $contribution['id'],
3928 'participant_id' => $participantID,
3929 ]);
3930 $this->callAPISuccess('line_item', 'get', [
3931 'entity_id' => $contribution['id'],
3932 'entity_table' => 'civicrm_contribution',
3933 'api.line_item.create' => [
3934 'entity_id' => $participantID,
3935 'entity_table' => 'civicrm_participant',
3936 ],
3937 ]);
3938 return $contribution['id'];
3939 }
3940
3941 /**
3942 * Get financial transaction amount.
3943 *
3944 * @param int $contId
3945 *
3946 * @return null|string
3947 */
3948 public function _getFinancialTrxnAmount($contId) {
3949 $query = "SELECT
3950 SUM( ft.total_amount ) AS total
3951 FROM civicrm_financial_trxn AS ft
3952 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.id = ceft.financial_trxn_id
3953 WHERE ceft.entity_table = 'civicrm_contribution'
3954 AND ceft.entity_id = {$contId}";
3955
3956 return CRM_Core_DAO::singleValueQuery($query);
3957 }
3958
3959 /**
3960 * @param int $contId
3961 *
3962 * @return null|string
3963 */
3964 public function _getFinancialItemAmount($contId) {
3965 $lineItem = key(CRM_Price_BAO_LineItem::getLineItems($contId, 'contribution'));
3966 $query = "SELECT
3967 SUM(amount)
3968 FROM civicrm_financial_item
3969 WHERE entity_table = 'civicrm_line_item'
3970 AND entity_id = {$lineItem}";
3971 return CRM_Core_DAO::singleValueQuery($query);
3972 }
3973
3974 /**
3975 * @param int $contId
3976 * @param $context
3977 */
3978 public function _checkFinancialItem($contId, $context) {
3979 if ($context !== 'paylater') {
3980 $params = [
3981 'entity_id' => $contId,
3982 'entity_table' => 'civicrm_contribution',
3983 ];
3984 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($params, TRUE));
3985 $entityParams = [
3986 'financial_trxn_id' => $trxn['financial_trxn_id'],
3987 'entity_table' => 'civicrm_financial_item',
3988 ];
3989 $entityTrxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
3990 $params = [
3991 'id' => $entityTrxn['entity_id'],
3992 ];
3993 }
3994 if ($context === 'paylater') {
3995 $lineItems = CRM_Price_BAO_LineItem::getLineItems($contId, 'contribution');
3996 foreach ($lineItems as $key => $item) {
3997 $params = [
3998 'entity_id' => $key,
3999 'entity_table' => 'civicrm_line_item',
4000 ];
4001 $compareParams = ['status_id' => 1];
4002 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4003 }
4004 }
4005 elseif ($context === 'refund') {
4006 $compareParams = [
4007 'status_id' => 1,
4008 'financial_account_id' => 1,
4009 'amount' => -100,
4010 ];
4011 }
4012 elseif ($context === 'cancelPending') {
4013 $compareParams = [
4014 'status_id' => 3,
4015 'financial_account_id' => 1,
4016 'amount' => -100,
4017 ];
4018 }
4019 elseif ($context === 'changeFinancial') {
4020 $lineKey = key(CRM_Price_BAO_LineItem::getLineItems($contId, 'contribution'));
4021 $params = [
4022 'entity_id' => $lineKey,
4023 'amount' => -100,
4024 ];
4025 $compareParams = [
4026 'financial_account_id' => 1,
4027 ];
4028 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4029 $params = [
4030 'financial_account_id' => 3,
4031 'entity_id' => $lineKey,
4032 ];
4033 $compareParams = [
4034 'amount' => 100,
4035 ];
4036 }
4037 if ($context !== 'paylater') {
4038 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4039 }
4040 }
4041
4042 /**
4043 * Check correct financial transaction entries were created for the change in payment instrument.
4044 *
4045 * @param int $contributionID
4046 * @param int $originalInstrumentID
4047 * @param int $newInstrumentID
4048 * @param int $amount
4049 */
4050 public function checkFinancialTrxnPaymentInstrumentChange($contributionID, $originalInstrumentID, $newInstrumentID, $amount = 100) {
4051
4052 $entityFinancialTrxns = $this->getFinancialTransactionsForContribution($contributionID);
4053
4054 $originalTrxnParams = [
4055 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($originalInstrumentID),
4056 'payment_instrument_id' => $originalInstrumentID,
4057 'amount' => $amount,
4058 'status_id' => 1,
4059 ];
4060
4061 $reversalTrxnParams = [
4062 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($originalInstrumentID),
4063 'payment_instrument_id' => $originalInstrumentID,
4064 'amount' => -$amount,
4065 'status_id' => 1,
4066 ];
4067
4068 $newTrxnParams = [
4069 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($newInstrumentID),
4070 'payment_instrument_id' => $newInstrumentID,
4071 'amount' => $amount,
4072 'status_id' => 1,
4073 ];
4074
4075 foreach ([$originalTrxnParams, $reversalTrxnParams, $newTrxnParams] as $index => $transaction) {
4076 $entityFinancialTrxn = $entityFinancialTrxns[$index];
4077 $this->assertEquals($entityFinancialTrxn['amount'], $transaction['amount']);
4078
4079 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', [
4080 'id' => $entityFinancialTrxn['financial_trxn_id'],
4081 ]);
4082 $this->assertEquals($transaction['status_id'], $financialTrxn['status_id']);
4083 $this->assertEquals($transaction['amount'], $financialTrxn['total_amount']);
4084 $this->assertEquals($transaction['amount'], $financialTrxn['net_amount']);
4085 $this->assertEquals(0, $financialTrxn['fee_amount']);
4086 $this->assertEquals($transaction['payment_instrument_id'], $financialTrxn['payment_instrument_id']);
4087 $this->assertEquals($transaction['to_financial_account_id'], $financialTrxn['to_financial_account_id']);
4088
4089 // Generic checks.
4090 $this->assertEquals(1, $financialTrxn['is_payment']);
4091 $this->assertEquals('USD', $financialTrxn['currency']);
4092 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($financialTrxn['trxn_date'])));
4093 }
4094 }
4095
4096 /**
4097 * Check financial transaction.
4098 *
4099 * @todo break this down into sensible functions - most calls to it only use a few lines out of the big if.
4100 *
4101 * @param array $contribution
4102 * @param string $context
4103 * @param int $instrumentId
4104 * @param array $extraParams
4105 */
4106 public function _checkFinancialTrxn($contribution, $context, $instrumentId = NULL, $extraParams = []) {
4107 $financialTrxns = $this->getFinancialTransactionsForContribution($contribution['id']);
4108 $trxn = array_pop($financialTrxns);
4109
4110 $params = [
4111 'id' => $trxn['financial_trxn_id'],
4112 ];
4113 if ($context === 'payLater') {
4114 $compareParams = [
4115 'status_id' => 1,
4116 'from_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is'),
4117 ];
4118 }
4119 elseif ($context === 'refund') {
4120 $compareParams = [
4121 'to_financial_account_id' => 6,
4122 'total_amount' => -100,
4123 'status_id' => 7,
4124 'trxn_date' => '2015-01-01 09:00:00',
4125 'trxn_id' => 'the refund',
4126 ];
4127 }
4128 elseif ($context === 'cancelPending') {
4129 $compareParams = [
4130 'to_financial_account_id' => 7,
4131 'total_amount' => -100,
4132 'status_id' => 3,
4133 ];
4134 }
4135 elseif ($context === 'changeFinancial' || $context === 'paymentInstrument') {
4136 // @todo checkFinancialTrxnPaymentInstrumentChange instead for paymentInstrument.
4137 // It does the same thing with greater readability.
4138 // @todo remove handling for
4139
4140 $entityParams = [
4141 'entity_id' => $contribution['id'],
4142 'entity_table' => 'civicrm_contribution',
4143 'amount' => -100,
4144 ];
4145 $trxn = current(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($entityParams));
4146 $trxnParams1 = [
4147 'id' => $trxn['financial_trxn_id'],
4148 ];
4149 if (empty($extraParams)) {
4150 $compareParams = [
4151 'total_amount' => -100,
4152 'status_id' => 1,
4153 ];
4154 }
4155 elseif ($context !== 'changeFinancial') {
4156 $compareParams = [
4157 'total_amount' => 100,
4158 'status_id' => 1,
4159 ];
4160 }
4161 if ($context === 'paymentInstrument') {
4162 $compareParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($instrumentId);
4163 $compareParams['payment_instrument_id'] = $instrumentId;
4164 }
4165 else {
4166 $compareParams['to_financial_account_id'] = 12;
4167 }
4168 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams1, array_merge($compareParams, $extraParams));
4169 $compareParams['total_amount'] = 100;
4170 // Reverse the extra params now that we will be checking the new positive transaction.
4171 if ($context === 'changeFinancial' && !empty($extraParams)) {
4172 foreach ($extraParams as $param => $value) {
4173 $extraParams[$param] = 0 - $value;
4174 }
4175 }
4176 }
4177
4178 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $params, array_merge($compareParams, $extraParams));
4179 }
4180
4181 /**
4182 * @return mixed
4183 */
4184 public function _addPaymentInstrument() {
4185 $gId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'payment_instrument', 'id', 'name');
4186 $optionParams = [
4187 'option_group_id' => $gId,
4188 'label' => 'Test Card',
4189 'name' => 'Test Card',
4190 'value' => '6',
4191 'weight' => '6',
4192 'is_active' => 1,
4193 ];
4194 $optionValue = $this->callAPISuccess('option_value', 'create', $optionParams);
4195 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
4196 $financialParams = [
4197 'entity_table' => 'civicrm_option_value',
4198 'entity_id' => $optionValue['id'],
4199 'account_relationship' => $relationTypeId,
4200 'financial_account_id' => 7,
4201 ];
4202 CRM_Financial_BAO_FinancialTypeAccount::add($financialParams);
4203 $this->assertNotEmpty($optionValue['values'][$optionValue['id']]['value']);
4204 return $optionValue['values'][$optionValue['id']]['value'];
4205 }
4206
4207 public function _deletedAddedPaymentInstrument() {
4208 $result = $this->callAPISuccess('OptionValue', 'get', [
4209 'option_group_id' => 'payment_instrument',
4210 'name' => 'Test Card',
4211 'value' => '6',
4212 'is_active' => 1,
4213 ]);
4214 if ($id = CRM_Utils_Array::value('id', $result)) {
4215 $this->callAPISuccess('OptionValue', 'delete', ['id' => $id]);
4216 }
4217 }
4218
4219 /**
4220 * Set up the basic recurring contribution for tests.
4221 *
4222 * @param array $generalParams
4223 * Parameters that can be merged into the recurring AND the contribution.
4224 *
4225 * @param array $recurParams
4226 * Parameters to merge into the recur only.
4227 *
4228 * @return array|int
4229 * @throws \CRM_Core_Exception
4230 */
4231 protected function setUpRecurringContribution($generalParams = [], $recurParams = []) {
4232 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4233 'contact_id' => $this->_individualId,
4234 'installments' => '12',
4235 'frequency_interval' => '1',
4236 'amount' => '100',
4237 'contribution_status_id' => 1,
4238 'start_date' => '2012-01-01 00:00:00',
4239 'currency' => 'USD',
4240 'frequency_unit' => 'month',
4241 'payment_processor_id' => $this->paymentProcessorID,
4242 ], $generalParams, $recurParams));
4243 $contributionParams = array_merge(
4244 $this->_params,
4245 [
4246 'contribution_recur_id' => $contributionRecur['id'],
4247 'contribution_status_id' => 'Pending',
4248 ], $generalParams);
4249 $contributionParams['api.Payment.create'] = ['total_amount' => $contributionParams['total_amount']];
4250 $originalContribution = $this->callAPISuccess('Order', 'create', $contributionParams);
4251 return $originalContribution;
4252 }
4253
4254 /**
4255 * Set up a basic auto-renew membership for tests.
4256 *
4257 * @param array $generalParams
4258 * Parameters that can be merged into the recurring AND the contribution.
4259 *
4260 * @param array $recurParams
4261 * Parameters to merge into the recur only.
4262 *
4263 * @return array|int
4264 * @throws \CRM_Core_Exception
4265 */
4266 protected function setUpAutoRenewMembership($generalParams = [], $recurParams = []) {
4267 $newContact = $this->callAPISuccess('Contact', 'create', [
4268 'contact_type' => 'Individual',
4269 'sort_name' => 'McTesterson, Testy',
4270 'display_name' => 'Testy McTesterson',
4271 'preferred_language' => 'en_US',
4272 'preferred_mail_format' => 'Both',
4273 'first_name' => 'Testy',
4274 'last_name' => 'McTesterson',
4275 'contact_is_deleted' => '0',
4276 'email_id' => '4',
4277 'email' => 'tmctesterson@example.com',
4278 'on_hold' => '0',
4279 ]);
4280 $membershipType = $this->callAPISuccess('MembershipType', 'create', [
4281 'domain_id' => 'Default Domain Name',
4282 'member_of_contact_id' => 1,
4283 'financial_type_id' => 'Member Dues',
4284 'duration_unit' => 'month',
4285 'duration_interval' => 1,
4286 'period_type' => 'rolling',
4287 'name' => 'Standard Member',
4288 'minimum_fee' => 100,
4289 ]);
4290 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4291 'contact_id' => $newContact['id'],
4292 'installments' => '12',
4293 'frequency_interval' => '1',
4294 'amount' => '100',
4295 'contribution_status_id' => 1,
4296 'start_date' => '2012-01-01 00:00:00',
4297 'currency' => 'USD',
4298 'frequency_unit' => 'month',
4299 'payment_processor_id' => $this->paymentProcessorID,
4300 ], $generalParams, $recurParams));
4301
4302 $originalContribution = $this->callAPISuccess('Order', 'create', array_merge(
4303 $this->_params,
4304 [
4305 'contact_id' => $newContact['id'],
4306 'contribution_recur_id' => $contributionRecur['id'],
4307 'financial_type_id' => 'Member Dues',
4308 'api.Payment.create' => ['total_amount' => 100, 'payment_instrument_id' => 'Credit card'],
4309 'invoice_id' => 2345,
4310 'line_items' => [
4311 [
4312 'line_item' => [
4313 [
4314 'membership_type_id' => $membershipType['id'],
4315 'financial_type_id' => 'Member Dues',
4316 'line_total' => $generalParams['total_amount'] ?? 100,
4317 ],
4318 ],
4319 'params' => [
4320 'contact_id' => $newContact['id'],
4321 'contribution_recur_id' => $contributionRecur['id'],
4322 'membership_type_id' => $membershipType['id'],
4323 'num_terms' => 1,
4324 ],
4325 ],
4326 ],
4327 ], $generalParams)
4328 );
4329 $lineItem = $this->callAPISuccess('LineItem', 'getsingle', []);
4330 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
4331 $membership = $this->callAPISuccess('Membership', 'getsingle', ['id' => $lineItem['entity_id']]);
4332 $this->callAPISuccess('LineItem', 'getsingle', []);
4333 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']], 1);
4334
4335 return [$originalContribution, $membership];
4336 }
4337
4338 /**
4339 * Set up a repeat transaction.
4340 *
4341 * @param array $recurParams
4342 * @param string $flag
4343 * @param array $contributionParams
4344 *
4345 * @return array
4346 */
4347 protected function setUpRepeatTransaction(array $recurParams, $flag, array $contributionParams = []) {
4348 $paymentProcessorID = $this->paymentProcessorCreate();
4349 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4350 'contact_id' => $this->_individualId,
4351 'installments' => '12',
4352 'frequency_interval' => '1',
4353 'amount' => '500',
4354 'contribution_status_id' => 1,
4355 'start_date' => '2012-01-01 00:00:00',
4356 'currency' => 'USD',
4357 'frequency_unit' => 'month',
4358 'payment_processor_id' => $paymentProcessorID,
4359 ], $recurParams));
4360
4361 $originalContribution = '';
4362 if ($flag === 'multiple') {
4363 // CRM-19309 create a contribution + also add in line_items (plural):
4364 $this->createContributionWithTwoLineItemsAgainstPriceSet([
4365 'contact_id' => $this->_individualId,
4366 'contribution_recur_id' => $contributionRecur['id'],
4367 ]);
4368 $originalContribution = $this->callAPISuccessGetSingle('Contribution', ['contribution_recur_id' => $contributionRecur['id'], 'return' => 'id']);
4369 }
4370 elseif ($flag === 'single') {
4371 $params = array_merge($this->_params, ['contribution_recur_id' => $contributionRecur['id']]);
4372 $params = array_merge($params, $contributionParams);
4373 $originalContribution = $this->callAPISuccess('Order', 'create', $params);
4374 // Note the saved contribution amount will include tax.
4375 $this->callAPISuccess('Payment', 'create', [
4376 'contribution_id' => $originalContribution['id'],
4377 'total_amount' => $originalContribution['values'][$originalContribution['id']]['total_amount'],
4378 ]);
4379 }
4380 $originalContribution['contribution_recur_id'] = $contributionRecur['id'];
4381 $originalContribution['payment_processor_id'] = $paymentProcessorID;
4382 return $originalContribution;
4383 }
4384
4385 /**
4386 * Common set up routine.
4387 *
4388 * @return array
4389 * @throws \CRM_Core_Exception
4390 */
4391 protected function setUpForCompleteTransaction(): array {
4392 $this->mut = new CiviMailUtils($this, TRUE);
4393 $this->createLoggedInUser();
4394 $params = array_merge($this->_params, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
4395 return $this->callAPISuccess('Contribution', 'create', $params);
4396 }
4397
4398 /**
4399 * Test repeat contribution uses the Payment Processor' payment_instrument setting.
4400 *
4401 * @throws \CRM_Core_Exception
4402 */
4403 public function testRepeatTransactionWithNonCreditCardDefault() {
4404 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
4405 'contact_id' => $this->_individualId,
4406 'installments' => '12',
4407 'frequency_interval' => '1',
4408 'amount' => '100',
4409 'contribution_status_id' => 1,
4410 'start_date' => '2012-01-01 00:00:00',
4411 'currency' => 'USD',
4412 'frequency_unit' => 'month',
4413 'payment_processor_id' => $this->paymentProcessorID,
4414 ]);
4415 $contribution1 = $this->callAPISuccess('contribution', 'create', array_merge(
4416 $this->_params,
4417 ['contribution_recur_id' => $contributionRecur['id'], 'payment_instrument_id' => 2])
4418 );
4419 $contribution2 = $this->callAPISuccess('contribution', 'repeattransaction', [
4420 'contribution_status_id' => 'Completed',
4421 'trxn_id' => 'blah',
4422 'original_contribution_id' => $contribution1,
4423 ]);
4424 $this->assertEquals('Debit Card', CRM_Contribute_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $contribution2['values'][$contribution2['id']]['payment_instrument_id']));
4425 }
4426
4427 /**
4428 * CRM-20008 Tests repeattransaction creates pending membership.
4429 *
4430 * @throws \CRM_Core_Exception
4431 */
4432 public function testRepeatTransactionMembershipCreatePendingContribution(): void {
4433 [$originalContribution, $membership] = $this->setUpAutoRenewMembership();
4434 $this->callAPISuccess('membership', 'create', [
4435 'id' => $membership['id'],
4436 'end_date' => 'yesterday',
4437 'status_id' => 'Expired',
4438 ]);
4439 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4440 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
4441 'contribution_status_id' => 'Pending',
4442 'trxn_id' => 1234,
4443 ]);
4444 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
4445 'id' => $membership['id'],
4446 'return' => 'status_id',
4447 ]);
4448
4449 // Let's see if the membership payments got created while we're at it.
4450 $membershipPayments = $this->callAPISuccess('MembershipPayment', 'get', [
4451 'membership_id' => $membership['id'],
4452 ]);
4453 $this->assertEquals(2, $membershipPayments['count']);
4454
4455 $this->assertEquals('Expired', CRM_Core_PseudoConstant::getLabel('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
4456 $this->callAPISuccess('Contribution', 'completetransaction', ['id' => $repeatedContribution['id']]);
4457 $membership = $this->callAPISuccessGetSingle('membership', [
4458 'id' => $membership['id'],
4459 'return' => 'status_id, end_date',
4460 ]);
4461 $this->assertEquals('New', CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membership['status_id']));
4462 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 month')), $membership['end_date']);
4463 }
4464
4465 /**
4466 * Test sending a mail via the API.
4467 *
4468 * @throws \CRM_Core_Exception
4469 */
4470 public function testSendMailWithAPISetFromDetails() {
4471 $mut = new CiviMailUtils($this, TRUE);
4472 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
4473 $this->callAPISuccess('contribution', 'sendconfirmation', [
4474 'id' => $contribution['id'],
4475 'receipt_from_email' => 'api@civicrm.org',
4476 'receipt_from_name' => 'CiviCRM LLC',
4477 ]);
4478 $mut->checkMailLog([
4479 'From: CiviCRM LLC <api@civicrm.org>',
4480 'Contribution Information',
4481 ], [
4482 'Event',
4483 ]);
4484 $mut->stop();
4485 }
4486
4487 /**
4488 * Test sending a mail via the API.
4489 */
4490 public function testSendMailWithNoFromSetFallToDomain() {
4491 $this->createLoggedInUser();
4492 $mut = new CiviMailUtils($this, TRUE);
4493 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params);
4494 $this->callAPISuccess('contribution', 'sendconfirmation', [
4495 'id' => $contribution['id'],
4496 ]);
4497 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4498 $mut->checkMailLog([
4499 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4500 'Contribution Information',
4501 ], [
4502 'Event',
4503 ]);
4504 $mut->stop();
4505 }
4506
4507 /**
4508 * Test sending a mail via the API.
4509 *
4510 * @throws \CRM_Core_Exception
4511 */
4512 public function testSendMailWithRepeatTransactionAPIFalltoDomain() {
4513 $this->createLoggedInUser();
4514 $mut = new CiviMailUtils($this, TRUE);
4515 $contribution = $this->setUpRepeatTransaction([], 'single');
4516 $this->callAPISuccess('contribution', 'repeattransaction', [
4517 'contribution_status_id' => 'Completed',
4518 'trxn_id' => 7890,
4519 'original_contribution_id' => $contribution,
4520 ]);
4521 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4522 $mut->checkMailLog([
4523 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4524 'Contribution Information',
4525 ], [
4526 'Event',
4527 ]
4528 );
4529 $mut->stop();
4530 }
4531
4532 /**
4533 * Test sending a mail via the API.
4534 *
4535 * @throws \CRM_Core_Exception
4536 */
4537 public function testSendMailWithRepeatTransactionAPIFalltoContributionPage() {
4538 $mut = new CiviMailUtils($this, TRUE);
4539 $contributionPage = $this->contributionPageCreate(['receipt_from_name' => 'CiviCRM LLC', 'receipt_from_email' => 'contributionpage@civicrm.org', 'is_email_receipt' => 1]);
4540 $paymentProcessorID = $this->paymentProcessorCreate();
4541 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
4542 'contact_id' => $this->_individualId,
4543 'installments' => '12',
4544 'frequency_interval' => '1',
4545 'amount' => '500',
4546 'contribution_status_id' => 1,
4547 'start_date' => '2012-01-01 00:00:00',
4548 'currency' => 'USD',
4549 'frequency_unit' => 'month',
4550 'payment_processor_id' => $paymentProcessorID,
4551 ]);
4552 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4553 $this->_params,
4554 [
4555 'contribution_recur_id' => $contributionRecur['id'],
4556 'contribution_page_id' => $contributionPage['id'],
4557 ])
4558 );
4559 $this->callAPISuccess('Contribution', 'repeattransaction', [
4560 'contribution_status_id' => 'Completed',
4561 'trxn_id' => 5678,
4562 'original_contribution_id' => $originalContribution,
4563 ]
4564 );
4565 $mut->checkMailLog([
4566 'From: CiviCRM LLC <contributionpage@civicrm.org>',
4567 'Contribution Information',
4568 ], [
4569 'Event',
4570 ]);
4571 $mut->stop();
4572 }
4573
4574 /**
4575 * Test sending a mail via the API.
4576 *
4577 * @throws \CRM_Core_Exception
4578 */
4579 public function testSendMailWithRepeatTransactionAPIFalltoSystemFromNoDefaultFrom(): void {
4580 $mut = new CiviMailUtils($this, TRUE);
4581 $originalContribution = $this->setUpRepeatTransaction([], 'single');
4582 $fromEmail = $this->callAPISuccess('optionValue', 'get', ['is_default' => 1, 'option_group_id' => 'from_email_address', 'sequential' => 1]);
4583 foreach ($fromEmail['values'] as $from) {
4584 $this->callAPISuccess('optionValue', 'create', ['is_default' => 0, 'id' => $from['id']]);
4585 }
4586 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => CRM_Core_Config::domainID()]);
4587 $this->callAPISuccess('contribution', 'repeattransaction', [
4588 'contribution_status_id' => 'Completed',
4589 'trxn_id' => 4567,
4590 'original_contribution_id' => $originalContribution,
4591 ]);
4592 $mut->checkMailLog([
4593 'From: ' . $domain['name'] . ' <' . $domain['domain_email'] . '>',
4594 'Contribution Information',
4595 ], [
4596 'Event',
4597 ]);
4598 $mut->stop();
4599 }
4600
4601 /**
4602 * Create a Contribution Page with is_email_receipt = TRUE.
4603 *
4604 * @param array $params
4605 * Params to overwrite with.
4606 *
4607 * @return array|int
4608 */
4609 protected function createReceiptableContributionPage($params = []) {
4610 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', array_merge([
4611 'receipt_from_name' => 'Mickey Mouse',
4612 'receipt_from_email' => 'mickey@mouse.com',
4613 'title' => "Test Contribution Page",
4614 'financial_type_id' => 1,
4615 'currency' => 'CAD',
4616 'is_monetary' => TRUE,
4617 'is_email_receipt' => TRUE,
4618 ], $params));
4619 return $contributionPage;
4620 }
4621
4622 /**
4623 * function to test card_type and pan truncation.
4624 *
4625 * @throws \CRM_Core_Exception
4626 */
4627 public function testCardTypeAndPanTruncation() {
4628 $creditCardTypeIDs = array_flip(CRM_Financial_DAO_FinancialTrxn::buildOptions('card_type_id'));
4629 $contactId = $this->individualCreate();
4630 $params = [
4631 'contact_id' => $contactId,
4632 'receive_date' => '2016-01-20',
4633 'total_amount' => 100,
4634 'financial_type_id' => 1,
4635 'payment_instrument' => 'Credit Card',
4636 'card_type_id' => $creditCardTypeIDs['Visa'],
4637 'pan_truncation' => 4567,
4638 ];
4639 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4640 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
4641 $financialTrxn = $this->callAPISuccessGetSingle(
4642 'FinancialTrxn',
4643 [
4644 'id' => $lastFinancialTrxnId['financialTrxnId'],
4645 'return' => ['card_type_id', 'pan_truncation'],
4646 ]
4647 );
4648 $this->assertEquals(CRM_Utils_Array::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Visa']);
4649 $this->assertEquals(CRM_Utils_Array::value('pan_truncation', $financialTrxn), 4567);
4650 $params = [
4651 'id' => $contribution['id'],
4652 'pan_truncation' => 2345,
4653 'card_type_id' => $creditCardTypeIDs['Amex'],
4654 ];
4655 $this->callAPISuccess('contribution', 'create', $params);
4656 $financialTrxn = $this->callAPISuccessGetSingle(
4657 'FinancialTrxn',
4658 [
4659 'id' => $lastFinancialTrxnId['financialTrxnId'],
4660 'return' => ['card_type_id', 'pan_truncation'],
4661 ]
4662 );
4663 $this->assertEquals(CRM_Utils_Array::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Amex']);
4664 $this->assertEquals(CRM_Utils_Array::value('pan_truncation', $financialTrxn), 2345);
4665 }
4666
4667 /**
4668 * Test repeat contribution uses non default currency
4669 *
4670 * @see https://issues.civicrm.org/jira/projects/CRM/issues/CRM-20678
4671 * @throws \CRM_Core_Exception
4672 */
4673 public function testRepeatTransactionWithDifferenceCurrency() {
4674 $originalContribution = $this->setUpRepeatTransaction(['currency' => 'AUD'], 'single', ['currency' => 'AUD']);
4675 $contribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
4676 'original_contribution_id' => $originalContribution['id'],
4677 'contribution_status_id' => 'Completed',
4678 'trxn_id' => 3456,
4679 ]);
4680 $this->assertEquals('AUD', $contribution['values'][$contribution['id']]['currency']);
4681 }
4682
4683 /**
4684 * Get the financial items for the contribution.
4685 *
4686 * @param int $contributionID
4687 *
4688 * @return array
4689 * Array of associated financial items.
4690 */
4691 protected function getFinancialTransactionsForContribution($contributionID) {
4692 $trxnParams = [
4693 'entity_id' => $contributionID,
4694 'entity_table' => 'civicrm_contribution',
4695 ];
4696 // @todo the following function has naming errors & has a weird signature & appears to
4697 // only be called from test classes. Move into test suite & maybe just use api
4698 // from this function.
4699 return array_merge(CRM_Financial_BAO_FinancialItem::retrieveEntityFinancialTrxn($trxnParams));
4700 }
4701
4702 /**
4703 * Test getunique api call for Contribution entity
4704 */
4705 public function testContributionGetUnique() {
4706 $result = $this->callAPIAndDocument($this->entity, 'getunique', [], __FUNCTION__, __FILE__);
4707 $this->assertEquals(2, $result['count']);
4708 $this->assertEquals(['trxn_id'], $result['values']['UI_contrib_trxn_id']);
4709 $this->assertEquals(['invoice_id'], $result['values']['UI_contrib_invoice_id']);
4710 }
4711
4712 /**
4713 * Test Repeat Transaction Contribution with Tax amount.
4714 *
4715 * https://lab.civicrm.org/dev/core/issues/806
4716 *
4717 * @throws \CRM_Core_Exception
4718 */
4719 public function testRepeatContributionWithTaxAmount(): void {
4720 $this->enableTaxAndInvoicing();
4721 $financialType = $this->callAPISuccess('financial_type', 'create', [
4722 'name' => 'Test taxable financial Type',
4723 'is_reserved' => 0,
4724 'is_active' => 1,
4725 ]);
4726 $this->addTaxAccountToFinancialType($financialType['id']);
4727 $contribution = $this->setUpRepeatTransaction(
4728 [],
4729 'single',
4730 [
4731 'financial_type_id' => $financialType['id'],
4732 ]
4733 );
4734 $this->callAPISuccess('contribution', 'repeattransaction', [
4735 'original_contribution_id' => $contribution['id'],
4736 'contribution_status_id' => 'Completed',
4737 'trxn_id' => 'test',
4738 ]);
4739 $payments = $this->callAPISuccess('Contribution', 'get', ['sequential' => 1, 'return' => ['total_amount', 'tax_amount']])['values'];
4740 //Assert if first payment and repeated payment has the same contribution amount.
4741 $this->assertEquals($payments[0]['total_amount'], $payments[1]['total_amount']);
4742 $this->callAPISuccessGetCount('Contribution', [], 2);
4743
4744 //Assert line item records.
4745 $lineItems = $this->callAPISuccess('LineItem', 'get', ['sequential' => 1])['values'];
4746 foreach ($lineItems as $lineItem) {
4747 $taxExclusiveAmount = $payments[0]['total_amount'] - $payments[0]['tax_amount'];
4748 $this->assertEquals($lineItem['unit_price'], $taxExclusiveAmount);
4749 $this->assertEquals($lineItem['line_total'], $taxExclusiveAmount);
4750 }
4751 $this->callAPISuccessGetCount('Contribution', [], 2);
4752 }
4753
4754 public function testGetCurrencyOptions() {
4755 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4756 'field' => 'currency',
4757 ]);
4758 $this->assertEquals('US Dollar', $result['values']['USD']);
4759 $this->assertNotContains('$', $result['values']);
4760 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4761 'field' => 'currency',
4762 'context' => "abbreviate",
4763 ]);
4764 $this->assertEquals('$', $result['values']['USD']);
4765 $this->assertNotContains('US Dollar', $result['values']);
4766 }
4767
4768 /**
4769 * @throws \API_Exception
4770 * @throws \CRM_Core_Exception
4771 * @throws \Civi\API\Exception\UnauthorizedException
4772 */
4773 public function testSetCustomDataInCreateAndHook() {
4774 $this->createCustomGroupWithFieldOfType([], 'int');
4775 $this->ids['CustomField']['text'] = (int) $this->createTextCustomField(['custom_group_id' => $this->ids['CustomGroup']['Custom Group']])['id'];
4776 $this->hookClass->setHook('civicrm_post', [
4777 $this,
4778 'civicrmPostContributionCustom',
4779 ]);
4780 $params = $this->_params;
4781 $params['custom_' . $this->ids['CustomField']['text']] = 'Some Text';
4782 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
4783 $getContribution = $this->callAPISuccess('Contribution', 'get', [
4784 'id' => $contribution['id'],
4785 'return' => ['id', 'custom_' . $this->ids['CustomField']['text'], 'custom_' . $this->ids['CustomField']['int']],
4786 ]);
4787 $this->assertEquals(5, $getContribution['values'][$contribution['id']][$this->getCustomFieldName('int')]);
4788 $this->assertEquals('Some Text', $getContribution['values'][$contribution['id']]['custom_' . $this->ids['CustomField']['text']]);
4789 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids['CustomField']['text']]);
4790 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids['CustomField']['int']]);
4791 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $this->ids['CustomGroup']['Custom Group']]);
4792 }
4793
4794 /**
4795 * Implement post hook.
4796 *
4797 * @param string $op
4798 * @param string $objectName
4799 * @param int|null $objectId
4800 *
4801 * @throws \CRM_Core_Exception
4802 */
4803 public function civicrmPostContributionCustom(string $op, string $objectName, ?int $objectId): void {
4804 if ($objectName === 'Contribution' && $op === 'create') {
4805 $this->callAPISuccess('Contribution', 'create', [
4806 'id' => $objectId,
4807 'custom_' . $this->ids['CustomField']['int'] => 5,
4808 ]);
4809 }
4810 }
4811
4812 /**
4813 * Test that passing in label for an option value linked to a custom field
4814 * works
4815 *
4816 * @see dev/core#1816
4817 *
4818 * @throws \API_Exception
4819 * @throws \CRM_Core_Exception
4820 */
4821 public function testCustomValueOptionLabelTest(): void {
4822 $this->createCustomGroupWithFieldOfType([], 'radio');
4823 $params = $this->_params;
4824 $params['custom_' . $this->ids['CustomField']['radio']] = 'Red Testing';
4825 $this->callAPISuccess('Contribution', 'Create', $params);
4826 }
4827
4828 /**
4829 * Test repeatTransaction with installments and next_sched_contribution_date
4830 *
4831 * @dataProvider getRepeatTransactionNextSchedData
4832 *
4833 * @param array $dataSet
4834 *
4835 * @throws \CRM_Core_Exception
4836 */
4837 public function testRepeatTransactionUpdateNextSchedContributionDate(array $dataSet): void {
4838 $paymentProcessorID = $this->paymentProcessorCreate();
4839 // Create the contribution before the recur so it doesn't trigger the update of next_sched_contribution_date
4840 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
4841 $this->_params,
4842 [
4843 'contribution_status_id' => 'Completed',
4844 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4845 ])
4846 );
4847 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4848 'contact_id' => $this->_individualId,
4849 'frequency_interval' => '1',
4850 'amount' => '500',
4851 'contribution_status_id' => 'Pending',
4852 'start_date' => '2012-01-01 00:00:00',
4853 'currency' => 'USD',
4854 'frequency_unit' => 'month',
4855 'payment_processor_id' => $paymentProcessorID,
4856 ], $dataSet['recur']));
4857 // Link the existing contribution to the recur *after* creating the recur.
4858 // If we just created the contribution now the next_sched_contribution_date would be automatically set
4859 // and we want to test the case when it is empty.
4860 $this->callAPISuccess('contribution', 'create', [
4861 'id' => $contribution['id'],
4862 'contribution_recur_id' => $contributionRecur['id'],
4863 ]);
4864
4865 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4866 'id' => $contributionRecur['id'],
4867 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4868 ]);
4869 // Check that next_sched_contribution_date is empty
4870 $this->assertEquals('', $contributionRecur['next_sched_contribution_date'] ?? '');
4871
4872 $this->callAPISuccess('Contribution', 'repeattransaction', [
4873 'contribution_status_id' => 'Completed',
4874 'contribution_recur_id' => $contributionRecur['id'],
4875 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4876 ]);
4877 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4878 'id' => $contributionRecur['id'],
4879 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4880 ]);
4881 // Check that recur has status "In Progress"
4882 $this->assertEquals(
4883 (string) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][0]['expectedRecurStatus']),
4884 $contributionRecur['contribution_status_id']
4885 );
4886 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4887 $this->assertEquals($dataSet['repeat'][0]['expectedNextSched'], $contributionRecur['next_sched_contribution_date']);
4888
4889 // Now call Contribution.repeattransaction again and check that the next_sched_contribution_date has moved forward by 1 period again
4890 $this->callAPISuccess('Contribution', 'repeattransaction', [
4891 'contribution_status_id' => 'Completed',
4892 'contribution_recur_id' => $contributionRecur['id'],
4893 'receive_date' => $dataSet['repeat'][1]['receive_date'],
4894 ]);
4895 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4896 'id' => $contributionRecur['id'],
4897 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4898 ]);
4899 // Check that recur has status "In Progress" or "Completed" depending on whether number of installments has been reached
4900 $this->assertEquals(
4901 (string) CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][1]['expectedRecurStatus']),
4902 $contributionRecur['contribution_status_id']
4903 );
4904 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4905 $this->assertEquals($dataSet['repeat'][1]['expectedNextSched'], $contributionRecur['next_sched_contribution_date'] ?? '');
4906 }
4907
4908 /**
4909 * Get dates for testing.
4910 *
4911 * @return array
4912 */
4913 public function getRepeatTransactionNextSchedData(): array {
4914 // Both these tests handle/test the case that next_sched_contribution_date is empty when Contribution.repeattransaction
4915 // is called for the first time. Historically setting it was inconsistent but on new updates it should always be set.
4916 /*
4917 * This tests that calling Contribution.repeattransaction with installments does the following:
4918 * - For the first call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4919 * to match next expected receive_date.
4920 * - Once the 3rd contribution is created contributionRecur status = completed and next_sched_contribution_date = ''.
4921 */
4922 $result['receive_date_includes_time_with_installments']['2012-01-01-1-month'] = [
4923 'recur' => [
4924 'start_date' => '2012-01-01',
4925 'frequency_interval' => 1,
4926 'installments' => '3',
4927 'frequency_unit' => 'month',
4928 ],
4929 'repeat' => [
4930 [
4931 'receive_date' => '2012-02-29 16:00:00',
4932 'expectedNextSched' => '2012-03-29 00:00:00',
4933 'expectedRecurStatus' => 'In Progress',
4934 ],
4935 [
4936 'receive_date' => '2012-03-29 16:00:00',
4937 'expectedNextSched' => '',
4938 'expectedRecurStatus' => 'Completed',
4939 ],
4940 ],
4941 ];
4942 /*
4943 * This tests that calling Contribution.repeattransaction with no installments does the following:
4944 * - For the each call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4945 * to match next expected receive_date.
4946 */
4947 $result['receive_date_includes_time_no_installments']['2012-01-01-1-month'] = [
4948 'recur' => [
4949 'start_date' => '2012-01-01',
4950 'frequency_interval' => 1,
4951 'frequency_unit' => 'month',
4952 ],
4953 'repeat' => [
4954 [
4955 'receive_date' => '2012-02-29 16:00:00',
4956 'expectedNextSched' => '2012-03-29 00:00:00',
4957 'expectedRecurStatus' => 'In Progress',
4958 ],
4959 [
4960 'receive_date' => '2012-03-29 16:00:00',
4961 'expectedNextSched' => '2012-04-29 00:00:00',
4962 'expectedRecurStatus' => 'In Progress',
4963 ],
4964 ],
4965 ];
4966 return $result;
4967 }
4968
4969 /**
4970 * Make sure that recording a payment doesn't alter the receive_date of a
4971 * pending contribution.
4972 */
4973 public function testPaymentDontChangeReceiveDate(): void {
4974 $params = [
4975 'contact_id' => $this->_individualId,
4976 'total_amount' => 100,
4977 'receive_date' => '2020-02-02',
4978 'contribution_status_id' => 'Pending',
4979 ];
4980 $contributionID = $this->contributionCreate($params);
4981 $paymentParams = [
4982 'contribution_id' => $contributionID,
4983 'total_amount' => 100,
4984 'trxn_date' => '2020-03-04',
4985 ];
4986 $this->callAPISuccess('payment', 'create', $paymentParams);
4987
4988 //check if contribution status is set to "Completed".
4989 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
4990 'id' => $contributionID,
4991 ]);
4992 $this->assertEquals('2020-02-02 00:00:00', $contribution['receive_date']);
4993 }
4994
4995 /**
4996 * Make sure that recording a payment with Different Payment Instrument update main contribution record payment
4997 * instrument too. If multiple Payment Recorded, last payment record payment (when No more due) instrument set to main
4998 * payment
4999 */
5000 public function testPaymentVerifyPaymentInstrumentChange() {
5001 // Create Pending contribution with pay later mode, with payment instrument Check
5002 $params = [
5003 'contact_id' => $this->_individualId,
5004 'total_amount' => 100,
5005 'receive_date' => '2020-02-02',
5006 'contribution_status_id' => 'Pending',
5007 'is_pay_later' => 1,
5008 'payment_instrument_id' => 'Check',
5009 ];
5010 $contributionID = $this->contributionCreate($params);
5011
5012 // Record the the Payment with instrument other than Check, e.g EFT
5013 $paymentParams = [
5014 'contribution_id' => $contributionID,
5015 'total_amount' => 50,
5016 'trxn_date' => '2020-03-04',
5017 'payment_instrument_id' => 'EFT',
5018 ];
5019 $this->callAPISuccess('payment', 'create', $paymentParams);
5020
5021 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
5022 'id' => $contributionID,
5023 ]);
5024 // payment status should be 'Partially paid'
5025 $this->assertEquals('Partially paid', $contribution['contribution_status']);
5026
5027 // Record the the Payment with instrument other than Check, e.g Cash (pay all remaining amount)
5028 $paymentParams = [
5029 'contribution_id' => $contributionID,
5030 'total_amount' => 50,
5031 'trxn_date' => '2020-03-04',
5032 'payment_instrument_id' => 'Cash',
5033 ];
5034 $this->callAPISuccess('payment', 'create', $paymentParams);
5035
5036 //check if contribution Payment Instrument (Payment Method) is is set to "Cash".
5037 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
5038 'id' => $contributionID,
5039 ]);
5040 $this->assertEquals('Cash', $contribution['payment_instrument']);
5041 $this->assertEquals('Completed', $contribution['contribution_status']);
5042 }
5043
5044 /**
5045 * Test the "clean money" functionality.
5046 */
5047 public function testCleanMoney() {
5048 $params = [
5049 'contact_id' => $this->_individualId,
5050 'financial_type_id' => 1,
5051 'total_amount' => '$100',
5052 'fee_amount' => '$20',
5053 'net_amount' => '$80',
5054 'non_deductible_amount' => '$80',
5055 'sequential' => 1,
5056 ];
5057 $id = $this->callAPISuccess('Contribution', 'create', $params)['id'];
5058 // Reading the return values of the API isn't reliable here; get the data from the db.
5059 $contribution = $this->callAPISuccess('Contribution', 'getsingle', ['id' => $id]);
5060 $this->assertEquals('100.00', $contribution['total_amount']);
5061 $this->assertEquals('20.00', $contribution['fee_amount']);
5062 $this->assertEquals('80.00', $contribution['net_amount']);
5063 $this->assertEquals('80.00', $contribution['non_deductible_amount']);
5064 }
5065
5066 /**
5067 * Create a price set with a quick config price set.
5068 *
5069 * The params to use this look like
5070 *
5071 * ['price_' . $this->ids['PriceField']['basic'] => $this->ids['PriceFieldValue']['basic']]
5072 *
5073 * @param array $contributionPageParams
5074 *
5075 * @return int
5076 *
5077 * @throws \API_Exception
5078 * @throws \CRM_Core_Exception
5079 * @throws \Civi\API\Exception\UnauthorizedException
5080 */
5081 private function createQuickConfigContributionPage(array $contributionPageParams = []): int {
5082 $contributionPageID = $this->callAPISuccess('ContributionPage', 'create', array_merge([
5083 'receipt_from_name' => 'Mickey Mouse',
5084 'receipt_from_email' => 'mickey@mouse.com',
5085 'title' => 'Test Contribution Page',
5086 'financial_type_id' => 'Member Dues',
5087 'currency' => 'CAD',
5088 'is_pay_later' => 1,
5089 'is_quick_config' => TRUE,
5090 'pay_later_text' => 'I will send payment by check',
5091 'pay_later_receipt' => 'This is a pay later receipt',
5092 'is_allow_other_amount' => 1,
5093 'min_amount' => 10.00,
5094 'max_amount' => 10000.00,
5095 'goal_amount' => 100000.00,
5096 'is_email_receipt' => 1,
5097 'is_active' => 1,
5098 'amount_block_is_active' => 1,
5099 'is_billing_required' => 0,
5100 ], $contributionPageParams))['id'];
5101
5102 $priceSetID = PriceSet::create()->setValues([
5103 'name' => 'quick config set',
5104 'title' => 'basic price set',
5105 'is_quick_config' => TRUE,
5106 'extends' => 2,
5107 ])->execute()->first()['id'];
5108
5109 $priceFieldID = PriceField::create()->setValues([
5110 'price_set_id' => $priceSetID,
5111 'name' => 'quick config field name',
5112 'label' => 'quick config field name',
5113 'html_type' => 'Radio',
5114 ])->execute()->first()['id'];
5115 $this->ids['PriceSet']['basic'] = $priceSetID;
5116 $this->ids['PriceField']['basic'] = $priceFieldID;
5117 $this->ids['PriceFieldValue']['basic'] = PriceFieldValue::create()->setValues([
5118 'price_field_id' => $priceFieldID,
5119 'name' => 'quick config price field',
5120 'label' => 'quick config price field',
5121 'amount' => 100,
5122 'financial_type_id:name' => 'Member Dues',
5123 ])->execute()->first()['id'];
5124 CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $contributionPageID, $priceSetID);
5125 return $contributionPageID;
5126 }
5127
5128 /**
5129 * Get the created contribution ID.
5130 *
5131 * @param string $key
5132 *
5133 * @return int
5134 */
5135 protected function getContributionID(string $key = 'first'): int {
5136 return (int) $this->ids['contribution'][$key];
5137 }
5138
5139 /**
5140 * Get the created contribution ID.
5141 *
5142 * @return int
5143 */
5144 protected function getMembershipID(): int {
5145 return (int) $this->_ids['membership'];
5146 }
5147
5148 /**
5149 * Create a paid membership for renewal tests.
5150 */
5151 protected function createSubsequentPendingMembership(): void {
5152 $this->setUpPendingContribution($this->_ids['price_field_value'][1], 'second', [], [], [
5153 'id' => $this->getMembershipID(),
5154 ]);
5155 }
5156
5157 /**
5158 * Create a paid membership for renewal tests.
5159 */
5160 protected function createInitialPaidMembership(): void {
5161 $this->setUpPendingContribution($this->_ids['price_field_value'][1]);
5162 $this->callAPISuccess('Payment', 'create', [
5163 'contribution_id' => $this->getContributionID(),
5164 'total_amount' => 20,
5165 ]);
5166 }
5167
5168 }