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\PriceField
;
15 use Civi\Api4\PriceFieldValue
;
16 use Civi\Api4\PriceSet
;
19 * Test APIv3 civicrm_contribute_* functions
21 * @package CiviCRM_APIv3
22 * @subpackage API_Contribution
25 class api_v3_ContributionTest
extends CiviUnitTestCase
{
27 use CRMTraits_Profile_ProfileTrait
;
28 use CRMTraits_Custom_CustomDataTrait
;
29 use CRMTraits_Financial_OrderTrait
;
30 use CRMTraits_Financial_TaxTrait
;
31 use CRMTraits_Financial_PriceSetTrait
;
33 protected $_individualId;
34 protected $_contribution;
35 protected $_financialTypeId = 1;
36 protected $entity = 'Contribution';
39 protected $_pageParams = [];
42 * Payment processor ID (dummy processor).
46 protected $paymentProcessorID;
49 * Parameters to create payment processor.
53 protected $_processorParams = [];
56 * ID of created event.
68 * Should financials be checked after the test but before tear down.
72 protected $isValidateFinancialsOnPostAssert = TRUE;
77 public function setUp(): void
{
80 $this->_apiversion
= 3;
81 $this->_individualId
= $this->individualCreate();
83 'contact_id' => $this->_individualId
,
84 'receive_date' => '20120511',
85 'total_amount' => 100.00,
86 'financial_type_id' => $this->_financialTypeId
,
87 'non_deductible_amount' => 10.00,
89 'net_amount' => 95.00,
91 'contribution_status_id' => 1,
93 $this->_processorParams
= [
96 'payment_processor_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', 'Dummy'),
97 'financial_account_id' => 12,
100 'url_site' => 'http://dummy.com',
101 'url_recur' => 'http://dummy.com',
104 $this->paymentProcessorID
= $this->processorCreate();
105 $this->_pageParams
= [
106 'title' => 'Test Contribution Page',
107 'financial_type_id' => 1,
109 'financial_account_id' => 1,
110 'payment_processor' => $this->paymentProcessorID
,
112 'is_allow_other_amount' => 1,
114 'max_amount' => 1000,
119 * Clean up after each test.
121 * @throws \API_Exception
122 * @throws \CRM_Core_Exception
124 public function tearDown(): void
{
125 $this->quickCleanUpFinancialEntities();
126 $this->quickCleanup(['civicrm_uf_match'], TRUE);
127 $financialAccounts = $this->callAPISuccess('FinancialAccount', 'get', ['return' => 'name']);
128 foreach ($financialAccounts['values'] as $financialAccount) {
129 if ($financialAccount['name'] === 'Test Tax financial account ' ||
$financialAccount['name'] === 'Test taxable financial Type') {
130 $entityFinancialTypes = $this->callAPISuccess('EntityFinancialAccount', 'get', [
131 'financial_account_id' => $financialAccount['id'],
133 foreach ($entityFinancialTypes['values'] as $entityFinancialType) {
134 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialType['id']]);
136 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
139 $this->restoreUFGroupOne();
146 public function testGetContribution(): void
{
147 $this->enableTaxAndInvoicing();
149 'contact_id' => $this->_individualId
,
150 'receive_date' => '2010-01-20',
151 'total_amount' => 100.00,
152 'financial_type_id' => $this->_financialTypeId
,
153 'non_deductible_amount' => 10.00,
154 'fee_amount' => 5.00,
155 'net_amount' => 95.00,
157 'invoice_id' => 78910,
159 'contribution_status_id' => 'Completed',
161 $this->_contribution
= $this->callAPISuccess('contribution', 'create', $p);
164 'contribution_id' => $this->_contribution
['id'],
165 'return' => array_merge(['invoice_number', 'contribution_source'], array_keys($p)),
168 $contributions = $this->callAPIAndDocument('Contribution', 'get', $params, __FUNCTION__
, __FILE__
);
170 $this->assertEquals(1, $contributions['count']);
171 $contribution = $contributions['values'][$contributions['id']];
172 $this->assertEquals($this->_individualId
, $contribution['contact_id']);
173 $this->assertEquals(1, $contribution['financial_type_id']);
174 $this->assertEquals(100.00, $contribution['total_amount']);
175 $this->assertEquals(10.00, $contribution['non_deductible_amount']);
176 $this->assertEquals(5.00, $contribution['fee_amount']);
177 $this->assertEquals(95.00, $contribution['net_amount']);
178 $this->assertEquals(23456, $contribution['trxn_id']);
179 $this->assertEquals(78910, $contribution['invoice_id']);
180 $this->assertRegExp('/INV_\d+/', $contribution['invoice_number']);
181 $this->assertEquals('SSF', $contribution['contribution_source']);
182 $this->assertEquals('Completed', $contribution['contribution_status']);
183 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
184 $p['trxn_id'] = '3847';
185 $p['invoice_id'] = '3847';
187 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
189 // Now we have 2 - test getcount.
190 $contribution = $this->callAPISuccess('contribution', 'getcount');
191 $this->assertEquals(2, $contribution);
192 // Test id only format.
193 $contribution = $this->callAPISuccess('contribution', 'get', [
194 'id' => $this->_contribution
['id'],
195 'format.only_id' => 1,
197 $this->assertEquals($this->_contribution
['id'], $contribution, print_r($contribution, TRUE));
198 // Test id only format.
199 $contribution = $this->callAPISuccess('contribution', 'get', [
200 'id' => $contribution2['id'],
201 'format.only_id' => 1,
203 $this->assertEquals($contribution2['id'], $contribution);
205 $contribution = $this->callAPISuccess('contribution', 'get', [
206 'id' => $this->_contribution
['id'],
208 $this->assertEquals(1, $contribution['count']);
210 // Test get by contact id works.
211 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId
]);
213 $this->assertEquals(2, $contribution['count']);
214 $this->callAPISuccess('Contribution', 'Delete', [
215 'id' => $this->_contribution
['id'],
217 $this->callAPISuccess('Contribution', 'Delete', [
218 'id' => $contribution2['id'],
223 * Test that test contributions can be retrieved.
225 * @throws \CRM_Core_Exception
227 public function testGetTestContribution(): void
{
228 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['is_test' => 1]));
229 $this->callAPISuccessGetSingle('Contribution', ['is_test' => 1]);
233 * Test Creating a check contribution with original check_number field
235 * @throws \CRM_Core_Exception
237 public function testCreateCheckContribution(): void
{
238 $params = $this->_params
;
239 $params['contribution_check_number'] = 'bouncer';
240 $params['payment_instrument_id'] = 'Check';
241 $params['cancel_date'] = 'yesterday';
242 $params['receipt_date'] = 'yesterday';
243 $params['thankyou_date'] = 'yesterday';
244 $params['revenue_recognition_date'] = 'yesterday';
245 $params['amount_level'] = 'Unreasonable';
246 $params['cancel_reason'] = 'You lose sucker';
247 $params['creditnote_id'] = 'sudo rm -rf';
248 $address = $this->callAPISuccess('Address', 'create', [
249 'street_address' => 'Knockturn Alley',
250 'contact_id' => $this->_individualId
,
251 'location_type_id' => 'Home',
253 $params['address_id'] = $address['id'];
254 $contributionPage = $this->contributionPageCreate();
255 $params['contribution_page_id'] = $contributionPage['id'];
256 $params['campaign_id'] = $this->campaignCreate();
257 $contributionID = $this->contributionCreate($params);
258 $getResult = $this->callAPISuccess('Contribution', 'get', [
259 'id' => $contributionID,
260 'return' => 'check_number',
261 ])['values'][$contributionID];
262 $this->assertEquals('bouncer', $getResult['check_number']);
263 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
264 'entity_id' => $contributionID,
265 'entity_table' => 'civicrm_contribution',
266 'return' => 'financial_trxn_id',
268 foreach ($entityFinancialTrxn['values'] as $eft) {
269 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'get', [
270 'id' => $eft['financial_trxn_id'],
271 'return' => 'check_number',
273 $this->assertEquals('bouncer', $financialTrxn['values'][$financialTrxn['id']]['check_number']);
278 * Test the 'return' param works for all fields.
280 public function testGetContributionReturnFunctionality(): void
{
281 $params = $this->_params
;
282 $params['contribution_check_number'] = 'bouncer';
283 $params['payment_instrument_id'] = 'Check';
284 $params['cancel_date'] = 'yesterday';
285 $params['receipt_date'] = 'yesterday';
286 $params['thankyou_date'] = 'yesterday';
287 $params['revenue_recognition_date'] = 'yesterday';
288 $params['amount_level'] = 'Unreasonable';
289 $params['cancel_reason'] = 'You lose sucker';
290 $params['creditnote_id'] = 'sudo rm -rf';
291 $address = $this->callAPISuccess('Address', 'create', [
292 'street_address' => 'Knockturn Alley',
293 'contact_id' => $this->_individualId
,
294 'location_type_id' => 'Home',
296 $params['address_id'] = $address['id'];
297 $contributionPage = $this->contributionPageCreate();
298 $params['contribution_page_id'] = $contributionPage['id'];
299 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
300 'contact_id' => $this->_individualId
,
301 'frequency_interval' => 1,
304 $params['contribution_recur_id'] = $contributionRecur['id'];
306 $params['campaign_id'] = $this->campaignCreate();
308 $contributionID = $this->contributionCreate($params);
310 // update contribution with invoice number
311 $params = array_merge($params, [
312 'id' => $contributionID,
313 'invoice_number' => Civi
::settings()->get('invoice_prefix') . $contributionID,
315 'invoice_id' => 6789,
317 $contributionID = $this->contributionCreate($params);
319 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID]);
320 $this->assertEquals('bouncer', $contribution['check_number']);
321 $this->assertEquals('bouncer', $contribution['contribution_check_number']);
323 $fields = CRM_Contribute_BAO_Contribution
::fields();
324 // Do not check for tax_amount as this test has not enabled invoicing
325 // & hence it is not reliable.
326 unset($fields['tax_amount']);
327 // Re-add these 2 to the fields to check. They were locked in but the metadata changed so we
328 // need to specify them.
329 $fields['address_id'] = $fields['contribution_address_id'];
330 $fields['check_number'] = $fields['contribution_check_number'];
333 'contribution_id', 'contribution_contact_id', 'financial_type_id', 'contribution_page_id',
334 'payment_instrument_id', 'receive_date', 'non_deductible_amount', 'total_amount',
335 'fee_amount', 'net_amount', 'trxn_id', 'invoice_id', 'currency', 'contribution_cancel_date', 'cancel_reason',
336 'receipt_date', 'thankyou_date', 'contribution_source', 'amount_level', 'contribution_recur_id',
337 'is_test', 'is_pay_later', 'contribution_status_id', 'address_id', 'check_number', 'contribution_campaign_id',
338 'creditnote_id', 'revenue_recognition_date', 'decoy',
340 $missingFields = array_diff($fieldsLockedIn, array_keys($fields));
341 // If any of the locked in fields disappear from the $fields array we need to make sure it is still
342 // covered as the test contract now guarantees them in the return array.
343 $this->assertEquals([28 => 'decoy'], $missingFields, 'A field which was covered by the test contract has changed.');
344 foreach ($fields as $fieldName => $fieldSpec) {
345 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => $fieldName]);
346 $returnField = $fieldName;
347 if ($returnField === 'contribution_contact_id') {
348 $returnField = 'contact_id';
350 $this->assertTrue((!empty($contribution[$returnField]) ||
$contribution[$returnField] === '0'), $returnField);
352 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
353 'entity_id' => $contributionID,
354 'entity_table' => 'civicrm_contribution',
355 'return' => 'financial_trxn_id',
357 foreach ($entityFinancialTrxn['values'] as $eft) {
358 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'get', ['id' => $eft['financial_trxn_id'], 'return' => 'check_number']);
359 $this->assertEquals('bouncer', $financialTrxn['values'][$financialTrxn['id']]['check_number']);
364 * Test cancel reason works as a filter.
366 * @throws \CRM_Core_Exception
368 public function testFilterCancelReason(): void
{
369 $params = $this->_params
;
370 $params['cancel_date'] = 'yesterday';
371 $params['cancel_reason'] = 'You lose sucker';
372 $this->callAPISuccess('Contribution', 'create', $params);
373 $params = $this->_params
;
374 $params['cancel_date'] = 'yesterday';
375 $params['cancel_reason'] = 'You are a winner';
376 $this->callAPISuccess('Contribution', 'create', $params);
377 $this->callAPISuccessGetCount('Contribution', ['cancel_reason' => 'You are a winner'], 1);
381 * We need to ensure previous tested api contract behaviour still works.
383 * @throws \CRM_Core_Exception
385 public function testGetContributionLegacyBehaviour(): void
{
387 'contact_id' => $this->_individualId
,
388 'receive_date' => '2010-01-20',
389 'total_amount' => 100.00,
390 'contribution_type_id' => $this->_financialTypeId
,
391 'non_deductible_amount' => 10.00,
392 'fee_amount' => 5.00,
393 'net_amount' => 95.00,
395 'invoice_id' => 78910,
397 'contribution_status_id' => 1,
399 $this->_contribution
= $this->callAPISuccess('Contribution', 'create', $p);
402 'contribution_id' => $this->_contribution
['id'],
403 'return' => array_keys($p),
405 $params['return'][] = 'financial_type_id';
406 $params['return'][] = 'contribution_source';
407 $contribution = $this->callAPISuccess('Contribution', 'get', $params);
409 $this->assertEquals(1, $contribution['count']);
410 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
411 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], $this->_financialTypeId
);
412 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_type_id'], $this->_financialTypeId
);
413 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
414 $this->assertEquals($contribution['values'][$contribution['id']]['non_deductible_amount'], 10.00);
415 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 5.00);
416 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 95.00);
417 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 23456);
418 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 78910);
419 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_source'], 'SSF');
420 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Completed');
422 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
423 $p['trxn_id'] = '3847';
424 $p['invoice_id'] = '3847';
426 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
428 // now we have 2 - test getcount
429 $contribution = $this->callAPISuccess('contribution', 'getcount', []);
430 $this->assertEquals(2, $contribution);
431 //test id only format
432 $contribution = $this->callAPISuccess('contribution', 'get', [
433 'id' => $this->_contribution
['id'],
434 'format.only_id' => 1,
436 $this->assertEquals($this->_contribution
['id'], $contribution, print_r($contribution, TRUE));
437 //test id only format
438 $contribution = $this->callAPISuccess('contribution', 'get', [
439 'id' => $contribution2['id'],
440 'format.only_id' => 1,
442 $this->assertEquals($contribution2['id'], $contribution);
443 $contribution = $this->callAPISuccess('contribution', 'get', [
444 'id' => $this->_contribution
['id'],
447 $this->assertEquals(1, $contribution['count']);
448 // $this->assertEquals($this->_contribution['id'], $contribution['id'] ) ;
449 //test get by contact id works
450 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId
]);
452 $this->assertEquals(2, $contribution['count']);
453 $this->callAPISuccess('Contribution', 'Delete', [
454 'id' => $this->_contribution
['id'],
456 $this->callAPISuccess('Contribution', 'Delete', [
457 'id' => $contribution2['id'],
462 * Create an contribution_id=FALSE and financial_type_id=Donation.
464 public function testCreateEmptyContributionIDUseDonation() {
466 'contribution_id' => FALSE,
469 'check_permissions' => FALSE,
470 'financial_type_id' => 'Donation',
472 $this->callAPISuccess('contribution', 'create', $params);
476 * Check with complete array + custom field.
478 * Note that the test is written on purpose without any
479 * variables specific to participant so it can be replicated into other entities
480 * and / or moved to the automated test suite
482 * @throws \CRM_Core_Exception
484 public function testCreateWithCustom(): void
{
485 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, __FILE__
);
487 $params = $this->_params
;
488 $params['custom_' . $ids['custom_field_id']] = 'custom string';
490 $result = $this->callAPIAndDocument($this->entity
, 'create', $params, __FUNCTION__
, __FILE__
);
491 $this->assertEquals($result['id'], $result['values'][$result['id']]['id']);
492 $check = $this->callAPISuccess($this->entity
, 'get', [
493 'return.custom_' . $ids['custom_field_id'] => 1,
494 'id' => $result['id'],
496 $this->assertEquals('custom string', $check['values'][$check['id']]['custom_' . $ids['custom_field_id']]);
500 * Check with complete array + custom field.
502 * Note that the test is written on purpose without any
503 * variables specific to participant so it can be replicated into other
504 * entities and / or moved to the automated test suite
506 * @throws \CRM_Core_Exception
508 public function testCreateGetFieldsWithCustom(): void
{
509 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, __FILE__
);
510 $idsContact = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, 'ContactTest.php');
511 $result = $this->callAPISuccess('Contribution', 'getfields', []);
512 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $result['values']);
513 $this->assertArrayNotHasKey('custom_' . $idsContact['custom_field_id'], $result['values']);
514 $this->customFieldDelete($ids['custom_field_id']);
515 $this->customGroupDelete($ids['custom_group_id']);
516 $this->customFieldDelete($idsContact['custom_field_id']);
517 $this->customGroupDelete($idsContact['custom_group_id']);
521 * Test creating a contribution without skipLineItems.
523 * @throws \CRM_Core_Exception
525 public function testCreateContributionNoLineItems(): void
{
526 // Turn off this validation as this test results in invalid
527 // financial entities.
528 $this->isValidateFinancialsOnPostAssert
= FALSE;
530 'contact_id' => $this->_individualId
,
531 'receive_date' => '20120511',
532 'total_amount' => 100.00,
533 'financial_type_id' => $this->_financialTypeId
,
534 'payment_instrument_id' => 1,
535 'non_deductible_amount' => 10.00,
536 'fee_amount' => 50.00,
537 'net_amount' => 90.00,
539 'invoice_id' => 67890,
541 'contribution_status_id' => 1,
545 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
546 $financialItems = $this->callAPISuccess('FinancialItem', 'get', ['return' => 'transaction_date']);
547 foreach ($financialItems['values'] as $financialItem) {
548 $this->assertEquals(date('Y-m-d H:i:s', strtotime($contribution['values'][$contribution['id']]['receive_date'])), date('Y-m-d H:i:s', strtotime($financialItem['transaction_date'])));
550 $this->callAPISuccessGetCount('LineItem', [
551 'entity_id' => $contribution['id'],
552 'entity_table' => 'civicrm_contribution',
558 * Test checks that passing in line items suppresses the create mechanism.
560 * @throws \CRM_Core_Exception
562 public function testCreateContributionChainedLineItems(): void
{
564 'contact_id' => $this->_individualId
,
565 'receive_date' => '20120511',
566 'total_amount' => 100.00,
567 'financial_type_id' => $this->_financialTypeId
,
568 'payment_instrument_id' => 1,
569 'non_deductible_amount' => 10.00,
570 'fee_amount' => 50.00,
571 'net_amount' => 90.00,
573 'invoice_id' => 67890,
575 'contribution_status_id' => 'Pending',
577 'api.line_item.create' => [
579 'price_field_id' => 1,
581 'line_total' => '20',
582 'unit_price' => '10',
585 'price_field_id' => 1,
587 'line_total' => '80',
588 'unit_price' => '80',
593 $description = 'Create Contribution with Nested Line Items.';
594 $subFile = 'CreateWithNestedLineItems';
595 $contribution = $this->callAPIAndDocument('Contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subFile);
597 $this->callAPISuccessGetCount('LineItem', [
598 'entity_id' => $contribution['id'],
599 'contribution_id' => $contribution['id'],
600 'entity_table' => 'civicrm_contribution',
606 * @throws \CRM_Core_Exception
608 public function testCreateContributionOffline(): void
{
610 'contact_id' => $this->_individualId
,
611 'receive_date' => '20120511',
612 'total_amount' => 100.00,
613 'financial_type_id' => 1,
615 'invoice_id' => 67890,
617 'contribution_status_id' => 1,
621 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
622 $this->assertEquals($this->_individualId
, $contribution['contact_id']);
623 $this->assertEquals(100.00, $contribution['total_amount']);
624 $this->assertEquals(1, $contribution['financial_type_id']);
625 $this->assertEquals(12345, $contribution['trxn_id']);
626 $this->assertEquals(67890, $contribution['invoice_id']);
627 $this->assertEquals('SSF', $contribution['source']);
628 $this->assertEquals(1, $contribution['contribution_status_id']);
629 $lineItems = $this->callAPISuccess('LineItem', 'get', [
630 'entity_id' => $contribution['id'],
631 'contribution_id' => $contribution['id'],
632 'entity_table' => 'civicrm_contribution',
634 'return' => ['entity_id', 'contribution_id'],
636 $this->assertEquals(1, $lineItems['count']);
637 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
638 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
639 $this->_checkFinancialRecords($contribution, 'offline');
640 $this->contributionGetnCheck($params, $contribution['id']);
644 * Test create with valid payment instrument.
646 * @throws \CRM_Core_Exception
648 public function testCreateContributionWithPaymentInstrument(): void
{
649 $params = $this->_params +
['payment_instrument' => 'EFT'];
650 $contribution = $this->callAPISuccess('contribution', 'create', $params);
651 $contribution = $this->callAPISuccess('contribution', 'get', [
653 'id' => $contribution['id'],
654 'return' => 'payment_instrument',
656 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
657 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
659 $this->callAPISuccess('Contribution', 'create', [
660 'id' => $contribution['id'],
661 'payment_instrument' => 'Credit Card',
663 $contribution = $this->callAPISuccess('Contribution', 'get', [
665 'id' => $contribution['id'],
666 'return' => 'payment_instrument',
668 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
669 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
673 * @throws \CRM_Core_Exception
675 public function testGetContributionByPaymentInstrument(): void
{
676 $params = $this->_params +
['payment_instrument' => 'EFT'];
677 $params2 = $this->_params +
['payment_instrument' => 'Cash'];
678 $this->callAPISuccess('contribution', 'create', $params);
679 $this->callAPISuccess('contribution', 'create', $params2);
680 $contribution = $this->callAPISuccess('Contribution', 'get', [
682 'contribution_payment_instrument' => 'Cash',
683 'return' => 'payment_instrument',
685 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
686 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
687 $this->assertEquals(1, $contribution['count']);
688 $contribution = $this->callAPISuccess('Contribution', 'get', ['sequential' => 1, 'payment_instrument' => 'Cash', 'return' => 'payment_instrument']);
689 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
690 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
691 $this->assertEquals(1, $contribution['count']);
692 $contribution = $this->callAPISuccess('Contribution', 'get', [
694 'payment_instrument_id' => 5,
695 'return' => 'payment_instrument',
697 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
698 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
699 $this->assertEquals(1, $contribution['count']);
700 $contribution = $this->callAPISuccess('Contribution', 'get', [
702 'payment_instrument' => 'EFT',
703 'return' => 'payment_instrument',
705 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
706 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
707 $this->assertEquals(1, $contribution['count']);
708 $contribution = $this->callAPISuccess('contribution', 'create', [
709 'id' => $contribution['id'],
710 'payment_instrument' => 'Credit Card',
711 'return' => 'payment_instrument',
713 $contribution = $this->callAPISuccess('Contribution', 'get', [
715 'id' => $contribution['id'],
716 'return' => 'payment_instrument',
718 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
719 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
720 $this->assertEquals(1, $contribution['count']);
724 * CRM-16227 introduces invoice_id as a parameter.
726 * @throws \CRM_Core_Exception
728 public function testGetContributionByInvoice(): void
{
729 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['invoice_id' => 'curly']));
730 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
), ['invoice_id' => 'churlish']);
731 $this->callAPISuccessGetCount('Contribution', [], 2);
732 $this->callAPISuccessGetCount('Contribution', ['invoice_id' => 'curly'], 1);
736 * Check the credit note retrieval is case insensitive.
738 * @throws \CRM_Core_Exception
740 public function testGetCreditNoteCaseInsensitive(): void
{
741 $this->contributionCreate(['contact_id' => $this->_individualId
]);
742 $this->contributionCreate(['creditnote_id' => 'cN1234', 'contact_id' => $this->_individualId
, 'invoice_id' => 91011, 'trxn_id' => 456]);
743 $contribution = $this->callAPISuccess('Contribution', 'getsingle', ['creditnote_id' => 'CN1234', 'return' => 'creditnote_id']);
744 $this->assertEquals('cN1234', $contribution['creditnote_id']);
748 * Test retrieval by total_amount works.
750 * @throws \CRM_Core_Exception
752 public function testGetContributionByTotalAmount(): void
{
753 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['total_amount' => '5']));
754 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['total_amount' => '10']));
755 $this->callAPISuccessGetCount('Contribution', ['total_amount' => 10], 1);
756 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 6]], 1);
757 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 0]], 2);
758 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => -5]], 2);
759 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['<' => 0]], 0);
760 $this->callAPISuccessGetCount('Contribution', [], 2);
764 * @dataProvider createLocalizedContributionDataProvider
766 * @param float|int|string $totalAmount
767 * @param string $decimalPoint
768 * @param string $thousandSeparator
769 * @param string $currency
770 * @param bool $expectedResult
772 * @throws \CRM_Core_Exception
774 public function testCreateLocalizedContribution($totalAmount, string $decimalPoint, string $thousandSeparator, string $currency, bool $expectedResult): void
{
775 $this->setDefaultCurrency($currency);
776 $this->setMonetaryDecimalPoint($decimalPoint);
777 $this->setMonetaryThousandSeparator($thousandSeparator);
780 'contact_id' => $this->_individualId
,
781 'receive_date' => '20120511',
782 'total_amount' => $totalAmount,
783 'financial_type_id' => $this->_financialTypeId
,
784 'contribution_status_id' => 1,
787 if ($expectedResult) {
788 $this->callAPISuccess('Contribution', 'create', $_params);
791 $this->callAPIFailure('Contribution', 'create', $_params);
798 public function createLocalizedContributionDataProvider(): array {
800 [10, '.', ',', 'USD', TRUE],
801 ['145.0E+3', '.', ',', 'USD', FALSE],
802 ['10', '.', ',', 'USD', TRUE],
803 [-10, '.', ',', 'USD', TRUE],
804 ['-10', '.', ',', 'USD', TRUE],
805 ['-10foo', '.', ',', 'USD', FALSE],
806 ['-10.0345619', '.', ',', 'USD', TRUE],
807 ['-10.010,4345619', '.', ',', 'USD', TRUE],
808 ['10.0104345619', '.', ',', 'USD', TRUE],
809 ['-0', '.', ',', 'USD', TRUE],
810 ['-.1', '.', ',', 'USD', TRUE],
811 ['.1', '.', ',', 'USD', TRUE],
812 // Test currency symbols too, default locale uses $, so if we wanted to test others we'd need to reconfigure locale
813 ['$1,234,567.89', '.', ',', 'USD', TRUE],
814 ['-$1,234,567.89', '.', ',', 'USD', TRUE],
815 ['$-1,234,567.89', '.', ',', 'USD', TRUE],
816 // This is the float format. Encapsulated in strings
817 ['1234567.89', '.', ',', 'USD', TRUE],
818 // This is the float format.
819 [1234567.89, '.', ',', 'USD', TRUE],
820 // Test EURO currency
821 ['€1,234,567.89', '.', ',', 'EUR', TRUE],
822 ['-€1,234,567.89', '.', ',', 'EUR', TRUE],
823 ['€-1,234,567.89', '.', ',', 'EUR', TRUE],
824 // This is the float format. Encapsulated in strings
825 ['1234567.89', '.', ',', 'EUR', TRUE],
826 // This is the float format.
827 [1234567.89, '.', ',', 'EUR', TRUE],
828 // Test Norwegian KR currency
829 ['kr1,234,567.89', '.', ',', 'NOK', TRUE],
830 ['kr 1,234,567.89', '.', ',', 'NOK', TRUE],
831 ['-kr1,234,567.89', '.', ',', 'NOK', TRUE],
832 ['-kr 1,234,567.89', '.', ',', 'NOK', TRUE],
833 ['kr-1,234,567.89', '.', ',', 'NOK', TRUE],
834 ['kr -1,234,567.89', '.', ',', 'NOK', TRUE],
835 // This is the float format. Encapsulated in strings
836 ['1234567.89', '.', ',', 'NOK', TRUE],
837 // This is the float format.
838 [1234567.89, '.', ',', 'NOK', TRUE],
839 // Test different localization options: , as decimal separator and dot as thousand separator
840 ['$1.234.567,89', ',', '.', 'USD', TRUE],
841 ['-$1.234.567,89', ',', '.', 'USD', TRUE],
842 ['$-1.234.567,89', ',', '.', 'USD', TRUE],
843 ['1.234.567,89', ',', '.', 'USD', TRUE],
844 // This is the float format. Encapsulated in strings
845 ['1234567.89', ',', '.', 'USD', TRUE],
846 // This is the float format.
847 [1234567.89, ',', '.', 'USD', TRUE],
848 ['$1,234,567.89', ',', '.', 'USD', FALSE],
849 ['-$1,234,567.89', ',', '.', 'USD', FALSE],
850 ['$-1,234,567.89', ',', '.', 'USD', FALSE],
851 // Now with a space as thousand separator
852 ['$1 234 567,89', ',', ' ', 'USD', TRUE],
853 ['-$1 234 567,89', ',', ' ', 'USD', TRUE],
854 ['$-1 234 567,89', ',', ' ', 'USD', TRUE],
855 ['1 234 567,89', ',', ' ', 'USD', TRUE],
856 // This is the float format. Encapsulated in strings
857 ['1234567.89', ',', ' ', 'USD', TRUE],
858 // This is the float format.
859 [1234567.89, ',', ' ', 'USD', TRUE],
864 * Create test with unique field name on source.
866 public function testCreateContributionSource() {
869 'contact_id' => $this->_individualId
,
870 'receive_date' => date('Ymd'),
871 'total_amount' => 100.00,
872 'financial_type_id' => $this->_financialTypeId
,
873 'payment_instrument_id' => 1,
874 'non_deductible_amount' => 10.00,
875 'fee_amount' => 50.00,
876 'net_amount' => 90.00,
878 'invoice_id' => 67890,
879 'contribution_source' => 'SSF',
880 'contribution_status_id' => 1,
883 $contribution = $this->callAPISuccess('contribution', 'create', $params);
884 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
885 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
889 * Create test with unique field name on source.
891 * @param string $thousandSeparator
892 * punctuation used to refer to thousands.
894 * @dataProvider getThousandSeparators
896 public function testCreateDefaultNow($thousandSeparator) {
897 $this->setCurrencySeparators($thousandSeparator);
898 $params = $this->_params
;
899 unset($params['receive_date'], $params['net_amount']);
901 $params['total_amount'] = $this->formatMoneyInput(5000.77);
902 $params['fee_amount'] = $this->formatMoneyInput(.77);
903 $params['skipCleanMoney'] = FALSE;
905 $contribution = $this->callAPISuccess('contribution', 'create', $params);
906 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
907 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receive_date'])));
908 $this->assertEquals(5000.77, $contribution['total_amount'], 'failed to handle ' . $this->formatMoneyInput(5000.77));
909 $this->assertEquals(.77, $contribution['fee_amount']);
910 $this->assertEquals(5000, $contribution['net_amount']);
914 * Create test with unique field name on source.
916 public function testCreateContributionNullOutThankyouDate() {
918 $params = $this->_params
;
919 $params['thankyou_date'] = 'yesterday';
921 $contribution = $this->callAPISuccess('contribution', 'create', $params);
922 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
923 $this->assertEquals(date('Y-m-d', strtotime('yesterday')), date('Y-m-d', strtotime($contribution['thankyou_date'])));
925 $params['thankyou_date'] = 'null';
926 $contribution = $this->callAPISuccess('contribution', 'create', $params);
927 $this->assertTrue(empty($contribution['thankyou_date']));
931 * Create test with unique field name on source.
933 public function testCreateContributionSourceInvalidContact() {
937 'receive_date' => date('Ymd'),
938 'total_amount' => 100.00,
939 'financial_type_id' => $this->_financialTypeId
,
940 'payment_instrument_id' => 1,
941 'non_deductible_amount' => 10.00,
942 'fee_amount' => 50.00,
943 'net_amount' => 90.00,
945 'invoice_id' => 67890,
946 'contribution_source' => 'SSF',
947 'contribution_status_id' => 1,
950 $this->callAPIFailure('contribution', 'create', $params, 'contact_id is not valid : 999');
954 * Test note created correctly.
956 * @throws \CRM_Core_Exception
958 public function testCreateContributionWithNote(): void
{
959 $description = 'Demonstrates creating contribution with Note Entity.';
960 $subFile = 'ContributionCreateWithNote';
962 'contact_id' => $this->_individualId
,
963 'receive_date' => '2012-01-01',
964 'total_amount' => 100.00,
965 'financial_type_id' => $this->_financialTypeId
,
966 'payment_instrument_id' => 1,
967 'non_deductible_amount' => 10.00,
968 'fee_amount' => 50.00,
969 'net_amount' => 90.00,
971 'invoice_id' => 67890,
973 'contribution_status_id' => 1,
974 'note' => 'my contribution note',
977 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subFile);
978 $result = $this->callAPISuccess('note', 'get', [
979 'entity_table' => 'civicrm_contribution',
980 'entity_id' => $contribution['id'],
984 $this->assertEquals('my contribution note', $result['values'][0]['note']);
985 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
989 * @throws \CRM_Core_Exception
991 public function testCreateContributionWithNoteUniqueNameAliases(): void
{
993 'contact_id' => $this->_individualId
,
994 'receive_date' => '2012-01-01',
995 'total_amount' => 100.00,
996 'financial_type_id' => $this->_financialTypeId
,
997 'payment_instrument_id' => 1,
998 'non_deductible_amount' => 10.00,
999 'fee_amount' => 50.00,
1000 'net_amount' => 90.00,
1002 'invoice_id' => 67890,
1004 'contribution_status_id' => 1,
1005 'contribution_note' => 'my contribution note',
1008 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1009 $result = $this->callAPISuccess('note', 'get', [
1010 'entity_table' => 'civicrm_contribution',
1011 'entity_id' => $contribution['id'],
1015 $this->assertEquals('my contribution note', $result['values'][0]['note']);
1019 * This is the test for creating soft credits.
1021 public function testCreateContributionWithSoftCredit() {
1022 $description = 'Demonstrates creating contribution with SoftCredit.';
1023 $subfile = 'ContributionCreateWithSoftCredit';
1024 $contact2 = $this->callAPISuccess('Contact', 'create', [
1025 'display_name' => 'superman',
1026 'contact_type' => 'Individual',
1029 'contact_id' => $contact2['id'],
1031 'soft_credit_type_id' => 3,
1034 $params = $this->_params +
['soft_credit' => [1 => $softParams]];
1035 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1036 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1038 $this->assertEquals($softParams['contact_id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1039 $this->assertEquals($softParams['amount'], $result['values'][0]['soft_credit'][1]['amount']);
1040 $this->assertEquals($softParams['soft_credit_type_id'], $result['values'][0]['soft_credit'][1]['soft_credit_type']);
1042 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1043 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1046 public function testCreateContributionWithSoftCreditDefaults() {
1047 $description = 'Demonstrates creating contribution with Soft Credit defaults for amount and type.';
1048 $subfile = 'ContributionCreateWithSoftCreditDefaults';
1049 $contact2 = $this->callAPISuccess('Contact', 'create', [
1050 'display_name' => 'superman',
1051 'contact_type' => 'Individual',
1053 $params = $this->_params +
[
1054 'soft_credit_to' => $contact2['id'],
1056 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1057 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1059 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1060 // Default soft credit amount = contribution.total_amount
1061 $this->assertEquals($this->_params
['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
1062 $this->assertEquals(CRM_Core_OptionGroup
::getDefaultValue('soft_credit_type'), $result['values'][0]['soft_credit'][1]['soft_credit_type']);
1064 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1065 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1069 * Test creating contribution with Soft Credit by passing in honor_contact_id.
1071 public function testCreateContributionWithHonoreeContact() {
1072 $description = 'Demonstrates creating contribution with Soft Credit by passing in honor_contact_id.';
1073 $subfile = 'ContributionCreateWithHonoreeContact';
1074 $contact2 = $this->callAPISuccess('Contact', 'create', [
1075 'display_name' => 'superman',
1076 'contact_type' => 'Individual',
1078 $params = $this->_params +
[
1079 'honor_contact_id' => $contact2['id'],
1081 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1082 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1084 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1085 // Default soft credit amount = contribution.total_amount
1086 // Legacy mode in create api (honor_contact_id param) uses the standard "In Honor of" soft credit type
1087 $this->assertEquals($this->_params
['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
1088 $softCreditValueTypeID = $result['values'][0]['soft_credit'][1]['soft_credit_type'];
1089 $this->assertEquals('in_honor_of', CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $softCreditValueTypeID));
1091 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1092 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1096 * Test using example code.
1098 public function testContributionCreateExample() {
1099 //make sure at least on page exists since there is a truncate in tear down
1100 $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1101 require_once 'api/v3/examples/Contribution/Create.ex.php';
1102 $result = contribution_create_example();
1103 $id = $result['id'];
1104 $expectedResult = contribution_create_expectedresult();
1105 $this->checkArrayEquals($expectedResult, $result);
1106 $this->contributionDelete($id);
1110 * Function tests that additional financial records are created when fee amount is recorded.
1112 public function testCreateContributionWithFee() {
1114 'contact_id' => $this->_individualId
,
1115 'receive_date' => '20120511',
1116 'total_amount' => 100.00,
1118 'financial_type_id' => 1,
1120 'invoice_id' => 67890,
1122 'contribution_status_id' => 1,
1125 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1126 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
1127 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1128 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 50.00);
1129 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 50.00);
1130 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1131 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1132 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1133 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1134 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
1136 $lineItems = $this->callAPISuccess('line_item', 'get', [
1138 'entity_id' => $contribution['id'],
1139 'entity_table' => 'civicrm_contribution',
1141 'return' => ['entity_id', 'contribution_id'],
1143 $this->assertEquals(1, $lineItems['count']);
1144 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
1145 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
1146 $this->callAPISuccessGetCount('line_item', [
1148 'entity_id' => $contribution['id'],
1149 'contribution_id' => $contribution['id'],
1150 'entity_table' => 'civicrm_contribution',
1153 $this->_checkFinancialRecords($contribution, 'feeAmount');
1157 * Function tests that additional financial records are created when online
1158 * contribution is created.
1160 * @throws \CRM_Core_Exception
1161 * @throws \CiviCRM_API3_Exception
1163 public function testCreateContributionOnline(): void
{
1164 CRM_Financial_BAO_PaymentProcessor
::create($this->_processorParams
);
1165 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1166 $this->assertAPISuccess($contributionPage);
1168 'contact_id' => $this->_individualId
,
1169 'receive_date' => '20120511',
1170 'total_amount' => 100.00,
1171 'financial_type_id' => 1,
1172 'contribution_page_id' => $contributionPage['id'],
1173 'payment_processor' => $this->paymentProcessorID
,
1175 'invoice_id' => 67890,
1177 'contribution_status_id' => 1,
1181 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
1182 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
1183 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1184 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1185 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1186 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1187 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1188 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
1189 $contribution['payment_instrument_id'] = $this->callAPISuccessGetValue('PaymentProcessor', [
1190 'id' => $this->paymentProcessorID
,
1191 'return' => 'payment_instrument_id',
1193 $this->_checkFinancialRecords($contribution, 'online');
1197 * Check handling of financial type.
1199 * In the interests of removing financial type / contribution type checks from
1200 * legacy format function lets test that the api is doing this for us
1202 public function testCreateInvalidFinancialType(): void
{
1203 $params = $this->_params
;
1204 $params['financial_type_id'] = 99999;
1205 $this->callAPIFailure($this->entity
, 'create', $params);
1209 * Check handling of financial type.
1211 * In the interests of removing financial type / contribution type checks from
1212 * legacy format function lets test that the api is doing this for us
1214 * @throws \CRM_Core_Exception
1216 public function testValidNamedFinancialType() {
1217 $params = $this->_params
;
1218 $params['financial_type_id'] = 'Donation';
1219 $this->callAPISuccess($this->entity
, 'create', $params);
1223 * Tests that additional financial records are created.
1225 * Checks when online contribution with pay later option is created
1227 * @throws \CRM_Core_Exception
1229 public function testCreateContributionPayLaterOnline(): void
{
1230 $this->_pageParams
['is_pay_later'] = 1;
1231 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1232 $this->assertAPISuccess($contributionPage);
1234 'contact_id' => $this->_individualId
,
1235 'receive_date' => '20120511',
1236 'total_amount' => 100.00,
1237 'financial_type_id' => 1,
1238 'contribution_page_id' => $contributionPage['id'],
1240 'is_pay_later' => 1,
1241 'invoice_id' => 67890,
1243 'contribution_status_id' => 'Pending',
1247 $contribution = $this->callAPIAndDocument('Contribution', 'create', $params, __FUNCTION__
, __FILE__
);
1248 $contribution = $contribution['values'][$contribution['id']];
1249 $this->assertEquals($contribution['contact_id'], $this->_individualId
);
1250 $this->assertEquals($contribution['total_amount'], 100.00);
1251 $this->assertEquals($contribution['financial_type_id'], 1);
1252 $this->assertEquals($contribution['trxn_id'], 12345);
1253 $this->assertEquals($contribution['invoice_id'], 67890);
1254 $this->assertEquals($contribution['source'], 'SSF');
1255 $this->assertEquals($contribution['contribution_status_id'], 2);
1256 $this->_checkFinancialRecords($contribution, 'payLater');
1260 * Function tests that additional financial records are created for online contribution with pending option.
1262 public function testCreateContributionPendingOnline() {
1263 CRM_Financial_BAO_PaymentProcessor
::create($this->_processorParams
);
1264 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1265 $this->assertAPISuccess($contributionPage);
1267 'contact_id' => $this->_individualId
,
1268 'receive_date' => '20120511',
1269 'total_amount' => 100.00,
1270 'financial_type_id' => 1,
1271 'contribution_page_id' => $contributionPage['id'],
1273 'invoice_id' => 67890,
1275 'contribution_status_id' => 2,
1278 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1279 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
1280 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1281 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1282 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1283 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1284 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1285 $this->assertEquals(2, $contribution['values'][$contribution['id']]['contribution_status_id']);
1286 $this->_checkFinancialRecords($contribution, 'pending');
1290 * Test that BAO defaults work.
1292 * @throws \CRM_Core_Exception
1294 public function testCreateBAODefaults() {
1295 unset($this->_params
['contribution_source_id'], $this->_params
['payment_instrument_id']);
1296 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1297 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
1298 'id' => $contribution['id'],
1299 'api.contribution.delete' => 1,
1300 'return' => ['contribution_status_id', 'payment_instrument'],
1302 $this->assertEquals(1, $contribution['contribution_status_id']);
1303 $this->assertEquals('Check', $contribution['payment_instrument']);
1304 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1308 * Test that getsingle can be chained with delete.
1310 * @throws CRM_Core_Exception
1312 public function testDeleteChainedGetSingle() {
1313 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1314 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
1315 'id' => $contribution['id'],
1316 'api.contribution.delete' => 1,
1319 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1323 * Function tests that line items, financial records are updated when contribution amount is changed.
1325 * @throws \CRM_Core_Exception
1327 public function testCreateUpdateContributionChangeTotal() {
1328 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
1329 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1331 'entity_id' => $contribution['id'],
1332 'entity_table' => 'civicrm_contribution',
1334 'return' => 'line_total',
1336 $this->assertEquals('100.00', $lineItems);
1337 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1338 // Financial trxn SUM = 100 + 5 (fee)
1339 $this->assertEquals('105.00', $trxnAmount);
1342 'id' => $contribution['id'],
1343 'total_amount' => '125',
1345 $contribution = $this->callAPISuccess('Contribution', 'create', $newParams);
1347 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1349 'entity_id' => $contribution['id'],
1350 'entity_table' => 'civicrm_contribution',
1352 'return' => 'line_total',
1355 $this->assertEquals('125.00', $lineItems);
1356 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1358 // Financial trxn SUM = 125 + 5 (fee).
1359 $this->assertEquals('130.00', $trxnAmount);
1360 $this->assertEquals('125.00', $this->_getFinancialItemAmount($contribution['id']));
1364 * Function tests that line items, financial records are updated when pay later contribution is received.
1366 public function testCreateUpdateContributionPayLater() {
1368 'contact_id' => $this->_individualId
,
1369 'receive_date' => '2012-01-01',
1370 'total_amount' => 100.00,
1371 'financial_type_id' => $this->_financialTypeId
,
1372 'payment_instrument_id' => 1,
1373 'contribution_status_id' => 2,
1374 'is_pay_later' => 1,
1377 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1379 $newParams = array_merge($contribParams, [
1380 'id' => $contribution['id'],
1381 'contribution_status_id' => 1,
1383 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1384 $contribution = $contribution['values'][$contribution['id']];
1385 $this->assertEquals($contribution['contribution_status_id'], '1');
1386 $this->_checkFinancialItem($contribution['id'], 'paylater');
1387 $this->_checkFinancialTrxn($contribution, 'payLater');
1391 * Function tests that financial records are updated when Payment Instrument is changed.
1393 public function testCreateUpdateContributionPaymentInstrument() {
1394 $instrumentId = $this->_addPaymentInstrument();
1396 'contact_id' => $this->_individualId
,
1397 'total_amount' => 100.00,
1398 'financial_type_id' => $this->_financialTypeId
,
1399 'payment_instrument_id' => 4,
1400 'contribution_status_id' => 1,
1403 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1405 $newParams = array_merge($contribParams, [
1406 'id' => $contribution['id'],
1407 'payment_instrument_id' => $instrumentId,
1409 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1410 $this->assertAPISuccess($contribution);
1411 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId);
1413 // cleanup - delete created payment instrument
1414 $this->_deletedAddedPaymentInstrument();
1418 * Function tests that financial records are updated when Payment Instrument is changed when amount is negative.
1420 public function testCreateUpdateNegativeContributionPaymentInstrument() {
1421 $instrumentId = $this->_addPaymentInstrument();
1423 'contact_id' => $this->_individualId
,
1424 'total_amount' => -100.00,
1425 'financial_type_id' => $this->_financialTypeId
,
1426 'payment_instrument_id' => 4,
1427 'contribution_status_id' => 1,
1430 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1432 $newParams = array_merge($contribParams, [
1433 'id' => $contribution['id'],
1434 'payment_instrument_id' => $instrumentId,
1436 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1437 $this->assertAPISuccess($contribution);
1438 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId, -100);
1440 // cleanup - delete created payment instrument
1441 $this->_deletedAddedPaymentInstrument();
1445 * Function tests that financial records are added when Contribution is Refunded.
1447 * @throws \CRM_Core_Exception
1449 public function testCreateUpdateContributionRefund() {
1450 $contributionParams = [
1451 'contact_id' => $this->_individualId
,
1452 'receive_date' => '2012-01-01',
1453 'total_amount' => 100.00,
1454 'financial_type_id' => $this->_financialTypeId
,
1455 'payment_instrument_id' => 4,
1456 'contribution_status_id' => 1,
1457 'trxn_id' => 'original_payment',
1459 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
1460 $newParams = array_merge($contributionParams, [
1461 'id' => $contribution['id'],
1462 'contribution_status_id' => 'Refunded',
1463 'cancel_date' => '2015-01-01 09:00',
1464 'refund_trxn_id' => 'the refund',
1467 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1468 $this->_checkFinancialTrxn($contribution, 'refund');
1469 $this->_checkFinancialItem($contribution['id'], 'refund');
1470 $this->assertEquals('original_payment', $this->callAPISuccessGetValue('Contribution', [
1471 'id' => $contribution['id'],
1472 'return' => 'trxn_id',
1477 * Refund a contribution for a financial type with a contra account.
1479 * CRM-17951 the contra account is a financial account with a relationship to a
1480 * financial type. It is not always configured but should be reflected
1481 * in the financial_trxn & financial_item table if it is.
1483 * @throws \CRM_Core_Exception
1485 public function testCreateUpdateChargebackContributionDefaultAccount() {
1486 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1487 $this->callAPISuccess('Contribution', 'create', [
1488 'id' => $contribution['id'],
1489 'contribution_status_id' => 'Chargeback',
1491 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1493 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1494 'contribution_id' => $contribution['id'],
1495 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1497 $this->assertEquals(1, $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1498 $this->callAPISuccessGetSingle('FinancialTrxn', [
1499 'total_amount' => -100,
1500 'status_id' => 'Chargeback',
1501 'to_financial_account_id' => 6,
1506 * Refund a contribution for a financial type with a contra account.
1508 * CRM-17951 the contra account is a financial account with a relationship to a
1509 * financial type. It is not always configured but should be reflected
1510 * in the financial_trxn & financial_item table if it is.
1512 * @throws \CRM_Core_Exception
1514 public function testCreateUpdateChargebackContributionCustomAccount() {
1515 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1516 'name' => 'Chargeback Account',
1517 'is_active' => TRUE,
1520 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1521 'entity_id' => $this->_financialTypeId
,
1522 'entity_table' => 'civicrm_financial_type',
1523 'account_relationship' => 'Chargeback Account is',
1524 'financial_account_id' => 'Chargeback Account',
1527 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1528 $this->callAPISuccess('Contribution', 'create', [
1529 'id' => $contribution['id'],
1530 'contribution_status_id' => 'Chargeback',
1532 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1534 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1535 'contribution_id' => $contribution['id'],
1536 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1538 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1540 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1541 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1542 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1546 * Refund a contribution for a financial type with a contra account.
1548 * CRM-17951 the contra account is a financial account with a relationship to a
1549 * financial type. It is not always configured but should be reflected
1550 * in the financial_trxn & financial_item table if it is.
1552 public function testCreateUpdateRefundContributionConfiguredContraAccount() {
1553 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1554 'name' => 'Refund Account',
1555 'is_active' => TRUE,
1558 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1559 'entity_id' => $this->_financialTypeId
,
1560 'entity_table' => 'civicrm_financial_type',
1561 'account_relationship' => 'Credit/Contra Revenue Account is',
1562 'financial_account_id' => 'Refund Account',
1565 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1566 $this->callAPISuccess('Contribution', 'create', [
1567 'id' => $contribution['id'],
1568 'contribution_status_id' => 'Refunded',
1571 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1572 'contribution_id' => $contribution['id'],
1573 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1575 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1577 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1578 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1579 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1583 * Function tests that trxn_id is set when passed in.
1585 * Here we ensure that the civicrm_financial_trxn.trxn_id & the civicrm_contribution.trxn_id are set
1586 * when trxn_id is passed in.
1588 public function testCreateUpdateContributionRefundTrxnIDPassedIn() {
1589 $contributionParams = [
1590 'contact_id' => $this->_individualId
,
1591 'receive_date' => '2012-01-01',
1592 'total_amount' => 100.00,
1593 'financial_type_id' => $this->_financialTypeId
,
1594 'payment_instrument_id' => 4,
1595 'contribution_status_id' => 1,
1596 'trxn_id' => 'original_payment',
1598 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1599 $newParams = array_merge($contributionParams, [
1600 'id' => $contribution['id'],
1601 'contribution_status_id' => 'Refunded',
1602 'cancel_date' => '2015-01-01 09:00',
1603 'trxn_id' => 'the refund',
1606 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1607 $this->_checkFinancialTrxn($contribution, 'refund');
1608 $this->_checkFinancialItem($contribution['id'], 'refund');
1609 $this->assertEquals('the refund', $this->callAPISuccessGetValue('Contribution', [
1610 'id' => $contribution['id'],
1611 'return' => 'trxn_id',
1616 * Function tests that trxn_id is set when passed in.
1618 * Here we ensure that the civicrm_contribution.trxn_id is set
1619 * when trxn_id is passed in but if refund_trxn_id is different then that
1620 * is kept for the refund transaction.
1622 public function testCreateUpdateContributionRefundRefundAndTrxnIDPassedIn() {
1623 $contributionParams = [
1624 'contact_id' => $this->_individualId
,
1625 'receive_date' => '2012-01-01',
1626 'total_amount' => 100.00,
1627 'financial_type_id' => $this->_financialTypeId
,
1628 'payment_instrument_id' => 4,
1629 'contribution_status_id' => 1,
1630 'trxn_id' => 'original_payment',
1632 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1633 $newParams = array_merge($contributionParams, [
1634 'id' => $contribution['id'],
1635 'contribution_status_id' => 'Refunded',
1636 'cancel_date' => '2015-01-01 09:00',
1637 'trxn_id' => 'cont id',
1638 'refund_trxn_id' => 'the refund',
1641 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1642 $this->_checkFinancialTrxn($contribution, 'refund');
1643 $this->_checkFinancialItem($contribution['id'], 'refund');
1644 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1645 'id' => $contribution['id'],
1646 'return' => 'trxn_id',
1651 * Function tests that refund_trxn_id is set when passed in empty.
1653 * Here we ensure that the civicrm_contribution.trxn_id is set
1654 * when trxn_id is passed in but if refund_trxn_id isset but empty then that
1655 * is kept for the refund transaction.
1657 public function testCreateUpdateContributionRefundRefundNullTrxnIDPassedIn() {
1658 $contributionParams = [
1659 'contact_id' => $this->_individualId
,
1660 'receive_date' => '2012-01-01',
1661 'total_amount' => 100.00,
1662 'financial_type_id' => $this->_financialTypeId
,
1663 'payment_instrument_id' => 4,
1664 'contribution_status_id' => 1,
1665 'trxn_id' => 'original_payment',
1667 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1668 $newParams = array_merge($contributionParams, [
1669 'id' => $contribution['id'],
1670 'contribution_status_id' => 'Refunded',
1671 'cancel_date' => '2015-01-01 09:00',
1672 'trxn_id' => 'cont id',
1673 'refund_trxn_id' => '',
1676 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1677 $this->_checkFinancialTrxn($contribution, 'refund', NULL, ['trxn_id' => NULL]);
1678 $this->_checkFinancialItem($contribution['id'], 'refund');
1679 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1680 'id' => $contribution['id'],
1681 'return' => 'trxn_id',
1686 * Function tests invalid contribution status change.
1688 public function testCreateUpdateContributionInValidStatusChange() {
1691 'receive_date' => '2012-01-01',
1692 'total_amount' => 100.00,
1693 'financial_type_id' => 1,
1694 'payment_instrument_id' => 1,
1695 'contribution_status_id' => 1,
1697 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1698 $newParams = array_merge($contribParams, [
1699 'id' => $contribution['id'],
1700 'contribution_status_id' => 2,
1702 $this->callAPIFailure('contribution', 'create', $newParams, ts('Cannot change contribution status from Completed to Pending.'));
1707 * Function tests that financial records are added when Pending Contribution is Canceled.
1709 * @throws \CRM_Core_Exception
1711 public function testCreateUpdateContributionCancelPending() {
1713 'contact_id' => $this->_individualId
,
1714 'receive_date' => '2012-01-01',
1715 'total_amount' => 100.00,
1716 'financial_type_id' => $this->_financialTypeId
,
1717 'payment_instrument_id' => 1,
1718 'contribution_status_id' => 2,
1719 'is_pay_later' => 1,
1722 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1723 $newParams = array_merge($contribParams, [
1724 'id' => $contribution['id'],
1725 'contribution_status_id' => 3,
1726 'cancel_date' => '2012-02-02 09:00',
1728 //Check if trxn_date is same as cancel_date.
1730 'trxn_date' => '2012-02-02 09:00:00',
1732 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1733 $this->_checkFinancialTrxn($contribution, 'cancelPending', NULL, $checkTrxnDate);
1734 $this->_checkFinancialItem($contribution['id'], 'cancelPending');
1738 * Function tests that financial records are added when Financial Type is Changed.
1740 * @throws \CRM_Core_Exception
1742 public function testCreateUpdateContributionChangeFinancialType() {
1744 'contact_id' => $this->_individualId
,
1745 'receive_date' => '2012-01-01',
1746 'total_amount' => 100.00,
1747 'financial_type_id' => 1,
1748 'payment_instrument_id' => 1,
1749 'contribution_status_id' => 1,
1752 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1753 $newParams = array_merge($contribParams, [
1754 'id' => $contribution['id'],
1755 'financial_type_id' => 3,
1757 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1758 $this->_checkFinancialTrxn($contribution, 'changeFinancial');
1759 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1763 * Function tets that financial records are correctly added when financial type is changed
1765 * @throws \CRM_Core_Exception
1767 public function testCreateUpdateContributionWithFeeAmountChangeFinancialType() {
1769 'contact_id' => $this->_individualId
,
1770 'receive_date' => '2012-01-01',
1771 'total_amount' => 100.00,
1772 'fee_amount' => 0.57,
1773 'financial_type_id' => 1,
1774 'payment_instrument_id' => 1,
1775 'contribution_status_id' => 1,
1778 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1779 $newParams = array_merge($contribParams, [
1780 'id' => $contribution['id'],
1781 'financial_type_id' => 3,
1783 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1784 $this->_checkFinancialTrxn($contribution, 'changeFinancial', NULL, ['fee_amount' => '-0.57', 'net_amount' => '-99.43']);
1785 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1789 * Test that update does not change status id CRM-15105.
1791 public function testCreateUpdateWithoutChangingPendingStatus() {
1792 $contribution = $this->callAPISuccess('contribution', 'create', array_merge($this->_params
, ['contribution_status_id' => 2]));
1793 $this->callAPISuccess('contribution', 'create', ['id' => $contribution['id'], 'source' => 'new source']);
1794 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1795 'id' => $contribution['id'],
1796 'api.contribution.delete' => 1,
1798 $this->assertEquals(2, $contribution['contribution_status_id']);
1802 * Test Updating a Contribution.
1804 * CHANGE: we require the API to do an incremental update
1806 public function testCreateUpdateContribution() {
1807 $contributionID = $this->contributionCreate([
1808 'contact_id' => $this->_individualId
,
1809 'trxn_id' => 212355,
1810 'financial_type_id' => $this->_financialTypeId
,
1811 'invoice_id' => 'old_invoice',
1814 'contribution_id' => $contributionID,
1816 $original = $this->callAPISuccess('contribution', 'get', $old_params);
1817 $this->assertEquals($original['id'], $contributionID);
1818 //set up list of old params, verify
1820 //This should not be required on update:
1821 $old_contact_id = $original['values'][$contributionID]['contact_id'];
1822 $old_payment_instrument = $original['values'][$contributionID]['instrument_id'];
1823 $old_fee_amount = $original['values'][$contributionID]['fee_amount'];
1824 $old_source = $original['values'][$contributionID]['contribution_source'];
1826 $old_trxn_id = $original['values'][$contributionID]['trxn_id'];
1827 $old_invoice_id = $original['values'][$contributionID]['invoice_id'];
1829 //check against values in CiviUnitTestCase::createContribution()
1830 $this->assertEquals($old_contact_id, $this->_individualId
);
1831 $this->assertEquals($old_fee_amount, 5.00);
1832 $this->assertEquals($old_source, 'SSF');
1833 $this->assertEquals($old_trxn_id, 212355);
1834 $this->assertEquals($old_invoice_id, 'old_invoice');
1836 'id' => $contributionID,
1837 'contact_id' => $this->_individualId
,
1838 'total_amount' => 105.00,
1839 'fee_amount' => 7.00,
1840 'financial_type_id' => $this->_financialTypeId
,
1841 'non_deductible_amount' => 22.00,
1842 'contribution_status_id' => 1,
1843 'note' => 'Donating for Noble Cause',
1846 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1849 'contribution_id' => $contribution['id'],
1851 $contribution = $this->callAPISuccessGetSingle('contribution', $new_params);
1853 $this->assertEquals($contribution['contact_id'], $this->_individualId
);
1854 $this->assertEquals($contribution['total_amount'], 105.00);
1855 $this->assertEquals($contribution['financial_type_id'], $this->_financialTypeId
);
1856 $this->assertEquals($contribution['financial_type'], 'Donation');
1857 $this->assertEquals($contribution['instrument_id'], $old_payment_instrument);
1858 $this->assertEquals($contribution['non_deductible_amount'], 22.00);
1859 $this->assertEquals($contribution['fee_amount'], 7.00);
1860 $this->assertEquals($contribution['trxn_id'], $old_trxn_id);
1861 $this->assertEquals($contribution['invoice_id'], $old_invoice_id);
1862 $this->assertEquals($contribution['contribution_source'], $old_source);
1863 $this->assertEquals($contribution['contribution_status'], 'Completed');
1865 $this->assertEquals($contribution['net_amount'], $contribution['total_amount'] - $contribution['fee_amount']);
1868 'contribution_id' => $contributionID,
1870 $result = $this->callAPISuccess('contribution', 'delete', $params);
1871 $this->assertAPISuccess($result);
1875 * Check that net_amount is updated when a contribution is updated.
1877 * Update fee amount AND total amount, just fee amount, just total amount
1878 * and neither to check that net_amount is keep updated.
1880 public function testUpdateContributionNetAmountVariants() {
1881 $contributionID = $this->contributionCreate(['contact_id' => $this->individualCreate()]);
1883 $this->callAPISuccess('Contribution', 'create', [
1884 'id' => $contributionID,
1885 'total_amount' => 90,
1888 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1889 'id' => $contributionID,
1890 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1892 $this->assertEquals(6, $contribution['fee_amount']);
1893 $this->assertEquals(90, $contribution['total_amount']);
1894 $this->assertEquals(84, $contribution['net_amount']);
1896 $this->callAPISuccess('Contribution', 'create', [
1897 'id' => $contributionID,
1900 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1901 'id' => $contributionID,
1902 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1904 $this->assertEquals(3, $contribution['fee_amount']);
1905 $this->assertEquals(90, $contribution['total_amount']);
1906 $this->assertEquals(87, $contribution['net_amount']);
1908 $this->callAPISuccess('Contribution', 'create', [
1909 'id' => $contributionID,
1910 'total_amount' => 200,
1912 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1913 'id' => $contributionID,
1914 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1916 $this->assertEquals(3, $contribution['fee_amount']);
1917 $this->assertEquals(200, $contribution['total_amount']);
1918 $this->assertEquals(197, $contribution['net_amount']);
1920 $this->callAPISuccess('Contribution', 'create', [
1921 'id' => $contributionID,
1922 'payment_instrument' => 'Cash',
1924 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1925 'id' => $contributionID,
1926 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1928 $this->assertEquals(3, $contribution['fee_amount']);
1929 $this->assertEquals(200, $contribution['total_amount']);
1930 $this->assertEquals(197, $contribution['net_amount']);
1934 * Attempt (but fail) to delete a contribution without parameters.
1936 public function testDeleteEmptyParamsContribution() {
1938 $this->callAPIFailure('contribution', 'delete', $params);
1941 public function testDeleteWrongParamContribution() {
1943 'contribution_source' => 'SSF',
1945 $this->callAPIFailure('contribution', 'delete', $params);
1948 public function testDeleteContribution() {
1949 $contributionID = $this->contributionCreate([
1950 'contact_id' => $this->_individualId
,
1951 'financial_type_id' => $this->_financialTypeId
,
1954 'id' => $contributionID,
1956 $this->callAPIAndDocument('contribution', 'delete', $params, __FUNCTION__
, __FILE__
);
1960 * Test civicrm_contribution_search with empty params.
1962 * All available contributions expected.
1964 public function testSearchEmptyParams() {
1968 'contact_id' => $this->_individualId
,
1969 'receive_date' => date('Ymd'),
1970 'total_amount' => 100.00,
1971 'financial_type_id' => $this->_financialTypeId
,
1972 'non_deductible_amount' => 10.00,
1973 'fee_amount' => 5.00,
1974 'net_amount' => 95.00,
1976 'invoice_id' => 78910,
1978 'contribution_status_id' => 1,
1980 $contribution = $this->callAPISuccess('contribution', 'create', $p);
1982 $result = $this->callAPISuccess('contribution', 'get', $params);
1983 // We're taking the first element.
1984 $res = $result['values'][$contribution['id']];
1986 $this->assertEquals($p['contact_id'], $res['contact_id']);
1987 $this->assertEquals($p['total_amount'], $res['total_amount']);
1988 $this->assertEquals($p['financial_type_id'], $res['financial_type_id']);
1989 $this->assertEquals($p['net_amount'], $res['net_amount']);
1990 $this->assertEquals($p['non_deductible_amount'], $res['non_deductible_amount']);
1991 $this->assertEquals($p['fee_amount'], $res['fee_amount']);
1992 $this->assertEquals($p['trxn_id'], $res['trxn_id']);
1993 $this->assertEquals($p['invoice_id'], $res['invoice_id']);
1994 $this->assertEquals($p['source'], $res['contribution_source']);
1995 // contribution_status_id = 1 => Completed
1996 $this->assertEquals('Completed', $res['contribution_status']);
1998 $this->contributionDelete($contribution['id']);
2002 * Test civicrm_contribution_search. Success expected.
2004 public function testSearch() {
2006 'contact_id' => $this->_individualId
,
2007 'receive_date' => date('Ymd'),
2008 'total_amount' => 100.00,
2009 'financial_type_id' => $this->_financialTypeId
,
2010 'non_deductible_amount' => 10.00,
2011 'contribution_status_id' => 1,
2013 $contribution1 = $this->callAPISuccess('contribution', 'create', $p1);
2016 'contact_id' => $this->_individualId
,
2017 'receive_date' => date('Ymd'),
2018 'total_amount' => 200.00,
2019 'financial_type_id' => $this->_financialTypeId
,
2020 'non_deductible_amount' => 20.00,
2021 'trxn_id' => 5454565,
2022 'invoice_id' => 1212124,
2023 'fee_amount' => 50.00,
2024 'net_amount' => 60.00,
2025 'contribution_status_id' => 2,
2027 $contribution2 = $this->callAPISuccess('contribution', 'create', $p2);
2030 'contribution_id' => $contribution2['id'],
2032 $result = $this->callAPISuccess('contribution', 'get', $params);
2033 $res = $result['values'][$contribution2['id']];
2035 $this->assertEquals($p2['contact_id'], $res['contact_id']);
2036 $this->assertEquals($p2['total_amount'], $res['total_amount']);
2037 $this->assertEquals($p2['financial_type_id'], $res['financial_type_id']);
2038 $this->assertEquals($p2['net_amount'], $res['net_amount']);
2039 $this->assertEquals($p2['non_deductible_amount'], $res['non_deductible_amount']);
2040 $this->assertEquals($p2['fee_amount'], $res['fee_amount']);
2041 $this->assertEquals($p2['trxn_id'], $res['trxn_id']);
2042 $this->assertEquals($p2['invoice_id'], $res['invoice_id']);
2043 $this->assertEquals(CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'), $res['contribution_status_id']);
2045 $this->contributionDelete($contribution1['id']);
2046 $this->contributionDelete($contribution2['id']);
2050 * Test completing a transaction via the API.
2052 * Note that we are creating a logged in user because email goes out from
2055 public function testCompleteTransaction(): void
{
2056 $mut = new CiviMailUtils($this, TRUE);
2057 Civi
::settings()->set('tax_term', 'GST');
2058 $this->swapMessageTemplateForTestTemplate();
2059 $this->createLoggedInUser();
2060 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2061 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2062 $this->callAPISuccess('contribution', 'completetransaction', [
2063 'id' => $contribution['id'],
2065 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2066 $this->assertEquals('SSF', $contribution['contribution_source']);
2067 $this->assertEquals('Completed', $contribution['contribution_status']);
2068 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
2069 $mut->checkMailLog([
2070 'email:::anthony_anderson@civicrm.org',
2074 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2075 "receipt_date:::\n",
2076 'title:::Contribution',
2077 'contributionStatus:::Completed',
2081 $this->revertTemplateToReservedTemplate();
2085 * Test completing a transaction via the API with a non-USD transaction.
2087 public function testCompleteTransactionEuro(): void
{
2088 $mut = new CiviMailUtils($this, TRUE);
2089 $this->swapMessageTemplateForTestTemplate();
2090 $this->createLoggedInUser();
2091 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'currency' => 'EUR']);
2092 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2094 $this->callAPISuccess('contribution', 'completetransaction', [
2095 'id' => $contribution['id'],
2098 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2099 $this->assertEquals('SSF', $contribution['contribution_source']);
2100 $this->assertEquals('Completed', $contribution['contribution_status']);
2101 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
2103 $entityFinancialTransactions = $this->getFinancialTransactionsForContribution($contribution['id']);
2104 $entityFinancialTransaction = reset($entityFinancialTransactions);
2105 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', ['id' => $entityFinancialTransaction['financial_trxn_id']]);
2106 $this->assertEquals('EUR', $financialTrxn['currency']);
2108 $mut->checkMailLog([
2109 'email:::anthony_anderson@civicrm.org',
2113 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2114 "receipt_date:::\n",
2115 'title:::Contribution',
2116 'contributionStatus:::Completed',
2119 $this->revertTemplateToReservedTemplate();
2123 * Test to ensure mail is sent for pay later
2125 * @throws \CRM_Core_Exception
2126 * @throws \API_Exception
2128 public function testPayLater(): void
{
2129 $mut = new CiviMailUtils($this, TRUE);
2130 $this->swapMessageTemplateForTestTemplate();
2131 $this->createLoggedInUser();
2132 $contributionPageID = $this->createQuickConfigContributionPage();
2135 'id' => $contributionPageID,
2136 'price_' . $this->ids
['PriceField']['basic'] => $this->ids
['PriceFieldValue']['basic'],
2137 'contact_id' => $this->_individualId
,
2138 'email-5' => 'anthony_anderson@civicrm.org',
2139 'payment_processor_id' => 0,
2140 'currencyID' => 'USD',
2141 'is_pay_later' => 1,
2142 'invoiceID' => 'f28e1ddc86f8c4a0ff5bcf46393e4bc8',
2143 'description' => 'Online Contribution: Help Support CiviCRM!',
2145 $this->callAPISuccess('ContributionPage', 'submit', $params);
2147 $mut->checkMailLog([
2149 'email:::anthony_anderson@civicrm.org',
2150 'pay_later_receipt:::This is a pay later receipt',
2151 'contributionPageId:::' . $contributionPageID,
2152 'title:::Test Contribution Page',
2156 $this->revertTemplateToReservedTemplate();
2160 * Test to check whether contact billing address is used when no contribution address
2162 public function testBillingAddress() {
2163 $mut = new CiviMailUtils($this, TRUE);
2164 $this->swapMessageTemplateForTestTemplate();
2165 $this->createLoggedInUser();
2167 //Scenario 1: When Contact don't have any address
2168 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2169 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2170 $this->callAPISuccess('contribution', 'completetransaction', [
2171 'id' => $contribution['id'],
2173 $mut->checkMailLog([
2177 // Scenario 2: Contribution using address
2178 $address = $this->callAPISuccess('address', 'create', [
2179 'street_address' => 'contribution billing st',
2180 'location_type_id' => 2,
2181 'contact_id' => $this->_params
['contact_id'],
2183 $params = array_merge($this->_params
, [
2184 'contribution_status_id' => 2,
2185 'address_id' => $address['id'],
2188 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2189 $this->callAPISuccess('contribution', 'completetransaction', [
2190 'id' => $contribution['id'],
2192 $mut->checkMailLog([
2193 'address:::contribution billing st',
2196 // Scenario 3: Contribution wtth no address but contact has a billing address
2197 $this->callAPISuccess('address', 'create', [
2198 'id' => $address['id'],
2199 'street_address' => 'is billing st',
2200 'contact_id' => $this->_params
['contact_id'],
2202 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2203 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2204 $this->callAPISuccess('contribution', 'completetransaction', [
2205 'id' => $contribution['id'],
2207 $mut->checkMailLog([
2208 'address:::is billing st',
2212 $this->revertTemplateToReservedTemplate();
2216 * Test completing a transaction via the API.
2218 * Note that we are creating a logged in user because email goes out from
2221 public function testCompleteTransactionFeeAmount() {
2222 $this->createLoggedInUser();
2223 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2224 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2225 $this->callAPISuccess('contribution', 'completetransaction', [
2226 'id' => $contribution['id'],
2227 'fee_amount' => '.56',
2228 'trxn_id' => '7778888',
2230 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id'], 'sequential' => 1]);
2231 $this->assertEquals('Completed', $contribution['contribution_status']);
2232 $this->assertEquals('7778888', $contribution['trxn_id']);
2233 $this->assertEquals('0.56', $contribution['fee_amount']);
2234 $this->assertEquals('99.44', $contribution['net_amount']);
2238 * CRM-19126 Add test to verify when complete transaction is called tax
2239 * amount is not changed.
2241 * We start of with a pending contribution.
2242 * - total_amount (input) = 100
2243 * - total_amount post save (based on tax being added) = 105
2246 * - non_deductible_amount = 10
2249 * - sum of (calculated) line items = 105
2251 * Note the fee_amount should really be set when the payment is received
2252 * and whatever the non_deductible amount is, it is ignored.
2254 * The fee amount when the payment comes in is 6 rather than 5. The net_amount
2255 * and fee_amount should change, but not the total_amount or
2258 * @param string $thousandSeparator
2259 * punctuation used to refer to thousands.
2261 * @throws \API_Exception
2262 * @throws \CRM_Core_Exception
2263 * @dataProvider getThousandSeparators
2265 public function testCheckTaxAmount(string $thousandSeparator): void
{
2266 $this->setCurrencySeparators($thousandSeparator);
2267 $this->createFinancialTypeWithSalesTax();
2268 $financialTypeId = $this->ids
['FinancialType']['taxable'];
2270 $contributionID = $this->callAPISuccess('Order', 'create',
2271 array_merge($this->_params
, ['financial_type_id' => $financialTypeId])
2273 $contributionPrePayment = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => ['tax_amount', 'total_amount']]);
2274 $this->validateAllContributions();
2275 $this->callAPISuccess('Contribution', 'completetransaction', [
2276 'id' => $contributionID,
2277 'trxn_id' => '777788888',
2278 'fee_amount' => '6.00',
2281 $contributionPostPayment = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => ['tax_amount', 'fee_amount', 'net_amount']]);
2282 $this->assertEquals(4.76, $contributionPrePayment['tax_amount']);
2283 $this->assertEquals(4.76, $contributionPostPayment['tax_amount']);
2284 $this->assertEquals('6.00', $contributionPostPayment['fee_amount']);
2285 $this->assertEquals('94.00', $contributionPostPayment['net_amount']);
2286 $this->validateAllContributions();
2287 $this->validateAllPayments();
2291 * Test repeat contribution successfully creates line item.
2293 * @throws \CRM_Core_Exception
2295 public function testRepeatTransaction(): void
{
2296 $originalContribution = $this->setUpRepeatTransaction([], 'single');
2297 $this->callAPISuccess('contribution', 'repeattransaction', [
2298 'original_contribution_id' => $originalContribution['id'],
2299 'contribution_status_id' => 'Completed',
2303 'entity_id' => $originalContribution['id'],
2311 'financial_type_id',
2312 'deductible_amount',
2313 'price_field_value_id',
2317 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2318 'entity_id' => $originalContribution['id'],
2320 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2321 'entity_id' => $originalContribution['id'] +
1,
2323 unset($lineItem1['values'][0]['id'], $lineItem1['values'][0]['entity_id']);
2324 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2325 $this->assertEquals($lineItem1['values'][0], $lineItem2['values'][0]);
2326 $this->_checkFinancialRecords([
2327 'id' => $originalContribution['id'] +
1,
2328 'payment_instrument_id' => $this->callAPISuccessGetValue('PaymentProcessor', [
2329 'id' => $originalContribution['payment_processor_id'],
2330 'return' => 'payment_instrument_id',
2336 * Test custom data is copied over from the template transaction.
2338 * (Over time various discussions have deemed this to be the most recent one, allowing
2339 * users to alter custom data going forwards. This is implemented for line items already.
2341 * @throws \API_Exception
2342 * @throws \CRM_Core_Exception
2344 public function testRepeatTransactionWithCustomData(): void
{
2345 $this->createCustomGroupWithFieldOfType(['extends' => 'Contribution', 'name' => 'Repeat'], 'text');
2346 $originalContribution = $this->setUpRepeatTransaction([], 'single', [$this->getCustomFieldName('text') => 'first']);
2347 $this->callAPISuccess('contribution', 'repeattransaction', [
2348 'contribution_recur_id' => $originalContribution['contribution_recur_id'],
2349 'contribution_status_id' => 'Completed',
2350 'trxn_id' => 'my_trxn',
2353 $contribution = Contribution
::get()
2354 ->addWhere('trxn_id', '=', 'my_trxn')
2355 ->addSelect('Custom_Group.Enter_text_here')
2357 ->execute()->first();
2358 $this->assertEquals('first', $contribution['Custom_Group.Enter_text_here']);
2360 Contribution
::update()->setValues(['Custom_Group.Enter_text_here' => 'second'])->addWhere('id', '=', $contribution['id'])->execute();
2362 $this->callAPISuccess('contribution', 'repeattransaction', [
2363 'original_contribution_id' => $originalContribution['id'],
2364 'contribution_status_id' => 'Completed',
2365 'trxn_id' => 'number_3',
2368 $contribution = Contribution
::get()
2369 ->addWhere('trxn_id', '=', 'number_3')
2370 ->setSelect(['id', 'Custom_Group.Enter_text_here'])
2371 ->execute()->first();
2372 $this->assertEquals('second', $contribution['Custom_Group.Enter_text_here']);
2376 * Test repeat contribution successfully creates line items (plural).
2378 * @throws \CRM_Core_Exception
2380 public function testRepeatTransactionLineItems(): void
{
2382 $originalContribution = $this->setUpRepeatTransaction([], 'multiple');
2383 $this->callAPISuccess('contribution', 'repeattransaction', [
2384 'original_contribution_id' => $originalContribution['id'],
2385 'contribution_status_id' => 'Completed',
2390 'entity_id' => $originalContribution['id'],
2398 'financial_type_id',
2399 'deductible_amount',
2400 'price_field_value_id',
2404 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2405 'entity_id' => $originalContribution['id'],
2406 'options' => ['sort' => 'qty'],
2408 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2409 'entity_id' => $originalContribution['id'] +
1,
2410 'options' => ['sort' => 'qty'],
2413 // unset id and entity_id for all of them to be able to compare the lineItems:
2414 unset($lineItem1[0]['id'], $lineItem1[0]['entity_id']);
2415 unset($lineItem2[0]['id'], $lineItem2[0]['entity_id']);
2416 $this->assertEquals($lineItem1[0], $lineItem2[0]);
2418 unset($lineItem1[1]['id'], $lineItem1[1]['entity_id']);
2419 unset($lineItem2[1]['id'], $lineItem2[1]['entity_id']);
2420 $this->assertEquals($lineItem1[1], $lineItem2[1]);
2422 // CRM-19309 so in future we also want to:
2423 // check that financial_line_items have been created for entity_id 3 and 4;
2425 $this->callAPISuccessGetCount('FinancialItem', ['description' => 'Sales Tax', 'amount' => 0], 0);
2429 * Test repeat contribution successfully creates is_test transaction.
2431 * @throws \CRM_Core_Exception
2433 public function testRepeatTransactionIsTest(): void
{
2434 $this->_params
['is_test'] = 1;
2435 $originalContribution = $this->setUpRepeatTransaction(['is_test' => 1], 'single');
2437 $this->callAPISuccess('contribution', 'repeattransaction', [
2438 'original_contribution_id' => $originalContribution['id'],
2439 'contribution_status_id' => 'Completed',
2440 'trxn_id' => '1234',
2442 $this->callAPISuccessGetCount('Contribution', ['contribution_test' => 1], 2);
2446 * Test repeat contribution passed in status.
2448 * @throws \CRM_Core_Exception
2450 public function testRepeatTransactionPassedInStatus(): void
{
2451 $originalContribution = $this->setUpRepeatTransaction([], 'single');
2453 $this->callAPISuccess('contribution', 'repeattransaction', [
2454 'original_contribution_id' => $originalContribution['id'],
2455 'contribution_status_id' => 'Pending',
2458 $this->callAPISuccessGetCount('Contribution', ['contribution_status_id' => 2], 1);
2462 * Test repeat contribution accepts recur_id instead of
2463 * original_contribution_id.
2465 * @throws \CRM_Core_Exception
2467 public function testRepeatTransactionAcceptRecurID(): void
{
2468 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2469 'contact_id' => $this->_individualId
,
2470 'installments' => '12',
2471 'frequency_interval' => '1',
2473 'contribution_status_id' => 1,
2474 'start_date' => '2012-01-01 00:00:00',
2475 'currency' => 'USD',
2476 'frequency_unit' => 'month',
2477 'payment_processor_id' => $this->paymentProcessorID
,
2479 $this->callAPISuccess('contribution', 'create', array_merge(
2481 ['contribution_recur_id' => $contributionRecur['id']])
2484 $this->callAPISuccess('contribution', 'repeattransaction', [
2485 'contribution_recur_id' => $contributionRecur['id'],
2486 'contribution_status_id' => 'Completed',
2493 * CRM-19873 Test repeattransaction if contribution_recur_id is a test.
2495 * @throws \CRM_Core_Exception
2497 public function testRepeatTransactionTestRecurId() {
2498 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
2499 'contact_id' => $this->_individualId
,
2500 'frequency_interval' => '1',
2502 'contribution_status_id' => 1,
2503 'start_date' => '2017-01-01 00:00:00',
2504 'currency' => 'USD',
2505 'frequency_unit' => 'month',
2506 'payment_processor_id' => $this->paymentProcessorID
,
2509 $this->callAPISuccess('contribution', 'create', array_merge(
2512 'contribution_recur_id' => $contributionRecur['id'],
2517 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2518 'contribution_recur_id' => $contributionRecur['id'],
2519 'contribution_status_id' => 'Completed',
2520 'trxn_id' => 'magic_number',
2523 $this->assertEquals($contributionRecur['values'][1]['is_test'], $repeatedContribution['values'][2]['is_test']);
2527 * CRM-19945 Tests that Contribute.repeattransaction renews a membership when contribution status=Completed
2529 * @throws \CRM_Core_Exception
2531 public function testRepeatTransactionMembershipRenewCompletedContribution(): void
{
2532 [$originalContribution, $membership] = $this->setUpAutoRenewMembership();
2534 $this->callAPISuccess('Contribution', 'repeattransaction', [
2535 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2536 'contribution_status_id' => 'Failed',
2539 $this->callAPISuccess('membership', 'create', [
2540 'id' => $membership['id'],
2541 'end_date' => 'yesterday',
2542 'status_id' => 'Expired',
2545 $contribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
2546 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2547 'contribution_status_id' => 'Completed',
2548 'trxn_id' => 'bobsled',
2551 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
2552 'id' => $membership['id'],
2553 'return' => 'status_id',
2556 $membership = $this->callAPISuccess('membership', 'get', [
2557 'id' => $membership['id'],
2560 $this->assertEquals('New', CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
2562 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2563 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2564 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2568 * This is one of those tests that locks in existing behaviour.
2570 * I feel like correct behaviour is arguable & has been discussed in the past. However, if the membership has
2571 * a date which says it should be expired then the result of repeattransaction is to push that date
2572 * to be one membership term from 'now' with status 'new'.
2574 public function testRepeattransactionRenewMembershipOldMembership() {
2575 $entities = $this->setUpAutoRenewMembership();
2576 $newStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'New');
2577 $membership = $this->callAPISuccess('Membership', 'create', [
2578 'id' => $entities[1]['id'],
2579 'join_date' => '4 months ago',
2580 'start_date' => '3 months ago',
2581 'end_date' => '2 months ago',
2583 $membership = $membership['values'][$membership['id']];
2585 // This status does not appear to be calculated at all and is set to 'new'. Feels like a bug.
2586 $this->assertEquals($newStatusID, $membership['status_id']);
2588 // So it seems renewing this expired membership results in it's new status being current and it being pushed to a future date
2589 $this->callAPISuccess('Contribution', 'repeattransaction', ['original_contribution_id' => $entities[0]['id'], 'contribution_status_id' => 'Completed']);
2590 $membership = $this->callAPISuccessGetSingle('Membership', ['id' => $membership['id']]);
2591 // If this date calculation winds up being flakey the spirit of the test would be maintained by just checking
2592 // date is greater than today.
2593 $this->assertEquals(date('Y-m-d', strtotime('+ 1 month -1 day')), $membership['end_date']);
2594 $this->assertEquals($newStatusID, $membership['membership_type_id']);
2598 * CRM-19945 Tests that Contribute.repeattransaction DOES NOT renew a membership when contribution status=Failed
2600 * @dataProvider contributionStatusProvider
2602 * @throws \CRM_Core_Exception
2604 public function testRepeatTransactionMembershipRenewContributionNotCompleted($contributionStatus): void
{
2605 // Completed status should renew so we don't test that here
2606 // In Progress status was never actually intended to be available for contributions.
2607 // Partially paid is not valid.
2608 if (in_array($contributionStatus['name'], ['Completed', 'In Progress', 'Partially paid'])) {
2611 [$originalContribution, $membership] = $this->setUpAutoRenewMembership();
2613 $this->callAPISuccess('Contribution', 'repeattransaction', [
2614 'original_contribution_id' => $originalContribution['id'],
2615 'contribution_status_id' => 'Completed',
2618 $this->callAPISuccess('membership', 'create', [
2619 'id' => $membership['id'],
2620 'end_date' => 'yesterday',
2621 'status_id' => 'Expired',
2624 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2625 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2626 'contribution_status_id' => $contributionStatus['name'],
2627 'trxn_id' => 'bobsled',
2630 $updatedMembership = $this->callAPISuccess('membership', 'getsingle', ['id' => $membership['id']]);
2632 $dateTime = new DateTime('yesterday');
2633 $this->assertEquals($dateTime->format('Y-m-d'), $updatedMembership['end_date']);
2634 $this->assertEquals(CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Expired'), $updatedMembership['status_id']);
2636 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2637 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2638 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2642 * Dataprovider provides contribution status as [optionvalue=>contribution_status_name]
2643 * FIXME: buildOptions seems to die in CRM_Core_Config::_construct when in test mode.
2646 * @throws \CiviCRM_API3_Exception
2648 public function contributionStatusProvider() {
2649 $contributionStatuses = civicrm_api3('OptionValue', 'get', [
2650 'return' => ['id', 'name'],
2651 'option_group_id' => 'contribution_status',
2653 foreach ($contributionStatuses['values'] as $statusName) {
2654 $statuses[] = [$statusName];
2660 * CRM-16397 test appropriate action if total amount has changed for single
2663 * @throws \CRM_Core_Exception
2665 public function testRepeatTransactionAlteredAmount(): void
{
2666 $paymentProcessorID = $this->paymentProcessorCreate();
2667 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2668 'contact_id' => $this->_individualId
,
2669 'installments' => '12',
2670 'frequency_interval' => '1',
2672 'contribution_status_id' => 1,
2673 'start_date' => '2012-01-01 00:00:00',
2674 'currency' => 'USD',
2675 'frequency_unit' => 'month',
2676 'payment_processor_id' => $paymentProcessorID,
2678 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2681 'contribution_recur_id' => $contributionRecur['id'],
2685 $this->callAPISuccess('contribution', 'repeattransaction', [
2686 'original_contribution_id' => $originalContribution['id'],
2687 'contribution_status_id' => 'Completed',
2689 'total_amount' => '400',
2694 'entity_id' => $originalContribution['id'],
2702 'financial_type_id',
2703 'deductible_amount',
2704 'price_field_value_id',
2708 $this->callAPISuccessGetSingle('contribution', [
2709 'total_amount' => 400,
2711 'net_amount' => 350,
2713 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2714 'entity_id' => $originalContribution['id'],
2716 $expectedLineItem = array_merge(
2717 $lineItem1['values'][0], [
2718 'line_total' => '400.00',
2719 'unit_price' => '400.00',
2723 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2724 'entity_id' => $originalContribution['id'] +
1,
2727 unset($expectedLineItem['id'], $expectedLineItem['entity_id'], $lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2728 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2732 * Test financial_type_id override behaviour with a single line item.
2734 * CRM-17718 a passed in financial_type_id is allowed to override the
2735 * original contribution where there is only one line item.
2737 * @throws \CRM_Core_Exception
2739 public function testRepeatTransactionPassedInFinancialType() {
2740 $originalContribution = $this->setUpRecurringContribution();
2742 $this->callAPISuccess('Contribution', 'repeattransaction', [
2743 'original_contribution_id' => $originalContribution['id'],
2744 'contribution_status_id' => 'Completed',
2746 'financial_type_id' => 2,
2749 'entity_id' => $originalContribution['id'],
2757 'financial_type_id',
2758 'deductible_amount',
2759 'price_field_value_id',
2764 $this->callAPISuccessGetSingle('Contribution', [
2765 'total_amount' => 100,
2766 'financial_type_id' => 2,
2768 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2769 'entity_id' => $originalContribution['id'],
2771 $expectedLineItem = array_merge(
2772 $lineItem1['values'][0], [
2773 'line_total' => '100.00',
2774 'unit_price' => '100.00',
2775 'financial_type_id' => 2,
2776 'contribution_type_id' => 2,
2779 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2780 'entity_id' => $originalContribution['id'] +
1,
2782 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2783 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2784 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2788 * Test Contribution with Order api.
2790 * @throws \CRM_Core_Exception|\CiviCRM_API3_Exception
2792 public function testContributionOrder() {
2793 $this->createContributionAndMembershipOrder();
2794 $contribution = $this->callAPISuccess('contribution', 'get')['values'][$this->ids
['Contribution'][0]];
2795 $this->assertEquals('Pending Label**', $contribution['contribution_status']);
2796 $membership = $this->callAPISuccessGetSingle('Membership', ['contact_id' => $this->ids
['Contact']['order']]);
2798 $this->callAPISuccess('Payment', 'create', [
2799 'contribution_id' => $this->ids
['Contribution'][0],
2800 'payment_instrument_id' => 'Check',
2801 'total_amount' => 300,
2803 $contribution = $this->callAPISuccess('contribution', 'get')['values'][$this->ids
['Contribution'][0]];
2804 $this->assertEquals('Completed', $contribution['contribution_status']);
2806 $lineItem = $this->callAPISuccess('LineItem', 'get', [
2808 'contribution_id' => $this->ids
['Contribution'][0],
2810 $this->assertCount(2, $lineItem);
2811 $this->assertEquals($this->ids
['Contribution'][0], $lineItem[0]['entity_id']);
2812 $this->assertEquals('civicrm_contribution', $lineItem[0]['entity_table']);
2813 $this->assertEquals($this->ids
['Contribution'][0], $lineItem[0]['contribution_id']);
2814 $this->assertEquals($this->ids
['Contribution'][0], $lineItem[1]['contribution_id']);
2815 $this->assertEquals('100.00', $lineItem[0]['line_total']);
2816 $this->assertEquals('200.00', $lineItem[1]['line_total']);
2817 $this->assertEquals($membership['id'], $lineItem[1]['entity_id']);
2818 $this->assertEquals('civicrm_membership', $lineItem[1]['entity_table']);
2822 * Test financial_type_id override behaviour with a single line item.
2824 * CRM-17718 a passed in financial_type_id is not allowed to override the
2825 * original contribution where there is more than one line item.
2827 * @throws \CRM_Core_Exception
2829 public function testRepeatTransactionPassedInFinancialTypeTwoLineItems(): void
{
2830 $this->_params
= $this->getParticipantOrderParams();
2831 $originalContribution = $this->setUpRecurringContribution();
2833 $this->callAPISuccess('Contribution', 'repeattransaction', [
2834 'original_contribution_id' => $originalContribution['id'],
2835 'contribution_status_id' => 'Completed',
2836 'trxn_id' => 'repeat',
2837 'financial_type_id' => 2,
2840 // Retrieve the new contribution and note the financial type passed in has been ignored.
2841 $contribution = $this->callAPISuccessGetSingle('Contribution', [
2842 'trxn_id' => 'repeat',
2844 $this->assertEquals(4, $contribution['financial_type_id']);
2846 $lineItems = $this->callAPISuccess('line_item', 'get', [
2847 'entity_id' => $contribution['id'],
2849 foreach ($lineItems as $lineItem) {
2850 $this->assertNotEquals(2, $lineItem['financial_type_id']);
2855 * CRM-17718 test appropriate action if financial type has changed for single
2858 * @throws \CRM_Core_Exception
2860 public function testRepeatTransactionUpdatedFinancialType(): void
{
2861 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2863 $this->callAPISuccess('contribution', 'repeattransaction', [
2864 'contribution_recur_id' => $originalContribution['id'],
2865 'contribution_status_id' => 'Completed',
2869 'entity_id' => $originalContribution['id'],
2877 'financial_type_id',
2878 'deductible_amount',
2879 'price_field_value_id',
2884 $this->callAPISuccessGetSingle('contribution', [
2885 'total_amount' => 100,
2886 'financial_type_id' => 2,
2888 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2889 'entity_id' => $originalContribution['id'],
2891 $expectedLineItem = array_merge(
2893 'line_total' => '100.00',
2894 'unit_price' => '100.00',
2895 'financial_type_id' => 2,
2896 'contribution_type_id' => 2,
2900 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2901 'entity_id' => $originalContribution['id'] +
1,
2903 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2904 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2905 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2909 * CRM-16397 test appropriate action if campaign has been passed in.
2911 public function testRepeatTransactionPassedInCampaign() {
2912 $paymentProcessorID = $this->paymentProcessorCreate();
2913 $campaignID = $this->campaignCreate();
2914 $campaignID2 = $this->campaignCreate();
2915 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2916 'contact_id' => $this->_individualId
,
2917 'installments' => '12',
2918 'frequency_interval' => '1',
2920 'contribution_status_id' => 1,
2921 'start_date' => '2012-01-01 00:00:00',
2922 'currency' => 'USD',
2923 'frequency_unit' => 'month',
2924 'payment_processor_id' => $paymentProcessorID,
2926 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2929 'contribution_recur_id' => $contributionRecur['id'],
2930 'campaign_id' => $campaignID,
2934 $this->callAPISuccess('contribution', 'repeattransaction', [
2935 'original_contribution_id' => $originalContribution['id'],
2936 'contribution_status_id' => 'Completed',
2938 'campaign_id' => $campaignID2,
2941 $this->callAPISuccessGetSingle('contribution', [
2942 'total_amount' => 100,
2943 'campaign_id' => $campaignID2,
2948 * CRM-17718 campaign stored on contribution recur gets priority.
2950 * This reflects the fact we permit people to update them.
2952 * @throws \CRM_Core_Exception
2954 public function testRepeatTransactionUpdatedCampaign(): void
{
2955 $paymentProcessorID = $this->paymentProcessorCreate();
2956 $campaignID = $this->campaignCreate();
2957 $campaignID2 = $this->campaignCreate();
2958 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2959 'contact_id' => $this->_individualId
,
2960 'installments' => '12',
2961 'frequency_interval' => '1',
2963 'contribution_status_id' => 1,
2964 'start_date' => '2012-01-01 00:00:00',
2965 'currency' => 'USD',
2966 'frequency_unit' => 'month',
2967 'payment_processor_id' => $paymentProcessorID,
2968 'campaign_id' => $campaignID,
2970 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2973 'contribution_recur_id' => $contributionRecur['id'],
2974 'campaign_id' => $campaignID2,
2978 $this->callAPISuccess('contribution', 'repeattransaction', [
2979 'original_contribution_id' => $originalContribution['id'],
2980 'contribution_status_id' => 'Completed',
2984 $this->callAPISuccessGetSingle('Contribution', [
2985 'total_amount' => 100,
2986 'campaign_id' => $campaignID,
2991 * CRM-20685 Repeattransaction produces incorrect Financial Type ID (in
2992 * specific circumstance) - if number of lineItems = 1.
2994 * This case happens when the line item & contribution do not have the same
2995 * type in his initiating transaction.
2997 * @throws \CRM_Core_Exception
2999 public function testRepeatTransactionUpdatedFinancialTypeAndNotEquals(): void
{
3000 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
3001 // This will made the trick to get the not equals behaviour.
3002 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 4]);
3003 $this->callAPISuccess('contribution', 'repeattransaction', [
3004 'contribution_recur_id' => $originalContribution['id'],
3005 'contribution_status_id' => 'Completed',
3009 'entity_id' => $originalContribution['id'],
3017 'financial_type_id',
3018 'deductible_amount',
3019 'price_field_value_id',
3023 $this->callAPISuccessGetSingle('contribution', [
3024 'total_amount' => 100,
3025 'financial_type_id' => 2,
3027 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
3028 'entity_id' => $originalContribution['id'],
3030 $expectedLineItem = array_merge(
3031 $lineItem1['values'][0], [
3032 'line_total' => '100.00',
3033 'unit_price' => '100.00',
3034 'financial_type_id' => 4,
3035 'contribution_type_id' => 4,
3039 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
3040 'entity_id' => $originalContribution['id'] +
1,
3042 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 1]);
3043 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
3044 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
3045 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
3049 * Test completing a transaction does not 'mess' with net amount (CRM-15960).
3051 public function testCompleteTransactionNetAmountOK() {
3052 $this->createLoggedInUser();
3053 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
3054 unset($params['net_amount']);
3055 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3056 $this->callAPISuccess('contribution', 'completetransaction', [
3057 'id' => $contribution['id'],
3059 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
3060 $this->assertEquals('Completed', $contribution['contribution_status']);
3061 $this->assertTrue(($contribution['total_amount'] - $contribution['net_amount']) == $contribution['fee_amount']);
3065 * CRM-14151 - Test completing a transaction via the API.
3067 public function testCompleteTransactionWithReceiptDateSet() {
3068 $this->swapMessageTemplateForTestTemplate();
3069 $mut = new CiviMailUtils($this, TRUE);
3070 $this->createLoggedInUser();
3071 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
3072 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3073 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id'], 'trxn_date' => date('Y-m-d')]);
3074 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'sequential' => 1]);
3075 $this->assertEquals('Completed', $contribution['values'][0]['contribution_status']);
3076 // Make sure receive_date is original date and make sure payment date is today
3077 $this->assertEquals('2012-05-11', date('Y-m-d', strtotime($contribution['values'][0]['receive_date'])));
3078 $payment = $this->callAPISuccess('payment', 'get', ['contribution_id' => $contribution['id'], 'sequential' => 1]);
3079 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($payment['values'][0]['trxn_date'])));
3080 $mut->checkMailLog([
3081 'Receipt - Contribution',
3082 'receipt_date:::' . date('Ymd'),
3085 $this->revertTemplateToReservedTemplate();
3089 * CRM-1960 - Test to ensure that completetransaction respects the is_email_receipt setting
3091 public function testCompleteTransactionWithEmailReceiptInput() {
3092 $contributionPage = $this->createReceiptableContributionPage();
3094 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3095 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
3096 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3097 // Complete the transaction overriding is_email_receipt to = FALSE
3098 $this->callAPISuccess('contribution', 'completetransaction', [
3099 'id' => $contribution['id'],
3100 'trxn_date' => date('2011-04-09'),
3101 'trxn_id' => 'kazam',
3102 'is_email_receipt' => 0,
3104 // Check if a receipt was issued
3105 $receipt_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receipt_date']);
3106 $this->assertEquals('', $receipt_date);
3110 * Test that $is_recur is assigned to the receipt.
3112 public function testCompleteTransactionForRecurring() {
3113 $this->mut
= new CiviMailUtils($this, TRUE);
3114 $this->swapMessageTemplateForTestTemplate();
3115 $recurring = $this->setUpRecurringContribution();
3116 $contributionPage = $this->createReceiptableContributionPage(['is_recur' => TRUE, 'recur_frequency_unit' => 'month', 'recur_interval' => 1]);
3118 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3119 $this->_params
['contribution_recur_id'] = $recurring['id'];
3121 $contribution = $this->setUpForCompleteTransaction();
3123 $this->callAPISuccess('contribution', 'completetransaction', [
3124 'id' => $contribution['id'],
3125 'trxn_date' => date('2011-04-09'),
3126 'trxn_id' => 'kazam',
3127 'is_email_receipt' => 1,
3130 $this->mut
->checkMailLog([
3132 'cancelSubscriptionUrl:::' . CIVICRM_UF_BASEURL
,
3135 $this->revertTemplateToReservedTemplate();
3139 * CRM-19710 - Test to ensure that completetransaction respects the input for
3140 * is_email_receipt setting.
3142 * If passed in it will override the default from contribution page.
3144 * @throws \CRM_Core_Exception
3146 public function testCompleteTransactionWithEmailReceiptInputTrue(): void
{
3147 $mut = new CiviMailUtils($this, TRUE);
3148 $this->createLoggedInUser();
3149 $contributionPageParams = ['is_email_receipt' => 0];
3150 // Create a Contribution Page with is_email_receipt = FALSE
3151 $contributionPageID = $this->createQuickConfigContributionPage($contributionPageParams);
3152 $this->_params
['contribution_page_id'] = $contributionPageID;
3153 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
3154 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3155 // Complete the transaction overriding is_email_receipt to = TRUE
3156 $this->callAPISuccess('contribution', 'completetransaction', [
3157 'id' => $contribution['id'],
3158 'is_email_receipt' => 1,
3160 $mut->checkMailLog([
3161 'Contribution Information',
3167 * Complete the transaction using the template with all the possible.
3169 public function testCompleteTransactionWithTestTemplate() {
3170 $this->swapMessageTemplateForTestTemplate();
3171 $contribution = $this->setUpForCompleteTransaction();
3172 $this->callAPISuccess('contribution', 'completetransaction', [
3173 'id' => $contribution['id'],
3174 'trxn_date' => date('2011-04-09'),
3175 'trxn_id' => 'kazam',
3177 $receive_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receive_date']);
3178 $this->mut
->checkMailLog([
3179 'email:::anthony_anderson@civicrm.org',
3183 'receive_date:::' . date('Ymd', strtotime($receive_date)),
3184 'receipt_date:::' . date('Ymd'),
3185 'title:::Contribution',
3187 'contactID:::' . $this->_params
['contact_id'],
3188 'contributionID:::' . $contribution['id'],
3189 'financialTypeId:::1',
3190 'financialTypeName:::Donation',
3193 $this->revertTemplateToReservedTemplate();
3197 * Complete the transaction using the template with all the possible.
3199 public function testCompleteTransactionContributionPageFromAddress() {
3200 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
3201 'receipt_from_name' => 'Mickey Mouse',
3202 'receipt_from_email' => 'mickey@mouse.com',
3203 'title' => 'Test Contribution Page',
3204 'financial_type_id' => 1,
3205 'currency' => 'NZD',
3206 'goal_amount' => 50,
3207 'is_pay_later' => 1,
3208 'is_monetary' => TRUE,
3209 'is_email_receipt' => TRUE,
3211 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3212 $contribution = $this->setUpForCompleteTransaction();
3213 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id']]);
3214 $this->mut
->checkMailLog([
3222 * Test completing first transaction in a recurring series.
3224 * The status should be set to 'in progress' and the next scheduled payment date calculated.
3226 * @dataProvider getScheduledDateData
3228 * @param array $dataSet
3230 * @throws \Exception
3232 public function testCompleteTransactionSetStatusToInProgress($dataSet) {
3233 $paymentProcessorID = $this->paymentProcessorCreate();
3234 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
3235 'contact_id' => $this->_individualId
,
3236 'installments' => '2',
3237 'frequency_interval' => '1',
3239 'contribution_status_id' => 'Pending',
3240 'start_date' => '2012-01-01 00:00:00',
3241 'currency' => 'USD',
3242 'frequency_unit' => 'month',
3243 'payment_processor_id' => $paymentProcessorID,
3244 ], $dataSet['data']));
3245 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
3248 'contribution_recur_id' => $contributionRecur['id'],
3249 'contribution_status_id' => 'Pending',
3250 'receive_date' => $dataSet['receive_date'],
3253 $this->callAPISuccess('Contribution', 'completetransaction', [
3254 'id' => $contribution,
3255 'receive_date' => $dataSet['receive_date'],
3257 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3258 'id' => $contributionRecur['id'],
3259 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
3261 $this->assertEquals(5, $contributionRecur['contribution_status_id']);
3262 $this->assertEquals($dataSet['expected'], $contributionRecur['next_sched_contribution_date']);
3263 $this->callAPISuccess('Contribution', 'create', array_merge(
3266 'contribution_recur_id' => $contributionRecur['id'],
3267 'contribution_status_id' => 'Completed',
3270 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3271 'id' => $contributionRecur['id'],
3272 'return' => ['contribution_status_id'],
3274 $this->assertEquals(1, $contributionRecur['contribution_status_id']);
3278 * Get dates for testing.
3282 public function getScheduledDateData() {
3284 $result[]['2016-08-31-1-month'] = [
3286 'start_date' => '2016-08-31',
3287 'frequency_interval' => 1,
3288 'frequency_unit' => 'month',
3290 'receive_date' => '2016-08-31',
3291 'expected' => '2016-10-01 00:00:00',
3293 $result[]['2012-01-01-1-month'] = [
3295 'start_date' => '2012-01-01',
3296 'frequency_interval' => 1,
3297 'frequency_unit' => 'month',
3299 'receive_date' => '2012-01-01',
3300 'expected' => '2012-02-01 00:00:00',
3302 $result[]['2012-01-01-1-month'] = [
3304 'start_date' => '2012-01-01',
3305 'frequency_interval' => 1,
3306 'frequency_unit' => 'month',
3308 'receive_date' => '2012-02-29',
3309 'expected' => '2012-03-29 00:00:00',
3311 $result['receive_date_includes_time']['2012-01-01-1-month'] = [
3313 'start_date' => '2012-01-01',
3314 'frequency_interval' => 1,
3315 'frequency_unit' => 'month',
3316 'next_sched_contribution_date' => '2012-02-29',
3318 'receive_date' => '2012-02-29 16:00:00',
3319 'expected' => '2012-03-29 00:00:00',
3325 * Test completing a pledge with the completeTransaction api..
3327 * Note that we are creating a logged in user because email goes out from
3330 public function testCompleteTransactionUpdatePledgePayment() {
3331 $this->swapMessageTemplateForTestTemplate();
3332 $mut = new CiviMailUtils($this, TRUE);
3333 $mut->clearMessages();
3334 $this->createLoggedInUser();
3335 $contributionID = $this->createPendingPledgeContribution();
3336 $this->callAPISuccess('contribution', 'completetransaction', [
3337 'id' => $contributionID,
3338 'trxn_date' => '1 Feb 2013',
3340 $pledge = $this->callAPISuccessGetSingle('Pledge', [
3341 'id' => $this->_ids
['pledge'],
3343 $this->assertEquals('Completed', $pledge['pledge_status']);
3345 $status = $this->callAPISuccessGetValue('PledgePayment', [
3346 'pledge_id' => $this->_ids
['pledge'],
3347 'return' => 'status_id',
3349 $this->assertEquals(1, $status);
3350 $mut->checkMailLog([
3352 // The `receive_date` should remain as it was created.
3353 // TODO: the latest payment transaction date (and maybe other details,
3354 // such as amount and payment instrument) would be a useful token to make
3356 'receive_date:::20120511000000',
3357 "receipt_date:::\n",
3360 $this->revertTemplateToReservedTemplate();
3364 * Test completing a transaction with an event via the API.
3366 * Note that we are creating a logged in user because email goes out from
3369 * @throws \CRM_Core_Exception
3371 public function testCompleteTransactionWithParticipantRecord(): void
{
3372 $mut = new CiviMailUtils($this, TRUE);
3373 $mut->clearMessages();
3374 $this->_individualId
= $this->createLoggedInUser();
3375 $this->_params
['source'] = 'Online Event Registration: Annual CiviCRM meet';
3376 $contributionID = $this->createPendingParticipantContribution();
3377 $this->createJoinedProfile(['entity_id' => $this->_ids
['event']['test'], 'entity_table' => 'civicrm_event']);
3378 $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']);
3379 $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']);
3380 $this->eliminateUFGroupOne();
3382 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contributionID]);
3383 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => ['contribution_source']]);
3384 $this->assertEquals('Online Event Registration: Annual CiviCRM meet', $contribution['contribution_source']);
3385 $participantStatus = $this->callAPISuccessGetValue('participant', [
3386 'id' => $this->_ids
['participant'],
3387 'return' => 'participant_status_id',
3389 $this->assertEquals(1, $participantStatus);
3391 //Assert only three activities are created.
3392 $activities = $this->callAPISuccess('Activity', 'get', [
3393 'contact_id' => $this->_individualId
,
3396 $this->assertCount(3, $activities);
3397 $activityNames = array_count_values(CRM_Utils_Array
::collect('activity_name', $activities));
3398 // record two activities before and after completing payment for Event registration
3399 $this->assertEquals(2, $activityNames['Event Registration']);
3400 // update the original 'Contribution' activity created after completing payment
3401 $this->assertEquals(1, $activityNames['Contribution']);
3403 $mut->checkMailLog([
3404 'Annual CiviCRM meet',
3406 'This is a confirmation that your registration has been received and your status has been updated to Registered.',
3407 'First Name: Logged In',
3411 ], ['Back end title', 'title_post_2', 'title_post_3']);
3416 * Test membership is renewed when transaction completed.
3418 * @throws \API_Exception
3420 public function testCompleteTransactionMembershipPriceSet(): void
{
3421 $this->createPriceSetWithPage('membership');
3422 $this->createInitialPaidMembership();
3423 $membership = $this->callAPISuccess('Membership', 'getsingle', [
3424 'id' => $this->getMembershipID(),
3425 'status_id' => 'Grace',
3426 'return' => ['end_date'],
3428 $this->assertEquals(date('Y-m-d', strtotime('yesterday')), $membership['end_date']);
3430 $this->createSubsequentPendingMembership();
3431 $this->callAPISuccess('Payment', 'create', [
3432 'contribution_id' => $this->getContributionID('second'),
3433 'total_amount' => 20,
3435 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3436 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 2 year')), $membership['end_date']);
3437 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3438 'membership_id' => $this->getMembershipID(),
3440 $this->assertEquals(4, $logs['count']);
3441 //Assert only three activities are created.
3442 $activityNames = (array) ActivityContact
::get(FALSE)
3443 ->addWhere('contact_id', '=', $this->_ids
['contact'])
3444 ->addSelect('activity_id.activity_type_id:name')->execute()->indexBy('activity_id.activity_type_id:name');
3445 $this->assertArrayHasKey('Contribution', $activityNames);
3446 $this->assertArrayHasKey('Membership Signup', $activityNames);
3447 $this->assertArrayHasKey('Change Membership Status', $activityNames);
3451 * Test if renewal activity is create after changing Pending contribution to
3452 * Completed via offline
3454 * @throws \CRM_Core_Exception|\CiviCRM_API3_Exception
3456 public function testPendingToCompleteContribution(): void
{
3457 $this->createPriceSetWithPage('membership');
3458 $this->setUpPendingContribution($this->_ids
['price_field_value'][0]);
3459 $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3460 // Case 1: Assert that Membership Signup Activity is created on Pending to Completed Contribution via backoffice
3461 $activity = $this->callAPISuccess('Activity', 'get', [
3462 'activity_type_id' => 'Membership Signup',
3463 'source_record_id' => $this->_ids
['membership'],
3464 'status_id' => 'Scheduled',
3466 $this->assertEquals(1, $activity['count']);
3467 $_REQUEST['id'] = $this->getContributionID();
3468 $_REQUEST['action'] = 'update';
3469 // change pending contribution to completed
3470 /* @var CRM_Contribute_Form_Contribution $form */
3471 $form = $this->getFormObject('CRM_Contribute_Form_Contribution', [
3472 'total_amount' => 20,
3475 'financial_type_id' => 1,
3476 'contact_id' => $this->_individualId
,
3477 'contribution_status_id' => 1,
3478 'billing_middle_name' => '',
3479 'billing_last_name' => 'Adams',
3480 'billing_street_address-5' => '790L Lincoln St S',
3481 'billing_city-5' => 'Mary knoll',
3482 'billing_state_province_id-5' => 1031,
3483 'billing_postal_code-5' => 10545,
3484 'billing_country_id-5' => 1228,
3485 'frequency_interval' => 1,
3486 'frequency_unit' => 'month',
3487 'installments' => '',
3488 'hidden_AdditionalDetail' => 1,
3489 'hidden_Premium' => 1,
3490 'from_email_address' => '"civi45" <civi45@civicrm.com>',
3491 'payment_processor_id' => $this->paymentProcessorID
,
3492 'currency' => 'USD',
3493 'contribution_page_id' => $this->_ids
['contribution_page'],
3494 'source' => 'Membership Signup and Renewal',
3497 $form->postProcess();
3499 // Case 2: After successful payment for Pending backoffice there are three activities created
3500 // 2.a Update status of existing Scheduled Membership Signup (created in step 1) to Completed
3501 $activity = $this->callAPISuccess('Activity', 'get', [
3502 'activity_type_id' => 'Membership Signup',
3503 'source_record_id' => $this->getMembershipID(),
3504 'status_id' => 'Completed',
3506 $this->assertEquals(1, $activity['count']);
3507 // 2.b Contribution activity created to record successful payment
3508 $activity = $this->callAPISuccess('Activity', 'get', [
3509 'activity_type_id' => 'Contribution',
3510 'source_record_id' => $this->getContributionID(),
3511 'status_id' => 'Completed',
3513 $this->assertEquals(1, $activity['count']);
3515 // 2.c 'Change membership type' activity created to record Membership status change from Grace to Current
3516 $activity = $this->callAPISuccess('Activity', 'get', [
3517 'activity_type_id' => 'Change Membership Status',
3518 'source_record_id' => $this->getMembershipID(),
3519 'status_id' => 'Completed',
3521 $this->assertEquals(1, $activity['count']);
3522 $this->assertEquals('Status changed from Pending to New', $activity['values'][$activity['id']]['subject']);
3523 $membershipLogs = $this->callAPISuccess('MembershipLog', 'get', ['sequential' => 1])['values'];
3524 $this->assertEquals('Pending', CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membershipLogs[0]['status_id']));
3525 $this->assertEquals('New', CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membershipLogs[1]['status_id']));
3526 //Create another pending contribution for renewal
3527 $this->setUpPendingContribution($this->_ids
['price_field_value'][0], 'second', [], ['entity_id' => $this->getMembershipID()], ['id' => $this->getMembershipID()]);
3529 //Update it to Failed.
3530 $form->_params
['id'] = $this->getContributionID('second');
3531 $form->_params
['contribution_status_id'] = 4;
3533 $form->testSubmit($form->_params
, CRM_Core_Action
::UPDATE
);
3534 //Existing membership should not get updated to expired.
3535 $membership = $this->callAPISuccess('Membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3536 $this->assertNotEquals(4, $membership['status_id']);
3540 * Test membership is renewed for 2 terms when transaction completed based on the line item having 2 terms as qty.
3542 * Also check that altering the qty for the most recent contribution results in repeattransaction picking it up.
3544 public function testCompleteTransactionMembershipPriceSetTwoTerms(): void
{
3545 $this->createPriceSetWithPage('membership');
3546 $this->createInitialPaidMembership();
3547 $this->createSubsequentPendingMembership();
3549 $this->callAPISuccess('Payment', 'create', [
3550 'contribution_id' => $this->getContributionID('second'),
3551 'total_amount' => 20,
3554 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->getMembershipID()]);
3555 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 2 years')), $membership['end_date']);
3557 $paymentProcessorID = $this->paymentProcessorAuthorizeNetCreate();
3559 $contributionRecurID = $this->callAPISuccess('ContributionRecur', 'create', ['contact_id' => $membership['contact_id'], 'payment_processor_id' => $paymentProcessorID, 'amount' => 20, 'frequency_interval' => 1])['id'];
3560 $this->callAPISuccess('Contribution', 'create', ['id' => $this->getContributionID(), 'contribution_recur_id' => $contributionRecurID]);
3561 $this->callAPISuccess('contribution', 'repeattransaction', ['contribution_recur_id' => $contributionRecurID, 'contribution_status_id' => 'Completed']);
3562 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->getMembershipID()]);
3563 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 4 years')), $membership['end_date']);
3565 // 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.
3566 $contribution = Contribution
::get()->setOrderBy(['id' => 'DESC'])->setSelect(['id'])->execute()->first();
3567 CRM_Core_DAO
::executeQuery('UPDATE civicrm_line_item SET price_field_value_id = ' . $this->_ids
['price_field_value'][0] . ' WHERE contribution_id = ' . $contribution['id']);
3568 $this->callAPISuccess('contribution', 'repeattransaction', ['contribution_recur_id' => $contributionRecurID, 'contribution_status_id' => 'Completed']);
3569 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->_ids
['membership']]);
3570 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 5 years')), $membership['end_date']);
3573 public function cleanUpAfterPriceSets() {
3574 $this->quickCleanUpFinancialEntities();
3575 $this->contactDelete($this->_ids
['contact']);
3579 * Set up a pending transaction with a specific price field id.
3581 * @param int $priceFieldValueID
3582 * @param string $key
3583 * @param array $contributionParams
3584 * @param array $lineParams
3585 * @param array $membershipParams
3587 public function setUpPendingContribution(int $priceFieldValueID, string $key = 'first', array $contributionParams = [], array $lineParams = [], array $membershipParams = []): void
{
3588 $contactID = $this->individualCreate();
3589 $membershipParams = array_merge([
3590 'contact_id' => $contactID,
3591 'membership_type_id' => $this->_ids
['membership_type'],
3592 ], $membershipParams);
3593 if ($key === 'first') {
3594 // If we want these after the initial we will set them.
3595 $membershipParams['start_date'] = 'yesterday - 1 year';
3596 $membershipParams['end_date'] = 'yesterday';
3597 $membershipParams['join_date'] = 'yesterday - 1 year';
3599 $contribution = $this->callAPISuccess('Order', 'create', array_merge([
3601 'contact_id' => $contactID,
3602 'receive_date' => date('Ymd'),
3603 'total_amount' => 20.00,
3604 'financial_type_id' => 1,
3605 'payment_instrument_id' => 'Credit Card',
3606 'non_deductible_amount' => 10.00,
3608 'contribution_page_id' => $this->_ids
['contribution_page'],
3613 'price_field_id' => $this->_ids
['price_field'][0],
3615 'entity_table' => 'civicrm_membership',
3618 'financial_type_id' => 1,
3619 'price_field_value_id' => $priceFieldValueID,
3622 'params' => $membershipParams,
3625 ], $contributionParams));
3627 $this->_ids
['contact'] = $contactID;
3628 $this->ids
['contribution'][$key] = $contribution['id'];
3629 $this->_ids
['membership'] = $this->callAPISuccessGetValue('MembershipPayment', ['return' => 'membership_id', 'contribution_id' => $contribution['id']]);
3633 * Test sending a mail via the API.
3635 * @throws \CRM_Core_Exception
3637 public function testSendMail(): void
{
3638 $mut = new CiviMailUtils($this, TRUE);
3639 $orderParams = $this->_params
;
3640 $orderParams['contribution_status_id'] = 'Pending';
3641 $orderParams['api.PaymentProcessor.pay'] = [
3642 'payment_processor_id' => $this->paymentProcessorID
,
3643 'credit_card_type' => 'Visa',
3644 'credit_card_number' => 41111111111111,
3648 $order = $this->callAPISuccess('Order', 'create', $orderParams);
3649 $this->callAPISuccess('Payment', 'create', ['total_amount' => 5, 'is_send_notification' => 0, 'order_id' => $order['id']]);
3650 $address = $this->callAPISuccess('Address', 'create', ['contribution_id' => $order['id'], 'name' => 'bob', 'contact_id' => 1, 'street_address' => 'blah']);
3651 $this->callAPISuccess('Contribution', 'create', ['id' => $order['id'], 'address_id' => $address['id']]);
3652 $this->callAPISuccess('contribution', 'sendconfirmation', [
3653 'id' => $order['id'],
3654 'receipt_from_email' => 'api@civicrm.org',
3656 $mut->checkMailLog([
3658 'Contribution Information',
3663 $this->checkCreditCardDetails($mut, $order['id']);
3665 $tplVars = CRM_Core_Smarty
::singleton()->get_template_vars();
3666 $this->assertEquals('bob', $tplVars['billingName']);
3670 * Test sending a mail via the API.
3671 * This simulates webform_civicrm using pay later contribution page
3673 * @throws \CRM_Core_Exception
3674 * @throws \CiviCRM_API3_Exception
3676 public function testSendConfirmationPayLater(): void
{
3677 $mut = new CiviMailUtils($this, TRUE);
3678 // Create contribution page
3680 'title' => 'Webform Contributions',
3681 'financial_type_id' => 1,
3682 'contribution_type_id' => 1,
3683 'is_confirm_enabled' => 1,
3684 'is_pay_later' => 1,
3685 'pay_later_text' => 'I will send payment by cheque',
3686 'pay_later_receipt' => 'Send your cheque payable to "CiviCRM LLC" to the office',
3688 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', $pageParams);
3690 // Create pay later contribution
3691 $contribution = $this->callAPISuccess('Order', 'create', [
3692 'contact_id' => $this->_individualId
,
3693 'financial_type_id' => 1,
3694 'is_pay_later' => 1,
3695 'contribution_status_id' => 2,
3696 'contribution_page_id' => $contributionPage['id'],
3697 'total_amount' => '10.00',
3702 'entity_table' => 'civicrm_contribution',
3703 'label' => 'My lineitem label',
3705 'unit_price' => '10.00',
3706 'line_total' => '10.00',
3715 civicrm_api3('contribution', 'sendconfirmation', [
3716 'id' => $contribution['id'],
3717 'receipt_from_email' => 'api@civicrm.org',
3720 catch (Exception
$e) {
3721 // Need to figure out how to stop this some other day
3722 // We don't care about the Payment Processor because this is Pay Later
3723 // The point of this test is to check we get the pay_later version of the mail
3724 if ($e->getMessage() !== 'Undefined variable: CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage') {
3729 // Retrieve mail & check it has the pay_later_receipt info
3730 $mut->getMostRecentEmail('raw');
3731 $mut->checkMailLog([
3733 $pageParams['pay_later_receipt'],
3737 $this->checkReceiptDetails($mut, $contributionPage['id'], $contribution['id'], $pageParams);
3742 * Check credit card details in sent mail via API
3744 * @param CiviMailUtils $mut
3745 * @param int $contributionID Contribution ID
3747 * @throws \CRM_Core_Exception
3749 public function checkCreditCardDetails($mut, $contributionID) {
3750 $this->callAPISuccess('contribution', 'create', $this->_params
);
3751 $this->callAPISuccess('contribution', 'sendconfirmation', [
3752 'id' => $contributionID,
3753 'receipt_from_email' => 'api@civicrm.org',
3754 'payment_processor_id' => $this->paymentProcessorID
,
3756 $mut->checkMailLog([
3758 'Billing Name and Address',
3760 'anthony_anderson@civicrm.org',
3767 * Check receipt details in sent mail via API
3769 * @param CiviMailUtils $mut
3770 * @param int $pageID Page ID
3771 * @param int $contributionID Contribution ID
3772 * @param array $pageParams
3774 * @throws \CRM_Core_Exception
3776 public function checkReceiptDetails($mut, $pageID, $contributionID, $pageParams): void
{
3778 'receipt_from_name' => 'Page FromName',
3779 'receipt_from_email' => 'page_from@email.com',
3780 'cc_receipt' => 'page_cc@email.com',
3781 'receipt_text' => 'Page Receipt Text',
3782 'pay_later_receipt' => $pageParams['pay_later_receipt'],
3785 'receipt_from_name' => 'Custom FromName',
3786 'receipt_from_email' => 'custom_from@email.com',
3787 'cc_receipt' => 'custom_cc@email.com',
3788 'receipt_text' => 'Test Custom Receipt Text',
3789 'pay_later_receipt' => 'Mail your check to test@example.com within 3 business days.',
3791 $this->callAPISuccess('ContributionPage', 'create', array_merge([
3793 'is_email_receipt' => 1,
3796 $this->callAPISuccess('contribution', 'sendconfirmation', array_merge([
3797 'id' => $contributionID,
3798 'payment_processor_id' => $this->paymentProcessorID
,
3799 ], $customReceipt));
3801 //Verify if custom receipt details are present in email.
3802 //Page receipt details shouldn't be included.
3803 $mut->checkMailLog(array_values($customReceipt), array_values($pageReceipt));
3807 * Test sending a mail via the API.
3809 public function testSendMailEvent() {
3810 $mut = new CiviMailUtils($this, TRUE);
3811 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
3812 $event = $this->eventCreate([
3813 'is_email_confirm' => 1,
3814 'confirm_from_email' => 'test@civicrm.org',
3816 $this->_eventID
= $event['id'];
3817 $participantParams = [
3818 'contact_id' => $this->_individualId
,
3819 'event_id' => $this->_eventID
,
3822 // to ensure it matches later on
3823 'register_date' => '2007-07-21 00:00:00',
3824 'source' => 'Online Event Registration: API Testing',
3827 $participant = $this->callAPISuccess('participant', 'create', $participantParams);
3828 $this->callAPISuccess('participant_payment', 'create', [
3829 'participant_id' => $participant['id'],
3830 'contribution_id' => $contribution['id'],
3832 $this->callAPISuccess('contribution', 'sendconfirmation', [
3833 'id' => $contribution['id'],
3834 'receipt_from_email' => 'api@civicrm.org',
3837 $mut->checkMailLog([
3838 'Annual CiviCRM meet',
3840 'To: "Mr. Anthony Anderson II" <anthony_anderson@civicrm.org>',
3846 * This function does a GET & compares the result against the $params.
3848 * Use as a double check on Creates.
3850 * @param array $params
3852 * @param bool $delete
3854 * @throws \CRM_Core_Exception
3856 public function contributionGetnCheck(array $params, int $id, bool $delete = TRUE): void
{
3857 $contribution = $this->callAPISuccess('Contribution', 'Get', [
3859 'return' => array_merge(['contribution_source'], array_keys($params)),
3862 $this->callAPISuccess('contribution', 'delete', ['id' => $id]);
3864 $this->assertAPISuccess($contribution, 0);
3865 $values = $contribution['values'][$contribution['id']];
3866 $params['receive_date'] = date('Y-m-d H:i:s', strtotime($params['receive_date']));
3867 // this is not returned in id format
3868 unset($params['payment_instrument_id']);
3869 $params['contribution_source'] = $params['source'];
3870 unset($params['source'], $params['sequential']);
3871 foreach ($params as $key => $value) {
3872 $this->assertEquals($value, $values[$key], $key . " value: $value doesn't match " . print_r($values, TRUE));
3877 * Create a pending contribution & linked pending pledge record.
3879 * @throws \CRM_Core_Exception
3881 public function createPendingPledgeContribution() {
3883 $pledgeID = $this->pledgeCreate(['contact_id' => $this->_individualId
, 'installments' => 1, 'amount' => 500]);
3884 $this->_ids
['pledge'] = $pledgeID;
3885 $contribution = $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, [
3886 'contribution_status_id' => 'Pending',
3887 'total_amount' => 500,
3889 $paymentID = $this->callAPISuccessGetValue('PledgePayment', [
3890 'options' => ['limit' => 1],
3893 $this->callAPISuccess('PledgePayment', 'create', [
3895 'contribution_id' =>
3896 $contribution['id'],
3897 'status_id' => 'Pending',
3898 'scheduled_amount' => 500,
3901 return $contribution['id'];
3905 * Create a pending contribution & linked pending participant record (along
3908 * @throws \CRM_Core_Exception
3910 public function createPendingParticipantContribution() {
3911 $this->_ids
['event']['test'] = $this->eventCreate(['is_email_confirm' => 1, 'confirm_from_email' => 'test@civicrm.org'])['id'];
3912 $participantID = $this->participantCreate(['event_id' => $this->_ids
['event']['test'], 'status_id' => 6, 'contact_id' => $this->_individualId
]);
3913 $this->_ids
['participant'] = $participantID;
3914 $params = array_merge($this->_params
, ['contact_id' => $this->_individualId
, 'contribution_status_id' => 2, 'financial_type_id' => 'Event Fee']);
3915 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3916 $this->callAPISuccess('participant_payment', 'create', [
3917 'contribution_id' => $contribution['id'],
3918 'participant_id' => $participantID,
3920 $this->callAPISuccess('line_item', 'get', [
3921 'entity_id' => $contribution['id'],
3922 'entity_table' => 'civicrm_contribution',
3923 'api.line_item.create' => [
3924 'entity_id' => $participantID,
3925 'entity_table' => 'civicrm_participant',
3928 return $contribution['id'];
3932 * Get financial transaction amount.
3934 * @param int $contId
3936 * @return null|string
3938 public function _getFinancialTrxnAmount($contId) {
3940 SUM( ft.total_amount ) AS total
3941 FROM civicrm_financial_trxn AS ft
3942 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.id = ceft.financial_trxn_id
3943 WHERE ceft.entity_table = 'civicrm_contribution'
3944 AND ceft.entity_id = {$contId}";
3946 return CRM_Core_DAO
::singleValueQuery($query);
3950 * @param int $contId
3952 * @return null|string
3954 public function _getFinancialItemAmount($contId) {
3955 $lineItem = key(CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution'));
3958 FROM civicrm_financial_item
3959 WHERE entity_table = 'civicrm_line_item'
3960 AND entity_id = {$lineItem}";
3961 return CRM_Core_DAO
::singleValueQuery($query);
3965 * @param int $contId
3968 public function _checkFinancialItem($contId, $context) {
3969 if ($context !== 'paylater') {
3971 'entity_id' => $contId,
3972 'entity_table' => 'civicrm_contribution',
3974 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($params, TRUE));
3976 'financial_trxn_id' => $trxn['financial_trxn_id'],
3977 'entity_table' => 'civicrm_financial_item',
3979 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3981 'id' => $entityTrxn['entity_id'],
3984 if ($context === 'paylater') {
3985 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution');
3986 foreach ($lineItems as $key => $item) {
3988 'entity_id' => $key,
3989 'entity_table' => 'civicrm_line_item',
3991 $compareParams = ['status_id' => 1];
3992 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3995 elseif ($context === 'refund') {
3998 'financial_account_id' => 1,
4002 elseif ($context === 'cancelPending') {
4005 'financial_account_id' => 1,
4009 elseif ($context === 'changeFinancial') {
4010 $lineKey = key(CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution'));
4012 'entity_id' => $lineKey,
4016 'financial_account_id' => 1,
4018 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4020 'financial_account_id' => 3,
4021 'entity_id' => $lineKey,
4027 if ($context !== 'paylater') {
4028 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
4033 * Check correct financial transaction entries were created for the change in payment instrument.
4035 * @param int $contributionID
4036 * @param int $originalInstrumentID
4037 * @param int $newInstrumentID
4038 * @param int $amount
4040 public function checkFinancialTrxnPaymentInstrumentChange($contributionID, $originalInstrumentID, $newInstrumentID, $amount = 100) {
4042 $entityFinancialTrxns = $this->getFinancialTransactionsForContribution($contributionID);
4044 $originalTrxnParams = [
4045 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($originalInstrumentID),
4046 'payment_instrument_id' => $originalInstrumentID,
4047 'amount' => $amount,
4051 $reversalTrxnParams = [
4052 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($originalInstrumentID),
4053 'payment_instrument_id' => $originalInstrumentID,
4054 'amount' => -$amount,
4059 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($newInstrumentID),
4060 'payment_instrument_id' => $newInstrumentID,
4061 'amount' => $amount,
4065 foreach ([$originalTrxnParams, $reversalTrxnParams, $newTrxnParams] as $index => $transaction) {
4066 $entityFinancialTrxn = $entityFinancialTrxns[$index];
4067 $this->assertEquals($entityFinancialTrxn['amount'], $transaction['amount']);
4069 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', [
4070 'id' => $entityFinancialTrxn['financial_trxn_id'],
4072 $this->assertEquals($transaction['status_id'], $financialTrxn['status_id']);
4073 $this->assertEquals($transaction['amount'], $financialTrxn['total_amount']);
4074 $this->assertEquals($transaction['amount'], $financialTrxn['net_amount']);
4075 $this->assertEquals(0, $financialTrxn['fee_amount']);
4076 $this->assertEquals($transaction['payment_instrument_id'], $financialTrxn['payment_instrument_id']);
4077 $this->assertEquals($transaction['to_financial_account_id'], $financialTrxn['to_financial_account_id']);
4080 $this->assertEquals(1, $financialTrxn['is_payment']);
4081 $this->assertEquals('USD', $financialTrxn['currency']);
4082 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($financialTrxn['trxn_date'])));
4087 * Check financial transaction.
4089 * @todo break this down into sensible functions - most calls to it only use a few lines out of the big if.
4091 * @param array $contribution
4092 * @param string $context
4093 * @param int $instrumentId
4094 * @param array $extraParams
4096 public function _checkFinancialTrxn($contribution, $context, $instrumentId = NULL, $extraParams = []) {
4097 $financialTrxns = $this->getFinancialTransactionsForContribution($contribution['id']);
4098 $trxn = array_pop($financialTrxns);
4101 'id' => $trxn['financial_trxn_id'],
4103 if ($context === 'payLater') {
4106 'from_financial_account_id' => CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is'),
4109 elseif ($context === 'refund') {
4111 'to_financial_account_id' => 6,
4112 'total_amount' => -100,
4114 'trxn_date' => '2015-01-01 09:00:00',
4115 'trxn_id' => 'the refund',
4118 elseif ($context === 'cancelPending') {
4120 'to_financial_account_id' => 7,
4121 'total_amount' => -100,
4125 elseif ($context === 'changeFinancial' ||
$context === 'paymentInstrument') {
4126 // @todo checkFinancialTrxnPaymentInstrumentChange instead for paymentInstrument.
4127 // It does the same thing with greater readability.
4128 // @todo remove handling for
4131 'entity_id' => $contribution['id'],
4132 'entity_table' => 'civicrm_contribution',
4135 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
4137 'id' => $trxn['financial_trxn_id'],
4139 if (empty($extraParams)) {
4141 'total_amount' => -100,
4145 elseif ($context !== 'changeFinancial') {
4147 'total_amount' => 100,
4151 if ($context === 'paymentInstrument') {
4152 $compareParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($instrumentId);
4153 $compareParams['payment_instrument_id'] = $instrumentId;
4156 $compareParams['to_financial_account_id'] = 12;
4158 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams1, array_merge($compareParams, $extraParams));
4159 $compareParams['total_amount'] = 100;
4160 // Reverse the extra params now that we will be checking the new positive transaction.
4161 if ($context === 'changeFinancial' && !empty($extraParams)) {
4162 foreach ($extraParams as $param => $value) {
4163 $extraParams[$param] = 0 - $value;
4168 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $params, array_merge($compareParams, $extraParams));
4174 public function _addPaymentInstrument() {
4175 $gId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'payment_instrument', 'id', 'name');
4177 'option_group_id' => $gId,
4178 'label' => 'Test Card',
4179 'name' => 'Test Card',
4184 $optionValue = $this->callAPISuccess('option_value', 'create', $optionParams);
4185 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
4186 $financialParams = [
4187 'entity_table' => 'civicrm_option_value',
4188 'entity_id' => $optionValue['id'],
4189 'account_relationship' => $relationTypeId,
4190 'financial_account_id' => 7,
4192 CRM_Financial_BAO_FinancialTypeAccount
::add($financialParams);
4193 $this->assertNotEmpty($optionValue['values'][$optionValue['id']]['value']);
4194 return $optionValue['values'][$optionValue['id']]['value'];
4197 public function _deletedAddedPaymentInstrument() {
4198 $result = $this->callAPISuccess('OptionValue', 'get', [
4199 'option_group_id' => 'payment_instrument',
4200 'name' => 'Test Card',
4204 if ($id = CRM_Utils_Array
::value('id', $result)) {
4205 $this->callAPISuccess('OptionValue', 'delete', ['id' => $id]);
4210 * Set up the basic recurring contribution for tests.
4212 * @param array $generalParams
4213 * Parameters that can be merged into the recurring AND the contribution.
4215 * @param array $recurParams
4216 * Parameters to merge into the recur only.
4219 * @throws \CRM_Core_Exception
4221 protected function setUpRecurringContribution($generalParams = [], $recurParams = []) {
4222 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4223 'contact_id' => $this->_individualId
,
4224 'installments' => '12',
4225 'frequency_interval' => '1',
4227 'contribution_status_id' => 1,
4228 'start_date' => '2012-01-01 00:00:00',
4229 'currency' => 'USD',
4230 'frequency_unit' => 'month',
4231 'payment_processor_id' => $this->paymentProcessorID
,
4232 ], $generalParams, $recurParams));
4233 $contributionParams = array_merge(
4236 'contribution_recur_id' => $contributionRecur['id'],
4237 'contribution_status_id' => 'Pending',
4239 $contributionParams['api.Payment.create'] = ['total_amount' => $contributionParams['total_amount']];
4240 $originalContribution = $this->callAPISuccess('Order', 'create', $contributionParams);
4241 return $originalContribution;
4245 * Set up a basic auto-renew membership for tests.
4247 * @param array $generalParams
4248 * Parameters that can be merged into the recurring AND the contribution.
4250 * @param array $recurParams
4251 * Parameters to merge into the recur only.
4254 * @throws \CRM_Core_Exception
4256 protected function setUpAutoRenewMembership($generalParams = [], $recurParams = []) {
4257 $newContact = $this->callAPISuccess('Contact', 'create', [
4258 'contact_type' => 'Individual',
4259 'sort_name' => 'McTesterson, Testy',
4260 'display_name' => 'Testy McTesterson',
4261 'preferred_language' => 'en_US',
4262 'preferred_mail_format' => 'Both',
4263 'first_name' => 'Testy',
4264 'last_name' => 'McTesterson',
4265 'contact_is_deleted' => '0',
4267 'email' => 'tmctesterson@example.com',
4270 $membershipType = $this->callAPISuccess('MembershipType', 'create', [
4271 'domain_id' => 'Default Domain Name',
4272 'member_of_contact_id' => 1,
4273 'financial_type_id' => 'Member Dues',
4274 'duration_unit' => 'month',
4275 'duration_interval' => 1,
4276 'period_type' => 'rolling',
4277 'name' => 'Standard Member',
4278 'minimum_fee' => 100,
4280 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4281 'contact_id' => $newContact['id'],
4282 'installments' => '12',
4283 'frequency_interval' => '1',
4285 'contribution_status_id' => 1,
4286 'start_date' => '2012-01-01 00:00:00',
4287 'currency' => 'USD',
4288 'frequency_unit' => 'month',
4289 'payment_processor_id' => $this->paymentProcessorID
,
4290 ], $generalParams, $recurParams));
4292 $originalContribution = $this->callAPISuccess('Order', 'create', array_merge(
4295 'contact_id' => $newContact['id'],
4296 'contribution_recur_id' => $contributionRecur['id'],
4297 'financial_type_id' => 'Member Dues',
4298 'api.Payment.create' => ['total_amount' => 100, 'payment_instrument_id' => 'Credit card'],
4299 'invoice_id' => 2345,
4304 'membership_type_id' => $membershipType['id'],
4305 'financial_type_id' => 'Member Dues',
4306 'line_total' => $generalParams['total_amount'] ??
100,
4310 'contact_id' => $newContact['id'],
4311 'contribution_recur_id' => $contributionRecur['id'],
4312 'membership_type_id' => $membershipType['id'],
4319 $lineItem = $this->callAPISuccess('LineItem', 'getsingle', []);
4320 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
4321 $membership = $this->callAPISuccess('Membership', 'getsingle', ['id' => $lineItem['entity_id']]);
4322 $this->callAPISuccess('LineItem', 'getsingle', []);
4323 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']], 1);
4325 return [$originalContribution, $membership];
4329 * Set up a repeat transaction.
4331 * @param array $recurParams
4332 * @param string $flag
4333 * @param array $contributionParams
4337 protected function setUpRepeatTransaction(array $recurParams, $flag, array $contributionParams = []) {
4338 $paymentProcessorID = $this->paymentProcessorCreate();
4339 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4340 'contact_id' => $this->_individualId
,
4341 'installments' => '12',
4342 'frequency_interval' => '1',
4344 'contribution_status_id' => 1,
4345 'start_date' => '2012-01-01 00:00:00',
4346 'currency' => 'USD',
4347 'frequency_unit' => 'month',
4348 'payment_processor_id' => $paymentProcessorID,
4351 $originalContribution = '';
4352 if ($flag === 'multiple') {
4353 // CRM-19309 create a contribution + also add in line_items (plural):
4354 $this->createContributionWithTwoLineItemsAgainstPriceSet([
4355 'contact_id' => $this->_individualId
,
4356 'contribution_recur_id' => $contributionRecur['id'],
4358 $originalContribution = $this->callAPISuccessGetSingle('Contribution', ['contribution_recur_id' => $contributionRecur['id'], 'return' => 'id']);
4360 elseif ($flag === 'single') {
4361 $params = array_merge($this->_params
, ['contribution_recur_id' => $contributionRecur['id']]);
4362 $params = array_merge($params, $contributionParams);
4363 $originalContribution = $this->callAPISuccess('Order', 'create', $params);
4364 // Note the saved contribution amount will include tax.
4365 $this->callAPISuccess('Payment', 'create', [
4366 'contribution_id' => $originalContribution['id'],
4367 'total_amount' => $originalContribution['values'][$originalContribution['id']]['total_amount'],
4370 $originalContribution['contribution_recur_id'] = $contributionRecur['id'];
4371 $originalContribution['payment_processor_id'] = $paymentProcessorID;
4372 return $originalContribution;
4376 * Common set up routine.
4379 * @throws \CRM_Core_Exception
4381 protected function setUpForCompleteTransaction(): array {
4382 $this->mut
= new CiviMailUtils($this, TRUE);
4383 $this->createLoggedInUser();
4384 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
4385 return $this->callAPISuccess('Contribution', 'create', $params);
4389 * Test repeat contribution uses the Payment Processor' payment_instrument setting.
4391 * @throws \CRM_Core_Exception
4393 public function testRepeatTransactionWithNonCreditCardDefault() {
4394 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
4395 'contact_id' => $this->_individualId
,
4396 'installments' => '12',
4397 'frequency_interval' => '1',
4399 'contribution_status_id' => 1,
4400 'start_date' => '2012-01-01 00:00:00',
4401 'currency' => 'USD',
4402 'frequency_unit' => 'month',
4403 'payment_processor_id' => $this->paymentProcessorID
,
4405 $contribution1 = $this->callAPISuccess('contribution', 'create', array_merge(
4407 ['contribution_recur_id' => $contributionRecur['id'], 'payment_instrument_id' => 2])
4409 $contribution2 = $this->callAPISuccess('contribution', 'repeattransaction', [
4410 'contribution_status_id' => 'Completed',
4411 'trxn_id' => 'blah',
4412 'original_contribution_id' => $contribution1,
4414 $this->assertEquals('Debit Card', CRM_Contribute_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $contribution2['values'][$contribution2['id']]['payment_instrument_id']));
4418 * CRM-20008 Tests repeattransaction creates pending membership.
4420 * @throws \CRM_Core_Exception
4422 public function testRepeatTransactionMembershipCreatePendingContribution(): void
{
4423 [$originalContribution, $membership] = $this->setUpAutoRenewMembership();
4424 $this->callAPISuccess('membership', 'create', [
4425 'id' => $membership['id'],
4426 'end_date' => 'yesterday',
4427 'status_id' => 'Expired',
4429 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4430 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
4431 'contribution_status_id' => 'Pending',
4434 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
4435 'id' => $membership['id'],
4436 'return' => 'status_id',
4439 // Let's see if the membership payments got created while we're at it.
4440 $membershipPayments = $this->callAPISuccess('MembershipPayment', 'get', [
4441 'membership_id' => $membership['id'],
4443 $this->assertEquals(2, $membershipPayments['count']);
4445 $this->assertEquals('Expired', CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
4446 $this->callAPISuccess('Contribution', 'completetransaction', ['id' => $repeatedContribution['id']]);
4447 $membership = $this->callAPISuccessGetSingle('membership', [
4448 'id' => $membership['id'],
4449 'return' => 'status_id, end_date',
4451 $this->assertEquals('New', CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membership['status_id']));
4452 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 month')), $membership['end_date']);
4456 * Test sending a mail via the API.
4458 * @throws \CRM_Core_Exception
4460 public function testSendMailWithAPISetFromDetails() {
4461 $mut = new CiviMailUtils($this, TRUE);
4462 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
4463 $this->callAPISuccess('contribution', 'sendconfirmation', [
4464 'id' => $contribution['id'],
4465 'receipt_from_email' => 'api@civicrm.org',
4466 'receipt_from_name' => 'CiviCRM LLC',
4468 $mut->checkMailLog([
4469 'From: CiviCRM LLC <api@civicrm.org>',
4470 'Contribution Information',
4478 * Test sending a mail via the API.
4480 public function testSendMailWithNoFromSetFallToDomain() {
4481 $this->createLoggedInUser();
4482 $mut = new CiviMailUtils($this, TRUE);
4483 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
4484 $this->callAPISuccess('contribution', 'sendconfirmation', [
4485 'id' => $contribution['id'],
4487 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4488 $mut->checkMailLog([
4489 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4490 'Contribution Information',
4498 * Test sending a mail via the API.
4500 * @throws \CRM_Core_Exception
4502 public function testSendMailWithRepeatTransactionAPIFalltoDomain() {
4503 $this->createLoggedInUser();
4504 $mut = new CiviMailUtils($this, TRUE);
4505 $contribution = $this->setUpRepeatTransaction([], 'single');
4506 $this->callAPISuccess('contribution', 'repeattransaction', [
4507 'contribution_status_id' => 'Completed',
4509 'original_contribution_id' => $contribution,
4511 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4512 $mut->checkMailLog([
4513 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4514 'Contribution Information',
4523 * Test sending a mail via the API.
4525 * @throws \CRM_Core_Exception
4527 public function testSendMailWithRepeatTransactionAPIFalltoContributionPage() {
4528 $mut = new CiviMailUtils($this, TRUE);
4529 $contributionPage = $this->contributionPageCreate(['receipt_from_name' => 'CiviCRM LLC', 'receipt_from_email' => 'contributionpage@civicrm.org', 'is_email_receipt' => 1]);
4530 $paymentProcessorID = $this->paymentProcessorCreate();
4531 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
4532 'contact_id' => $this->_individualId
,
4533 'installments' => '12',
4534 'frequency_interval' => '1',
4536 'contribution_status_id' => 1,
4537 'start_date' => '2012-01-01 00:00:00',
4538 'currency' => 'USD',
4539 'frequency_unit' => 'month',
4540 'payment_processor_id' => $paymentProcessorID,
4542 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4545 'contribution_recur_id' => $contributionRecur['id'],
4546 'contribution_page_id' => $contributionPage['id'],
4549 $this->callAPISuccess('Contribution', 'repeattransaction', [
4550 'contribution_status_id' => 'Completed',
4552 'original_contribution_id' => $originalContribution,
4555 $mut->checkMailLog([
4556 'From: CiviCRM LLC <contributionpage@civicrm.org>',
4557 'Contribution Information',
4565 * Test sending a mail via the API.
4567 * @throws \CRM_Core_Exception
4569 public function testSendMailWithRepeatTransactionAPIFalltoSystemFromNoDefaultFrom(): void
{
4570 $mut = new CiviMailUtils($this, TRUE);
4571 $originalContribution = $this->setUpRepeatTransaction([], 'single');
4572 $fromEmail = $this->callAPISuccess('optionValue', 'get', ['is_default' => 1, 'option_group_id' => 'from_email_address', 'sequential' => 1]);
4573 foreach ($fromEmail['values'] as $from) {
4574 $this->callAPISuccess('optionValue', 'create', ['is_default' => 0, 'id' => $from['id']]);
4576 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => CRM_Core_Config
::domainID()]);
4577 $this->callAPISuccess('contribution', 'repeattransaction', [
4578 'contribution_status_id' => 'Completed',
4580 'original_contribution_id' => $originalContribution,
4582 $mut->checkMailLog([
4583 'From: ' . $domain['name'] . ' <' . $domain['domain_email'] . '>',
4584 'Contribution Information',
4592 * Create a Contribution Page with is_email_receipt = TRUE.
4594 * @param array $params
4595 * Params to overwrite with.
4599 protected function createReceiptableContributionPage($params = []) {
4600 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', array_merge([
4601 'receipt_from_name' => 'Mickey Mouse',
4602 'receipt_from_email' => 'mickey@mouse.com',
4603 'title' => 'Test Contribution Page',
4604 'financial_type_id' => 1,
4605 'currency' => 'CAD',
4606 'is_monetary' => TRUE,
4607 'is_email_receipt' => TRUE,
4609 return $contributionPage;
4613 * function to test card_type and pan truncation.
4615 * @throws \CRM_Core_Exception
4617 public function testCardTypeAndPanTruncation() {
4618 $creditCardTypeIDs = array_flip(CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'));
4619 $contactId = $this->individualCreate();
4621 'contact_id' => $contactId,
4622 'receive_date' => '2016-01-20',
4623 'total_amount' => 100,
4624 'financial_type_id' => 1,
4625 'payment_instrument' => 'Credit Card',
4626 'card_type_id' => $creditCardTypeIDs['Visa'],
4627 'pan_truncation' => 4567,
4629 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4630 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contribution['id'], 'DESC');
4631 $financialTrxn = $this->callAPISuccessGetSingle(
4634 'id' => $lastFinancialTrxnId['financialTrxnId'],
4635 'return' => ['card_type_id', 'pan_truncation'],
4638 $this->assertEquals(CRM_Utils_Array
::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Visa']);
4639 $this->assertEquals(CRM_Utils_Array
::value('pan_truncation', $financialTrxn), 4567);
4641 'id' => $contribution['id'],
4642 'pan_truncation' => 2345,
4643 'card_type_id' => $creditCardTypeIDs['Amex'],
4645 $this->callAPISuccess('contribution', 'create', $params);
4646 $financialTrxn = $this->callAPISuccessGetSingle(
4649 'id' => $lastFinancialTrxnId['financialTrxnId'],
4650 'return' => ['card_type_id', 'pan_truncation'],
4653 $this->assertEquals(CRM_Utils_Array
::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Amex']);
4654 $this->assertEquals(CRM_Utils_Array
::value('pan_truncation', $financialTrxn), 2345);
4658 * Test repeat contribution uses non default currency
4660 * @see https://issues.civicrm.org/jira/projects/CRM/issues/CRM-20678
4661 * @throws \CRM_Core_Exception
4663 public function testRepeatTransactionWithDifferenceCurrency() {
4664 $originalContribution = $this->setUpRepeatTransaction(['currency' => 'AUD'], 'single', ['currency' => 'AUD']);
4665 $contribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
4666 'original_contribution_id' => $originalContribution['id'],
4667 'contribution_status_id' => 'Completed',
4670 $this->assertEquals('AUD', $contribution['values'][$contribution['id']]['currency']);
4674 * Get the financial items for the contribution.
4676 * @param int $contributionID
4679 * Array of associated financial items.
4681 protected function getFinancialTransactionsForContribution($contributionID) {
4683 'entity_id' => $contributionID,
4684 'entity_table' => 'civicrm_contribution',
4686 // @todo the following function has naming errors & has a weird signature & appears to
4687 // only be called from test classes. Move into test suite & maybe just use api
4688 // from this function.
4689 return array_merge(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($trxnParams));
4693 * Test getunique api call for Contribution entity
4695 public function testContributionGetUnique() {
4696 $result = $this->callAPIAndDocument($this->entity
, 'getunique', [], __FUNCTION__
, __FILE__
);
4697 $this->assertEquals(2, $result['count']);
4698 $this->assertEquals(['trxn_id'], $result['values']['UI_contrib_trxn_id']);
4699 $this->assertEquals(['invoice_id'], $result['values']['UI_contrib_invoice_id']);
4703 * Test Repeat Transaction Contribution with Tax amount.
4705 * https://lab.civicrm.org/dev/core/issues/806
4707 * @throws \CRM_Core_Exception
4709 public function testRepeatContributionWithTaxAmount(): void
{
4710 $this->enableTaxAndInvoicing();
4711 $financialType = $this->callAPISuccess('financial_type', 'create', [
4712 'name' => 'Test taxable financial Type',
4716 $this->addTaxAccountToFinancialType($financialType['id']);
4717 $contribution = $this->setUpRepeatTransaction(
4721 'financial_type_id' => $financialType['id'],
4724 $this->callAPISuccess('contribution', 'repeattransaction', [
4725 'original_contribution_id' => $contribution['id'],
4726 'contribution_status_id' => 'Completed',
4727 'trxn_id' => 'test',
4729 $payments = $this->callAPISuccess('Contribution', 'get', ['sequential' => 1, 'return' => ['total_amount', 'tax_amount']])['values'];
4730 //Assert if first payment and repeated payment has the same contribution amount.
4731 $this->assertEquals($payments[0]['total_amount'], $payments[1]['total_amount']);
4732 $this->callAPISuccessGetCount('Contribution', [], 2);
4734 //Assert line item records.
4735 $lineItems = $this->callAPISuccess('LineItem', 'get', ['sequential' => 1])['values'];
4736 foreach ($lineItems as $lineItem) {
4737 $taxExclusiveAmount = $payments[0]['total_amount'] - $payments[0]['tax_amount'];
4738 $this->assertEquals($lineItem['unit_price'], $taxExclusiveAmount);
4739 $this->assertEquals($lineItem['line_total'], $taxExclusiveAmount);
4741 $this->callAPISuccessGetCount('Contribution', [], 2);
4744 public function testGetCurrencyOptions() {
4745 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4746 'field' => 'currency',
4748 $this->assertEquals('US Dollar', $result['values']['USD']);
4749 $this->assertNotContains('$', $result['values']);
4750 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4751 'field' => 'currency',
4752 'context' => 'abbreviate',
4754 $this->assertEquals('$', $result['values']['USD']);
4755 $this->assertNotContains('US Dollar', $result['values']);
4759 * @throws \API_Exception
4760 * @throws \CRM_Core_Exception
4761 * @throws \Civi\API\Exception\UnauthorizedException
4763 public function testSetCustomDataInCreateAndHook() {
4764 $this->createCustomGroupWithFieldOfType([], 'int');
4765 $this->ids
['CustomField']['text'] = (int) $this->createTextCustomField(['custom_group_id' => $this->ids
['CustomGroup']['Custom Group']])['id'];
4766 $this->hookClass
->setHook('civicrm_post', [
4768 'civicrmPostContributionCustom',
4770 $params = $this->_params
;
4771 $params['custom_' . $this->ids
['CustomField']['text']] = 'Some Text';
4772 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
4773 $getContribution = $this->callAPISuccess('Contribution', 'get', [
4774 'id' => $contribution['id'],
4775 'return' => ['id', 'custom_' . $this->ids
['CustomField']['text'], 'custom_' . $this->ids
['CustomField']['int']],
4777 $this->assertEquals(5, $getContribution['values'][$contribution['id']][$this->getCustomFieldName('int')]);
4778 $this->assertEquals('Some Text', $getContribution['values'][$contribution['id']]['custom_' . $this->ids
['CustomField']['text']]);
4779 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids
['CustomField']['text']]);
4780 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids
['CustomField']['int']]);
4781 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $this->ids
['CustomGroup']['Custom Group']]);
4785 * Implement post hook.
4788 * @param string $objectName
4789 * @param int|null $objectId
4791 * @throws \CRM_Core_Exception
4793 public function civicrmPostContributionCustom(string $op, string $objectName, ?
int $objectId): void
{
4794 if ($objectName === 'Contribution' && $op === 'create') {
4795 $this->callAPISuccess('Contribution', 'create', [
4797 'custom_' . $this->ids
['CustomField']['int'] => 5,
4803 * Test that passing in label for an option value linked to a custom field
4806 * @see dev/core#1816
4808 * @throws \API_Exception
4809 * @throws \CRM_Core_Exception
4811 public function testCustomValueOptionLabelTest(): void
{
4812 $this->createCustomGroupWithFieldOfType([], 'radio');
4813 $params = $this->_params
;
4814 $params['custom_' . $this->ids
['CustomField']['radio']] = 'Red Testing';
4815 $this->callAPISuccess('Contribution', 'Create', $params);
4819 * Test repeatTransaction with installments and next_sched_contribution_date
4821 * @dataProvider getRepeatTransactionNextSchedData
4823 * @param array $dataSet
4825 * @throws \CRM_Core_Exception
4827 public function testRepeatTransactionUpdateNextSchedContributionDate(array $dataSet): void
{
4828 $paymentProcessorID = $this->paymentProcessorCreate();
4829 // Create the contribution before the recur so it doesn't trigger the update of next_sched_contribution_date
4830 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
4833 'contribution_status_id' => 'Completed',
4834 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4837 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4838 'contact_id' => $this->_individualId
,
4839 'frequency_interval' => '1',
4841 'contribution_status_id' => 'Pending',
4842 'start_date' => '2012-01-01 00:00:00',
4843 'currency' => 'USD',
4844 'frequency_unit' => 'month',
4845 'payment_processor_id' => $paymentProcessorID,
4846 ], $dataSet['recur']));
4847 // Link the existing contribution to the recur *after* creating the recur.
4848 // If we just created the contribution now the next_sched_contribution_date would be automatically set
4849 // and we want to test the case when it is empty.
4850 $this->callAPISuccess('contribution', 'create', [
4851 'id' => $contribution['id'],
4852 'contribution_recur_id' => $contributionRecur['id'],
4855 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4856 'id' => $contributionRecur['id'],
4857 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4859 // Check that next_sched_contribution_date is empty
4860 $this->assertEquals('', $contributionRecur['next_sched_contribution_date'] ??
'');
4862 $this->callAPISuccess('Contribution', 'repeattransaction', [
4863 'contribution_status_id' => 'Completed',
4864 'contribution_recur_id' => $contributionRecur['id'],
4865 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4867 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4868 'id' => $contributionRecur['id'],
4869 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4871 // Check that recur has status "In Progress"
4872 $this->assertEquals(
4873 (string) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][0]['expectedRecurStatus']),
4874 $contributionRecur['contribution_status_id']
4876 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4877 $this->assertEquals($dataSet['repeat'][0]['expectedNextSched'], $contributionRecur['next_sched_contribution_date']);
4879 // Now call Contribution.repeattransaction again and check that the next_sched_contribution_date has moved forward by 1 period again
4880 $this->callAPISuccess('Contribution', 'repeattransaction', [
4881 'contribution_status_id' => 'Completed',
4882 'contribution_recur_id' => $contributionRecur['id'],
4883 'receive_date' => $dataSet['repeat'][1]['receive_date'],
4885 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4886 'id' => $contributionRecur['id'],
4887 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4889 // Check that recur has status "In Progress" or "Completed" depending on whether number of installments has been reached
4890 $this->assertEquals(
4891 (string) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][1]['expectedRecurStatus']),
4892 $contributionRecur['contribution_status_id']
4894 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4895 $this->assertEquals($dataSet['repeat'][1]['expectedNextSched'], $contributionRecur['next_sched_contribution_date'] ??
'');
4899 * Get dates for testing.
4903 public function getRepeatTransactionNextSchedData(): array {
4904 // Both these tests handle/test the case that next_sched_contribution_date is empty when Contribution.repeattransaction
4905 // is called for the first time. Historically setting it was inconsistent but on new updates it should always be set.
4907 * This tests that calling Contribution.repeattransaction with installments does the following:
4908 * - For the first call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4909 * to match next expected receive_date.
4910 * - Once the 3rd contribution is created contributionRecur status = completed and next_sched_contribution_date = ''.
4912 $result['receive_date_includes_time_with_installments']['2012-01-01-1-month'] = [
4914 'start_date' => '2012-01-01',
4915 'frequency_interval' => 1,
4916 'installments' => '3',
4917 'frequency_unit' => 'month',
4921 'receive_date' => '2012-02-29 16:00:00',
4922 'expectedNextSched' => '2012-03-29 00:00:00',
4923 'expectedRecurStatus' => 'In Progress',
4926 'receive_date' => '2012-03-29 16:00:00',
4927 'expectedNextSched' => '',
4928 'expectedRecurStatus' => 'Completed',
4933 * This tests that calling Contribution.repeattransaction with no installments does the following:
4934 * - For the each call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4935 * to match next expected receive_date.
4937 $result['receive_date_includes_time_no_installments']['2012-01-01-1-month'] = [
4939 'start_date' => '2012-01-01',
4940 'frequency_interval' => 1,
4941 'frequency_unit' => 'month',
4945 'receive_date' => '2012-02-29 16:00:00',
4946 'expectedNextSched' => '2012-03-29 00:00:00',
4947 'expectedRecurStatus' => 'In Progress',
4950 'receive_date' => '2012-03-29 16:00:00',
4951 'expectedNextSched' => '2012-04-29 00:00:00',
4952 'expectedRecurStatus' => 'In Progress',
4960 * Make sure that recording a payment doesn't alter the receive_date of a
4961 * pending contribution.
4963 public function testPaymentDontChangeReceiveDate(): void
{
4965 'contact_id' => $this->_individualId
,
4966 'total_amount' => 100,
4967 'receive_date' => '2020-02-02',
4968 'contribution_status_id' => 'Pending',
4970 $contributionID = $this->contributionCreate($params);
4972 'contribution_id' => $contributionID,
4973 'total_amount' => 100,
4974 'trxn_date' => '2020-03-04',
4976 $this->callAPISuccess('payment', 'create', $paymentParams);
4978 //check if contribution status is set to "Completed".
4979 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
4980 'id' => $contributionID,
4982 $this->assertEquals('2020-02-02 00:00:00', $contribution['receive_date']);
4986 * Make sure that recording a payment with Different Payment Instrument update main contribution record payment
4987 * instrument too. If multiple Payment Recorded, last payment record payment (when No more due) instrument set to main
4990 public function testPaymentVerifyPaymentInstrumentChange() {
4991 // Create Pending contribution with pay later mode, with payment instrument Check
4993 'contact_id' => $this->_individualId
,
4994 'total_amount' => 100,
4995 'receive_date' => '2020-02-02',
4996 'contribution_status_id' => 'Pending',
4997 'is_pay_later' => 1,
4998 'payment_instrument_id' => 'Check',
5000 $contributionID = $this->contributionCreate($params);
5002 // Record the the Payment with instrument other than Check, e.g EFT
5004 'contribution_id' => $contributionID,
5005 'total_amount' => 50,
5006 'trxn_date' => '2020-03-04',
5007 'payment_instrument_id' => 'EFT',
5009 $this->callAPISuccess('payment', 'create', $paymentParams);
5011 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
5012 'id' => $contributionID,
5014 // payment status should be 'Partially paid'
5015 $this->assertEquals('Partially paid', $contribution['contribution_status']);
5017 // Record the the Payment with instrument other than Check, e.g Cash (pay all remaining amount)
5019 'contribution_id' => $contributionID,
5020 'total_amount' => 50,
5021 'trxn_date' => '2020-03-04',
5022 'payment_instrument_id' => 'Cash',
5024 $this->callAPISuccess('payment', 'create', $paymentParams);
5026 //check if contribution Payment Instrument (Payment Method) is is set to "Cash".
5027 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
5028 'id' => $contributionID,
5030 $this->assertEquals('Cash', $contribution['payment_instrument']);
5031 $this->assertEquals('Completed', $contribution['contribution_status']);
5035 * Test the "clean money" functionality.
5037 public function testCleanMoney() {
5039 'contact_id' => $this->_individualId
,
5040 'financial_type_id' => 1,
5041 'total_amount' => '$100',
5042 'fee_amount' => '$20',
5043 'net_amount' => '$80',
5044 'non_deductible_amount' => '$80',
5047 $id = $this->callAPISuccess('Contribution', 'create', $params)['id'];
5048 // Reading the return values of the API isn't reliable here; get the data from the db.
5049 $contribution = $this->callAPISuccess('Contribution', 'getsingle', ['id' => $id]);
5050 $this->assertEquals('100.00', $contribution['total_amount']);
5051 $this->assertEquals('20.00', $contribution['fee_amount']);
5052 $this->assertEquals('80.00', $contribution['net_amount']);
5053 $this->assertEquals('80.00', $contribution['non_deductible_amount']);
5057 * Create a price set with a quick config price set.
5059 * The params to use this look like
5061 * ['price_' . $this->ids['PriceField']['basic'] => $this->ids['PriceFieldValue']['basic']]
5063 * @param array $contributionPageParams
5067 * @throws \API_Exception
5068 * @throws \CRM_Core_Exception
5069 * @throws \Civi\API\Exception\UnauthorizedException
5071 private function createQuickConfigContributionPage(array $contributionPageParams = []): int {
5072 $contributionPageID = $this->callAPISuccess('ContributionPage', 'create', array_merge([
5073 'receipt_from_name' => 'Mickey Mouse',
5074 'receipt_from_email' => 'mickey@mouse.com',
5075 'title' => 'Test Contribution Page',
5076 'financial_type_id' => 'Member Dues',
5077 'currency' => 'CAD',
5078 'is_pay_later' => 1,
5079 'is_quick_config' => TRUE,
5080 'pay_later_text' => 'I will send payment by check',
5081 'pay_later_receipt' => 'This is a pay later receipt',
5082 'is_allow_other_amount' => 1,
5083 'min_amount' => 10.00,
5084 'max_amount' => 10000.00,
5085 'goal_amount' => 100000.00,
5086 'is_email_receipt' => 1,
5088 'amount_block_is_active' => 1,
5089 'is_billing_required' => 0,
5090 ], $contributionPageParams))['id'];
5092 $priceSetID = PriceSet
::create()->setValues([
5093 'name' => 'quick config set',
5094 'title' => 'basic price set',
5095 'is_quick_config' => TRUE,
5097 ])->execute()->first()['id'];
5099 $priceFieldID = PriceField
::create()->setValues([
5100 'price_set_id' => $priceSetID,
5101 'name' => 'quick config field name',
5102 'label' => 'quick config field name',
5103 'html_type' => 'Radio',
5104 ])->execute()->first()['id'];
5105 $this->ids
['PriceSet']['basic'] = $priceSetID;
5106 $this->ids
['PriceField']['basic'] = $priceFieldID;
5107 $this->ids
['PriceFieldValue']['basic'] = PriceFieldValue
::create()->setValues([
5108 'price_field_id' => $priceFieldID,
5109 'name' => 'quick config price field',
5110 'label' => 'quick config price field',
5112 'financial_type_id:name' => 'Member Dues',
5113 ])->execute()->first()['id'];
5114 CRM_Price_BAO_PriceSet
::addTo('civicrm_contribution_page', $contributionPageID, $priceSetID);
5115 return $contributionPageID;
5119 * Get the created contribution ID.
5121 * @param string $key
5125 protected function getContributionID(string $key = 'first'): int {
5126 return (int) $this->ids
['contribution'][$key];
5130 * Get the created contribution ID.
5134 protected function getMembershipID(): int {
5135 return (int) $this->_ids
['membership'];
5139 * Create a paid membership for renewal tests.
5141 protected function createSubsequentPendingMembership(): void
{
5142 $this->setUpPendingContribution($this->_ids
['price_field_value'][1], 'second', [], [], [
5143 'id' => $this->getMembershipID(),
5148 * Create a paid membership for renewal tests.
5150 protected function createInitialPaidMembership(): void
{
5151 $this->setUpPendingContribution($this->_ids
['price_field_value'][1]);
5152 $this->callAPISuccess('Payment', 'create', [
5153 'contribution_id' => $this->getContributionID(),
5154 'total_amount' => 20,