3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
12 use Civi\Api4\ActivityContact
;
13 use Civi\Api4\Contribution
;
14 use Civi\Api4\ContributionRecur
;
16 use Civi\Api4\PriceField
;
17 use Civi\Api4\PriceFieldValue
;
18 use Civi\Api4\PriceSet
;
21 * Test APIv3 civicrm_contribute_* functions
23 * @package CiviCRM_APIv3
24 * @subpackage API_Contribution
27 class api_v3_ContributionTest
extends CiviUnitTestCase
{
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
;
35 protected $_individualId;
36 protected $_contribution;
37 protected $_financialTypeId = 1;
38 protected $entity = 'Contribution';
41 protected $_pageParams = [];
44 * Payment processor ID (dummy processor).
48 protected $paymentProcessorID;
51 * Parameters to create payment processor.
55 protected $_processorParams = [];
58 * ID of created event.
70 * Should financials be checked after the test but before tear down.
74 protected $isValidateFinancialsOnPostAssert = TRUE;
79 public function setUp(): void
{
82 $this->_apiversion
= 3;
83 $this->_individualId
= $this->individualCreate();
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,
91 'net_amount' => 95.00,
93 'contribution_status_id' => 1,
95 $this->_processorParams
= [
98 'payment_processor_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', 'Dummy'),
99 'financial_account_id' => 12,
102 'url_site' => 'http://dummy.com',
103 'url_recur' => 'http://dummy.com',
106 $this->paymentProcessorID
= $this->processorCreate();
107 $this->_pageParams
= [
108 'title' => 'Test Contribution Page',
109 'financial_type_id' => 1,
111 'financial_account_id' => 1,
112 'payment_processor' => $this->paymentProcessorID
,
114 'is_allow_other_amount' => 1,
116 'max_amount' => 1000,
121 * Clean up after each test.
123 * @throws \API_Exception
124 * @throws \CRM_Core_Exception
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'],
135 foreach ($entityFinancialTypes['values'] as $entityFinancialType) {
136 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialType['id']]);
138 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
141 $this->restoreUFGroupOne();
148 public function testGetContribution(): void
{
149 $this->enableTaxAndInvoicing();
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,
159 'invoice_id' => 78910,
161 'contribution_status_id' => 'Completed',
163 $this->_contribution
= $this->callAPISuccess('contribution', 'create', $p);
166 'contribution_id' => $this->_contribution
['id'],
167 'return' => array_merge(['invoice_number', 'contribution_source'], array_keys($p)),
170 $contributions = $this->callAPIAndDocument('Contribution', 'get', $params, __FUNCTION__
, __FILE__
);
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';
189 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
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,
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,
205 $this->assertEquals($contribution2['id'], $contribution);
207 $contribution = $this->callAPISuccess('contribution', 'get', [
208 'id' => $this->_contribution
['id'],
210 $this->assertEquals(1, $contribution['count']);
212 // Test get by contact id works.
213 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId
]);
215 $this->assertEquals(2, $contribution['count']);
216 $this->callAPISuccess('Contribution', 'Delete', [
217 'id' => $this->_contribution
['id'],
219 $this->callAPISuccess('Contribution', 'Delete', [
220 'id' => $contribution2['id'],
225 * Test that test contributions can be retrieved.
227 * @throws \CRM_Core_Exception
229 public function testGetTestContribution(): void
{
230 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['is_test' => 1]));
231 $this->callAPISuccessGetSingle('Contribution', ['is_test' => 1]);
235 * Test Creating a check contribution with original check_number field
237 * @throws \CRM_Core_Exception
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',
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',
270 foreach ($entityFinancialTrxn['values'] as $eft) {
271 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'get', [
272 'id' => $eft['financial_trxn_id'],
273 'return' => 'check_number',
275 $this->assertEquals('bouncer', $financialTrxn['values'][$financialTrxn['id']]['check_number']);
280 * Test the 'return' param works for all fields.
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',
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,
306 $params['contribution_recur_id'] = $contributionRecur['id'];
308 $params['campaign_id'] = $this->campaignCreate();
310 $contributionID = $this->contributionCreate($params);
312 // update contribution with invoice number
313 $params = array_merge($params, [
314 'id' => $contributionID,
315 'invoice_number' => Civi
::settings()->get('invoice_prefix') . $contributionID,
317 'invoice_id' => 6789,
319 $contributionID = $this->contributionCreate($params);
321 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID]);
322 $this->assertEquals('bouncer', $contribution['check_number']);
323 $this->assertEquals('bouncer', $contribution['contribution_check_number']);
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'];
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',
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';
352 $this->assertTrue((!empty($contribution[$returnField]) ||
$contribution[$returnField] === '0'), $returnField);
354 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
355 'entity_id' => $contributionID,
356 'entity_table' => 'civicrm_contribution',
357 'return' => 'financial_trxn_id',
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']);
366 * Test cancel reason works as a filter.
368 * @throws \CRM_Core_Exception
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);
383 * We need to ensure previous tested api contract behaviour still works.
385 * @throws \CRM_Core_Exception
387 public function testGetContributionLegacyBehaviour(): void
{
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,
397 'invoice_id' => 78910,
399 'contribution_status_id' => 1,
401 $this->_contribution
= $this->callAPISuccess('Contribution', 'create', $p);
404 'contribution_id' => $this->_contribution
['id'],
405 'return' => array_keys($p),
407 $params['return'][] = 'financial_type_id';
408 $params['return'][] = 'contribution_source';
409 $contribution = $this->callAPISuccess('Contribution', 'get', $params);
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');
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';
428 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
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,
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,
444 $this->assertEquals($contribution2['id'], $contribution);
445 $contribution = $this->callAPISuccess('contribution', 'get', [
446 'id' => $this->_contribution
['id'],
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
]);
454 $this->assertEquals(2, $contribution['count']);
455 $this->callAPISuccess('Contribution', 'Delete', [
456 'id' => $this->_contribution
['id'],
458 $this->callAPISuccess('Contribution', 'Delete', [
459 'id' => $contribution2['id'],
464 * Create an contribution_id=FALSE and financial_type_id=Donation.
466 public function testCreateEmptyContributionIDUseDonation() {
468 'contribution_id' => FALSE,
471 'check_permissions' => FALSE,
472 'financial_type_id' => 'Donation',
474 $this->callAPISuccess('contribution', 'create', $params);
478 * Check with complete array + custom field.
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
484 * @throws \CRM_Core_Exception
486 public function testCreateWithCustom(): void
{
487 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, __FILE__
);
489 $params = $this->_params
;
490 $params['custom_' . $ids['custom_field_id']] = 'custom string';
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'],
498 $this->assertEquals('custom string', $check['values'][$check['id']]['custom_' . $ids['custom_field_id']]);
502 * Check with complete array + custom field.
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
508 * @throws \CRM_Core_Exception
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']);
523 * Test creating a contribution without skipLineItems.
525 * @throws \CRM_Core_Exception
527 public function testCreateContributionNoLineItems(): void
{
528 // Turn off this validation as this test results in invalid
529 // financial entities.
530 $this->isValidateFinancialsOnPostAssert
= FALSE;
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,
541 'invoice_id' => 67890,
543 'contribution_status_id' => 1,
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'])));
552 $this->callAPISuccessGetCount('LineItem', [
553 'entity_id' => $contribution['id'],
554 'entity_table' => 'civicrm_contribution',
560 * Test checks that passing in line items suppresses the create mechanism.
562 * @throws \CRM_Core_Exception
564 public function testCreateContributionChainedLineItems(): void
{
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,
575 'invoice_id' => 67890,
577 'contribution_status_id' => 'Pending',
579 'api.line_item.create' => [
581 'price_field_id' => 1,
583 'line_total' => '20',
584 'unit_price' => '10',
587 'price_field_id' => 1,
589 'line_total' => '80',
590 'unit_price' => '80',
595 $description = 'Create Contribution with Nested Line Items.';
596 $subFile = 'CreateWithNestedLineItems';
597 $contribution = $this->callAPIAndDocument('Contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subFile);
599 $this->callAPISuccessGetCount('LineItem', [
600 'entity_id' => $contribution['id'],
601 'contribution_id' => $contribution['id'],
602 'entity_table' => 'civicrm_contribution',
608 * @throws \CRM_Core_Exception
610 public function testCreateContributionOffline(): void
{
612 'contact_id' => $this->_individualId
,
613 'receive_date' => '20120511',
614 'total_amount' => 100.00,
615 'financial_type_id' => 1,
617 'invoice_id' => 67890,
619 'contribution_status_id' => 1,
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',
636 'return' => ['entity_id', 'contribution_id'],
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']);
646 * Test create with valid payment instrument.
648 * @throws \CRM_Core_Exception
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', [
655 'id' => $contribution['id'],
656 'return' => 'payment_instrument',
658 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
659 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
661 $this->callAPISuccess('Contribution', 'create', [
662 'id' => $contribution['id'],
663 'payment_instrument' => 'Credit Card',
665 $contribution = $this->callAPISuccess('Contribution', 'get', [
667 'id' => $contribution['id'],
668 'return' => 'payment_instrument',
670 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
671 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
675 * @throws \CRM_Core_Exception
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', [
684 'contribution_payment_instrument' => 'Cash',
685 'return' => 'payment_instrument',
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', [
696 'payment_instrument_id' => 5,
697 'return' => 'payment_instrument',
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', [
704 'payment_instrument' => 'EFT',
705 'return' => 'payment_instrument',
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',
715 $contribution = $this->callAPISuccess('Contribution', 'get', [
717 'id' => $contribution['id'],
718 'return' => 'payment_instrument',
720 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
721 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
722 $this->assertEquals(1, $contribution['count']);
726 * CRM-16227 introduces invoice_id as a parameter.
728 * @throws \CRM_Core_Exception
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);
738 * Check the credit note retrieval is case insensitive.
740 * @throws \CRM_Core_Exception
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']);
750 * Test retrieval by total_amount works.
752 * @throws \CRM_Core_Exception
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);
766 * @dataProvider createLocalizedContributionDataProvider
768 * @param float|int|string $totalAmount
769 * @param string $decimalPoint
770 * @param string $thousandSeparator
771 * @param string $currency
772 * @param bool $expectedResult
774 * @throws \CRM_Core_Exception
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);
782 'contact_id' => $this->_individualId
,
783 'receive_date' => '20120511',
784 'total_amount' => $totalAmount,
785 'financial_type_id' => $this->_financialTypeId
,
786 'contribution_status_id' => 1,
789 if ($expectedResult) {
790 $this->callAPISuccess('Contribution', 'create', $_params);
793 $this->callAPIFailure('Contribution', 'create', $_params);
800 public function createLocalizedContributionDataProvider(): array {
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],
866 * Create test with unique field name on source.
868 public function testCreateContributionSource() {
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,
880 'invoice_id' => 67890,
881 'contribution_source' => 'SSF',
882 'contribution_status_id' => 1,
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');
891 * Create test with unique field name on source.
893 * @param string $thousandSeparator
894 * punctuation used to refer to thousands.
896 * @dataProvider getThousandSeparators
898 public function testCreateDefaultNow($thousandSeparator) {
899 $this->setCurrencySeparators($thousandSeparator);
900 $params = $this->_params
;
901 unset($params['receive_date'], $params['net_amount']);
903 $params['total_amount'] = $this->formatMoneyInput(5000.77);
904 $params['fee_amount'] = $this->formatMoneyInput(.77);
905 $params['skipCleanMoney'] = FALSE;
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']);
916 * Create test with unique field name on source.
918 public function testCreateContributionNullOutThankyouDate() {
920 $params = $this->_params
;
921 $params['thankyou_date'] = 'yesterday';
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'])));
927 $params['thankyou_date'] = 'null';
928 $contribution = $this->callAPISuccess('contribution', 'create', $params);
929 $this->assertTrue(empty($contribution['thankyou_date']));
933 * Create test with unique field name on source.
935 public function testCreateContributionSourceInvalidContact() {
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,
947 'invoice_id' => 67890,
948 'contribution_source' => 'SSF',
949 'contribution_status_id' => 1,
952 $this->callAPIFailure('contribution', 'create', $params, 'contact_id is not valid : 999');
956 * Test note created correctly.
958 * @throws \CRM_Core_Exception
960 public function testCreateContributionWithNote(): void
{
961 $description = 'Demonstrates creating contribution with Note Entity.';
962 $subFile = 'ContributionCreateWithNote';
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,
973 'invoice_id' => 67890,
975 'contribution_status_id' => 1,
976 'note' => 'my contribution note',
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'],
986 $this->assertEquals('my contribution note', $result['values'][0]['note']);
987 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
991 * @throws \CRM_Core_Exception
993 public function testCreateContributionWithNoteUniqueNameAliases(): void
{
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,
1004 'invoice_id' => 67890,
1006 'contribution_status_id' => 1,
1007 'contribution_note' => 'my contribution note',
1010 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1011 $result = $this->callAPISuccess('note', 'get', [
1012 'entity_table' => 'civicrm_contribution',
1013 'entity_id' => $contribution['id'],
1017 $this->assertEquals('my contribution note', $result['values'][0]['note']);
1021 * This is the test for creating soft credits.
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',
1031 'contact_id' => $contact2['id'],
1033 'soft_credit_type_id' => 3,
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]);
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']);
1044 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1045 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
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',
1055 $params = $this->_params +
[
1056 'soft_credit_to' => $contact2['id'],
1058 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1059 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
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']);
1066 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1067 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1071 * Test creating contribution with Soft Credit by passing in honor_contact_id.
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',
1080 $params = $this->_params +
[
1081 'honor_contact_id' => $contact2['id'],
1083 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1084 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
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));
1093 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1094 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1098 * Test using example code.
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);
1112 * Function tests that additional financial records are created when fee amount is recorded.
1114 public function testCreateContributionWithFee() {
1116 'contact_id' => $this->_individualId
,
1117 'receive_date' => '20120511',
1118 'total_amount' => 100.00,
1120 'financial_type_id' => 1,
1122 'invoice_id' => 67890,
1124 'contribution_status_id' => 1,
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);
1138 $lineItems = $this->callAPISuccess('line_item', 'get', [
1140 'entity_id' => $contribution['id'],
1141 'entity_table' => 'civicrm_contribution',
1143 'return' => ['entity_id', 'contribution_id'],
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', [
1150 'entity_id' => $contribution['id'],
1151 'contribution_id' => $contribution['id'],
1152 'entity_table' => 'civicrm_contribution',
1155 $this->_checkFinancialRecords($contribution, 'feeAmount');
1159 * Function tests that additional financial records are created when online
1160 * contribution is created.
1162 * @throws \CRM_Core_Exception
1163 * @throws \CiviCRM_API3_Exception
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);
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
,
1177 'invoice_id' => 67890,
1179 'contribution_status_id' => 1,
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',
1195 $this->_checkFinancialRecords($contribution, 'online');
1199 * Check handling of financial type.
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
1204 public function testCreateInvalidFinancialType(): void
{
1205 $params = $this->_params
;
1206 $params['financial_type_id'] = 99999;
1207 $this->callAPIFailure($this->entity
, 'create', $params);
1211 * Check handling of financial type.
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
1216 * @throws \CRM_Core_Exception
1218 public function testValidNamedFinancialType() {
1219 $params = $this->_params
;
1220 $params['financial_type_id'] = 'Donation';
1221 $this->callAPISuccess($this->entity
, 'create', $params);
1225 * Tests that additional financial records are created.
1227 * Checks when online contribution with pay later option is created
1229 * @throws \CRM_Core_Exception
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);
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'],
1242 'is_pay_later' => 1,
1243 'invoice_id' => 67890,
1245 'contribution_status_id' => 'Pending',
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');
1262 * Function tests that additional financial records are created for online contribution with pending option.
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);
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'],
1275 'invoice_id' => 67890,
1277 'contribution_status_id' => 2,
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');
1292 * Test that BAO defaults work.
1294 * @throws \CRM_Core_Exception
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'],
1304 $this->assertEquals(1, $contribution['contribution_status_id']);
1305 $this->assertEquals('Check', $contribution['payment_instrument']);
1306 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1310 * Test that getsingle can be chained with delete.
1312 * @throws CRM_Core_Exception
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,
1321 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1325 * Function tests that line items, financial records are updated when contribution amount is changed.
1327 * @throws \CRM_Core_Exception
1329 public function testCreateUpdateContributionChangeTotal() {
1330 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
1331 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1333 'entity_id' => $contribution['id'],
1334 'entity_table' => 'civicrm_contribution',
1336 'return' => 'line_total',
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);
1344 'id' => $contribution['id'],
1345 'total_amount' => '125',
1347 $contribution = $this->callAPISuccess('Contribution', 'create', $newParams);
1349 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1351 'entity_id' => $contribution['id'],
1352 'entity_table' => 'civicrm_contribution',
1354 'return' => 'line_total',
1357 $this->assertEquals('125.00', $lineItems);
1358 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1360 // Financial trxn SUM = 125 + 5 (fee).
1361 $this->assertEquals('130.00', $trxnAmount);
1362 $this->assertEquals('125.00', $this->_getFinancialItemAmount($contribution['id']));
1366 * Function tests that line items, financial records are updated when pay later contribution is received.
1368 public function testCreateUpdateContributionPayLater() {
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,
1379 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1381 $newParams = array_merge($contribParams, [
1382 'id' => $contribution['id'],
1383 'contribution_status_id' => 1,
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');
1393 * Function tests that financial records are updated when Payment Instrument is changed.
1395 public function testCreateUpdateContributionPaymentInstrument(): void
{
1396 $instrumentId = $this->_addPaymentInstrument();
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,
1405 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1407 $newParams = array_merge($contribParams, [
1408 'id' => $contribution['id'],
1409 'payment_instrument_id' => $instrumentId,
1411 $contribution = $this->callAPISuccess('Contribution', 'create', $newParams);
1412 $this->assertAPISuccess($contribution);
1413 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId);
1415 // cleanup - delete created payment instrument
1416 $this->deletedAddedPaymentInstrument();
1420 * Function tests that financial records are updated when Payment Instrument is changed when amount is negative.
1422 public function testCreateUpdateNegativeContributionPaymentInstrument() {
1423 $instrumentId = $this->_addPaymentInstrument();
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,
1432 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1434 $newParams = array_merge($contribParams, [
1435 'id' => $contribution['id'],
1436 'payment_instrument_id' => $instrumentId,
1438 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1439 $this->assertAPISuccess($contribution);
1440 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId, -100);
1442 // cleanup - delete created payment instrument
1443 $this->deletedAddedPaymentInstrument();
1447 * Function tests that financial records are added when Contribution is Refunded.
1449 * @throws \CRM_Core_Exception
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',
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',
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',
1479 * Refund a contribution for a financial type with a contra account.
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.
1485 * @throws \CRM_Core_Exception
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',
1493 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1495 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1496 'contribution_id' => $contribution['id'],
1497 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
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,
1508 * Refund a contribution for a financial type with a contra account.
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.
1514 * @throws \CRM_Core_Exception
1516 public function testCreateUpdateChargebackContributionCustomAccount() {
1517 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1518 'name' => 'Chargeback Account',
1519 'is_active' => TRUE,
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',
1529 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1530 $this->callAPISuccess('Contribution', 'create', [
1531 'id' => $contribution['id'],
1532 'contribution_status_id' => 'Chargeback',
1534 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1536 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1537 'contribution_id' => $contribution['id'],
1538 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1540 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1542 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1543 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1544 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1548 * Refund a contribution for a financial type with a contra account.
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.
1554 public function testCreateUpdateRefundContributionConfiguredContraAccount() {
1555 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1556 'name' => 'Refund Account',
1557 'is_active' => TRUE,
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',
1567 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1568 $this->callAPISuccess('Contribution', 'create', [
1569 'id' => $contribution['id'],
1570 'contribution_status_id' => 'Refunded',
1573 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1574 'contribution_id' => $contribution['id'],
1575 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1577 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1579 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1580 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1581 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1585 * Function tests that trxn_id is set when passed in.
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.
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',
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',
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',
1618 * Function tests that trxn_id is set when passed in.
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.
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',
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',
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',
1653 * Function tests that refund_trxn_id is set when passed in empty.
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.
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',
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' => '',
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',
1688 * Function tests invalid contribution status change.
1690 public function testCreateUpdateContributionInValidStatusChange() {
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,
1699 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1700 $newParams = array_merge($contribParams, [
1701 'id' => $contribution['id'],
1702 'contribution_status_id' => 2,
1704 $this->callAPIFailure('contribution', 'create', $newParams, ts('Cannot change contribution status from Completed to Pending.'));
1709 * Function tests that financial records are added when Pending Contribution is Canceled.
1711 * @throws \CRM_Core_Exception
1713 public function testCreateUpdateContributionCancelPending() {
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,
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',
1730 //Check if trxn_date is same as cancel_date.
1732 'trxn_date' => '2012-02-02 09:00:00',
1734 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1735 $this->_checkFinancialTrxn($contribution, 'cancelPending', NULL, $checkTrxnDate);
1736 $this->_checkFinancialItem($contribution['id'], 'cancelPending');
1740 * Function tests that financial records are added when Financial Type is Changed.
1742 * @throws \CRM_Core_Exception
1744 public function testCreateUpdateContributionChangeFinancialType() {
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,
1754 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1755 $newParams = array_merge($contribParams, [
1756 'id' => $contribution['id'],
1757 'financial_type_id' => 3,
1759 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1760 $this->_checkFinancialTrxn($contribution, 'changeFinancial');
1761 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1765 * Function tets that financial records are correctly added when financial type is changed
1767 * @throws \CRM_Core_Exception
1769 public function testCreateUpdateContributionWithFeeAmountChangeFinancialType() {
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,
1780 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1781 $newParams = array_merge($contribParams, [
1782 'id' => $contribution['id'],
1783 'financial_type_id' => 3,
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');
1791 * Test that update does not change status id CRM-15105.
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,
1800 $this->assertEquals(2, $contribution['contribution_status_id']);
1804 * Test Updating a Contribution.
1806 * CHANGE: we require the API to do an incremental update
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',
1816 'contribution_id' => $contributionID,
1818 $original = $this->callAPISuccess('contribution', 'get', $old_params);
1819 $this->assertEquals($original['id'], $contributionID);
1820 //set up list of old params, verify
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'];
1828 $old_trxn_id = $original['values'][$contributionID]['trxn_id'];
1829 $old_invoice_id = $original['values'][$contributionID]['invoice_id'];
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');
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',
1848 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1851 'contribution_id' => $contribution['id'],
1853 $contribution = $this->callAPISuccessGetSingle('contribution', $new_params);
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');
1867 $this->assertEquals($contribution['net_amount'], $contribution['total_amount'] - $contribution['fee_amount']);
1870 'contribution_id' => $contributionID,
1872 $result = $this->callAPISuccess('contribution', 'delete', $params);
1873 $this->assertAPISuccess($result);
1877 * Check that net_amount is updated when a contribution is updated.
1879 * Update fee amount AND total amount, just fee amount, just total amount
1880 * and neither to check that net_amount is keep updated.
1882 public function testUpdateContributionNetAmountVariants() {
1883 $contributionID = $this->contributionCreate(['contact_id' => $this->individualCreate()]);
1885 $this->callAPISuccess('Contribution', 'create', [
1886 'id' => $contributionID,
1887 'total_amount' => 90,
1890 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1891 'id' => $contributionID,
1892 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1894 $this->assertEquals(6, $contribution['fee_amount']);
1895 $this->assertEquals(90, $contribution['total_amount']);
1896 $this->assertEquals(84, $contribution['net_amount']);
1898 $this->callAPISuccess('Contribution', 'create', [
1899 'id' => $contributionID,
1902 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1903 'id' => $contributionID,
1904 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1906 $this->assertEquals(3, $contribution['fee_amount']);
1907 $this->assertEquals(90, $contribution['total_amount']);
1908 $this->assertEquals(87, $contribution['net_amount']);
1910 $this->callAPISuccess('Contribution', 'create', [
1911 'id' => $contributionID,
1912 'total_amount' => 200,
1914 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1915 'id' => $contributionID,
1916 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1918 $this->assertEquals(3, $contribution['fee_amount']);
1919 $this->assertEquals(200, $contribution['total_amount']);
1920 $this->assertEquals(197, $contribution['net_amount']);
1922 $this->callAPISuccess('Contribution', 'create', [
1923 'id' => $contributionID,
1924 'payment_instrument' => 'Cash',
1926 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1927 'id' => $contributionID,
1928 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1930 $this->assertEquals(3, $contribution['fee_amount']);
1931 $this->assertEquals(200, $contribution['total_amount']);
1932 $this->assertEquals(197, $contribution['net_amount']);
1936 * Attempt (but fail) to delete a contribution without parameters.
1938 public function testDeleteEmptyParamsContribution() {
1940 $this->callAPIFailure('contribution', 'delete', $params);
1943 public function testDeleteWrongParamContribution() {
1945 'contribution_source' => 'SSF',
1947 $this->callAPIFailure('contribution', 'delete', $params);
1950 public function testDeleteContribution() {
1951 $contributionID = $this->contributionCreate([
1952 'contact_id' => $this->_individualId
,
1953 'financial_type_id' => $this->_financialTypeId
,
1956 'id' => $contributionID,
1958 $this->callAPIAndDocument('contribution', 'delete', $params, __FUNCTION__
, __FILE__
);
1962 * Test civicrm_contribution_search with empty params.
1964 * All available contributions expected.
1966 public function testSearchEmptyParams() {
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,
1978 'invoice_id' => 78910,
1980 'contribution_status_id' => 1,
1982 $contribution = $this->callAPISuccess('contribution', 'create', $p);
1984 $result = $this->callAPISuccess('contribution', 'get', $params);
1985 // We're taking the first element.
1986 $res = $result['values'][$contribution['id']];
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']);
2000 $this->contributionDelete($contribution['id']);
2004 * Test civicrm_contribution_search. Success expected.
2006 public function testSearch() {
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,
2015 $contribution1 = $this->callAPISuccess('contribution', 'create', $p1);
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,
2029 $contribution2 = $this->callAPISuccess('contribution', 'create', $p2);
2032 'contribution_id' => $contribution2['id'],
2034 $result = $this->callAPISuccess('contribution', 'get', $params);
2035 $res = $result['values'][$contribution2['id']];
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']);
2047 $this->contributionDelete($contribution1['id']);
2048 $this->contributionDelete($contribution2['id']);
2052 * Test completing a transaction via the API.
2054 * Note that we are creating a logged in user because email goes out from
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'],
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',
2076 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2077 "receipt_date:::\n",
2078 'title:::Contribution',
2079 'contributionStatus:::Completed',
2083 $this->revertTemplateToReservedTemplate();
2087 * Test completing a transaction via the API with a non-USD transaction.
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);
2096 $this->callAPISuccess('contribution', 'completetransaction', [
2097 'id' => $contribution['id'],
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'])));
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']);
2110 $mut->checkMailLog([
2111 'email:::anthony_anderson@civicrm.org',
2115 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2116 "receipt_date:::\n",
2117 'title:::Contribution',
2118 'contributionStatus:::Completed',
2121 $this->revertTemplateToReservedTemplate();
2125 * Test to ensure mail is sent for pay later
2127 * @throws \CRM_Core_Exception
2128 * @throws \API_Exception
2130 public function testPayLater(): void
{
2131 $mut = new CiviMailUtils($this, TRUE);
2132 $this->swapMessageTemplateForTestTemplate();
2133 $this->createLoggedInUser();
2134 $contributionPageID = $this->createQuickConfigContributionPage();
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!',
2147 $this->callAPISuccess('ContributionPage', 'submit', $params);
2149 $mut->checkMailLog([
2151 'email:::anthony_anderson@civicrm.org',
2152 'pay_later_receipt:::This is a pay later receipt',
2153 'contributionPageId:::' . $contributionPageID,
2154 'title:::Test Contribution Page',
2158 $this->revertTemplateToReservedTemplate();
2162 * Test to check whether contact billing address is used when no contribution address
2164 public function testBillingAddress() {
2165 $mut = new CiviMailUtils($this, TRUE);
2166 $this->swapMessageTemplateForTestTemplate();
2167 $this->createLoggedInUser();
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'],
2175 $mut->checkMailLog([
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'],
2185 $params = array_merge($this->_params
, [
2186 'contribution_status_id' => 2,
2187 'address_id' => $address['id'],
2190 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2191 $this->callAPISuccess('contribution', 'completetransaction', [
2192 'id' => $contribution['id'],
2194 $mut->checkMailLog([
2195 'address:::contribution billing st',
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'],
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'],
2209 $mut->checkMailLog([
2210 'address:::is billing st',
2214 $this->revertTemplateToReservedTemplate();
2218 * Test completing a transaction via the API.
2220 * Note that we are creating a logged in user because email goes out from
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',
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']);
2240 * CRM-19126 Add test to verify when complete transaction is called tax
2241 * amount is not changed.
2243 * We start of with a pending contribution.
2244 * - total_amount (input) = 100
2245 * - total_amount post save (based on tax being added) = 105
2248 * - non_deductible_amount = 10
2251 * - sum of (calculated) line items = 105
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.
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
2260 * @param string $thousandSeparator
2261 * punctuation used to refer to thousands.
2263 * @throws \API_Exception
2264 * @throws \CRM_Core_Exception
2265 * @dataProvider getThousandSeparators
2267 public function testCheckTaxAmount(string $thousandSeparator): void
{
2268 $this->setCurrencySeparators($thousandSeparator);
2269 $this->createFinancialTypeWithSalesTax();
2270 $financialTypeId = $this->ids
['FinancialType']['taxable'];
2272 $contributionID = $this->callAPISuccess('Order', 'create',
2273 array_merge($this->_params
, ['financial_type_id' => $financialTypeId])
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',
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();
2293 * Test repeat contribution successfully creates line item.
2295 * @throws \CRM_Core_Exception
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',
2305 'entity_id' => $originalContribution['id'],
2313 'financial_type_id',
2314 'deductible_amount',
2315 'price_field_value_id',
2319 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2320 'entity_id' => $originalContribution['id'],
2322 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2323 'entity_id' => $originalContribution['id'] +
1,
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',
2338 * Test custom data is copied over from the template transaction.
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.
2343 * @throws \API_Exception
2344 * @throws \CRM_Core_Exception
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',
2355 $contribution = Contribution
::get()
2356 ->addWhere('trxn_id', '=', 'my_trxn')
2357 ->addSelect('Custom_Group.Enter_text_here')
2359 ->execute()->first();
2360 $this->assertEquals('first', $contribution['Custom_Group.Enter_text_here']);
2362 Contribution
::update()->setValues(['Custom_Group.Enter_text_here' => 'second'])->addWhere('id', '=', $contribution['id'])->execute();
2364 $this->callAPISuccess('contribution', 'repeattransaction', [
2365 'original_contribution_id' => $originalContribution['id'],
2366 'contribution_status_id' => 'Completed',
2367 'trxn_id' => 'number_3',
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']);
2378 * Test repeat contribution successfully creates line items (plural).
2380 * @throws \CRM_Core_Exception
2382 public function testRepeatTransactionLineItems(): void
{
2384 $originalContribution = $this->setUpRepeatTransaction([], 'multiple');
2385 $this->callAPISuccess('contribution', 'repeattransaction', [
2386 'original_contribution_id' => $originalContribution['id'],
2387 'contribution_status_id' => 'Completed',
2392 'entity_id' => $originalContribution['id'],
2400 'financial_type_id',
2401 'deductible_amount',
2402 'price_field_value_id',
2406 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2407 'entity_id' => $originalContribution['id'],
2408 'options' => ['sort' => 'qty'],
2410 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2411 'entity_id' => $originalContribution['id'] +
1,
2412 'options' => ['sort' => 'qty'],
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]);
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]);
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;
2427 $this->callAPISuccessGetCount('FinancialItem', ['description' => 'Sales Tax', 'amount' => 0], 0);
2431 * Test repeat contribution successfully creates is_test transaction.
2433 * @throws \CRM_Core_Exception
2435 public function testRepeatTransactionIsTest(): void
{
2436 $this->_params
['is_test'] = 1;
2437 $originalContribution = $this->setUpRepeatTransaction(['is_test' => 1], 'single');
2439 $this->callAPISuccess('contribution', 'repeattransaction', [
2440 'original_contribution_id' => $originalContribution['id'],
2441 'contribution_status_id' => 'Completed',
2442 'trxn_id' => '1234',
2444 $this->callAPISuccessGetCount('Contribution', ['contribution_test' => 1], 2);
2448 * Test repeat contribution passed in status.
2450 * @throws \CRM_Core_Exception
2452 public function testRepeatTransactionPassedInStatus(): void
{
2453 $originalContribution = $this->setUpRepeatTransaction([], 'single');
2455 $this->callAPISuccess('contribution', 'repeattransaction', [
2456 'original_contribution_id' => $originalContribution['id'],
2457 'contribution_status_id' => 'Pending',
2460 $this->callAPISuccessGetCount('Contribution', ['contribution_status_id' => 2], 1);
2464 * Test repeat contribution accepts recur_id instead of
2465 * original_contribution_id.
2467 * @throws \CRM_Core_Exception
2469 public function testRepeatTransactionAcceptRecurID(): void
{
2470 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2471 'contact_id' => $this->_individualId
,
2472 'installments' => '12',
2473 'frequency_interval' => '1',
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
,
2481 $this->callAPISuccess('contribution', 'create', array_merge(
2483 ['contribution_recur_id' => $contributionRecur['id']])
2486 $this->callAPISuccess('contribution', 'repeattransaction', [
2487 'contribution_recur_id' => $contributionRecur['id'],
2488 'contribution_status_id' => 'Completed',
2495 * CRM-19873 Test repeattransaction if contribution_recur_id is a test.
2497 * @throws \CRM_Core_Exception
2499 public function testRepeatTransactionTestRecurId() {
2500 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
2501 'contact_id' => $this->_individualId
,
2502 'frequency_interval' => '1',
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
,
2511 $this->callAPISuccess('contribution', 'create', array_merge(
2514 'contribution_recur_id' => $contributionRecur['id'],
2519 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2520 'contribution_recur_id' => $contributionRecur['id'],
2521 'contribution_status_id' => 'Completed',
2522 'trxn_id' => 'magic_number',
2525 $this->assertEquals($contributionRecur['values'][1]['is_test'], $repeatedContribution['values'][2]['is_test']);
2529 * Test repeat contribution accepts recur_id instead of
2530 * original_contribution_id.
2532 * @throws \CRM_Core_Exception
2534 public function testRepeatTransactionPreviousContributionRefunded(): void
{
2535 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2536 'contact_id' => $this->_individualId
,
2537 'installments' => '12',
2538 'frequency_interval' => '1',
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
,
2546 $this->callAPISuccess('contribution', 'create', array_merge(
2549 'contribution_recur_id' => $contributionRecur['id'],
2550 'contribution_status_id' => 'Refunded',
2555 $this->callAPISuccess('contribution', 'repeattransaction', [
2556 'contribution_recur_id' => $contributionRecur['id'],
2559 $contributions = $this->callAPISuccess('contribution', 'get', [
2560 'contribution_recur_id' => $contributionRecur['id'],
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']);
2570 * CRM-19945 Tests that Contribute.repeattransaction renews a membership when contribution status=Completed
2572 * @throws \CRM_Core_Exception
2574 public function testRepeatTransactionMembershipRenewCompletedContribution(): void
{
2575 [$originalContribution, $membership] = $this->setUpAutoRenewMembership();
2577 $this->callAPISuccess('Contribution', 'repeattransaction', [
2578 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2579 'contribution_status_id' => 'Failed',
2582 $this->callAPISuccess('membership', 'create', [
2583 'id' => $membership['id'],
2584 'end_date' => 'yesterday',
2585 'status_id' => 'Expired',
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',
2594 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
2595 'id' => $membership['id'],
2596 'return' => 'status_id',
2599 $membership = $this->callAPISuccess('membership', 'get', [
2600 'id' => $membership['id'],
2603 $this->assertEquals('New', CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
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']]);
2611 * This is one of those tests that locks in existing behaviour.
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'.
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',
2626 $membership = $membership['values'][$membership['id']];
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']);
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']);
2641 * CRM-19945 Tests that Contribute.repeattransaction DOES NOT renew a membership when contribution status=Failed
2643 * @dataProvider contributionStatusProvider
2645 * @throws \CRM_Core_Exception
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'])) {
2654 [$originalContribution, $membership] = $this->setUpAutoRenewMembership();
2656 $this->callAPISuccess('Contribution', 'repeattransaction', [
2657 'original_contribution_id' => $originalContribution['id'],
2658 'contribution_status_id' => 'Completed',
2661 $this->callAPISuccess('membership', 'create', [
2662 'id' => $membership['id'],
2663 'end_date' => 'yesterday',
2664 'status_id' => 'Expired',
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',
2673 $updatedMembership = $this->callAPISuccess('membership', 'getsingle', ['id' => $membership['id']]);
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']);
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']]);
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.
2689 * @throws \CiviCRM_API3_Exception
2691 public function contributionStatusProvider() {
2692 $contributionStatuses = civicrm_api3('OptionValue', 'get', [
2693 'return' => ['id', 'name'],
2694 'option_group_id' => 'contribution_status',
2696 foreach ($contributionStatuses['values'] as $statusName) {
2697 $statuses[] = [$statusName];
2703 * CRM-16397 test appropriate action if total amount has changed for single
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',
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,
2719 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2722 'contribution_recur_id' => $contributionRecur['id'],
2726 $this->callAPISuccess('contribution', 'repeattransaction', [
2727 'original_contribution_id' => $originalContribution['id'],
2728 'contribution_status_id' => 'Completed',
2730 'total_amount' => '400',
2735 'entity_id' => $originalContribution['id'],
2743 'financial_type_id',
2744 'deductible_amount',
2745 'price_field_value_id',
2749 $this->callAPISuccessGetSingle('contribution', [
2750 'total_amount' => 400,
2752 'net_amount' => 350,
2754 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2755 'entity_id' => $originalContribution['id'],
2757 $expectedLineItem = array_merge(
2758 $lineItem1['values'][0], [
2759 'line_total' => '400.00',
2760 'unit_price' => '400.00',
2764 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2765 'entity_id' => $originalContribution['id'] +
1,
2768 unset($expectedLineItem['id'], $expectedLineItem['entity_id'], $lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2769 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2771 $this->callAPISuccess('contribution', 'repeattransaction', [
2772 'original_contribution_id' => $originalContribution['id'],
2773 'contribution_status_id' => 'Completed',
2776 $this->callAPISuccessGetSingle('contribution', [
2777 'total_amount' => 400,
2783 * Test financial_type_id override behaviour with a single line item.
2785 * CRM-17718 a passed in financial_type_id is allowed to override the
2786 * original contribution where there is only one line item.
2788 * @throws \CRM_Core_Exception
2790 public function testRepeatTransactionPassedInFinancialType() {
2791 $originalContribution = $this->setUpRecurringContribution();
2793 $this->callAPISuccess('Contribution', 'repeattransaction', [
2794 'original_contribution_id' => $originalContribution['id'],
2795 'contribution_status_id' => 'Completed',
2797 'financial_type_id' => 2,
2800 'entity_id' => $originalContribution['id'],
2808 'financial_type_id',
2809 'deductible_amount',
2810 'price_field_value_id',
2815 $this->callAPISuccessGetSingle('Contribution', [
2816 'total_amount' => 100,
2817 'financial_type_id' => 2,
2819 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2820 'entity_id' => $originalContribution['id'],
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,
2830 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2831 'entity_id' => $originalContribution['id'] +
1,
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]);
2839 * Test Contribution with Order api.
2841 * @throws \CRM_Core_Exception|\CiviCRM_API3_Exception
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']]);
2849 $this->callAPISuccess('Payment', 'create', [
2850 'contribution_id' => $this->ids
['Contribution'][0],
2851 'payment_instrument_id' => 'Check',
2852 'total_amount' => 300,
2854 $contribution = $this->callAPISuccess('contribution', 'get')['values'][$this->ids
['Contribution'][0]];
2855 $this->assertEquals('Completed', $contribution['contribution_status']);
2857 $lineItem = $this->callAPISuccess('LineItem', 'get', [
2859 'contribution_id' => $this->ids
['Contribution'][0],
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']);
2873 * Test financial_type_id override behaviour with a single line item.
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.
2878 * @throws \CRM_Core_Exception
2880 public function testRepeatTransactionPassedInFinancialTypeTwoLineItems(): void
{
2881 $this->_params
= $this->getParticipantOrderParams();
2882 $originalContribution = $this->setUpRecurringContribution();
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,
2891 // Retrieve the new contribution and note the financial type passed in has been ignored.
2892 $contribution = $this->callAPISuccessGetSingle('Contribution', [
2893 'trxn_id' => 'repeat',
2895 $this->assertEquals(4, $contribution['financial_type_id']);
2897 $lineItems = $this->callAPISuccess('line_item', 'get', [
2898 'entity_id' => $contribution['id'],
2900 foreach ($lineItems as $lineItem) {
2901 $this->assertNotEquals(2, $lineItem['financial_type_id']);
2906 * CRM-17718 test appropriate action if financial type has changed for single
2909 * @throws \CRM_Core_Exception
2911 public function testRepeatTransactionUpdatedFinancialType(): void
{
2912 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2914 $this->callAPISuccess('contribution', 'repeattransaction', [
2915 'contribution_recur_id' => $originalContribution['id'],
2916 'contribution_status_id' => 'Completed',
2920 'entity_id' => $originalContribution['id'],
2928 'financial_type_id',
2929 'deductible_amount',
2930 'price_field_value_id',
2935 $this->callAPISuccessGetSingle('contribution', [
2936 'total_amount' => 100,
2937 'financial_type_id' => 2,
2939 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2940 'entity_id' => $originalContribution['id'],
2942 $expectedLineItem = array_merge(
2944 'line_total' => '100.00',
2945 'unit_price' => '100.00',
2946 'financial_type_id' => 2,
2947 'contribution_type_id' => 2,
2951 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2952 'entity_id' => $originalContribution['id'] +
1,
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]);
2960 * CRM-16397 test appropriate action if campaign has been passed in.
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',
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,
2977 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2980 'contribution_recur_id' => $contributionRecur['id'],
2981 'campaign_id' => $campaignID,
2985 $this->callAPISuccess('contribution', 'repeattransaction', [
2986 'original_contribution_id' => $originalContribution['id'],
2987 'contribution_status_id' => 'Completed',
2989 'campaign_id' => $campaignID2,
2992 $this->callAPISuccessGetSingle('contribution', [
2993 'total_amount' => 100,
2994 'campaign_id' => $campaignID2,
2999 * CRM-17718 campaign stored on contribution recur gets priority.
3001 * This reflects the fact we permit people to update them.
3003 * @throws \CRM_Core_Exception
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',
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,
3021 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
3024 'contribution_recur_id' => $contributionRecur['id'],
3025 'campaign_id' => $campaignID2,
3029 $this->callAPISuccess('contribution', 'repeattransaction', [
3030 'original_contribution_id' => $originalContribution['id'],
3031 'contribution_status_id' => 'Completed',
3035 $this->callAPISuccessGetSingle('Contribution', [
3036 'total_amount' => 100,
3037 'campaign_id' => $campaignID,
3042 * CRM-20685 Repeattransaction produces incorrect Financial Type ID (in
3043 * specific circumstance) - if number of lineItems = 1.
3045 * This case happens when the line item & contribution do not have the same
3046 * type in his initiating transaction.
3048 * @throws \CRM_Core_Exception
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',
3060 'entity_id' => $originalContribution['id'],
3068 'financial_type_id',
3069 'deductible_amount',
3070 'price_field_value_id',
3074 $this->callAPISuccessGetSingle('contribution', [
3075 'total_amount' => 100,
3076 'financial_type_id' => 2,
3078 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
3079 'entity_id' => $originalContribution['id'],
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,
3090 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
3091 'entity_id' => $originalContribution['id'] +
1,
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]);
3100 * Test completing a transaction does not 'mess' with net amount (CRM-15960).
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'],
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']);
3116 * CRM-14151 - Test completing a transaction via the API.
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'),
3136 $this->revertTemplateToReservedTemplate();
3140 * CRM-1960 - Test to ensure that completetransaction respects the is_email_receipt setting
3142 public function testCompleteTransactionWithEmailReceiptInput() {
3143 $contributionPage = $this->createReceiptableContributionPage();
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,
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);
3161 * Test that $is_recur is assigned to the receipt.
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]);
3169 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3170 $this->_params
['contribution_recur_id'] = $recurring['id'];
3172 $contribution = $this->setUpForCompleteTransaction();
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,
3181 $this->mut
->checkMailLog([
3183 'cancelSubscriptionUrl:::' . CIVICRM_UF_BASEURL
,
3186 $this->revertTemplateToReservedTemplate();
3190 * CRM-19710 - Test to ensure that completetransaction respects the input for
3191 * is_email_receipt setting.
3193 * If passed in it will override the default from contribution page.
3195 * @throws \API_Exception
3196 * @throws \CRM_Core_Exception
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,
3212 $mut->checkMailLog([
3213 'Contribution Information',
3220 * Complete the transaction using the template with all the possible.
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',
3230 $receive_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receive_date']);
3231 $this->mut
->checkMailLog([
3232 'email:::anthony_anderson@civicrm.org',
3236 'receive_date:::' . date('Ymd', strtotime($receive_date)),
3237 'receipt_date:::' . date('Ymd'),
3238 'title:::Contribution',
3240 'contactID:::' . $this->_params
['contact_id'],
3241 'contributionID:::' . $contribution['id'],
3242 'financialTypeId:::1',
3243 'financialTypeName:::Donation',
3246 $this->revertTemplateToReservedTemplate();
3250 * Complete the transaction using the template with all the possible.
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,
3264 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3265 $contribution = $this->setUpForCompleteTransaction();
3266 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id']]);
3267 $this->mut
->checkMailLog([
3275 * Test completing first transaction in a recurring series.
3277 * The status should be set to 'in progress' and the next scheduled payment date calculated.
3279 * @dataProvider getScheduledDateData
3281 * @param array $dataSet
3283 * @throws \Exception
3285 public function testCompleteTransactionSetStatusToInProgress(array $dataSet): void
{
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',
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(
3301 'contribution_recur_id' => $contributionRecur['id'],
3302 'contribution_status_id' => 'Pending',
3303 'receive_date' => $dataSet['receive_date'],
3306 $this->callAPISuccess('Contribution', 'completetransaction', [
3307 'id' => $contribution['id'],
3308 'receive_date' => $dataSet['receive_date'],
3310 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3311 'id' => $contributionRecur['id'],
3312 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
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(
3319 'contribution_recur_id' => $contributionRecur['id'],
3320 'contribution_status_id' => 'Completed',
3323 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3324 'id' => $contributionRecur['id'],
3325 'return' => ['contribution_status_id'],
3327 $this->assertEquals(1, $contributionRecur['contribution_status_id']);
3331 * Get dates for testing.
3335 public function getScheduledDateData() {
3337 $result[]['2016-08-31-1-month'] = [
3339 'start_date' => '2016-08-31',
3340 'frequency_interval' => 1,
3341 'frequency_unit' => 'month',
3343 'receive_date' => '2016-08-31',
3344 'expected' => '2016-10-01 00:00:00',
3346 $result[]['2012-01-01-1-month'] = [
3348 'start_date' => '2012-01-01',
3349 'frequency_interval' => 1,
3350 'frequency_unit' => 'month',
3352 'receive_date' => '2012-01-01',
3353 'expected' => '2012-02-01 00:00:00',
3355 $result[]['2012-01-01-1-month'] = [
3357 'start_date' => '2012-01-01',
3358 'frequency_interval' => 1,
3359 'frequency_unit' => 'month',
3361 'receive_date' => '2012-02-29',
3362 'expected' => '2012-03-29 00:00:00',
3364 $result['receive_date_includes_time']['2012-01-01-1-month'] = [
3366 'start_date' => '2012-01-01',
3367 'frequency_interval' => 1,
3368 'frequency_unit' => 'month',
3369 'next_sched_contribution_date' => '2012-02-29',
3371 'receive_date' => '2012-02-29 16:00:00',
3372 'expected' => '2012-03-29 00:00:00',
3378 * Test completing a pledge with the completeTransaction api..
3380 * Note that we are creating a logged in user because email goes out from
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',
3393 $pledge = $this->callAPISuccessGetSingle('Pledge', [
3394 'id' => $this->_ids
['pledge'],
3396 $this->assertEquals('Completed', $pledge['pledge_status']);
3398 $status = $this->callAPISuccessGetValue('PledgePayment', [
3399 'pledge_id' => $this->_ids
['pledge'],
3400 'return' => 'status_id',
3402 $this->assertEquals(1, $status);
3403 $mut->checkMailLog([
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
3409 'receive_date:::20120511000000',
3410 "receipt_date:::\n",
3413 $this->revertTemplateToReservedTemplate();
3417 * Test repeating a pledge with the repeatTransaction api..
3419 * @throws \API_Exception
3421 public function testRepeatTransactionWithPledgePayment(): void
{
3422 $contributionID = $this->createPendingPledgeContribution(2);
3423 $contributionRecurID = ContributionRecur
::create()->setValues([
3424 'contact_id' => $this->_individualId
,
3426 'payment_processor_id' => $this->paymentProcessorID
,
3427 ])->execute()->first()['id'];
3428 Contribution
::update()->setValues([
3429 'id' => $contributionID,
3430 'contribution_recur_id' => $contributionRecurID,
3432 $this->callAPISuccess('contribution', 'completetransaction', [
3433 'id' => $contributionID,
3434 'trxn_date' => '1 Feb 2013',
3436 $this->assertEquals('In Progress', Pledge
::get()
3437 ->addWhere('id', '=', $this->_ids
['pledge'])
3438 ->addSelect('status_id:name')->execute()->first()['status_id:name']
3440 $this->callAPISuccess('contribution', 'repeattransaction', [
3441 'contribution_recur_id' => $contributionRecurID,
3442 'trxn_id' => '2013',
3443 'contribution_status_id' => 'Completed',
3445 $this->assertEquals('Completed', Pledge
::get()
3446 ->addWhere('id', '=', $this->_ids
['pledge'])
3447 ->addSelect('status_id:name')->execute()->first()['status_id:name']
3452 * Test completing a transaction with an event via the API.
3454 * Note that we are creating a logged in user because email goes out from
3457 * @throws \CRM_Core_Exception
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();
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',
3477 $this->assertEquals(1, $participantStatus);
3479 //Assert only three activities are created.
3480 $activities = $this->callAPISuccess('Activity', 'get', [
3481 'contact_id' => $this->_individualId
,
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']);
3491 $mut->checkMailLog([
3492 'Annual CiviCRM meet',
3494 'This is a confirmation that your registration has been received and your status has been updated to Registered.',
3495 'First Name: Logged In',
3499 ], ['Back end title', 'title_post_2', 'title_post_3']);
3504 * Test membership is renewed when transaction completed.
3506 * @throws \API_Exception
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'],
3516 $this->assertEquals(date('Y-m-d', strtotime('yesterday')), $membership['end_date']);
3518 $this->createSubsequentPendingMembership();
3519 $this->callAPISuccess('Payment', 'create', [
3520 'contribution_id' => $this->getContributionID('second'),
3521 'total_amount' => 20,
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(),
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);
3539 * Test if renewal activity is create after changing Pending contribution to
3540 * Completed via offline
3542 * @throws \CRM_Core_Exception|\CiviCRM_API3_Exception
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',
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,
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',
3585 $form->postProcess();
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',
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',
3601 $this->assertEquals(1, $activity['count']);
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',
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()]);
3617 //Update it to Failed.
3618 $form->_params
['id'] = $this->getContributionID('second');
3619 $form->_params
['contribution_status_id'] = 4;
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']);
3628 * Test membership is renewed for 2 terms when transaction completed based on the line item having 2 terms as qty.
3630 * Also check that altering the qty for the most recent contribution results in repeattransaction picking it up.
3632 public function testCompleteTransactionMembershipPriceSetTwoTerms(): void
{
3633 $this->createPriceSetWithPage('membership');
3634 $this->createInitialPaidMembership();
3635 $this->createSubsequentPendingMembership();
3637 $this->callAPISuccess('Payment', 'create', [
3638 'contribution_id' => $this->getContributionID('second'),
3639 'total_amount' => 20,
3642 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->getMembershipID()]);
3643 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 2 years')), $membership['end_date']);
3645 $paymentProcessorID = $this->paymentProcessorAuthorizeNetCreate();
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']);
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']);
3661 public function cleanUpAfterPriceSets() {
3662 $this->quickCleanUpFinancialEntities();
3663 $this->contactDelete($this->_ids
['contact']);
3667 * Set up a pending transaction with a specific price field id.
3669 * @param int $priceFieldValueID
3670 * @param string $key
3671 * @param array $contributionParams
3672 * @param array $lineParams
3673 * @param array $membershipParams
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';
3687 $contribution = $this->callAPISuccess('Order', 'create', array_merge([
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,
3696 'contribution_page_id' => $this->_ids
['contribution_page'],
3701 'price_field_id' => $this->_ids
['price_field'][0],
3703 'entity_table' => 'civicrm_membership',
3706 'financial_type_id' => 1,
3707 'price_field_value_id' => $priceFieldValueID,
3710 'params' => $membershipParams,
3713 ], $contributionParams));
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']]);
3721 * Test sending a mail via the API.
3723 * @throws \CRM_Core_Exception
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,
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',
3744 $mut->checkMailLog([
3746 'Contribution Information',
3751 $this->checkCreditCardDetails($mut, $order['id']);
3753 $tplVars = CRM_Core_Smarty
::singleton()->get_template_vars();
3754 $this->assertEquals('bob', $tplVars['billingName']);
3758 * Test sending a mail via the API.
3759 * This simulates webform_civicrm using pay later contribution page
3761 * @throws \CRM_Core_Exception
3762 * @throws \CiviCRM_API3_Exception
3764 public function testSendConfirmationPayLater(): void
{
3765 $mut = new CiviMailUtils($this, TRUE);
3766 // Create contribution page
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',
3776 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', $pageParams);
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',
3790 'entity_table' => 'civicrm_contribution',
3791 'label' => 'My lineitem label',
3793 'unit_price' => '10.00',
3794 'line_total' => '10.00',
3803 civicrm_api3('contribution', 'sendconfirmation', [
3804 'id' => $contribution['id'],
3805 'receipt_from_email' => 'api@civicrm.org',
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') {
3817 // Retrieve mail & check it has the pay_later_receipt info
3818 $mut->getMostRecentEmail('raw');
3819 $mut->checkMailLog([
3821 $pageParams['pay_later_receipt'],
3825 $this->checkReceiptDetails($mut, $contributionPage['id'], $contribution['id'], $pageParams);
3830 * Check credit card details in sent mail via API
3832 * @param CiviMailUtils $mut
3833 * @param int $contributionID Contribution ID
3835 * @throws \CRM_Core_Exception
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
,
3844 $mut->checkMailLog([
3846 'Billing Name and Address',
3848 'anthony_anderson@civicrm.org',
3855 * Check receipt details in sent mail via API
3857 * @param CiviMailUtils $mut
3858 * @param int $pageID Page ID
3859 * @param int $contributionID Contribution ID
3860 * @param array $pageParams
3862 * @throws \CRM_Core_Exception
3864 public function checkReceiptDetails($mut, $pageID, $contributionID, $pageParams): void
{
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'],
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.',
3879 $this->callAPISuccess('ContributionPage', 'create', array_merge([
3881 'is_email_receipt' => 1,
3884 $this->callAPISuccess('contribution', 'sendconfirmation', array_merge([
3885 'id' => $contributionID,
3886 'payment_processor_id' => $this->paymentProcessorID
,
3887 ], $customReceipt));
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));
3895 * Test sending a mail via the API.
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',
3904 $this->_eventID
= $event['id'];
3905 $participantParams = [
3906 'contact_id' => $this->_individualId
,
3907 'event_id' => $this->_eventID
,
3910 // to ensure it matches later on
3911 'register_date' => '2007-07-21 00:00:00',
3912 'source' => 'Online Event Registration: API Testing',
3915 $participant = $this->callAPISuccess('participant', 'create', $participantParams);
3916 $this->callAPISuccess('participant_payment', 'create', [
3917 'participant_id' => $participant['id'],
3918 'contribution_id' => $contribution['id'],
3920 $this->callAPISuccess('contribution', 'sendconfirmation', [
3921 'id' => $contribution['id'],
3922 'receipt_from_email' => 'api@civicrm.org',
3925 $mut->checkMailLog([
3926 'Annual CiviCRM meet',
3928 'To: "Mr. Anthony Anderson II" <anthony_anderson@civicrm.org>',
3934 * This function does a GET & compares the result against the $params.
3936 * Use as a double check on Creates.
3938 * @param array $params
3940 * @param bool $delete
3942 * @throws \CRM_Core_Exception
3944 public function contributionGetnCheck(array $params, int $id, bool $delete = TRUE): void
{
3945 $contribution = $this->callAPISuccess('Contribution', 'Get', [
3947 'return' => array_merge(['contribution_source'], array_keys($params)),
3950 $this->callAPISuccess('contribution', 'delete', ['id' => $id]);
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));
3965 * Create a pending contribution & linked pending pledge record.
3967 * @param int $installments
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),
3978 $paymentID = $this->callAPISuccessGetValue('PledgePayment', [
3979 'options' => ['limit' => 1],
3982 $this->callAPISuccess('PledgePayment', 'create', [
3984 'contribution_id' =>
3985 $contribution['id'],
3986 'status_id' => 'Pending',
3987 'scheduled_amount' => (500 / $installments),
3990 return (int) $contribution['id'];
3994 * Create a pending contribution & linked pending participant record (along
3997 * @throws \CRM_Core_Exception
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,
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',
4017 return $contribution['id'];
4021 * Get financial transaction amount.
4023 * @param int $contId
4025 * @return null|string
4027 public function _getFinancialTrxnAmount($contId) {
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}";
4035 return CRM_Core_DAO
::singleValueQuery($query);
4039 * @param int $contId
4041 * @return null|string
4043 public function _getFinancialItemAmount($contId) {
4044 $lineItem = key(CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution'));
4047 FROM civicrm_financial_item
4048 WHERE entity_table = 'civicrm_line_item'
4049 AND entity_id = {$lineItem}";
4050 return CRM_Core_DAO
::singleValueQuery($query);
4054 * @param int $contId
4057 public function _checkFinancialItem($contId, $context) {
4058 if ($context !== 'paylater') {
4060 'entity_id' => $contId,
4061 'entity_table' => 'civicrm_contribution',
4063 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($params, TRUE));
4065 'financial_trxn_id' => $trxn['financial_trxn_id'],
4066 'entity_table' => 'civicrm_financial_item',
4068 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
4070 'id' => $entityTrxn['entity_id'],
4073 if ($context === 'paylater') {
4074 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution');
4075 foreach ($lineItems as $key => $item) {
4077 'entity_id' => $key,
4078 'entity_table' => 'civicrm_line_item',
4080 $compareParams = ['status_id' => 1];
4081 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4084 elseif ($context === 'refund') {
4087 'financial_account_id' => 1,
4091 elseif ($context === 'cancelPending') {
4094 'financial_account_id' => 1,
4098 elseif ($context === 'changeFinancial') {
4099 $lineKey = key(CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution'));
4101 'entity_id' => $lineKey,
4105 'financial_account_id' => 1,
4107 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4109 'financial_account_id' => 3,
4110 'entity_id' => $lineKey,
4116 if ($context !== 'paylater') {
4117 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4122 * Check correct financial transaction entries were created for the change in payment instrument.
4124 * @param int $contributionID
4125 * @param int $originalInstrumentID
4126 * @param int $newInstrumentID
4127 * @param int $amount
4129 public function checkFinancialTrxnPaymentInstrumentChange($contributionID, $originalInstrumentID, $newInstrumentID, $amount = 100) {
4131 $entityFinancialTrxns = $this->getFinancialTransactionsForContribution($contributionID);
4133 $originalTrxnParams = [
4134 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($originalInstrumentID),
4135 'payment_instrument_id' => $originalInstrumentID,
4136 'amount' => $amount,
4140 $reversalTrxnParams = [
4141 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($originalInstrumentID),
4142 'payment_instrument_id' => $originalInstrumentID,
4143 'amount' => -$amount,
4148 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($newInstrumentID),
4149 'payment_instrument_id' => $newInstrumentID,
4150 'amount' => $amount,
4154 foreach ([$originalTrxnParams, $reversalTrxnParams, $newTrxnParams] as $index => $transaction) {
4155 $entityFinancialTrxn = $entityFinancialTrxns[$index];
4156 $this->assertEquals($entityFinancialTrxn['amount'], $transaction['amount']);
4158 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', [
4159 'id' => $entityFinancialTrxn['financial_trxn_id'],
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']);
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'])));
4176 * Check financial transaction.
4178 * @todo break this down into sensible functions - most calls to it only use a few lines out of the big if.
4180 * @param array $contribution
4181 * @param string $context
4182 * @param int $instrumentId
4183 * @param array $extraParams
4185 public function _checkFinancialTrxn($contribution, $context, $instrumentId = NULL, $extraParams = []) {
4186 $financialTrxns = $this->getFinancialTransactionsForContribution($contribution['id']);
4187 $trxn = array_pop($financialTrxns);
4190 'id' => $trxn['financial_trxn_id'],
4192 if ($context === 'payLater') {
4195 'from_financial_account_id' => CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is'),
4198 elseif ($context === 'refund') {
4200 'to_financial_account_id' => 6,
4201 'total_amount' => -100,
4203 'trxn_date' => '2015-01-01 09:00:00',
4204 'trxn_id' => 'the refund',
4207 elseif ($context === 'cancelPending') {
4209 'to_financial_account_id' => 7,
4210 'total_amount' => -100,
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
4220 'entity_id' => $contribution['id'],
4221 'entity_table' => 'civicrm_contribution',
4224 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
4226 'id' => $trxn['financial_trxn_id'],
4228 if (empty($extraParams)) {
4230 'total_amount' => -100,
4234 elseif ($context !== 'changeFinancial') {
4236 'total_amount' => 100,
4240 if ($context === 'paymentInstrument') {
4241 $compareParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($instrumentId);
4242 $compareParams['payment_instrument_id'] = $instrumentId;
4245 $compareParams['to_financial_account_id'] = 12;
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;
4257 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $params, array_merge($compareParams, $extraParams));
4263 public function _addPaymentInstrument() {
4264 $gId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'payment_instrument', 'id', 'name');
4266 'option_group_id' => $gId,
4267 'label' => 'Test Card',
4268 'name' => 'Test Card',
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,
4281 CRM_Financial_BAO_FinancialTypeAccount
::add($financialParams);
4282 $this->assertNotEmpty($optionValue['values'][$optionValue['id']]['value']);
4283 return $optionValue['values'][$optionValue['id']]['value'];
4286 public function deletedAddedPaymentInstrument() {
4287 $result = $this->callAPISuccess('OptionValue', 'get', [
4288 'option_group_id' => 'payment_instrument',
4289 'name' => 'Test Card',
4293 if ($id = CRM_Utils_Array
::value('id', $result)) {
4294 $this->callAPISuccess('OptionValue', 'delete', ['id' => $id]);
4299 * Set up the basic recurring contribution for tests.
4301 * @param array $generalParams
4302 * Parameters that can be merged into the recurring AND the contribution.
4304 * @param array $recurParams
4305 * Parameters to merge into the recur only.
4308 * @throws \CRM_Core_Exception
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',
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(
4325 'contribution_recur_id' => $contributionRecur['id'],
4326 'contribution_status_id' => 'Pending',
4328 $contributionParams['api.Payment.create'] = ['total_amount' => $contributionParams['total_amount']];
4329 $originalContribution = $this->callAPISuccess('Order', 'create', $contributionParams);
4330 return $originalContribution;
4334 * Set up a basic auto-renew membership for tests.
4336 * @param array $generalParams
4337 * Parameters that can be merged into the recurring AND the contribution.
4339 * @param array $recurParams
4340 * Parameters to merge into the recur only.
4343 * @throws \CRM_Core_Exception
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',
4356 'email' => 'tmctesterson@example.com',
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,
4369 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4370 'contact_id' => $newContact['id'],
4371 'installments' => '12',
4372 'frequency_interval' => '1',
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));
4381 $originalContribution = $this->callAPISuccess('Order', 'create', array_merge(
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,
4393 'membership_type_id' => $membershipType['id'],
4394 'financial_type_id' => 'Member Dues',
4395 'line_total' => $generalParams['total_amount'] ??
100,
4399 'contact_id' => $newContact['id'],
4400 'contribution_recur_id' => $contributionRecur['id'],
4401 'membership_type_id' => $membershipType['id'],
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);
4414 return [$originalContribution, $membership];
4418 * Set up a repeat transaction.
4420 * @param array $recurParams
4421 * @param string $flag
4422 * @param array $contributionParams
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',
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,
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'],
4447 $originalContribution = $this->callAPISuccessGetSingle('Contribution', ['contribution_recur_id' => $contributionRecur['id'], 'return' => 'id']);
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'],
4459 $originalContribution['contribution_recur_id'] = $contributionRecur['id'];
4460 $originalContribution['payment_processor_id'] = $paymentProcessorID;
4461 return $originalContribution;
4465 * Common set up routine.
4468 * @throws \CRM_Core_Exception
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);
4478 * Test repeat contribution uses the Payment Processor' payment_instrument setting.
4480 * @throws \CRM_Core_Exception
4482 public function testRepeatTransactionWithNonCreditCardDefault() {
4483 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
4484 'contact_id' => $this->_individualId
,
4485 'installments' => '12',
4486 'frequency_interval' => '1',
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
,
4494 $contribution1 = $this->callAPISuccess('contribution', 'create', array_merge(
4496 ['contribution_recur_id' => $contributionRecur['id'], 'payment_instrument_id' => 2])
4498 $contribution2 = $this->callAPISuccess('contribution', 'repeattransaction', [
4499 'contribution_status_id' => 'Completed',
4500 'trxn_id' => 'blah',
4501 'original_contribution_id' => $contribution1,
4503 $this->assertEquals('Debit Card', CRM_Contribute_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $contribution2['values'][$contribution2['id']]['payment_instrument_id']));
4507 * CRM-20008 Tests repeattransaction creates pending membership.
4509 * @throws \CRM_Core_Exception
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',
4518 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4519 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
4520 'contribution_status_id' => 'Pending',
4523 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
4524 'id' => $membership['id'],
4525 'return' => 'status_id',
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'],
4532 $this->assertEquals(2, $membershipPayments['count']);
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',
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']);
4545 * Test sending a mail via the API.
4547 * @throws \CRM_Core_Exception
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',
4557 $mut->checkMailLog([
4558 'From: CiviCRM LLC <api@civicrm.org>',
4559 'Contribution Information',
4567 * Test sending a mail via the API.
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'],
4576 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4577 $mut->checkMailLog([
4578 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4579 'Contribution Information',
4587 * Test sending a mail via the API.
4589 * @throws \CRM_Core_Exception
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',
4598 'original_contribution_id' => $contribution['id'],
4600 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4601 $mut->checkMailLog([
4602 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4603 'Contribution Information',
4612 * Test sending a mail via the API.
4614 * @throws \CRM_Core_Exception
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',
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,
4631 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4634 'contribution_recur_id' => $contributionRecur['id'],
4635 'contribution_page_id' => $contributionPage['id'],
4638 $this->callAPISuccess('Contribution', 'repeattransaction', [
4639 'contribution_status_id' => 'Completed',
4641 'original_contribution_id' => $originalContribution['id'],
4644 $mut->checkMailLog([
4645 'From: CiviCRM LLC <contributionpage@civicrm.org>',
4646 'Contribution Information',
4654 * Test sending a mail via the API.
4656 * @throws \CRM_Core_Exception
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']]);
4665 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => CRM_Core_Config
::domainID()]);
4666 $this->callAPISuccess('contribution', 'repeattransaction', [
4667 'contribution_status_id' => 'Completed',
4669 'original_contribution_id' => $originalContribution['id'],
4671 $mut->checkMailLog([
4672 'From: ' . $domain['name'] . ' <' . $domain['domain_email'] . '>',
4673 'Contribution Information',
4681 * Create a Contribution Page with is_email_receipt = TRUE.
4683 * @param array $params
4684 * Params to overwrite with.
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,
4698 return $contributionPage;
4702 * function to test card_type and pan truncation.
4704 * @throws \CRM_Core_Exception
4706 public function testCardTypeAndPanTruncation() {
4707 $creditCardTypeIDs = array_flip(CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'));
4708 $contactId = $this->individualCreate();
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,
4718 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4719 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contribution['id'], 'DESC');
4720 $financialTrxn = $this->callAPISuccessGetSingle(
4723 'id' => $lastFinancialTrxnId['financialTrxnId'],
4724 'return' => ['card_type_id', 'pan_truncation'],
4727 $this->assertEquals(CRM_Utils_Array
::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Visa']);
4728 $this->assertEquals(CRM_Utils_Array
::value('pan_truncation', $financialTrxn), 4567);
4730 'id' => $contribution['id'],
4731 'pan_truncation' => 2345,
4732 'card_type_id' => $creditCardTypeIDs['Amex'],
4734 $this->callAPISuccess('contribution', 'create', $params);
4735 $financialTrxn = $this->callAPISuccessGetSingle(
4738 'id' => $lastFinancialTrxnId['financialTrxnId'],
4739 'return' => ['card_type_id', 'pan_truncation'],
4742 $this->assertEquals(CRM_Utils_Array
::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Amex']);
4743 $this->assertEquals(CRM_Utils_Array
::value('pan_truncation', $financialTrxn), 2345);
4747 * Test repeat contribution uses non default currency
4749 * @see https://issues.civicrm.org/jira/projects/CRM/issues/CRM-20678
4750 * @throws \CRM_Core_Exception
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',
4759 $this->assertEquals('AUD', $contribution['values'][$contribution['id']]['currency']);
4763 * Get the financial items for the contribution.
4765 * @param int $contributionID
4768 * Array of associated financial items.
4770 protected function getFinancialTransactionsForContribution($contributionID) {
4772 'entity_id' => $contributionID,
4773 'entity_table' => 'civicrm_contribution',
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));
4782 * Test getunique api call for Contribution entity
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']);
4792 * Test Repeat Transaction Contribution with Tax amount.
4794 * https://lab.civicrm.org/dev/core/issues/806
4796 * @throws \CRM_Core_Exception
4798 public function testRepeatContributionWithTaxAmount(): void
{
4799 $this->enableTaxAndInvoicing();
4800 $financialType = $this->callAPISuccess('financial_type', 'create', [
4801 'name' => 'Test taxable financial Type',
4805 $this->addTaxAccountToFinancialType($financialType['id']);
4806 $contribution = $this->setUpRepeatTransaction(
4810 'financial_type_id' => $financialType['id'],
4813 $this->callAPISuccess('contribution', 'repeattransaction', [
4814 'original_contribution_id' => $contribution['id'],
4815 'contribution_status_id' => 'Completed',
4816 'trxn_id' => 'test',
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);
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);
4830 $this->callAPISuccessGetCount('Contribution', [], 2);
4833 public function testGetCurrencyOptions() {
4834 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4835 'field' => 'currency',
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',
4843 $this->assertEquals('$', $result['values']['USD']);
4844 $this->assertNotContains('US Dollar', $result['values']);
4848 * @throws \API_Exception
4849 * @throws \CRM_Core_Exception
4850 * @throws \Civi\API\Exception\UnauthorizedException
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', [
4857 'civicrmPostContributionCustom',
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']],
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']]);
4874 * Implement post hook.
4877 * @param string $objectName
4878 * @param int|null $objectId
4880 * @throws \CRM_Core_Exception
4882 public function civicrmPostContributionCustom(string $op, string $objectName, ?
int $objectId): void
{
4883 if ($objectName === 'Contribution' && $op === 'create') {
4884 $this->callAPISuccess('Contribution', 'create', [
4886 'custom_' . $this->ids
['CustomField']['int'] => 5,
4892 * Test that passing in label for an option value linked to a custom field
4895 * @see dev/core#1816
4897 * @throws \API_Exception
4898 * @throws \CRM_Core_Exception
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);
4908 * Test repeatTransaction with installments and next_sched_contribution_date
4910 * @dataProvider getRepeatTransactionNextSchedData
4912 * @param array $dataSet
4914 * @throws \CRM_Core_Exception
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(
4922 'contribution_status_id' => 'Completed',
4923 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4926 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4927 'contact_id' => $this->_individualId
,
4928 'frequency_interval' => '1',
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'],
4944 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4945 'id' => $contributionRecur['id'],
4946 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4948 // Check that next_sched_contribution_date is empty
4949 $this->assertEquals('', $contributionRecur['next_sched_contribution_date'] ??
'');
4951 $this->callAPISuccess('Contribution', 'repeattransaction', [
4952 'contribution_status_id' => 'Completed',
4953 'contribution_recur_id' => $contributionRecur['id'],
4954 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4956 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4957 'id' => $contributionRecur['id'],
4958 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
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']
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']);
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'],
4974 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4975 'id' => $contributionRecur['id'],
4976 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
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']
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'] ??
'');
4988 * Get dates for testing.
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.
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 = ''.
5001 $result['receive_date_includes_time_with_installments']['2012-01-01-1-month'] = [
5003 'start_date' => '2012-01-01',
5004 'frequency_interval' => 1,
5005 'installments' => '3',
5006 'frequency_unit' => 'month',
5010 'receive_date' => '2012-02-29 16:00:00',
5011 'expectedNextSched' => '2012-03-29 00:00:00',
5012 'expectedRecurStatus' => 'In Progress',
5015 'receive_date' => '2012-03-29 16:00:00',
5016 'expectedNextSched' => '',
5017 'expectedRecurStatus' => 'Completed',
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.
5026 $result['receive_date_includes_time_no_installments']['2012-01-01-1-month'] = [
5028 'start_date' => '2012-01-01',
5029 'frequency_interval' => 1,
5030 'frequency_unit' => 'month',
5034 'receive_date' => '2012-02-29 16:00:00',
5035 'expectedNextSched' => '2012-03-29 00:00:00',
5036 'expectedRecurStatus' => 'In Progress',
5039 'receive_date' => '2012-03-29 16:00:00',
5040 'expectedNextSched' => '2012-04-29 00:00:00',
5041 'expectedRecurStatus' => 'In Progress',
5049 * Make sure that recording a payment doesn't alter the receive_date of a
5050 * pending contribution.
5052 public function testPaymentDontChangeReceiveDate(): void
{
5054 'contact_id' => $this->_individualId
,
5055 'total_amount' => 100,
5056 'receive_date' => '2020-02-02',
5057 'contribution_status_id' => 'Pending',
5059 $contributionID = $this->contributionCreate($params);
5061 'contribution_id' => $contributionID,
5062 'total_amount' => 100,
5063 'trxn_date' => '2020-03-04',
5065 $this->callAPISuccess('payment', 'create', $paymentParams);
5067 //check if contribution status is set to "Completed".
5068 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
5069 'id' => $contributionID,
5071 $this->assertEquals('2020-02-02 00:00:00', $contribution['receive_date']);
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
5079 public function testPaymentVerifyPaymentInstrumentChange() {
5080 // Create Pending contribution with pay later mode, with payment instrument Check
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',
5089 $contributionID = $this->contributionCreate($params);
5091 // Record the the Payment with instrument other than Check, e.g EFT
5093 'contribution_id' => $contributionID,
5094 'total_amount' => 50,
5095 'trxn_date' => '2020-03-04',
5096 'payment_instrument_id' => 'EFT',
5098 $this->callAPISuccess('payment', 'create', $paymentParams);
5100 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
5101 'id' => $contributionID,
5103 // payment status should be 'Partially paid'
5104 $this->assertEquals('Partially paid', $contribution['contribution_status']);
5106 // Record the the Payment with instrument other than Check, e.g Cash (pay all remaining amount)
5108 'contribution_id' => $contributionID,
5109 'total_amount' => 50,
5110 'trxn_date' => '2020-03-04',
5111 'payment_instrument_id' => 'Cash',
5113 $this->callAPISuccess('payment', 'create', $paymentParams);
5115 //check if contribution Payment Instrument (Payment Method) is is set to "Cash".
5116 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
5117 'id' => $contributionID,
5119 $this->assertEquals('Cash', $contribution['payment_instrument']);
5120 $this->assertEquals('Completed', $contribution['contribution_status']);
5124 * Test the "clean money" functionality.
5126 public function testCleanMoney() {
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',
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']);
5146 * Create a price set with a quick config price set.
5148 * The params to use this look like
5150 * ['price_' . $this->ids['PriceField']['basic'] => $this->ids['PriceFieldValue']['basic']]
5152 * @param array $contributionPageParams
5156 * @throws \API_Exception
5157 * @throws \CRM_Core_Exception
5158 * @throws \Civi\API\Exception\UnauthorizedException
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,
5177 'amount_block_is_active' => 1,
5178 'is_billing_required' => 0,
5179 ], $contributionPageParams))['id'];
5181 $priceSetID = PriceSet
::create()->setValues([
5182 'name' => 'quick config set',
5183 'title' => 'basic price set',
5184 'is_quick_config' => TRUE,
5186 ])->execute()->first()['id'];
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',
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;
5208 * Get the created contribution ID.
5210 * @param string $key
5214 protected function getContributionID(string $key = 'first'): int {
5215 return (int) $this->ids
['contribution'][$key];
5219 * Get the created contribution ID.
5223 protected function getMembershipID(): int {
5224 return (int) $this->_ids
['membership'];
5228 * Create a paid membership for renewal tests.
5230 protected function createSubsequentPendingMembership(): void
{
5231 $this->setUpPendingContribution($this->_ids
['price_field_value'][1], 'second', [], [], [
5232 'id' => $this->getMembershipID(),
5237 * Create a paid membership for renewal tests.
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,