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 * Class CRM_Contribute_BAO_ContributionTest
16 class CRM_Contribute_BAO_ContributionTest
extends CiviUnitTestCase
{
18 use CRMTraits_Financial_FinancialACLTrait
;
19 use CRMTraits_Financial_PriceSetTrait
;
22 * Clean up after tests.
24 public function tearDown() {
25 $this->quickCleanUpFinancialEntities();
30 * Test create method (create and update modes).
32 * @throws \CRM_Core_Exception
34 public function testCreate() {
35 $contactId = $this->individualCreate();
38 'contact_id' => $contactId,
40 'financial_type_id' => 1,
41 'contribution_status_id' => 1,
42 'payment_instrument_id' => 1,
43 'source' => 'STUDENT',
44 'receive_date' => '20080522000000',
45 'receipt_date' => '20080522000000',
46 'non_deductible_amount' => 0.00,
47 'total_amount' => 200.00,
50 'trxn_id' => '22ereerwww444444',
51 'invoice_id' => '86ed39c9e9ee6ef6031621ce0eafe7eb81',
52 'thankyou_date' => '20080522',
56 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
58 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transaction id creation.');
59 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
61 //update contribution amount
62 $params['id'] = $contribution['id'];
63 $params['fee_amount'] = 10;
64 $params['net_amount'] = 190;
66 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
68 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id .');
69 $this->assertEquals($params['net_amount'], $contribution['net_amount'], 'Check for Amount updation.');
73 * Create() method with custom data.
75 public function testCreateWithCustomData() {
76 $contactId = $this->individualCreate();
79 $customGroup = $this->customGroupCreate(['extends' => 'Contribution']);
80 $customGroupID = $customGroup['id'];
81 $customGroup = $customGroup['values'][$customGroupID];
85 'data_type' => 'String',
86 'html_type' => 'Text',
88 'custom_group_id' => $customGroupID,
90 $customField = CRM_Core_BAO_CustomField
::create($fields);
93 'contact_id' => $contactId,
95 'financial_type_id' => 1,
96 'contribution_status_id' => 1,
97 'payment_instrument_id' => 1,
98 'source' => 'STUDENT',
99 'receive_date' => '20080522000000',
100 'receipt_date' => '20080522000000',
102 'non_deductible_amount' => 0.00,
103 'total_amount' => 200.00,
106 'trxn_id' => '22ereerwww322323',
107 'invoice_id' => '22ed39c9e9ee6ef6031621ce0eafe6da70',
108 'thankyou_date' => '20080522',
109 'skipCleanMoney' => TRUE,
112 $params['custom'] = [
113 $customField->id
=> [
115 'value' => 'Test custom value',
117 'custom_field_id' => $customField->id
,
118 'custom_group_id' => $customGroupID,
119 'table_name' => $customGroup['table_name'],
120 'column_name' => $customField->column_name
,
126 $contribution = CRM_Contribute_BAO_Contribution
::create($params);
128 // Check that the custom field value is saved
129 $customValueParams = [
130 'entityID' => $contribution->id
,
131 'custom_' . $customField->id
=> 1,
133 $values = CRM_Core_BAO_CustomValueTable
::getValues($customValueParams);
134 $this->assertEquals('Test custom value', $values['custom_' . $customField->id
], 'Check the custom field value');
136 $this->assertEquals($params['trxn_id'], $contribution->trxn_id
, 'Check for transcation id creation.');
137 $this->assertEquals($contactId, $contribution->contact_id
, 'Check for contact id for Conribution.');
141 * CRM-21026 Test ContributionCount after contribution created with disabled FT
143 public function testContributionCountDisabledFinancialType() {
144 $contactId = $this->individualCreate();
146 'name' => 'grassvariety1' . substr(sha1(rand()), 0, 7),
150 $finType = $this->callAPISuccess('financial_type', 'create', $financialType);
152 'contact_id' => $contactId,
154 'financial_type_id' => $finType['id'],
155 'contribution_status_id' => 1,
156 'payment_instrument_id' => 1,
157 'source' => 'STUDENT',
158 'receive_date' => '20080522000000',
159 'receipt_date' => '20080522000000',
161 'non_deductible_amount' => 0.00,
162 'total_amount' => 200.00,
165 'trxn_id' => '22ereerwww322323',
166 'invoice_id' => '22ed39c9e9ee6ef6031621ce0eafe6da70',
167 'thankyou_date' => '20080522',
169 $this->callAPISuccess('Contribution', 'create', $params);
170 $this->callAPISuccess('financial_type', 'create', ['is_active' => 0, 'id' => $finType['id']]);
171 $contributionCount = CRM_Contribute_BAO_Contribution
::contributionCount($contactId);
172 $this->assertEquals(1, $contributionCount);
176 * DeleteContribution() method
178 public function testDeleteContribution() {
179 $contactId = $this->individualCreate();
182 'contact_id' => $contactId,
184 'financial_type_id' => 1,
185 'contribution_status_id' => 1,
186 'payment_instrument_id' => 1,
187 'source' => 'STUDENT',
188 'receive_date' => '20080522000000',
189 'receipt_date' => '20080522000000',
191 'non_deductible_amount' => 0.00,
192 'total_amount' => 200.00,
195 'trxn_id' => '33ereerwww322323',
196 'invoice_id' => '33ed39c9e9ee6ef6031621ce0eafe6da70',
197 'thankyou_date' => '20080522',
198 'sequential' => TRUE,
201 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
203 CRM_Contribute_BAO_Contribution
::deleteContribution($contribution['id']);
205 $this->assertDBNull('CRM_Contribute_DAO_Contribution', $contribution['trxn_id'],
206 'id', 'trxn_id', 'Database check for deleted Contribution.'
211 * Create honor-contact method.
213 public function testCreateAndGetHonorContact() {
214 $firstName = 'John_' . substr(sha1(rand()), 0, 7);
215 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
216 $email = "{$firstName}.{$lastName}@example.com";
218 //Get profile id of name honoree_individual used to create profileContact
219 $honoreeProfileId = NULL;
220 $ufGroupDAO = new CRM_Core_DAO_UFGroup();
221 $ufGroupDAO->name
= 'honoree_individual';
222 if ($ufGroupDAO->find(TRUE)) {
223 $honoreeProfileId = $ufGroupDAO->id
;
228 'first_name' => $firstName,
229 'last_name' => $lastName,
232 $softParam = ['soft_credit_type_id' => 1];
235 $honoreeContactId = CRM_Contact_BAO_Contact
::createProfileContact($params, $null,
236 NULL, NULL, $honoreeProfileId
239 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName,
240 'Database check for created honor contact record.'
242 //create contribution on behalf of honary.
244 $contactId = $this->individualCreate(['first_name' => 'John', 'last_name' => 'Doe']);
247 'contact_id' => $contactId,
249 'financial_type_id' => 4,
250 'contribution_status_id' => 1,
251 'receive_date' => date('Ymd'),
252 'total_amount' => 66,
256 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
257 $id = $contribution['id'];
258 $softParam['contact_id'] = $honoreeContactId;
259 $softParam['contribution_id'] = $id;
260 $softParam['currency'] = $contribution['currency'];
261 $softParam['amount'] = $contribution['total_amount'];
263 //Create Soft Contribution for honoree contact
264 CRM_Contribute_BAO_ContributionSoft
::add($softParam);
266 $this->assertDBCompareValue('CRM_Contribute_DAO_ContributionSoft', $id, 'contact_id',
267 'contribution_id', $honoreeContactId, 'Check DB for honor contact of the contribution'
269 //get honorary information
270 $getHonorContact = CRM_Contribute_BAO_Contribution
::getHonorContacts($honoreeContactId);
271 $this->assertEquals([
273 'honor_type' => 'In Honor of',
274 'honorId' => $contactId,
275 'display_name' => 'Mr. John Doe II',
276 'type' => 'Event Fee',
278 'amount' => '$ 66.00',
280 'receive_date' => date('Y-m-d 00:00:00'),
281 'contribution_status' => 'Completed',
283 ], $getHonorContact);
285 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName,
286 'Database check for created honor contact record.'
289 //get annual contribution information
290 $annual = CRM_Contribute_BAO_Contribution
::annual($contactId);
292 $currencySymbol = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_Currency', CRM_Core_Config
::singleton()->defaultCurrency
, 'symbol', 'name');
293 $this->assertDBCompareValue('CRM_Contribute_DAO_Contribution', $id, 'total_amount',
294 'id', ltrim($annual[2], $currencySymbol), 'Check DB for total amount of the contribution'
299 * Test that financial type data is not added to the annual query if acls not enabled.
301 public function testAnnualQueryWithFinancialACLsEnabled() {
302 $this->enableFinancialACLs();
303 $this->createLoggedInUserWithFinancialACL();
304 $permittedFinancialType = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation');
305 $sql = CRM_Contribute_BAO_Contribution
::getAnnualQuery([1, 2, 3]);
306 $this->assertContains('SUM(total_amount) as amount,', $sql);
307 $this->assertContains('WHERE b.contact_id IN (1,2,3)', $sql);
308 $this->assertContains('b.financial_type_id IN (' . $permittedFinancialType . ')', $sql);
310 // Run it to make sure it's not bad sql.
311 CRM_Core_DAO
::executeQuery($sql);
312 $this->disableFinancialACLs();
316 * Test the annual query returns a correct result when multiple line items are present.
318 public function testAnnualWithMultipleLineItems() {
319 $contactID = $this->createLoggedInUserWithFinancialACL();
320 $this->createContributionWithTwoLineItemsAgainstPriceSet([
321 'contact_id' => $contactID,
324 $this->enableFinancialACLs();
325 $sql = CRM_Contribute_BAO_Contribution
::getAnnualQuery([$contactID]);
326 $result = CRM_Core_DAO
::executeQuery($sql);
328 $this->assertEquals(300, $result->amount
);
329 $this->assertEquals(1, $result->count
);
330 $this->disableFinancialACLs();
334 * Test that financial type data is not added to the annual query if acls not enabled.
336 public function testAnnualQueryWithFinancialACLsDisabled() {
337 $sql = CRM_Contribute_BAO_Contribution
::getAnnualQuery([1, 2, 3]);
338 $this->assertContains('SUM(total_amount) as amount,', $sql);
339 $this->assertContains('WHERE b.contact_id IN (1,2,3)', $sql);
340 $this->assertNotContains('b.financial_type_id', $sql);
341 //$this->assertNotContains('line_item', $sql);
342 // Run it to make sure it's not bad sql.
343 CRM_Core_DAO
::executeQuery($sql);
347 * Test that financial type data is not added to the annual query if acls not enabled.
349 public function testAnnualQueryWithFinancialHook() {
350 $this->hookClass
->setHook('civicrm_selectWhereClause', [$this, 'aclIdNoZero']);
351 $sql = CRM_Contribute_BAO_Contribution
::getAnnualQuery([1, 2, 3]);
352 $this->assertContains('SUM(total_amount) as amount,', $sql);
353 $this->assertContains('WHERE b.contact_id IN (1,2,3)', $sql);
354 $this->assertContains('b.id NOT IN (0)', $sql);
355 $this->assertNotContains('b.financial_type_id', $sql);
356 CRM_Core_DAO
::executeQuery($sql);
360 * Add ACL denying values LIKE '0'.
362 * @param string $entity
363 * @param string $clauses
365 public function aclIdNoZero($entity, &$clauses) {
366 if ($entity != 'Contribution') {
369 $clauses['id'] = "NOT IN (0)";
373 * Display sort name during.
374 * Update multiple contributions
377 public function testsortName() {
379 'first_name' => 'Shane',
380 'last_name' => 'Whatson',
381 'contact_type' => 'Individual',
384 $contact = CRM_Contact_BAO_Contact
::add($params);
386 //Now check $contact is object of contact DAO..
387 $this->assertInstanceOf('CRM_Contact_DAO_Contact', $contact, 'Check for created object');
389 $contactId = $contact->id
;
391 'contact_id' => $contactId,
393 'financial_type_id' => 1,
394 'contribution_status_id' => 1,
395 'payment_instrument_id' => 1,
396 'source' => 'STUDENT',
397 'receive_date' => '20080522000000',
398 'receipt_date' => '20080522000000',
400 'non_deductible_amount' => 0.00,
401 'total_amount' => 300.00,
404 'trxn_id' => '22ereerwww323',
405 'invoice_id' => '22ed39c9e9ee621ce0eafe6da70',
406 'thankyou_date' => '20080522',
407 'sequential' => TRUE,
410 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
412 $this->assertEquals($param['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
413 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
415 //display sort name during Update multiple contributions
416 $sortName = CRM_Contribute_BAO_Contribution
::sortName($contribution['id']);
418 $this->assertEquals('Whatson, Shane', $sortName, 'Check for sort name.');
422 * Add premium during online Contribution.
426 public function testAddPremium() {
427 $contactId = $this->individualCreate();
430 'name' => 'TEST Premium',
432 'imageOption' => 'noImage',
433 'MAX_FILE_SIZE' => 2097152,
436 'min_contribution' => 100,
439 $premium = CRM_Contribute_BAO_Product
::create($params);
441 $this->assertEquals('TEST Premium', $premium->name
, 'Check for premium name.');
443 $contributionParams = [
444 'contact_id' => $contactId,
446 'financial_type_id' => 1,
447 'contribution_status_id' => 1,
448 'payment_instrument_id' => 1,
449 'source' => 'STUDENT',
450 'receive_date' => '20080522000000',
451 'receipt_date' => '20080522000000',
453 'non_deductible_amount' => 0.00,
454 'total_amount' => 300.00,
457 'trxn_id' => '33erdfrwvw434',
458 'invoice_id' => '98ed34f7u9hh672ce0eafe8fb92',
459 'thankyou_date' => '20080522',
460 'sequential' => TRUE,
462 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams)['values'][0];
464 $this->assertEquals($contributionParams['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
465 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
467 //parameter for adding premium to contribution
469 'product_id' => $premium->id
,
470 'contribution_id' => $contribution['id'],
471 'product_option' => NULL,
474 $contributionProduct = CRM_Contribute_BAO_Contribution
::addPremium($data);
475 $this->assertEquals($contributionProduct->product_id
, $premium->id
, 'Check for Product id .');
478 CRM_Contribute_BAO_Product
::del($premium->id
);
479 $this->assertDBNull('CRM_Contribute_DAO_Product', $premium->name
,
480 'id', 'name', 'Database check for deleted Product.'
485 * Check duplicate contribution id.
486 * during the contribution import
487 * checkDuplicateIds();
489 public function testcheckDuplicateIds() {
490 $contactId = $this->individualCreate();
493 'contact_id' => $contactId,
495 'financial_type_id' => 1,
496 'contribution_status_id' => 1,
497 'payment_instrument_id' => 1,
498 'source' => 'STUDENT',
499 'receive_date' => '20080522000000',
500 'receipt_date' => '20080522000000',
502 'non_deductible_amount' => 0.00,
503 'total_amount' => 300.00,
506 'trxn_id' => '76ereeswww835',
507 'invoice_id' => '93ed39a9e9hd621bs0eafe3da82',
508 'thankyou_date' => '20080522',
509 'sequential' => TRUE,
512 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
514 $this->assertEquals($param['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
515 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
517 'id' => $contribution['id'],
518 'trxn_id' => $contribution['trxn_id'],
519 'invoice_id' => $contribution['invoice_id'],
521 $contributionID = CRM_Contribute_BAO_Contribution
::checkDuplicateIds($data);
522 $this->assertEquals($contributionID, $contribution['id'], 'Check for duplicate transcation id .');
526 * Check credit note id creation
527 * when a contribution is cancelled or refunded
528 * createCreditNoteId();
530 public function testCreateCreditNoteId() {
531 $contactId = $this->individualCreate();
534 'contact_id' => $contactId,
536 'financial_type_id' => 1,
537 'contribution_status_id' => 3,
538 'payment_instrument_id' => 1,
539 'source' => 'STUDENT',
540 'receive_date' => '20080522000000',
541 'receipt_date' => '20080522000000',
543 'non_deductible_amount' => 0.00,
544 'total_amount' => 300.00,
547 'trxn_id' => '76ereeswww835',
548 'invoice_id' => '93ed39a9e9hd621bs0eafe3da82',
549 'thankyou_date' => '20080522',
550 'sequential' => TRUE,
553 $creditNoteId = CRM_Contribute_BAO_Contribution
::createCreditNoteId();
554 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
555 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
556 $this->assertEquals($creditNoteId, $contribution['creditnote_id'], 'Check if credit note id is created correctly.');
560 * Create() method (create and update modes).
562 public function testIsPaymentFlag() {
563 $contactId = $this->individualCreate();
566 'contact_id' => $contactId,
568 'financial_type_id' => 1,
569 'contribution_status_id' => 1,
570 'payment_instrument_id' => 1,
571 'source' => 'STUDENT',
572 'receive_date' => '20080522000000',
573 'receipt_date' => '20080522000000',
574 'non_deductible_amount' => 0.00,
575 'total_amount' => 200.00,
578 'trxn_id' => '22ereerwww4444xx',
579 'invoice_id' => '86ed39c9e9ee6ef6541621ce0eafe7eb81',
580 'thankyou_date' => '20080522',
581 'sequential' => TRUE,
583 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
585 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
586 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
589 'trxn_id' => $params['trxn_id'],
593 $financialTrxn = CRM_Core_BAO_FinancialTrxn
::retrieve($trxnArray, $defaults);
594 $this->assertEquals(1, $financialTrxn->N
, 'Mismatch count for is payment flag.');
595 //update contribution amount
596 $params['id'] = $contribution['id'];
597 $params['total_amount'] = 150;
598 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
600 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id .');
601 $this->assertEquals($params['total_amount'], $contribution['total_amount'], 'Check for Amount updation.');
603 'trxn_id' => $params['trxn_id'],
607 $financialTrxn = CRM_Core_BAO_FinancialTrxn
::retrieve($trxnArray, $defaults);
608 $this->assertEquals(2, $financialTrxn->N
, 'Mismatch count for is payment flag.');
609 $trxnArray['is_payment'] = 0;
610 $financialTrxn = CRM_Core_BAO_FinancialTrxn
::retrieve($trxnArray, $defaults);
611 $this->assertEquals(1, $financialTrxn->N
, 'Mismatch count for is payment flag.');
615 * Create() method (create and update modes).
617 public function testIsPaymentFlagForPending() {
618 $contactId = $this->individualCreate();
621 'contact_id' => $contactId,
623 'financial_type_id' => 1,
624 'contribution_status_id' => 2,
625 'payment_instrument_id' => 1,
626 'source' => 'STUDENT',
628 'receive_date' => '20080522000000',
629 'receipt_date' => '20080522000000',
630 'non_deductible_amount' => 0.00,
631 'total_amount' => 200.00,
634 'trxn_id' => '22ereerwww4444yy',
635 'invoice_id' => '86ed39c9e9yy6ef6541621ce0eafe7eb81',
636 'thankyou_date' => '20080522',
637 'sequential' => TRUE,
640 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
642 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transaction id creation.');
643 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
646 'trxn_id' => $params['trxn_id'],
650 $financialTrxn = CRM_Core_BAO_FinancialTrxn
::retrieve($trxnArray, $defaults);
651 $this->assertEquals(2, $financialTrxn->N
, 'Mismatch count for is payment flag.');
652 $trxnArray['is_payment'] = 1;
653 $financialTrxn = CRM_Core_BAO_FinancialTrxn
::retrieve($trxnArray, $defaults);
654 $this->assertEquals(NULL, $financialTrxn, 'Mismatch count for is payment flag.');
655 //update contribution amount
656 $params['id'] = $contribution['id'];
657 $params['contribution_status_id'] = 1;
659 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
661 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id .');
662 $this->assertEquals($params['contribution_status_id'], $contribution['contribution_status_id'], 'Check for status updation.');
664 'trxn_id' => $params['trxn_id'],
668 $financialTrxn = CRM_Core_BAO_FinancialTrxn
::retrieve($trxnArray, $defaults);
669 $this->assertEquals(1, $financialTrxn->N
, 'Mismatch count for is payment flag.');
670 $trxnArray['is_payment'] = 0;
671 $financialTrxn = CRM_Core_BAO_FinancialTrxn
::retrieve($trxnArray, $defaults);
672 $this->assertEquals(2, $financialTrxn->N
, 'Mismatch count for is payment flag.');
676 * addPayments() method (add and edit modes of participant).
678 * Add Payments is part of an old, flawed, code flow.
680 public function testAddPayments() {
681 $contribution = $this->addParticipantWithContribution();
682 // Delete existing financial_trxns. This is because we are testing a code flow we
683 // want to deprecate & remove & the test relies on bad data asa starting point.
684 // End goal is the Order.create->Payment.create flow.
685 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_entity_financial_trxn WHERE entity_table = "civicrm_financial_item"');
686 CRM_Contribute_BAO_Contribution
::addPayments([$contribution]);
687 $this->checkItemValues($contribution);
691 * checks db values for financial item
693 public function checkItemValues($contribution) {
694 $toFinancialAccount = CRM_Contribute_PseudoConstant
::getRelationalFinancialAccount(4, 'Accounts Receivable Account is');
695 $query = "SELECT eft1.entity_id, ft.total_amount, eft1.amount FROM civicrm_financial_trxn ft INNER JOIN civicrm_entity_financial_trxn eft ON (eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution')
696 INNER JOIN civicrm_entity_financial_trxn eft1 ON (eft1.financial_trxn_id = eft.financial_trxn_id AND eft1.entity_table = 'civicrm_financial_item')
697 WHERE eft.entity_id = %1 AND ft.to_financial_account_id <> %2";
699 $queryParams[1] = [$contribution->id
, 'Integer'];
700 $queryParams[2] = [$toFinancialAccount, 'Integer'];
702 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
703 $amounts = [100.00, 50.00];
704 while ($dao->fetch()) {
705 $this->assertEquals(150.00, $dao->total_amount
, 'Mismatch of total amount paid.');
706 $this->assertEquals($dao->amount
, array_pop($amounts), 'Mismatch of amount proportionally assigned to financial item');
711 * assignProportionalLineItems() method (add and edit modes of participant)
713 * @throws \CRM_Core_Exception
714 * @throws \CiviCRM_API3_Exception
716 public function testAssignProportionalLineItems() {
717 $contribution = $this->addParticipantWithContribution();
718 // Delete existing financial_trxns. This is because we are testing a code flow we
719 // want to deprecate & remove & the test relies on bad data asa starting point.
720 // End goal is the Order.create->Payment.create flow.
721 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_entity_financial_trxn WHERE entity_table = "civicrm_financial_item"');
723 'contribution_id' => $contribution->id
,
724 'total_amount' => 150.00,
726 $trxn = new CRM_Financial_DAO_FinancialTrxn();
727 $trxn->orderBy('id DESC');
729 CRM_Contribute_BAO_Contribution
::assignProportionalLineItems($params, $trxn->id
, $contribution->total_amount
);
730 $this->checkItemValues($contribution);
734 * Add participant with contribution
738 * @throws \CRM_Core_Exception
739 * @throws \CiviCRM_API3_Exception
741 public function addParticipantWithContribution() {
742 // creating price set, price field
743 $this->_contactId
= $this->individualCreate();
744 $event = $this->eventCreatePaid([]);
745 $this->_eventId
= $event['id'];
746 $priceSetId = $this->priceSetID
;
748 'label' => 'Price Field',
749 'name' => CRM_Utils_String
::titleToVar('Price Field'),
750 'html_type' => 'CheckBox',
751 'option_label' => ['1' => 'Price Field 1', '2' => 'Price Field 2'],
752 'option_value' => ['1' => 100, '2' => 200],
753 'option_name' => ['1' => 'Price Field 1', '2' => 'Price Field 2'],
754 'option_weight' => ['1' => 1, '2' => 2],
755 'option_amount' => ['1' => 100, '2' => 200],
756 'is_display_amounts' => 1,
758 'options_per_line' => 1,
759 'is_active' => ['1' => 1, '2' => 1],
760 'price_set_id' => $this->priceSetID
,
762 'financial_type_id' => CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
764 $priceField = CRM_Price_BAO_PriceField
::create($paramsField);
766 'id' => $this->_eventId
,
767 'financial_type_id' => 4,
770 CRM_Event_BAO_Event
::create($eventParams);
771 CRM_Price_BAO_PriceSet
::addTo('civicrm_event', $this->_eventId
, $priceSetId);
773 $priceFields = $this->callAPISuccess('PriceFieldValue', 'get', ['price_field_id' => $priceField->id
]);
774 $participantParams = [
775 'financial_type_id' => 4,
776 'event_id' => $this->_eventId
,
779 'fee_currency' => 'USD',
780 'contact_id' => $this->_contactId
,
782 $participant = CRM_Event_BAO_Participant
::add($participantParams);
783 $contributionParams = [
784 'total_amount' => 300,
786 'contact_id' => $this->_contactId
,
787 'financial_type_id' => 4,
788 'contribution_status_id' => 'Pending',
789 'contribution_mode' => 'participant',
790 'participant_id' => $participant->id
,
791 'sequential' => TRUE,
792 'api.Payment.create' => ['total_amount' => 150],
795 foreach ($priceFields['values'] as $key => $priceField) {
796 $lineItems[1][$key] = [
797 'price_field_id' => $priceField['price_field_id'],
798 'price_field_value_id' => $priceField['id'],
799 'label' => $priceField['label'],
800 'field_title' => $priceField['label'],
802 'unit_price' => $priceField['amount'],
803 'line_total' => $priceField['amount'],
804 'financial_type_id' => $priceField['financial_type_id'],
807 $contributionParams['line_item'] = $lineItems;
808 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams)['values'][0];
810 $paymentParticipant = [
811 'participant_id' => $participant->id
,
812 'contribution_id' => $contribution['id'],
814 CRM_Event_BAO_ParticipantPayment
::create($paymentParticipant);
816 $contributionObject = new CRM_Contribute_BAO_Contribution();
817 $contributionObject->id
= $contribution['id'];
818 $contributionObject->find(TRUE);
820 return $contributionObject;
824 * checkLineItems() check if total amount matches the sum of line total
826 public function testcheckLineItems() {
829 'receive_date' => '2010-01-20',
830 'total_amount' => 100,
831 'financial_type_id' => 3,
836 'entity_table' => 'civicrm_contribution',
837 'price_field_id' => 8,
838 'price_field_value_id' => 16,
845 'entity_table' => 'civicrm_contribution',
846 'price_field_id' => 8,
847 'price_field_value_id' => 17,
852 'financial_type_id' => 1,
861 CRM_Contribute_BAO_Contribution
::checkLineItems($params);
862 $this->fail("Missed expected exception");
864 catch (CRM_Contribute_Exception_CheckLineItemsException
$e) {
866 CRM_Contribute_Exception_CheckLineItemsException
::LINE_ITEM_DIFFERRING_TOTAL_EXCEPTON_MSG
,
871 $this->assertEquals(3, $params['line_items'][0]['line_item'][0]['financial_type_id']);
872 $params['total_amount'] = 300;
874 CRM_Contribute_BAO_Contribution
::checkLineItems($params);
878 * Tests CRM_Contribute_BAO_Contribution::checkLineItems() method works with
879 * floating point values.
881 public function testCheckLineItemsWithFloatingPointValues() {
884 'receive_date' => date('Y-m-d'),
885 'total_amount' => 16.67,
886 'financial_type_id' => 3,
891 'entity_table' => 'civicrm_contribution',
892 'price_field_id' => 8,
893 'price_field_value_id' => 16,
896 'unit_price' => 14.85,
897 'line_total' => 14.85,
900 'entity_table' => 'civicrm_contribution',
901 'price_field_id' => 8,
902 'price_field_value_id' => 17,
905 'unit_price' => 1.66,
906 'line_total' => 1.66,
907 'financial_type_id' => 1,
910 'entity_table' => 'civicrm_contribution',
911 'price_field_id' => 8,
912 'price_field_value_id' => 17,
915 'unit_price' => 0.16,
916 'line_total' => 0.16,
917 'financial_type_id' => 1,
925 $foundException = FALSE;
928 CRM_Contribute_BAO_Contribution
::checkLineItems($params);
930 catch (CRM_Contribute_Exception_CheckLineItemsException
$e) {
931 $foundException = TRUE;
934 $this->assertFalse($foundException);
938 * Test activity amount updation.
940 public function testActivityCreate() {
941 $contactId = $this->individualCreate();
945 'contact_id' => $contactId,
947 'financial_type_id' => 1,
948 'contribution_status_id' => 1,
949 'payment_instrument_id' => 1,
950 'source' => 'STUDENT',
951 'receive_date' => '20080522000000',
952 'receipt_date' => '20080522000000',
953 'non_deductible_amount' => 0.00,
954 'total_amount' => 100.00,
955 'trxn_id' => '22ereerwww444444',
956 'invoice_id' => '86ed39c9e9ee6ef6031621ce0eafe7eb81',
957 'thankyou_date' => '20160519',
961 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
963 $this->assertEquals($params['total_amount'], $contribution['total_amount'], 'Check for total amount in contribution.');
964 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
966 // Check amount in activity.
968 'source_record_id' => $contribution['id'],
969 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Contribution'),
971 // @todo use api instead.
972 $activity = CRM_Activity_BAO_Activity
::retrieve($activityParams, $defaults);
974 $this->assertEquals($contribution['id'], $activity->source_record_id
, 'Check for activity associated with contribution.');
975 $this->assertEquals("$ 100.00 - STUDENT", $activity->subject
, 'Check for total amount in activity.');
977 $params['id'] = $contribution['id'];
978 $params['total_amount'] = 200;
980 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
982 $this->assertEquals($params['total_amount'], $contribution['total_amount'], 'Check for total amount in contribution.');
983 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
985 // Retrieve activity again.
986 $activity = CRM_Activity_BAO_Activity
::retrieve($activityParams, $defaults);
988 $this->assertEquals($contribution['id'], $activity->source_record_id
, 'Check for activity associated with contribution.');
989 $this->assertEquals("$ 200.00 - STUDENT", $activity->subject
, 'Check for total amount in activity.');
993 * Test allowUpdateRevenueRecognitionDate.
995 * @throws \CRM_Core_Exception
997 public function testAllowUpdateRevenueRecognitionDate() {
998 $contactId = $this->individualCreate();
1000 'contact_id' => $contactId,
1001 'receive_date' => '2010-01-20',
1002 'total_amount' => 100,
1003 'financial_type_id' => 4,
1004 'contribution_status_id' => 'Pending',
1006 $order = $this->callAPISuccess('Order', 'create', $params);
1007 $allowUpdate = CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($order['id']);
1008 $this->assertTrue($allowUpdate);
1010 $event = $this->eventCreate();
1012 'contact_id' => $contactId,
1013 'receive_date' => '2010-01-20',
1014 'total_amount' => 300,
1015 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
1016 'contribution_status_id' => 'Pending',
1018 $priceFields = $this->createPriceSet('event', $event['id']);
1019 foreach ($priceFields['values'] as $key => $priceField) {
1020 $lineItems[$key] = [
1021 'price_field_id' => $priceField['price_field_id'],
1022 'price_field_value_id' => $priceField['id'],
1023 'label' => $priceField['label'],
1024 'field_title' => $priceField['label'],
1026 'unit_price' => $priceField['amount'],
1027 'line_total' => $priceField['amount'],
1028 'financial_type_id' => $priceField['financial_type_id'],
1029 'entity_table' => 'civicrm_participant',
1032 $params['line_items'][] = [
1033 'line_item' => $lineItems,
1035 'contact_id' => $contactId,
1036 'event_id' => $event['id'],
1039 'register_date' => '2007-07-21 00:00:00',
1040 'source' => 'Online Event Registration: API Testing',
1043 $order = $this->callAPISuccess('Order', 'create', $params);
1044 $allowUpdate = CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($order['id']);
1045 $this->assertFalse($allowUpdate);
1048 'contact_id' => $contactId,
1049 'receive_date' => '2010-01-20',
1050 'total_amount' => 200,
1051 'financial_type_id' => $this->getFinancialTypeId('Member Dues'),
1052 'contribution_status_id' => 'Pending',
1054 $membershipType = $this->membershipTypeCreate();
1055 $priceFields = $this->createPriceSet();
1057 foreach ($priceFields['values'] as $key => $priceField) {
1058 $lineItems[$key] = [
1059 'price_field_id' => $priceField['price_field_id'],
1060 'price_field_value_id' => $priceField['id'],
1061 'label' => $priceField['label'],
1062 'field_title' => $priceField['label'],
1064 'unit_price' => $priceField['amount'],
1065 'line_total' => $priceField['amount'],
1066 'financial_type_id' => $priceField['financial_type_id'],
1067 'entity_table' => 'civicrm_membership',
1068 'membership_type_id' => $membershipType,
1071 $params['line_items'][] = [
1072 'line_item' => [array_pop($lineItems)],
1074 'contact_id' => $contactId,
1075 'membership_type_id' => $membershipType,
1076 'join_date' => '2006-01-21',
1077 'start_date' => '2006-01-21',
1078 'end_date' => '2006-12-21',
1079 'source' => 'Payment',
1084 $order = $this->callAPISuccess('Order', 'create', $params);
1085 $allowUpdate = CRM_Contribute_BAO_Contribution
::allowUpdateRevenueRecognitionDate($order['id']);
1086 $this->assertFalse($allowUpdate);
1090 * Test calculateFinancialItemAmount().
1092 public function testcalculateFinancialItemAmount() {
1097 'line_total' => 100,
1098 'previous_line_total' => 300,
1101 'context' => 'changedAmount',
1102 'expectedItemAmount' => -200,
1107 'line_total' => 100,
1108 'previous_line_total' => 100,
1111 // Most contexts are ignored. Removing refs to change payment instrument so placeholder.
1112 'context' => 'not null',
1113 'expectedItemAmount' => -100,
1117 'is_quick_config' => TRUE,
1118 'total_amount' => 110,
1122 'item_amount' => 100,
1124 'context' => 'changedAmount',
1125 'expectedItemAmount' => 100,
1129 'is_quick_config' => TRUE,
1130 'total_amount' => 110,
1134 'item_amount' => NULL,
1136 'context' => 'changedAmount',
1137 'expectedItemAmount' => 110,
1141 'is_quick_config' => TRUE,
1142 'total_amount' => 110,
1146 'item_amount' => NULL,
1149 'expectedItemAmount' => 100,
1152 foreach ($testParams as $params) {
1153 $itemAmount = CRM_Contribute_BAO_Contribution
::calculateFinancialItemAmount($params['params'], $params['amountParams'], $params['context']);
1154 $this->assertEquals($itemAmount, $params['expectedItemAmount'], 'Invalid Financial Item amount.');
1159 * Test recording of amount with comma separator.
1161 * @throws \CRM_Core_Exception
1163 public function testCommaSeparatorAmount() {
1164 $contactId = $this->individualCreate();
1167 'contact_id' => $contactId,
1168 'currency' => 'USD',
1169 'financial_type_id' => 1,
1170 'contribution_status_id' => 'Pending',
1171 'payment_instrument_id' => 1,
1172 'receive_date' => '20080522000000',
1173 'receipt_date' => '20080522000000',
1174 'total_amount' => '20,000.00',
1175 'api.Payment.create' => ['total_amount' => '8,000.00'],
1178 $contribution = $this->callAPISuccess('Order', 'create', $params);
1179 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contribution['id'], 'DESC');
1180 $financialTrxn = $this->callAPISuccessGetSingle(
1183 'id' => $lastFinancialTrxnId['financialTrxnId'],
1184 'return' => ['total_amount'],
1187 $this->assertEquals($financialTrxn['total_amount'], 8000, 'Invalid amount.');
1191 * Test for function getSalesTaxFinancialAccounts().
1193 public function testgetSalesTaxFinancialAccounts() {
1194 $this->enableTaxAndInvoicing();
1195 $financialType = $this->createFinancialType();
1196 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1197 $expectedResult = [$financialAccount->financial_account_id
=> $financialAccount->financial_account_id
];
1198 $financialType = $this->createFinancialType();
1199 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1200 $expectedResult[$financialAccount->financial_account_id
] = $financialAccount->financial_account_id
;
1201 $salesTaxFinancialAccount = CRM_Contribute_BAO_Contribution
::getSalesTaxFinancialAccounts();
1202 $this->assertTrue(($salesTaxFinancialAccount == $expectedResult), 'Function returned wrong values.');
1206 * Test for function createProportionalEntry().
1208 * @param string $thousandSeparator
1209 * punctuation used to refer to thousands.
1211 * @dataProvider getThousandSeparators
1213 public function testCreateProportionalEntry($thousandSeparator) {
1214 $this->setCurrencySeparators($thousandSeparator);
1215 list($contribution, $financialAccount) = $this->createContributionWithTax();
1217 'total_amount' => 55,
1218 'to_financial_account_id' => $financialAccount->financial_account_id
,
1219 'payment_instrument_id' => 1,
1220 'trxn_date' => date('Ymd'),
1222 'entity_id' => $contribution['id'],
1224 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'create', $params);
1226 'contribution_total_amount' => $contribution['total_amount'],
1227 'trxn_total_amount' => 55,
1228 'line_item_amount' => 100,
1230 $previousLineItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($contribution['id']);
1232 'entity_table' => 'civicrm_financial_item',
1233 'entity_id' => $previousLineItem['id'],
1234 'financial_trxn_id' => (string) $financialTrxn['id'],
1236 CRM_Contribute_BAO_Contribution
::createProportionalEntry($entityParams, $eftParams);
1237 $trxnTestArray = array_merge($eftParams, [
1238 'amount' => '50.00',
1240 $this->callAPISuccessGetSingle('EntityFinancialTrxn', $eftParams, $trxnTestArray);
1244 * Test for function createProportionalEntry with zero amount().
1246 * @param string $thousandSeparator
1247 * punctuation used to refer to thousands.
1249 * @dataProvider getThousandSeparators
1251 public function testCreateProportionalEntryZeroAmount($thousandSeparator) {
1252 $this->setCurrencySeparators($thousandSeparator);
1253 list($contribution, $financialAccount) = $this->createContributionWithTax(['total_amount' => 0]);
1255 'total_amount' => 0,
1256 'to_financial_account_id' => $financialAccount->financial_account_id
,
1257 'payment_instrument_id' => 1,
1258 'trxn_date' => date('Ymd'),
1260 'entity_id' => $contribution['id'],
1262 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'create', $params);
1264 'contribution_total_amount' => $contribution['total_amount'],
1265 'trxn_total_amount' => 0,
1266 'line_item_amount' => 0,
1268 $previousLineItem = CRM_Financial_BAO_FinancialItem
::getPreviousFinancialItem($contribution['id']);
1270 'entity_table' => 'civicrm_financial_item',
1271 'entity_id' => $previousLineItem['id'],
1272 'financial_trxn_id' => (string) $financialTrxn['id'],
1274 CRM_Contribute_BAO_Contribution
::createProportionalEntry($entityParams, $eftParams);
1275 $trxnTestArray = array_merge($eftParams, [
1278 $this->callAPISuccessGetSingle('EntityFinancialTrxn', $eftParams, $trxnTestArray);
1282 * Test for function getLastFinancialItemIds().
1284 public function testgetLastFinancialItemIds() {
1285 list($contribution, $financialAccount) = $this->createContributionWithTax();
1286 list($ftIds, $taxItems) = CRM_Contribute_BAO_Contribution
::getLastFinancialItemIds($contribution['id']);
1287 $this->assertEquals(count($ftIds), 1, 'Invalid count.');
1288 $this->assertEquals(count($taxItems), 1, 'Invalid count.');
1289 foreach ($taxItems as $value) {
1290 $this->assertEquals($value['amount'], 10, 'Invalid tax amount.');
1295 * Test to ensure proportional entries are creating when adding a payment..
1297 * In this test we create a pending contribution for $110 consisting of $100 contribution and $10 tax.
1299 * We pay $50, resulting in it being allocated as $45.45 paymnt & $4.55 tax. This is in equivalent proportions
1300 * to the original payment - ie. .0909 of the $110 is 10 & that * 50 is $4.54 (note the rounding seems wrong as it should be
1301 * saved un-rounded).
1303 public function testCreateProportionalFinancialEntriesViaPaymentCreate() {
1304 list($contribution, $financialAccount) = $this->createContributionWithTax([], FALSE);
1306 'total_amount' => 50,
1307 'to_financial_account_id' => $financialAccount->financial_account_id
,
1308 'payment_instrument_id' => 1,
1309 'trxn_date' => date('Ymd'),
1311 'entity_id' => $contribution['id'],
1312 'contribution_id' => $contribution['id'],
1314 $financialTrxn = $this->callAPISuccess('Payment', 'create', $params);
1316 'entity_table' => 'civicrm_financial_item',
1317 'financial_trxn_id' => $financialTrxn['id'],
1319 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'Get', $eftParams);
1320 $this->assertEquals($entityFinancialTrxn['count'], 2, 'Invalid count.');
1321 $testAmount = [4.55, 45.45];
1322 foreach ($entityFinancialTrxn['values'] as $value) {
1323 $this->assertEquals(array_pop($testAmount), $value['amount'], 'Invalid amount stored in civicrm_entity_financial_trxn.');
1328 * Test to check if amount is proportionally asigned for PI change.
1330 public function testProportionallyAssignedForPIChange() {
1331 list($contribution, $financialAccount) = $this->createContributionWithTax();
1333 'id' => $contribution['id'],
1334 'payment_instrument_id' => 3,
1336 $this->callAPISuccess('Contribution', 'create', $params);
1337 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn
::getFinancialTrxnId($contribution['id'], 'DESC');
1339 'entity_table' => 'civicrm_financial_item',
1340 'financial_trxn_id' => $lastFinancialTrxnId['financialTrxnId'],
1342 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'Get', $eftParams);
1343 $this->assertEquals($entityFinancialTrxn['count'], 2, 'Invalid count.');
1344 $testAmount = [10, 100];
1345 foreach ($entityFinancialTrxn['values'] as $value) {
1346 $this->assertEquals($value['amount'], array_pop($testAmount), 'Invalid amount stored in civicrm_entity_financial_trxn.');
1351 * Function to create contribution with tax.
1353 public function createContributionWithTax($params = [], $isCompleted = TRUE) {
1354 if (!isset($params['total_amount'])) {
1355 $params['total_amount'] = 100;
1357 $contactId = $this->individualCreate();
1358 $this->enableTaxAndInvoicing();
1359 $financialType = $this->createFinancialType();
1360 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1361 $form = new CRM_Contribute_Form_Contribution();
1364 'total_amount' => $params['total_amount'],
1365 'financial_type_id' => $financialType['id'],
1366 'contact_id' => $contactId,
1367 'contribution_status_id' => $isCompleted ?
1 : 2,
1368 'price_set_id' => 0,
1369 ], CRM_Core_Action
::ADD
);
1370 $contribution = $this->callAPISuccessGetSingle('Contribution',
1372 'contact_id' => $contactId,
1373 'return' => ['tax_amount', 'total_amount'],
1376 return [$contribution, $financialAccount];
1380 * Test processOnBehalfOrganization() function.
1382 public function testProcessOnBehalfOrganization() {
1384 'phone' => '11111111',
1385 'email' => 'testorg@gmail.com',
1386 'street_address' => 'test Street',
1387 'city' => 'test City',
1388 'state_province' => 'AA',
1389 'postal_code' => '222222',
1390 'country' => 'United States',
1392 $contactID = $this->individualCreate();
1393 $orgId = $this->organizationCreate(['organization_name' => 'testorg1']);
1394 $orgCount = $this->callAPISuccessGetCount('Contact', [
1395 'contact_type' => "Organization",
1396 'organization_name' => "testorg1",
1398 $this->assertEquals($orgCount, 1);
1400 $values = $params = [];
1401 $behalfOrganization = [
1402 'organization_name' => 'testorg1',
1405 'phone' => $orgInfo['phone'],
1411 'email' => $orgInfo['email'],
1417 'street_address' => $orgInfo['street_address'],
1418 'city' => $orgInfo['city'],
1419 'location_type_id' => 3,
1420 'postal_code' => $orgInfo['postal_code'],
1422 'state_province' => 'AA',
1428 'organization_name' => 1,
1431 'street_address-3' => 1,
1433 'postal_code-3' => 1,
1435 'state_province-3' => 1,
1437 CRM_Contribute_Form_Contribution_Confirm
::processOnBehalfOrganization($behalfOrganization, $contactID, $values, $params, $fields);
1439 //Check whether new organisation is not created.
1440 $result = $this->callAPISuccess('Contact', 'get', [
1441 'contact_type' => "Organization",
1442 'organization_name' => "testorg1",
1444 $this->assertEquals($result['count'], 1);
1446 //Assert all org values are updated.
1447 foreach ($orgInfo as $key => $val) {
1448 $this->assertEquals($result['values'][$orgId][$key], $val);
1451 //Check if alert is assigned to params if more than 1 dupe exists.
1452 $orgId = $this->organizationCreate(['organization_name' => 'testorg1', 'email' => 'testorg@gmail.com']);
1453 CRM_Contribute_Form_Contribution_Confirm
::processOnBehalfOrganization($behalfOrganization, $contactID, $values, $params, $fields);
1454 $this->assertEquals($params['onbehalf_dupe_alert'], 1);
1458 * Test for replaceContributionTokens.
1459 * This function tests whether the contribution tokens are replaced with values from contribution.
1461 public function testReplaceContributionTokens() {
1462 $customGroup = $this->customGroupCreate(['extends' => 'Contribution', 'title' => 'contribution stuff']);
1463 $customField = $this->customFieldOptionValueCreate($customGroup, 'myCustomField');
1464 $contactId1 = $this->individualCreate();
1466 'contact_id' => $contactId1,
1467 'receive_date' => '20120511',
1468 'total_amount' => 100.00,
1469 'financial_type_id' => 1,
1471 'invoice_id' => 67890,
1473 'contribution_status_id' => 2,
1474 "custom_{$customField['id']}" => 'value1',
1476 $contribution1 = $this->contributionCreate($params);
1477 $contactId2 = $this->individualCreate();
1479 'contact_id' => $contactId2,
1480 'receive_date' => '20150511',
1481 'total_amount' => 200.00,
1482 'financial_type_id' => 1,
1484 'invoice_id' => 12345,
1486 'contribution_status_id' => 1,
1487 "custom_{$customField['id']}" => 'value2',
1489 $contribution2 = $this->contributionCreate($params);
1490 $ids = [$contribution1, $contribution2];
1492 $subject = "This is a test for contribution ID: {contribution.contribution_id}";
1493 $text = "Contribution Amount: {contribution.total_amount}";
1494 $html = "<p>Contribution Source: {contribution.contribution_source}</p></br>
1495 <p>Contribution Invoice ID: {contribution.invoice_id}</p></br>
1496 <p>Contribution Receive Date: {contribution.receive_date}</p></br>
1497 <p>Contribution Custom Field: {contribution.custom_{$customField['id']}}</p></br>";
1499 $subjectToken = CRM_Utils_Token
::getTokens($subject);
1500 $messageToken = CRM_Utils_Token
::getTokens($text);
1501 $messageToken = array_merge($messageToken, CRM_Utils_Token
::getTokens($html));
1503 $contributionDetails = CRM_Contribute_BAO_Contribution
::replaceContributionTokens(
1513 $this->assertEquals("Contribution Amount: $ 100.00", $contributionDetails[$contactId1]['text'], "The text does not match");
1514 $this->assertEquals("<p>Contribution Source: ABC</p></br>
1515 <p>Contribution Invoice ID: 12345</p></br>
1516 <p>Contribution Receive Date: May 11th, 2015</p></br>
1517 <p>Contribution Custom Field: Label2</p></br>", $contributionDetails[$contactId2]['html'], "The html does not match");
1521 * Test for contribution with deferred revenue.
1523 public function testContributionWithDeferredRevenue() {
1524 $contactId = $this->individualCreate();
1525 Civi
::settings()->set('deferred_revenue_enabled', TRUE);
1527 'contact_id' => $contactId,
1528 'receive_date' => '20120511',
1529 'total_amount' => 100.00,
1530 'financial_type_id' => 'Event Fee',
1532 'invoice_id' => 67890,
1534 'contribution_status_id' => 'Completed',
1535 'revenue_recognition_date' => date('Ymd', strtotime("+3 month")),
1537 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1539 $this->callAPISuccessGetCount('EntityFinancialTrxn', [
1540 'entity_table' => "civicrm_contribution",
1541 'entity_id' => $contribution['id'],
1545 'financial_trxn_id.to_financial_account_id.name' => 'Deferred Revenue - Event Fee',
1546 'financial_trxn_id.from_financial_account_id.name' => 'Event Fee',
1547 'financial_trxn_id' => '2',
1549 $result = $this->callAPISuccessGetSingle('EntityFinancialTrxn', [
1551 "financial_trxn_id.from_financial_account_id.name",
1552 "financial_trxn_id.to_financial_account_id.name",
1553 "financial_trxn_id",
1555 'entity_table' => "civicrm_contribution",
1556 'entity_id' => $contribution['id'],
1557 'financial_trxn_id.is_payment' => 0,
1560 $result = $this->callAPISuccessGetSingle('EntityFinancialTrxn', [
1561 'entity_table' => "civicrm_financial_item",
1562 'financial_trxn_id' => $result['financial_trxn_id'],
1563 'return' => ['entity_id'],
1567 'financial_account_id.name' => 'Deferred Revenue - Event Fee',
1568 'id' => $result['entity_id'],
1570 $result = $this->callAPISuccessGetSingle('FinancialItem', [
1571 'id' => $result['entity_id'],
1572 'return' => ["financial_account_id.name"],
1577 * https://lab.civicrm.org/dev/financial/issues/56
1578 * Changing financial type on a contribution records correct financial items
1580 public function testChangingFinancialTypeWithoutTax() {
1581 $ids = $values = [];
1582 $contactId = $this->individualCreate();
1584 'contact_id' => $contactId,
1585 'receive_date' => date('YmdHis'),
1586 'total_amount' => 100.00,
1587 'financial_type_id' => 'Donation',
1588 'contribution_status_id' => 'Completed',
1590 /* first test the scenario when sending an email */
1591 $contributionId = $this->callAPISuccess(
1597 // Update Financial Type.
1598 $this->callAPISuccess('contribution', 'create', [
1599 'id' => $contributionId,
1600 'financial_type_id' => 'Event Fee',
1604 $lineItem = $this->callAPISuccessGetSingle('LineItem', [
1605 'contribution_id' => $contributionId,
1606 'return' => ["financial_type_id.name", "line_total"],
1609 $this->assertEquals(
1610 $lineItem['line_total'],
1612 'Invalid line amount.'
1615 $this->assertEquals(
1616 $lineItem['financial_type_id.name'],
1618 'Invalid Financial Type stored.'
1621 // Get Financial Items.
1622 $financialItems = $this->callAPISuccess('FinancialItem', 'get', [
1623 'entity_id' => $lineItem['id'],
1625 'entity_table' => 'civicrm_line_item',
1626 'options' => ['sort' => "id"],
1627 'return' => ["financial_account_id.name", "amount", "description"],
1630 $this->assertEquals($financialItems['count'], 3, 'Count mismatch.');
1633 ['Donation', 100.00],
1634 ['Donation', -100.00],
1635 ['Event Fee', 100.00],
1638 foreach ($financialItems['values'] as $key => $values) {
1639 $this->assertEquals(
1640 $values['financial_account_id.name'],
1642 'Invalid Financial Account stored.'
1644 $this->assertEquals(
1649 $this->assertEquals(
1650 $values['description'],
1651 'Contribution Amount',
1652 'Description mismatch.'
1656 // Check transactions.
1657 $financialTransactions = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
1658 'return' => ["financial_trxn_id"],
1659 'entity_table' => "civicrm_contribution",
1660 'entity_id' => $contributionId,
1663 $this->assertEquals($financialTransactions['count'], 3, 'Count mismatch.');
1665 foreach ($financialTransactions['values'] as $key => $values) {
1666 $this->callAPISuccessGetCount('EntityFinancialTrxn', [
1667 'financial_trxn_id' => $values['financial_trxn_id'],
1668 'amount' => $toCheck[$key][1],
1669 'financial_trxn_id.total_amount' => $toCheck[$key][1],
1675 * CRM-21424 Check if the receipt update is set after composing the receipt message
1677 public function testSendMailUpdateReceiptDate() {
1678 $ids = $values = [];
1679 $contactId = $this->individualCreate();
1681 'contact_id' => $contactId,
1682 'receive_date' => '20120511',
1683 'total_amount' => 100.00,
1684 'financial_type_id' => 'Donation',
1686 'contribution_status_id' => 'Completed',
1688 /* first test the scenario when sending an email */
1689 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1690 $contributionId = $contribution['id'];
1691 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After creating receipt date must be null');
1692 $input = ['receipt_update' => 0];
1693 CRM_Contribute_BAO_Contribution
::sendMail($input, $ids, $contributionId, $values);
1694 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail, with the explicit instruction not to update receipt date stays null');
1695 $input = ['receipt_update' => 1];
1696 CRM_Contribute_BAO_Contribution
::sendMail($input, $ids, $contributionId, $values);
1697 $this->assertDBNotNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail with the permission to allow update receipt date must be set');
1699 /* repeat the same scenario for downloading a pdf */
1700 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1701 $contributionId = $contribution['id'];
1702 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After creating receipt date must be null');
1703 $input = ['receipt_update' => 0];
1704 /* setting the lasast parameter (returnmessagetext) to TRUE is done by the download of the pdf */
1705 CRM_Contribute_BAO_Contribution
::sendMail($input, $ids, $contributionId, $values, TRUE);
1706 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail, with the explicit instruction not to update receipt date stays null');
1707 $input = ['receipt_update' => 1];
1708 CRM_Contribute_BAO_Contribution
::sendMail($input, $ids, $contributionId, $values, TRUE);
1709 $this->assertDBNotNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail with the permission to allow update receipt date must be set');