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\Contribution
;
15 * Test APIv3 civicrm_contribute_* functions
17 * @package CiviCRM_APIv3
18 * @subpackage API_Contribution
21 class api_v3_ContributionTest
extends CiviUnitTestCase
{
23 use CRMTraits_Profile_ProfileTrait
;
24 use CRMTraits_Custom_CustomDataTrait
;
26 protected $_individualId;
27 protected $_contribution;
28 protected $_financialTypeId = 1;
29 protected $entity = 'Contribution';
32 protected $_pageParams = [];
34 * Payment processor ID (dummy processor).
38 protected $paymentProcessorID;
41 * Parameters to create payment processor.
45 protected $_processorParams = [];
48 * ID of created event.
62 * @throws \CRM_Core_Exception
64 public function setUp() {
67 $this->_apiversion
= 3;
68 $this->_individualId
= $this->individualCreate();
70 'contact_id' => $this->_individualId
,
71 'receive_date' => '20120511',
72 'total_amount' => 100.00,
73 'financial_type_id' => $this->_financialTypeId
,
74 'non_deductible_amount' => 10.00,
76 'net_amount' => 95.00,
78 'contribution_status_id' => 1,
80 $this->_processorParams
= [
83 'payment_processor_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', 'Dummy'),
84 'financial_account_id' => 12,
87 'url_site' => 'http://dummy.com',
88 'url_recur' => 'http://dummy.com',
91 $this->paymentProcessorID
= $this->processorCreate();
92 $this->_pageParams
= [
93 'title' => 'Test Contribution Page',
94 'financial_type_id' => 1,
96 'financial_account_id' => 1,
97 'payment_processor' => $this->paymentProcessorID
,
99 'is_allow_other_amount' => 1,
101 'max_amount' => 1000,
106 * Clean up after each test.
108 * @throws \CRM_Core_Exception
110 public function tearDown() {
111 $this->quickCleanUpFinancialEntities();
112 $this->quickCleanup(['civicrm_uf_match'], TRUE);
113 $financialAccounts = $this->callAPISuccess('FinancialAccount', 'get', []);
114 foreach ($financialAccounts['values'] as $financialAccount) {
115 if ($financialAccount['name'] === 'Test Tax financial account ' ||
$financialAccount['name'] === 'Test taxable financial Type') {
116 $entityFinancialTypes = $this->callAPISuccess('EntityFinancialAccount', 'get', [
117 'financial_account_id' => $financialAccount['id'],
119 foreach ($entityFinancialTypes['values'] as $entityFinancialType) {
120 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialType['id']]);
122 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
125 $this->restoreUFGroupOne();
131 * @throws \CRM_Core_Exception
133 public function testGetContribution() {
134 $this->enableTaxAndInvoicing();
136 'contact_id' => $this->_individualId
,
137 'receive_date' => '2010-01-20',
138 'total_amount' => 100.00,
139 'financial_type_id' => $this->_financialTypeId
,
140 'non_deductible_amount' => 10.00,
141 'fee_amount' => 5.00,
142 'net_amount' => 95.00,
144 'invoice_id' => 78910,
146 'contribution_status_id' => 'Completed',
148 $this->_contribution
= $this->callAPISuccess('contribution', 'create', $p);
151 'contribution_id' => $this->_contribution
['id'],
154 $contributions = $this->callAPIAndDocument('contribution', 'get', $params, __FUNCTION__
, __FILE__
);
155 $financialParams['id'] = $this->_financialTypeId
;
157 CRM_Financial_BAO_FinancialType
::retrieve($financialParams, $default);
159 $this->assertEquals(1, $contributions['count']);
160 $contribution = $contributions['values'][$contributions['id']];
161 $this->assertEquals($contribution['contact_id'], $this->_individualId
);
162 // Note there was an assertion converting financial_type_id to 'Donation' which wasn't working.
163 // Passing back a string rather than an id seems like an error/cruft.
164 // If it is to be introduced we should discuss.
165 $this->assertEquals($contribution['financial_type_id'], 1);
166 $this->assertEquals($contribution['total_amount'], 100.00);
167 $this->assertEquals($contribution['non_deductible_amount'], 10.00);
168 $this->assertEquals($contribution['fee_amount'], 5.00);
169 $this->assertEquals($contribution['net_amount'], 95.00);
170 $this->assertEquals($contribution['trxn_id'], 23456);
171 $this->assertEquals($contribution['invoice_id'], 78910);
172 $this->assertEquals($contribution['invoice_number'], 'INV_' . $contributions['id']);
173 $this->assertEquals($contribution['contribution_source'], 'SSF');
174 $this->assertEquals($contribution['contribution_status'], 'Completed');
175 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
176 $p['trxn_id'] = '3847';
177 $p['invoice_id'] = '3847';
179 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
181 // Now we have 2 - test getcount.
182 $contribution = $this->callAPISuccess('contribution', 'getcount');
183 $this->assertEquals(2, $contribution);
184 // Test id only format.
185 $contribution = $this->callAPISuccess('contribution', 'get', [
186 'id' => $this->_contribution
['id'],
187 'format.only_id' => 1,
189 $this->assertEquals($this->_contribution
['id'], $contribution, print_r($contribution, TRUE));
190 // Test id only format.
191 $contribution = $this->callAPISuccess('contribution', 'get', [
192 'id' => $contribution2['id'],
193 'format.only_id' => 1,
195 $this->assertEquals($contribution2['id'], $contribution);
197 $contribution = $this->callAPISuccess('contribution', 'get', [
198 'id' => $this->_contribution
['id'],
200 $this->assertEquals(1, $contribution['count']);
202 // Test get by contact id works.
203 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId
]);
205 $this->assertEquals(2, $contribution['count']);
206 $this->callAPISuccess('Contribution', 'Delete', [
207 'id' => $this->_contribution
['id'],
209 $this->callAPISuccess('Contribution', 'Delete', [
210 'id' => $contribution2['id'],
215 * Test that test contributions can be retrieved.
217 * @throws \CRM_Core_Exception
219 public function testGetTestContribution() {
220 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['is_test' => 1]));
221 $this->callAPISuccessGetSingle('Contribution', ['is_test' => 1]);
225 * Test Creating a check contribution with original check_number field
227 public function testCreateCheckContribution() {
228 $params = $this->_params
;
229 $params['contribution_check_number'] = 'bouncer';
230 $params['payment_instrument_id'] = 'Check';
231 $params['cancel_date'] = 'yesterday';
232 $params['receipt_date'] = 'yesterday';
233 $params['thankyou_date'] = 'yesterday';
234 $params['revenue_recognition_date'] = 'yesterday';
235 $params['amount_level'] = 'Unreasonable';
236 $params['cancel_reason'] = 'You lose sucker';
237 $params['creditnote_id'] = 'sudo rm -rf';
238 $params['tax_amount'] = '1';
239 $address = $this->callAPISuccess('Address', 'create', [
240 'street_address' => 'Knockturn Alley',
241 'contact_id' => $this->_individualId
,
242 'location_type_id' => 'Home',
244 $params['address_id'] = $address['id'];
245 $contributionPage = $this->contributionPageCreate();
246 $params['contribution_page_id'] = $contributionPage['id'];
247 $params['campaign_id'] = $this->campaignCreate();
248 $contributionID = $this->contributionCreate($params);
249 $getResult = $this->callAPISuccess('Contribution', 'get', ['id' => $contributionID]);
250 $this->assertEquals('bouncer', $getResult['values'][$contributionID]['check_number']);
251 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'get', ['entity_id' => $contributionID, 'entity_table' => 'civicrm_contribution']);
252 foreach ($entityFinancialTrxn['values'] as $eft) {
253 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'get', ['id' => $eft['financial_trxn_id']]);
254 $this->assertEquals('bouncer', $financialTrxn['values'][$financialTrxn['id']]['check_number']);
259 * Test the 'return' param works for all fields.
261 * @throws \CRM_Core_Exception
263 public function testGetContributionReturnFunctionality() {
264 $params = $this->_params
;
265 $params['contribution_check_number'] = 'bouncer';
266 $params['payment_instrument_id'] = 'Check';
267 $params['cancel_date'] = 'yesterday';
268 $params['receipt_date'] = 'yesterday';
269 $params['thankyou_date'] = 'yesterday';
270 $params['revenue_recognition_date'] = 'yesterday';
271 $params['amount_level'] = 'Unreasonable';
272 $params['cancel_reason'] = 'You lose sucker';
273 $params['creditnote_id'] = 'sudo rm -rf';
274 $params['tax_amount'] = '1';
275 $address = $this->callAPISuccess('Address', 'create', [
276 'street_address' => 'Knockturn Alley',
277 'contact_id' => $this->_individualId
,
278 'location_type_id' => 'Home',
280 $params['address_id'] = $address['id'];
281 $contributionPage = $this->contributionPageCreate();
282 $params['contribution_page_id'] = $contributionPage['id'];
283 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
284 'contact_id' => $this->_individualId
,
285 'frequency_interval' => 1,
288 $params['contribution_recur_id'] = $contributionRecur['id'];
290 $params['campaign_id'] = $this->campaignCreate();
292 $contributionID = $this->contributionCreate($params);
294 // update contribution with invoice number
295 $params = array_merge($params, [
296 'id' => $contributionID,
297 'invoice_number' => CRM_Utils_Array
::value('invoice_prefix', Civi
::settings()->get('contribution_invoice_settings')) . "" . $contributionID,
299 'invoice_id' => 6789,
301 $contributionID = $this->contributionCreate($params);
303 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID]);
304 $this->assertEquals('bouncer', $contribution['check_number']);
305 $this->assertEquals('bouncer', $contribution['contribution_check_number']);
307 $fields = CRM_Contribute_BAO_Contribution
::fields();
308 // Re-add these 2 to the fields to check. They were locked in but the metadata changed so we
309 // need to specify them.
310 $fields['address_id'] = $fields['contribution_address_id'];
311 $fields['check_number'] = $fields['contribution_check_number'];
314 'contribution_id', 'contribution_contact_id', 'financial_type_id', 'contribution_page_id',
315 'payment_instrument_id', 'receive_date', 'non_deductible_amount', 'total_amount',
316 'fee_amount', 'net_amount', 'trxn_id', 'invoice_id', 'currency', 'contribution_cancel_date', 'cancel_reason',
317 'receipt_date', 'thankyou_date', 'contribution_source', 'amount_level', 'contribution_recur_id',
318 'is_test', 'is_pay_later', 'contribution_status_id', 'address_id', 'check_number', 'contribution_campaign_id',
319 'creditnote_id', 'tax_amount', 'revenue_recognition_date', 'decoy',
321 $missingFields = array_diff($fieldsLockedIn, array_keys($fields));
322 // If any of the locked in fields disappear from the $fields array we need to make sure it is still
323 // covered as the test contract now guarantees them in the return array.
324 $this->assertEquals($missingFields, [29 => 'decoy'], 'A field which was covered by the test contract has changed.');
325 foreach ($fields as $fieldName => $fieldSpec) {
326 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => $fieldName]);
327 $returnField = $fieldName;
328 if ($returnField == 'contribution_contact_id') {
329 $returnField = 'contact_id';
331 $this->assertTrue((!empty($contribution[$returnField]) ||
$contribution[$returnField] === "0"), $returnField);
333 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'get', ['entity_id' => $contributionID, 'entity_table' => 'civicrm_contribution']);
334 foreach ($entityFinancialTrxn['values'] as $eft) {
335 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'get', ['id' => $eft['financial_trxn_id']]);
336 $this->assertEquals('bouncer', $financialTrxn['values'][$financialTrxn['id']]['check_number']);
341 * Test cancel reason works as a filter.
343 public function testFilterCancelReason() {
344 $params = $this->_params
;
345 $params['cancel_date'] = 'yesterday';
346 $params['cancel_reason'] = 'You lose sucker';
347 $this->callAPISuccess('Contribution', 'create', $params);
348 $params = $this->_params
;
349 $params['cancel_date'] = 'yesterday';
350 $params['cancel_reason'] = 'You are a winner';
351 $this->callAPISuccess('Contribution', 'create', $params);
352 $this->callAPISuccessGetCount('Contribution', ['cancel_reason' => 'You are a winner'], 1);
356 * We need to ensure previous tested behaviour still works as part of the api contract.
358 public function testGetContributionLegacyBehaviour() {
360 'contact_id' => $this->_individualId
,
361 'receive_date' => '2010-01-20',
362 'total_amount' => 100.00,
363 'contribution_type_id' => $this->_financialTypeId
,
364 'non_deductible_amount' => 10.00,
365 'fee_amount' => 5.00,
366 'net_amount' => 95.00,
368 'invoice_id' => 78910,
370 'contribution_status_id' => 1,
372 $this->_contribution
= $this->callAPISuccess('Contribution', 'create', $p);
375 'contribution_id' => $this->_contribution
['id'],
377 $contribution = $this->callAPISuccess('contribution', 'get', $params);
378 $financialParams['id'] = $this->_financialTypeId
;
380 CRM_Financial_BAO_FinancialType
::retrieve($financialParams, $default);
382 $this->assertEquals(1, $contribution['count']);
383 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
384 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], $this->_financialTypeId
);
385 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_type_id'], $this->_financialTypeId
);
386 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
387 $this->assertEquals($contribution['values'][$contribution['id']]['non_deductible_amount'], 10.00);
388 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 5.00);
389 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 95.00);
390 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 23456);
391 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 78910);
392 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_source'], 'SSF');
393 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Completed');
395 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
396 $p['trxn_id'] = '3847';
397 $p['invoice_id'] = '3847';
399 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
401 // now we have 2 - test getcount
402 $contribution = $this->callAPISuccess('contribution', 'getcount', []);
403 $this->assertEquals(2, $contribution);
404 //test id only format
405 $contribution = $this->callAPISuccess('contribution', 'get', [
406 'id' => $this->_contribution
['id'],
407 'format.only_id' => 1,
409 $this->assertEquals($this->_contribution
['id'], $contribution, print_r($contribution, TRUE));
410 //test id only format
411 $contribution = $this->callAPISuccess('contribution', 'get', [
412 'id' => $contribution2['id'],
413 'format.only_id' => 1,
415 $this->assertEquals($contribution2['id'], $contribution);
416 $contribution = $this->callAPISuccess('contribution', 'get', [
417 'id' => $this->_contribution
['id'],
420 $this->assertEquals(1, $contribution['count']);
421 // $this->assertEquals($this->_contribution['id'], $contribution['id'] ) ;
422 //test get by contact id works
423 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId
]);
425 $this->assertEquals(2, $contribution['count']);
426 $this->callAPISuccess('Contribution', 'Delete', [
427 'id' => $this->_contribution
['id'],
429 $this->callAPISuccess('Contribution', 'Delete', [
430 'id' => $contribution2['id'],
435 * Create an contribution_id=FALSE and financial_type_id=Donation.
437 public function testCreateEmptyContributionIDUseDonation() {
439 'contribution_id' => FALSE,
442 'check_permissions' => FALSE,
443 'financial_type_id' => 'Donation',
445 $this->callAPISuccess('contribution', 'create', $params);
449 * Check with complete array + custom field.
451 * Note that the test is written on purpose without any
452 * variables specific to participant so it can be replicated into other entities
453 * and / or moved to the automated test suite
455 * @throws \CRM_Core_Exception
457 public function testCreateWithCustom() {
458 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, __FILE__
);
460 $params = $this->_params
;
461 $params['custom_' . $ids['custom_field_id']] = "custom string";
463 $result = $this->callAPIAndDocument($this->entity
, 'create', $params, __FUNCTION__
, __FILE__
);
464 $this->assertEquals($result['id'], $result['values'][$result['id']]['id']);
465 $check = $this->callAPISuccess($this->entity
, 'get', [
466 'return.custom_' . $ids['custom_field_id'] => 1,
467 'id' => $result['id'],
469 $group = $this->callAPISuccess('CustomGroup', 'getsingle', ['id' => $ids['custom_group_id']]);
470 $field = $this->callAPISuccess('CustomField', 'getsingle', ['id' => $ids['custom_field_id']]);
471 $contribution = \Civi\Api4\Contribution
::get()
475 $group['name'] . '.' . $field['name'],
477 ->addWhere('id', '=', $result['id'])
480 $this->customFieldDelete($ids['custom_field_id']);
481 $this->customGroupDelete($ids['custom_group_id']);
482 $this->assertEquals('custom string', $check['values'][$check['id']]['custom_' . $ids['custom_field_id']]);
486 * Check with complete array + custom field.
488 * Note that the test is written on purpose without any
489 * variables specific to participant so it can be replicated into other entities
490 * and / or moved to the automated test suite
492 public function testCreateGetFieldsWithCustom() {
493 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, __FILE__
);
494 $idsContact = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, 'ContactTest.php');
495 $result = $this->callAPISuccess('Contribution', 'getfields', []);
496 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $result['values']);
497 $this->assertArrayNotHasKey('custom_' . $idsContact['custom_field_id'], $result['values']);
498 $this->customFieldDelete($ids['custom_field_id']);
499 $this->customGroupDelete($ids['custom_group_id']);
500 $this->customFieldDelete($idsContact['custom_field_id']);
501 $this->customGroupDelete($idsContact['custom_group_id']);
504 public function testCreateContributionNoLineItems() {
507 'contact_id' => $this->_individualId
,
508 'receive_date' => '20120511',
509 'total_amount' => 100.00,
510 'financial_type_id' => $this->_financialTypeId
,
511 'payment_instrument_id' => 1,
512 'non_deductible_amount' => 10.00,
513 'fee_amount' => 50.00,
514 'net_amount' => 90.00,
516 'invoice_id' => 67890,
518 'contribution_status_id' => 1,
522 $contribution = $this->callAPISuccess('contribution', 'create', $params);
523 $financialItems = $this->callAPISuccess('FinancialItem', 'get', []);
524 foreach ($financialItems['values'] as $financialItem) {
525 $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'])));
527 $lineItems = $this->callAPISuccess('line_item', 'get', [
528 'entity_id' => $contribution['id'],
529 'entity_table' => 'civicrm_contribution',
532 $this->assertEquals(0, $lineItems['count']);
536 * Test checks that passing in line items suppresses the create mechanism.
538 public function testCreateContributionChainedLineItems() {
540 'contact_id' => $this->_individualId
,
541 'receive_date' => '20120511',
542 'total_amount' => 100.00,
543 'financial_type_id' => $this->_financialTypeId
,
544 'payment_instrument_id' => 1,
545 'non_deductible_amount' => 10.00,
546 'fee_amount' => 50.00,
547 'net_amount' => 90.00,
549 'invoice_id' => 67890,
551 'contribution_status_id' => 1,
553 'api.line_item.create' => [
555 'price_field_id' => 1,
557 'line_total' => '20',
558 'unit_price' => '10',
561 'price_field_id' => 1,
563 'line_total' => '80',
564 'unit_price' => '80',
569 $description = "Create Contribution with Nested Line Items.";
570 $subfile = "CreateWithNestedLineItems";
571 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
573 $lineItems = $this->callAPISuccess('line_item', 'get', [
574 'entity_id' => $contribution['id'],
575 'contribution_id' => $contribution['id'],
576 'entity_table' => 'civicrm_contribution',
579 $this->assertEquals(2, $lineItems['count']);
582 public function testCreateContributionOffline() {
584 'contact_id' => $this->_individualId
,
585 'receive_date' => '20120511',
586 'total_amount' => 100.00,
587 'financial_type_id' => 1,
589 'invoice_id' => 67890,
591 'contribution_status_id' => 1,
594 $contribution = $this->callAPISuccess('contribution', 'create', $params);
595 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
596 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
597 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
598 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
599 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
600 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
601 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
602 $lineItems = $this->callAPISuccess('line_item', 'get', [
603 'entity_id' => $contribution['id'],
604 'contribution_id' => $contribution['id'],
605 'entity_table' => 'civicrm_contribution',
608 $this->assertEquals(1, $lineItems['count']);
609 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
610 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
611 $this->_checkFinancialRecords($contribution, 'offline');
612 $this->contributionGetnCheck($params, $contribution['id']);
616 * Test create with valid payment instrument.
618 public function testCreateContributionWithPaymentInstrument() {
619 $params = $this->_params +
['payment_instrument' => 'EFT'];
620 $contribution = $this->callAPISuccess('contribution', 'create', $params);
621 $contribution = $this->callAPISuccess('contribution', 'get', [
623 'id' => $contribution['id'],
625 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
626 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
628 $this->callAPISuccess('contribution', 'create', [
629 'id' => $contribution['id'],
630 'payment_instrument' => 'Credit Card',
632 $contribution = $this->callAPISuccess('contribution', 'get', [
634 'id' => $contribution['id'],
636 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
637 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
640 public function testGetContributionByPaymentInstrument() {
641 $params = $this->_params +
['payment_instrument' => 'EFT'];
642 $params2 = $this->_params +
['payment_instrument' => 'Cash'];
643 $this->callAPISuccess('contribution', 'create', $params);
644 $this->callAPISuccess('contribution', 'create', $params2);
645 $contribution = $this->callAPISuccess('contribution', 'get', [
647 'contribution_payment_instrument' => 'Cash',
649 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
650 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
651 $this->assertEquals(1, $contribution['count']);
652 $contribution = $this->callAPISuccess('contribution', 'get', ['sequential' => 1, 'payment_instrument' => 'Cash']);
653 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
654 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
655 $this->assertEquals(1, $contribution['count']);
656 $contribution = $this->callAPISuccess('contribution', 'get', [
658 'payment_instrument_id' => 5,
660 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
661 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
662 $this->assertEquals(1, $contribution['count']);
663 $contribution = $this->callAPISuccess('contribution', 'get', [
665 'payment_instrument' => 'EFT',
667 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
668 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
669 $this->assertEquals(1, $contribution['count']);
670 $contribution = $this->callAPISuccess('contribution', 'create', [
671 'id' => $contribution['id'],
672 'payment_instrument' => 'Credit Card',
674 $contribution = $this->callAPISuccess('contribution', 'get', ['sequential' => 1, 'id' => $contribution['id']]);
675 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
676 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
677 $this->assertEquals(1, $contribution['count']);
681 * CRM-16227 introduces invoice_id as a parameter.
683 public function testGetContributionByInvoice() {
684 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['invoice_id' => 'curly']));
685 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
), ['invoice_id' => 'churlish']);
686 $this->callAPISuccessGetCount('Contribution', [], 2);
687 $this->callAPISuccessGetSingle('Contribution', ['invoice_id' => 'curly']);
688 // The following don't work. They are the format we are trying to introduce but although the form uses this format
689 // CRM_Contact_BAO_Query::convertFormValues puts them into the other format & the where only supports that.
690 // ideally the where clause would support this format (as it does on contact_BAO_Query) and those lines would
691 // come out of convertFormValues
692 // $this->callAPISuccessGetSingle('Contribution', array('invoice_id' => array('LIKE' => '%ish%')));
693 // $this->callAPISuccessGetSingle('Contribution', array('invoice_id' => array('NOT IN' => array('curly'))));
694 // $this->callAPISuccessGetCount('Contribution', array('invoice_id' => array('LIKE' => '%ly%')), 2);
695 // $this->callAPISuccessGetCount('Contribution', array('invoice_id' => array('IN' => array('curly', 'churlish'))),
700 * Check the credit note retrieval is case insensitive.
702 public function testGetCreditNoteCaseInsensitive() {
703 $this->contributionCreate(['contact_id' => $this->_individualId
]);
704 $this->contributionCreate(['creditnote_id' => 'cN1234', 'contact_id' => $this->_individualId
, 'invoice_id' => rand(), 'trxn_id' => rand()]);
705 $contribution = $this->callAPISuccess('Contribution', 'getsingle', ['creditnote_id' => 'CN1234']);
706 $this->assertEquals($contribution['creditnote_id'], 'cN1234');
710 * Test retrieval by total_amount works.
714 public function testGetContributionByTotalAmount() {
715 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['total_amount' => '5']));
716 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['total_amount' => '10']));
717 $this->callAPISuccessGetCount('Contribution', ['total_amount' => 10], 1);
718 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 6]], 1);
719 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 0]], 2);
720 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => -5]], 2);
721 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['<' => 0]], 0);
722 $this->callAPISuccessGetCount('Contribution', [], 2);
726 * @dataProvider createLocalizedContributionDataProvider
727 * @param $totalAmount
728 * @param $decimalPoint
729 * @param $thousandSeparator
731 * @param $expectedResult
734 public function testCreateLocalizedContribution($totalAmount, $decimalPoint, $thousandSeparator, $currency, $expectedResult) {
735 $this->setDefaultCurrency($currency);
736 $this->setMonetaryDecimalPoint($decimalPoint);
737 $this->setMonetaryThousandSeparator($thousandSeparator);
740 'contact_id' => $this->_individualId
,
741 'receive_date' => '20120511',
742 'total_amount' => $totalAmount,
743 'financial_type_id' => $this->_financialTypeId
,
744 'contribution_status_id' => 1,
747 if ($expectedResult) {
748 $this->callAPISuccess('Contribution', 'create', $_params);
751 $this->callAPIFailure('Contribution', 'create', $_params);
758 public function createLocalizedContributionDataProvider() {
760 [10, '.', ',', 'USD', TRUE],
761 ['145.0E+3', '.', ',', 'USD', FALSE],
762 ['10', '.', ',', 'USD', TRUE],
763 [-10, '.', ',', 'USD', TRUE],
764 ['-10', '.', ',', 'USD', TRUE],
765 ['-10foo', '.', ',', 'USD', FALSE],
766 ['-10.0345619', '.', ',', 'USD', TRUE],
767 ['-10.010,4345619', '.', ',', 'USD', TRUE],
768 ['10.0104345619', '.', ',', 'USD', TRUE],
769 ['-0', '.', ',', 'USD', TRUE],
770 ['-.1', '.', ',', 'USD', TRUE],
771 ['.1', '.', ',', 'USD', TRUE],
772 // Test currency symbols too, default locale uses $, so if we wanted to test others we'd need to reconfigure locale
773 ['$1,234,567.89', '.', ',', 'USD', TRUE],
774 ['-$1,234,567.89', '.', ',', 'USD', TRUE],
775 ['$-1,234,567.89', '.', ',', 'USD', TRUE],
776 // This is the float format. Encapsulated in strings
777 ['1234567.89', '.', ',', 'USD', TRUE],
778 // This is the float format.
779 [1234567.89, '.', ',', 'USD', TRUE],
780 // Test EURO currency
781 ['€1,234,567.89', '.', ',', 'EUR', TRUE],
782 ['-€1,234,567.89', '.', ',', 'EUR', TRUE],
783 ['€-1,234,567.89', '.', ',', 'EUR', TRUE],
784 // This is the float format. Encapsulated in strings
785 ['1234567.89', '.', ',', 'EUR', TRUE],
786 // This is the float format.
787 [1234567.89, '.', ',', 'EUR', TRUE],
788 // Test Norwegian KR currency
789 ['kr1,234,567.89', '.', ',', 'NOK', TRUE],
790 ['kr 1,234,567.89', '.', ',', 'NOK', TRUE],
791 ['-kr1,234,567.89', '.', ',', 'NOK', TRUE],
792 ['-kr 1,234,567.89', '.', ',', 'NOK', TRUE],
793 ['kr-1,234,567.89', '.', ',', 'NOK', TRUE],
794 ['kr -1,234,567.89', '.', ',', 'NOK', TRUE],
795 // This is the float format. Encapsulated in strings
796 ['1234567.89', '.', ',', 'NOK', TRUE],
797 // This is the float format.
798 [1234567.89, '.', ',', 'NOK', TRUE],
799 // Test different localization options: , as decimal separator and dot as thousand separator
800 ['$1.234.567,89', ',', '.', 'USD', TRUE],
801 ['-$1.234.567,89', ',', '.', 'USD', TRUE],
802 ['$-1.234.567,89', ',', '.', 'USD', TRUE],
803 ['1.234.567,89', ',', '.', 'USD', TRUE],
804 // This is the float format. Encapsulated in strings
805 ['1234567.89', ',', '.', 'USD', TRUE],
806 // This is the float format.
807 [1234567.89, ',', '.', 'USD', TRUE],
808 ['$1,234,567.89', ',', '.', 'USD', FALSE],
809 ['-$1,234,567.89', ',', '.', 'USD', FALSE],
810 ['$-1,234,567.89', ',', '.', 'USD', FALSE],
811 // Now with a space as thousand separator
812 ['$1 234 567,89', ',', ' ', 'USD', TRUE],
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],
824 * Create test with unique field name on source.
826 public function testCreateContributionSource() {
829 'contact_id' => $this->_individualId
,
830 'receive_date' => date('Ymd'),
831 'total_amount' => 100.00,
832 'financial_type_id' => $this->_financialTypeId
,
833 'payment_instrument_id' => 1,
834 'non_deductible_amount' => 10.00,
835 'fee_amount' => 50.00,
836 'net_amount' => 90.00,
838 'invoice_id' => 67890,
839 'contribution_source' => 'SSF',
840 'contribution_status_id' => 1,
843 $contribution = $this->callAPISuccess('contribution', 'create', $params);
844 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
845 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
849 * Create test with unique field name on source.
851 * @param string $thousandSeparator
852 * punctuation used to refer to thousands.
854 * @dataProvider getThousandSeparators
856 public function testCreateDefaultNow($thousandSeparator) {
857 $this->setCurrencySeparators($thousandSeparator);
858 $params = $this->_params
;
859 unset($params['receive_date'], $params['net_amount']);
861 $params['total_amount'] = $this->formatMoneyInput(5000.77);
862 $params['fee_amount'] = $this->formatMoneyInput(.77);
863 $params['skipCleanMoney'] = FALSE;
865 $contribution = $this->callAPISuccess('contribution', 'create', $params);
866 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
867 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receive_date'])));
868 $this->assertEquals(5000.77, $contribution['total_amount'], 'failed to handle ' . $this->formatMoneyInput(5000.77));
869 $this->assertEquals(.77, $contribution['fee_amount']);
870 $this->assertEquals(5000, $contribution['net_amount']);
874 * Create test with unique field name on source.
876 public function testCreateContributionNullOutThankyouDate() {
878 $params = $this->_params
;
879 $params['thankyou_date'] = 'yesterday';
881 $contribution = $this->callAPISuccess('contribution', 'create', $params);
882 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
883 $this->assertEquals(date('Y-m-d', strtotime('yesterday')), date('Y-m-d', strtotime($contribution['thankyou_date'])));
885 $params['thankyou_date'] = 'null';
886 $contribution = $this->callAPISuccess('contribution', 'create', $params);
887 $contribution = $this->assertTrue(empty($contribution['thankyou_date']));
891 * Create test with unique field name on source.
893 public function testCreateContributionSourceInvalidContact() {
897 'receive_date' => date('Ymd'),
898 'total_amount' => 100.00,
899 'financial_type_id' => $this->_financialTypeId
,
900 'payment_instrument_id' => 1,
901 'non_deductible_amount' => 10.00,
902 'fee_amount' => 50.00,
903 'net_amount' => 90.00,
905 'invoice_id' => 67890,
906 'contribution_source' => 'SSF',
907 'contribution_status_id' => 1,
910 $this->callAPIFailure('contribution', 'create', $params, 'contact_id is not valid : 999');
913 public function testCreateContributionSourceInvalidContContact() {
916 'contribution_contact_id' => 999,
917 'receive_date' => date('Ymd'),
918 'total_amount' => 100.00,
919 'financial_type_id' => $this->_financialTypeId
,
920 'payment_instrument_id' => 1,
921 'non_deductible_amount' => 10.00,
922 'fee_amount' => 50.00,
923 'net_amount' => 90.00,
925 'invoice_id' => 67890,
926 'contribution_source' => 'SSF',
927 'contribution_status_id' => 1,
930 $this->callAPIFailure('contribution', 'create', $params);
934 * Test note created correctly.
936 public function testCreateContributionWithNote() {
937 $description = "Demonstrates creating contribution with Note Entity.";
938 $subfile = "ContributionCreateWithNote";
940 'contact_id' => $this->_individualId
,
941 'receive_date' => '2012-01-01',
942 'total_amount' => 100.00,
943 'financial_type_id' => $this->_financialTypeId
,
944 'payment_instrument_id' => 1,
945 'non_deductible_amount' => 10.00,
946 'fee_amount' => 50.00,
947 'net_amount' => 90.00,
949 'invoice_id' => 67890,
951 'contribution_status_id' => 1,
952 'note' => 'my contribution note',
955 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
956 $result = $this->callAPISuccess('note', 'get', [
957 'entity_table' => 'civicrm_contribution',
958 'entity_id' => $contribution['id'],
961 $this->assertEquals('my contribution note', $result['values'][0]['note']);
962 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
965 public function testCreateContributionWithNoteUniqueNameAliases() {
967 'contact_id' => $this->_individualId
,
968 'receive_date' => '2012-01-01',
969 'total_amount' => 100.00,
970 'financial_type_id' => $this->_financialTypeId
,
971 'payment_instrument_id' => 1,
972 'non_deductible_amount' => 10.00,
973 'fee_amount' => 50.00,
974 'net_amount' => 90.00,
976 'invoice_id' => 67890,
978 'contribution_status_id' => 1,
979 'contribution_note' => 'my contribution note',
982 $contribution = $this->callAPISuccess('contribution', 'create', $params);
983 $result = $this->callAPISuccess('note', 'get', [
984 'entity_table' => 'civicrm_contribution',
985 'entity_id' => $contribution['id'],
988 $this->assertEquals('my contribution note', $result['values'][0]['note']);
989 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
993 * This is the test for creating soft credits.
995 public function testCreateContributionWithSoftCredit() {
996 $description = "Demonstrates creating contribution with SoftCredit.";
997 $subfile = "ContributionCreateWithSoftCredit";
998 $contact2 = $this->callAPISuccess('Contact', 'create', [
999 'display_name' => 'superman',
1000 'contact_type' => 'Individual',
1003 'contact_id' => $contact2['id'],
1005 'soft_credit_type_id' => 3,
1008 $params = $this->_params +
['soft_credit' => [1 => $softParams]];
1009 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1010 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1012 $this->assertEquals($softParams['contact_id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1013 $this->assertEquals($softParams['amount'], $result['values'][0]['soft_credit'][1]['amount']);
1014 $this->assertEquals($softParams['soft_credit_type_id'], $result['values'][0]['soft_credit'][1]['soft_credit_type']);
1016 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1017 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1020 public function testCreateContributionWithSoftCreditDefaults() {
1021 $description = "Demonstrates creating contribution with Soft Credit defaults for amount and type.";
1022 $subfile = "ContributionCreateWithSoftCreditDefaults";
1023 $contact2 = $this->callAPISuccess('Contact', 'create', [
1024 'display_name' => 'superman',
1025 'contact_type' => 'Individual',
1027 $params = $this->_params +
[
1028 'soft_credit_to' => $contact2['id'],
1030 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1031 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1033 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1034 // Default soft credit amount = contribution.total_amount
1035 $this->assertEquals($this->_params
['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
1036 $this->assertEquals(CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type"), $result['values'][0]['soft_credit'][1]['soft_credit_type']);
1038 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1039 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1043 * Test creating contribution with Soft Credit by passing in honor_contact_id.
1045 public function testCreateContributionWithHonoreeContact() {
1046 $description = "Demonstrates creating contribution with Soft Credit by passing in honor_contact_id.";
1047 $subfile = "ContributionCreateWithHonoreeContact";
1048 $contact2 = $this->callAPISuccess('Contact', 'create', [
1049 'display_name' => 'superman',
1050 'contact_type' => 'Individual',
1052 $params = $this->_params +
[
1053 'honor_contact_id' => $contact2['id'],
1055 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1056 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1058 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1059 // Default soft credit amount = contribution.total_amount
1060 // Legacy mode in create api (honor_contact_id param) uses the standard "In Honor of" soft credit type
1061 $this->assertEquals($this->_params
['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
1062 $softCreditValueTypeID = $result['values'][0]['soft_credit'][1]['soft_credit_type'];
1063 $this->assertEquals('in_honor_of', CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $softCreditValueTypeID));
1065 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1066 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1070 * Test using example code.
1072 public function testContributionCreateExample() {
1073 //make sure at least on page exists since there is a truncate in tear down
1074 $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1075 require_once 'api/v3/examples/Contribution/Create.ex.php';
1076 $result = contribution_create_example();
1077 $id = $result['id'];
1078 $expectedResult = contribution_create_expectedresult();
1079 $this->checkArrayEquals($expectedResult, $result);
1080 $this->contributionDelete($id);
1084 * Function tests that additional financial records are created when fee amount is recorded.
1086 public function testCreateContributionWithFee() {
1088 'contact_id' => $this->_individualId
,
1089 'receive_date' => '20120511',
1090 'total_amount' => 100.00,
1092 'financial_type_id' => 1,
1094 'invoice_id' => 67890,
1096 'contribution_status_id' => 1,
1099 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1100 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
1101 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1102 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 50.00);
1103 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 50.00);
1104 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1105 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1106 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1107 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1108 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
1110 $lineItems = $this->callAPISuccess('line_item', 'get', [
1112 'entity_id' => $contribution['id'],
1113 'entity_table' => 'civicrm_contribution',
1116 $this->assertEquals(1, $lineItems['count']);
1117 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
1118 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
1119 $lineItems = $this->callAPISuccess('line_item', 'get', [
1121 'entity_id' => $contribution['id'],
1122 'contribution_id' => $contribution['id'],
1123 'entity_table' => 'civicrm_contribution',
1126 $this->assertEquals(1, $lineItems['count']);
1127 $this->_checkFinancialRecords($contribution, 'feeAmount');
1131 * Function tests that additional financial records are created when online contribution is created.
1133 public function testCreateContributionOnline() {
1134 CRM_Financial_BAO_PaymentProcessor
::create($this->_processorParams
);
1135 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1136 $this->assertAPISuccess($contributionPage);
1138 'contact_id' => $this->_individualId
,
1139 'receive_date' => '20120511',
1140 'total_amount' => 100.00,
1141 'financial_type_id' => 1,
1142 'contribution_page_id' => $contributionPage['id'],
1143 'payment_processor' => $this->paymentProcessorID
,
1145 'invoice_id' => 67890,
1147 'contribution_status_id' => 1,
1151 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1152 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
1153 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1154 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1155 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1156 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1157 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1158 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
1159 $contribution['payment_instrument_id'] = $this->callAPISuccessGetValue('PaymentProcessor', [
1160 'id' => $this->paymentProcessorID
,
1161 'return' => 'payment_instrument_id',
1163 $this->_checkFinancialRecords($contribution, 'online');
1167 * Check handling of financial type.
1169 * In the interests of removing financial type / contribution type checks from
1170 * legacy format function lets test that the api is doing this for us
1172 public function testCreateInvalidFinancialType() {
1173 $params = $this->_params
;
1174 $params['financial_type_id'] = 99999;
1175 $this->callAPIFailure($this->entity
, 'create', $params, "'99999' is not a valid option for field financial_type_id");
1179 * Check handling of financial type.
1181 * In the interests of removing financial type / contribution type checks from
1182 * legacy format function lets test that the api is doing this for us
1184 * @throws \CRM_Core_Exception
1186 public function testValidNamedFinancialType() {
1187 $params = $this->_params
;
1188 $params['financial_type_id'] = 'Donation';
1189 $this->callAPISuccess($this->entity
, 'create', $params);
1193 * Tests that additional financial records are created.
1195 * Checks when online contribution with pay later option is created
1197 * @throws \CRM_Core_Exception
1199 public function testCreateContributionPayLaterOnline() {
1200 $this->_pageParams
['is_pay_later'] = 1;
1201 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1202 $this->assertAPISuccess($contributionPage);
1204 'contact_id' => $this->_individualId
,
1205 'receive_date' => '20120511',
1206 'total_amount' => 100.00,
1207 'financial_type_id' => 1,
1208 'contribution_page_id' => $contributionPage['id'],
1210 'is_pay_later' => 1,
1211 'invoice_id' => 67890,
1213 'contribution_status_id' => 'Pending',
1217 $contribution = $this->callAPIAndDocument('Contribution', 'create', $params, __FUNCTION__
, __FILE__
);
1218 $contribution = $contribution['values'][$contribution['id']];
1219 $this->assertEquals($contribution['contact_id'], $this->_individualId
);
1220 $this->assertEquals($contribution['total_amount'], 100.00);
1221 $this->assertEquals($contribution['financial_type_id'], 1);
1222 $this->assertEquals($contribution['trxn_id'], 12345);
1223 $this->assertEquals($contribution['invoice_id'], 67890);
1224 $this->assertEquals($contribution['source'], 'SSF');
1225 $this->assertEquals($contribution['contribution_status_id'], 2);
1226 $this->_checkFinancialRecords($contribution, 'payLater');
1230 * Function tests that additional financial records are created for online contribution with pending option.
1232 public function testCreateContributionPendingOnline() {
1233 CRM_Financial_BAO_PaymentProcessor
::create($this->_processorParams
);
1234 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1235 $this->assertAPISuccess($contributionPage);
1237 'contact_id' => $this->_individualId
,
1238 'receive_date' => '20120511',
1239 'total_amount' => 100.00,
1240 'financial_type_id' => 1,
1241 'contribution_page_id' => $contributionPage['id'],
1243 'invoice_id' => 67890,
1245 'contribution_status_id' => 2,
1248 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1249 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
1250 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1251 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1252 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1253 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1254 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1255 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 2);
1256 $this->_checkFinancialRecords($contribution, 'pending');
1260 * Test that BAO defaults work.
1262 * @throws \CRM_Core_Exception
1264 public function testCreateBAODefaults() {
1265 unset($this->_params
['contribution_source_id'], $this->_params
['payment_instrument_id']);
1266 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1267 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
1268 'id' => $contribution['id'],
1269 'api.contribution.delete' => 1,
1271 $this->assertEquals(1, $contribution['contribution_status_id']);
1272 $this->assertEquals('Check', $contribution['payment_instrument']);
1273 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1277 * Test that getsingle can be chained with delete.
1279 * @throws CRM_Core_Exception
1281 public function testDeleteChainedGetSingle() {
1282 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1283 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
1284 'id' => $contribution['id'],
1285 'api.contribution.delete' => 1,
1287 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1291 * Function tests that line items, financial records are updated when contribution amount is changed.
1293 * @throws \CRM_Core_Exception
1295 public function testCreateUpdateContributionChangeTotal() {
1296 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
1297 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1299 'entity_id' => $contribution['id'],
1300 'entity_table' => 'civicrm_contribution',
1302 'return' => 'line_total',
1304 $this->assertEquals('100.00', $lineItems);
1305 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1306 // Financial trxn SUM = 100 + 5 (fee)
1307 $this->assertEquals('105.00', $trxnAmount);
1310 'id' => $contribution['id'],
1311 'total_amount' => '125',
1313 $contribution = $this->callAPISuccess('Contribution', 'create', $newParams);
1315 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1317 'entity_id' => $contribution['id'],
1318 'entity_table' => 'civicrm_contribution',
1320 'return' => 'line_total',
1323 $this->assertEquals('125.00', $lineItems);
1324 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1326 // Financial trxn SUM = 125 + 5 (fee).
1327 $this->assertEquals('130.00', $trxnAmount);
1328 $this->assertEquals('125.00', $this->_getFinancialItemAmount($contribution['id']));
1332 * Function tests that line items, financial records are updated when pay later contribution is received.
1334 public function testCreateUpdateContributionPayLater() {
1336 'contact_id' => $this->_individualId
,
1337 'receive_date' => '2012-01-01',
1338 'total_amount' => 100.00,
1339 'financial_type_id' => $this->_financialTypeId
,
1340 'payment_instrument_id' => 1,
1341 'contribution_status_id' => 2,
1342 'is_pay_later' => 1,
1345 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1347 $newParams = array_merge($contribParams, [
1348 'id' => $contribution['id'],
1349 'contribution_status_id' => 1,
1351 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1352 $contribution = $contribution['values'][$contribution['id']];
1353 $this->assertEquals($contribution['contribution_status_id'], '1');
1354 $this->_checkFinancialItem($contribution['id'], 'paylater');
1355 $this->_checkFinancialTrxn($contribution, 'payLater');
1359 * Function tests that financial records are updated when Payment Instrument is changed.
1361 public function testCreateUpdateContributionPaymentInstrument() {
1362 $instrumentId = $this->_addPaymentInstrument();
1364 'contact_id' => $this->_individualId
,
1365 'total_amount' => 100.00,
1366 'financial_type_id' => $this->_financialTypeId
,
1367 'payment_instrument_id' => 4,
1368 'contribution_status_id' => 1,
1371 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1373 $newParams = array_merge($contribParams, [
1374 'id' => $contribution['id'],
1375 'payment_instrument_id' => $instrumentId,
1377 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1378 $this->assertAPISuccess($contribution);
1379 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId);
1381 // cleanup - delete created payment instrument
1382 $this->_deletedAddedPaymentInstrument();
1386 * Function tests that financial records are updated when Payment Instrument is changed when amount is negative.
1388 public function testCreateUpdateNegativeContributionPaymentInstrument() {
1389 $instrumentId = $this->_addPaymentInstrument();
1391 'contact_id' => $this->_individualId
,
1392 'total_amount' => -100.00,
1393 'financial_type_id' => $this->_financialTypeId
,
1394 'payment_instrument_id' => 4,
1395 'contribution_status_id' => 1,
1398 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1400 $newParams = array_merge($contribParams, [
1401 'id' => $contribution['id'],
1402 'payment_instrument_id' => $instrumentId,
1404 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1405 $this->assertAPISuccess($contribution);
1406 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId, -100);
1408 // cleanup - delete created payment instrument
1409 $this->_deletedAddedPaymentInstrument();
1413 * Function tests that financial records are added when Contribution is Refunded.
1415 * @throws \CRM_Core_Exception
1417 public function testCreateUpdateContributionRefund() {
1418 $contributionParams = [
1419 'contact_id' => $this->_individualId
,
1420 'receive_date' => '2012-01-01',
1421 'total_amount' => 100.00,
1422 'financial_type_id' => $this->_financialTypeId
,
1423 'payment_instrument_id' => 4,
1424 'contribution_status_id' => 1,
1425 'trxn_id' => 'original_payment',
1427 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
1428 $newParams = array_merge($contributionParams, [
1429 'id' => $contribution['id'],
1430 'contribution_status_id' => 'Refunded',
1431 'cancel_date' => '2015-01-01 09:00',
1432 'refund_trxn_id' => 'the refund',
1435 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1436 $this->_checkFinancialTrxn($contribution, 'refund');
1437 $this->_checkFinancialItem($contribution['id'], 'refund');
1438 $this->assertEquals('original_payment', $this->callAPISuccessGetValue('Contribution', [
1439 'id' => $contribution['id'],
1440 'return' => 'trxn_id',
1445 * Refund a contribution for a financial type with a contra account.
1447 * CRM-17951 the contra account is a financial account with a relationship to a
1448 * financial type. It is not always configured but should be reflected
1449 * in the financial_trxn & financial_item table if it is.
1451 * @throws \CRM_Core_Exception
1453 public function testCreateUpdateChargebackContributionDefaultAccount() {
1454 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1455 $this->callAPISuccess('Contribution', 'create', [
1456 'id' => $contribution['id'],
1457 'contribution_status_id' => 'Chargeback',
1459 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1461 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1462 'contribution_id' => $contribution['id'],
1463 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1465 $this->assertEquals(1, $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1466 $this->callAPISuccessGetSingle('FinancialTrxn', [
1467 'total_amount' => -100,
1468 'status_id' => 'Chargeback',
1469 'to_financial_account_id' => 6,
1474 * Refund a contribution for a financial type with a contra account.
1476 * CRM-17951 the contra account is a financial account with a relationship to a
1477 * financial type. It is not always configured but should be reflected
1478 * in the financial_trxn & financial_item table if it is.
1480 * @throws \CRM_Core_Exception
1482 public function testCreateUpdateChargebackContributionCustomAccount() {
1483 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1484 'name' => 'Chargeback Account',
1485 'is_active' => TRUE,
1488 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1489 'entity_id' => $this->_financialTypeId
,
1490 'entity_table' => 'civicrm_financial_type',
1491 'account_relationship' => 'Chargeback Account is',
1492 'financial_account_id' => 'Chargeback Account',
1495 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1496 $this->callAPISuccess('Contribution', 'create', [
1497 'id' => $contribution['id'],
1498 'contribution_status_id' => 'Chargeback',
1500 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1502 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1503 'contribution_id' => $contribution['id'],
1504 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1506 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1508 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1509 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1510 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1514 * Refund a contribution for a financial type with a contra account.
1516 * CRM-17951 the contra account is a financial account with a relationship to a
1517 * financial type. It is not always configured but should be reflected
1518 * in the financial_trxn & financial_item table if it is.
1520 public function testCreateUpdateRefundContributionConfiguredContraAccount() {
1521 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1522 'name' => 'Refund Account',
1523 'is_active' => TRUE,
1526 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1527 'entity_id' => $this->_financialTypeId
,
1528 'entity_table' => 'civicrm_financial_type',
1529 'account_relationship' => 'Credit/Contra Revenue Account is',
1530 'financial_account_id' => 'Refund Account',
1533 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1534 $this->callAPISuccess('Contribution', 'create', [
1535 'id' => $contribution['id'],
1536 'contribution_status_id' => 'Refunded',
1539 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1540 'contribution_id' => $contribution['id'],
1541 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1543 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1545 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1546 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1547 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1551 * Function tests that trxn_id is set when passed in.
1553 * Here we ensure that the civicrm_financial_trxn.trxn_id & the civicrm_contribution.trxn_id are set
1554 * when trxn_id is passed in.
1556 public function testCreateUpdateContributionRefundTrxnIDPassedIn() {
1557 $contributionParams = [
1558 'contact_id' => $this->_individualId
,
1559 'receive_date' => '2012-01-01',
1560 'total_amount' => 100.00,
1561 'financial_type_id' => $this->_financialTypeId
,
1562 'payment_instrument_id' => 4,
1563 'contribution_status_id' => 1,
1564 'trxn_id' => 'original_payment',
1566 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1567 $newParams = array_merge($contributionParams, [
1568 'id' => $contribution['id'],
1569 'contribution_status_id' => 'Refunded',
1570 'cancel_date' => '2015-01-01 09:00',
1571 'trxn_id' => 'the refund',
1574 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1575 $this->_checkFinancialTrxn($contribution, 'refund');
1576 $this->_checkFinancialItem($contribution['id'], 'refund');
1577 $this->assertEquals('the refund', $this->callAPISuccessGetValue('Contribution', [
1578 'id' => $contribution['id'],
1579 'return' => 'trxn_id',
1584 * Function tests that trxn_id is set when passed in.
1586 * Here we ensure that the civicrm_contribution.trxn_id is set
1587 * when trxn_id is passed in but if refund_trxn_id is different then that
1588 * is kept for the refund transaction.
1590 public function testCreateUpdateContributionRefundRefundAndTrxnIDPassedIn() {
1591 $contributionParams = [
1592 'contact_id' => $this->_individualId
,
1593 'receive_date' => '2012-01-01',
1594 'total_amount' => 100.00,
1595 'financial_type_id' => $this->_financialTypeId
,
1596 'payment_instrument_id' => 4,
1597 'contribution_status_id' => 1,
1598 'trxn_id' => 'original_payment',
1600 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1601 $newParams = array_merge($contributionParams, [
1602 'id' => $contribution['id'],
1603 'contribution_status_id' => 'Refunded',
1604 'cancel_date' => '2015-01-01 09:00',
1605 'trxn_id' => 'cont id',
1606 'refund_trxn_id' => 'the refund',
1609 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1610 $this->_checkFinancialTrxn($contribution, 'refund');
1611 $this->_checkFinancialItem($contribution['id'], 'refund');
1612 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1613 'id' => $contribution['id'],
1614 'return' => 'trxn_id',
1619 * Function tests that refund_trxn_id is set when passed in empty.
1621 * Here we ensure that the civicrm_contribution.trxn_id is set
1622 * when trxn_id is passed in but if refund_trxn_id isset but empty then that
1623 * is kept for the refund transaction.
1625 public function testCreateUpdateContributionRefundRefundNullTrxnIDPassedIn() {
1626 $contributionParams = [
1627 'contact_id' => $this->_individualId
,
1628 'receive_date' => '2012-01-01',
1629 'total_amount' => 100.00,
1630 'financial_type_id' => $this->_financialTypeId
,
1631 'payment_instrument_id' => 4,
1632 'contribution_status_id' => 1,
1633 'trxn_id' => 'original_payment',
1635 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1636 $newParams = array_merge($contributionParams, [
1637 'id' => $contribution['id'],
1638 'contribution_status_id' => 'Refunded',
1639 'cancel_date' => '2015-01-01 09:00',
1640 'trxn_id' => 'cont id',
1641 'refund_trxn_id' => '',
1644 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1645 $this->_checkFinancialTrxn($contribution, 'refund', NULL, ['trxn_id' => NULL]);
1646 $this->_checkFinancialItem($contribution['id'], 'refund');
1647 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1648 'id' => $contribution['id'],
1649 'return' => 'trxn_id',
1654 * Function tests invalid contribution status change.
1656 public function testCreateUpdateContributionInValidStatusChange() {
1659 'receive_date' => '2012-01-01',
1660 'total_amount' => 100.00,
1661 'financial_type_id' => 1,
1662 'payment_instrument_id' => 1,
1663 'contribution_status_id' => 1,
1665 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1666 $newParams = array_merge($contribParams, [
1667 'id' => $contribution['id'],
1668 'contribution_status_id' => 2,
1670 $this->callAPIFailure('contribution', 'create', $newParams, ts('Cannot change contribution status from Completed to Pending.'));
1675 * Function tests that financial records are added when Pending Contribution is Canceled.
1677 * @throws \CRM_Core_Exception
1679 public function testCreateUpdateContributionCancelPending() {
1681 'contact_id' => $this->_individualId
,
1682 'receive_date' => '2012-01-01',
1683 'total_amount' => 100.00,
1684 'financial_type_id' => $this->_financialTypeId
,
1685 'payment_instrument_id' => 1,
1686 'contribution_status_id' => 2,
1687 'is_pay_later' => 1,
1690 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1691 $newParams = array_merge($contribParams, [
1692 'id' => $contribution['id'],
1693 'contribution_status_id' => 3,
1694 'cancel_date' => '2012-02-02 09:00',
1696 //Check if trxn_date is same as cancel_date.
1698 'trxn_date' => '2012-02-02 09:00:00',
1700 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1701 $this->_checkFinancialTrxn($contribution, 'cancelPending', NULL, $checkTrxnDate);
1702 $this->_checkFinancialItem($contribution['id'], 'cancelPending');
1706 * Function tests that financial records are added when Financial Type is Changed.
1708 * @throws \CRM_Core_Exception
1710 public function testCreateUpdateContributionChangeFinancialType() {
1712 'contact_id' => $this->_individualId
,
1713 'receive_date' => '2012-01-01',
1714 'total_amount' => 100.00,
1715 'financial_type_id' => 1,
1716 'payment_instrument_id' => 1,
1717 'contribution_status_id' => 1,
1720 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1721 $newParams = array_merge($contribParams, [
1722 'id' => $contribution['id'],
1723 'financial_type_id' => 3,
1725 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1726 $this->_checkFinancialTrxn($contribution, 'changeFinancial');
1727 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1731 * Function tets that financial records are correctly added when financial type is changed
1733 * @throws \CRM_Core_Exception
1735 public function testCreateUpdateContributionWithFeeAmountChangeFinancialType() {
1737 'contact_id' => $this->_individualId
,
1738 'receive_date' => '2012-01-01',
1739 'total_amount' => 100.00,
1740 'fee_amount' => 0.57,
1741 'financial_type_id' => 1,
1742 'payment_instrument_id' => 1,
1743 'contribution_status_id' => 1,
1746 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1747 $newParams = array_merge($contribParams, [
1748 'id' => $contribution['id'],
1749 'financial_type_id' => 3,
1751 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1752 $this->_checkFinancialTrxn($contribution, 'changeFinancial', NULL, ['fee_amount' => '-0.57', 'net_amount' => '-99.43']);
1753 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1757 * Test that update does not change status id CRM-15105.
1759 public function testCreateUpdateWithoutChangingPendingStatus() {
1760 $contribution = $this->callAPISuccess('contribution', 'create', array_merge($this->_params
, ['contribution_status_id' => 2]));
1761 $this->callAPISuccess('contribution', 'create', ['id' => $contribution['id'], 'source' => 'new source']);
1762 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1763 'id' => $contribution['id'],
1764 'api.contribution.delete' => 1,
1766 $this->assertEquals(2, $contribution['contribution_status_id']);
1770 * Test Updating a Contribution.
1772 * CHANGE: we require the API to do an incremental update
1774 public function testCreateUpdateContribution() {
1775 $contributionID = $this->contributionCreate([
1776 'contact_id' => $this->_individualId
,
1777 'trxn_id' => 212355,
1778 'financial_type_id' => $this->_financialTypeId
,
1779 'invoice_id' => 'old_invoice',
1782 'contribution_id' => $contributionID,
1784 $original = $this->callAPISuccess('contribution', 'get', $old_params);
1785 $this->assertEquals($original['id'], $contributionID);
1786 //set up list of old params, verify
1788 //This should not be required on update:
1789 $old_contact_id = $original['values'][$contributionID]['contact_id'];
1790 $old_payment_instrument = $original['values'][$contributionID]['instrument_id'];
1791 $old_fee_amount = $original['values'][$contributionID]['fee_amount'];
1792 $old_source = $original['values'][$contributionID]['contribution_source'];
1794 $old_trxn_id = $original['values'][$contributionID]['trxn_id'];
1795 $old_invoice_id = $original['values'][$contributionID]['invoice_id'];
1797 //check against values in CiviUnitTestCase::createContribution()
1798 $this->assertEquals($old_contact_id, $this->_individualId
);
1799 $this->assertEquals($old_fee_amount, 5.00);
1800 $this->assertEquals($old_source, 'SSF');
1801 $this->assertEquals($old_trxn_id, 212355);
1802 $this->assertEquals($old_invoice_id, 'old_invoice');
1804 'id' => $contributionID,
1805 'contact_id' => $this->_individualId
,
1806 'total_amount' => 105.00,
1807 'fee_amount' => 7.00,
1808 'financial_type_id' => $this->_financialTypeId
,
1809 'non_deductible_amount' => 22.00,
1810 'contribution_status_id' => 1,
1811 'note' => 'Donating for Noble Cause',
1814 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1817 'contribution_id' => $contribution['id'],
1819 $contribution = $this->callAPISuccessGetSingle('contribution', $new_params);
1821 $this->assertEquals($contribution['contact_id'], $this->_individualId
);
1822 $this->assertEquals($contribution['total_amount'], 105.00);
1823 $this->assertEquals($contribution['financial_type_id'], $this->_financialTypeId
);
1824 $this->assertEquals($contribution['financial_type'], 'Donation');
1825 $this->assertEquals($contribution['instrument_id'], $old_payment_instrument);
1826 $this->assertEquals($contribution['non_deductible_amount'], 22.00);
1827 $this->assertEquals($contribution['fee_amount'], 7.00);
1828 $this->assertEquals($contribution['trxn_id'], $old_trxn_id);
1829 $this->assertEquals($contribution['invoice_id'], $old_invoice_id);
1830 $this->assertEquals($contribution['contribution_source'], $old_source);
1831 $this->assertEquals($contribution['contribution_status'], 'Completed');
1833 $this->assertEquals($contribution['net_amount'], $contribution['total_amount'] - $contribution['fee_amount']);
1836 'contribution_id' => $contributionID,
1838 $result = $this->callAPISuccess('contribution', 'delete', $params);
1839 $this->assertAPISuccess($result);
1843 * Check that net_amount is updated when a contribution is updated.
1845 * Update fee amount AND total amount, just fee amount, just total amount
1846 * and neither to check that net_amount is keep updated.
1848 public function testUpdateContributionNetAmountVariants() {
1849 $contributionID = $this->contributionCreate(['contact_id' => $this->individualCreate()]);
1851 $this->callAPISuccess('Contribution', 'create', [
1852 'id' => $contributionID,
1853 'total_amount' => 90,
1856 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1857 'id' => $contributionID,
1858 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1860 $this->assertEquals(6, $contribution['fee_amount']);
1861 $this->assertEquals(90, $contribution['total_amount']);
1862 $this->assertEquals(84, $contribution['net_amount']);
1864 $this->callAPISuccess('Contribution', 'create', [
1865 'id' => $contributionID,
1868 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1869 'id' => $contributionID,
1870 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1872 $this->assertEquals(3, $contribution['fee_amount']);
1873 $this->assertEquals(90, $contribution['total_amount']);
1874 $this->assertEquals(87, $contribution['net_amount']);
1876 $this->callAPISuccess('Contribution', 'create', [
1877 'id' => $contributionID,
1878 'total_amount' => 200,
1880 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1881 'id' => $contributionID,
1882 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1884 $this->assertEquals(3, $contribution['fee_amount']);
1885 $this->assertEquals(200, $contribution['total_amount']);
1886 $this->assertEquals(197, $contribution['net_amount']);
1888 $this->callAPISuccess('Contribution', 'create', [
1889 'id' => $contributionID,
1890 'payment_instrument' => 'Cash',
1892 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1893 'id' => $contributionID,
1894 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1896 $this->assertEquals(3, $contribution['fee_amount']);
1897 $this->assertEquals(200, $contribution['total_amount']);
1898 $this->assertEquals(197, $contribution['net_amount']);
1902 * Attempt (but fail) to delete a contribution without parameters.
1904 public function testDeleteEmptyParamsContribution() {
1906 $this->callAPIFailure('contribution', 'delete', $params);
1909 public function testDeleteParamsNotArrayContribution() {
1910 $this->expectException(TypeError
::class);
1911 $params = 'contribution_id= 1';
1912 $contribution = $this->callAPIFailure('contribution', 'delete', $params);
1915 public function testDeleteWrongParamContribution() {
1917 'contribution_source' => 'SSF',
1919 $this->callAPIFailure('contribution', 'delete', $params);
1922 public function testDeleteContribution() {
1923 $contributionID = $this->contributionCreate([
1924 'contact_id' => $this->_individualId
,
1925 'financial_type_id' => $this->_financialTypeId
,
1928 'id' => $contributionID,
1930 $this->callAPIAndDocument('contribution', 'delete', $params, __FUNCTION__
, __FILE__
);
1934 * Test civicrm_contribution_search with empty params.
1936 * All available contributions expected.
1938 public function testSearchEmptyParams() {
1942 'contact_id' => $this->_individualId
,
1943 'receive_date' => date('Ymd'),
1944 'total_amount' => 100.00,
1945 'financial_type_id' => $this->_financialTypeId
,
1946 'non_deductible_amount' => 10.00,
1947 'fee_amount' => 5.00,
1948 'net_amount' => 95.00,
1950 'invoice_id' => 78910,
1952 'contribution_status_id' => 1,
1954 $contribution = $this->callAPISuccess('contribution', 'create', $p);
1956 $result = $this->callAPISuccess('contribution', 'get', $params);
1957 // We're taking the first element.
1958 $res = $result['values'][$contribution['id']];
1960 $this->assertEquals($p['contact_id'], $res['contact_id']);
1961 $this->assertEquals($p['total_amount'], $res['total_amount']);
1962 $this->assertEquals($p['financial_type_id'], $res['financial_type_id']);
1963 $this->assertEquals($p['net_amount'], $res['net_amount']);
1964 $this->assertEquals($p['non_deductible_amount'], $res['non_deductible_amount']);
1965 $this->assertEquals($p['fee_amount'], $res['fee_amount']);
1966 $this->assertEquals($p['trxn_id'], $res['trxn_id']);
1967 $this->assertEquals($p['invoice_id'], $res['invoice_id']);
1968 $this->assertEquals($p['source'], $res['contribution_source']);
1969 // contribution_status_id = 1 => Completed
1970 $this->assertEquals('Completed', $res['contribution_status']);
1972 $this->contributionDelete($contribution['id']);
1976 * Test civicrm_contribution_search. Success expected.
1978 public function testSearch() {
1980 'contact_id' => $this->_individualId
,
1981 'receive_date' => date('Ymd'),
1982 'total_amount' => 100.00,
1983 'financial_type_id' => $this->_financialTypeId
,
1984 'non_deductible_amount' => 10.00,
1985 'contribution_status_id' => 1,
1987 $contribution1 = $this->callAPISuccess('contribution', 'create', $p1);
1990 'contact_id' => $this->_individualId
,
1991 'receive_date' => date('Ymd'),
1992 'total_amount' => 200.00,
1993 'financial_type_id' => $this->_financialTypeId
,
1994 'non_deductible_amount' => 20.00,
1995 'trxn_id' => 5454565,
1996 'invoice_id' => 1212124,
1997 'fee_amount' => 50.00,
1998 'net_amount' => 60.00,
1999 'contribution_status_id' => 2,
2001 $contribution2 = $this->callAPISuccess('contribution', 'create', $p2);
2004 'contribution_id' => $contribution2['id'],
2006 $result = $this->callAPISuccess('contribution', 'get', $params);
2007 $res = $result['values'][$contribution2['id']];
2009 $this->assertEquals($p2['contact_id'], $res['contact_id']);
2010 $this->assertEquals($p2['total_amount'], $res['total_amount']);
2011 $this->assertEquals($p2['financial_type_id'], $res['financial_type_id']);
2012 $this->assertEquals($p2['net_amount'], $res['net_amount']);
2013 $this->assertEquals($p2['non_deductible_amount'], $res['non_deductible_amount']);
2014 $this->assertEquals($p2['fee_amount'], $res['fee_amount']);
2015 $this->assertEquals($p2['trxn_id'], $res['trxn_id']);
2016 $this->assertEquals($p2['invoice_id'], $res['invoice_id']);
2017 $this->assertEquals(CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'), $res['contribution_status_id']);
2019 $this->contributionDelete($contribution1['id']);
2020 $this->contributionDelete($contribution2['id']);
2024 * Test completing a transaction via the API.
2026 * Note that we are creating a logged in user because email goes out from
2029 public function testCompleteTransaction() {
2030 $mut = new CiviMailUtils($this, TRUE);
2031 $this->swapMessageTemplateForTestTemplate();
2032 $this->createLoggedInUser();
2033 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2034 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2035 $this->callAPISuccess('contribution', 'completetransaction', [
2036 'id' => $contribution['id'],
2038 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2039 $this->assertEquals('SSF', $contribution['contribution_source']);
2040 $this->assertEquals('Completed', $contribution['contribution_status']);
2041 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
2042 $mut->checkMailLog([
2043 'email:::anthony_anderson@civicrm.org',
2047 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2048 "receipt_date:::\n",
2049 'contributeMode:::notify',
2050 'title:::Contribution',
2051 'displayName:::Mr. Anthony Anderson II',
2052 'contributionStatus:::Completed',
2055 $this->revertTemplateToReservedTemplate();
2059 * Test completing a transaction via the API with a non-USD transaction.
2061 public function testCompleteTransactionEuro() {
2062 $mut = new CiviMailUtils($this, TRUE);
2063 $this->swapMessageTemplateForTestTemplate();
2064 $this->createLoggedInUser();
2065 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'currency' => 'EUR']);
2066 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2068 $this->callAPISuccess('contribution', 'completetransaction', [
2069 'id' => $contribution['id'],
2072 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2073 $this->assertEquals('SSF', $contribution['contribution_source']);
2074 $this->assertEquals('Completed', $contribution['contribution_status']);
2075 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
2077 $entityFinancialTransactions = $this->getFinancialTransactionsForContribution($contribution['id']);
2078 $entityFinancialTransaction = reset($entityFinancialTransactions);
2079 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', ['id' => $entityFinancialTransaction['financial_trxn_id']]);
2080 $this->assertEquals('EUR', $financialTrxn['currency']);
2082 $mut->checkMailLog([
2083 'email:::anthony_anderson@civicrm.org',
2087 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2088 "receipt_date:::\n",
2089 'contributeMode:::notify',
2090 'title:::Contribution',
2091 'displayName:::Mr. Anthony Anderson II',
2092 'contributionStatus:::Completed',
2095 $this->revertTemplateToReservedTemplate();
2099 * Test to ensure mail is sent on chosing pay later
2101 public function testPayLater() {
2102 $mut = new CiviMailUtils($this, TRUE);
2103 $this->swapMessageTemplateForTestTemplate();
2104 $this->createLoggedInUser();
2106 // create contribution page first
2107 $contributionPageParams = [
2108 'title' => 'Help Support CiviCRM!',
2109 'financial_type_id' => 1,
2110 'is_monetary' => TRUE,
2111 'is_pay_later' => 1,
2112 'is_quick_config' => TRUE,
2113 'pay_later_text' => 'I will send payment by check',
2114 'pay_later_receipt' => 'This is a pay later reciept',
2115 'is_allow_other_amount' => 1,
2116 'min_amount' => 10.00,
2117 'max_amount' => 10000.00,
2118 'goal_amount' => 100000.00,
2119 'is_email_receipt' => 1,
2121 'amount_block_is_active' => 1,
2122 'currency' => 'USD',
2123 'is_billing_required' => 0,
2125 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', $contributionPageParams);
2127 // submit form values
2128 $priceSet = $this->callAPISuccess('price_set', 'getsingle', ['name' => 'default_contribution_amount']);
2130 'id' => $contributionPageResult['id'],
2131 'contact_id' => $this->_individualId
,
2132 'email-5' => 'anthony_anderson@civicrm.org',
2133 'payment_processor_id' => 0,
2136 'currencyID' => 'USD',
2137 'is_pay_later' => 1,
2138 'invoiceID' => 'f28e1ddc86f8c4a0ff5bcf46393e4bc8',
2139 'is_quick_config' => 1,
2140 'description' => 'Online Contribution: Help Support CiviCRM!',
2141 'price_set_id' => $priceSet['id'],
2143 $this->callAPISuccess('ContributionPage', 'submit', $params);
2145 $mut->checkMailLog([
2147 'email:::anthony_anderson@civicrm.org',
2148 'pay_later_receipt:::' . $contributionPageParams['pay_later_receipt'],
2149 'displayName:::Mr. Anthony Anderson II',
2150 'contributionPageId:::' . $contributionPageResult['id'],
2151 'title:::' . $contributionPageParams['title'],
2152 'amount:::' . $params['amount'],
2155 $this->revertTemplateToReservedTemplate();
2159 * Test to check whether contact billing address is used when no contribution address
2161 public function testBillingAddress() {
2162 $mut = new CiviMailUtils($this, TRUE);
2163 $this->swapMessageTemplateForTestTemplate();
2164 $this->createLoggedInUser();
2166 //Scenario 1: When Contact don't have any address
2167 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2168 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2169 $this->callAPISuccess('contribution', 'completetransaction', [
2170 'id' => $contribution['id'],
2172 $mut->checkMailLog([
2176 // Scenario 2: Contribution using address
2177 $address = $this->callAPISuccess('address', 'create', [
2178 'street_address' => 'contribution billing st',
2179 'location_type_id' => 2,
2180 'contact_id' => $this->_params
['contact_id'],
2182 $params = array_merge($this->_params
, [
2183 'contribution_status_id' => 2,
2184 'address_id' => $address['id'],
2187 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2188 $this->callAPISuccess('contribution', 'completetransaction', [
2189 'id' => $contribution['id'],
2191 $mut->checkMailLog([
2192 'address:::contribution billing st',
2195 // Scenario 3: Contribution wtth no address but contact has a billing address
2196 $this->callAPISuccess('address', 'create', [
2197 'id' => $address['id'],
2198 'street_address' => 'is billing st',
2199 'contact_id' => $this->_params
['contact_id'],
2201 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2202 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2203 $this->callAPISuccess('contribution', 'completetransaction', [
2204 'id' => $contribution['id'],
2206 $mut->checkMailLog([
2207 'address:::is billing st',
2211 $this->revertTemplateToReservedTemplate();
2215 * Test completing a transaction via the API.
2217 * Note that we are creating a logged in user because email goes out from
2220 public function testCompleteTransactionFeeAmount() {
2221 $this->createLoggedInUser();
2222 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2223 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2224 $this->callAPISuccess('contribution', 'completetransaction', [
2225 'id' => $contribution['id'],
2226 'fee_amount' => '.56',
2227 'trxn_id' => '7778888',
2229 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id'], 'sequential' => 1]);
2230 $this->assertEquals('Completed', $contribution['contribution_status']);
2231 $this->assertEquals('7778888', $contribution['trxn_id']);
2232 $this->assertEquals('0.56', $contribution['fee_amount']);
2233 $this->assertEquals('99.44', $contribution['net_amount']);
2237 * CRM-19126 Add test to verify when complete transaction is called tax amount is not changed.
2239 * @param string $thousandSeparator
2240 * punctuation used to refer to thousands.
2242 * @dataProvider getThousandSeparators
2244 public function testCheckTaxAmount($thousandSeparator) {
2245 $this->setCurrencySeparators($thousandSeparator);
2246 $contact = $this->createLoggedInUser();
2247 $financialType = $this->callAPISuccess('financial_type', 'create', [
2248 'name' => 'Test taxable financial Type',
2252 $financialAccount = $this->callAPISuccess('financial_account', 'create', [
2253 'name' => 'Test Tax financial account ',
2254 'contact_id' => $contact,
2255 'financial_account_type_id' => 2,
2262 $financialTypeId = $financialType['id'];
2263 $financialAccountId = $financialAccount['id'];
2264 $financialAccountParams = [
2265 'entity_table' => 'civicrm_financial_type',
2266 'entity_id' => $financialTypeId,
2267 'account_relationship' => 10,
2268 'financial_account_id' => $financialAccountId,
2270 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2272 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'financial_type_id' => $financialTypeId]);
2273 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2274 $contribution1 = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'return' => 'tax_amount', 'sequential' => 1]);
2275 $this->callAPISuccess('contribution', 'completetransaction', [
2276 'id' => $contribution['id'],
2277 'trxn_id' => '777788888',
2278 'fee_amount' => '6.00',
2280 $contribution2 = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'return' => ['tax_amount', 'fee_amount', 'net_amount'], 'sequential' => 1]);
2281 $this->assertEquals($contribution1['values'][0]['tax_amount'], $contribution2['values'][0]['tax_amount']);
2282 $this->assertEquals('6.00', $contribution2['values'][0]['fee_amount']);
2283 $this->assertEquals('99.00', $contribution2['values'][0]['net_amount']);
2287 * Test repeat contribution successfully creates line item.
2289 * @throws \CRM_Core_Exception
2291 public function testRepeatTransaction() {
2292 $originalContribution = $this->setUpRepeatTransaction($recurParams = [], 'single');
2293 $this->callAPISuccess('contribution', 'repeattransaction', [
2294 'original_contribution_id' => $originalContribution['id'],
2295 'contribution_status_id' => 'Completed',
2296 'trxn_id' => uniqid(),
2299 'entity_id' => $originalContribution['id'],
2307 'financial_type_id',
2308 'deductible_amount',
2309 'price_field_value_id',
2313 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2314 'entity_id' => $originalContribution['id'],
2316 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2317 'entity_id' => $originalContribution['id'] +
1,
2319 unset($lineItem1['values'][0]['id'], $lineItem1['values'][0]['entity_id']);
2320 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2321 $this->assertEquals($lineItem1['values'][0], $lineItem2['values'][0]);
2322 $this->_checkFinancialRecords([
2323 'id' => $originalContribution['id'] +
1,
2324 'payment_instrument_id' => $this->callAPISuccessGetValue('PaymentProcessor', [
2325 'id' => $originalContribution['payment_processor_id'],
2326 'return' => 'payment_instrument_id',
2332 * Test custom data is copied over from the template transaction.
2334 * (Over time various discussions have deemed this to be the most recent one, allowing
2335 * users to alter custom data going forwards. This is implemented for line items already.
2337 * @throws \API_Exception
2338 * @throws \CRM_Core_Exception
2340 public function testRepeatTransactionWithCustomData() {
2341 $this->createCustomGroupWithFieldOfType(['extends' => 'Contribution', 'name' => 'Repeat'], 'text');
2342 $originalContribution = $this->setUpRepeatTransaction([], 'single', [$this->getCustomFieldName('text') => 'first']);
2343 $this->callAPISuccess('contribution', 'repeattransaction', [
2344 'contribution_recur_id' => $originalContribution['contribution_recur_id'],
2345 'contribution_status_id' => 'Completed',
2346 'trxn_id' => 'my_trxn',
2349 $contribution = Contribution
::get()
2350 ->addWhere('trxn_id', '=', 'my_trxn')
2351 ->addSelect('Custom_Group.Enter_text_here')
2353 ->execute()->first();
2354 $this->assertEquals('first', $contribution['Custom_Group.Enter_text_here']);
2356 Contribution
::update()->setValues(['Custom_Group.Enter_text_here' => 'second'])->addWhere('id', '=', $contribution['id'])->execute();
2358 $this->callAPISuccess('contribution', 'repeattransaction', [
2359 'original_contribution_id' => $originalContribution['id'],
2360 'contribution_status_id' => 'Completed',
2361 'trxn_id' => 'number_3',
2364 $contribution = Contribution
::get()
2365 ->addWhere('trxn_id', '=', 'number_3')
2366 ->setSelect(['id', 'Custom_Group.Enter_text_here'])
2367 ->execute()->first();
2368 $this->assertEquals('second', $contribution['Custom_Group.Enter_text_here']);
2372 * Test repeat contribution successfully creates line items (plural).
2374 * @throws \CRM_Core_Exception
2376 public function testRepeatTransactionLineItems() {
2378 $originalContribution = $this->setUpRepeatTransaction($recurParams = [], 'multiple');
2379 $this->callAPISuccess('contribution', 'repeattransaction', [
2380 'original_contribution_id' => $originalContribution['id'],
2381 'contribution_status_id' => 'Completed',
2382 'trxn_id' => uniqid(),
2386 'entity_id' => $originalContribution['id'],
2394 'financial_type_id',
2395 'deductible_amount',
2396 'price_field_value_id',
2400 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2401 'entity_id' => $originalContribution['id'],
2403 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2404 'entity_id' => $originalContribution['id'] +
1,
2407 // unset id and entity_id for all of them to be able to compare the lineItems:
2408 unset($lineItem1['values'][0]['id'], $lineItem1['values'][0]['entity_id']);
2409 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2410 $this->assertEquals($lineItem1['values'][0], $lineItem2['values'][0]);
2412 unset($lineItem1['values'][1]['id'], $lineItem1['values'][1]['entity_id']);
2413 unset($lineItem2['values'][1]['id'], $lineItem2['values'][1]['entity_id']);
2414 $this->assertEquals($lineItem1['values'][1], $lineItem2['values'][1]);
2416 // CRM-19309 so in future we also want to:
2417 // check that financial_line_items have been created for entity_id 3 and 4;
2419 $this->callAPISuccessGetCount('FinancialItem', ['description' => 'Sales Tax', 'amount' => 0], 0);
2423 * Test repeat contribution successfully creates is_test transaction.
2425 public function testRepeatTransactionIsTest() {
2426 $this->_params
['is_test'] = 1;
2427 $originalContribution = $this->setUpRepeatTransaction(['is_test' => 1], 'single');
2429 $this->callAPISuccess('contribution', 'repeattransaction', [
2430 'original_contribution_id' => $originalContribution['id'],
2431 'contribution_status_id' => 'Completed',
2432 'trxn_id' => uniqid(),
2434 $this->callAPISuccessGetCount('Contribution', ['contribution_test' => 1], 2);
2438 * Test repeat contribution passed in status.
2440 public function testRepeatTransactionPassedInStatus() {
2441 $originalContribution = $this->setUpRepeatTransaction($recurParams = [], 'single');
2443 $this->callAPISuccess('contribution', 'repeattransaction', [
2444 'original_contribution_id' => $originalContribution['id'],
2445 'contribution_status_id' => 'Pending',
2446 'trxn_id' => uniqid(),
2448 $this->callAPISuccessGetCount('Contribution', ['contribution_status_id' => 2], 1);
2452 * Test repeat contribution accepts recur_id instead of original_contribution_id.
2454 public function testRepeatTransactionAcceptRecurID() {
2455 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2456 'contact_id' => $this->_individualId
,
2457 'installments' => '12',
2458 'frequency_interval' => '1',
2460 'contribution_status_id' => 1,
2461 'start_date' => '2012-01-01 00:00:00',
2462 'currency' => 'USD',
2463 'frequency_unit' => 'month',
2464 'payment_processor_id' => $this->paymentProcessorID
,
2466 $this->callAPISuccess('contribution', 'create', array_merge(
2468 ['contribution_recur_id' => $contributionRecur['id']])
2471 $this->callAPISuccess('contribution', 'repeattransaction', [
2472 'contribution_recur_id' => $contributionRecur['id'],
2473 'contribution_status_id' => 'Completed',
2474 'trxn_id' => uniqid(),
2480 * CRM-19873 Test repeattransaction if contribution_recur_id is a test.
2482 * @throws \CRM_Core_Exception
2484 public function testRepeatTransactionTestRecurId() {
2485 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
2486 'contact_id' => $this->_individualId
,
2487 'frequency_interval' => '1',
2489 'contribution_status_id' => 1,
2490 'start_date' => '2017-01-01 00:00:00',
2491 'currency' => 'USD',
2492 'frequency_unit' => 'month',
2493 'payment_processor_id' => $this->paymentProcessorID
,
2496 $this->callAPISuccess('contribution', 'create', array_merge(
2499 'contribution_recur_id' => $contributionRecur['id'],
2504 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2505 'contribution_recur_id' => $contributionRecur['id'],
2506 'contribution_status_id' => 'Completed',
2507 'trxn_id' => 'magic_number',
2510 $this->assertEquals($contributionRecur['values'][1]['is_test'], $repeatedContribution['values'][2]['is_test']);
2514 * CRM-19945 Tests that Contribute.repeattransaction renews a membership when contribution status=Completed
2516 * @throws \CRM_Core_Exception
2518 public function testRepeatTransactionMembershipRenewCompletedContribution() {
2519 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
2521 $contribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
2522 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2523 'contribution_status_id' => 'Failed',
2526 $this->callAPISuccess('membership', 'create', [
2527 'id' => $membership['id'],
2528 'end_date' => 'yesterday',
2529 'status_id' => 'Expired',
2532 $contribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
2533 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2534 'contribution_status_id' => 'Completed',
2535 'trxn_id' => 'bobsled',
2538 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
2539 'id' => $membership['id'],
2540 'return' => 'status_id',
2543 $membership = $this->callAPISuccess('membership', 'get', [
2544 'id' => $membership['id'],
2547 $this->assertEquals('New', CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
2549 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2550 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2551 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2555 * This is one of those tests that locks in existing behaviour.
2557 * I feel like correct behaviour is arguable & has been discussed in the past. However, if the membership has
2558 * a date which says it should be expired then the result of repeattransaction is to push that date
2559 * to be one membership term from 'now' with status 'new'.
2561 public function testRepeattransactionRenewMembershipOldMembership() {
2562 $entities = $this->setUpAutoRenewMembership();
2563 $newStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'New');
2564 $membership = $this->callAPISuccess('Membership', 'create', [
2565 'id' => $entities[1]['id'],
2566 'join_date' => '4 months ago',
2567 'start_date' => '3 months ago',
2568 'end_date' => '2 months ago',
2570 $membership = $membership['values'][$membership['id']];
2572 // This status does not appear to be calculated at all and is set to 'new'. Feels like a bug.
2573 $this->assertEquals($newStatusID, $membership['status_id']);
2575 // So it seems renewing this expired membership results in it's new status being current and it being pushed to a future date
2576 $this->callAPISuccess('Contribution', 'repeattransaction', ['original_contribution_id' => $entities[0]['id'], 'contribution_status_id' => 'Completed']);
2577 $membership = $this->callAPISuccessGetSingle('Membership', ['id' => $membership['id']]);
2578 // If this date calculation winds up being flakey the spirit of the test would be maintained by just checking
2579 // date is greater than today.
2580 $this->assertEquals(date('Y-m-d', strtotime('+ 1 month -1 day')), $membership['end_date']);
2581 $this->assertEquals($newStatusID, $membership['membership_type_id']);
2585 * CRM-19945 Tests that Contribute.repeattransaction DOES NOT renew a membership when contribution status=Failed
2587 * @dataProvider contributionStatusProvider
2589 * @throws \CRM_Core_Exception
2591 public function testRepeatTransactionMembershipRenewContributionNotCompleted($contributionStatus) {
2592 // Completed status should renew so we don't test that here
2593 // In Progress status was never actually intended to be available for contributions.
2594 // Partially paid is not valid.
2595 if (in_array($contributionStatus['name'], ['Completed', 'In Progress', 'Partially paid'])) {
2598 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
2600 $this->callAPISuccess('Contribution', 'repeattransaction', [
2601 'original_contribution_id' => $originalContribution['id'],
2602 'contribution_status_id' => 'Completed',
2605 $this->callAPISuccess('membership', 'create', [
2606 'id' => $membership['id'],
2607 'end_date' => 'yesterday',
2608 'status_id' => 'Expired',
2611 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2612 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2613 'contribution_status_id' => $contributionStatus['name'],
2614 'trxn_id' => 'bobsled',
2617 $updatedMembership = $this->callAPISuccess('membership', 'getsingle', ['id' => $membership['id']]);
2619 $dateTime = new DateTime('yesterday');
2620 $this->assertEquals($dateTime->format('Y-m-d'), $updatedMembership['end_date']);
2621 $this->assertEquals(CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Expired'), $updatedMembership['status_id']);
2623 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2624 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2625 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2629 * Dataprovider provides contribution status as [optionvalue=>contribution_status_name]
2630 * FIXME: buildOptions seems to die in CRM_Core_Config::_construct when in test mode.
2633 * @throws \CiviCRM_API3_Exception
2635 public function contributionStatusProvider() {
2636 $contributionStatuses = civicrm_api3('OptionValue', 'get', [
2637 'return' => ["id", "name"],
2638 'option_group_id' => "contribution_status",
2640 foreach ($contributionStatuses['values'] as $statusName) {
2641 $statuses[] = [$statusName];
2647 * CRM-16397 test appropriate action if total amount has changed for single line items.
2649 public function testRepeatTransactionAlteredAmount() {
2650 $paymentProcessorID = $this->paymentProcessorCreate();
2651 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2652 'contact_id' => $this->_individualId
,
2653 'installments' => '12',
2654 'frequency_interval' => '1',
2656 'contribution_status_id' => 1,
2657 'start_date' => '2012-01-01 00:00:00',
2658 'currency' => 'USD',
2659 'frequency_unit' => 'month',
2660 'payment_processor_id' => $paymentProcessorID,
2662 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2665 'contribution_recur_id' => $contributionRecur['id'],
2669 $this->callAPISuccess('contribution', 'repeattransaction', [
2670 'original_contribution_id' => $originalContribution['id'],
2671 'contribution_status_id' => 'Completed',
2672 'trxn_id' => uniqid(),
2673 'total_amount' => '400',
2678 'entity_id' => $originalContribution['id'],
2686 'financial_type_id',
2687 'deductible_amount',
2688 'price_field_value_id',
2692 $this->callAPISuccessGetSingle('contribution', [
2693 'total_amount' => 400,
2695 'net_amount' => 350,
2697 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2698 'entity_id' => $originalContribution['id'],
2700 $expectedLineItem = array_merge(
2701 $lineItem1['values'][0], [
2702 'line_total' => '400.00',
2703 'unit_price' => '400.00',
2707 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2708 'entity_id' => $originalContribution['id'] +
1,
2711 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2712 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2713 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2717 * Test financial_type_id override behaviour with a single line item.
2719 * CRM-17718 a passed in financial_type_id is allowed to override the original contribution where there
2720 * is only one line item.
2722 public function testRepeatTransactionPassedInFinancialType() {
2723 $originalContribution = $this->setUpRecurringContribution();
2725 $this->callAPISuccess('contribution', 'repeattransaction', [
2726 'original_contribution_id' => $originalContribution['id'],
2727 'contribution_status_id' => 'Completed',
2728 'trxn_id' => uniqid(),
2729 'financial_type_id' => 2,
2732 'entity_id' => $originalContribution['id'],
2740 'financial_type_id',
2741 'deductible_amount',
2742 'price_field_value_id',
2747 $this->callAPISuccessGetSingle('Contribution', [
2748 'total_amount' => 100,
2749 'financial_type_id' => 2,
2751 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2752 'entity_id' => $originalContribution['id'],
2754 $expectedLineItem = array_merge(
2755 $lineItem1['values'][0], [
2756 'line_total' => '100.00',
2757 'unit_price' => '100.00',
2758 'financial_type_id' => 2,
2759 'contribution_type_id' => 2,
2762 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2763 'entity_id' => $originalContribution['id'] +
1,
2765 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2766 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2767 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2771 * Test financial_type_id override behaviour with a single line item.
2773 * CRM-17718 a passed in financial_type_id is not allowed to override the original contribution where there
2774 * is more than one line item.
2776 public function testRepeatTransactionPassedInFinancialTypeTwoLineItems() {
2777 $this->_params
= $this->getParticipantOrderParams();
2778 $originalContribution = $this->setUpRecurringContribution();
2780 $this->callAPISuccess('Contribution', 'repeattransaction', [
2781 'original_contribution_id' => $originalContribution['id'],
2782 'contribution_status_id' => 'Completed',
2783 'trxn_id' => 'repeat',
2784 'financial_type_id' => 2,
2787 // Retrieve the new contribution and note the financial type passed in has been ignored.
2788 $contribution = $this->callAPISuccessGetSingle('Contribution', [
2789 'trxn_id' => 'repeat',
2791 $this->assertEquals(4, $contribution['financial_type_id']);
2793 $lineItems = $this->callAPISuccess('line_item', 'get', [
2794 'entity_id' => $contribution['id'],
2796 foreach ($lineItems as $lineItem) {
2797 $this->assertNotEquals(2, $lineItem['financial_type_id']);
2802 * CRM-17718 test appropriate action if financial type has changed for single line items.
2804 public function testRepeatTransactionUpdatedFinancialType() {
2805 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2807 $this->callAPISuccess('contribution', 'repeattransaction', [
2808 'contribution_recur_id' => $originalContribution['id'],
2809 'contribution_status_id' => 'Completed',
2810 'trxn_id' => uniqid(),
2813 'entity_id' => $originalContribution['id'],
2821 'financial_type_id',
2822 'deductible_amount',
2823 'price_field_value_id',
2828 $this->callAPISuccessGetSingle('contribution', [
2829 'total_amount' => 100,
2830 'financial_type_id' => 2,
2832 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2833 'entity_id' => $originalContribution['id'],
2835 $expectedLineItem = array_merge(
2836 $lineItem1['values'][0], [
2837 'line_total' => '100.00',
2838 'unit_price' => '100.00',
2839 'financial_type_id' => 2,
2840 'contribution_type_id' => 2,
2844 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2845 'entity_id' => $originalContribution['id'] +
1,
2847 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2848 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2849 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2853 * CRM-16397 test appropriate action if campaign has been passed in.
2855 public function testRepeatTransactionPassedInCampaign() {
2856 $paymentProcessorID = $this->paymentProcessorCreate();
2857 $campaignID = $this->campaignCreate();
2858 $campaignID2 = $this->campaignCreate();
2859 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2860 'contact_id' => $this->_individualId
,
2861 'installments' => '12',
2862 'frequency_interval' => '1',
2864 'contribution_status_id' => 1,
2865 'start_date' => '2012-01-01 00:00:00',
2866 'currency' => 'USD',
2867 'frequency_unit' => 'month',
2868 'payment_processor_id' => $paymentProcessorID,
2870 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2873 'contribution_recur_id' => $contributionRecur['id'],
2874 'campaign_id' => $campaignID,
2878 $this->callAPISuccess('contribution', 'repeattransaction', [
2879 'original_contribution_id' => $originalContribution['id'],
2880 'contribution_status_id' => 'Completed',
2881 'trxn_id' => uniqid(),
2882 'campaign_id' => $campaignID2,
2885 $this->callAPISuccessGetSingle('contribution', [
2886 'total_amount' => 100,
2887 'campaign_id' => $campaignID2,
2892 * CRM-17718 campaign stored on contribution recur gets priority.
2894 * This reflects the fact we permit people to update them.
2896 public function testRepeatTransactionUpdatedCampaign() {
2897 $paymentProcessorID = $this->paymentProcessorCreate();
2898 $campaignID = $this->campaignCreate();
2899 $campaignID2 = $this->campaignCreate();
2900 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2901 'contact_id' => $this->_individualId
,
2902 'installments' => '12',
2903 'frequency_interval' => '1',
2905 'contribution_status_id' => 1,
2906 'start_date' => '2012-01-01 00:00:00',
2907 'currency' => 'USD',
2908 'frequency_unit' => 'month',
2909 'payment_processor_id' => $paymentProcessorID,
2910 'campaign_id' => $campaignID,
2912 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2915 'contribution_recur_id' => $contributionRecur['id'],
2916 'campaign_id' => $campaignID2,
2920 $this->callAPISuccess('contribution', 'repeattransaction', [
2921 'original_contribution_id' => $originalContribution['id'],
2922 'contribution_status_id' => 'Completed',
2923 'trxn_id' => uniqid(),
2926 $this->callAPISuccessGetSingle('contribution', [
2927 'total_amount' => 100,
2928 'campaign_id' => $campaignID,
2933 * CRM-20685 Repeattransaction produces incorrect Financial Type ID (in specific circumstance) - if number of lineItems = 1.
2935 * This case happens when the line item & contribution do not have the same type in his initiating transaction.
2937 public function testRepeatTransactionUpdatedFinancialTypeAndNotEquals() {
2938 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2939 // This will made the trick to get the not equals behaviour.
2940 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 4]);
2941 $this->callAPISuccess('contribution', 'repeattransaction', [
2942 'contribution_recur_id' => $originalContribution['id'],
2943 'contribution_status_id' => 'Completed',
2944 'trxn_id' => uniqid(),
2947 'entity_id' => $originalContribution['id'],
2955 'financial_type_id',
2956 'deductible_amount',
2957 'price_field_value_id',
2961 $this->callAPISuccessGetSingle('contribution', [
2962 'total_amount' => 100,
2963 'financial_type_id' => 2,
2965 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2966 'entity_id' => $originalContribution['id'],
2968 $expectedLineItem = array_merge(
2969 $lineItem1['values'][0], [
2970 'line_total' => '100.00',
2971 'unit_price' => '100.00',
2972 'financial_type_id' => 4,
2973 'contribution_type_id' => 4,
2977 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2978 'entity_id' => $originalContribution['id'] +
1,
2980 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 1]);
2981 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2982 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2983 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2987 * Test completing a transaction does not 'mess' with net amount (CRM-15960).
2989 public function testCompleteTransactionNetAmountOK() {
2990 $this->createLoggedInUser();
2991 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2992 unset($params['net_amount']);
2993 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2994 $this->callAPISuccess('contribution', 'completetransaction', [
2995 'id' => $contribution['id'],
2997 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2998 $this->assertEquals('Completed', $contribution['contribution_status']);
2999 $this->assertTrue(($contribution['total_amount'] - $contribution['net_amount']) == $contribution['fee_amount']);
3003 * CRM-14151 - Test completing a transaction via the API.
3005 public function testCompleteTransactionWithReceiptDateSet() {
3006 $this->swapMessageTemplateForTestTemplate();
3007 $mut = new CiviMailUtils($this, TRUE);
3008 $this->createLoggedInUser();
3009 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
3010 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3011 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id'], 'trxn_date' => date('Y-m-d')]);
3012 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'sequential' => 1]);
3013 $this->assertEquals('Completed', $contribution['values'][0]['contribution_status']);
3014 // Make sure receive_date is original date and make sure payment date is today
3015 $this->assertEquals('2012-05-11', date('Y-m-d', strtotime($contribution['values'][0]['receive_date'])));
3016 $payment = $this->callAPISuccess('payment', 'get', ['contribution_id' => $contribution['id'], 'sequential' => 1]);
3017 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($payment['values'][0]['trxn_date'])));
3018 $mut->checkMailLog([
3019 'Receipt - Contribution',
3020 'receipt_date:::' . date('Ymd'),
3023 $this->revertTemplateToReservedTemplate();
3027 * CRM-1960 - Test to ensure that completetransaction respects the is_email_receipt setting
3029 public function testCompleteTransactionWithEmailReceiptInput() {
3030 $contributionPage = $this->createReceiptableContributionPage();
3032 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3033 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
3034 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3035 // Complete the transaction overriding is_email_receipt to = FALSE
3036 $this->callAPISuccess('contribution', 'completetransaction', [
3037 'id' => $contribution['id'],
3038 'trxn_date' => date('2011-04-09'),
3039 'trxn_id' => 'kazam',
3040 'is_email_receipt' => 0,
3042 // Check if a receipt was issued
3043 $receipt_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receipt_date']);
3044 $this->assertEquals('', $receipt_date);
3048 * Test that $is_recur is assigned to the receipt.
3050 public function testCompleteTransactionForRecurring() {
3051 $this->mut
= new CiviMailUtils($this, TRUE);
3052 $this->swapMessageTemplateForTestTemplate();
3053 $recurring = $this->setUpRecurringContribution();
3054 $contributionPage = $this->createReceiptableContributionPage(['is_recur' => TRUE, 'recur_frequency_unit' => 'month', 'recur_interval' => 1]);
3056 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3057 $this->_params
['contribution_recur_id'] = $recurring['id'];
3059 $contribution = $this->setUpForCompleteTransaction();
3061 $this->callAPISuccess('contribution', 'completetransaction', [
3062 'id' => $contribution['id'],
3063 'trxn_date' => date('2011-04-09'),
3064 'trxn_id' => 'kazam',
3065 'is_email_receipt' => 1,
3068 $this->mut
->checkMailLog([
3070 'cancelSubscriptionUrl:::' . CIVICRM_UF_BASEURL
,
3073 $this->revertTemplateToReservedTemplate();
3077 * CRM-19710 - Test to ensure that completetransaction respects the input for is_email_receipt setting.
3079 * If passed in it will override the default from contribution page.
3081 public function testCompleteTransactionWithEmailReceiptInputTrue() {
3082 $mut = new CiviMailUtils($this, TRUE);
3083 $this->createLoggedInUser();
3084 // Create a Contribution Page with is_email_receipt = FALSE
3085 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
3086 'receipt_from_name' => 'Mickey Mouse',
3087 'receipt_from_email' => 'mickey@mouse.com',
3088 'title' => "Test Contribution Page",
3089 'financial_type_id' => 1,
3090 'currency' => 'CAD',
3091 'is_monetary' => TRUE,
3092 'is_email_receipt' => 0,
3094 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3095 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
3096 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3097 // Complete the transaction overriding is_email_receipt to = TRUE
3098 $this->callAPISuccess('contribution', 'completetransaction', [
3099 'id' => $contribution['id'],
3100 'is_email_receipt' => 1,
3102 $mut->checkMailLog([
3103 'Contribution Information',
3109 * Complete the transaction using the template with all the possible.
3111 public function testCompleteTransactionWithTestTemplate() {
3112 $this->swapMessageTemplateForTestTemplate();
3113 $contribution = $this->setUpForCompleteTransaction();
3114 $this->callAPISuccess('contribution', 'completetransaction', [
3115 'id' => $contribution['id'],
3116 'trxn_date' => date('2011-04-09'),
3117 'trxn_id' => 'kazam',
3119 $receive_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receive_date']);
3120 $this->mut
->checkMailLog([
3121 'email:::anthony_anderson@civicrm.org',
3125 'receive_date:::' . date('Ymd', strtotime($receive_date)),
3126 'receipt_date:::' . date('Ymd'),
3127 'contributeMode:::notify',
3128 'title:::Contribution',
3129 'displayName:::Mr. Anthony Anderson II',
3131 'contactID:::' . $this->_params
['contact_id'],
3132 'contributionID:::' . $contribution['id'],
3133 'financialTypeId:::1',
3134 'financialTypeName:::Donation',
3137 $this->revertTemplateToReservedTemplate();
3141 * Complete the transaction using the template with all the possible.
3143 public function testCompleteTransactionContributionPageFromAddress() {
3144 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
3145 'receipt_from_name' => 'Mickey Mouse',
3146 'receipt_from_email' => 'mickey@mouse.com',
3147 'title' => "Test Contribution Page",
3148 'financial_type_id' => 1,
3149 'currency' => 'NZD',
3150 'goal_amount' => 50,
3151 'is_pay_later' => 1,
3152 'is_monetary' => TRUE,
3153 'is_email_receipt' => TRUE,
3155 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3156 $contribution = $this->setUpForCompleteTransaction();
3157 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id']]);
3158 $this->mut
->checkMailLog([
3166 * Test completing first transaction in a recurring series.
3168 * The status should be set to 'in progress' and the next scheduled payment date calculated.
3170 * @dataProvider getScheduledDateData
3172 * @param array $dataSet
3174 * @throws \Exception
3176 public function testCompleteTransactionSetStatusToInProgress($dataSet) {
3177 $paymentProcessorID = $this->paymentProcessorCreate();
3178 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
3179 'contact_id' => $this->_individualId
,
3180 'installments' => '2',
3181 'frequency_interval' => '1',
3183 'contribution_status_id' => 'Pending',
3184 'start_date' => '2012-01-01 00:00:00',
3185 'currency' => 'USD',
3186 'frequency_unit' => 'month',
3187 'payment_processor_id' => $paymentProcessorID,
3188 ], $dataSet['data']));
3189 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
3192 'contribution_recur_id' => $contributionRecur['id'],
3193 'contribution_status_id' => 'Pending',
3194 'receive_date' => $dataSet['receive_date'],
3197 $this->callAPISuccess('Contribution', 'completetransaction', [
3198 'id' => $contribution,
3199 'receive_date' => $dataSet['receive_date'],
3201 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3202 'id' => $contributionRecur['id'],
3203 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
3205 $this->assertEquals(5, $contributionRecur['contribution_status_id']);
3206 $this->assertEquals($dataSet['expected'], $contributionRecur['next_sched_contribution_date']);
3207 $this->callAPISuccess('Contribution', 'create', array_merge(
3210 'contribution_recur_id' => $contributionRecur['id'],
3211 'contribution_status_id' => 'Completed',
3214 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3215 'id' => $contributionRecur['id'],
3216 'return' => ['contribution_status_id'],
3218 $this->assertEquals(1, $contributionRecur['contribution_status_id']);
3222 * Get dates for testing.
3226 public function getScheduledDateData() {
3228 $result[]['2016-08-31-1-month'] = [
3230 'start_date' => '2016-08-31',
3231 'frequency_interval' => 1,
3232 'frequency_unit' => 'month',
3234 'receive_date' => '2016-08-31',
3235 'expected' => '2016-10-01 00:00:00',
3237 $result[]['2012-01-01-1-month'] = [
3239 'start_date' => '2012-01-01',
3240 'frequency_interval' => 1,
3241 'frequency_unit' => 'month',
3243 'receive_date' => '2012-01-01',
3244 'expected' => '2012-02-01 00:00:00',
3246 $result[]['2012-01-01-1-month'] = [
3248 'start_date' => '2012-01-01',
3249 'frequency_interval' => 1,
3250 'frequency_unit' => 'month',
3252 'receive_date' => '2012-02-29',
3253 'expected' => '2012-03-29 00:00:00',
3255 $result['receive_date_includes_time']['2012-01-01-1-month'] = [
3257 'start_date' => '2012-01-01',
3258 'frequency_interval' => 1,
3259 'frequency_unit' => 'month',
3260 'next_sched_contribution_date' => '2012-02-29',
3262 'receive_date' => '2012-02-29 16:00:00',
3263 'expected' => '2012-03-29 00:00:00',
3269 * Test completing a pledge with the completeTransaction api..
3271 * Note that we are creating a logged in user because email goes out from
3274 public function testCompleteTransactionUpdatePledgePayment() {
3275 $this->swapMessageTemplateForTestTemplate();
3276 $mut = new CiviMailUtils($this, TRUE);
3277 $mut->clearMessages();
3278 $this->createLoggedInUser();
3279 $contributionID = $this->createPendingPledgeContribution();
3280 $this->callAPISuccess('contribution', 'completetransaction', [
3281 'id' => $contributionID,
3282 'trxn_date' => '1 Feb 2013',
3284 $pledge = $this->callAPISuccessGetSingle('Pledge', [
3285 'id' => $this->_ids
['pledge'],
3287 $this->assertEquals('Completed', $pledge['pledge_status']);
3289 $status = $this->callAPISuccessGetValue('PledgePayment', [
3290 'pledge_id' => $this->_ids
['pledge'],
3291 'return' => 'status_id',
3293 $this->assertEquals(1, $status);
3294 $mut->checkMailLog([
3296 // The `receive_date` should remain as it was created.
3297 // TODO: the latest payment transaction date (and maybe other details,
3298 // such as amount and payment instrument) would be a useful token to make
3300 'receive_date:::20120511000000',
3301 "receipt_date:::\n",
3304 $this->revertTemplateToReservedTemplate();
3308 * Test completing a transaction with an event via the API.
3310 * Note that we are creating a logged in user because email goes out from
3313 * @throws \CRM_Core_Exception
3315 public function testCompleteTransactionWithParticipantRecord() {
3316 $mut = new CiviMailUtils($this, TRUE);
3317 $mut->clearMessages();
3318 $this->_individualId
= $this->createLoggedInUser();
3319 // Unset source to test whether one is generated if not set already on the contribution.
3320 unset($this->_params
['source']);
3321 $contributionID = $this->createPendingParticipantContribution();
3322 $this->createJoinedProfile(['entity_id' => $this->_ids
['event']['test'], 'entity_table' => 'civicrm_event']);
3323 $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']);
3324 $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']);
3325 $this->eliminateUFGroupOne();
3327 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contributionID]);
3328 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => ['contribution_source']]);
3329 $this->assertEquals('Online Event Registration: Annual CiviCRM meet', $contribution['contribution_source']);
3330 $participantStatus = $this->callAPISuccessGetValue('participant', [
3331 'id' => $this->_ids
['participant'],
3332 'return' => 'participant_status_id',
3334 $this->assertEquals(1, $participantStatus);
3336 //Assert only three activities are created.
3337 $activities = $this->callAPISuccess('Activity', 'get', [
3338 'contact_id' => $this->_individualId
,
3341 $this->assertCount(3, $activities);
3342 $activityNames = array_count_values(CRM_Utils_Array
::collect('activity_name', $activities));
3343 // record two activities before and after completing payment for Event registration
3344 $this->assertEquals(2, $activityNames['Event Registration']);
3345 // update the original 'Contribution' activity created after completing payment
3346 $this->assertEquals(1, $activityNames['Contribution']);
3348 $mut->checkMailLog([
3349 'Annual CiviCRM meet',
3351 'This is a confirmation that your registration has been received and your status has been updated to Registered.',
3352 'First Name: Logged In',
3356 ], ['Back end title', 'title_post_2', 'title_post_3']);
3361 * Test membership is renewed when transaction completed.
3363 public function testCompleteTransactionMembershipPriceSet() {
3364 $this->createPriceSetWithPage('membership');
3365 $stateOfGrace = $this->callAPISuccess('MembershipStatus', 'getvalue', [
3369 $this->setUpPendingContribution($this->_ids
['price_field_value'][0]);
3370 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3371 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3372 'membership_id' => $this->_ids
['membership'],
3374 $this->assertEquals(1, $logs['count']);
3375 $this->assertEquals($stateOfGrace, $membership['status_id']);
3376 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $this->_ids
['contribution']]);
3377 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3378 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 year')), $membership['end_date']);
3379 $this->callAPISuccessGetSingle('LineItem', [
3380 'entity_id' => $this->_ids
['membership'],
3381 'entity_table' => 'civicrm_membership',
3383 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3384 'membership_id' => $this->_ids
['membership'],
3386 $this->assertEquals(2, $logs['count']);
3387 $this->assertNotEquals($stateOfGrace, $logs['values'][2]['status_id']);
3388 //Assert only three activities are created.
3389 $activities = CRM_Activity_BAO_Activity
::getContactActivity($this->_ids
['contact']);
3390 $this->assertEquals(3, count($activities));
3391 $activityNames = array_flip(CRM_Utils_Array
::collect('activity_name', $activities));
3392 $this->assertArrayHasKey('Contribution', $activityNames);
3393 $this->assertArrayHasKey('Membership Signup', $activityNames);
3394 $this->assertArrayHasKey('Change Membership Status', $activityNames);
3395 $this->cleanUpAfterPriceSets();
3399 * Test if renewal activity is create after changing Pending contribution to Completed via offline
3401 public function testPendingToCompleteContribution() {
3402 $this->createPriceSetWithPage('membership');
3403 $this->setUpPendingContribution($this->_ids
['price_field_value'][0]);
3404 $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3405 // Case 1: Assert that Membership Signup Activity is created on Pending to Completed Contribution via backoffice
3406 $activity = $this->callAPISuccess('Activity', 'get', [
3407 'activity_type_id' => 'Membership Signup',
3408 'source_record_id' => $this->_ids
['membership'],
3409 'status_id' => 'Scheduled',
3411 $this->assertEquals(1, $activity['count']);
3413 // change pending contribution to completed
3414 $form = new CRM_Contribute_Form_Contribution();
3417 'id' => $this->_ids
['contribution'],
3418 'total_amount' => 20,
3421 'financial_type_id' => 1,
3422 'contact_id' => $this->_individualId
,
3423 'contribution_status_id' => 1,
3424 'billing_middle_name' => '',
3425 'billing_last_name' => 'Adams',
3426 'billing_street_address-5' => '790L Lincoln St S',
3427 'billing_city-5' => 'Maryknoll',
3428 'billing_state_province_id-5' => 1031,
3429 'billing_postal_code-5' => 10545,
3430 'billing_country_id-5' => 1228,
3431 'frequency_interval' => 1,
3432 'frequency_unit' => 'month',
3433 'installments' => '',
3434 'hidden_AdditionalDetail' => 1,
3435 'hidden_Premium' => 1,
3436 'from_email_address' => '"civi45" <civi45@civicrm.com>',
3437 'receipt_date' => '',
3438 'receipt_date_time' => '',
3439 'payment_processor_id' => $this->paymentProcessorID
,
3440 'currency' => 'USD',
3441 'contribution_page_id' => $this->_ids
['contribution_page'],
3442 'contribution_mode' => 'membership',
3443 'source' => 'Membership Signup and Renewal',
3446 $form->testSubmit($form->_params
, CRM_Core_Action
::UPDATE
);
3448 // Case 2: After successful payment for Pending backoffice there are three activities created
3449 // 2.a Update status of existing Scheduled Membership Signup (created in step 1) to Completed
3450 $activity = $this->callAPISuccess('Activity', 'get', [
3451 'activity_type_id' => 'Membership Signup',
3452 'source_record_id' => $this->_ids
['membership'],
3453 'status_id' => 'Completed',
3455 $this->assertEquals(1, $activity['count']);
3456 // 2.b Contribution activity created to record successful payment
3457 $activity = $this->callAPISuccess('Activity', 'get', [
3458 'activity_type_id' => 'Contribution',
3459 'source_record_id' => $this->_ids
['contribution'],
3460 'status_id' => 'Completed',
3462 $this->assertEquals(1, $activity['count']);
3464 // 2.c 'Change membership type' activity created to record Membership status change from Grace to Current
3465 $activity = $this->callAPISuccess('Activity', 'get', [
3466 'activity_type_id' => 'Change Membership Status',
3467 'source_record_id' => $this->_ids
['membership'],
3468 'status_id' => 'Completed',
3470 $this->assertEquals(1, $activity['count']);
3471 $this->assertEquals('Status changed from Grace to Current', $activity['values'][$activity['id']]['subject']);
3473 //Create another pending contribution for renewal
3474 $contribution = $this->callAPISuccess('contribution', 'create', [
3476 'contact_id' => $this->_ids
['contact'],
3477 'receive_date' => date('Ymd'),
3478 'total_amount' => 20.00,
3479 'financial_type_id' => 1,
3480 'payment_instrument_id' => 'Credit Card',
3481 'non_deductible_amount' => 10.00,
3482 'trxn_id' => 'rdhfi88',
3483 'invoice_id' => 'dofhiewuyr',
3485 'contribution_status_id' => 2,
3486 'contribution_page_id' => $this->_ids
['contribution_page'],
3487 // We can't rely on contribution api to link line items correctly to membership
3488 'skipLineItem' => TRUE,
3489 'api.membership_payment.create' => ['membership_id' => $this->_ids
['membership']],
3492 $this->callAPISuccess('line_item', 'create', [
3493 'entity_id' => $contribution['id'],
3494 'entity_table' => 'civicrm_contribution',
3495 'contribution_id' => $contribution['id'],
3496 'price_field_id' => $this->_ids
['price_field'][0],
3500 'financial_type_id' => 1,
3501 'price_field_value_id' => $this->_ids
['price_field_value']['cont'],
3503 $this->callAPISuccess('line_item', 'create', [
3504 'entity_id' => $this->_ids
['membership'],
3505 'entity_table' => 'civicrm_membership',
3506 'contribution_id' => $contribution['id'],
3507 'price_field_id' => $this->_ids
['price_field'][0],
3511 'financial_type_id' => 1,
3512 'price_field_value_id' => $this->_ids
['price_field_value'][0],
3513 'membership_type_id' => $this->_ids
['membership_type'],
3516 //Update it to Failed.
3517 $form->_params
['id'] = $contribution['id'];
3518 $form->_params
['contribution_status_id'] = 4;
3520 $form->testSubmit($form->_params
, CRM_Core_Action
::UPDATE
);
3521 //Existing membership should not get updated to expired.
3522 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3523 $this->assertNotEquals($membership['status_id'], 4);
3527 * Test membership is renewed for 2 terms when transaction completed based on the line item having 2 terms as qty.
3529 * Also check that altering the qty for the most recent contribution results in repeattransaction picking it up.
3531 public function testCompleteTransactionMembershipPriceSetTwoTerms() {
3532 $this->createPriceSetWithPage('membership');
3533 $this->setUpPendingContribution($this->_ids
['price_field_value'][1]);
3534 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $this->_ids
['contribution']]);
3535 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->_ids
['membership']]);
3536 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 2 years')), $membership['end_date']);
3538 $paymentProcessorID = $this->paymentProcessorAuthorizeNetCreate();
3540 $contributionRecurID = $this->callAPISuccess('ContributionRecur', 'create', ['contact_id' => $membership['contact_id'], 'payment_processor_id' => $paymentProcessorID, 'amount' => 20, 'frequency_interval' => 1])['id'];
3541 $this->callAPISuccess('Contribution', 'create', ['id' => $this->_ids
['contribution'], 'contribution_recur_id' => $contributionRecurID]);
3542 $this->callAPISuccess('contribution', 'repeattransaction', ['contribution_recur_id' => $contributionRecurID, 'contribution_status_id' => 'Completed']);
3543 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->_ids
['membership']]);
3544 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 4 years')), $membership['end_date']);
3546 // 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.
3547 $contribution = Contribution
::get()->setOrderBy(['id' => 'DESC'])->setSelect(['id'])->execute()->first();
3548 CRM_Core_DAO
::executeQuery('UPDATE civicrm_line_item SET price_field_value_id = ' . $this->_ids
['price_field_value'][0] . ' WHERE contribution_id = ' . $contribution['id']);
3549 $this->callAPISuccess('contribution', 'repeattransaction', ['contribution_recur_id' => $contributionRecurID, 'contribution_status_id' => 'Completed']);
3550 $membership = $this->callAPISuccessGetSingle('membership', ['id' => $this->_ids
['membership']]);
3551 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 5 years')), $membership['end_date']);
3553 $this->cleanUpAfterPriceSets();
3556 public function cleanUpAfterPriceSets() {
3557 $this->quickCleanUpFinancialEntities();
3558 $this->contactDelete($this->_ids
['contact']);
3562 * Set up a pending transaction with a specific price field id.
3564 * @param int $priceFieldValueID
3565 * @param array $contriParams
3567 * @throws \CRM_Core_Exception
3569 public function setUpPendingContribution($priceFieldValueID, $contriParams = []) {
3570 $contactID = $this->individualCreate();
3571 $contribution = $this->callAPISuccess('Order', 'create', array_merge([
3573 'contact_id' => $contactID,
3574 'receive_date' => date('Ymd'),
3575 'total_amount' => 20.00,
3576 'financial_type_id' => 1,
3577 'payment_instrument_id' => 'Credit Card',
3578 'non_deductible_amount' => 10.00,
3579 'trxn_id' => 'jdhfi' . rand(1, 100),
3580 'invoice_id' => 'djfhiew' . rand(5, 100),
3582 'contribution_status_id' => 2,
3583 'contribution_page_id' => $this->_ids
['contribution_page'],
3588 'price_field_id' => $this->_ids
['price_field'][0],
3590 'entity_table' => 'civicrm_membership',
3593 'financial_type_id' => 1,
3594 'price_field_value_id' => $priceFieldValueID,
3598 'contact_id' => $contactID,
3599 'membership_type_id' => $this->_ids
['membership_type'],
3600 'start_date' => 'yesterday - 1 year',
3601 'end_date' => 'yesterday',
3602 'join_date' => 'yesterday - 1 year',
3608 $this->_ids
['contact'] = $contactID;
3609 $this->_ids
['contribution'] = $contribution['id'];
3610 $this->_ids
['membership'] = $this->callAPISuccessGetValue('MembershipPayment', ['return' => 'membership_id', 'contribution_id' => $contribution['id']]);
3614 * Test sending a mail via the API.
3616 * @throws \CRM_Core_Exception
3617 * @throws \CiviCRM_API3_Exception
3619 public function testSendMail() {
3620 $mut = new CiviMailUtils($this, TRUE);
3621 $orderParams = $this->_params
;
3622 $orderParams['contribution_status_id'] = 'Pending';
3623 $orderParams['api.PaymentProcessor.pay'] = [
3624 'payment_processor_id' => $this->paymentProcessorID
,
3625 'credit_card_type' => 'Visa',
3626 'credit_card_number' => 41111111111111,
3630 $order = $this->callAPISuccess('Order', 'create', $orderParams);
3631 $this->callAPISuccess('Payment', 'create', ['total_amount' => 5, 'is_send_notification' => 0, 'order_id' => $order['id']]);
3632 $address = $this->callAPISuccess('Address', 'create', ['contribution_id' => $order['id'], 'name' => 'bob', 'contact_id' => 1, 'street_address' => 'blah']);
3633 $this->callAPISuccess('Contribution', 'create', ['id' => $order['id'], 'address_id' => $address['id']]);
3634 $this->callAPISuccess('contribution', 'sendconfirmation', [
3635 'id' => $order['id'],
3636 'receipt_from_email' => 'api@civicrm.org',
3638 $mut->checkMailLog([
3640 'Contribution Information',
3645 $this->checkCreditCardDetails($mut, $order['id']);
3647 $tplVars = CRM_Core_Smarty
::singleton()->get_template_vars();
3648 $this->assertEquals('bob', $tplVars['billingName']);
3649 $this->assertEquals("bob\nblah\n", $tplVars['address']);
3653 * Test sending a mail via the API.
3654 * This simulates webform_civicrm using pay later contribution page
3656 public function testSendconfirmationPayLater() {
3657 $mut = new CiviMailUtils($this, TRUE);
3659 // Create contribution page
3661 'title' => 'Webform Contributions',
3662 'financial_type_id' => 1,
3663 'contribution_type_id' => 1,
3664 'is_confirm_enabled' => 1,
3665 'is_pay_later' => 1,
3666 'pay_later_text' => 'I will send payment by cheque',
3667 'pay_later_receipt' => 'Send your cheque payable to "CiviCRM LLC" to the office',
3669 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $pageParams);
3671 // Create pay later contribution
3673 'contact_id' => $this->_individualId
,
3674 'financial_type_id' => 1,
3675 'is_pay_later' => 1,
3676 'contribution_status_id' => 2,
3677 'contribution_page_id' => $contributionPage['id'],
3678 'total_amount' => '10.00',
3680 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
3684 'contribution_id' => $contribution['id'],
3685 'entity_id' => $contribution['id'],
3686 'entity_table' => 'civicrm_contribution',
3687 'label' => 'My lineitem label',
3689 'unit_price' => "10.00",
3690 'line_total' => "10.00",
3692 $lineItem = $this->callAPISuccess('lineItem', 'create', $lineItemParams);
3696 civicrm_api3('contribution', 'sendconfirmation', [
3697 'id' => $contribution['id'],
3698 'receipt_from_email' => 'api@civicrm.org',
3701 catch (Exception
$e) {
3702 // Need to figure out how to stop this some other day
3703 // We don't care about the Payment Processor because this is Pay Later
3704 // The point of this test is to check we get the pay_later version of the mail
3705 if ($e->getMessage() != "Undefined variable: CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage") {
3710 // Retrieve mail & check it has the pay_later_receipt info
3711 $mut->getMostRecentEmail('raw');
3712 $mut->checkMailLog([
3713 (string) $contribParams['total_amount'],
3714 $pageParams['pay_later_receipt'],
3722 * Check credit card details in sent mail via API
3724 * @param CiviMailUtils $mut
3725 * @param int $contributionID Contribution ID
3727 * @throws \CRM_Core_Exception
3729 public function checkCreditCardDetails($mut, $contributionID) {
3730 $this->callAPISuccess('contribution', 'create', $this->_params
);
3731 $this->callAPISuccess('contribution', 'sendconfirmation', [
3732 'id' => $contributionID,
3733 'receipt_from_email' => 'api@civicrm.org',
3734 'payment_processor_id' => $this->paymentProcessorID
,
3736 $mut->checkMailLog([
3738 'Billing Name and Address',
3740 'anthony_anderson@civicrm.org',
3747 * Test sending a mail via the API.
3749 public function testSendMailEvent() {
3750 $mut = new CiviMailUtils($this, TRUE);
3751 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
3752 $event = $this->eventCreate([
3753 'is_email_confirm' => 1,
3754 'confirm_from_email' => 'test@civicrm.org',
3756 $this->_eventID
= $event['id'];
3757 $participantParams = [
3758 'contact_id' => $this->_individualId
,
3759 'event_id' => $this->_eventID
,
3762 // to ensure it matches later on
3763 'register_date' => '2007-07-21 00:00:00',
3764 'source' => 'Online Event Registration: API Testing',
3767 $participant = $this->callAPISuccess('participant', 'create', $participantParams);
3768 $this->callAPISuccess('participant_payment', 'create', [
3769 'participant_id' => $participant['id'],
3770 'contribution_id' => $contribution['id'],
3772 $this->callAPISuccess('contribution', 'sendconfirmation', [
3773 'id' => $contribution['id'],
3774 'receipt_from_email' => 'api@civicrm.org',
3777 $mut->checkMailLog([
3778 'Annual CiviCRM meet',
3780 'To: "Mr. Anthony Anderson II" <anthony_anderson@civicrm.org>',
3786 * This function does a GET & compares the result against the $params.
3788 * Use as a double check on Creates.
3790 * @param array $params
3792 * @param bool $delete
3794 public function contributionGetnCheck($params, $id, $delete = TRUE) {
3796 $contribution = $this->callAPISuccess('Contribution', 'Get', [
3801 $this->callAPISuccess('contribution', 'delete', ['id' => $id]);
3803 $this->assertAPISuccess($contribution, 0);
3804 $values = $contribution['values'][$contribution['id']];
3805 $params['receive_date'] = date('Y-m-d H:i:s', strtotime($params['receive_date']));
3806 // this is not returned in id format
3807 unset($params['payment_instrument_id']);
3808 $params['contribution_source'] = $params['source'];
3809 unset($params['source']);
3810 foreach ($params as $key => $value) {
3811 $this->assertEquals($value, $values[$key], $key . " value: $value doesn't match " . print_r($values, TRUE));
3816 * Create a pending contribution & linked pending pledge record.
3818 public function createPendingPledgeContribution() {
3820 $pledgeID = $this->pledgeCreate(['contact_id' => $this->_individualId
, 'installments' => 1, 'amount' => 500]);
3821 $this->_ids
['pledge'] = $pledgeID;
3822 $contribution = $this->callAPISuccess('contribution', 'create', array_merge($this->_params
, [
3823 'contribution_status_id' => 'Pending',
3824 'total_amount' => 500,
3826 $paymentID = $this->callAPISuccessGetValue('PledgePayment', [
3827 'options' => ['limit' => 1],
3830 $this->callAPISuccess('PledgePayment', 'create', [
3832 'contribution_id' =>
3833 $contribution['id'],
3834 'status_id' => 'Pending',
3835 'scheduled_amount' => 500,
3838 return $contribution['id'];
3842 * Create a pending contribution & linked pending participant record (along with an event).
3844 public function createPendingParticipantContribution() {
3845 $this->_ids
['event']['test'] = $this->eventCreate(['is_email_confirm' => 1, 'confirm_from_email' => 'test@civicrm.org'])['id'];
3846 $participantID = $this->participantCreate(['event_id' => $this->_ids
['event']['test'], 'status_id' => 6, 'contact_id' => $this->_individualId
]);
3847 $this->_ids
['participant'] = $participantID;
3848 $params = array_merge($this->_params
, ['contact_id' => $this->_individualId
, 'contribution_status_id' => 2, 'financial_type_id' => 'Event Fee']);
3849 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3850 $this->callAPISuccess('participant_payment', 'create', [
3851 'contribution_id' => $contribution['id'],
3852 'participant_id' => $participantID,
3854 $this->callAPISuccess('line_item', 'get', [
3855 'entity_id' => $contribution['id'],
3856 'entity_table' => 'civicrm_contribution',
3857 'api.line_item.create' => [
3858 'entity_id' => $participantID,
3859 'entity_table' => 'civicrm_participant',
3862 return $contribution['id'];
3866 * Get financial transaction amount.
3868 * @param int $contId
3870 * @return null|string
3872 public function _getFinancialTrxnAmount($contId) {
3874 SUM( ft.total_amount ) AS total
3875 FROM civicrm_financial_trxn AS ft
3876 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.id = ceft.financial_trxn_id
3877 WHERE ceft.entity_table = 'civicrm_contribution'
3878 AND ceft.entity_id = {$contId}";
3880 $result = CRM_Core_DAO
::singleValueQuery($query);
3885 * @param int $contId
3887 * @return null|string
3889 public function _getFinancialItemAmount($contId) {
3890 $lineItem = key(CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution'));
3893 FROM civicrm_financial_item
3894 WHERE entity_table = 'civicrm_line_item'
3895 AND entity_id = {$lineItem}";
3896 $result = CRM_Core_DAO
::singleValueQuery($query);
3901 * @param int $contId
3904 public function _checkFinancialItem($contId, $context) {
3905 if ($context != 'paylater') {
3907 'entity_id' => $contId,
3908 'entity_table' => 'civicrm_contribution',
3910 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($params, TRUE));
3912 'financial_trxn_id' => $trxn['financial_trxn_id'],
3913 'entity_table' => 'civicrm_financial_item',
3915 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3917 'id' => $entityTrxn['entity_id'],
3920 if ($context == 'paylater') {
3921 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution');
3922 foreach ($lineItems as $key => $item) {
3924 'entity_id' => $key,
3925 'entity_table' => 'civicrm_line_item',
3927 $compareParams = ['status_id' => 1];
3928 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3931 elseif ($context == 'refund') {
3934 'financial_account_id' => 1,
3938 elseif ($context == 'cancelPending') {
3941 'financial_account_id' => 1,
3945 elseif ($context == 'changeFinancial') {
3946 $lineKey = key(CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution'));
3948 'entity_id' => $lineKey,
3952 'financial_account_id' => 1,
3954 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3956 'financial_account_id' => 3,
3957 'entity_id' => $lineKey,
3963 if ($context != 'paylater') {
3964 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3969 * Check correct financial transaction entries were created for the change in payment instrument.
3971 * @param int $contributionID
3972 * @param int $originalInstrumentID
3973 * @param int $newInstrumentID
3974 * @param int $amount
3976 public function checkFinancialTrxnPaymentInstrumentChange($contributionID, $originalInstrumentID, $newInstrumentID, $amount = 100) {
3978 $entityFinancialTrxns = $this->getFinancialTransactionsForContribution($contributionID);
3980 $originalTrxnParams = [
3981 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($originalInstrumentID),
3982 'payment_instrument_id' => $originalInstrumentID,
3983 'amount' => $amount,
3987 $reversalTrxnParams = [
3988 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($originalInstrumentID),
3989 'payment_instrument_id' => $originalInstrumentID,
3990 'amount' => -$amount,
3995 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($newInstrumentID),
3996 'payment_instrument_id' => $newInstrumentID,
3997 'amount' => $amount,
4001 foreach ([$originalTrxnParams, $reversalTrxnParams, $newTrxnParams] as $index => $transaction) {
4002 $entityFinancialTrxn = $entityFinancialTrxns[$index];
4003 $this->assertEquals($entityFinancialTrxn['amount'], $transaction['amount']);
4005 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', [
4006 'id' => $entityFinancialTrxn['financial_trxn_id'],
4008 $this->assertEquals($transaction['status_id'], $financialTrxn['status_id']);
4009 $this->assertEquals($transaction['amount'], $financialTrxn['total_amount']);
4010 $this->assertEquals($transaction['amount'], $financialTrxn['net_amount']);
4011 $this->assertEquals(0, $financialTrxn['fee_amount']);
4012 $this->assertEquals($transaction['payment_instrument_id'], $financialTrxn['payment_instrument_id']);
4013 $this->assertEquals($transaction['to_financial_account_id'], $financialTrxn['to_financial_account_id']);
4016 $this->assertEquals(1, $financialTrxn['is_payment']);
4017 $this->assertEquals('USD', $financialTrxn['currency']);
4018 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($financialTrxn['trxn_date'])));
4023 * Check financial transaction.
4025 * @todo break this down into sensible functions - most calls to it only use a few lines out of the big if.
4027 * @param array $contribution
4028 * @param string $context
4029 * @param int $instrumentId
4030 * @param array $extraParams
4032 public function _checkFinancialTrxn($contribution, $context, $instrumentId = NULL, $extraParams = []) {
4033 $financialTrxns = $this->getFinancialTransactionsForContribution($contribution['id']);
4034 $trxn = array_pop($financialTrxns);
4037 'id' => $trxn['financial_trxn_id'],
4039 if ($context == 'payLater') {
4042 'from_financial_account_id' => CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is'),
4045 elseif ($context == 'refund') {
4047 'to_financial_account_id' => 6,
4048 'total_amount' => -100,
4050 'trxn_date' => '2015-01-01 09:00:00',
4051 'trxn_id' => 'the refund',
4054 elseif ($context == 'cancelPending') {
4056 'to_financial_account_id' => 7,
4057 'total_amount' => -100,
4061 elseif ($context == 'changeFinancial' ||
$context == 'paymentInstrument') {
4062 // @todo checkFinancialTrxnPaymentInstrumentChange instead for paymentInstrument.
4063 // It does the same thing with greater readability.
4064 // @todo remove handling for
4067 'entity_id' => $contribution['id'],
4068 'entity_table' => 'civicrm_contribution',
4071 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
4073 'id' => $trxn['financial_trxn_id'],
4075 if (empty($extraParams)) {
4077 'total_amount' => -100,
4081 elseif ($context !== 'changeFinancial') {
4083 'total_amount' => 100,
4087 if ($context == 'paymentInstrument') {
4088 $compareParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($instrumentId);
4089 $compareParams['payment_instrument_id'] = $instrumentId;
4092 $compareParams['to_financial_account_id'] = 12;
4094 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams1, array_merge($compareParams, $extraParams));
4095 $compareParams['total_amount'] = 100;
4096 // Reverse the extra params now that we will be checking the new positive transaction.
4097 if ($context === 'changeFinancial' && !empty($extraParams)) {
4098 foreach ($extraParams as $param => $value) {
4099 $extraParams[$param] = 0 - $value;
4104 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $params, array_merge($compareParams, $extraParams));
4110 public function _addPaymentInstrument() {
4111 $gId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'payment_instrument', 'id', 'name');
4113 'option_group_id' => $gId,
4114 'label' => 'Test Card',
4115 'name' => 'Test Card',
4120 $optionValue = $this->callAPISuccess('option_value', 'create', $optionParams);
4121 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
4122 $financialParams = [
4123 'entity_table' => 'civicrm_option_value',
4124 'entity_id' => $optionValue['id'],
4125 'account_relationship' => $relationTypeId,
4126 'financial_account_id' => 7,
4128 CRM_Financial_BAO_FinancialTypeAccount
::add($financialParams);
4129 $this->assertNotEmpty($optionValue['values'][$optionValue['id']]['value']);
4130 return $optionValue['values'][$optionValue['id']]['value'];
4133 public function _deletedAddedPaymentInstrument() {
4134 $result = $this->callAPISuccess('OptionValue', 'get', [
4135 'option_group_id' => 'payment_instrument',
4136 'name' => 'Test Card',
4140 if ($id = CRM_Utils_Array
::value('id', $result)) {
4141 $this->callAPISuccess('OptionValue', 'delete', ['id' => $id]);
4146 * Set up the basic recurring contribution for tests.
4148 * @param array $generalParams
4149 * Parameters that can be merged into the recurring AND the contribution.
4151 * @param array $recurParams
4152 * Parameters to merge into the recur only.
4155 * @throws \CRM_Core_Exception
4157 protected function setUpRecurringContribution($generalParams = [], $recurParams = []) {
4158 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4159 'contact_id' => $this->_individualId
,
4160 'installments' => '12',
4161 'frequency_interval' => '1',
4163 'contribution_status_id' => 1,
4164 'start_date' => '2012-01-01 00:00:00',
4165 'currency' => 'USD',
4166 'frequency_unit' => 'month',
4167 'payment_processor_id' => $this->paymentProcessorID
,
4168 ], $generalParams, $recurParams));
4169 $contributionParams = array_merge(
4172 'contribution_recur_id' => $contributionRecur['id'],
4173 'contribution_status_id' => 'Pending',
4175 $contributionParams['api.Payment.create'] = ['total_amount' => $contributionParams['total_amount']];
4176 $originalContribution = $this->callAPISuccess('Order', 'create', $contributionParams);
4177 return $originalContribution;
4181 * Set up a basic auto-renew membership for tests.
4183 * @param array $generalParams
4184 * Parameters that can be merged into the recurring AND the contribution.
4186 * @param array $recurParams
4187 * Parameters to merge into the recur only.
4190 * @throws \CRM_Core_Exception
4192 protected function setUpAutoRenewMembership($generalParams = [], $recurParams = []) {
4193 $newContact = $this->callAPISuccess('Contact', 'create', [
4194 'contact_type' => 'Individual',
4195 'sort_name' => 'McTesterson, Testy',
4196 'display_name' => 'Testy McTesterson',
4197 'preferred_language' => 'en_US',
4198 'preferred_mail_format' => 'Both',
4199 'first_name' => 'Testy',
4200 'last_name' => 'McTesterson',
4201 'contact_is_deleted' => '0',
4203 'email' => 'tmctesterson@example.com',
4206 $membershipType = $this->callAPISuccess('MembershipType', 'create', [
4207 'domain_id' => 'Default Domain Name',
4208 'member_of_contact_id' => 1,
4209 'financial_type_id' => 'Member Dues',
4210 'duration_unit' => 'month',
4211 'duration_interval' => 1,
4212 'period_type' => 'rolling',
4213 'name' => 'Standard Member',
4214 'minimum_fee' => 100,
4216 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4217 'contact_id' => $newContact['id'],
4218 'installments' => '12',
4219 'frequency_interval' => '1',
4221 'contribution_status_id' => 1,
4222 'start_date' => '2012-01-01 00:00:00',
4223 'currency' => 'USD',
4224 'frequency_unit' => 'month',
4225 'payment_processor_id' => $this->paymentProcessorID
,
4226 ], $generalParams, $recurParams));
4228 $membership = $this->callAPISuccess('membership', 'create', [
4229 'contact_id' => $newContact['id'],
4230 'contribution_recur_id' => $contributionRecur['id'],
4231 'financial_type_id' => "Member Dues",
4232 'membership_type_id' => $membershipType['id'],
4234 'skipLineItem' => TRUE,
4237 CRM_Price_BAO_LineItem
::getLineItemArray($this->_params
, NULL, 'membership', $membershipType['id']);
4238 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4241 'contact_id' => $newContact['id'],
4242 'contribution_recur_id' => $contributionRecur['id'],
4243 'financial_type_id' => "Member Dues",
4244 'contribution_status_id' => 1,
4245 'invoice_id' => uniqid(),
4248 $lineItem = $this->callAPISuccess('LineItem', 'getsingle', []);
4249 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
4250 $membership = $this->callAPISuccess('Membership', 'getsingle', ['id' => $lineItem['entity_id']]);
4251 $this->callAPISuccess('LineItem', 'getsingle', []);
4252 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']], 1);
4254 return [$originalContribution, $membership];
4258 * Set up a repeat transaction.
4260 * @param array $recurParams
4261 * @param mixed $flag
4262 * @param array $contributionParams
4265 protected function setUpRepeatTransaction($recurParams = [], $flag, $contributionParams = []) {
4266 $paymentProcessorID = $this->paymentProcessorCreate();
4267 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4268 'contact_id' => $this->_individualId
,
4269 'installments' => '12',
4270 'frequency_interval' => '1',
4272 'contribution_status_id' => 1,
4273 'start_date' => '2012-01-01 00:00:00',
4274 'currency' => 'USD',
4275 'frequency_unit' => 'month',
4276 'payment_processor_id' => $paymentProcessorID,
4279 $originalContribution = '';
4280 if ($flag == 'multiple') {
4281 // CRM-19309 create a contribution + also add in line_items (plural):
4282 $params = array_merge($this->_params
, $contributionParams);
4283 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4286 'contribution_recur_id' => $contributionRecur['id'],
4287 'skipLineItem' => 1,
4288 'api.line_item.create' => [
4290 'price_field_id' => 1,
4292 'line_total' => '20',
4293 'unit_price' => '10',
4294 'financial_type_id' => 1,
4297 'price_field_id' => 1,
4299 'line_total' => '80',
4300 'unit_price' => '80',
4301 'financial_type_id' => 2,
4308 elseif ($flag == 'single') {
4309 $params = array_merge($this->_params
, ['contribution_recur_id' => $contributionRecur['id']]);
4310 $params = array_merge($params, $contributionParams);
4311 $originalContribution = $this->callAPISuccess('contribution', 'create', $params);
4313 $originalContribution['contribution_recur_id'] = $contributionRecur['id'];
4314 $originalContribution['payment_processor_id'] = $paymentProcessorID;
4315 return $originalContribution;
4319 * Common set up routine.
4323 protected function setUpForCompleteTransaction() {
4324 $this->mut
= new CiviMailUtils($this, TRUE);
4325 $this->createLoggedInUser();
4326 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
4327 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4328 return $contribution;
4332 * Test repeat contribution uses the Payment Processor' payment_instrument setting.
4334 * @throws \CRM_Core_Exception
4336 public function testRepeatTransactionWithNonCreditCardDefault() {
4337 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
4338 'contact_id' => $this->_individualId
,
4339 'installments' => '12',
4340 'frequency_interval' => '1',
4342 'contribution_status_id' => 1,
4343 'start_date' => '2012-01-01 00:00:00',
4344 'currency' => 'USD',
4345 'frequency_unit' => 'month',
4346 'payment_processor_id' => $this->paymentProcessorID
,
4348 $contribution1 = $this->callAPISuccess('contribution', 'create', array_merge(
4350 ['contribution_recur_id' => $contributionRecur['id'], 'payment_instrument_id' => 2])
4352 $contribution2 = $this->callAPISuccess('contribution', 'repeattransaction', [
4353 'contribution_status_id' => 'Completed',
4354 'trxn_id' => 'blah',
4355 'original_contribution_id' => $contribution1,
4357 $this->assertEquals('Debit Card', CRM_Contribute_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $contribution2['values'][$contribution2['id']]['payment_instrument_id']));
4361 * CRM-20008 Tests repeattransaction creates pending membership.
4363 public function testRepeatTransactionMembershipCreatePendingContribution() {
4364 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
4365 $this->callAPISuccess('membership', 'create', [
4366 'id' => $membership['id'],
4367 'end_date' => 'yesterday',
4368 'status_id' => 'Expired',
4370 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4371 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
4372 'contribution_status_id' => 'Pending',
4373 'trxn_id' => uniqid(),
4375 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
4376 'id' => $membership['id'],
4377 'return' => 'status_id',
4380 // Let's see if the membership payments got created while we're at it.
4381 $membershipPayments = $this->callAPISuccess('MembershipPayment', 'get', [
4382 'membership_id' => $membership['id'],
4384 $this->assertEquals(2, $membershipPayments['count']);
4386 $this->assertEquals('Expired', CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
4387 $this->callAPISuccess('Contribution', 'completetransaction', ['id' => $repeatedContribution['id']]);
4388 $membership = $this->callAPISuccessGetSingle('membership', [
4389 'id' => $membership['id'],
4390 'return' => 'status_id, end_date',
4392 $this->assertEquals('New', CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membership['status_id']));
4393 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 month')), $membership['end_date']);
4397 * Test sending a mail via the API.
4399 * @throws \CRM_Core_Exception
4401 public function testSendMailWithAPISetFromDetails() {
4402 $mut = new CiviMailUtils($this, TRUE);
4403 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
4404 $this->callAPISuccess('contribution', 'sendconfirmation', [
4405 'id' => $contribution['id'],
4406 'receipt_from_email' => 'api@civicrm.org',
4407 'receipt_from_name' => 'CiviCRM LLC',
4409 $mut->checkMailLog([
4410 'From: CiviCRM LLC <api@civicrm.org>',
4411 'Contribution Information',
4419 * Test sending a mail via the API.
4421 public function testSendMailWithNoFromSetFallToDomain() {
4422 $this->createLoggedInUser();
4423 $mut = new CiviMailUtils($this, TRUE);
4424 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
4425 $this->callAPISuccess('contribution', 'sendconfirmation', [
4426 'id' => $contribution['id'],
4428 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4429 $mut->checkMailLog([
4430 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4431 'Contribution Information',
4439 * Test sending a mail via the API.
4441 public function testSendMailWithRepeatTransactionAPIFalltoDomain() {
4442 $this->createLoggedInUser();
4443 $mut = new CiviMailUtils($this, TRUE);
4444 $contribution = $this->setUpRepeatTransaction([], 'single');
4445 $this->callAPISuccess('contribution', 'repeattransaction', [
4446 'contribution_status_id' => 'Completed',
4447 'trxn_id' => uniqid(),
4448 'original_contribution_id' => $contribution,
4450 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4451 $mut->checkMailLog([
4452 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4453 'Contribution Information',
4462 * Test sending a mail via the API.
4464 public function testSendMailWithRepeatTransactionAPIFalltoContributionPage() {
4465 $mut = new CiviMailUtils($this, TRUE);
4466 $contributionPage = $this->contributionPageCreate(['receipt_from_name' => 'CiviCRM LLC', 'receipt_from_email' => 'contributionpage@civicrm.org', 'is_email_receipt' => 1]);
4467 $paymentProcessorID = $this->paymentProcessorCreate();
4468 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
4469 'contact_id' => $this->_individualId
,
4470 'installments' => '12',
4471 'frequency_interval' => '1',
4473 'contribution_status_id' => 1,
4474 'start_date' => '2012-01-01 00:00:00',
4475 'currency' => 'USD',
4476 'frequency_unit' => 'month',
4477 'payment_processor_id' => $paymentProcessorID,
4479 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4482 'contribution_recur_id' => $contributionRecur['id'],
4483 'contribution_page_id' => $contributionPage['id'],
4486 $this->callAPISuccess('contribution', 'repeattransaction', [
4487 'contribution_status_id' => 'Completed',
4488 'trxn_id' => uniqid(),
4489 'original_contribution_id' => $originalContribution,
4492 $mut->checkMailLog([
4493 'From: CiviCRM LLC <contributionpage@civicrm.org>',
4494 'Contribution Information',
4502 * Test sending a mail via the API.
4504 public function testSendMailWithRepeatTransactionAPIFalltoSystemFromNoDefaultFrom() {
4505 $mut = new CiviMailUtils($this, TRUE);
4506 $originalContribution = $contribution = $this->setUpRepeatTransaction([], 'single');
4507 $fromEmail = $this->CallAPISuccess('optionValue', 'get', ['is_default' => 1, 'option_group_id' => 'from_email_address', 'sequential' => 1]);
4508 foreach ($fromEmail['values'] as $from) {
4509 $this->callAPISuccess('optionValue', 'create', ['is_default' => 0, 'id' => $from['id']]);
4511 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => CRM_Core_Config
::domainID()]);
4512 $this->callAPISuccess('contribution', 'repeattransaction', [
4513 'contribution_status_id' => 'Completed',
4514 'trxn_id' => uniqid(),
4515 'original_contribution_id' => $originalContribution,
4517 $mut->checkMailLog([
4518 'From: ' . $domain['name'] . ' <' . $domain['domain_email'] . '>',
4519 'Contribution Information',
4527 * Create a Contribution Page with is_email_receipt = TRUE.
4529 * @param array $params
4530 * Params to overwrite with.
4534 protected function createReceiptableContributionPage($params = []) {
4535 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', array_merge([
4536 'receipt_from_name' => 'Mickey Mouse',
4537 'receipt_from_email' => 'mickey@mouse.com',
4538 'title' => "Test Contribution Page",
4539 'financial_type_id' => 1,
4540 'currency' => 'CAD',
4541 'is_monetary' => TRUE,
4542 'is_email_receipt' => TRUE,
4544 return $contributionPage;
4548 * function to test card_type and pan truncation.
4550 public function testCardTypeAndPanTruncation() {
4551 $creditCardTypeIDs = array_flip(CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'));
4552 $contactId = $this->individualCreate();
4554 'contact_id' => $contactId,
4555 'receive_date' => '2016-01-20',
4556 'total_amount' => 100,
4557 'financial_type_id' => 1,
4558 'payment_instrument' => 'Credit Card',
4559 'card_type_id' => $creditCardTypeIDs['Visa'],
4560 'pan_truncation' => 4567,
4562 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4563 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contribution['id'], 'DESC');
4564 $financialTrxn = $this->callAPISuccessGetSingle(
4567 'id' => $lastFinancialTrxnId['financialTrxnId'],
4568 'return' => ['card_type_id', 'pan_truncation'],
4571 $this->assertEquals(CRM_Utils_Array
::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Visa']);
4572 $this->assertEquals(CRM_Utils_Array
::value('pan_truncation', $financialTrxn), 4567);
4574 'id' => $contribution['id'],
4575 'pan_truncation' => 2345,
4576 'card_type_id' => $creditCardTypeIDs['Amex'],
4578 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4579 $financialTrxn = $this->callAPISuccessGetSingle(
4582 'id' => $lastFinancialTrxnId['financialTrxnId'],
4583 'return' => ['card_type_id', 'pan_truncation'],
4586 $this->assertEquals(CRM_Utils_Array
::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Amex']);
4587 $this->assertEquals(CRM_Utils_Array
::value('pan_truncation', $financialTrxn), 2345);
4591 * Test repeat contribution uses non default currency
4592 * @see https://issues.civicrm.org/jira/projects/CRM/issues/CRM-20678
4594 public function testRepeatTransactionWithDifferenceCurrency() {
4595 $originalContribution = $this->setUpRepeatTransaction(['currency' => 'AUD'], 'single', ['currency' => 'AUD']);
4596 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4597 'original_contribution_id' => $originalContribution['id'],
4598 'contribution_status_id' => 'Completed',
4599 'trxn_id' => uniqid(),
4601 $this->assertEquals('AUD', $contribution['values'][$contribution['id']]['currency']);
4605 * Get the financial items for the contribution.
4607 * @param int $contributionID
4610 * Array of associated financial items.
4612 protected function getFinancialTransactionsForContribution($contributionID) {
4614 'entity_id' => $contributionID,
4615 'entity_table' => 'civicrm_contribution',
4617 // @todo the following function has naming errors & has a weird signature & appears to
4618 // only be called from test classes. Move into test suite & maybe just use api
4619 // from this function.
4620 return array_merge(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($trxnParams));
4624 * Test getunique api call for Contribution entity
4626 public function testContributionGetUnique() {
4627 $result = $this->callAPIAndDocument($this->entity
, 'getunique', [], __FUNCTION__
, __FILE__
);
4628 $this->assertEquals(2, $result['count']);
4629 $this->assertEquals(['trxn_id'], $result['values']['UI_contrib_trxn_id']);
4630 $this->assertEquals(['invoice_id'], $result['values']['UI_contrib_invoice_id']);
4634 * Test Repeat Transaction Contribution with Tax amount.
4635 * https://lab.civicrm.org/dev/core/issues/806
4637 public function testRepeatContributionWithTaxAmount() {
4638 $this->enableTaxAndInvoicing();
4639 $financialType = $this->callAPISuccess('financial_type', 'create', [
4640 'name' => 'Test taxable financial Type',
4644 $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
4645 $contribution = $this->setUpRepeatTransaction(
4649 'financial_type_id' => $financialType['id'],
4652 $this->callAPISuccess('contribution', 'repeattransaction', [
4653 'original_contribution_id' => $contribution['id'],
4654 'contribution_status_id' => 'Completed',
4655 'trxn_id' => uniqid(),
4657 $payments = $this->callAPISuccess('Contribution', 'get', ['sequential' => 1])['values'];
4658 //Assert if first payment and repeated payment has the same contribution amount.
4659 $this->assertEquals($payments[0]['total_amount'], $payments[1]['total_amount']);
4660 $this->callAPISuccessGetCount('Contribution', [], 2);
4662 //Assert line item records.
4663 $lineItems = $this->callAPISuccess('LineItem', 'get', ['sequential' => 1])['values'];
4664 foreach ($lineItems as $lineItem) {
4665 $this->assertEquals($lineItem['unit_price'], $this->_params
['total_amount']);
4666 $this->assertEquals($lineItem['line_total'], $this->_params
['total_amount']);
4668 $this->callAPISuccessGetCount('Contribution', [], 2);
4671 public function testGetCurrencyOptions() {
4672 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4673 'field' => 'currency',
4675 $this->assertEquals('US Dollar', $result['values']['USD']);
4676 $this->assertNotContains('$', $result['values']);
4677 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4678 'field' => 'currency',
4679 'context' => "abbreviate",
4681 $this->assertEquals('$', $result['values']['USD']);
4682 $this->assertNotContains('US Dollar', $result['values']);
4686 * @throws \API_Exception
4687 * @throws \CRM_Core_Exception
4688 * @throws \Civi\API\Exception\UnauthorizedException
4690 public function testSetCustomDataInCreateAndHook() {
4691 $this->createCustomGroupWithFieldOfType([], 'int');
4692 $this->ids
['CustomField']['text'] = (int) $this->createTextCustomField(['custom_group_id' => $this->ids
['CustomGroup']['Custom Group']])['id'];
4693 $this->hookClass
->setHook('civicrm_post', [
4695 'civicrmPostContributionCustom',
4697 $params = $this->_params
;
4698 $params['custom_' . $this->ids
['CustomField']['text']] = 'Some Text';
4699 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
4700 $getContribution = $this->callAPISuccess('Contribution', 'get', [
4701 'id' => $contribution['id'],
4702 'return' => ['id', 'custom_' . $this->ids
['CustomField']['text'], 'custom_' . $this->ids
['CustomField']['int']],
4704 $this->assertEquals(5, $getContribution['values'][$contribution['id']][$this->getCustomFieldName('int')]);
4705 $this->assertEquals('Some Text', $getContribution['values'][$contribution['id']]['custom_' . $this->ids
['CustomField']['text']]);
4706 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids
['CustomField']['text']]);
4707 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids
['CustomField']['int']]);
4708 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $this->ids
['CustomGroup']['Custom Group']]);
4712 * Implement post hook.
4715 * @param string $objectName
4716 * @param int $objectId
4717 * @param \CRM_Core_DAO $objectRef
4719 * @throws \CRM_Core_Exception
4721 public function civicrmPostContributionCustom($op, $objectName, $objectId, &$objectRef) {
4722 if ($objectName === 'Contribution' && $op === 'create') {
4723 $this->callAPISuccess('Contribution', 'create', [
4725 'custom_' . $this->ids
['CustomField']['int'] => 5,
4731 * Test that passing in label for an option value linked to a custom field works
4732 * @see dev/core#1816
4734 public function testCustomValueOptionLabelTest() {
4735 $this->createCustomGroupWithFieldOfType([], 'radio');
4736 $params = $this->_params
;
4737 $params['custom_' . $this->ids
['CustomField']['radio']] = 'Red Testing';
4738 $contribution = $this->callAPISuccess('Contribution', 'Create', $params);
4742 * Test repeatTransaction with installments and next_sched_contribution_date
4744 * @dataProvider getRepeatTransactionNextSchedData
4746 * @param array $dataSet
4748 * @throws \Exception
4750 public function testRepeatTransactionUpdateNextSchedContributionDate($dataSet) {
4751 $paymentProcessorID = $this->paymentProcessorCreate();
4752 // Create the contribution before the recur so it doesn't trigger the update of next_sched_contribution_date
4753 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
4756 'contribution_status_id' => 'Completed',
4757 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4760 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4761 'contact_id' => $this->_individualId
,
4762 'frequency_interval' => '1',
4764 'contribution_status_id' => 'Pending',
4765 'start_date' => '2012-01-01 00:00:00',
4766 'currency' => 'USD',
4767 'frequency_unit' => 'month',
4768 'payment_processor_id' => $paymentProcessorID,
4769 ], $dataSet['recur']));
4770 // Link the existing contribution to the recur *after* creating the recur.
4771 // If we just created the contribution now the next_sched_contribution_date would be automatically set
4772 // and we want to test the case when it is empty.
4773 $this->callAPISuccess('contribution', 'create', [
4774 'id' => $contribution['id'],
4775 'contribution_recur_id' => $contributionRecur['id'],
4778 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4779 'id' => $contributionRecur['id'],
4780 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4782 // Check that next_sched_contribution_date is empty
4783 $this->assertEquals('', $contributionRecur['next_sched_contribution_date'] ??
'');
4785 $this->callAPISuccess('Contribution', 'repeattransaction', [
4786 'contribution_status_id' => 'Completed',
4787 'contribution_recur_id' => $contributionRecur['id'],
4788 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4790 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4791 'id' => $contributionRecur['id'],
4792 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4794 // Check that recur has status "In Progress"
4795 $this->assertEquals(
4796 (string) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][0]['expectedRecurStatus']),
4797 $contributionRecur['contribution_status_id']
4799 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4800 $this->assertEquals($dataSet['repeat'][0]['expectedNextSched'], $contributionRecur['next_sched_contribution_date']);
4802 // Now call Contribution.repeattransaction again and check that the next_sched_contribution_date has moved forward by 1 period again
4803 $this->callAPISuccess('Contribution', 'repeattransaction', [
4804 'contribution_status_id' => 'Completed',
4805 'contribution_recur_id' => $contributionRecur['id'],
4806 'receive_date' => $dataSet['repeat'][1]['receive_date'],
4808 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4809 'id' => $contributionRecur['id'],
4810 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4812 // Check that recur has status "In Progress" or "Completed" depending on whether number of installments has been reached
4813 $this->assertEquals(
4814 (string) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][1]['expectedRecurStatus']),
4815 $contributionRecur['contribution_status_id']
4817 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4818 $this->assertEquals($dataSet['repeat'][1]['expectedNextSched'], $contributionRecur['next_sched_contribution_date'] ??
'');
4822 * Get dates for testing.
4826 public function getRepeatTransactionNextSchedData() {
4827 // Both these tests handle/test the case that next_sched_contribution_date is empty when Contribution.repeattransaction
4828 // is called for the first time. Historically setting it was inconsistent but on new updates it should always be set.
4830 * This tests that calling Contribution.repeattransaction with installments does the following:
4831 * - For the first call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4832 * to match next expected receive_date.
4833 * - Once the 3rd contribution is created contributionRecur status = completed and next_sched_contribution_date = ''.
4835 $result['receive_date_includes_time_with_installments']['2012-01-01-1-month'] = [
4837 'start_date' => '2012-01-01',
4838 'frequency_interval' => 1,
4839 'installments' => '3',
4840 'frequency_unit' => 'month',
4844 'receive_date' => '2012-02-29 16:00:00',
4845 'expectedNextSched' => '2012-03-29 00:00:00',
4846 'expectedRecurStatus' => 'In Progress',
4849 'receive_date' => '2012-03-29 16:00:00',
4850 'expectedNextSched' => '',
4851 'expectedRecurStatus' => 'Completed',
4856 * This tests that calling Contribution.repeattransaction with no installments does the following:
4857 * - For the each call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4858 * to match next expected receive_date.
4860 $result['receive_date_includes_time_no_installments']['2012-01-01-1-month'] = [
4862 'start_date' => '2012-01-01',
4863 'frequency_interval' => 1,
4864 'frequency_unit' => 'month',
4868 'receive_date' => '2012-02-29 16:00:00',
4869 'expectedNextSched' => '2012-03-29 00:00:00',
4870 'expectedRecurStatus' => 'In Progress',
4873 'receive_date' => '2012-03-29 16:00:00',
4874 'expectedNextSched' => '2012-04-29 00:00:00',
4875 'expectedRecurStatus' => 'In Progress',
4883 * Make sure that recording a payment doesn't alter the receive_date of a
4884 * pending contribution.
4886 public function testPaymentDontChangeReceiveDate() {
4888 'contact_id' => $this->_individualId
,
4889 'total_amount' => 100,
4890 'receive_date' => '2020-02-02',
4891 'contribution_status_id' => 'Pending',
4893 $contributionID = $this->contributionCreate($params);
4895 'contribution_id' => $contributionID,
4896 'total_amount' => 100,
4897 'trxn_date' => '2020-03-04',
4899 $this->callAPISuccess('payment', 'create', $paymentParams);
4901 //check if contribution status is set to "Completed".
4902 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
4903 'id' => $contributionID,
4905 $this->assertEquals('2020-02-02 00:00:00', $contribution['receive_date']);
4909 * Make sure that recording a payment with Different Payment Instrument update main contribution record payment
4910 * instrument too. If multiple Payment Recorded, last payment record payment (when No more due) instrument set to main
4913 public function testPaymentVerifyPaymentInstrumentChange() {
4914 // Create Pending contribution with pay later mode, with payment instrument Check
4916 'contact_id' => $this->_individualId
,
4917 'total_amount' => 100,
4918 'receive_date' => '2020-02-02',
4919 'contribution_status_id' => 'Pending',
4920 'is_pay_later' => 1,
4921 'payment_instrument_id' => 'Check',
4923 $contributionID = $this->contributionCreate($params);
4925 // Record the the Payment with instrument other than Check, e.g EFT
4927 'contribution_id' => $contributionID,
4928 'total_amount' => 50,
4929 'trxn_date' => '2020-03-04',
4930 'payment_instrument_id' => 'EFT',
4932 $this->callAPISuccess('payment', 'create', $paymentParams);
4934 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
4935 'id' => $contributionID,
4937 // payment status should be 'Partially paid'
4938 $this->assertEquals('Partially paid', $contribution['contribution_status']);
4940 // Record the the Payment with instrument other than Check, e.g Cash (pay all remaining amount)
4942 'contribution_id' => $contributionID,
4943 'total_amount' => 50,
4944 'trxn_date' => '2020-03-04',
4945 'payment_instrument_id' => 'Cash',
4947 $this->callAPISuccess('payment', 'create', $paymentParams);
4949 //check if contribution Payment Instrument (Payment Method) is is set to "Cash".
4950 $contribution = $this->callAPISuccess('Contribution', 'getSingle', [
4951 'id' => $contributionID,
4953 $this->assertEquals('Cash', $contribution['payment_instrument']);
4954 $this->assertEquals('Completed', $contribution['contribution_status']);
4958 * Test the "clean money" functionality.
4960 public function testCleanMoney() {
4962 'contact_id' => $this->_individualId
,
4963 'financial_type_id' => 1,
4964 'total_amount' => '$100',
4965 'fee_amount' => '$20',
4966 'net_amount' => '$80',
4967 'non_deductible_amount' => '$80',
4970 $id = $this->callAPISuccess('Contribution', 'create', $params)['id'];
4971 // Reading the return values of the API isn't reliable here; get the data from the db.
4972 $contribution = $this->callAPISuccess('Contribution', 'getsingle', ['id' => $id]);
4973 $this->assertEquals('100.00', $contribution['total_amount']);
4974 $this->assertEquals('20.00', $contribution['fee_amount']);
4975 $this->assertEquals('80.00', $contribution['net_amount']);
4976 $this->assertEquals('80.00', $contribution['non_deductible_amount']);