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