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 +--------------------------------------------------------------------+
13 * Test APIv3 civicrm_contribute_* functions
15 * @package CiviCRM_APIv3
16 * @subpackage API_Contribution
19 class api_v3_ContributionTest
extends CiviUnitTestCase
{
21 use CRMTraits_Profile_ProfileTrait
;
22 use CRMTraits_Custom_CustomDataTrait
;
24 protected $_individualId;
25 protected $_contribution;
26 protected $_financialTypeId = 1;
27 protected $entity = 'Contribution';
30 protected $_pageParams = [];
32 * Payment processor ID (dummy processor).
36 protected $paymentProcessorID;
39 * Parameters to create payment processor.
43 protected $_processorParams = [];
46 * ID of created event.
60 * @throws \CRM_Core_Exception
62 public function setUp() {
65 $this->_apiversion
= 3;
66 $this->_individualId
= $this->individualCreate();
68 'contact_id' => $this->_individualId
,
69 'receive_date' => '20120511',
70 'total_amount' => 100.00,
71 'financial_type_id' => $this->_financialTypeId
,
72 'non_deductible_amount' => 10.00,
74 'net_amount' => 95.00,
76 'contribution_status_id' => 1,
78 $this->_processorParams
= [
81 'payment_processor_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', 'Dummy'),
82 'financial_account_id' => 12,
85 'url_site' => 'http://dummy.com',
86 'url_recur' => 'http://dummy.com',
89 $this->paymentProcessorID
= $this->processorCreate();
90 $this->_pageParams
= [
91 'title' => 'Test Contribution Page',
92 'financial_type_id' => 1,
94 'financial_account_id' => 1,
95 'payment_processor' => $this->paymentProcessorID
,
97 'is_allow_other_amount' => 1,
104 * Clean up after each test.
106 * @throws \CRM_Core_Exception
108 public function tearDown() {
109 $this->quickCleanUpFinancialEntities();
110 $this->quickCleanup(['civicrm_uf_match']);
111 $financialAccounts = $this->callAPISuccess('FinancialAccount', 'get', []);
112 foreach ($financialAccounts['values'] as $financialAccount) {
113 if ($financialAccount['name'] === 'Test Tax financial account ' ||
$financialAccount['name'] === 'Test taxable financial Type') {
114 $entityFinancialTypes = $this->callAPISuccess('EntityFinancialAccount', 'get', [
115 'financial_account_id' => $financialAccount['id'],
117 foreach ($entityFinancialTypes['values'] as $entityFinancialType) {
118 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialType['id']]);
120 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
123 $this->restoreUFGroupOne();
129 * @throws \CRM_Core_Exception
131 public function testGetContribution() {
132 $this->enableTaxAndInvoicing();
134 'contact_id' => $this->_individualId
,
135 'receive_date' => '2010-01-20',
136 'total_amount' => 100.00,
137 'financial_type_id' => $this->_financialTypeId
,
138 'non_deductible_amount' => 10.00,
139 'fee_amount' => 5.00,
140 'net_amount' => 95.00,
142 'invoice_id' => 78910,
144 'contribution_status_id' => 'Completed',
146 $this->_contribution
= $this->callAPISuccess('contribution', 'create', $p);
149 'contribution_id' => $this->_contribution
['id'],
152 $contributions = $this->callAPIAndDocument('contribution', 'get', $params, __FUNCTION__
, __FILE__
);
153 $financialParams['id'] = $this->_financialTypeId
;
155 CRM_Financial_BAO_FinancialType
::retrieve($financialParams, $default);
157 $this->assertEquals(1, $contributions['count']);
158 $contribution = $contributions['values'][$contributions['id']];
159 $this->assertEquals($contribution['contact_id'], $this->_individualId
);
160 // Note there was an assertion converting financial_type_id to 'Donation' which wasn't working.
161 // Passing back a string rather than an id seems like an error/cruft.
162 // If it is to be introduced we should discuss.
163 $this->assertEquals($contribution['financial_type_id'], 1);
164 $this->assertEquals($contribution['total_amount'], 100.00);
165 $this->assertEquals($contribution['non_deductible_amount'], 10.00);
166 $this->assertEquals($contribution['fee_amount'], 5.00);
167 $this->assertEquals($contribution['net_amount'], 95.00);
168 $this->assertEquals($contribution['trxn_id'], 23456);
169 $this->assertEquals($contribution['invoice_id'], 78910);
170 $this->assertEquals($contribution['invoice_number'], 'INV_' . $contributions['id']);
171 $this->assertEquals($contribution['contribution_source'], 'SSF');
172 $this->assertEquals($contribution['contribution_status'], 'Completed');
173 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
174 $p['trxn_id'] = '3847';
175 $p['invoice_id'] = '3847';
177 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
179 // Now we have 2 - test getcount.
180 $contribution = $this->callAPISuccess('contribution', 'getcount', []);
181 $this->assertEquals(2, $contribution);
182 // Test id only format.
183 $contribution = $this->callAPISuccess('contribution', 'get', [
184 'id' => $this->_contribution
['id'],
185 'format.only_id' => 1,
187 $this->assertEquals($this->_contribution
['id'], $contribution, print_r($contribution, TRUE));
188 // Test id only format.
189 $contribution = $this->callAPISuccess('contribution', 'get', [
190 'id' => $contribution2['id'],
191 'format.only_id' => 1,
193 $this->assertEquals($contribution2['id'], $contribution);
195 $contribution = $this->callAPISuccess('contribution', 'get', [
196 'id' => $this->_contribution
['id'],
198 $this->assertEquals(1, $contribution['count']);
200 // Test get by contact id works.
201 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId
]);
203 $this->assertEquals(2, $contribution['count']);
204 $this->callAPISuccess('Contribution', 'Delete', [
205 'id' => $this->_contribution
['id'],
207 $this->callAPISuccess('Contribution', 'Delete', [
208 'id' => $contribution2['id'],
213 * Test that test contributions can be retrieved.
215 * @throws \CRM_Core_Exception
217 public function testGetTestContribution() {
218 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['is_test' => 1]));
219 $this->callAPISuccessGetSingle('Contribution', ['is_test' => 1]);
223 * Test Creating a check contribution with original check_number field
225 public function testCreateCheckContribution() {
226 $params = $this->_params
;
227 $params['contribution_check_number'] = 'bouncer';
228 $params['payment_instrument_id'] = 'Check';
229 $params['cancel_date'] = 'yesterday';
230 $params['receipt_date'] = 'yesterday';
231 $params['thankyou_date'] = 'yesterday';
232 $params['revenue_recognition_date'] = 'yesterday';
233 $params['amount_level'] = 'Unreasonable';
234 $params['cancel_reason'] = 'You lose sucker';
235 $params['creditnote_id'] = 'sudo rm -rf';
236 $params['tax_amount'] = '1';
237 $address = $this->callAPISuccess('Address', 'create', [
238 'street_address' => 'Knockturn Alley',
239 'contact_id' => $this->_individualId
,
240 'location_type_id' => 'Home',
242 $params['address_id'] = $address['id'];
243 $contributionPage = $this->contributionPageCreate();
244 $params['contribution_page_id'] = $contributionPage['id'];
245 $params['campaign_id'] = $this->campaignCreate();
246 $contributionID = $this->contributionCreate($params);
247 $getResult = $this->callAPISuccess('Contribution', 'get', ['id' => $contributionID]);
248 $this->assertEquals('bouncer', $getResult['values'][$contributionID]['check_number']);
249 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'get', ['entity_id' => $contributionID, 'entity_table' => 'civicrm_contribution']);
250 foreach ($entityFinancialTrxn['values'] as $eft) {
251 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'get', ['id' => $eft['financial_trxn_id']]);
252 $this->assertEquals('bouncer', $financialTrxn['values'][$financialTrxn['id']]['check_number']);
257 * Test the 'return' param works for all fields.
259 * @throws \CRM_Core_Exception
261 public function testGetContributionReturnFunctionality() {
262 $params = $this->_params
;
263 $params['contribution_check_number'] = 'bouncer';
264 $params['payment_instrument_id'] = 'Check';
265 $params['cancel_date'] = 'yesterday';
266 $params['receipt_date'] = 'yesterday';
267 $params['thankyou_date'] = 'yesterday';
268 $params['revenue_recognition_date'] = 'yesterday';
269 $params['amount_level'] = 'Unreasonable';
270 $params['cancel_reason'] = 'You lose sucker';
271 $params['creditnote_id'] = 'sudo rm -rf';
272 $params['tax_amount'] = '1';
273 $address = $this->callAPISuccess('Address', 'create', [
274 'street_address' => 'Knockturn Alley',
275 'contact_id' => $this->_individualId
,
276 'location_type_id' => 'Home',
278 $params['address_id'] = $address['id'];
279 $contributionPage = $this->contributionPageCreate();
280 $params['contribution_page_id'] = $contributionPage['id'];
281 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
282 'contact_id' => $this->_individualId
,
283 'frequency_interval' => 1,
286 $params['contribution_recur_id'] = $contributionRecur['id'];
288 $params['campaign_id'] = $this->campaignCreate();
290 $contributionID = $this->contributionCreate($params);
292 // update contribution with invoice number
293 $params = array_merge($params, [
294 'id' => $contributionID,
295 'invoice_number' => CRM_Utils_Array
::value('invoice_prefix', Civi
::settings()->get('contribution_invoice_settings')) . "" . $contributionID,
297 'invoice_id' => 6789,
299 $contributionID = $this->contributionCreate($params);
301 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID]);
302 $this->assertEquals('bouncer', $contribution['check_number']);
303 $this->assertEquals('bouncer', $contribution['contribution_check_number']);
305 $fields = CRM_Contribute_BAO_Contribution
::fields();
306 // Re-add these 2 to the fields to check. They were locked in but the metadata changed so we
307 // need to specify them.
308 $fields['address_id'] = $fields['contribution_address_id'];
309 $fields['check_number'] = $fields['contribution_check_number'];
312 'contribution_id', 'contribution_contact_id', 'financial_type_id', 'contribution_page_id',
313 'payment_instrument_id', 'receive_date', 'non_deductible_amount', 'total_amount',
314 'fee_amount', 'net_amount', 'trxn_id', 'invoice_id', 'currency', 'contribution_cancel_date', 'cancel_reason',
315 'receipt_date', 'thankyou_date', 'contribution_source', 'amount_level', 'contribution_recur_id',
316 'is_test', 'is_pay_later', 'contribution_status_id', 'address_id', 'check_number', 'contribution_campaign_id',
317 'creditnote_id', 'tax_amount', 'revenue_recognition_date', 'decoy',
319 $missingFields = array_diff($fieldsLockedIn, array_keys($fields));
320 // If any of the locked in fields disappear from the $fields array we need to make sure it is still
321 // covered as the test contract now guarantees them in the return array.
322 $this->assertEquals($missingFields, [29 => 'decoy'], 'A field which was covered by the test contract has changed.');
323 foreach ($fields as $fieldName => $fieldSpec) {
324 $contribution = $this->callAPISuccessGetSingle('Contribution', ['id' => $contributionID, 'return' => $fieldName]);
325 $returnField = $fieldName;
326 if ($returnField == 'contribution_contact_id') {
327 $returnField = 'contact_id';
329 $this->assertTrue((!empty($contribution[$returnField]) ||
$contribution[$returnField] === "0"), $returnField);
331 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'get', ['entity_id' => $contributionID, 'entity_table' => 'civicrm_contribution']);
332 foreach ($entityFinancialTrxn['values'] as $eft) {
333 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'get', ['id' => $eft['financial_trxn_id']]);
334 $this->assertEquals('bouncer', $financialTrxn['values'][$financialTrxn['id']]['check_number']);
339 * Test cancel reason works as a filter.
341 public function testFilterCancelReason() {
342 $params = $this->_params
;
343 $params['cancel_date'] = 'yesterday';
344 $params['cancel_reason'] = 'You lose sucker';
345 $this->callAPISuccess('Contribution', 'create', $params);
346 $params = $this->_params
;
347 $params['cancel_date'] = 'yesterday';
348 $params['cancel_reason'] = 'You are a winner';
349 $this->callAPISuccess('Contribution', 'create', $params);
350 $this->callAPISuccessGetCount('Contribution', ['cancel_reason' => 'You are a winner'], 1);
354 * We need to ensure previous tested behaviour still works as part of the api contract.
356 public function testGetContributionLegacyBehaviour() {
358 'contact_id' => $this->_individualId
,
359 'receive_date' => '2010-01-20',
360 'total_amount' => 100.00,
361 'contribution_type_id' => $this->_financialTypeId
,
362 'non_deductible_amount' => 10.00,
363 'fee_amount' => 5.00,
364 'net_amount' => 95.00,
366 'invoice_id' => 78910,
368 'contribution_status_id' => 1,
370 $this->_contribution
= $this->callAPISuccess('Contribution', 'create', $p);
373 'contribution_id' => $this->_contribution
['id'],
375 $contribution = $this->callAPISuccess('contribution', 'get', $params);
376 $financialParams['id'] = $this->_financialTypeId
;
378 CRM_Financial_BAO_FinancialType
::retrieve($financialParams, $default);
380 $this->assertEquals(1, $contribution['count']);
381 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
382 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], $this->_financialTypeId
);
383 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_type_id'], $this->_financialTypeId
);
384 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
385 $this->assertEquals($contribution['values'][$contribution['id']]['non_deductible_amount'], 10.00);
386 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 5.00);
387 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 95.00);
388 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 23456);
389 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 78910);
390 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_source'], 'SSF');
391 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Completed');
393 // Create a second contribution - we are testing that 'id' gets the right contribution id (not the contact id).
394 $p['trxn_id'] = '3847';
395 $p['invoice_id'] = '3847';
397 $contribution2 = $this->callAPISuccess('contribution', 'create', $p);
399 // now we have 2 - test getcount
400 $contribution = $this->callAPISuccess('contribution', 'getcount', []);
401 $this->assertEquals(2, $contribution);
402 //test id only format
403 $contribution = $this->callAPISuccess('contribution', 'get', [
404 'id' => $this->_contribution
['id'],
405 'format.only_id' => 1,
407 $this->assertEquals($this->_contribution
['id'], $contribution, print_r($contribution, TRUE));
408 //test id only format
409 $contribution = $this->callAPISuccess('contribution', 'get', [
410 'id' => $contribution2['id'],
411 'format.only_id' => 1,
413 $this->assertEquals($contribution2['id'], $contribution);
414 $contribution = $this->callAPISuccess('contribution', 'get', [
415 'id' => $this->_contribution
['id'],
418 $this->assertEquals(1, $contribution['count']);
419 // $this->assertEquals($this->_contribution['id'], $contribution['id'] ) ;
420 //test get by contact id works
421 $contribution = $this->callAPISuccess('contribution', 'get', ['contact_id' => $this->_individualId
]);
423 $this->assertEquals(2, $contribution['count']);
424 $this->callAPISuccess('Contribution', 'Delete', [
425 'id' => $this->_contribution
['id'],
427 $this->callAPISuccess('Contribution', 'Delete', [
428 'id' => $contribution2['id'],
433 * Create an contribution_id=FALSE and financial_type_id=Donation.
435 public function testCreateEmptyContributionIDUseDonation() {
437 'contribution_id' => FALSE,
440 'check_permissions' => FALSE,
441 'financial_type_id' => 'Donation',
443 $this->callAPISuccess('contribution', 'create', $params);
447 * Check with complete array + custom field.
449 * Note that the test is written on purpose without any
450 * variables specific to participant so it can be replicated into other entities
451 * and / or moved to the automated test suite
453 * @throws \CRM_Core_Exception
455 public function testCreateWithCustom() {
456 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, __FILE__
);
458 $params = $this->_params
;
459 $params['custom_' . $ids['custom_field_id']] = "custom string";
461 $result = $this->callAPIAndDocument($this->entity
, 'create', $params, __FUNCTION__
, __FILE__
);
462 $this->assertEquals($result['id'], $result['values'][$result['id']]['id']);
463 $check = $this->callAPISuccess($this->entity
, 'get', [
464 'return.custom_' . $ids['custom_field_id'] => 1,
465 'id' => $result['id'],
467 $group = $this->callAPISuccess('CustomGroup', 'getsingle', ['id' => $ids['custom_group_id']]);
468 $field = $this->callAPISuccess('CustomField', 'getsingle', ['id' => $ids['custom_field_id']]);
469 $contribution = \Civi\Api4\Contribution
::get()
473 $group['name'] . '.' . $field['name'],
475 ->addWhere('id', '=', $result['id'])
478 $this->customFieldDelete($ids['custom_field_id']);
479 $this->customGroupDelete($ids['custom_group_id']);
480 $this->assertEquals('custom string', $check['values'][$check['id']]['custom_' . $ids['custom_field_id']]);
484 * Check with complete array + custom field.
486 * Note that the test is written on purpose without any
487 * variables specific to participant so it can be replicated into other entities
488 * and / or moved to the automated test suite
490 public function testCreateGetFieldsWithCustom() {
491 $ids = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, __FILE__
);
492 $idsContact = $this->entityCustomGroupWithSingleFieldCreate(__FUNCTION__
, 'ContactTest.php');
493 $result = $this->callAPISuccess('Contribution', 'getfields', []);
494 $this->assertArrayHasKey('custom_' . $ids['custom_field_id'], $result['values']);
495 $this->assertArrayNotHasKey('custom_' . $idsContact['custom_field_id'], $result['values']);
496 $this->customFieldDelete($ids['custom_field_id']);
497 $this->customGroupDelete($ids['custom_group_id']);
498 $this->customFieldDelete($idsContact['custom_field_id']);
499 $this->customGroupDelete($idsContact['custom_group_id']);
502 public function testCreateContributionNoLineItems() {
505 'contact_id' => $this->_individualId
,
506 'receive_date' => '20120511',
507 'total_amount' => 100.00,
508 'financial_type_id' => $this->_financialTypeId
,
509 'payment_instrument_id' => 1,
510 'non_deductible_amount' => 10.00,
511 'fee_amount' => 50.00,
512 'net_amount' => 90.00,
514 'invoice_id' => 67890,
516 'contribution_status_id' => 1,
520 $contribution = $this->callAPISuccess('contribution', 'create', $params);
521 $financialItems = $this->callAPISuccess('FinancialItem', 'get', []);
522 foreach ($financialItems['values'] as $financialItem) {
523 $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'])));
525 $lineItems = $this->callAPISuccess('line_item', 'get', [
526 'entity_id' => $contribution['id'],
527 'entity_table' => 'civicrm_contribution',
530 $this->assertEquals(0, $lineItems['count']);
534 * Test checks that passing in line items suppresses the create mechanism.
536 public function testCreateContributionChainedLineItems() {
538 'contact_id' => $this->_individualId
,
539 'receive_date' => '20120511',
540 'total_amount' => 100.00,
541 'financial_type_id' => $this->_financialTypeId
,
542 'payment_instrument_id' => 1,
543 'non_deductible_amount' => 10.00,
544 'fee_amount' => 50.00,
545 'net_amount' => 90.00,
547 'invoice_id' => 67890,
549 'contribution_status_id' => 1,
551 'api.line_item.create' => [
553 'price_field_id' => 1,
555 'line_total' => '20',
556 'unit_price' => '10',
559 'price_field_id' => 1,
561 'line_total' => '80',
562 'unit_price' => '80',
567 $description = "Create Contribution with Nested Line Items.";
568 $subfile = "CreateWithNestedLineItems";
569 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
571 $lineItems = $this->callAPISuccess('line_item', 'get', [
572 'entity_id' => $contribution['id'],
573 'contribution_id' => $contribution['id'],
574 'entity_table' => 'civicrm_contribution',
577 $this->assertEquals(2, $lineItems['count']);
580 public function testCreateContributionOffline() {
582 'contact_id' => $this->_individualId
,
583 'receive_date' => '20120511',
584 'total_amount' => 100.00,
585 'financial_type_id' => 1,
587 'invoice_id' => 67890,
589 'contribution_status_id' => 1,
592 $contribution = $this->callAPISuccess('contribution', 'create', $params);
593 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
594 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
595 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
596 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
597 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
598 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
599 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
600 $lineItems = $this->callAPISuccess('line_item', 'get', [
601 'entity_id' => $contribution['id'],
602 'contribution_id' => $contribution['id'],
603 'entity_table' => 'civicrm_contribution',
606 $this->assertEquals(1, $lineItems['count']);
607 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
608 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
609 $this->_checkFinancialRecords($contribution, 'offline');
610 $this->contributionGetnCheck($params, $contribution['id']);
614 * Test create with valid payment instrument.
616 public function testCreateContributionWithPaymentInstrument() {
617 $params = $this->_params +
['payment_instrument' => 'EFT'];
618 $contribution = $this->callAPISuccess('contribution', 'create', $params);
619 $contribution = $this->callAPISuccess('contribution', 'get', [
621 'id' => $contribution['id'],
623 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
624 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
626 $this->callAPISuccess('contribution', 'create', [
627 'id' => $contribution['id'],
628 'payment_instrument' => 'Credit Card',
630 $contribution = $this->callAPISuccess('contribution', 'get', [
632 'id' => $contribution['id'],
634 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
635 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
638 public function testGetContributionByPaymentInstrument() {
639 $params = $this->_params +
['payment_instrument' => 'EFT'];
640 $params2 = $this->_params +
['payment_instrument' => 'Cash'];
641 $this->callAPISuccess('contribution', 'create', $params);
642 $this->callAPISuccess('contribution', 'create', $params2);
643 $contribution = $this->callAPISuccess('contribution', 'get', [
645 'contribution_payment_instrument' => 'Cash',
647 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
648 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
649 $this->assertEquals(1, $contribution['count']);
650 $contribution = $this->callAPISuccess('contribution', 'get', ['sequential' => 1, 'payment_instrument' => 'Cash']);
651 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
652 $this->assertEquals('Cash', $contribution['values'][0]['payment_instrument']);
653 $this->assertEquals(1, $contribution['count']);
654 $contribution = $this->callAPISuccess('contribution', 'get', [
656 'payment_instrument_id' => 5,
658 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
659 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
660 $this->assertEquals(1, $contribution['count']);
661 $contribution = $this->callAPISuccess('contribution', 'get', [
663 'payment_instrument' => 'EFT',
665 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
666 $this->assertEquals('EFT', $contribution['values'][0]['payment_instrument']);
667 $this->assertEquals(1, $contribution['count']);
668 $contribution = $this->callAPISuccess('contribution', 'create', [
669 'id' => $contribution['id'],
670 'payment_instrument' => 'Credit Card',
672 $contribution = $this->callAPISuccess('contribution', 'get', ['sequential' => 1, 'id' => $contribution['id']]);
673 $this->assertArrayHasKey('payment_instrument', $contribution['values'][0]);
674 $this->assertEquals('Credit Card', $contribution['values'][0]['payment_instrument']);
675 $this->assertEquals(1, $contribution['count']);
679 * CRM-16227 introduces invoice_id as a parameter.
681 public function testGetContributionByInvoice() {
682 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['invoice_id' => 'curly']));
683 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
), ['invoice_id' => 'churlish']);
684 $this->callAPISuccessGetCount('Contribution', [], 2);
685 $this->callAPISuccessGetSingle('Contribution', ['invoice_id' => 'curly']);
686 // The following don't work. They are the format we are trying to introduce but although the form uses this format
687 // CRM_Contact_BAO_Query::convertFormValues puts them into the other format & the where only supports that.
688 // ideally the where clause would support this format (as it does on contact_BAO_Query) and those lines would
689 // come out of convertFormValues
690 // $this->callAPISuccessGetSingle('Contribution', array('invoice_id' => array('LIKE' => '%ish%')));
691 // $this->callAPISuccessGetSingle('Contribution', array('invoice_id' => array('NOT IN' => array('curly'))));
692 // $this->callAPISuccessGetCount('Contribution', array('invoice_id' => array('LIKE' => '%ly%')), 2);
693 // $this->callAPISuccessGetCount('Contribution', array('invoice_id' => array('IN' => array('curly', 'churlish'))),
698 * Check the credit note retrieval is case insensitive.
700 public function testGetCreditNoteCaseInsensitive() {
701 $this->contributionCreate(['contact_id' => $this->_individualId
]);
702 $this->contributionCreate(['creditnote_id' => 'cN1234', 'contact_id' => $this->_individualId
, 'invoice_id' => rand(), 'trxn_id' => rand()]);
703 $contribution = $this->callAPISuccess('Contribution', 'getsingle', ['creditnote_id' => 'CN1234']);
704 $this->assertEquals($contribution['creditnote_id'], 'cN1234');
708 * Test retrieval by total_amount works.
712 public function testGetContributionByTotalAmount() {
713 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['total_amount' => '5']));
714 $this->callAPISuccess('Contribution', 'create', array_merge($this->_params
, ['total_amount' => '10']));
715 $this->callAPISuccessGetCount('Contribution', ['total_amount' => 10], 1);
716 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 6]], 1);
717 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => 0]], 2);
718 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['>' => -5]], 2);
719 $this->callAPISuccessGetCount('Contribution', ['total_amount' => ['<' => 0]], 0);
720 $this->callAPISuccessGetCount('Contribution', [], 2);
724 * @dataProvider createLocalizedContributionDataProvider
725 * @param $totalAmount
726 * @param $decimalPoint
727 * @param $thousandSeparator
729 * @param $expectedResult
732 public function testCreateLocalizedContribution($totalAmount, $decimalPoint, $thousandSeparator, $currency, $expectedResult) {
733 $this->setDefaultCurrency($currency);
734 $this->setMonetaryDecimalPoint($decimalPoint);
735 $this->setMonetaryThousandSeparator($thousandSeparator);
738 'contact_id' => $this->_individualId
,
739 'receive_date' => '20120511',
740 'total_amount' => $totalAmount,
741 'financial_type_id' => $this->_financialTypeId
,
742 'contribution_status_id' => 1,
745 if ($expectedResult) {
746 $this->callAPISuccess('Contribution', 'create', $_params);
749 $this->callAPIFailure('Contribution', 'create', $_params);
756 public function createLocalizedContributionDataProvider() {
758 [10, '.', ',', 'USD', TRUE],
759 ['145.0E+3', '.', ',', 'USD', FALSE],
760 ['10', '.', ',', 'USD', TRUE],
761 [-10, '.', ',', 'USD', TRUE],
762 ['-10', '.', ',', 'USD', TRUE],
763 ['-10foo', '.', ',', 'USD', FALSE],
764 ['-10.0345619', '.', ',', 'USD', TRUE],
765 ['-10.010,4345619', '.', ',', 'USD', TRUE],
766 ['10.0104345619', '.', ',', 'USD', TRUE],
767 ['-0', '.', ',', 'USD', TRUE],
768 ['-.1', '.', ',', 'USD', TRUE],
769 ['.1', '.', ',', 'USD', TRUE],
770 // Test currency symbols too, default locale uses $, so if we wanted to test others we'd need to reconfigure locale
771 ['$1,234,567.89', '.', ',', 'USD', TRUE],
772 ['-$1,234,567.89', '.', ',', 'USD', TRUE],
773 ['$-1,234,567.89', '.', ',', 'USD', TRUE],
774 // This is the float format. Encapsulated in strings
775 ['1234567.89', '.', ',', 'USD', TRUE],
776 // This is the float format.
777 [1234567.89, '.', ',', 'USD', TRUE],
778 // Test EURO currency
779 ['€1,234,567.89', '.', ',', 'EUR', TRUE],
780 ['-€1,234,567.89', '.', ',', 'EUR', TRUE],
781 ['€-1,234,567.89', '.', ',', 'EUR', TRUE],
782 // This is the float format. Encapsulated in strings
783 ['1234567.89', '.', ',', 'EUR', TRUE],
784 // This is the float format.
785 [1234567.89, '.', ',', 'EUR', TRUE],
786 // Test Norwegian KR currency
787 ['kr1,234,567.89', '.', ',', 'NOK', TRUE],
788 ['kr 1,234,567.89', '.', ',', 'NOK', TRUE],
789 ['-kr1,234,567.89', '.', ',', 'NOK', TRUE],
790 ['-kr 1,234,567.89', '.', ',', 'NOK', TRUE],
791 ['kr-1,234,567.89', '.', ',', 'NOK', TRUE],
792 ['kr -1,234,567.89', '.', ',', 'NOK', TRUE],
793 // This is the float format. Encapsulated in strings
794 ['1234567.89', '.', ',', 'NOK', TRUE],
795 // This is the float format.
796 [1234567.89, '.', ',', 'NOK', TRUE],
797 // Test different localization options: , as decimal separator and dot as thousand separator
798 ['$1.234.567,89', ',', '.', 'USD', TRUE],
799 ['-$1.234.567,89', ',', '.', 'USD', TRUE],
800 ['$-1.234.567,89', ',', '.', 'USD', TRUE],
801 ['1.234.567,89', ',', '.', 'USD', TRUE],
802 // This is the float format. Encapsulated in strings
803 ['1234567.89', ',', '.', 'USD', TRUE],
804 // This is the float format.
805 [1234567.89, ',', '.', 'USD', TRUE],
806 ['$1,234,567.89', ',', '.', 'USD', FALSE],
807 ['-$1,234,567.89', ',', '.', 'USD', FALSE],
808 ['$-1,234,567.89', ',', '.', 'USD', FALSE],
809 // Now with a space as thousand separator
810 ['$1 234 567,89', ',', ' ', 'USD', TRUE],
811 ['-$1 234 567,89', ',', ' ', 'USD', TRUE],
812 ['$-1 234 567,89', ',', ' ', 'USD', TRUE],
813 ['1 234 567,89', ',', ' ', 'USD', TRUE],
814 // This is the float format. Encapsulated in strings
815 ['1234567.89', ',', ' ', 'USD', TRUE],
816 // This is the float format.
817 [1234567.89, ',', ' ', 'USD', TRUE],
822 * Create test with unique field name on source.
824 public function testCreateContributionSource() {
827 'contact_id' => $this->_individualId
,
828 'receive_date' => date('Ymd'),
829 'total_amount' => 100.00,
830 'financial_type_id' => $this->_financialTypeId
,
831 'payment_instrument_id' => 1,
832 'non_deductible_amount' => 10.00,
833 'fee_amount' => 50.00,
834 'net_amount' => 90.00,
836 'invoice_id' => 67890,
837 'contribution_source' => 'SSF',
838 'contribution_status_id' => 1,
841 $contribution = $this->callAPISuccess('contribution', 'create', $params);
842 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
843 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
847 * Create test with unique field name on source.
849 * @param string $thousandSeparator
850 * punctuation used to refer to thousands.
852 * @dataProvider getThousandSeparators
854 public function testCreateDefaultNow($thousandSeparator) {
855 $this->setCurrencySeparators($thousandSeparator);
856 $params = $this->_params
;
857 unset($params['receive_date'], $params['net_amount']);
859 $params['total_amount'] = $this->formatMoneyInput(5000.77);
860 $params['fee_amount'] = $this->formatMoneyInput(.77);
861 $params['skipCleanMoney'] = FALSE;
863 $contribution = $this->callAPISuccess('contribution', 'create', $params);
864 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
865 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receive_date'])));
866 $this->assertEquals(5000.77, $contribution['total_amount'], 'failed to handle ' . $this->formatMoneyInput(5000.77));
867 $this->assertEquals(.77, $contribution['fee_amount']);
868 $this->assertEquals(5000, $contribution['net_amount']);
872 * Create test with unique field name on source.
874 public function testCreateContributionNullOutThankyouDate() {
876 $params = $this->_params
;
877 $params['thankyou_date'] = 'yesterday';
879 $contribution = $this->callAPISuccess('contribution', 'create', $params);
880 $contribution = $this->callAPISuccessGetSingle('contribution', ['id' => $contribution['id']]);
881 $this->assertEquals(date('Y-m-d', strtotime('yesterday')), date('Y-m-d', strtotime($contribution['thankyou_date'])));
883 $params['thankyou_date'] = 'null';
884 $contribution = $this->callAPISuccess('contribution', 'create', $params);
885 $contribution = $this->assertTrue(empty($contribution['thankyou_date']));
889 * Create test with unique field name on source.
891 public function testCreateContributionSourceInvalidContact() {
895 'receive_date' => date('Ymd'),
896 'total_amount' => 100.00,
897 'financial_type_id' => $this->_financialTypeId
,
898 'payment_instrument_id' => 1,
899 'non_deductible_amount' => 10.00,
900 'fee_amount' => 50.00,
901 'net_amount' => 90.00,
903 'invoice_id' => 67890,
904 'contribution_source' => 'SSF',
905 'contribution_status_id' => 1,
908 $this->callAPIFailure('contribution', 'create', $params, 'contact_id is not valid : 999');
911 public function testCreateContributionSourceInvalidContContact() {
914 'contribution_contact_id' => 999,
915 'receive_date' => date('Ymd'),
916 'total_amount' => 100.00,
917 'financial_type_id' => $this->_financialTypeId
,
918 'payment_instrument_id' => 1,
919 'non_deductible_amount' => 10.00,
920 'fee_amount' => 50.00,
921 'net_amount' => 90.00,
923 'invoice_id' => 67890,
924 'contribution_source' => 'SSF',
925 'contribution_status_id' => 1,
928 $this->callAPIFailure('contribution', 'create', $params);
932 * Test note created correctly.
934 public function testCreateContributionWithNote() {
935 $description = "Demonstrates creating contribution with Note Entity.";
936 $subfile = "ContributionCreateWithNote";
938 'contact_id' => $this->_individualId
,
939 'receive_date' => '2012-01-01',
940 'total_amount' => 100.00,
941 'financial_type_id' => $this->_financialTypeId
,
942 'payment_instrument_id' => 1,
943 'non_deductible_amount' => 10.00,
944 'fee_amount' => 50.00,
945 'net_amount' => 90.00,
947 'invoice_id' => 67890,
949 'contribution_status_id' => 1,
950 'note' => 'my contribution note',
953 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
954 $result = $this->callAPISuccess('note', 'get', [
955 'entity_table' => 'civicrm_contribution',
956 'entity_id' => $contribution['id'],
959 $this->assertEquals('my contribution note', $result['values'][0]['note']);
960 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
963 public function testCreateContributionWithNoteUniqueNameAliases() {
965 'contact_id' => $this->_individualId
,
966 'receive_date' => '2012-01-01',
967 'total_amount' => 100.00,
968 'financial_type_id' => $this->_financialTypeId
,
969 'payment_instrument_id' => 1,
970 'non_deductible_amount' => 10.00,
971 'fee_amount' => 50.00,
972 'net_amount' => 90.00,
974 'invoice_id' => 67890,
976 'contribution_status_id' => 1,
977 'contribution_note' => 'my contribution note',
980 $contribution = $this->callAPISuccess('contribution', 'create', $params);
981 $result = $this->callAPISuccess('note', 'get', [
982 'entity_table' => 'civicrm_contribution',
983 'entity_id' => $contribution['id'],
986 $this->assertEquals('my contribution note', $result['values'][0]['note']);
987 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
991 * This is the test for creating soft credits.
993 public function testCreateContributionWithSoftCredit() {
994 $description = "Demonstrates creating contribution with SoftCredit.";
995 $subfile = "ContributionCreateWithSoftCredit";
996 $contact2 = $this->callAPISuccess('Contact', 'create', [
997 'display_name' => 'superman',
998 'contact_type' => 'Individual',
1001 'contact_id' => $contact2['id'],
1003 'soft_credit_type_id' => 3,
1006 $params = $this->_params +
['soft_credit' => [1 => $softParams]];
1007 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1008 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1010 $this->assertEquals($softParams['contact_id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1011 $this->assertEquals($softParams['amount'], $result['values'][0]['soft_credit'][1]['amount']);
1012 $this->assertEquals($softParams['soft_credit_type_id'], $result['values'][0]['soft_credit'][1]['soft_credit_type']);
1014 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1015 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1018 public function testCreateContributionWithSoftCreditDefaults() {
1019 $description = "Demonstrates creating contribution with Soft Credit defaults for amount and type.";
1020 $subfile = "ContributionCreateWithSoftCreditDefaults";
1021 $contact2 = $this->callAPISuccess('Contact', 'create', [
1022 'display_name' => 'superman',
1023 'contact_type' => 'Individual',
1025 $params = $this->_params +
[
1026 'soft_credit_to' => $contact2['id'],
1028 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1029 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1031 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1032 // Default soft credit amount = contribution.total_amount
1033 $this->assertEquals($this->_params
['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
1034 $this->assertEquals(CRM_Core_OptionGroup
::getDefaultValue("soft_credit_type"), $result['values'][0]['soft_credit'][1]['soft_credit_type']);
1036 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1037 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1041 * Test creating contribution with Soft Credit by passing in honor_contact_id.
1043 public function testCreateContributionWithHonoreeContact() {
1044 $description = "Demonstrates creating contribution with Soft Credit by passing in honor_contact_id.";
1045 $subfile = "ContributionCreateWithHonoreeContact";
1046 $contact2 = $this->callAPISuccess('Contact', 'create', [
1047 'display_name' => 'superman',
1048 'contact_type' => 'Individual',
1050 $params = $this->_params +
[
1051 'honor_contact_id' => $contact2['id'],
1053 $contribution = $this->callAPIAndDocument('contribution', 'create', $params, __FUNCTION__
, __FILE__
, $description, $subfile);
1054 $result = $this->callAPISuccess('contribution', 'get', ['return' => 'soft_credit', 'sequential' => 1]);
1056 $this->assertEquals($contact2['id'], $result['values'][0]['soft_credit'][1]['contact_id']);
1057 // Default soft credit amount = contribution.total_amount
1058 // Legacy mode in create api (honor_contact_id param) uses the standard "In Honor of" soft credit type
1059 $this->assertEquals($this->_params
['total_amount'], $result['values'][0]['soft_credit'][1]['amount']);
1060 $softCreditValueTypeID = $result['values'][0]['soft_credit'][1]['soft_credit_type'];
1061 $this->assertEquals('in_honor_of', CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $softCreditValueTypeID));
1063 $this->callAPISuccess('contribution', 'delete', ['id' => $contribution['id']]);
1064 $this->callAPISuccess('contact', 'delete', ['id' => $contact2['id']]);
1068 * Test using example code.
1070 public function testContributionCreateExample() {
1071 //make sure at least on page exists since there is a truncate in tear down
1072 $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1073 require_once 'api/v3/examples/Contribution/Create.ex.php';
1074 $result = contribution_create_example();
1075 $id = $result['id'];
1076 $expectedResult = contribution_create_expectedresult();
1077 $this->checkArrayEquals($expectedResult, $result);
1078 $this->contributionDelete($id);
1082 * Function tests that additional financial records are created when fee amount is recorded.
1084 public function testCreateContributionWithFee() {
1086 'contact_id' => $this->_individualId
,
1087 'receive_date' => '20120511',
1088 'total_amount' => 100.00,
1090 'financial_type_id' => 1,
1092 'invoice_id' => 67890,
1094 'contribution_status_id' => 1,
1097 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1098 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
1099 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1100 $this->assertEquals($contribution['values'][$contribution['id']]['fee_amount'], 50.00);
1101 $this->assertEquals($contribution['values'][$contribution['id']]['net_amount'], 50.00);
1102 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1103 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1104 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1105 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1106 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
1108 $lineItems = $this->callAPISuccess('line_item', 'get', [
1110 'entity_id' => $contribution['id'],
1111 'entity_table' => 'civicrm_contribution',
1114 $this->assertEquals(1, $lineItems['count']);
1115 $this->assertEquals($contribution['id'], $lineItems['values'][0]['entity_id']);
1116 $this->assertEquals($contribution['id'], $lineItems['values'][0]['contribution_id']);
1117 $lineItems = $this->callAPISuccess('line_item', 'get', [
1119 'entity_id' => $contribution['id'],
1120 'contribution_id' => $contribution['id'],
1121 'entity_table' => 'civicrm_contribution',
1124 $this->assertEquals(1, $lineItems['count']);
1125 $this->_checkFinancialRecords($contribution, 'feeAmount');
1129 * Function tests that additional financial records are created when online contribution is created.
1131 public function testCreateContributionOnline() {
1132 CRM_Financial_BAO_PaymentProcessor
::create($this->_processorParams
);
1133 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1134 $this->assertAPISuccess($contributionPage);
1136 'contact_id' => $this->_individualId
,
1137 'receive_date' => '20120511',
1138 'total_amount' => 100.00,
1139 'financial_type_id' => 1,
1140 'contribution_page_id' => $contributionPage['id'],
1141 'payment_processor' => $this->paymentProcessorID
,
1143 'invoice_id' => 67890,
1145 'contribution_status_id' => 1,
1149 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1150 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
1151 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1152 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1153 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1154 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1155 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1156 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 1);
1157 $contribution['payment_instrument_id'] = $this->callAPISuccessGetValue('PaymentProcessor', [
1158 'id' => $this->paymentProcessorID
,
1159 'return' => 'payment_instrument_id',
1161 $this->_checkFinancialRecords($contribution, 'online');
1165 * Check handling of financial type.
1167 * In the interests of removing financial type / contribution type checks from
1168 * legacy format function lets test that the api is doing this for us
1170 public function testCreateInvalidFinancialType() {
1171 $params = $this->_params
;
1172 $params['financial_type_id'] = 99999;
1173 $this->callAPIFailure($this->entity
, 'create', $params, "'99999' is not a valid option for field financial_type_id");
1177 * Check handling of financial type.
1179 * In the interests of removing financial type / contribution type checks from
1180 * legacy format function lets test that the api is doing this for us
1182 * @throws \CRM_Core_Exception
1184 public function testValidNamedFinancialType() {
1185 $params = $this->_params
;
1186 $params['financial_type_id'] = 'Donation';
1187 $this->callAPISuccess($this->entity
, 'create', $params);
1191 * Tests that additional financial records are created.
1193 * Checks when online contribution with pay later option is created
1195 * @throws \CRM_Core_Exception
1197 public function testCreateContributionPayLaterOnline() {
1198 $this->_pageParams
['is_pay_later'] = 1;
1199 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1200 $this->assertAPISuccess($contributionPage);
1202 'contact_id' => $this->_individualId
,
1203 'receive_date' => '20120511',
1204 'total_amount' => 100.00,
1205 'financial_type_id' => 1,
1206 'contribution_page_id' => $contributionPage['id'],
1208 'is_pay_later' => 1,
1209 'invoice_id' => 67890,
1211 'contribution_status_id' => 'Pending',
1215 $contribution = $this->callAPIAndDocument('Contribution', 'create', $params, __FUNCTION__
, __FILE__
);
1216 $contribution = $contribution['values'][$contribution['id']];
1217 $this->assertEquals($contribution['contact_id'], $this->_individualId
);
1218 $this->assertEquals($contribution['total_amount'], 100.00);
1219 $this->assertEquals($contribution['financial_type_id'], 1);
1220 $this->assertEquals($contribution['trxn_id'], 12345);
1221 $this->assertEquals($contribution['invoice_id'], 67890);
1222 $this->assertEquals($contribution['source'], 'SSF');
1223 $this->assertEquals($contribution['contribution_status_id'], 2);
1224 $this->_checkFinancialRecords($contribution, 'payLater');
1228 * Function tests that additional financial records are created for online contribution with pending option.
1230 public function testCreateContributionPendingOnline() {
1231 CRM_Financial_BAO_PaymentProcessor
::create($this->_processorParams
);
1232 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $this->_pageParams
);
1233 $this->assertAPISuccess($contributionPage);
1235 'contact_id' => $this->_individualId
,
1236 'receive_date' => '20120511',
1237 'total_amount' => 100.00,
1238 'financial_type_id' => 1,
1239 'contribution_page_id' => $contributionPage['id'],
1241 'invoice_id' => 67890,
1243 'contribution_status_id' => 2,
1246 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1247 $this->assertEquals($contribution['values'][$contribution['id']]['contact_id'], $this->_individualId
);
1248 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
1249 $this->assertEquals($contribution['values'][$contribution['id']]['financial_type_id'], 1);
1250 $this->assertEquals($contribution['values'][$contribution['id']]['trxn_id'], 12345);
1251 $this->assertEquals($contribution['values'][$contribution['id']]['invoice_id'], 67890);
1252 $this->assertEquals($contribution['values'][$contribution['id']]['source'], 'SSF');
1253 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status_id'], 2);
1254 $this->_checkFinancialRecords($contribution, 'pending');
1258 * Test that BAO defaults work.
1260 * @throws \CRM_Core_Exception
1262 public function testCreateBAODefaults() {
1263 unset($this->_params
['contribution_source_id'], $this->_params
['payment_instrument_id']);
1264 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1265 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
1266 'id' => $contribution['id'],
1267 'api.contribution.delete' => 1,
1269 $this->assertEquals(1, $contribution['contribution_status_id']);
1270 $this->assertEquals('Check', $contribution['payment_instrument']);
1271 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1275 * Test that getsingle can be chained with delete.
1277 * @throws CRM_Core_Exception
1279 public function testDeleteChainedGetSingle() {
1280 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1281 $contribution = $this->callAPISuccess('Contribution', 'getsingle', [
1282 'id' => $contribution['id'],
1283 'api.contribution.delete' => 1,
1285 $this->callAPISuccessGetCount('Contribution', ['id' => $contribution['id']], 0);
1289 * Function tests that line items, financial records are updated when contribution amount is changed.
1291 * @throws \CRM_Core_Exception
1293 public function testCreateUpdateContributionChangeTotal() {
1294 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
1295 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1297 'entity_id' => $contribution['id'],
1298 'entity_table' => 'civicrm_contribution',
1300 'return' => 'line_total',
1302 $this->assertEquals('100.00', $lineItems);
1303 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1304 // Financial trxn SUM = 100 + 5 (fee)
1305 $this->assertEquals('105.00', $trxnAmount);
1308 'id' => $contribution['id'],
1309 'total_amount' => '125',
1311 $contribution = $this->callAPISuccess('Contribution', 'create', $newParams);
1313 $lineItems = $this->callAPISuccess('line_item', 'getvalue', [
1315 'entity_id' => $contribution['id'],
1316 'entity_table' => 'civicrm_contribution',
1318 'return' => 'line_total',
1321 $this->assertEquals('125.00', $lineItems);
1322 $trxnAmount = $this->_getFinancialTrxnAmount($contribution['id']);
1324 // Financial trxn SUM = 125 + 5 (fee).
1325 $this->assertEquals('130.00', $trxnAmount);
1326 $this->assertEquals('125.00', $this->_getFinancialItemAmount($contribution['id']));
1330 * Function tests that line items, financial records are updated when pay later contribution is received.
1332 public function testCreateUpdateContributionPayLater() {
1334 'contact_id' => $this->_individualId
,
1335 'receive_date' => '2012-01-01',
1336 'total_amount' => 100.00,
1337 'financial_type_id' => $this->_financialTypeId
,
1338 'payment_instrument_id' => 1,
1339 'contribution_status_id' => 2,
1340 'is_pay_later' => 1,
1343 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1345 $newParams = array_merge($contribParams, [
1346 'id' => $contribution['id'],
1347 'contribution_status_id' => 1,
1349 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1350 $contribution = $contribution['values'][$contribution['id']];
1351 $this->assertEquals($contribution['contribution_status_id'], '1');
1352 $this->_checkFinancialItem($contribution['id'], 'paylater');
1353 $this->_checkFinancialTrxn($contribution, 'payLater');
1357 * Function tests that financial records are updated when Payment Instrument is changed.
1359 public function testCreateUpdateContributionPaymentInstrument() {
1360 $instrumentId = $this->_addPaymentInstrument();
1362 'contact_id' => $this->_individualId
,
1363 'total_amount' => 100.00,
1364 'financial_type_id' => $this->_financialTypeId
,
1365 'payment_instrument_id' => 4,
1366 'contribution_status_id' => 1,
1369 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1371 $newParams = array_merge($contribParams, [
1372 'id' => $contribution['id'],
1373 'payment_instrument_id' => $instrumentId,
1375 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1376 $this->assertAPISuccess($contribution);
1377 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId);
1379 // cleanup - delete created payment instrument
1380 $this->_deletedAddedPaymentInstrument();
1384 * Function tests that financial records are updated when Payment Instrument is changed when amount is negative.
1386 public function testCreateUpdateNegativeContributionPaymentInstrument() {
1387 $instrumentId = $this->_addPaymentInstrument();
1389 'contact_id' => $this->_individualId
,
1390 'total_amount' => -100.00,
1391 'financial_type_id' => $this->_financialTypeId
,
1392 'payment_instrument_id' => 4,
1393 'contribution_status_id' => 1,
1396 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1398 $newParams = array_merge($contribParams, [
1399 'id' => $contribution['id'],
1400 'payment_instrument_id' => $instrumentId,
1402 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1403 $this->assertAPISuccess($contribution);
1404 $this->checkFinancialTrxnPaymentInstrumentChange($contribution['id'], 4, $instrumentId, -100);
1406 // cleanup - delete created payment instrument
1407 $this->_deletedAddedPaymentInstrument();
1411 * Function tests that financial records are added when Contribution is Refunded.
1413 * @throws \CRM_Core_Exception
1415 public function testCreateUpdateContributionRefund() {
1416 $contributionParams = [
1417 'contact_id' => $this->_individualId
,
1418 'receive_date' => '2012-01-01',
1419 'total_amount' => 100.00,
1420 'financial_type_id' => $this->_financialTypeId
,
1421 'payment_instrument_id' => 4,
1422 'contribution_status_id' => 1,
1423 'trxn_id' => 'original_payment',
1425 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
1426 $newParams = array_merge($contributionParams, [
1427 'id' => $contribution['id'],
1428 'contribution_status_id' => 'Refunded',
1429 'cancel_date' => '2015-01-01 09:00',
1430 'refund_trxn_id' => 'the refund',
1433 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1434 $this->_checkFinancialTrxn($contribution, 'refund');
1435 $this->_checkFinancialItem($contribution['id'], 'refund');
1436 $this->assertEquals('original_payment', $this->callAPISuccessGetValue('Contribution', [
1437 'id' => $contribution['id'],
1438 'return' => 'trxn_id',
1443 * Refund a contribution for a financial type with a contra account.
1445 * CRM-17951 the contra account is a financial account with a relationship to a
1446 * financial type. It is not always configured but should be reflected
1447 * in the financial_trxn & financial_item table if it is.
1449 * @throws \CRM_Core_Exception
1451 public function testCreateUpdateChargebackContributionDefaultAccount() {
1452 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1453 $this->callAPISuccess('Contribution', 'create', [
1454 'id' => $contribution['id'],
1455 'contribution_status_id' => 'Chargeback',
1457 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1459 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1460 'contribution_id' => $contribution['id'],
1461 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1463 $this->assertEquals(1, $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1464 $this->callAPISuccessGetSingle('FinancialTrxn', [
1465 'total_amount' => -100,
1466 'status_id' => 'Chargeback',
1467 'to_financial_account_id' => 6,
1472 * Refund a contribution for a financial type with a contra account.
1474 * CRM-17951 the contra account is a financial account with a relationship to a
1475 * financial type. It is not always configured but should be reflected
1476 * in the financial_trxn & financial_item table if it is.
1478 * @throws \CRM_Core_Exception
1480 public function testCreateUpdateChargebackContributionCustomAccount() {
1481 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1482 'name' => 'Chargeback Account',
1483 'is_active' => TRUE,
1486 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1487 'entity_id' => $this->_financialTypeId
,
1488 'entity_table' => 'civicrm_financial_type',
1489 'account_relationship' => 'Chargeback Account is',
1490 'financial_account_id' => 'Chargeback Account',
1493 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1494 $this->callAPISuccess('Contribution', 'create', [
1495 'id' => $contribution['id'],
1496 'contribution_status_id' => 'Chargeback',
1498 $this->callAPISuccessGetSingle('Contribution', ['contribution_status_id' => 'Chargeback']);
1500 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1501 'contribution_id' => $contribution['id'],
1502 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1504 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1506 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1507 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1508 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1512 * Refund a contribution for a financial type with a contra account.
1514 * CRM-17951 the contra account is a financial account with a relationship to a
1515 * financial type. It is not always configured but should be reflected
1516 * in the financial_trxn & financial_item table if it is.
1518 public function testCreateUpdateRefundContributionConfiguredContraAccount() {
1519 $financialAccount = $this->callAPISuccess('FinancialAccount', 'create', [
1520 'name' => 'Refund Account',
1521 'is_active' => TRUE,
1524 $entityFinancialAccount = $this->callAPISuccess('EntityFinancialAccount', 'create', [
1525 'entity_id' => $this->_financialTypeId
,
1526 'entity_table' => 'civicrm_financial_type',
1527 'account_relationship' => 'Credit/Contra Revenue Account is',
1528 'financial_account_id' => 'Refund Account',
1531 $contribution = $this->callAPISuccess('Contribution', 'create', $this->_params
);
1532 $this->callAPISuccess('Contribution', 'create', [
1533 'id' => $contribution['id'],
1534 'contribution_status_id' => 'Refunded',
1537 $lineItems = $this->callAPISuccessGetSingle('LineItem', [
1538 'contribution_id' => $contribution['id'],
1539 'api.FinancialItem.getsingle' => ['amount' => ['<' => 0]],
1541 $this->assertEquals($financialAccount['id'], $lineItems['api.FinancialItem.getsingle']['financial_account_id']);
1543 $this->callAPISuccess('Contribution', 'delete', ['id' => $contribution['id']]);
1544 $this->callAPISuccess('EntityFinancialAccount', 'delete', ['id' => $entityFinancialAccount['id']]);
1545 $this->callAPISuccess('FinancialAccount', 'delete', ['id' => $financialAccount['id']]);
1549 * Function tests that trxn_id is set when passed in.
1551 * Here we ensure that the civicrm_financial_trxn.trxn_id & the civicrm_contribution.trxn_id are set
1552 * when trxn_id is passed in.
1554 public function testCreateUpdateContributionRefundTrxnIDPassedIn() {
1555 $contributionParams = [
1556 'contact_id' => $this->_individualId
,
1557 'receive_date' => '2012-01-01',
1558 'total_amount' => 100.00,
1559 'financial_type_id' => $this->_financialTypeId
,
1560 'payment_instrument_id' => 4,
1561 'contribution_status_id' => 1,
1562 'trxn_id' => 'original_payment',
1564 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1565 $newParams = array_merge($contributionParams, [
1566 'id' => $contribution['id'],
1567 'contribution_status_id' => 'Refunded',
1568 'cancel_date' => '2015-01-01 09:00',
1569 'trxn_id' => 'the refund',
1572 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1573 $this->_checkFinancialTrxn($contribution, 'refund');
1574 $this->_checkFinancialItem($contribution['id'], 'refund');
1575 $this->assertEquals('the refund', $this->callAPISuccessGetValue('Contribution', [
1576 'id' => $contribution['id'],
1577 'return' => 'trxn_id',
1582 * Function tests that trxn_id is set when passed in.
1584 * Here we ensure that the civicrm_contribution.trxn_id is set
1585 * when trxn_id is passed in but if refund_trxn_id is different then that
1586 * is kept for the refund transaction.
1588 public function testCreateUpdateContributionRefundRefundAndTrxnIDPassedIn() {
1589 $contributionParams = [
1590 'contact_id' => $this->_individualId
,
1591 'receive_date' => '2012-01-01',
1592 'total_amount' => 100.00,
1593 'financial_type_id' => $this->_financialTypeId
,
1594 'payment_instrument_id' => 4,
1595 'contribution_status_id' => 1,
1596 'trxn_id' => 'original_payment',
1598 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1599 $newParams = array_merge($contributionParams, [
1600 'id' => $contribution['id'],
1601 'contribution_status_id' => 'Refunded',
1602 'cancel_date' => '2015-01-01 09:00',
1603 'trxn_id' => 'cont id',
1604 'refund_trxn_id' => 'the refund',
1607 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1608 $this->_checkFinancialTrxn($contribution, 'refund');
1609 $this->_checkFinancialItem($contribution['id'], 'refund');
1610 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1611 'id' => $contribution['id'],
1612 'return' => 'trxn_id',
1617 * Function tests that refund_trxn_id is set when passed in empty.
1619 * Here we ensure that the civicrm_contribution.trxn_id is set
1620 * when trxn_id is passed in but if refund_trxn_id isset but empty then that
1621 * is kept for the refund transaction.
1623 public function testCreateUpdateContributionRefundRefundNullTrxnIDPassedIn() {
1624 $contributionParams = [
1625 'contact_id' => $this->_individualId
,
1626 'receive_date' => '2012-01-01',
1627 'total_amount' => 100.00,
1628 'financial_type_id' => $this->_financialTypeId
,
1629 'payment_instrument_id' => 4,
1630 'contribution_status_id' => 1,
1631 'trxn_id' => 'original_payment',
1633 $contribution = $this->callAPISuccess('contribution', 'create', $contributionParams);
1634 $newParams = array_merge($contributionParams, [
1635 'id' => $contribution['id'],
1636 'contribution_status_id' => 'Refunded',
1637 'cancel_date' => '2015-01-01 09:00',
1638 'trxn_id' => 'cont id',
1639 'refund_trxn_id' => '',
1642 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1643 $this->_checkFinancialTrxn($contribution, 'refund', NULL, ['trxn_id' => NULL]);
1644 $this->_checkFinancialItem($contribution['id'], 'refund');
1645 $this->assertEquals('cont id', $this->callAPISuccessGetValue('Contribution', [
1646 'id' => $contribution['id'],
1647 'return' => 'trxn_id',
1652 * Function tests invalid contribution status change.
1654 public function testCreateUpdateContributionInValidStatusChange() {
1657 'receive_date' => '2012-01-01',
1658 'total_amount' => 100.00,
1659 'financial_type_id' => 1,
1660 'payment_instrument_id' => 1,
1661 'contribution_status_id' => 1,
1663 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1664 $newParams = array_merge($contribParams, [
1665 'id' => $contribution['id'],
1666 'contribution_status_id' => 2,
1668 $this->callAPIFailure('contribution', 'create', $newParams, ts('Cannot change contribution status from Completed to Pending.'));
1673 * Function tests that financial records are added when Pending Contribution is Canceled.
1675 * @throws \CRM_Core_Exception
1677 public function testCreateUpdateContributionCancelPending() {
1679 'contact_id' => $this->_individualId
,
1680 'receive_date' => '2012-01-01',
1681 'total_amount' => 100.00,
1682 'financial_type_id' => $this->_financialTypeId
,
1683 'payment_instrument_id' => 1,
1684 'contribution_status_id' => 2,
1685 'is_pay_later' => 1,
1688 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1689 $newParams = array_merge($contribParams, [
1690 'id' => $contribution['id'],
1691 'contribution_status_id' => 3,
1692 'cancel_date' => '2012-02-02 09:00',
1694 //Check if trxn_date is same as cancel_date.
1696 'trxn_date' => '2012-02-02 09:00:00',
1698 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1699 $this->_checkFinancialTrxn($contribution, 'cancelPending', NULL, $checkTrxnDate);
1700 $this->_checkFinancialItem($contribution['id'], 'cancelPending');
1704 * Function tests that financial records are added when Financial Type is Changed.
1706 * @throws \CRM_Core_Exception
1708 public function testCreateUpdateContributionChangeFinancialType() {
1710 'contact_id' => $this->_individualId
,
1711 'receive_date' => '2012-01-01',
1712 'total_amount' => 100.00,
1713 'financial_type_id' => 1,
1714 'payment_instrument_id' => 1,
1715 'contribution_status_id' => 1,
1718 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1719 $newParams = array_merge($contribParams, [
1720 'id' => $contribution['id'],
1721 'financial_type_id' => 3,
1723 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1724 $this->_checkFinancialTrxn($contribution, 'changeFinancial');
1725 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1729 * Function tets that financial records are correctly added when financial type is changed
1731 * @throws \CRM_Core_Exception
1733 public function testCreateUpdateContributionWithFeeAmountChangeFinancialType() {
1735 'contact_id' => $this->_individualId
,
1736 'receive_date' => '2012-01-01',
1737 'total_amount' => 100.00,
1738 'fee_amount' => 0.57,
1739 'financial_type_id' => 1,
1740 'payment_instrument_id' => 1,
1741 'contribution_status_id' => 1,
1744 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
1745 $newParams = array_merge($contribParams, [
1746 'id' => $contribution['id'],
1747 'financial_type_id' => 3,
1749 $contribution = $this->callAPISuccess('contribution', 'create', $newParams);
1750 $this->_checkFinancialTrxn($contribution, 'changeFinancial', NULL, ['fee_amount' => '-0.57', 'net_amount' => '-99.43']);
1751 $this->_checkFinancialItem($contribution['id'], 'changeFinancial');
1755 * Test that update does not change status id CRM-15105.
1757 public function testCreateUpdateWithoutChangingPendingStatus() {
1758 $contribution = $this->callAPISuccess('contribution', 'create', array_merge($this->_params
, ['contribution_status_id' => 2]));
1759 $this->callAPISuccess('contribution', 'create', ['id' => $contribution['id'], 'source' => 'new source']);
1760 $contribution = $this->callAPISuccess('contribution', 'getsingle', [
1761 'id' => $contribution['id'],
1762 'api.contribution.delete' => 1,
1764 $this->assertEquals(2, $contribution['contribution_status_id']);
1768 * Test Updating a Contribution.
1770 * CHANGE: we require the API to do an incremental update
1772 public function testCreateUpdateContribution() {
1773 $contributionID = $this->contributionCreate([
1774 'contact_id' => $this->_individualId
,
1775 'trxn_id' => 212355,
1776 'financial_type_id' => $this->_financialTypeId
,
1777 'invoice_id' => 'old_invoice',
1780 'contribution_id' => $contributionID,
1782 $original = $this->callAPISuccess('contribution', 'get', $old_params);
1783 $this->assertEquals($original['id'], $contributionID);
1784 //set up list of old params, verify
1786 //This should not be required on update:
1787 $old_contact_id = $original['values'][$contributionID]['contact_id'];
1788 $old_payment_instrument = $original['values'][$contributionID]['instrument_id'];
1789 $old_fee_amount = $original['values'][$contributionID]['fee_amount'];
1790 $old_source = $original['values'][$contributionID]['contribution_source'];
1792 $old_trxn_id = $original['values'][$contributionID]['trxn_id'];
1793 $old_invoice_id = $original['values'][$contributionID]['invoice_id'];
1795 //check against values in CiviUnitTestCase::createContribution()
1796 $this->assertEquals($old_contact_id, $this->_individualId
);
1797 $this->assertEquals($old_fee_amount, 5.00);
1798 $this->assertEquals($old_source, 'SSF');
1799 $this->assertEquals($old_trxn_id, 212355);
1800 $this->assertEquals($old_invoice_id, 'old_invoice');
1802 'id' => $contributionID,
1803 'contact_id' => $this->_individualId
,
1804 'total_amount' => 105.00,
1805 'fee_amount' => 7.00,
1806 'financial_type_id' => $this->_financialTypeId
,
1807 'non_deductible_amount' => 22.00,
1808 'contribution_status_id' => 1,
1809 'note' => 'Donating for Noble Cause',
1812 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1815 'contribution_id' => $contribution['id'],
1817 $contribution = $this->callAPISuccessGetSingle('contribution', $new_params);
1819 $this->assertEquals($contribution['contact_id'], $this->_individualId
);
1820 $this->assertEquals($contribution['total_amount'], 105.00);
1821 $this->assertEquals($contribution['financial_type_id'], $this->_financialTypeId
);
1822 $this->assertEquals($contribution['financial_type'], 'Donation');
1823 $this->assertEquals($contribution['instrument_id'], $old_payment_instrument);
1824 $this->assertEquals($contribution['non_deductible_amount'], 22.00);
1825 $this->assertEquals($contribution['fee_amount'], 7.00);
1826 $this->assertEquals($contribution['trxn_id'], $old_trxn_id);
1827 $this->assertEquals($contribution['invoice_id'], $old_invoice_id);
1828 $this->assertEquals($contribution['contribution_source'], $old_source);
1829 $this->assertEquals($contribution['contribution_status'], 'Completed');
1831 $this->assertEquals($contribution['net_amount'], $contribution['total_amount'] - $contribution['fee_amount']);
1834 'contribution_id' => $contributionID,
1836 $result = $this->callAPISuccess('contribution', 'delete', $params);
1837 $this->assertAPISuccess($result);
1841 * Check that net_amount is updated when a contribution is updated.
1843 * Update fee amount AND total amount, just fee amount, just total amount
1844 * and neither to check that net_amount is keep updated.
1846 public function testUpdateContributionNetAmountVariants() {
1847 $contributionID = $this->contributionCreate(['contact_id' => $this->individualCreate()]);
1849 $this->callAPISuccess('Contribution', 'create', [
1850 'id' => $contributionID,
1851 'total_amount' => 90,
1854 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1855 'id' => $contributionID,
1856 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1858 $this->assertEquals(6, $contribution['fee_amount']);
1859 $this->assertEquals(90, $contribution['total_amount']);
1860 $this->assertEquals(84, $contribution['net_amount']);
1862 $this->callAPISuccess('Contribution', 'create', [
1863 'id' => $contributionID,
1866 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1867 'id' => $contributionID,
1868 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1870 $this->assertEquals(3, $contribution['fee_amount']);
1871 $this->assertEquals(90, $contribution['total_amount']);
1872 $this->assertEquals(87, $contribution['net_amount']);
1874 $this->callAPISuccess('Contribution', 'create', [
1875 'id' => $contributionID,
1876 'total_amount' => 200,
1878 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1879 'id' => $contributionID,
1880 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1882 $this->assertEquals(3, $contribution['fee_amount']);
1883 $this->assertEquals(200, $contribution['total_amount']);
1884 $this->assertEquals(197, $contribution['net_amount']);
1886 $this->callAPISuccess('Contribution', 'create', [
1887 'id' => $contributionID,
1888 'payment_instrument' => 'Cash',
1890 $contribution = $this->callAPISuccessGetSingle('Contribution', [
1891 'id' => $contributionID,
1892 'return' => ['net_amount', 'fee_amount', 'total_amount'],
1894 $this->assertEquals(3, $contribution['fee_amount']);
1895 $this->assertEquals(200, $contribution['total_amount']);
1896 $this->assertEquals(197, $contribution['net_amount']);
1900 * Attempt (but fail) to delete a contribution without parameters.
1902 public function testDeleteEmptyParamsContribution() {
1904 $this->callAPIFailure('contribution', 'delete', $params);
1907 public function testDeleteParamsNotArrayContribution() {
1908 $this->expectException(TypeError
::class);
1909 $params = 'contribution_id= 1';
1910 $contribution = $this->callAPIFailure('contribution', 'delete', $params);
1913 public function testDeleteWrongParamContribution() {
1915 'contribution_source' => 'SSF',
1917 $this->callAPIFailure('contribution', 'delete', $params);
1920 public function testDeleteContribution() {
1921 $contributionID = $this->contributionCreate([
1922 'contact_id' => $this->_individualId
,
1923 'financial_type_id' => $this->_financialTypeId
,
1926 'id' => $contributionID,
1928 $this->callAPIAndDocument('contribution', 'delete', $params, __FUNCTION__
, __FILE__
);
1932 * Test civicrm_contribution_search with empty params.
1934 * All available contributions expected.
1936 public function testSearchEmptyParams() {
1940 'contact_id' => $this->_individualId
,
1941 'receive_date' => date('Ymd'),
1942 'total_amount' => 100.00,
1943 'financial_type_id' => $this->_financialTypeId
,
1944 'non_deductible_amount' => 10.00,
1945 'fee_amount' => 5.00,
1946 'net_amount' => 95.00,
1948 'invoice_id' => 78910,
1950 'contribution_status_id' => 1,
1952 $contribution = $this->callAPISuccess('contribution', 'create', $p);
1954 $result = $this->callAPISuccess('contribution', 'get', $params);
1955 // We're taking the first element.
1956 $res = $result['values'][$contribution['id']];
1958 $this->assertEquals($p['contact_id'], $res['contact_id']);
1959 $this->assertEquals($p['total_amount'], $res['total_amount']);
1960 $this->assertEquals($p['financial_type_id'], $res['financial_type_id']);
1961 $this->assertEquals($p['net_amount'], $res['net_amount']);
1962 $this->assertEquals($p['non_deductible_amount'], $res['non_deductible_amount']);
1963 $this->assertEquals($p['fee_amount'], $res['fee_amount']);
1964 $this->assertEquals($p['trxn_id'], $res['trxn_id']);
1965 $this->assertEquals($p['invoice_id'], $res['invoice_id']);
1966 $this->assertEquals($p['source'], $res['contribution_source']);
1967 // contribution_status_id = 1 => Completed
1968 $this->assertEquals('Completed', $res['contribution_status']);
1970 $this->contributionDelete($contribution['id']);
1974 * Test civicrm_contribution_search. Success expected.
1976 public function testSearch() {
1978 'contact_id' => $this->_individualId
,
1979 'receive_date' => date('Ymd'),
1980 'total_amount' => 100.00,
1981 'financial_type_id' => $this->_financialTypeId
,
1982 'non_deductible_amount' => 10.00,
1983 'contribution_status_id' => 1,
1985 $contribution1 = $this->callAPISuccess('contribution', 'create', $p1);
1988 'contact_id' => $this->_individualId
,
1989 'receive_date' => date('Ymd'),
1990 'total_amount' => 200.00,
1991 'financial_type_id' => $this->_financialTypeId
,
1992 'non_deductible_amount' => 20.00,
1993 'trxn_id' => 5454565,
1994 'invoice_id' => 1212124,
1995 'fee_amount' => 50.00,
1996 'net_amount' => 60.00,
1997 'contribution_status_id' => 2,
1999 $contribution2 = $this->callAPISuccess('contribution', 'create', $p2);
2002 'contribution_id' => $contribution2['id'],
2004 $result = $this->callAPISuccess('contribution', 'get', $params);
2005 $res = $result['values'][$contribution2['id']];
2007 $this->assertEquals($p2['contact_id'], $res['contact_id']);
2008 $this->assertEquals($p2['total_amount'], $res['total_amount']);
2009 $this->assertEquals($p2['financial_type_id'], $res['financial_type_id']);
2010 $this->assertEquals($p2['net_amount'], $res['net_amount']);
2011 $this->assertEquals($p2['non_deductible_amount'], $res['non_deductible_amount']);
2012 $this->assertEquals($p2['fee_amount'], $res['fee_amount']);
2013 $this->assertEquals($p2['trxn_id'], $res['trxn_id']);
2014 $this->assertEquals($p2['invoice_id'], $res['invoice_id']);
2015 $this->assertEquals(CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending'), $res['contribution_status_id']);
2017 $this->contributionDelete($contribution1['id']);
2018 $this->contributionDelete($contribution2['id']);
2022 * Test completing a transaction via the API.
2024 * Note that we are creating a logged in user because email goes out from
2027 public function testCompleteTransaction() {
2028 $mut = new CiviMailUtils($this, TRUE);
2029 $this->swapMessageTemplateForTestTemplate();
2030 $this->createLoggedInUser();
2031 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2032 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2033 $this->callAPISuccess('contribution', 'completetransaction', [
2034 'id' => $contribution['id'],
2036 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2037 $this->assertEquals('SSF', $contribution['contribution_source']);
2038 $this->assertEquals('Completed', $contribution['contribution_status']);
2039 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
2040 $mut->checkMailLog([
2041 'email:::anthony_anderson@civicrm.org',
2045 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2046 "receipt_date:::\n",
2047 'contributeMode:::notify',
2048 'title:::Contribution',
2049 'displayName:::Mr. Anthony Anderson II',
2050 'contributionStatus:::Completed',
2053 $this->revertTemplateToReservedTemplate();
2057 * Test completing a transaction via the API with a non-USD transaction.
2059 public function testCompleteTransactionEuro() {
2060 $mut = new CiviMailUtils($this, TRUE);
2061 $this->swapMessageTemplateForTestTemplate();
2062 $this->createLoggedInUser();
2063 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'currency' => 'EUR']);
2064 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2066 $this->callAPISuccess('contribution', 'completetransaction', [
2067 'id' => $contribution['id'],
2070 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2071 $this->assertEquals('SSF', $contribution['contribution_source']);
2072 $this->assertEquals('Completed', $contribution['contribution_status']);
2073 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['receipt_date'])));
2075 $entityFinancialTransactions = $this->getFinancialTransactionsForContribution($contribution['id']);
2076 $entityFinancialTransaction = reset($entityFinancialTransactions);
2077 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', ['id' => $entityFinancialTransaction['financial_trxn_id']]);
2078 $this->assertEquals('EUR', $financialTrxn['currency']);
2080 $mut->checkMailLog([
2081 'email:::anthony_anderson@civicrm.org',
2085 'receive_date:::' . date('Ymd', strtotime($contribution['receive_date'])),
2086 "receipt_date:::\n",
2087 'contributeMode:::notify',
2088 'title:::Contribution',
2089 'displayName:::Mr. Anthony Anderson II',
2090 'contributionStatus:::Completed',
2093 $this->revertTemplateToReservedTemplate();
2097 * Test to ensure mail is sent on chosing pay later
2099 public function testpayLater() {
2100 $mut = new CiviMailUtils($this, TRUE);
2101 $this->swapMessageTemplateForTestTemplate();
2102 $this->createLoggedInUser();
2104 // create contribution page first
2105 $contributionPageParams = [
2106 'title' => 'Help Support CiviCRM!',
2107 'financial_type_id' => 1,
2108 'is_monetary' => TRUE,
2109 'is_pay_later' => 1,
2110 'is_quick_config' => TRUE,
2111 'pay_later_text' => 'I will send payment by check',
2112 'pay_later_receipt' => 'This is a pay later reciept',
2113 'is_allow_other_amount' => 1,
2114 'min_amount' => 10.00,
2115 'max_amount' => 10000.00,
2116 'goal_amount' => 100000.00,
2117 'is_email_receipt' => 1,
2119 'amount_block_is_active' => 1,
2120 'currency' => 'USD',
2121 'is_billing_required' => 0,
2123 $contributionPageResult = $this->callAPISuccess('contribution_page', 'create', $contributionPageParams);
2125 // submit form values
2126 $priceSet = $this->callAPISuccess('price_set', 'getsingle', ['name' => 'default_contribution_amount']);
2128 'id' => $contributionPageResult['id'],
2129 'contact_id' => $this->_individualId
,
2130 'email-5' => 'anthony_anderson@civicrm.org',
2131 'payment_processor_id' => 0,
2134 'currencyID' => 'USD',
2135 'is_pay_later' => 1,
2136 'invoiceID' => 'f28e1ddc86f8c4a0ff5bcf46393e4bc8',
2137 'is_quick_config' => 1,
2138 'description' => 'Online Contribution: Help Support CiviCRM!',
2139 'price_set_id' => $priceSet['id'],
2141 $this->callAPISuccess('contribution_page', 'submit', $params);
2143 $mut->checkMailLog([
2145 'email:::anthony_anderson@civicrm.org',
2146 'pay_later_receipt:::' . $contributionPageParams['pay_later_receipt'],
2147 'displayName:::Mr. Anthony Anderson II',
2148 'contributionPageId:::' . $contributionPageResult['id'],
2149 'title:::' . $contributionPageParams['title'],
2150 'amount:::' . $params['amount'],
2153 $this->revertTemplateToReservedTemplate();
2157 * Test to check whether contact billing address is used when no contribution address
2159 public function testBillingAddress() {
2160 $mut = new CiviMailUtils($this, TRUE);
2161 $this->swapMessageTemplateForTestTemplate();
2162 $this->createLoggedInUser();
2164 //Scenario 1: When Contact don't have any address
2165 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2166 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2167 $this->callAPISuccess('contribution', 'completetransaction', [
2168 'id' => $contribution['id'],
2170 $mut->checkMailLog([
2174 // Scenario 2: Contribution using address
2175 $address = $this->callAPISuccess('address', 'create', [
2176 'street_address' => 'contribution billing st',
2177 'location_type_id' => 2,
2178 'contact_id' => $this->_params
['contact_id'],
2180 $params = array_merge($this->_params
, [
2181 'contribution_status_id' => 2,
2182 'address_id' => $address['id'],
2185 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2186 $this->callAPISuccess('contribution', 'completetransaction', [
2187 'id' => $contribution['id'],
2189 $mut->checkMailLog([
2190 'address:::contribution billing st',
2193 // Scenario 3: Contribution wtth no address but contact has a billing address
2194 $this->callAPISuccess('address', 'create', [
2195 'id' => $address['id'],
2196 'street_address' => 'is billing st',
2197 'contact_id' => $this->_params
['contact_id'],
2199 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2200 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2201 $this->callAPISuccess('contribution', 'completetransaction', [
2202 'id' => $contribution['id'],
2204 $mut->checkMailLog([
2205 'address:::is billing st',
2209 $this->revertTemplateToReservedTemplate();
2213 * Test completing a transaction via the API.
2215 * Note that we are creating a logged in user because email goes out from
2218 public function testCompleteTransactionFeeAmount() {
2219 $this->createLoggedInUser();
2220 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2221 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2222 $this->callAPISuccess('contribution', 'completetransaction', [
2223 'id' => $contribution['id'],
2224 'fee_amount' => '.56',
2225 'trxn_id' => '7778888',
2227 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id'], 'sequential' => 1]);
2228 $this->assertEquals('Completed', $contribution['contribution_status']);
2229 $this->assertEquals('7778888', $contribution['trxn_id']);
2230 $this->assertEquals('0.56', $contribution['fee_amount']);
2231 $this->assertEquals('99.44', $contribution['net_amount']);
2235 * CRM-19126 Add test to verify when complete transaction is called tax amount is not changed.
2237 * @param string $thousandSeparator
2238 * punctuation used to refer to thousands.
2240 * @dataProvider getThousandSeparators
2242 public function testCheckTaxAmount($thousandSeparator) {
2243 $this->setCurrencySeparators($thousandSeparator);
2244 $contact = $this->createLoggedInUser();
2245 $financialType = $this->callAPISuccess('financial_type', 'create', [
2246 'name' => 'Test taxable financial Type',
2250 $financialAccount = $this->callAPISuccess('financial_account', 'create', [
2251 'name' => 'Test Tax financial account ',
2252 'contact_id' => $contact,
2253 'financial_account_type_id' => 2,
2260 $financialTypeId = $financialType['id'];
2261 $financialAccountId = $financialAccount['id'];
2262 $financialAccountParams = [
2263 'entity_table' => 'civicrm_financial_type',
2264 'entity_id' => $financialTypeId,
2265 'account_relationship' => 10,
2266 'financial_account_id' => $financialAccountId,
2268 CRM_Financial_BAO_FinancialTypeAccount
::add($financialAccountParams);
2270 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'financial_type_id' => $financialTypeId]);
2271 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2272 $contribution1 = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'return' => 'tax_amount', 'sequential' => 1]);
2273 $this->callAPISuccess('contribution', 'completetransaction', [
2274 'id' => $contribution['id'],
2275 'trxn_id' => '777788888',
2276 'fee_amount' => '6.00',
2278 $contribution2 = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'return' => ['tax_amount', 'fee_amount', 'net_amount'], 'sequential' => 1]);
2279 $this->assertEquals($contribution1['values'][0]['tax_amount'], $contribution2['values'][0]['tax_amount']);
2280 $this->assertEquals('6.00', $contribution2['values'][0]['fee_amount']);
2281 $this->assertEquals('99.00', $contribution2['values'][0]['net_amount']);
2285 * Test repeat contribution successfully creates line item.
2287 * @throws \CRM_Core_Exception
2289 public function testRepeatTransaction() {
2290 $originalContribution = $this->setUpRepeatTransaction($recurParams = [], 'single');
2291 $this->callAPISuccess('contribution', 'repeattransaction', [
2292 'original_contribution_id' => $originalContribution['id'],
2293 'contribution_status_id' => 'Completed',
2294 'trxn_id' => uniqid(),
2297 'entity_id' => $originalContribution['id'],
2305 'financial_type_id',
2306 'deductible_amount',
2307 'price_field_value_id',
2311 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2312 'entity_id' => $originalContribution['id'],
2314 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2315 'entity_id' => $originalContribution['id'] +
1,
2317 unset($lineItem1['values'][0]['id'], $lineItem1['values'][0]['entity_id']);
2318 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2319 $this->assertEquals($lineItem1['values'][0], $lineItem2['values'][0]);
2320 $this->_checkFinancialRecords([
2321 'id' => $originalContribution['id'] +
1,
2322 'payment_instrument_id' => $this->callAPISuccessGetValue('PaymentProcessor', [
2323 'id' => $originalContribution['payment_processor_id'],
2324 'return' => 'payment_instrument_id',
2330 * Test repeat contribution successfully creates line items (plural).
2332 * @throws \CRM_Core_Exception
2334 public function testRepeatTransactionLineItems() {
2336 $originalContribution = $this->setUpRepeatTransaction($recurParams = [], 'multiple');
2337 $this->callAPISuccess('contribution', 'repeattransaction', [
2338 'original_contribution_id' => $originalContribution['id'],
2339 'contribution_status_id' => 'Completed',
2340 'trxn_id' => uniqid(),
2344 'entity_id' => $originalContribution['id'],
2352 'financial_type_id',
2353 'deductible_amount',
2354 'price_field_value_id',
2358 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2359 'entity_id' => $originalContribution['id'],
2361 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2362 'entity_id' => $originalContribution['id'] +
1,
2365 // unset id and entity_id for all of them to be able to compare the lineItems:
2366 unset($lineItem1['values'][0]['id'], $lineItem1['values'][0]['entity_id']);
2367 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2368 $this->assertEquals($lineItem1['values'][0], $lineItem2['values'][0]);
2370 unset($lineItem1['values'][1]['id'], $lineItem1['values'][1]['entity_id']);
2371 unset($lineItem2['values'][1]['id'], $lineItem2['values'][1]['entity_id']);
2372 $this->assertEquals($lineItem1['values'][1], $lineItem2['values'][1]);
2374 // CRM-19309 so in future we also want to:
2375 // check that financial_line_items have been created for entity_id 3 and 4;
2377 $this->callAPISuccessGetCount('FinancialItem', ['description' => 'Sales Tax', 'amount' => 0], 0);
2381 * Test repeat contribution successfully creates is_test transaction.
2383 public function testRepeatTransactionIsTest() {
2384 $this->_params
['is_test'] = 1;
2385 $originalContribution = $this->setUpRepeatTransaction(['is_test' => 1], 'single');
2387 $this->callAPISuccess('contribution', 'repeattransaction', [
2388 'original_contribution_id' => $originalContribution['id'],
2389 'contribution_status_id' => 'Completed',
2390 'trxn_id' => uniqid(),
2392 $this->callAPISuccessGetCount('Contribution', ['contribution_test' => 1], 2);
2396 * Test repeat contribution passed in status.
2398 public function testRepeatTransactionPassedInStatus() {
2399 $originalContribution = $this->setUpRepeatTransaction($recurParams = [], 'single');
2401 $this->callAPISuccess('contribution', 'repeattransaction', [
2402 'original_contribution_id' => $originalContribution['id'],
2403 'contribution_status_id' => 'Pending',
2404 'trxn_id' => uniqid(),
2406 $this->callAPISuccessGetCount('Contribution', ['contribution_status_id' => 2], 1);
2410 * Test repeat contribution accepts recur_id instead of original_contribution_id.
2412 public function testRepeatTransactionAcceptRecurID() {
2413 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2414 'contact_id' => $this->_individualId
,
2415 'installments' => '12',
2416 'frequency_interval' => '1',
2418 'contribution_status_id' => 1,
2419 'start_date' => '2012-01-01 00:00:00',
2420 'currency' => 'USD',
2421 'frequency_unit' => 'month',
2422 'payment_processor_id' => $this->paymentProcessorID
,
2424 $this->callAPISuccess('contribution', 'create', array_merge(
2426 ['contribution_recur_id' => $contributionRecur['id']])
2429 $this->callAPISuccess('contribution', 'repeattransaction', [
2430 'contribution_recur_id' => $contributionRecur['id'],
2431 'contribution_status_id' => 'Completed',
2432 'trxn_id' => uniqid(),
2438 * CRM-19873 Test repeattransaction if contribution_recur_id is a test.
2440 * @throws \CRM_Core_Exception
2442 public function testRepeatTransactionTestRecurId() {
2443 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
2444 'contact_id' => $this->_individualId
,
2445 'frequency_interval' => '1',
2447 'contribution_status_id' => 1,
2448 'start_date' => '2017-01-01 00:00:00',
2449 'currency' => 'USD',
2450 'frequency_unit' => 'month',
2451 'payment_processor_id' => $this->paymentProcessorID
,
2454 $this->callAPISuccess('contribution', 'create', array_merge(
2457 'contribution_recur_id' => $contributionRecur['id'],
2462 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2463 'contribution_recur_id' => $contributionRecur['id'],
2464 'contribution_status_id' => 'Completed',
2465 'trxn_id' => 'magic_number',
2468 $this->assertEquals($contributionRecur['values'][1]['is_test'], $repeatedContribution['values'][2]['is_test']);
2472 * CRM-19945 Tests that Contribute.repeattransaction renews a membership when contribution status=Completed
2474 * @throws \CRM_Core_Exception
2476 public function testRepeatTransactionMembershipRenewCompletedContribution() {
2477 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
2479 $contribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
2480 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2481 'contribution_status_id' => 'Failed',
2484 $this->callAPISuccess('membership', 'create', [
2485 'id' => $membership['id'],
2486 'end_date' => 'yesterday',
2487 'status_id' => 'Expired',
2490 $contribution = $this->callAPISuccess('Contribution', 'repeattransaction', [
2491 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2492 'contribution_status_id' => 'Completed',
2493 'trxn_id' => 'bobsled',
2496 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
2497 'id' => $membership['id'],
2498 'return' => 'status_id',
2501 $membership = $this->callAPISuccess('membership', 'get', [
2502 'id' => $membership['id'],
2505 $this->assertEquals('New', CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
2507 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2508 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2509 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2513 * CRM-19945 Tests that Contribute.repeattransaction DOES NOT renew a membership when contribution status=Failed
2515 * @dataProvider contributionStatusProvider
2517 * @throws \CRM_Core_Exception
2519 public function testRepeatTransactionMembershipRenewContributionNotCompleted($contributionStatus) {
2520 // Completed status should renew so we don't test that here
2521 // In Progress status was never actually intended to be available for contributions.
2522 // Partially paid is not valid.
2523 if (in_array($contributionStatus['name'], ['Completed', 'In Progress', 'Partially paid'])) {
2526 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
2528 $this->callAPISuccess('Contribution', 'repeattransaction', [
2529 'original_contribution_id' => $originalContribution['id'],
2530 'contribution_status_id' => 'Completed',
2533 $this->callAPISuccess('membership', 'create', [
2534 'id' => $membership['id'],
2535 'end_date' => 'yesterday',
2536 'status_id' => 'Expired',
2539 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
2540 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
2541 'contribution_status_id' => $contributionStatus['name'],
2542 'trxn_id' => 'bobsled',
2545 $updatedMembership = $this->callAPISuccess('membership', 'getsingle', ['id' => $membership['id']]);
2547 $dateTime = new DateTime('yesterday');
2548 $this->assertEquals($dateTime->format('Y-m-d'), $updatedMembership['end_date']);
2549 $this->assertEquals(CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Expired'), $updatedMembership['status_id']);
2551 $lineItem = $this->callAPISuccessGetSingle('LineItem', ['contribution_id' => $contribution['id']]);
2552 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
2553 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']]);
2557 * Dataprovider provides contribution status as [optionvalue=>contribution_status_name]
2558 * FIXME: buildOptions seems to die in CRM_Core_Config::_construct when in test mode.
2561 * @throws \CiviCRM_API3_Exception
2563 public function contributionStatusProvider() {
2564 $contributionStatuses = civicrm_api3('OptionValue', 'get', [
2565 'return' => ["id", "name"],
2566 'option_group_id' => "contribution_status",
2568 foreach ($contributionStatuses['values'] as $statusName) {
2569 $statuses[] = [$statusName];
2575 * CRM-16397 test appropriate action if total amount has changed for single line items.
2577 public function testRepeatTransactionAlteredAmount() {
2578 $paymentProcessorID = $this->paymentProcessorCreate();
2579 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2580 'contact_id' => $this->_individualId
,
2581 'installments' => '12',
2582 'frequency_interval' => '1',
2584 'contribution_status_id' => 1,
2585 'start_date' => '2012-01-01 00:00:00',
2586 'currency' => 'USD',
2587 'frequency_unit' => 'month',
2588 'payment_processor_id' => $paymentProcessorID,
2590 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2593 'contribution_recur_id' => $contributionRecur['id'],
2597 $this->callAPISuccess('contribution', 'repeattransaction', [
2598 'original_contribution_id' => $originalContribution['id'],
2599 'contribution_status_id' => 'Completed',
2600 'trxn_id' => uniqid(),
2601 'total_amount' => '400',
2606 'entity_id' => $originalContribution['id'],
2614 'financial_type_id',
2615 'deductible_amount',
2616 'price_field_value_id',
2620 $this->callAPISuccessGetSingle('contribution', [
2621 'total_amount' => 400,
2623 'net_amount' => 350,
2625 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2626 'entity_id' => $originalContribution['id'],
2628 $expectedLineItem = array_merge(
2629 $lineItem1['values'][0], [
2630 'line_total' => '400.00',
2631 'unit_price' => '400.00',
2635 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2636 'entity_id' => $originalContribution['id'] +
1,
2639 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2640 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2641 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2645 * CRM-17718 test appropriate action if financial type has changed for single line items.
2647 public function testRepeatTransactionPassedInFinancialType() {
2648 $originalContribution = $this->setUpRecurringContribution();
2650 $this->callAPISuccess('contribution', 'repeattransaction', [
2651 'original_contribution_id' => $originalContribution['id'],
2652 'contribution_status_id' => 'Completed',
2653 'trxn_id' => uniqid(),
2654 'financial_type_id' => 2,
2657 'entity_id' => $originalContribution['id'],
2665 'financial_type_id',
2666 'deductible_amount',
2667 'price_field_value_id',
2672 $this->callAPISuccessGetSingle('contribution', [
2673 'total_amount' => 100,
2674 'financial_type_id' => 2,
2676 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2677 'entity_id' => $originalContribution['id'],
2679 $expectedLineItem = array_merge(
2680 $lineItem1['values'][0], [
2681 'line_total' => '100.00',
2682 'unit_price' => '100.00',
2683 'financial_type_id' => 2,
2684 'contribution_type_id' => 2,
2687 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2688 'entity_id' => $originalContribution['id'] +
1,
2690 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2691 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2692 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2696 * CRM-17718 test appropriate action if financial type has changed for single line items.
2698 public function testRepeatTransactionUpdatedFinancialType() {
2699 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2701 $this->callAPISuccess('contribution', 'repeattransaction', [
2702 'contribution_recur_id' => $originalContribution['id'],
2703 'contribution_status_id' => 'Completed',
2704 'trxn_id' => uniqid(),
2707 'entity_id' => $originalContribution['id'],
2715 'financial_type_id',
2716 'deductible_amount',
2717 'price_field_value_id',
2722 $this->callAPISuccessGetSingle('contribution', [
2723 'total_amount' => 100,
2724 'financial_type_id' => 2,
2726 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2727 'entity_id' => $originalContribution['id'],
2729 $expectedLineItem = array_merge(
2730 $lineItem1['values'][0], [
2731 'line_total' => '100.00',
2732 'unit_price' => '100.00',
2733 'financial_type_id' => 2,
2734 'contribution_type_id' => 2,
2738 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2739 'entity_id' => $originalContribution['id'] +
1,
2741 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2742 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2743 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2747 * CRM-16397 test appropriate action if campaign has been passed in.
2749 public function testRepeatTransactionPassedInCampaign() {
2750 $paymentProcessorID = $this->paymentProcessorCreate();
2751 $campaignID = $this->campaignCreate();
2752 $campaignID2 = $this->campaignCreate();
2753 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2754 'contact_id' => $this->_individualId
,
2755 'installments' => '12',
2756 'frequency_interval' => '1',
2758 'contribution_status_id' => 1,
2759 'start_date' => '2012-01-01 00:00:00',
2760 'currency' => 'USD',
2761 'frequency_unit' => 'month',
2762 'payment_processor_id' => $paymentProcessorID,
2764 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2767 'contribution_recur_id' => $contributionRecur['id'],
2768 'campaign_id' => $campaignID,
2772 $this->callAPISuccess('contribution', 'repeattransaction', [
2773 'original_contribution_id' => $originalContribution['id'],
2774 'contribution_status_id' => 'Completed',
2775 'trxn_id' => uniqid(),
2776 'campaign_id' => $campaignID2,
2779 $this->callAPISuccessGetSingle('contribution', [
2780 'total_amount' => 100,
2781 'campaign_id' => $campaignID2,
2786 * CRM-17718 campaign stored on contribution recur gets priority.
2788 * This reflects the fact we permit people to update them.
2790 public function testRepeatTransactionUpdatedCampaign() {
2791 $paymentProcessorID = $this->paymentProcessorCreate();
2792 $campaignID = $this->campaignCreate();
2793 $campaignID2 = $this->campaignCreate();
2794 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
2795 'contact_id' => $this->_individualId
,
2796 'installments' => '12',
2797 'frequency_interval' => '1',
2799 'contribution_status_id' => 1,
2800 'start_date' => '2012-01-01 00:00:00',
2801 'currency' => 'USD',
2802 'frequency_unit' => 'month',
2803 'payment_processor_id' => $paymentProcessorID,
2804 'campaign_id' => $campaignID,
2806 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
2809 'contribution_recur_id' => $contributionRecur['id'],
2810 'campaign_id' => $campaignID2,
2814 $this->callAPISuccess('contribution', 'repeattransaction', [
2815 'original_contribution_id' => $originalContribution['id'],
2816 'contribution_status_id' => 'Completed',
2817 'trxn_id' => uniqid(),
2820 $this->callAPISuccessGetSingle('contribution', [
2821 'total_amount' => 100,
2822 'campaign_id' => $campaignID,
2827 * CRM-20685 Repeattransaction produces incorrect Financial Type ID (in specific circumstance) - if number of lineItems = 1.
2829 * This case happens when the line item & contribution do not have the same type in his initiating transaction.
2831 public function testRepeatTransactionUpdatedFinancialTypeAndNotEquals() {
2832 $originalContribution = $this->setUpRecurringContribution([], ['financial_type_id' => 2]);
2833 // This will made the trick to get the not equals behaviour.
2834 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 4]);
2835 $this->callAPISuccess('contribution', 'repeattransaction', [
2836 'contribution_recur_id' => $originalContribution['id'],
2837 'contribution_status_id' => 'Completed',
2838 'trxn_id' => uniqid(),
2841 'entity_id' => $originalContribution['id'],
2849 'financial_type_id',
2850 'deductible_amount',
2851 'price_field_value_id',
2855 $this->callAPISuccessGetSingle('contribution', [
2856 'total_amount' => 100,
2857 'financial_type_id' => 2,
2859 $lineItem1 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2860 'entity_id' => $originalContribution['id'],
2862 $expectedLineItem = array_merge(
2863 $lineItem1['values'][0], [
2864 'line_total' => '100.00',
2865 'unit_price' => '100.00',
2866 'financial_type_id' => 4,
2867 'contribution_type_id' => 4,
2871 $lineItem2 = $this->callAPISuccess('line_item', 'get', array_merge($lineItemParams, [
2872 'entity_id' => $originalContribution['id'] +
1,
2874 $this->callAPISuccess('line_item', 'create', ['id' => 1, 'financial_type_id' => 1]);
2875 unset($expectedLineItem['id'], $expectedLineItem['entity_id']);
2876 unset($lineItem2['values'][0]['id'], $lineItem2['values'][0]['entity_id']);
2877 $this->assertEquals($expectedLineItem, $lineItem2['values'][0]);
2881 * Test completing a transaction does not 'mess' with net amount (CRM-15960).
2883 public function testCompleteTransactionNetAmountOK() {
2884 $this->createLoggedInUser();
2885 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2886 unset($params['net_amount']);
2887 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2888 $this->callAPISuccess('contribution', 'completetransaction', [
2889 'id' => $contribution['id'],
2891 $contribution = $this->callAPISuccess('contribution', 'getsingle', ['id' => $contribution['id']]);
2892 $this->assertEquals('Completed', $contribution['contribution_status']);
2893 $this->assertTrue(($contribution['total_amount'] - $contribution['net_amount']) == $contribution['fee_amount']);
2897 * CRM-14151 - Test completing a transaction via the API.
2899 public function testCompleteTransactionWithReceiptDateSet() {
2900 $this->swapMessageTemplateForTestTemplate();
2901 $mut = new CiviMailUtils($this, TRUE);
2902 $this->createLoggedInUser();
2903 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
2904 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2905 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id'], 'trxn_date' => date('Y-m-d')]);
2906 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id'], 'sequential' => 1]);
2907 $this->assertEquals('Completed', $contribution['values'][0]['contribution_status']);
2908 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($contribution['values'][0]['receive_date'])));
2909 $mut->checkMailLog([
2910 'Receipt - Contribution',
2911 'receipt_date:::' . date('Ymd'),
2914 $this->revertTemplateToReservedTemplate();
2918 * CRM-1960 - Test to ensure that completetransaction respects the is_email_receipt setting
2920 public function testCompleteTransactionWithEmailReceiptInput() {
2921 $contributionPage = $this->createReceiptableContributionPage();
2923 $this->_params
['contribution_page_id'] = $contributionPage['id'];
2924 $params = array_merge($this->_params
, ['contribution_status_id' => 2]);
2925 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2926 // Complete the transaction overriding is_email_receipt to = FALSE
2927 $this->callAPISuccess('contribution', 'completetransaction', [
2928 'id' => $contribution['id'],
2929 'trxn_date' => date('2011-04-09'),
2930 'trxn_id' => 'kazam',
2931 'is_email_receipt' => 0,
2933 // Check if a receipt was issued
2934 $receipt_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receipt_date']);
2935 $this->assertEquals('', $receipt_date);
2939 * Test that $is_recur is assigned to the receipt.
2941 public function testCompleteTransactionForRecurring() {
2943 $this->swapMessageTemplateForTestTemplate();
2944 $recurring = $this->setUpRecurringContribution();
2945 $contributionPage = $this->createReceiptableContributionPage(['is_recur' => TRUE, 'recur_frequency_unit' => 'month', 'recur_interval' => 1]);
2947 $this->_params
['contribution_page_id'] = $contributionPage['id'];
2948 $this->_params
['contribution_recur_id'] = $recurring['id'];
2950 $contribution = $this->setUpForCompleteTransaction();
2952 $this->callAPISuccess('contribution', 'completetransaction', [
2953 'id' => $contribution['id'],
2954 'trxn_date' => date('2011-04-09'),
2955 'trxn_id' => 'kazam',
2956 'is_email_receipt' => 1,
2959 $this->mut
->checkMailLog([
2961 'cancelSubscriptionUrl:::' . CIVICRM_UF_BASEURL
,
2964 $this->revertTemplateToReservedTemplate();
2968 * CRM-19710 - Test to ensure that completetransaction respects the input for is_email_receipt setting.
2970 * If passed in it will override the default from contribution page.
2972 public function testCompleteTransactionWithEmailReceiptInputTrue() {
2973 $mut = new CiviMailUtils($this, TRUE);
2974 $this->createLoggedInUser();
2975 // Create a Contribution Page with is_email_receipt = FALSE
2976 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
2977 'receipt_from_name' => 'Mickey Mouse',
2978 'receipt_from_email' => 'mickey@mouse.com',
2979 'title' => "Test Contribution Page",
2980 'financial_type_id' => 1,
2981 'currency' => 'CAD',
2982 'is_monetary' => TRUE,
2983 'is_email_receipt' => 0,
2985 $this->_params
['contribution_page_id'] = $contributionPage['id'];
2986 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
2987 $contribution = $this->callAPISuccess('contribution', 'create', $params);
2988 // Complete the transaction overriding is_email_receipt to = TRUE
2989 $this->callAPISuccess('contribution', 'completetransaction', [
2990 'id' => $contribution['id'],
2991 'is_email_receipt' => 1,
2993 $mut->checkMailLog([
2994 'Contribution Information',
3000 * Complete the transaction using the template with all the possible.
3002 public function testCompleteTransactionWithTestTemplate() {
3003 $this->swapMessageTemplateForTestTemplate();
3004 $contribution = $this->setUpForCompleteTransaction();
3005 $this->callAPISuccess('contribution', 'completetransaction', [
3006 'id' => $contribution['id'],
3007 'trxn_date' => date('2011-04-09'),
3008 'trxn_id' => 'kazam',
3010 $receive_date = $this->callAPISuccess('Contribution', 'getvalue', ['id' => $contribution['id'], 'return' => 'receive_date']);
3011 $this->mut
->checkMailLog([
3012 'email:::anthony_anderson@civicrm.org',
3016 'receive_date:::' . date('Ymd', strtotime($receive_date)),
3017 'receipt_date:::' . date('Ymd'),
3018 'contributeMode:::notify',
3019 'title:::Contribution',
3020 'displayName:::Mr. Anthony Anderson II',
3022 'contactID:::' . $this->_params
['contact_id'],
3023 'contributionID:::' . $contribution['id'],
3024 'financialTypeId:::1',
3025 'financialTypeName:::Donation',
3028 $this->revertTemplateToReservedTemplate();
3032 * Complete the transaction using the template with all the possible.
3034 public function testCompleteTransactionContributionPageFromAddress() {
3035 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', [
3036 'receipt_from_name' => 'Mickey Mouse',
3037 'receipt_from_email' => 'mickey@mouse.com',
3038 'title' => "Test Contribution Page",
3039 'financial_type_id' => 1,
3040 'currency' => 'NZD',
3041 'goal_amount' => 50,
3042 'is_pay_later' => 1,
3043 'is_monetary' => TRUE,
3044 'is_email_receipt' => TRUE,
3046 $this->_params
['contribution_page_id'] = $contributionPage['id'];
3047 $contribution = $this->setUpForCompleteTransaction();
3048 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $contribution['id']]);
3049 $this->mut
->checkMailLog([
3057 * Test completing first transaction in a recurring series.
3059 * The status should be set to 'in progress' and the next scheduled payment date calculated.
3061 * @dataProvider getScheduledDateData
3063 * @param array $dataSet
3065 * @throws \Exception
3067 public function testCompleteTransactionSetStatusToInProgress($dataSet) {
3068 $paymentProcessorID = $this->paymentProcessorCreate();
3069 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
3070 'contact_id' => $this->_individualId
,
3071 'installments' => '2',
3072 'frequency_interval' => '1',
3074 'contribution_status_id' => 'Pending',
3075 'start_date' => '2012-01-01 00:00:00',
3076 'currency' => 'USD',
3077 'frequency_unit' => 'month',
3078 'payment_processor_id' => $paymentProcessorID,
3079 ], $dataSet['data']));
3080 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
3083 'contribution_recur_id' => $contributionRecur['id'],
3084 'contribution_status_id' => 'Pending',
3085 'receive_date' => $dataSet['receive_date'],
3088 $this->callAPISuccess('Contribution', 'completetransaction', [
3089 'id' => $contribution,
3090 'receive_date' => $dataSet['receive_date'],
3092 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3093 'id' => $contributionRecur['id'],
3094 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
3096 $this->assertEquals(5, $contributionRecur['contribution_status_id']);
3097 $this->assertEquals($dataSet['expected'], $contributionRecur['next_sched_contribution_date']);
3098 $this->callAPISuccess('Contribution', 'create', array_merge(
3101 'contribution_recur_id' => $contributionRecur['id'],
3102 'contribution_status_id' => 'Completed',
3105 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
3106 'id' => $contributionRecur['id'],
3107 'return' => ['contribution_status_id'],
3109 $this->assertEquals(1, $contributionRecur['contribution_status_id']);
3113 * Get dates for testing.
3117 public function getScheduledDateData() {
3119 $result[]['2016-08-31-1-month'] = [
3121 'start_date' => '2016-08-31',
3122 'frequency_interval' => 1,
3123 'frequency_unit' => 'month',
3125 'receive_date' => '2016-08-31',
3126 'expected' => '2016-10-01 00:00:00',
3128 $result[]['2012-01-01-1-month'] = [
3130 'start_date' => '2012-01-01',
3131 'frequency_interval' => 1,
3132 'frequency_unit' => 'month',
3134 'receive_date' => '2012-01-01',
3135 'expected' => '2012-02-01 00:00:00',
3137 $result[]['2012-01-01-1-month'] = [
3139 'start_date' => '2012-01-01',
3140 'frequency_interval' => 1,
3141 'frequency_unit' => 'month',
3143 'receive_date' => '2012-02-29',
3144 'expected' => '2012-03-29 00:00:00',
3146 $result['receive_date_includes_time']['2012-01-01-1-month'] = [
3148 'start_date' => '2012-01-01',
3149 'frequency_interval' => 1,
3150 'frequency_unit' => 'month',
3151 'next_sched_contribution_date' => '2012-02-29',
3153 'receive_date' => '2012-02-29 16:00:00',
3154 'expected' => '2012-03-29 00:00:00',
3160 * Test completing a pledge with the completeTransaction api..
3162 * Note that we are creating a logged in user because email goes out from
3165 public function testCompleteTransactionUpdatePledgePayment() {
3166 $this->swapMessageTemplateForTestTemplate();
3167 $mut = new CiviMailUtils($this, TRUE);
3168 $mut->clearMessages();
3169 $this->createLoggedInUser();
3170 $contributionID = $this->createPendingPledgeContribution();
3171 $this->callAPISuccess('contribution', 'completetransaction', [
3172 'id' => $contributionID,
3173 'trxn_date' => '1 Feb 2013',
3175 $pledge = $this->callAPISuccessGetSingle('Pledge', [
3176 'id' => $this->_ids
['pledge'],
3178 $this->assertEquals('Completed', $pledge['pledge_status']);
3180 $status = $this->callAPISuccessGetValue('PledgePayment', [
3181 'pledge_id' => $this->_ids
['pledge'],
3182 'return' => 'status_id',
3184 $this->assertEquals(1, $status);
3185 $mut->checkMailLog([
3187 'receive_date:::20130201000000',
3188 "receipt_date:::\n",
3191 $this->revertTemplateToReservedTemplate();
3195 * Test completing a transaction with an event via the API.
3197 * Note that we are creating a logged in user because email goes out from
3200 * @throws \CRM_Core_Exception
3202 public function testCompleteTransactionWithParticipantRecord() {
3203 $mut = new CiviMailUtils($this, TRUE);
3204 $mut->clearMessages();
3205 $this->_individualId
= $this->createLoggedInUser();
3206 $contributionID = $this->createPendingParticipantContribution();
3207 $this->createJoinedProfile(['entity_id' => $this->_ids
['event']['test'], 'entity_table' => 'civicrm_event']);
3208 $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']);
3209 $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']);
3210 $this->eliminateUFGroupOne();
3212 $this->callAPISuccess('contribution', 'completetransaction', [
3213 'id' => $contributionID,
3216 $participantStatus = $this->callAPISuccessGetValue('participant', [
3217 'id' => $this->_ids
['participant'],
3218 'return' => 'participant_status_id',
3220 $this->assertEquals(1, $participantStatus);
3222 //Assert only three activities are created.
3223 $activities = $this->callAPISuccess('Activity', 'get', [
3224 'contact_id' => $this->_individualId
,
3227 $this->assertCount(3, $activities);
3228 $activityNames = array_count_values(CRM_Utils_Array
::collect('activity_name', $activities));
3229 // record two activities before and after completing payment for Event registration
3230 $this->assertEquals(2, $activityNames['Event Registration']);
3231 // update the original 'Contribution' activity created after completing payment
3232 $this->assertEquals(1, $activityNames['Contribution']);
3234 $mut->checkMailLog([
3235 'Annual CiviCRM meet',
3237 'This is a confirmation that your registration has been received and your status has been updated to Registered.',
3238 'First Name: Logged In',
3242 ], ['Back end title', 'title_post_2', 'title_post_3']);
3247 * Test membership is renewed when transaction completed.
3249 public function testCompleteTransactionMembershipPriceSet() {
3250 $this->createPriceSetWithPage('membership');
3251 $stateOfGrace = $this->callAPISuccess('MembershipStatus', 'getvalue', [
3255 $this->setUpPendingContribution($this->_ids
['price_field_value'][0]);
3256 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3257 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3258 'membership_id' => $this->_ids
['membership'],
3260 $this->assertEquals(1, $logs['count']);
3261 $this->assertEquals($stateOfGrace, $membership['status_id']);
3262 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $this->_ids
['contribution']]);
3263 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3264 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 year')), $membership['end_date']);
3265 $this->callAPISuccessGetSingle('LineItem', [
3266 'entity_id' => $this->_ids
['membership'],
3267 'entity_table' => 'civicrm_membership',
3269 $logs = $this->callAPISuccess('MembershipLog', 'get', [
3270 'membership_id' => $this->_ids
['membership'],
3272 $this->assertEquals(2, $logs['count']);
3273 $this->assertNotEquals($stateOfGrace, $logs['values'][2]['status_id']);
3274 //Assert only three activities are created.
3275 $activities = CRM_Activity_BAO_Activity
::getContactActivity($this->_ids
['contact']);
3276 $this->assertEquals(3, count($activities));
3277 $activityNames = array_flip(CRM_Utils_Array
::collect('activity_name', $activities));
3278 $this->assertArrayHasKey('Contribution', $activityNames);
3279 $this->assertArrayHasKey('Membership Signup', $activityNames);
3280 $this->assertArrayHasKey('Change Membership Status', $activityNames);
3281 $this->cleanUpAfterPriceSets();
3285 * Test if renewal activity is create after changing Pending contribution to Completed via offline
3287 public function testPendingToCompleteContribution() {
3288 $this->createPriceSetWithPage('membership');
3289 $this->setUpPendingContribution($this->_ids
['price_field_value'][0]);
3290 $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3291 // Case 1: Assert that Membership Signup Activity is created on Pending to Completed Contribution via backoffice
3292 $activity = $this->callAPISuccess('Activity', 'get', [
3293 'activity_type_id' => 'Membership Signup',
3294 'source_record_id' => $this->_ids
['membership'],
3295 'status_id' => 'Scheduled',
3297 $this->assertEquals(1, $activity['count']);
3299 // change pending contribution to completed
3300 $form = new CRM_Contribute_Form_Contribution();
3303 'id' => $this->_ids
['contribution'],
3304 'total_amount' => 20,
3307 'financial_type_id' => 1,
3308 'contact_id' => $this->_individualId
,
3309 'contribution_status_id' => 1,
3310 'billing_middle_name' => '',
3311 'billing_last_name' => 'Adams',
3312 'billing_street_address-5' => '790L Lincoln St S',
3313 'billing_city-5' => 'Maryknoll',
3314 'billing_state_province_id-5' => 1031,
3315 'billing_postal_code-5' => 10545,
3316 'billing_country_id-5' => 1228,
3317 'frequency_interval' => 1,
3318 'frequency_unit' => 'month',
3319 'installments' => '',
3320 'hidden_AdditionalDetail' => 1,
3321 'hidden_Premium' => 1,
3322 'from_email_address' => '"civi45" <civi45@civicrm.com>',
3323 'receipt_date' => '',
3324 'receipt_date_time' => '',
3325 'payment_processor_id' => $this->paymentProcessorID
,
3326 'currency' => 'USD',
3327 'contribution_page_id' => $this->_ids
['contribution_page'],
3328 'contribution_mode' => 'membership',
3329 'source' => 'Membership Signup and Renewal',
3332 $form->testSubmit($form->_params
, CRM_Core_Action
::UPDATE
);
3334 // Case 2: After successful payment for Pending backoffice there are three activities created
3335 // 2.a Update status of existing Scheduled Membership Signup (created in step 1) to Completed
3336 $activity = $this->callAPISuccess('Activity', 'get', [
3337 'activity_type_id' => 'Membership Signup',
3338 'source_record_id' => $this->_ids
['membership'],
3339 'status_id' => 'Completed',
3341 $this->assertEquals(1, $activity['count']);
3342 // 2.b Contribution activity created to record successful payment
3343 $activity = $this->callAPISuccess('Activity', 'get', [
3344 'activity_type_id' => 'Contribution',
3345 'source_record_id' => $this->_ids
['contribution'],
3346 'status_id' => 'Completed',
3348 $this->assertEquals(1, $activity['count']);
3350 // 2.c 'Change membership type' activity created to record Membership status change from Grace to Current
3351 $activity = $this->callAPISuccess('Activity', 'get', [
3352 'activity_type_id' => 'Change Membership Status',
3353 'source_record_id' => $this->_ids
['membership'],
3354 'status_id' => 'Completed',
3356 $this->assertEquals(1, $activity['count']);
3357 $this->assertEquals('Status changed from Grace to Current', $activity['values'][$activity['id']]['subject']);
3359 //Create another pending contribution for renewal
3360 $contribution = $this->callAPISuccess('contribution', 'create', [
3362 'contact_id' => $this->_ids
['contact'],
3363 'receive_date' => date('Ymd'),
3364 'total_amount' => 20.00,
3365 'financial_type_id' => 1,
3366 'payment_instrument_id' => 'Credit Card',
3367 'non_deductible_amount' => 10.00,
3368 'trxn_id' => 'rdhfi88',
3369 'invoice_id' => 'dofhiewuyr',
3371 'contribution_status_id' => 2,
3372 'contribution_page_id' => $this->_ids
['contribution_page'],
3373 // We can't rely on contribution api to link line items correctly to membership
3374 'skipLineItem' => TRUE,
3375 'api.membership_payment.create' => ['membership_id' => $this->_ids
['membership']],
3378 $this->callAPISuccess('line_item', 'create', [
3379 'entity_id' => $contribution['id'],
3380 'entity_table' => 'civicrm_contribution',
3381 'contribution_id' => $contribution['id'],
3382 'price_field_id' => $this->_ids
['price_field'][0],
3386 'financial_type_id' => 1,
3387 'price_field_value_id' => $this->_ids
['price_field_value']['cont'],
3389 $this->callAPISuccess('line_item', 'create', [
3390 'entity_id' => $this->_ids
['membership'],
3391 'entity_table' => 'civicrm_membership',
3392 'contribution_id' => $contribution['id'],
3393 'price_field_id' => $this->_ids
['price_field'][0],
3397 'financial_type_id' => 1,
3398 'price_field_value_id' => $this->_ids
['price_field_value'][0],
3399 'membership_type_id' => $this->_ids
['membership_type'],
3402 //Update it to Failed.
3403 $form->_params
['id'] = $contribution['id'];
3404 $form->_params
['contribution_status_id'] = 4;
3406 $form->testSubmit($form->_params
, CRM_Core_Action
::UPDATE
);
3407 //Existing membership should not get updated to expired.
3408 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3409 $this->assertNotEquals($membership['status_id'], 4);
3413 * Test membership is renewed when transaction completed.
3415 public function testCompleteTransactionMembershipPriceSetTwoTerms() {
3416 $this->createPriceSetWithPage('membership');
3417 $this->setUpPendingContribution($this->_ids
['price_field_value'][1]);
3418 $this->callAPISuccess('contribution', 'completetransaction', ['id' => $this->_ids
['contribution']]);
3419 $membership = $this->callAPISuccess('membership', 'getsingle', ['id' => $this->_ids
['membership']]);
3420 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 2 years')), $membership['end_date']);
3421 $this->cleanUpAfterPriceSets();
3424 public function cleanUpAfterPriceSets() {
3425 $this->quickCleanUpFinancialEntities();
3426 $this->contactDelete($this->_ids
['contact']);
3430 * Set up a pending transaction with a specific price field id.
3432 * @param int $priceFieldValueID
3433 * @param array $contriParams
3435 public function setUpPendingContribution($priceFieldValueID, $contriParams = []) {
3436 $contactID = $this->individualCreate();
3437 $membership = $this->callAPISuccess('membership', 'create', [
3438 'contact_id' => $contactID,
3439 'membership_type_id' => $this->_ids
['membership_type'],
3440 'start_date' => 'yesterday - 1 year',
3441 'end_date' => 'yesterday',
3442 'join_date' => 'yesterday - 1 year',
3444 $contribution = $this->callAPISuccess('contribution', 'create', array_merge([
3446 'contact_id' => $contactID,
3447 'receive_date' => date('Ymd'),
3448 'total_amount' => 20.00,
3449 'financial_type_id' => 1,
3450 'payment_instrument_id' => 'Credit Card',
3451 'non_deductible_amount' => 10.00,
3452 'trxn_id' => 'jdhfi' . rand(1, 100),
3453 'invoice_id' => 'djfhiew' . rand(5, 100),
3455 'contribution_status_id' => 2,
3456 'contribution_page_id' => $this->_ids
['contribution_page'],
3457 'api.membership_payment.create' => ['membership_id' => $membership['id']],
3460 $this->callAPISuccess('line_item', 'create', [
3461 'entity_id' => $contribution['id'],
3462 'entity_table' => 'civicrm_contribution',
3463 'contribution_id' => $contribution['id'],
3464 'price_field_id' => $this->_ids
['price_field'][0],
3468 'financial_type_id' => 1,
3469 'price_field_value_id' => $priceFieldValueID,
3471 $this->_ids
['contact'] = $contactID;
3472 $this->_ids
['contribution'] = $contribution['id'];
3473 $this->_ids
['membership'] = $membership['id'];
3477 * Test sending a mail via the API.
3479 * @throws \CRM_Core_Exception
3480 * @throws \CiviCRM_API3_Exception
3482 public function testSendMail() {
3483 $mut = new CiviMailUtils($this, TRUE);
3484 $orderParams = $this->_params
;
3485 $orderParams['contribution_status_id'] = 'Pending';
3486 $orderParams['api.PaymentProcessor.pay'] = [
3487 'payment_processor_id' => $this->paymentProcessorID
,
3488 'credit_card_type' => 'Visa',
3489 'credit_card_number' => 41111111111111,
3493 $order = $this->callAPISuccess('Order', 'create', $orderParams);
3494 $this->callAPISuccess('Payment', 'create', ['total_amount' => 5, 'is_send_notification' => 0, 'order_id' => $order['id']]);
3495 $address = $this->callAPISuccess('Address', 'create', ['contribution_id' => $order['id'], 'name' => 'bob', 'contact_id' => 1, 'street_address' => 'blah']);
3496 $this->callAPISuccess('Contribution', 'create', ['id' => $order['id'], 'address_id' => $address['id']]);
3497 $this->callAPISuccess('contribution', 'sendconfirmation', [
3498 'id' => $order['id'],
3499 'receipt_from_email' => 'api@civicrm.org',
3501 $mut->checkMailLog([
3503 'Contribution Information',
3508 $this->checkCreditCardDetails($mut, $order['id']);
3510 $tplVars = CRM_Core_Smarty
::singleton()->get_template_vars();
3511 $this->assertEquals('bob', $tplVars['billingName']);
3512 $this->assertEquals("bob\nblah\n", $tplVars['address']);
3516 * Test sending a mail via the API.
3517 * This simulates webform_civicrm using pay later contribution page
3519 public function testSendconfirmationPayLater() {
3520 $mut = new CiviMailUtils($this, TRUE);
3522 // Create contribution page
3524 'title' => 'Webform Contributions',
3525 'financial_type_id' => 1,
3526 'contribution_type_id' => 1,
3527 'is_confirm_enabled' => 1,
3528 'is_pay_later' => 1,
3529 'pay_later_text' => 'I will send payment by cheque',
3530 'pay_later_receipt' => 'Send your cheque payable to "CiviCRM LLC" to the office',
3532 $contributionPage = $this->callAPISuccess('contribution_page', 'create', $pageParams);
3534 // Create pay later contribution
3536 'contact_id' => $this->_individualId
,
3537 'financial_type_id' => 1,
3538 'is_pay_later' => 1,
3539 'contribution_status_id' => 2,
3540 'contribution_page_id' => $contributionPage['id'],
3541 'total_amount' => '10.00',
3543 $contribution = $this->callAPISuccess('contribution', 'create', $contribParams);
3547 'contribution_id' => $contribution['id'],
3548 'entity_id' => $contribution['id'],
3549 'entity_table' => 'civicrm_contribution',
3550 'label' => 'My lineitem label',
3552 'unit_price' => "10.00",
3553 'line_total' => "10.00",
3555 $lineItem = $this->callAPISuccess('lineItem', 'create', $lineItemParams);
3559 civicrm_api3('contribution', 'sendconfirmation', [
3560 'id' => $contribution['id'],
3561 'receipt_from_email' => 'api@civicrm.org',
3564 catch (Exception
$e) {
3565 // Need to figure out how to stop this some other day
3566 // We don't care about the Payment Processor because this is Pay Later
3567 // The point of this test is to check we get the pay_later version of the mail
3568 if ($e->getMessage() != "Undefined variable: CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage") {
3573 // Retrieve mail & check it has the pay_later_receipt info
3574 $mut->getMostRecentEmail('raw');
3575 $mut->checkMailLog([
3576 (string) $contribParams['total_amount'],
3577 $pageParams['pay_later_receipt'],
3585 * Check credit card details in sent mail via API
3587 * @param CiviMailUtils $mut
3588 * @param int $contributionID Contribution ID
3590 * @throws \CRM_Core_Exception
3592 public function checkCreditCardDetails($mut, $contributionID) {
3593 $this->callAPISuccess('contribution', 'create', $this->_params
);
3594 $this->callAPISuccess('contribution', 'sendconfirmation', [
3595 'id' => $contributionID,
3596 'receipt_from_email' => 'api@civicrm.org',
3597 'payment_processor_id' => $this->paymentProcessorID
,
3599 $mut->checkMailLog([
3601 'Billing Name and Address',
3603 'anthony_anderson@civicrm.org',
3610 * Test sending a mail via the API.
3612 public function testSendMailEvent() {
3613 $mut = new CiviMailUtils($this, TRUE);
3614 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
3615 $event = $this->eventCreate([
3616 'is_email_confirm' => 1,
3617 'confirm_from_email' => 'test@civicrm.org',
3619 $this->_eventID
= $event['id'];
3620 $participantParams = [
3621 'contact_id' => $this->_individualId
,
3622 'event_id' => $this->_eventID
,
3625 // to ensure it matches later on
3626 'register_date' => '2007-07-21 00:00:00',
3627 'source' => 'Online Event Registration: API Testing',
3630 $participant = $this->callAPISuccess('participant', 'create', $participantParams);
3631 $this->callAPISuccess('participant_payment', 'create', [
3632 'participant_id' => $participant['id'],
3633 'contribution_id' => $contribution['id'],
3635 $this->callAPISuccess('contribution', 'sendconfirmation', [
3636 'id' => $contribution['id'],
3637 'receipt_from_email' => 'api@civicrm.org',
3640 $mut->checkMailLog([
3641 'Annual CiviCRM meet',
3643 'To: "Mr. Anthony Anderson II" <anthony_anderson@civicrm.org>',
3649 * This function does a GET & compares the result against the $params.
3651 * Use as a double check on Creates.
3653 * @param array $params
3655 * @param bool $delete
3657 public function contributionGetnCheck($params, $id, $delete = TRUE) {
3659 $contribution = $this->callAPISuccess('Contribution', 'Get', [
3664 $this->callAPISuccess('contribution', 'delete', ['id' => $id]);
3666 $this->assertAPISuccess($contribution, 0);
3667 $values = $contribution['values'][$contribution['id']];
3668 $params['receive_date'] = date('Y-m-d H:i:s', strtotime($params['receive_date']));
3669 // this is not returned in id format
3670 unset($params['payment_instrument_id']);
3671 $params['contribution_source'] = $params['source'];
3672 unset($params['source']);
3673 foreach ($params as $key => $value) {
3674 $this->assertEquals($value, $values[$key], $key . " value: $value doesn't match " . print_r($values, TRUE));
3679 * Create a pending contribution & linked pending pledge record.
3681 public function createPendingPledgeContribution() {
3683 $pledgeID = $this->pledgeCreate(['contact_id' => $this->_individualId
, 'installments' => 1, 'amount' => 500]);
3684 $this->_ids
['pledge'] = $pledgeID;
3685 $contribution = $this->callAPISuccess('contribution', 'create', array_merge($this->_params
, [
3686 'contribution_status_id' => 'Pending',
3687 'total_amount' => 500,
3689 $paymentID = $this->callAPISuccessGetValue('PledgePayment', [
3690 'options' => ['limit' => 1],
3693 $this->callAPISuccess('PledgePayment', 'create', [
3695 'contribution_id' =>
3696 $contribution['id'],
3697 'status_id' => 'Pending',
3698 'scheduled_amount' => 500,
3701 return $contribution['id'];
3705 * Create a pending contribution & linked pending participant record (along with an event).
3707 public function createPendingParticipantContribution() {
3708 $this->_ids
['event']['test'] = $this->eventCreate(['is_email_confirm' => 1, 'confirm_from_email' => 'test@civicrm.org'])['id'];
3709 $participantID = $this->participantCreate(['event_id' => $this->_ids
['event']['test'], 'status_id' => 6, 'contact_id' => $this->_individualId
]);
3710 $this->_ids
['participant'] = $participantID;
3711 $params = array_merge($this->_params
, ['contact_id' => $this->_individualId
, 'contribution_status_id' => 2, 'financial_type_id' => 'Event Fee']);
3712 $contribution = $this->callAPISuccess('contribution', 'create', $params);
3713 $this->callAPISuccess('participant_payment', 'create', [
3714 'contribution_id' => $contribution['id'],
3715 'participant_id' => $participantID,
3717 $this->callAPISuccess('line_item', 'get', [
3718 'entity_id' => $contribution['id'],
3719 'entity_table' => 'civicrm_contribution',
3720 'api.line_item.create' => [
3721 'entity_id' => $participantID,
3722 'entity_table' => 'civicrm_participant',
3725 return $contribution['id'];
3729 * Get financial transaction amount.
3731 * @param int $contId
3733 * @return null|string
3735 public function _getFinancialTrxnAmount($contId) {
3737 SUM( ft.total_amount ) AS total
3738 FROM civicrm_financial_trxn AS ft
3739 LEFT JOIN civicrm_entity_financial_trxn AS ceft ON ft.id = ceft.financial_trxn_id
3740 WHERE ceft.entity_table = 'civicrm_contribution'
3741 AND ceft.entity_id = {$contId}";
3743 $result = CRM_Core_DAO
::singleValueQuery($query);
3748 * @param int $contId
3750 * @return null|string
3752 public function _getFinancialItemAmount($contId) {
3753 $lineItem = key(CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution'));
3756 FROM civicrm_financial_item
3757 WHERE entity_table = 'civicrm_line_item'
3758 AND entity_id = {$lineItem}";
3759 $result = CRM_Core_DAO
::singleValueQuery($query);
3764 * @param int $contId
3767 public function _checkFinancialItem($contId, $context) {
3768 if ($context != 'paylater') {
3770 'entity_id' => $contId,
3771 'entity_table' => 'civicrm_contribution',
3773 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($params, TRUE));
3775 'financial_trxn_id' => $trxn['financial_trxn_id'],
3776 'entity_table' => 'civicrm_financial_item',
3778 $entityTrxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3780 'id' => $entityTrxn['entity_id'],
3783 if ($context == 'paylater') {
3784 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution');
3785 foreach ($lineItems as $key => $item) {
3787 'entity_id' => $key,
3788 'entity_table' => 'civicrm_line_item',
3790 $compareParams = ['status_id' => 1];
3791 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3794 elseif ($context == 'refund') {
3797 'financial_account_id' => 1,
3801 elseif ($context == 'cancelPending') {
3804 'financial_account_id' => 1,
3808 elseif ($context == 'changeFinancial') {
3809 $lineKey = key(CRM_Price_BAO_LineItem
::getLineItems($contId, 'contribution'));
3811 'entity_id' => $lineKey,
3815 'financial_account_id' => 1,
3817 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3819 'financial_account_id' => 3,
3820 'entity_id' => $lineKey,
3826 if ($context != 'paylater') {
3827 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialItem', $params, $compareParams);
3832 * Check correct financial transaction entries were created for the change in payment instrument.
3834 * @param int $contributionID
3835 * @param int $originalInstrumentID
3836 * @param int $newInstrumentID
3837 * @param int $amount
3839 public function checkFinancialTrxnPaymentInstrumentChange($contributionID, $originalInstrumentID, $newInstrumentID, $amount = 100) {
3841 $entityFinancialTrxns = $this->getFinancialTransactionsForContribution($contributionID);
3843 $originalTrxnParams = [
3844 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($originalInstrumentID),
3845 'payment_instrument_id' => $originalInstrumentID,
3846 'amount' => $amount,
3850 $reversalTrxnParams = [
3851 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($originalInstrumentID),
3852 'payment_instrument_id' => $originalInstrumentID,
3853 'amount' => -$amount,
3858 'to_financial_account_id' => CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($newInstrumentID),
3859 'payment_instrument_id' => $newInstrumentID,
3860 'amount' => $amount,
3864 foreach ([$originalTrxnParams, $reversalTrxnParams, $newTrxnParams] as $index => $transaction) {
3865 $entityFinancialTrxn = $entityFinancialTrxns[$index];
3866 $this->assertEquals($entityFinancialTrxn['amount'], $transaction['amount']);
3868 $financialTrxn = $this->callAPISuccessGetSingle('FinancialTrxn', [
3869 'id' => $entityFinancialTrxn['financial_trxn_id'],
3871 $this->assertEquals($transaction['status_id'], $financialTrxn['status_id']);
3872 $this->assertEquals($transaction['amount'], $financialTrxn['total_amount']);
3873 $this->assertEquals($transaction['amount'], $financialTrxn['net_amount']);
3874 $this->assertEquals(0, $financialTrxn['fee_amount']);
3875 $this->assertEquals($transaction['payment_instrument_id'], $financialTrxn['payment_instrument_id']);
3876 $this->assertEquals($transaction['to_financial_account_id'], $financialTrxn['to_financial_account_id']);
3879 $this->assertEquals(1, $financialTrxn['is_payment']);
3880 $this->assertEquals('USD', $financialTrxn['currency']);
3881 $this->assertEquals(date('Y-m-d'), date('Y-m-d', strtotime($financialTrxn['trxn_date'])));
3886 * Check financial transaction.
3888 * @todo break this down into sensible functions - most calls to it only use a few lines out of the big if.
3890 * @param array $contribution
3891 * @param string $context
3892 * @param int $instrumentId
3893 * @param array $extraParams
3895 public function _checkFinancialTrxn($contribution, $context, $instrumentId = NULL, $extraParams = []) {
3896 $financialTrxns = $this->getFinancialTransactionsForContribution($contribution['id']);
3897 $trxn = array_pop($financialTrxns);
3900 'id' => $trxn['financial_trxn_id'],
3902 if ($context == 'payLater') {
3905 'from_financial_account_id' => CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount($contribution['financial_type_id'], 'Accounts Receivable Account is'),
3908 elseif ($context == 'refund') {
3910 'to_financial_account_id' => 6,
3911 'total_amount' => -100,
3913 'trxn_date' => '2015-01-01 09:00:00',
3914 'trxn_id' => 'the refund',
3917 elseif ($context == 'cancelPending') {
3919 'to_financial_account_id' => 7,
3920 'total_amount' => -100,
3924 elseif ($context == 'changeFinancial' ||
$context == 'paymentInstrument') {
3925 // @todo checkFinancialTrxnPaymentInstrumentChange instead for paymentInstrument.
3926 // It does the same thing with greater readability.
3927 // @todo remove handling for
3930 'entity_id' => $contribution['id'],
3931 'entity_table' => 'civicrm_contribution',
3934 $trxn = current(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($entityParams));
3936 'id' => $trxn['financial_trxn_id'],
3938 if (empty($extraParams)) {
3940 'total_amount' => -100,
3944 elseif ($context !== 'changeFinancial') {
3946 'total_amount' => 100,
3950 if ($context == 'paymentInstrument') {
3951 $compareParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount
::getInstrumentFinancialAccount($instrumentId);
3952 $compareParams['payment_instrument_id'] = $instrumentId;
3955 $compareParams['to_financial_account_id'] = 12;
3957 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $trxnParams1, array_merge($compareParams, $extraParams));
3958 $compareParams['total_amount'] = 100;
3959 // Reverse the extra params now that we will be checking the new positive transaction.
3960 if ($context === 'changeFinancial' && !empty($extraParams)) {
3961 foreach ($extraParams as $param => $value) {
3962 $extraParams[$param] = 0 - $value;
3967 $this->assertDBCompareValues('CRM_Financial_DAO_FinancialTrxn', $params, array_merge($compareParams, $extraParams));
3973 public function _addPaymentInstrument() {
3974 $gId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup', 'payment_instrument', 'id', 'name');
3976 'option_group_id' => $gId,
3977 'label' => 'Test Card',
3978 'name' => 'Test Card',
3983 $optionValue = $this->callAPISuccess('option_value', 'create', $optionParams);
3984 $relationTypeId = key(CRM_Core_PseudoConstant
::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
3985 $financialParams = [
3986 'entity_table' => 'civicrm_option_value',
3987 'entity_id' => $optionValue['id'],
3988 'account_relationship' => $relationTypeId,
3989 'financial_account_id' => 7,
3991 CRM_Financial_BAO_FinancialTypeAccount
::add($financialParams);
3992 $this->assertNotEmpty($optionValue['values'][$optionValue['id']]['value']);
3993 return $optionValue['values'][$optionValue['id']]['value'];
3996 public function _deletedAddedPaymentInstrument() {
3997 $result = $this->callAPISuccess('OptionValue', 'get', [
3998 'option_group_id' => 'payment_instrument',
3999 'name' => 'Test Card',
4003 if ($id = CRM_Utils_Array
::value('id', $result)) {
4004 $this->callAPISuccess('OptionValue', 'delete', ['id' => $id]);
4009 * Set up the basic recurring contribution for tests.
4011 * @param array $generalParams
4012 * Parameters that can be merged into the recurring AND the contribution.
4014 * @param array $recurParams
4015 * Parameters to merge into the recur only.
4019 protected function setUpRecurringContribution($generalParams = [], $recurParams = []) {
4020 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4021 'contact_id' => $this->_individualId
,
4022 'installments' => '12',
4023 'frequency_interval' => '1',
4025 'contribution_status_id' => 1,
4026 'start_date' => '2012-01-01 00:00:00',
4027 'currency' => 'USD',
4028 'frequency_unit' => 'month',
4029 'payment_processor_id' => $this->paymentProcessorID
,
4030 ], $generalParams, $recurParams));
4031 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4034 'contribution_recur_id' => $contributionRecur['id'],
4037 return $originalContribution;
4041 * Set up a basic auto-renew membership for tests.
4043 * @param array $generalParams
4044 * Parameters that can be merged into the recurring AND the contribution.
4046 * @param array $recurParams
4047 * Parameters to merge into the recur only.
4050 * @throws \CRM_Core_Exception
4052 protected function setUpAutoRenewMembership($generalParams = [], $recurParams = []) {
4053 $newContact = $this->callAPISuccess('Contact', 'create', [
4054 'contact_type' => 'Individual',
4055 'sort_name' => 'McTesterson, Testy',
4056 'display_name' => 'Testy McTesterson',
4057 'preferred_language' => 'en_US',
4058 'preferred_mail_format' => 'Both',
4059 'first_name' => 'Testy',
4060 'last_name' => 'McTesterson',
4061 'contact_is_deleted' => '0',
4063 'email' => 'tmctesterson@example.com',
4066 $membershipType = $this->callAPISuccess('MembershipType', 'create', [
4067 'domain_id' => 'Default Domain Name',
4068 'member_of_contact_id' => 1,
4069 'financial_type_id' => 'Member Dues',
4070 'duration_unit' => 'month',
4071 'duration_interval' => 1,
4072 'period_type' => 'rolling',
4073 'name' => 'Standard Member',
4074 'minimum_fee' => 100,
4076 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4077 'contact_id' => $newContact['id'],
4078 'installments' => '12',
4079 'frequency_interval' => '1',
4081 'contribution_status_id' => 1,
4082 'start_date' => '2012-01-01 00:00:00',
4083 'currency' => 'USD',
4084 'frequency_unit' => 'month',
4085 'payment_processor_id' => $this->paymentProcessorID
,
4086 ], $generalParams, $recurParams));
4088 $membership = $this->callAPISuccess('membership', 'create', [
4089 'contact_id' => $newContact['id'],
4090 'contribution_recur_id' => $contributionRecur['id'],
4091 'financial_type_id' => "Member Dues",
4092 'membership_type_id' => $membershipType['id'],
4094 'skipLineItem' => TRUE,
4097 CRM_Price_BAO_LineItem
::getLineItemArray($this->_params
, NULL, 'membership', $membershipType['id']);
4098 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4101 'contact_id' => $newContact['id'],
4102 'contribution_recur_id' => $contributionRecur['id'],
4103 'financial_type_id' => "Member Dues",
4104 'contribution_status_id' => 1,
4105 'invoice_id' => uniqid(),
4108 $lineItem = $this->callAPISuccess('LineItem', 'getsingle', []);
4109 $this->assertEquals('civicrm_membership', $lineItem['entity_table']);
4110 $membership = $this->callAPISuccess('Membership', 'getsingle', ['id' => $lineItem['entity_id']]);
4111 $this->callAPISuccess('LineItem', 'getsingle', []);
4112 $this->callAPISuccessGetCount('MembershipPayment', ['membership_id' => $membership['id']], 1);
4114 return [$originalContribution, $membership];
4118 * Set up a repeat transaction.
4120 * @param array $recurParams
4121 * @param mixed $flag
4122 * @param array $contributionParams
4125 protected function setUpRepeatTransaction($recurParams = [], $flag, $contributionParams = []) {
4126 $paymentProcessorID = $this->paymentProcessorCreate();
4127 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4128 'contact_id' => $this->_individualId
,
4129 'installments' => '12',
4130 'frequency_interval' => '1',
4132 'contribution_status_id' => 1,
4133 'start_date' => '2012-01-01 00:00:00',
4134 'currency' => 'USD',
4135 'frequency_unit' => 'month',
4136 'payment_processor_id' => $paymentProcessorID,
4139 $originalContribution = '';
4140 if ($flag == 'multiple') {
4141 // CRM-19309 create a contribution + also add in line_items (plural):
4142 $params = array_merge($this->_params
, $contributionParams);
4143 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4146 'contribution_recur_id' => $contributionRecur['id'],
4147 'skipLineItem' => 1,
4148 'api.line_item.create' => [
4150 'price_field_id' => 1,
4152 'line_total' => '20',
4153 'unit_price' => '10',
4154 'financial_type_id' => 1,
4157 'price_field_id' => 1,
4159 'line_total' => '80',
4160 'unit_price' => '80',
4161 'financial_type_id' => 2,
4168 elseif ($flag == 'single') {
4169 $params = array_merge($this->_params
, ['contribution_recur_id' => $contributionRecur['id']]);
4170 $params = array_merge($params, $contributionParams);
4171 $originalContribution = $this->callAPISuccess('contribution', 'create', $params);
4173 $originalContribution['payment_processor_id'] = $paymentProcessorID;
4174 return $originalContribution;
4178 * Common set up routine.
4182 protected function setUpForCompleteTransaction() {
4183 $this->mut
= new CiviMailUtils($this, TRUE);
4184 $this->createLoggedInUser();
4185 $params = array_merge($this->_params
, ['contribution_status_id' => 2, 'receipt_date' => 'now']);
4186 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4187 return $contribution;
4191 * Test repeat contribution uses the Payment Processor' payment_instrument setting.
4193 * @throws \CRM_Core_Exception
4195 public function testRepeatTransactionWithNonCreditCardDefault() {
4196 $contributionRecur = $this->callAPISuccess('ContributionRecur', 'create', [
4197 'contact_id' => $this->_individualId
,
4198 'installments' => '12',
4199 'frequency_interval' => '1',
4201 'contribution_status_id' => 1,
4202 'start_date' => '2012-01-01 00:00:00',
4203 'currency' => 'USD',
4204 'frequency_unit' => 'month',
4205 'payment_processor_id' => $this->paymentProcessorID
,
4207 $contribution1 = $this->callAPISuccess('contribution', 'create', array_merge(
4209 ['contribution_recur_id' => $contributionRecur['id'], 'payment_instrument_id' => 2])
4211 $contribution2 = $this->callAPISuccess('contribution', 'repeattransaction', [
4212 'contribution_status_id' => 'Completed',
4213 'trxn_id' => 'blah',
4214 'original_contribution_id' => $contribution1,
4216 $this->assertEquals('Debit Card', CRM_Contribute_PseudoConstant
::getLabel('CRM_Contribute_BAO_Contribution', 'payment_instrument_id', $contribution2['values'][$contribution2['id']]['payment_instrument_id']));
4220 * CRM-20008 Tests repeattransaction creates pending membership.
4222 public function testRepeatTransactionMembershipCreatePendingContribution() {
4223 list($originalContribution, $membership) = $this->setUpAutoRenewMembership();
4224 $this->callAPISuccess('membership', 'create', [
4225 'id' => $membership['id'],
4226 'end_date' => 'yesterday',
4227 'status_id' => 'Expired',
4229 $repeatedContribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4230 'contribution_recur_id' => $originalContribution['values'][1]['contribution_recur_id'],
4231 'contribution_status_id' => 'Pending',
4232 'trxn_id' => uniqid(),
4234 $membershipStatusId = $this->callAPISuccess('membership', 'getvalue', [
4235 'id' => $membership['id'],
4236 'return' => 'status_id',
4239 // Let's see if the membership payments got created while we're at it.
4240 $membershipPayments = $this->callAPISuccess('MembershipPayment', 'get', [
4241 'membership_id' => $membership['id'],
4243 $this->assertEquals(2, $membershipPayments['count']);
4245 $this->assertEquals('Expired', CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'status_id', $membershipStatusId));
4246 $this->callAPISuccess('Contribution', 'completetransaction', ['id' => $repeatedContribution['id']]);
4247 $membership = $this->callAPISuccessGetSingle('membership', [
4248 'id' => $membership['id'],
4249 'return' => 'status_id, end_date',
4251 $this->assertEquals('New', CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membership['status_id']));
4252 $this->assertEquals(date('Y-m-d', strtotime('yesterday + 1 month')), $membership['end_date']);
4256 * Test sending a mail via the API.
4258 * @throws \CRM_Core_Exception
4260 public function testSendMailWithAPISetFromDetails() {
4261 $mut = new CiviMailUtils($this, TRUE);
4262 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
4263 $this->callAPISuccess('contribution', 'sendconfirmation', [
4264 'id' => $contribution['id'],
4265 'receipt_from_email' => 'api@civicrm.org',
4266 'receipt_from_name' => 'CiviCRM LLC',
4268 $mut->checkMailLog([
4269 'From: CiviCRM LLC <api@civicrm.org>',
4270 'Contribution Information',
4278 * Test sending a mail via the API.
4280 public function testSendMailWithNoFromSetFallToDomain() {
4281 $this->createLoggedInUser();
4282 $mut = new CiviMailUtils($this, TRUE);
4283 $contribution = $this->callAPISuccess('contribution', 'create', $this->_params
);
4284 $this->callAPISuccess('contribution', 'sendconfirmation', [
4285 'id' => $contribution['id'],
4287 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4288 $mut->checkMailLog([
4289 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4290 'Contribution Information',
4298 * Test sending a mail via the API.
4300 public function testSendMailWithRepeatTransactionAPIFalltoDomain() {
4301 $this->createLoggedInUser();
4302 $mut = new CiviMailUtils($this, TRUE);
4303 $contribution = $this->setUpRepeatTransaction([], 'single');
4304 $this->callAPISuccess('contribution', 'repeattransaction', [
4305 'contribution_status_id' => 'Completed',
4306 'trxn_id' => uniqid(),
4307 'original_contribution_id' => $contribution,
4309 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => 1]);
4310 $mut->checkMailLog([
4311 'From: ' . $domain['from_name'] . ' <' . $domain['from_email'] . '>',
4312 'Contribution Information',
4321 * Test sending a mail via the API.
4323 public function testSendMailWithRepeatTransactionAPIFalltoContributionPage() {
4324 $mut = new CiviMailUtils($this, TRUE);
4325 $contributionPage = $this->contributionPageCreate(['receipt_from_name' => 'CiviCRM LLC', 'receipt_from_email' => 'contributionpage@civicrm.org', 'is_email_receipt' => 1]);
4326 $paymentProcessorID = $this->paymentProcessorCreate();
4327 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', [
4328 'contact_id' => $this->_individualId
,
4329 'installments' => '12',
4330 'frequency_interval' => '1',
4332 'contribution_status_id' => 1,
4333 'start_date' => '2012-01-01 00:00:00',
4334 'currency' => 'USD',
4335 'frequency_unit' => 'month',
4336 'payment_processor_id' => $paymentProcessorID,
4338 $originalContribution = $this->callAPISuccess('contribution', 'create', array_merge(
4341 'contribution_recur_id' => $contributionRecur['id'],
4342 'contribution_page_id' => $contributionPage['id'],
4345 $this->callAPISuccess('contribution', 'repeattransaction', [
4346 'contribution_status_id' => 'Completed',
4347 'trxn_id' => uniqid(),
4348 'original_contribution_id' => $originalContribution,
4351 $mut->checkMailLog([
4352 'From: CiviCRM LLC <contributionpage@civicrm.org>',
4353 'Contribution Information',
4361 * Test sending a mail via the API.
4363 public function testSendMailWithRepeatTransactionAPIFalltoSystemFromNoDefaultFrom() {
4364 $mut = new CiviMailUtils($this, TRUE);
4365 $originalContribution = $contribution = $this->setUpRepeatTransaction([], 'single');
4366 $fromEmail = $this->CallAPISuccess('optionValue', 'get', ['is_default' => 1, 'option_group_id' => 'from_email_address', 'sequential' => 1]);
4367 foreach ($fromEmail['values'] as $from) {
4368 $this->callAPISuccess('optionValue', 'create', ['is_default' => 0, 'id' => $from['id']]);
4370 $domain = $this->callAPISuccess('domain', 'getsingle', ['id' => CRM_Core_Config
::domainID()]);
4371 $this->callAPISuccess('contribution', 'repeattransaction', [
4372 'contribution_status_id' => 'Completed',
4373 'trxn_id' => uniqid(),
4374 'original_contribution_id' => $originalContribution,
4376 $mut->checkMailLog([
4377 'From: ' . $domain['name'] . ' <' . $domain['domain_email'] . '>',
4378 'Contribution Information',
4386 * Create a Contribution Page with is_email_receipt = TRUE.
4388 * @param array $params
4389 * Params to overwrite with.
4393 protected function createReceiptableContributionPage($params = []) {
4394 $contributionPage = $this->callAPISuccess('ContributionPage', 'create', array_merge([
4395 'receipt_from_name' => 'Mickey Mouse',
4396 'receipt_from_email' => 'mickey@mouse.com',
4397 'title' => "Test Contribution Page",
4398 'financial_type_id' => 1,
4399 'currency' => 'CAD',
4400 'is_monetary' => TRUE,
4401 'is_email_receipt' => TRUE,
4403 return $contributionPage;
4407 * function to test card_type and pan truncation.
4409 public function testCardTypeAndPanTruncation() {
4410 $creditCardTypeIDs = array_flip(CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'));
4411 $contactId = $this->individualCreate();
4413 'contact_id' => $contactId,
4414 'receive_date' => '2016-01-20',
4415 'total_amount' => 100,
4416 'financial_type_id' => 1,
4417 'payment_instrument' => 'Credit Card',
4418 'card_type_id' => $creditCardTypeIDs['Visa'],
4419 'pan_truncation' => 4567,
4421 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4422 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contribution['id'], 'DESC');
4423 $financialTrxn = $this->callAPISuccessGetSingle(
4426 'id' => $lastFinancialTrxnId['financialTrxnId'],
4427 'return' => ['card_type_id', 'pan_truncation'],
4430 $this->assertEquals(CRM_Utils_Array
::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Visa']);
4431 $this->assertEquals(CRM_Utils_Array
::value('pan_truncation', $financialTrxn), 4567);
4433 'id' => $contribution['id'],
4434 'pan_truncation' => 2345,
4435 'card_type_id' => $creditCardTypeIDs['Amex'],
4437 $contribution = $this->callAPISuccess('contribution', 'create', $params);
4438 $financialTrxn = $this->callAPISuccessGetSingle(
4441 'id' => $lastFinancialTrxnId['financialTrxnId'],
4442 'return' => ['card_type_id', 'pan_truncation'],
4445 $this->assertEquals(CRM_Utils_Array
::value('card_type_id', $financialTrxn), $creditCardTypeIDs['Amex']);
4446 $this->assertEquals(CRM_Utils_Array
::value('pan_truncation', $financialTrxn), 2345);
4450 * Test repeat contribution uses non default currency
4451 * @see https://issues.civicrm.org/jira/projects/CRM/issues/CRM-20678
4453 public function testRepeatTransactionWithDifferenceCurrency() {
4454 $originalContribution = $this->setUpRepeatTransaction(['currency' => 'AUD'], 'single', ['currency' => 'AUD']);
4455 $contribution = $this->callAPISuccess('contribution', 'repeattransaction', [
4456 'original_contribution_id' => $originalContribution['id'],
4457 'contribution_status_id' => 'Completed',
4458 'trxn_id' => uniqid(),
4460 $this->assertEquals('AUD', $contribution['values'][$contribution['id']]['currency']);
4464 * Get the financial items for the contribution.
4466 * @param int $contributionID
4469 * Array of associated financial items.
4471 protected function getFinancialTransactionsForContribution($contributionID) {
4473 'entity_id' => $contributionID,
4474 'entity_table' => 'civicrm_contribution',
4476 // @todo the following function has naming errors & has a weird signature & appears to
4477 // only be called from test classes. Move into test suite & maybe just use api
4478 // from this function.
4479 return array_merge(CRM_Financial_BAO_FinancialItem
::retrieveEntityFinancialTrxn($trxnParams));
4483 * Test getunique api call for Contribution entity
4485 public function testContributionGetUnique() {
4486 $result = $this->callAPIAndDocument($this->entity
, 'getunique', [], __FUNCTION__
, __FILE__
);
4487 $this->assertEquals(2, $result['count']);
4488 $this->assertEquals(['trxn_id'], $result['values']['UI_contrib_trxn_id']);
4489 $this->assertEquals(['invoice_id'], $result['values']['UI_contrib_invoice_id']);
4493 * Test Repeat Transaction Contribution with Tax amount.
4494 * https://lab.civicrm.org/dev/core/issues/806
4496 public function testRepeatContributionWithTaxAmount() {
4497 $this->enableTaxAndInvoicing();
4498 $financialType = $this->callAPISuccess('financial_type', 'create', [
4499 'name' => 'Test taxable financial Type',
4503 $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
4504 $contribution = $this->setUpRepeatTransaction(
4508 'financial_type_id' => $financialType['id'],
4511 $this->callAPISuccess('contribution', 'repeattransaction', [
4512 'original_contribution_id' => $contribution['id'],
4513 'contribution_status_id' => 'Completed',
4514 'trxn_id' => uniqid(),
4516 $payments = $this->callAPISuccess('Contribution', 'get', ['sequential' => 1])['values'];
4517 //Assert if first payment and repeated payment has the same contribution amount.
4518 $this->assertEquals($payments[0]['total_amount'], $payments[1]['total_amount']);
4519 $this->callAPISuccessGetCount('Contribution', [], 2);
4521 //Assert line item records.
4522 $lineItems = $this->callAPISuccess('LineItem', 'get', ['sequential' => 1])['values'];
4523 foreach ($lineItems as $lineItem) {
4524 $this->assertEquals($lineItem['unit_price'], $this->_params
['total_amount']);
4525 $this->assertEquals($lineItem['line_total'], $this->_params
['total_amount']);
4527 $this->callAPISuccessGetCount('Contribution', [], 2);
4530 public function testGetCurrencyOptions() {
4531 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4532 'field' => 'currency',
4534 $this->assertEquals('US Dollar', $result['values']['USD']);
4535 $this->assertNotContains('$', $result['values']);
4536 $result = $this->callAPISuccess('Contribution', 'getoptions', [
4537 'field' => 'currency',
4538 'context' => "abbreviate",
4540 $this->assertEquals('$', $result['values']['USD']);
4541 $this->assertNotContains('US Dollar', $result['values']);
4545 * @throws \API_Exception
4546 * @throws \CRM_Core_Exception
4547 * @throws \Civi\API\Exception\UnauthorizedException
4549 public function testSetCustomDataInCreateAndHook() {
4550 $this->createCustomGroupWithFieldOfType([], 'int');
4551 $this->ids
['CustomField']['text'] = (int) $this->createTextCustomField(['custom_group_id' => $this->ids
['CustomGroup']['Custom Group']])['id'];
4552 $this->hookClass
->setHook('civicrm_post', [
4554 'civicrmPostContributionCustom',
4556 $params = $this->_params
;
4557 $params['custom_' . $this->ids
['CustomField']['text']] = 'Some Text';
4558 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
4559 $getContribution = $this->callAPISuccess('Contribution', 'get', [
4560 'id' => $contribution['id'],
4561 'return' => ['id', 'custom_' . $this->ids
['CustomField']['text'], 'custom_' . $this->ids
['CustomField']['int']],
4563 $this->assertEquals(5, $getContribution['values'][$contribution['id']][$this->getCustomFieldName('int')]);
4564 $this->assertEquals('Some Text', $getContribution['values'][$contribution['id']]['custom_' . $this->ids
['CustomField']['text']]);
4565 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids
['CustomField']['text']]);
4566 $this->callAPISuccess('CustomField', 'delete', ['id' => $this->ids
['CustomField']['int']]);
4567 $this->callAPISuccess('CustomGroup', 'delete', ['id' => $this->ids
['CustomGroup']['Custom Group']]);
4571 * Implement post hook.
4574 * @param string $objectName
4575 * @param int $objectId
4576 * @param \CRM_Core_DAO $objectRef
4578 * @throws \CRM_Core_Exception
4580 public function civicrmPostContributionCustom($op, $objectName, $objectId, &$objectRef) {
4581 if ($objectName === 'Contribution' && $op === 'create') {
4582 $this->callAPISuccess('Contribution', 'create', [
4584 'custom_' . $this->ids
['CustomField']['int'] => 5,
4590 * Test that passing in label for an option value linked to a custom field works
4591 * @see dev/core#1816
4593 public function testCustomValueOptionLabelTest() {
4594 $this->createCustomGroupWithFieldOfType([], 'radio');
4595 $params = $this->_params
;
4596 $params['custom_' . $this->ids
['CustomField']['radio']] = 'Red Testing';
4597 $contribution = $this->callAPISuccess('Contribution', 'Create', $params);
4601 * Test repeatTransaction with installments and next_sched_contribution_date
4603 * @dataProvider getRepeatTransactionNextSchedData
4605 * @param array $dataSet
4607 * @throws \Exception
4609 public function testRepeatTransactionUpdateNextSchedContributionDate($dataSet) {
4610 $paymentProcessorID = $this->paymentProcessorCreate();
4611 // Create the contribution before the recur so it doesn't trigger the update of next_sched_contribution_date
4612 $contribution = $this->callAPISuccess('contribution', 'create', array_merge(
4615 'contribution_status_id' => 'Completed',
4616 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4619 $contributionRecur = $this->callAPISuccess('contribution_recur', 'create', array_merge([
4620 'contact_id' => $this->_individualId
,
4621 'frequency_interval' => '1',
4623 'contribution_status_id' => 'Pending',
4624 'start_date' => '2012-01-01 00:00:00',
4625 'currency' => 'USD',
4626 'frequency_unit' => 'month',
4627 'payment_processor_id' => $paymentProcessorID,
4628 ], $dataSet['recur']));
4629 // Link the existing contribution to the recur *after* creating the recur.
4630 // If we just created the contribution now the next_sched_contribution_date would be automatically set
4631 // and we want to test the case when it is empty.
4632 $this->callAPISuccess('contribution', 'create', [
4633 'id' => $contribution['id'],
4634 'contribution_recur_id' => $contributionRecur['id'],
4637 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4638 'id' => $contributionRecur['id'],
4639 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4641 // Check that next_sched_contribution_date is empty
4642 $this->assertEquals('', $contributionRecur['next_sched_contribution_date'] ??
'');
4644 $this->callAPISuccess('Contribution', 'repeattransaction', [
4645 'contribution_status_id' => 'Completed',
4646 'contribution_recur_id' => $contributionRecur['id'],
4647 'receive_date' => $dataSet['repeat'][0]['receive_date'],
4649 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4650 'id' => $contributionRecur['id'],
4651 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4653 // Check that recur has status "In Progress"
4654 $this->assertEquals(
4655 (string) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][0]['expectedRecurStatus']),
4656 $contributionRecur['contribution_status_id']
4658 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4659 $this->assertEquals($dataSet['repeat'][0]['expectedNextSched'], $contributionRecur['next_sched_contribution_date']);
4661 // Now call Contribution.repeattransaction again and check that the next_sched_contribution_date has moved forward by 1 period again
4662 $this->callAPISuccess('Contribution', 'repeattransaction', [
4663 'contribution_status_id' => 'Completed',
4664 'contribution_recur_id' => $contributionRecur['id'],
4665 'receive_date' => $dataSet['repeat'][1]['receive_date'],
4667 $contributionRecur = $this->callAPISuccessGetSingle('ContributionRecur', [
4668 'id' => $contributionRecur['id'],
4669 'return' => ['next_sched_contribution_date', 'contribution_status_id'],
4671 // Check that recur has status "In Progress" or "Completed" depending on whether number of installments has been reached
4672 $this->assertEquals(
4673 (string) CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $dataSet['repeat'][1]['expectedRecurStatus']),
4674 $contributionRecur['contribution_status_id']
4676 // Check that next_sched_contribution_date has been set to 1 period after the contribution receive date (ie. 1 month)
4677 $this->assertEquals($dataSet['repeat'][1]['expectedNextSched'], $contributionRecur['next_sched_contribution_date'] ??
'');
4681 * Get dates for testing.
4685 public function getRepeatTransactionNextSchedData() {
4686 // Both these tests handle/test the case that next_sched_contribution_date is empty when Contribution.repeattransaction
4687 // is called for the first time. Historically setting it was inconsistent but on new updates it should always be set.
4689 * This tests that calling Contribution.repeattransaction with installments does the following:
4690 * - For the first call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4691 * to match next expected receive_date.
4692 * - Once the 3rd contribution is created contributionRecur status = completed and next_sched_contribution_date = ''.
4694 $result['receive_date_includes_time_with_installments']['2012-01-01-1-month'] = [
4696 'start_date' => '2012-01-01',
4697 'frequency_interval' => 1,
4698 'installments' => '3',
4699 'frequency_unit' => 'month',
4703 'receive_date' => '2012-02-29 16:00:00',
4704 'expectedNextSched' => '2012-03-29 00:00:00',
4705 'expectedRecurStatus' => 'In Progress',
4708 'receive_date' => '2012-03-29 16:00:00',
4709 'expectedNextSched' => '',
4710 'expectedRecurStatus' => 'Completed',
4715 * This tests that calling Contribution.repeattransaction with no installments does the following:
4716 * - For the each call to repeattransaction the recur status is In Progress and next_sched_contribution_date is updated
4717 * to match next expected receive_date.
4719 $result['receive_date_includes_time_no_installments']['2012-01-01-1-month'] = [
4721 'start_date' => '2012-01-01',
4722 'frequency_interval' => 1,
4723 'frequency_unit' => 'month',
4727 'receive_date' => '2012-02-29 16:00:00',
4728 'expectedNextSched' => '2012-03-29 00:00:00',
4729 'expectedRecurStatus' => 'In Progress',
4732 'receive_date' => '2012-03-29 16:00:00',
4733 'expectedNextSched' => '2012-04-29 00:00:00',
4734 'expectedRecurStatus' => 'In Progress',