540f6fe9db414b90a0bd4bb6674a182a0844bd08
[civicrm-core.git] / tests / phpunit / CRM / Contribute / BAO / ContributionTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info'AT'civicrm'DOT'org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Class CRM_Contribute_BAO_ContributionTest
30 * @group headless
31 */
32 class CRM_Contribute_BAO_ContributionTest extends CiviUnitTestCase {
33
34 use CRMTraits_Financial_FinancialACLTrait;
35 use CRMTraits_Financial_PriceSetTrait;
36
37 /**
38 * Clean up after tests.
39 */
40 public function tearDown() {
41 $this->quickCleanUpFinancialEntities();
42 parent::tearDown();
43 }
44
45 /**
46 * Test create method (create and update modes).
47 */
48 public function testCreate() {
49 $contactId = $this->individualCreate();
50
51 $params = [
52 'contact_id' => $contactId,
53 'currency' => 'USD',
54 'financial_type_id' => 1,
55 'contribution_status_id' => 1,
56 'payment_instrument_id' => 1,
57 'source' => 'STUDENT',
58 'receive_date' => '20080522000000',
59 'receipt_date' => '20080522000000',
60 'non_deductible_amount' => 0.00,
61 'total_amount' => 200.00,
62 'fee_amount' => 5,
63 'net_amount' => 195,
64 'trxn_id' => '22ereerwww444444',
65 'invoice_id' => '86ed39c9e9ee6ef6031621ce0eafe7eb81',
66 'thankyou_date' => '20080522',
67 'sequential' => TRUE,
68 ];
69
70 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
71
72 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transaction id creation.');
73 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
74
75 //update contribution amount
76 $params['id'] = $contribution['id'];
77 $params['fee_amount'] = 10;
78 $params['net_amount'] = 190;
79
80 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
81
82 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id .');
83 $this->assertEquals($params['net_amount'], $contribution['net_amount'], 'Check for Amount updation.');
84 }
85
86 /**
87 * Create() method with custom data.
88 */
89 public function testCreateWithCustomData() {
90 $contactId = $this->individualCreate();
91
92 //create custom data
93 $customGroup = $this->customGroupCreate(['extends' => 'Contribution']);
94 $customGroupID = $customGroup['id'];
95 $customGroup = $customGroup['values'][$customGroupID];
96
97 $fields = [
98 'label' => 'testFld',
99 'data_type' => 'String',
100 'html_type' => 'Text',
101 'is_active' => 1,
102 'custom_group_id' => $customGroupID,
103 ];
104 $customField = CRM_Core_BAO_CustomField::create($fields);
105
106 $params = [
107 'contact_id' => $contactId,
108 'currency' => 'USD',
109 'financial_type_id' => 1,
110 'contribution_status_id' => 1,
111 'payment_instrument_id' => 1,
112 'source' => 'STUDENT',
113 'receive_date' => '20080522000000',
114 'receipt_date' => '20080522000000',
115 'id' => NULL,
116 'non_deductible_amount' => 0.00,
117 'total_amount' => 200.00,
118 'fee_amount' => 5,
119 'net_amount' => 195,
120 'trxn_id' => '22ereerwww322323',
121 'invoice_id' => '22ed39c9e9ee6ef6031621ce0eafe6da70',
122 'thankyou_date' => '20080522',
123 'skipCleanMoney' => TRUE,
124 ];
125
126 $params['custom'] = [
127 $customField->id => [
128 -1 => [
129 'value' => 'Test custom value',
130 'type' => 'String',
131 'custom_field_id' => $customField->id,
132 'custom_group_id' => $customGroupID,
133 'table_name' => $customGroup['table_name'],
134 'column_name' => $customField->column_name,
135 'file_id' => NULL,
136 ],
137 ],
138 ];
139
140 $contribution = CRM_Contribute_BAO_Contribution::create($params);
141
142 // Check that the custom field value is saved
143 $customValueParams = [
144 'entityID' => $contribution->id,
145 'custom_' . $customField->id => 1,
146 ];
147 $values = CRM_Core_BAO_CustomValueTable::getValues($customValueParams);
148 $this->assertEquals('Test custom value', $values['custom_' . $customField->id], 'Check the custom field value');
149
150 $this->assertEquals($params['trxn_id'], $contribution->trxn_id, 'Check for transcation id creation.');
151 $this->assertEquals($contactId, $contribution->contact_id, 'Check for contact id for Conribution.');
152 }
153
154 /**
155 * CRM-21026 Test ContributionCount after contribution created with disabled FT
156 */
157 public function testContributionCountDisabledFinancialType() {
158 $contactId = $this->individualCreate();
159 $financialType = [
160 'name' => 'grassvariety1' . substr(sha1(rand()), 0, 7),
161 'is_reserved' => 0,
162 'is_active' => 0,
163 ];
164 $finType = $this->callAPISuccess('financial_type', 'create', $financialType);
165 $params = [
166 'contact_id' => $contactId,
167 'currency' => 'USD',
168 'financial_type_id' => $finType['id'],
169 'contribution_status_id' => 1,
170 'payment_instrument_id' => 1,
171 'source' => 'STUDENT',
172 'receive_date' => '20080522000000',
173 'receipt_date' => '20080522000000',
174 'id' => NULL,
175 'non_deductible_amount' => 0.00,
176 'total_amount' => 200.00,
177 'fee_amount' => 5,
178 'net_amount' => 195,
179 'trxn_id' => '22ereerwww322323',
180 'invoice_id' => '22ed39c9e9ee6ef6031621ce0eafe6da70',
181 'thankyou_date' => '20080522',
182 ];
183 $this->callAPISuccess('Contribution', 'create', $params);
184 $this->callAPISuccess('financial_type', 'create', ['is_active' => 0, 'id' => $finType['id']]);
185 $contributionCount = CRM_Contribute_BAO_Contribution::contributionCount($contactId);
186 $this->assertEquals(1, $contributionCount);
187 }
188
189 /**
190 * DeleteContribution() method
191 */
192 public function testDeleteContribution() {
193 $contactId = $this->individualCreate();
194
195 $params = [
196 'contact_id' => $contactId,
197 'currency' => 'USD',
198 'financial_type_id' => 1,
199 'contribution_status_id' => 1,
200 'payment_instrument_id' => 1,
201 'source' => 'STUDENT',
202 'receive_date' => '20080522000000',
203 'receipt_date' => '20080522000000',
204 'id' => NULL,
205 'non_deductible_amount' => 0.00,
206 'total_amount' => 200.00,
207 'fee_amount' => 5,
208 'net_amount' => 195,
209 'trxn_id' => '33ereerwww322323',
210 'invoice_id' => '33ed39c9e9ee6ef6031621ce0eafe6da70',
211 'thankyou_date' => '20080522',
212 'sequential' => TRUE,
213 ];
214
215 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
216
217 CRM_Contribute_BAO_Contribution::deleteContribution($contribution['id']);
218
219 $this->assertDBNull('CRM_Contribute_DAO_Contribution', $contribution['trxn_id'],
220 'id', 'trxn_id', 'Database check for deleted Contribution.'
221 );
222 }
223
224 /**
225 * Create honor-contact method.
226 */
227 public function testCreateAndGetHonorContact() {
228 $firstName = 'John_' . substr(sha1(rand()), 0, 7);
229 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
230 $email = "{$firstName}.{$lastName}@example.com";
231
232 //Get profile id of name honoree_individual used to create profileContact
233 $honoreeProfileId = NULL;
234 $ufGroupDAO = new CRM_Core_DAO_UFGroup();
235 $ufGroupDAO->name = 'honoree_individual';
236 if ($ufGroupDAO->find(TRUE)) {
237 $honoreeProfileId = $ufGroupDAO->id;
238 }
239
240 $params = [
241 'prefix_id' => 3,
242 'first_name' => $firstName,
243 'last_name' => $lastName,
244 'email-1' => $email,
245 ];
246 $softParam = ['soft_credit_type_id' => 1];
247
248 $null = [];
249 $honoreeContactId = CRM_Contact_BAO_Contact::createProfileContact($params, $null,
250 NULL, NULL, $honoreeProfileId
251 );
252
253 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName,
254 'Database check for created honor contact record.'
255 );
256 //create contribution on behalf of honary.
257
258 $contactId = $this->individualCreate(['first_name' => 'John', 'last_name' => 'Doe']);
259
260 $param = [
261 'contact_id' => $contactId,
262 'currency' => 'USD',
263 'financial_type_id' => 4,
264 'contribution_status_id' => 1,
265 'receive_date' => date('Ymd'),
266 'total_amount' => 66,
267 'sequential' => 1,
268 ];
269
270 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
271 $id = $contribution['id'];
272 $softParam['contact_id'] = $honoreeContactId;
273 $softParam['contribution_id'] = $id;
274 $softParam['currency'] = $contribution['currency'];
275 $softParam['amount'] = $contribution['total_amount'];
276
277 //Create Soft Contribution for honoree contact
278 CRM_Contribute_BAO_ContributionSoft::add($softParam);
279
280 $this->assertDBCompareValue('CRM_Contribute_DAO_ContributionSoft', $id, 'contact_id',
281 'contribution_id', $honoreeContactId, 'Check DB for honor contact of the contribution'
282 );
283 //get honorary information
284 $getHonorContact = CRM_Contribute_BAO_Contribution::getHonorContacts($honoreeContactId);
285 $this->assertEquals([
286 $id => [
287 'honor_type' => 'In Honor of',
288 'honorId' => $contactId,
289 'display_name' => 'Mr. John Doe II',
290 'type' => 'Event Fee',
291 'type_id' => '4',
292 'amount' => '$ 66.00',
293 'source' => NULL,
294 'receive_date' => date('Y-m-d 00:00:00'),
295 'contribution_status' => 'Completed',
296 ],
297 ], $getHonorContact);
298
299 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName,
300 'Database check for created honor contact record.'
301 );
302
303 //get annual contribution information
304 $annual = CRM_Contribute_BAO_Contribution::annual($contactId);
305
306 $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', CRM_Core_Config::singleton()->defaultCurrency, 'symbol', 'name');
307 $this->assertDBCompareValue('CRM_Contribute_DAO_Contribution', $id, 'total_amount',
308 'id', ltrim($annual[2], $currencySymbol), 'Check DB for total amount of the contribution'
309 );
310 }
311
312 /**
313 * Test that financial type data is not added to the annual query if acls not enabled.
314 */
315 public function testAnnualQueryWithFinancialACLsEnabled() {
316 $this->enableFinancialACLs();
317 $this->createLoggedInUserWithFinancialACL();
318 $permittedFinancialType = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'financial_type_id', 'Donation');
319 $sql = CRM_Contribute_BAO_Contribution::getAnnualQuery([1, 2, 3]);
320 $this->assertContains('SUM(total_amount) as amount,', $sql);
321 $this->assertContains('WHERE b.contact_id IN (1,2,3)', $sql);
322 $this->assertContains('b.financial_type_id IN (' . $permittedFinancialType . ')', $sql);
323
324 // Run it to make sure it's not bad sql.
325 CRM_Core_DAO::executeQuery($sql);
326 $this->disableFinancialACLs();
327 }
328
329 /**
330 * Test the annual query returns a correct result when multiple line items are present.
331 */
332 public function testAnnualWithMultipleLineItems() {
333 $contactID = $this->createLoggedInUserWithFinancialACL();
334 $this->createContributionWithTwoLineItemsAgainstPriceSet([
335 'contact_id' => $contactID,
336 ]
337 );
338 $this->enableFinancialACLs();
339 $sql = CRM_Contribute_BAO_Contribution::getAnnualQuery([$contactID]);
340 $result = CRM_Core_DAO::executeQuery($sql);
341 $result->fetch();
342 $this->assertEquals(300, $result->amount);
343 $this->assertEquals(1, $result->count);
344 $this->disableFinancialACLs();
345 }
346
347 /**
348 * Test that financial type data is not added to the annual query if acls not enabled.
349 */
350 public function testAnnualQueryWithFinancialACLsDisabled() {
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->assertNotContains('b.financial_type_id', $sql);
355 //$this->assertNotContains('line_item', $sql);
356 // Run it to make sure it's not bad sql.
357 CRM_Core_DAO::executeQuery($sql);
358 }
359
360 /**
361 * Test that financial type data is not added to the annual query if acls not enabled.
362 */
363 public function testAnnualQueryWithFinancialHook() {
364 $this->hookClass->setHook('civicrm_selectWhereClause', [$this, 'aclIdNoZero']);
365 $sql = CRM_Contribute_BAO_Contribution::getAnnualQuery([1, 2, 3]);
366 $this->assertContains('SUM(total_amount) as amount,', $sql);
367 $this->assertContains('WHERE b.contact_id IN (1,2,3)', $sql);
368 $this->assertContains('b.id NOT IN (0)', $sql);
369 $this->assertNotContains('b.financial_type_id', $sql);
370 CRM_Core_DAO::executeQuery($sql);
371 }
372
373 /**
374 * Add ACL denying values LIKE '0'.
375 *
376 * @param string $entity
377 * @param string $clauses
378 */
379 public function aclIdNoZero($entity, &$clauses) {
380 if ($entity != 'Contribution') {
381 return;
382 }
383 $clauses['id'] = "NOT IN (0)";
384 }
385
386 /**
387 * Display sort name during.
388 * Update multiple contributions
389 * sortName();
390 */
391 public function testsortName() {
392 $params = [
393 'first_name' => 'Shane',
394 'last_name' => 'Whatson',
395 'contact_type' => 'Individual',
396 ];
397
398 $contact = CRM_Contact_BAO_Contact::add($params);
399
400 //Now check $contact is object of contact DAO..
401 $this->assertInstanceOf('CRM_Contact_DAO_Contact', $contact, 'Check for created object');
402
403 $contactId = $contact->id;
404 $param = [
405 'contact_id' => $contactId,
406 'currency' => 'USD',
407 'financial_type_id' => 1,
408 'contribution_status_id' => 1,
409 'payment_instrument_id' => 1,
410 'source' => 'STUDENT',
411 'receive_date' => '20080522000000',
412 'receipt_date' => '20080522000000',
413 'id' => NULL,
414 'non_deductible_amount' => 0.00,
415 'total_amount' => 300.00,
416 'fee_amount' => 5,
417 'net_amount' => 295,
418 'trxn_id' => '22ereerwww323',
419 'invoice_id' => '22ed39c9e9ee621ce0eafe6da70',
420 'thankyou_date' => '20080522',
421 'sequential' => TRUE,
422 ];
423
424 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
425
426 $this->assertEquals($param['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
427 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
428
429 //display sort name during Update multiple contributions
430 $sortName = CRM_Contribute_BAO_Contribution::sortName($contribution['id']);
431
432 $this->assertEquals('Whatson, Shane', $sortName, 'Check for sort name.');
433 }
434
435 /**
436 * Add premium during online Contribution.
437 *
438 * AddPremium();
439 */
440 public function testAddPremium() {
441 $contactId = $this->individualCreate();
442
443 $params = [
444 'name' => 'TEST Premium',
445 'sku' => 111,
446 'imageOption' => 'noImage',
447 'MAX_FILE_SIZE' => 2097152,
448 'price' => 100.00,
449 'cost' => 90.00,
450 'min_contribution' => 100,
451 'is_active' => 1,
452 ];
453 $premium = CRM_Contribute_BAO_Product::create($params);
454
455 $this->assertEquals('TEST Premium', $premium->name, 'Check for premium name.');
456
457 $contributionParams = [
458 'contact_id' => $contactId,
459 'currency' => 'USD',
460 'financial_type_id' => 1,
461 'contribution_status_id' => 1,
462 'payment_instrument_id' => 1,
463 'source' => 'STUDENT',
464 'receive_date' => '20080522000000',
465 'receipt_date' => '20080522000000',
466 'id' => NULL,
467 'non_deductible_amount' => 0.00,
468 'total_amount' => 300.00,
469 'fee_amount' => 5,
470 'net_amount' => 295,
471 'trxn_id' => '33erdfrwvw434',
472 'invoice_id' => '98ed34f7u9hh672ce0eafe8fb92',
473 'thankyou_date' => '20080522',
474 'sequential' => TRUE,
475 ];
476 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams)['values'][0];
477
478 $this->assertEquals($contributionParams['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
479 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
480
481 //parameter for adding premium to contribution
482 $data = [
483 'product_id' => $premium->id,
484 'contribution_id' => $contribution['id'],
485 'product_option' => NULL,
486 'quantity' => 1,
487 ];
488 $contributionProduct = CRM_Contribute_BAO_Contribution::addPremium($data);
489 $this->assertEquals($contributionProduct->product_id, $premium->id, 'Check for Product id .');
490
491 //Delete Product
492 CRM_Contribute_BAO_Product::del($premium->id);
493 $this->assertDBNull('CRM_Contribute_DAO_Product', $premium->name,
494 'id', 'name', 'Database check for deleted Product.'
495 );
496 }
497
498 /**
499 * Check duplicate contribution id.
500 * during the contribution import
501 * checkDuplicateIds();
502 */
503 public function testcheckDuplicateIds() {
504 $contactId = $this->individualCreate();
505
506 $param = [
507 'contact_id' => $contactId,
508 'currency' => 'USD',
509 'financial_type_id' => 1,
510 'contribution_status_id' => 1,
511 'payment_instrument_id' => 1,
512 'source' => 'STUDENT',
513 'receive_date' => '20080522000000',
514 'receipt_date' => '20080522000000',
515 'id' => NULL,
516 'non_deductible_amount' => 0.00,
517 'total_amount' => 300.00,
518 'fee_amount' => 5,
519 'net_amount' => 295,
520 'trxn_id' => '76ereeswww835',
521 'invoice_id' => '93ed39a9e9hd621bs0eafe3da82',
522 'thankyou_date' => '20080522',
523 'sequential' => TRUE,
524 ];
525
526 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
527
528 $this->assertEquals($param['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
529 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
530 $data = [
531 'id' => $contribution['id'],
532 'trxn_id' => $contribution['trxn_id'],
533 'invoice_id' => $contribution['invoice_id'],
534 ];
535 $contributionID = CRM_Contribute_BAO_Contribution::checkDuplicateIds($data);
536 $this->assertEquals($contributionID, $contribution['id'], 'Check for duplicate transcation id .');
537 }
538
539 /**
540 * Check credit note id creation
541 * when a contribution is cancelled or refunded
542 * createCreditNoteId();
543 */
544 public function testCreateCreditNoteId() {
545 $contactId = $this->individualCreate();
546
547 $param = [
548 'contact_id' => $contactId,
549 'currency' => 'USD',
550 'financial_type_id' => 1,
551 'contribution_status_id' => 3,
552 'payment_instrument_id' => 1,
553 'source' => 'STUDENT',
554 'receive_date' => '20080522000000',
555 'receipt_date' => '20080522000000',
556 'id' => NULL,
557 'non_deductible_amount' => 0.00,
558 'total_amount' => 300.00,
559 'fee_amount' => 5,
560 'net_amount' => 295,
561 'trxn_id' => '76ereeswww835',
562 'invoice_id' => '93ed39a9e9hd621bs0eafe3da82',
563 'thankyou_date' => '20080522',
564 'sequential' => TRUE,
565 ];
566
567 $creditNoteId = CRM_Contribute_BAO_Contribution::createCreditNoteId();
568 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
569 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
570 $this->assertEquals($creditNoteId, $contribution['creditnote_id'], 'Check if credit note id is created correctly.');
571 }
572
573 /**
574 * Create() method (create and update modes).
575 */
576 public function testIsPaymentFlag() {
577 $contactId = $this->individualCreate();
578
579 $params = [
580 'contact_id' => $contactId,
581 'currency' => 'USD',
582 'financial_type_id' => 1,
583 'contribution_status_id' => 1,
584 'payment_instrument_id' => 1,
585 'source' => 'STUDENT',
586 'receive_date' => '20080522000000',
587 'receipt_date' => '20080522000000',
588 'non_deductible_amount' => 0.00,
589 'total_amount' => 200.00,
590 'fee_amount' => 5,
591 'net_amount' => 195,
592 'trxn_id' => '22ereerwww4444xx',
593 'invoice_id' => '86ed39c9e9ee6ef6541621ce0eafe7eb81',
594 'thankyou_date' => '20080522',
595 'sequential' => TRUE,
596 ];
597 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
598
599 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
600 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
601
602 $trxnArray = [
603 'trxn_id' => $params['trxn_id'],
604 'is_payment' => 1,
605 ];
606 $defaults = [];
607 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
608 $this->assertEquals(1, $financialTrxn->N, 'Mismatch count for is payment flag.');
609 //update contribution amount
610 $params['id'] = $contribution['id'];
611 $params['total_amount'] = 150;
612 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
613
614 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id .');
615 $this->assertEquals($params['total_amount'], $contribution['total_amount'], 'Check for Amount updation.');
616 $trxnArray = [
617 'trxn_id' => $params['trxn_id'],
618 'is_payment' => 1,
619 ];
620 $defaults = [];
621 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
622 $this->assertEquals(2, $financialTrxn->N, 'Mismatch count for is payment flag.');
623 $trxnArray['is_payment'] = 0;
624 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
625 $this->assertEquals(1, $financialTrxn->N, 'Mismatch count for is payment flag.');
626 }
627
628 /**
629 * Create() method (create and update modes).
630 */
631 public function testIsPaymentFlagForPending() {
632 $contactId = $this->individualCreate();
633
634 $params = [
635 'contact_id' => $contactId,
636 'currency' => 'USD',
637 'financial_type_id' => 1,
638 'contribution_status_id' => 2,
639 'payment_instrument_id' => 1,
640 'source' => 'STUDENT',
641 'is_pay_later' => 1,
642 'receive_date' => '20080522000000',
643 'receipt_date' => '20080522000000',
644 'non_deductible_amount' => 0.00,
645 'total_amount' => 200.00,
646 'fee_amount' => 5,
647 'net_amount' => 195,
648 'trxn_id' => '22ereerwww4444yy',
649 'invoice_id' => '86ed39c9e9yy6ef6541621ce0eafe7eb81',
650 'thankyou_date' => '20080522',
651 'sequential' => TRUE,
652 ];
653
654 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
655
656 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transaction id creation.');
657 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
658
659 $trxnArray = [
660 'trxn_id' => $params['trxn_id'],
661 'is_payment' => 0,
662 ];
663 $defaults = [];
664 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
665 $this->assertEquals(2, $financialTrxn->N, 'Mismatch count for is payment flag.');
666 $trxnArray['is_payment'] = 1;
667 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
668 $this->assertEquals(NULL, $financialTrxn, 'Mismatch count for is payment flag.');
669 //update contribution amount
670 $params['id'] = $contribution['id'];
671 $params['contribution_status_id'] = 1;
672
673 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
674
675 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id .');
676 $this->assertEquals($params['contribution_status_id'], $contribution['contribution_status_id'], 'Check for status updation.');
677 $trxnArray = [
678 'trxn_id' => $params['trxn_id'],
679 'is_payment' => 1,
680 ];
681 $defaults = [];
682 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
683 $this->assertEquals(1, $financialTrxn->N, 'Mismatch count for is payment flag.');
684 $trxnArray['is_payment'] = 0;
685 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
686 $this->assertEquals(2, $financialTrxn->N, 'Mismatch count for is payment flag.');
687 }
688
689 /**
690 * addPayments() method (add and edit modes of participant)
691 */
692 public function testAddPayments() {
693 list($lineItems, $contribution) = $this->addParticipantWithContribution();
694 CRM_Contribute_BAO_Contribution::addPayments([$contribution]);
695 $this->checkItemValues($contribution);
696 }
697
698 /**
699 * checks db values for financial item
700 */
701 public function checkItemValues($contribution) {
702 $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(4, 'Accounts Receivable Account is');
703 $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')
704 INNER JOIN civicrm_entity_financial_trxn eft1 ON (eft1.financial_trxn_id = eft.financial_trxn_id AND eft1.entity_table = 'civicrm_financial_item')
705 WHERE eft.entity_id = %1 AND ft.to_financial_account_id <> %2";
706
707 $queryParams[1] = [$contribution->id, 'Integer'];
708 $queryParams[2] = [$toFinancialAccount, 'Integer'];
709
710 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
711 $amounts = [100.00, 50.00];
712 while ($dao->fetch()) {
713 $this->assertEquals(150.00, $dao->total_amount, 'Mismatch of total amount paid.');
714 $this->assertEquals($dao->amount, array_pop($amounts), 'Mismatch of amount proportionally assigned to financial item');
715 }
716 }
717
718 /**
719 * assignProportionalLineItems() method (add and edit modes of participant)
720 */
721 public function testAssignProportionalLineItems() {
722 list($lineItems, $contribution) = $this->addParticipantWithContribution();
723 $params = [
724 'contribution_id' => $contribution->id,
725 'total_amount' => 150.00,
726 ];
727 $trxn = new CRM_Financial_DAO_FinancialTrxn();
728 $trxn->orderBy('id DESC');
729 $trxn->find(TRUE);
730 CRM_Contribute_BAO_Contribution::assignProportionalLineItems($params, $trxn->id, $contribution->total_amount);
731 $this->checkItemValues($contribution);
732 }
733
734 /**
735 * Add participant with contribution
736 *
737 * @return array
738 */
739 public function addParticipantWithContribution() {
740 // creating price set, price field
741 $this->_contactId = $this->individualCreate();
742 $event = $this->eventCreate();
743 $this->_eventId = $event['id'];
744 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 4);
745 $paramsSet['name'] = CRM_Utils_String::titleToVar($paramsSet['title']);
746 $paramsSet['is_active'] = TRUE;
747 $paramsSet['financial_type_id'] = 4;
748 $paramsSet['extends'] = 1;
749
750 $priceset = CRM_Price_BAO_PriceSet::create($paramsSet);
751 $priceSetId = $priceset->id;
752
753 //Checking for priceset added in the table.
754 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
755 'id', $paramsSet['title'], 'Check DB for created priceset'
756 );
757 $paramsField = [
758 'label' => 'Price Field',
759 'name' => CRM_Utils_String::titleToVar('Price Field'),
760 'html_type' => 'CheckBox',
761 'option_label' => ['1' => 'Price Field 1', '2' => 'Price Field 2'],
762 'option_value' => ['1' => 100, '2' => 200],
763 'option_name' => ['1' => 'Price Field 1', '2' => 'Price Field 2'],
764 'option_weight' => ['1' => 1, '2' => 2],
765 'option_amount' => ['1' => 100, '2' => 200],
766 'is_display_amounts' => 1,
767 'weight' => 1,
768 'options_per_line' => 1,
769 'is_active' => ['1' => 1, '2' => 1],
770 'price_set_id' => $priceset->id,
771 'is_enter_qty' => 1,
772 'financial_type_id' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
773 ];
774 $priceField = CRM_Price_BAO_PriceField::create($paramsField);
775 $eventParams = [
776 'id' => $this->_eventId,
777 'financial_type_id' => 4,
778 'is_monetary' => 1,
779 ];
780 CRM_Event_BAO_Event::create($eventParams);
781 CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_eventId, $priceSetId);
782
783 $priceFields = $this->callAPISuccess('PriceFieldValue', 'get', ['price_field_id' => $priceField->id]);
784 $participantParams = [
785 'financial_type_id' => 4,
786 'event_id' => $this->_eventId,
787 'role_id' => 1,
788 'status_id' => 14,
789 'fee_currency' => 'USD',
790 'contact_id' => $this->_contactId,
791 ];
792 $participant = CRM_Event_BAO_Participant::add($participantParams);
793 $contributionParams = [
794 'total_amount' => 150,
795 'currency' => 'USD',
796 'contact_id' => $this->_contactId,
797 'financial_type_id' => 4,
798 'contribution_status_id' => 1,
799 'partial_payment_total' => 300.00,
800 'partial_amount_to_pay' => 150,
801 'contribution_mode' => 'participant',
802 'participant_id' => $participant->id,
803 'sequential' => TRUE,
804 ];
805
806 foreach ($priceFields['values'] as $key => $priceField) {
807 $lineItems[1][$key] = [
808 'price_field_id' => $priceField['price_field_id'],
809 'price_field_value_id' => $priceField['id'],
810 'label' => $priceField['label'],
811 'field_title' => $priceField['label'],
812 'qty' => 1,
813 'unit_price' => $priceField['amount'],
814 'line_total' => $priceField['amount'],
815 'financial_type_id' => $priceField['financial_type_id'],
816 ];
817 }
818 $contributionParams['line_item'] = $lineItems;
819 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams)['values'][0];
820
821 $paymentParticipant = [
822 'participant_id' => $participant->id,
823 'contribution_id' => $contribution['id'],
824 ];
825 CRM_Event_BAO_ParticipantPayment::create($paymentParticipant);
826
827 $contributionObject = new CRM_Contribute_BAO_Contribution();
828 $contributionObject->id = $contribution['id'];
829 $contributionObject->find(TRUE);
830
831 return [$lineItems, $contributionObject];
832 }
833
834 /**
835 * checkLineItems() check if total amount matches the sum of line total
836 */
837 public function testcheckLineItems() {
838 $params = [
839 'contact_id' => 202,
840 'receive_date' => '2010-01-20',
841 'total_amount' => 100,
842 'financial_type_id' => 3,
843 'line_items' => [
844 [
845 'line_item' => [
846 [
847 'entity_table' => 'civicrm_contribution',
848 'price_field_id' => 8,
849 'price_field_value_id' => 16,
850 'label' => 'test 1',
851 'qty' => 1,
852 'unit_price' => 100,
853 'line_total' => 100,
854 ],
855 [
856 'entity_table' => 'civicrm_contribution',
857 'price_field_id' => 8,
858 'price_field_value_id' => 17,
859 'label' => 'Test 2',
860 'qty' => 1,
861 'unit_price' => 200,
862 'line_total' => 200,
863 'financial_type_id' => 1,
864 ],
865 ],
866 'params' => [],
867 ],
868 ],
869 ];
870
871 try {
872 CRM_Contribute_BAO_Contribution::checkLineItems($params);
873 $this->fail("Missed expected exception");
874 }
875 catch (CRM_Contribute_Exception_CheckLineItemsException $e) {
876 $this->assertEquals(
877 CRM_Contribute_Exception_CheckLineItemsException::LINE_ITEM_DIFFERRING_TOTAL_EXCEPTON_MSG,
878 $e->getMessage()
879 );
880 }
881
882 $this->assertEquals(3, $params['line_items'][0]['line_item'][0]['financial_type_id']);
883 $params['total_amount'] = 300;
884
885 CRM_Contribute_BAO_Contribution::checkLineItems($params);
886 }
887
888 /**
889 * Tests CRM_Contribute_BAO_Contribution::checkLineItems() method works with
890 * floating point values.
891 */
892 public function testCheckLineItemsWithFloatingPointValues() {
893 $params = [
894 'contact_id' => 202,
895 'receive_date' => date('Y-m-d'),
896 'total_amount' => 16.67,
897 'financial_type_id' => 3,
898 'line_items' => [
899 [
900 'line_item' => [
901 [
902 'entity_table' => 'civicrm_contribution',
903 'price_field_id' => 8,
904 'price_field_value_id' => 16,
905 'label' => 'test 1',
906 'qty' => 1,
907 'unit_price' => 14.85,
908 'line_total' => 14.85,
909 ],
910 [
911 'entity_table' => 'civicrm_contribution',
912 'price_field_id' => 8,
913 'price_field_value_id' => 17,
914 'label' => 'Test 2',
915 'qty' => 1,
916 'unit_price' => 1.66,
917 'line_total' => 1.66,
918 'financial_type_id' => 1,
919 ],
920 [
921 'entity_table' => 'civicrm_contribution',
922 'price_field_id' => 8,
923 'price_field_value_id' => 17,
924 'label' => 'Test 2',
925 'qty' => 1,
926 'unit_price' => 0.16,
927 'line_total' => 0.16,
928 'financial_type_id' => 1,
929 ],
930 ],
931 'params' => [],
932 ],
933 ],
934 ];
935
936 $foundException = FALSE;
937
938 try {
939 CRM_Contribute_BAO_Contribution::checkLineItems($params);
940 }
941 catch (CRM_Contribute_Exception_CheckLineItemsException $e) {
942 $foundException = TRUE;
943 }
944
945 $this->assertFalse($foundException);
946 }
947
948 /**
949 * Test activity amount updation.
950 */
951 public function testActivityCreate() {
952 $contactId = $this->individualCreate();
953 $defaults = [];
954
955 $params = [
956 'contact_id' => $contactId,
957 'currency' => 'USD',
958 'financial_type_id' => 1,
959 'contribution_status_id' => 1,
960 'payment_instrument_id' => 1,
961 'source' => 'STUDENT',
962 'receive_date' => '20080522000000',
963 'receipt_date' => '20080522000000',
964 'non_deductible_amount' => 0.00,
965 'total_amount' => 100.00,
966 'trxn_id' => '22ereerwww444444',
967 'invoice_id' => '86ed39c9e9ee6ef6031621ce0eafe7eb81',
968 'thankyou_date' => '20160519',
969 'sequential' => 1,
970 ];
971
972 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
973
974 $this->assertEquals($params['total_amount'], $contribution['total_amount'], 'Check for total amount in contribution.');
975 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
976
977 // Check amount in activity.
978 $activityParams = [
979 'source_record_id' => $contribution['id'],
980 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Contribution'),
981 ];
982 // @todo use api instead.
983 $activity = CRM_Activity_BAO_Activity::retrieve($activityParams, $defaults);
984
985 $this->assertEquals($contribution['id'], $activity->source_record_id, 'Check for activity associated with contribution.');
986 $this->assertEquals("$ 100.00 - STUDENT", $activity->subject, 'Check for total amount in activity.');
987
988 $params['id'] = $contribution['id'];
989 $params['total_amount'] = 200;
990
991 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
992
993 $this->assertEquals($params['total_amount'], $contribution['total_amount'], 'Check for total amount in contribution.');
994 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
995
996 // Retrieve activity again.
997 $activity = CRM_Activity_BAO_Activity::retrieve($activityParams, $defaults);
998
999 $this->assertEquals($contribution['id'], $activity->source_record_id, 'Check for activity associated with contribution.');
1000 $this->assertEquals("$ 200.00 - STUDENT", $activity->subject, 'Check for total amount in activity.');
1001 }
1002
1003 /**
1004 * Test allowUpdateRevenueRecognitionDate.
1005 */
1006 public function testAllowUpdateRevenueRecognitionDate() {
1007 $contactId = $this->individualCreate();
1008 $params = [
1009 'contact_id' => $contactId,
1010 'receive_date' => '2010-01-20',
1011 'total_amount' => 100,
1012 'financial_type_id' => 4,
1013 ];
1014 $order = $this->callAPISuccess('order', 'create', $params);
1015 $allowUpdate = CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($order['id']);
1016 $this->assertTrue($allowUpdate);
1017
1018 $event = $this->eventCreate();
1019 $params = [
1020 'contact_id' => $contactId,
1021 'receive_date' => '2010-01-20',
1022 'total_amount' => 300,
1023 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
1024 'contribution_status_id' => 'Completed',
1025 ];
1026 $priceFields = $this->createPriceSet('event', $event['id']);
1027 foreach ($priceFields['values'] as $key => $priceField) {
1028 $lineItems[$key] = [
1029 'price_field_id' => $priceField['price_field_id'],
1030 'price_field_value_id' => $priceField['id'],
1031 'label' => $priceField['label'],
1032 'field_title' => $priceField['label'],
1033 'qty' => 1,
1034 'unit_price' => $priceField['amount'],
1035 'line_total' => $priceField['amount'],
1036 'financial_type_id' => $priceField['financial_type_id'],
1037 'entity_table' => 'civicrm_participant',
1038 ];
1039 }
1040 $params['line_items'][] = [
1041 'line_item' => $lineItems,
1042 'params' => [
1043 'contact_id' => $contactId,
1044 'event_id' => $event['id'],
1045 'status_id' => 1,
1046 'role_id' => 1,
1047 'register_date' => '2007-07-21 00:00:00',
1048 'source' => 'Online Event Registration: API Testing',
1049 ],
1050 ];
1051 $order = $this->callAPISuccess('order', 'create', $params);
1052 $allowUpdate = CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($order['id']);
1053 $this->assertFalse($allowUpdate);
1054
1055 $params = [
1056 'contact_id' => $contactId,
1057 'receive_date' => '2010-01-20',
1058 'total_amount' => 200,
1059 'financial_type_id' => $this->getFinancialTypeId('Member Dues'),
1060 'contribution_status_id' => 'Completed',
1061 ];
1062 $membershipType = $this->membershipTypeCreate();
1063 $priceFields = $this->createPriceSet();
1064 $lineItems = [];
1065 foreach ($priceFields['values'] as $key => $priceField) {
1066 $lineItems[$key] = [
1067 'price_field_id' => $priceField['price_field_id'],
1068 'price_field_value_id' => $priceField['id'],
1069 'label' => $priceField['label'],
1070 'field_title' => $priceField['label'],
1071 'qty' => 1,
1072 'unit_price' => $priceField['amount'],
1073 'line_total' => $priceField['amount'],
1074 'financial_type_id' => $priceField['financial_type_id'],
1075 'entity_table' => 'civicrm_membership',
1076 'membership_type_id' => $membershipType,
1077 ];
1078 }
1079 $params['line_items'][] = [
1080 'line_item' => [array_pop($lineItems)],
1081 'params' => [
1082 'contact_id' => $contactId,
1083 'membership_type_id' => $membershipType,
1084 'join_date' => '2006-01-21',
1085 'start_date' => '2006-01-21',
1086 'end_date' => '2006-12-21',
1087 'source' => 'Payment',
1088 'is_override' => 1,
1089 'status_id' => 1,
1090 ],
1091 ];
1092 $order = $this->callAPISuccess('order', 'create', $params);
1093 $allowUpdate = CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($order['id']);
1094 $this->assertFalse($allowUpdate);
1095 }
1096
1097 /**
1098 * Test calculateFinancialItemAmount().
1099 */
1100 public function testcalculateFinancialItemAmount() {
1101 $testParams = [
1102 [
1103 'params' => [],
1104 'amountParams' => [
1105 'line_total' => 100,
1106 'previous_line_total' => 300,
1107 'diff' => 1,
1108 ],
1109 'context' => 'changedAmount',
1110 'expectedItemAmount' => -200,
1111 ],
1112 [
1113 'params' => [],
1114 'amountParams' => [
1115 'line_total' => 100,
1116 'previous_line_total' => 100,
1117 'diff' => -1,
1118 ],
1119 // Most contexts are ignored. Removing refs to change payment instrument so placeholder.
1120 'context' => 'not null',
1121 'expectedItemAmount' => -100,
1122 ],
1123 [
1124 'params' => [
1125 'is_quick_config' => TRUE,
1126 'total_amount' => 110,
1127 'tax_amount' => 10,
1128 ],
1129 'amountParams' => [
1130 'item_amount' => 100,
1131 ],
1132 'context' => 'changedAmount',
1133 'expectedItemAmount' => 100,
1134 ],
1135 [
1136 'params' => [
1137 'is_quick_config' => TRUE,
1138 'total_amount' => 110,
1139 'tax_amount' => 10,
1140 ],
1141 'amountParams' => [
1142 'item_amount' => NULL,
1143 ],
1144 'context' => 'changedAmount',
1145 'expectedItemAmount' => 110,
1146 ],
1147 [
1148 'params' => [
1149 'is_quick_config' => TRUE,
1150 'total_amount' => 110,
1151 'tax_amount' => 10,
1152 ],
1153 'amountParams' => [
1154 'item_amount' => NULL,
1155 ],
1156 'context' => NULL,
1157 'expectedItemAmount' => 100,
1158 ],
1159 ];
1160 foreach ($testParams as $params) {
1161 $itemAmount = CRM_Contribute_BAO_Contribution::calculateFinancialItemAmount($params['params'], $params['amountParams'], $params['context']);
1162 $this->assertEquals($itemAmount, $params['expectedItemAmount'], 'Invalid Financial Item amount.');
1163 }
1164 }
1165
1166 /**
1167 * Test recording of amount with comma separator.
1168 */
1169 public function testCommaSeparatorAmount() {
1170 $contactId = $this->individualCreate();
1171
1172 $params = [
1173 'contact_id' => $contactId,
1174 'currency' => 'USD',
1175 'financial_type_id' => 1,
1176 'contribution_status_id' => 8,
1177 'payment_instrument_id' => 1,
1178 'receive_date' => '20080522000000',
1179 'receipt_date' => '20080522000000',
1180 'total_amount' => '20000.00',
1181 'partial_payment_total' => '20,000.00',
1182 'partial_amount_to_pay' => '8,000.00',
1183 ];
1184
1185 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
1186 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
1187 $financialTrxn = $this->callAPISuccessGetSingle(
1188 'FinancialTrxn',
1189 [
1190 'id' => $lastFinancialTrxnId['financialTrxnId'],
1191 'return' => ['total_amount'],
1192 ]
1193 );
1194 $this->assertEquals($financialTrxn['total_amount'], 8000, 'Invalid Tax amount.');
1195 }
1196
1197 /**
1198 * Test for function getSalesTaxFinancialAccounts().
1199 */
1200 public function testgetSalesTaxFinancialAccounts() {
1201 $this->enableTaxAndInvoicing();
1202 $financialType = $this->createFinancialType();
1203 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1204 $expectedResult = [$financialAccount->financial_account_id => $financialAccount->financial_account_id];
1205 $financialType = $this->createFinancialType();
1206 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1207 $expectedResult[$financialAccount->financial_account_id] = $financialAccount->financial_account_id;
1208 $salesTaxFinancialAccount = CRM_Contribute_BAO_Contribution::getSalesTaxFinancialAccounts();
1209 $this->assertTrue(($salesTaxFinancialAccount == $expectedResult), 'Function returned wrong values.');
1210 }
1211
1212 /**
1213 * Test for function createProportionalEntry().
1214 *
1215 * @param string $thousandSeparator
1216 * punctuation used to refer to thousands.
1217 *
1218 * @dataProvider getThousandSeparators
1219 */
1220 public function testCreateProportionalEntry($thousandSeparator) {
1221 $this->setCurrencySeparators($thousandSeparator);
1222 list($contribution, $financialAccount) = $this->createContributionWithTax();
1223 $params = [
1224 'total_amount' => 55,
1225 'to_financial_account_id' => $financialAccount->financial_account_id,
1226 'payment_instrument_id' => 1,
1227 'trxn_date' => date('Ymd'),
1228 'status_id' => 1,
1229 'entity_id' => $contribution['id'],
1230 ];
1231 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'create', $params);
1232 $entityParams = [
1233 'contribution_total_amount' => $contribution['total_amount'],
1234 'trxn_total_amount' => 55,
1235 'line_item_amount' => 100,
1236 ];
1237 $previousLineItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($contribution['id']);
1238 $eftParams = [
1239 'entity_table' => 'civicrm_financial_item',
1240 'entity_id' => $previousLineItem['id'],
1241 'financial_trxn_id' => (string) $financialTrxn['id'],
1242 ];
1243 CRM_Contribute_BAO_Contribution::createProportionalEntry($entityParams, $eftParams);
1244 $trxnTestArray = array_merge($eftParams, [
1245 'amount' => '50.00',
1246 ]);
1247 $this->callAPISuccessGetSingle('EntityFinancialTrxn', $eftParams, $trxnTestArray);
1248 }
1249
1250 /**
1251 * Test for function createProportionalEntry with zero amount().
1252 *
1253 * @param string $thousandSeparator
1254 * punctuation used to refer to thousands.
1255 *
1256 * @dataProvider getThousandSeparators
1257 */
1258 public function testCreateProportionalEntryZeroAmount($thousandSeparator) {
1259 $this->setCurrencySeparators($thousandSeparator);
1260 list($contribution, $financialAccount) = $this->createContributionWithTax(['total_amount' => 0]);
1261 $params = [
1262 'total_amount' => 0,
1263 'to_financial_account_id' => $financialAccount->financial_account_id,
1264 'payment_instrument_id' => 1,
1265 'trxn_date' => date('Ymd'),
1266 'status_id' => 1,
1267 'entity_id' => $contribution['id'],
1268 ];
1269 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'create', $params);
1270 $entityParams = [
1271 'contribution_total_amount' => $contribution['total_amount'],
1272 'trxn_total_amount' => 0,
1273 'line_item_amount' => 0,
1274 ];
1275 $previousLineItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($contribution['id']);
1276 $eftParams = [
1277 'entity_table' => 'civicrm_financial_item',
1278 'entity_id' => $previousLineItem['id'],
1279 'financial_trxn_id' => (string) $financialTrxn['id'],
1280 ];
1281 CRM_Contribute_BAO_Contribution::createProportionalEntry($entityParams, $eftParams);
1282 $trxnTestArray = array_merge($eftParams, [
1283 'amount' => '0.00',
1284 ]);
1285 $this->callAPISuccessGetSingle('EntityFinancialTrxn', $eftParams, $trxnTestArray);
1286 }
1287
1288 /**
1289 * Test for function getLastFinancialItemIds().
1290 */
1291 public function testgetLastFinancialItemIds() {
1292 list($contribution, $financialAccount) = $this->createContributionWithTax();
1293 list($ftIds, $taxItems) = CRM_Contribute_BAO_Contribution::getLastFinancialItemIds($contribution['id']);
1294 $this->assertEquals(count($ftIds), 1, 'Invalid count.');
1295 $this->assertEquals(count($taxItems), 1, 'Invalid count.');
1296 foreach ($taxItems as $value) {
1297 $this->assertEquals($value['amount'], 10, 'Invalid tax amount.');
1298 }
1299 }
1300
1301 /**
1302 * Test to ensure proportional entries are creating when adding a payment..
1303 *
1304 * In this test we create a pending contribution for $110 consisting of $100 contribution and $10 tax.
1305 *
1306 * We pay $50, resulting in it being allocated as $45.45 paymnt & $4.55 tax. This is in equivalent proportions
1307 * 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
1308 * saved un-rounded).
1309 */
1310 public function testCreateProportionalFinancialEntriesViaPaymentCreate() {
1311 list($contribution, $financialAccount) = $this->createContributionWithTax([], FALSE);
1312 $params = [
1313 'total_amount' => 50,
1314 'to_financial_account_id' => $financialAccount->financial_account_id,
1315 'payment_instrument_id' => 1,
1316 'trxn_date' => date('Ymd'),
1317 'status_id' => 1,
1318 'entity_id' => $contribution['id'],
1319 'contribution_id' => $contribution['id'],
1320 ];
1321 $financialTrxn = $this->callAPISuccess('Payment', 'create', $params);
1322 $eftParams = [
1323 'entity_table' => 'civicrm_financial_item',
1324 'financial_trxn_id' => $financialTrxn['id'],
1325 ];
1326 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'Get', $eftParams);
1327 $this->assertEquals($entityFinancialTrxn['count'], 2, 'Invalid count.');
1328 $testAmount = [4.55, 45.45];
1329 foreach ($entityFinancialTrxn['values'] as $value) {
1330 $this->assertEquals(array_pop($testAmount), $value['amount'], 'Invalid amount stored in civicrm_entity_financial_trxn.');
1331 }
1332 }
1333
1334 /**
1335 * Test to check if amount is proportionally asigned for PI change.
1336 */
1337 public function testProportionallyAssignedForPIChange() {
1338 list($contribution, $financialAccount) = $this->createContributionWithTax();
1339 $params = [
1340 'id' => $contribution['id'],
1341 'payment_instrument_id' => 3,
1342 ];
1343 $this->callAPISuccess('Contribution', 'create', $params);
1344 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
1345 $eftParams = [
1346 'entity_table' => 'civicrm_financial_item',
1347 'financial_trxn_id' => $lastFinancialTrxnId['financialTrxnId'],
1348 ];
1349 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'Get', $eftParams);
1350 $this->assertEquals($entityFinancialTrxn['count'], 2, 'Invalid count.');
1351 $testAmount = [10, 100];
1352 foreach ($entityFinancialTrxn['values'] as $value) {
1353 $this->assertEquals($value['amount'], array_pop($testAmount), 'Invalid amount stored in civicrm_entity_financial_trxn.');
1354 }
1355 }
1356
1357 /**
1358 * Function to create contribution with tax.
1359 */
1360 public function createContributionWithTax($params = [], $isCompleted = TRUE) {
1361 if (!isset($params['total_amount'])) {
1362 $params['total_amount'] = 100;
1363 }
1364 $contactId = $this->individualCreate();
1365 $this->enableTaxAndInvoicing();
1366 $financialType = $this->createFinancialType();
1367 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1368 $form = new CRM_Contribute_Form_Contribution();
1369
1370 $form->testSubmit([
1371 'total_amount' => $params['total_amount'],
1372 'financial_type_id' => $financialType['id'],
1373 'contact_id' => $contactId,
1374 'contribution_status_id' => $isCompleted ? 1 : 2,
1375 'price_set_id' => 0,
1376 ], CRM_Core_Action::ADD);
1377 $contribution = $this->callAPISuccessGetSingle('Contribution',
1378 [
1379 'contact_id' => $contactId,
1380 'return' => ['tax_amount', 'total_amount'],
1381 ]
1382 );
1383 return [$contribution, $financialAccount];
1384 }
1385
1386 /**
1387 * Test processOnBehalfOrganization() function.
1388 */
1389 public function testProcessOnBehalfOrganization() {
1390 $orgInfo = [
1391 'phone' => '11111111',
1392 'email' => 'testorg@gmail.com',
1393 'street_address' => 'test Street',
1394 'city' => 'test City',
1395 'state_province' => 'AA',
1396 'postal_code' => '222222',
1397 'country' => 'United States',
1398 ];
1399 $contactID = $this->individualCreate();
1400 $orgId = $this->organizationCreate(['organization_name' => 'testorg1']);
1401 $orgCount = $this->callAPISuccessGetCount('Contact', [
1402 'contact_type' => "Organization",
1403 'organization_name' => "testorg1",
1404 ]);
1405 $this->assertEquals($orgCount, 1);
1406
1407 $values = $params = [];
1408 $behalfOrganization = [
1409 'organization_name' => 'testorg1',
1410 'phone' => [
1411 1 => [
1412 'phone' => $orgInfo['phone'],
1413 'is_primary' => 1,
1414 ],
1415 ],
1416 'email' => [
1417 1 => [
1418 'email' => $orgInfo['email'],
1419 'is_primary' => 1,
1420 ],
1421 ],
1422 'address' => [
1423 3 => [
1424 'street_address' => $orgInfo['street_address'],
1425 'city' => $orgInfo['city'],
1426 'location_type_id' => 3,
1427 'postal_code' => $orgInfo['postal_code'],
1428 'country' => 'US',
1429 'state_province' => 'AA',
1430 'is_primary' => 1,
1431 ],
1432 ],
1433 ];
1434 $fields = [
1435 'organization_name' => 1,
1436 'phone-3-1' => 1,
1437 'email-3' => 1,
1438 'street_address-3' => 1,
1439 'city-3' => 1,
1440 'postal_code-3' => 1,
1441 'country-3' => 1,
1442 'state_province-3' => 1,
1443 ];
1444 CRM_Contribute_Form_Contribution_Confirm::processOnBehalfOrganization($behalfOrganization, $contactID, $values, $params, $fields);
1445
1446 //Check whether new organisation is not created.
1447 $result = $this->callAPISuccess('Contact', 'get', [
1448 'contact_type' => "Organization",
1449 'organization_name' => "testorg1",
1450 ]);
1451 $this->assertEquals($result['count'], 1);
1452
1453 //Assert all org values are updated.
1454 foreach ($orgInfo as $key => $val) {
1455 $this->assertEquals($result['values'][$orgId][$key], $val);
1456 }
1457
1458 //Check if alert is assigned to params if more than 1 dupe exists.
1459 $orgId = $this->organizationCreate(['organization_name' => 'testorg1', 'email' => 'testorg@gmail.com']);
1460 CRM_Contribute_Form_Contribution_Confirm::processOnBehalfOrganization($behalfOrganization, $contactID, $values, $params, $fields);
1461 $this->assertEquals($params['onbehalf_dupe_alert'], 1);
1462 }
1463
1464 /**
1465 * Test for replaceContributionTokens.
1466 * This function tests whether the contribution tokens are replaced with values from contribution.
1467 */
1468 public function testReplaceContributionTokens() {
1469 $customGroup = $this->customGroupCreate(['extends' => 'Contribution', 'title' => 'contribution stuff']);
1470 $customField = $this->customFieldOptionValueCreate($customGroup, 'myCustomField');
1471 $contactId1 = $this->individualCreate();
1472 $params = [
1473 'contact_id' => $contactId1,
1474 'receive_date' => '20120511',
1475 'total_amount' => 100.00,
1476 'financial_type_id' => 1,
1477 'trxn_id' => 12345,
1478 'invoice_id' => 67890,
1479 'source' => 'SSF',
1480 'contribution_status_id' => 2,
1481 "custom_{$customField['id']}" => 'value1',
1482 ];
1483 $contribution1 = $this->contributionCreate($params);
1484 $contactId2 = $this->individualCreate();
1485 $params = [
1486 'contact_id' => $contactId2,
1487 'receive_date' => '20150511',
1488 'total_amount' => 200.00,
1489 'financial_type_id' => 1,
1490 'trxn_id' => 6789,
1491 'invoice_id' => 12345,
1492 'source' => 'ABC',
1493 'contribution_status_id' => 1,
1494 "custom_{$customField['id']}" => 'value2',
1495 ];
1496 $contribution2 = $this->contributionCreate($params);
1497 $ids = [$contribution1, $contribution2];
1498
1499 $subject = "This is a test for contribution ID: {contribution.contribution_id}";
1500 $text = "Contribution Amount: {contribution.total_amount}";
1501 $html = "<p>Contribution Source: {contribution.contribution_source}</p></br>
1502 <p>Contribution Invoice ID: {contribution.invoice_id}</p></br>
1503 <p>Contribution Receive Date: {contribution.receive_date}</p></br>
1504 <p>Contribution Custom Field: {contribution.custom_{$customField['id']}}</p></br>";
1505
1506 $subjectToken = CRM_Utils_Token::getTokens($subject);
1507 $messageToken = CRM_Utils_Token::getTokens($text);
1508 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
1509
1510 $contributionDetails = CRM_Contribute_BAO_Contribution::replaceContributionTokens(
1511 $ids,
1512 $subject,
1513 $subjectToken,
1514 $text,
1515 $html,
1516 $messageToken,
1517 TRUE
1518 );
1519
1520 $this->assertEquals("Contribution Amount: $ 100.00", $contributionDetails[$contactId1]['text'], "The text does not match");
1521 $this->assertEquals("<p>Contribution Source: ABC</p></br>
1522 <p>Contribution Invoice ID: 12345</p></br>
1523 <p>Contribution Receive Date: May 11th, 2015</p></br>
1524 <p>Contribution Custom Field: Label2</p></br>", $contributionDetails[$contactId2]['html'], "The html does not match");
1525 }
1526
1527 /**
1528 * Test for contribution with deferred revenue.
1529 */
1530 public function testContributionWithDeferredRevenue() {
1531 $contactId = $this->individualCreate();
1532 Civi::settings()->set('deferred_revenue_enabled', TRUE);
1533 $params = [
1534 'contact_id' => $contactId,
1535 'receive_date' => '20120511',
1536 'total_amount' => 100.00,
1537 'financial_type_id' => 'Event Fee',
1538 'trxn_id' => 12345,
1539 'invoice_id' => 67890,
1540 'source' => 'SSF',
1541 'contribution_status_id' => 'Completed',
1542 'revenue_recognition_date' => date('Ymd', strtotime("+3 month")),
1543 ];
1544 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1545
1546 $this->callAPISuccessGetCount('EntityFinancialTrxn', [
1547 'entity_table' => "civicrm_contribution",
1548 'entity_id' => $contribution['id'],
1549 ], 2);
1550
1551 $checkAgainst = [
1552 'financial_trxn_id.to_financial_account_id.name' => 'Deferred Revenue - Event Fee',
1553 'financial_trxn_id.from_financial_account_id.name' => 'Event Fee',
1554 'financial_trxn_id' => '2',
1555 ];
1556 $result = $this->callAPISuccessGetSingle('EntityFinancialTrxn', [
1557 'return' => [
1558 "financial_trxn_id.from_financial_account_id.name",
1559 "financial_trxn_id.to_financial_account_id.name",
1560 "financial_trxn_id",
1561 ],
1562 'entity_table' => "civicrm_contribution",
1563 'entity_id' => $contribution['id'],
1564 'financial_trxn_id.is_payment' => 0,
1565 ], $checkAgainst);
1566
1567 $result = $this->callAPISuccessGetSingle('EntityFinancialTrxn', [
1568 'entity_table' => "civicrm_financial_item",
1569 'financial_trxn_id' => $result['financial_trxn_id'],
1570 'return' => ['entity_id'],
1571 ]);
1572
1573 $checkAgainst = [
1574 'financial_account_id.name' => 'Deferred Revenue - Event Fee',
1575 'id' => $result['entity_id'],
1576 ];
1577 $result = $this->callAPISuccessGetSingle('FinancialItem', [
1578 'id' => $result['entity_id'],
1579 'return' => ["financial_account_id.name"],
1580 ], $checkAgainst);
1581 }
1582
1583 /**
1584 * https://lab.civicrm.org/dev/financial/issues/56
1585 * Changing financial type on a contribution records correct financial items
1586 */
1587 public function testChangingFinancialTypeWithoutTax() {
1588 $ids = $values = [];
1589 $contactId = $this->individualCreate();
1590 $params = [
1591 'contact_id' => $contactId,
1592 'receive_date' => date('YmdHis'),
1593 'total_amount' => 100.00,
1594 'financial_type_id' => 'Donation',
1595 'contribution_status_id' => 'Completed',
1596 ];
1597 /* first test the scenario when sending an email */
1598 $contributionId = $this->callAPISuccess(
1599 'contribution',
1600 'create',
1601 $params
1602 )['id'];
1603
1604 // Update Financial Type.
1605 $this->callAPISuccess('contribution', 'create', [
1606 'id' => $contributionId,
1607 'financial_type_id' => 'Event Fee',
1608 ]);
1609
1610 // Get line item
1611 $lineItem = $this->callAPISuccessGetSingle('LineItem', [
1612 'contribution_id' => $contributionId,
1613 'return' => ["financial_type_id.name", "line_total"],
1614 ]);
1615
1616 $this->assertEquals(
1617 $lineItem['line_total'],
1618 100.00,
1619 'Invalid line amount.'
1620 );
1621
1622 $this->assertEquals(
1623 $lineItem['financial_type_id.name'],
1624 'Event Fee',
1625 'Invalid Financial Type stored.'
1626 );
1627
1628 // Get Financial Items.
1629 $financialItems = $this->callAPISuccess('FinancialItem', 'get', [
1630 'entity_id' => $lineItem['id'],
1631 'sequential' => 1,
1632 'entity_table' => 'civicrm_line_item',
1633 'options' => ['sort' => "id"],
1634 'return' => ["financial_account_id.name", "amount", "description"],
1635 ]);
1636
1637 $this->assertEquals($financialItems['count'], 3, 'Count mismatch.');
1638
1639 $toCheck = [
1640 ['Donation', 100.00],
1641 ['Donation', -100.00],
1642 ['Event Fee', 100.00],
1643 ];
1644
1645 foreach ($financialItems['values'] as $key => $values) {
1646 $this->assertEquals(
1647 $values['financial_account_id.name'],
1648 $toCheck[$key][0],
1649 'Invalid Financial Account stored.'
1650 );
1651 $this->assertEquals(
1652 $values['amount'],
1653 $toCheck[$key][1],
1654 'Amount mismatch.'
1655 );
1656 $this->assertEquals(
1657 $values['description'],
1658 'Contribution Amount',
1659 'Description mismatch.'
1660 );
1661 }
1662
1663 // Check transactions.
1664 $financialTransactions = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
1665 'return' => ["financial_trxn_id"],
1666 'entity_table' => "civicrm_contribution",
1667 'entity_id' => $contributionId,
1668 'sequential' => 1,
1669 ]);
1670 $this->assertEquals($financialTransactions['count'], 3, 'Count mismatch.');
1671
1672 foreach ($financialTransactions['values'] as $key => $values) {
1673 $this->callAPISuccessGetCount('EntityFinancialTrxn', [
1674 'financial_trxn_id' => $values['financial_trxn_id'],
1675 'amount' => $toCheck[$key][1],
1676 'financial_trxn_id.total_amount' => $toCheck[$key][1],
1677 ], 2);
1678 }
1679 }
1680
1681 /**
1682 * CRM-21424 Check if the receipt update is set after composing the receipt message
1683 */
1684 public function testSendMailUpdateReceiptDate() {
1685 $ids = $values = [];
1686 $contactId = $this->individualCreate();
1687 $params = [
1688 'contact_id' => $contactId,
1689 'receive_date' => '20120511',
1690 'total_amount' => 100.00,
1691 'financial_type_id' => 'Donation',
1692 'source' => 'SSF',
1693 'contribution_status_id' => 'Completed',
1694 ];
1695 /* first test the scenario when sending an email */
1696 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1697 $contributionId = $contribution['id'];
1698 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After creating receipt date must be null');
1699 $input = ['receipt_update' => 0];
1700 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $contributionId, $values);
1701 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail, with the explicit instruction not to update receipt date stays null');
1702 $input = ['receipt_update' => 1];
1703 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $contributionId, $values);
1704 $this->assertDBNotNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail with the permission to allow update receipt date must be set');
1705
1706 /* repeat the same scenario for downloading a pdf */
1707 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1708 $contributionId = $contribution['id'];
1709 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After creating receipt date must be null');
1710 $input = ['receipt_update' => 0];
1711 /* setting the lasast parameter (returnmessagetext) to TRUE is done by the download of the pdf */
1712 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $contributionId, $values, TRUE);
1713 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail, with the explicit instruction not to update receipt date stays null');
1714 $input = ['receipt_update' => 1];
1715 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $contributionId, $values, TRUE);
1716 $this->assertDBNotNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail with the permission to allow update receipt date must be set');
1717 }
1718
1719 }