Merge pull request #15909 from eileenmcnaughton/payment
[civicrm-core.git] / tests / phpunit / CRM / Contribute / BAO / ContributionTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Class CRM_Contribute_BAO_ContributionTest
14 * @group headless
15 */
16 class CRM_Contribute_BAO_ContributionTest extends CiviUnitTestCase {
17
18 use CRMTraits_Financial_FinancialACLTrait;
19 use CRMTraits_Financial_PriceSetTrait;
20
21 /**
22 * Clean up after tests.
23 */
24 public function tearDown() {
25 $this->quickCleanUpFinancialEntities();
26 parent::tearDown();
27 }
28
29 /**
30 * Test create method (create and update modes).
31 *
32 * @throws \CRM_Core_Exception
33 */
34 public function testCreate() {
35 $contactId = $this->individualCreate();
36
37 $params = [
38 'contact_id' => $contactId,
39 'currency' => 'USD',
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,
48 'fee_amount' => 5,
49 'net_amount' => 195,
50 'trxn_id' => '22ereerwww444444',
51 'invoice_id' => '86ed39c9e9ee6ef6031621ce0eafe7eb81',
52 'thankyou_date' => '20080522',
53 'sequential' => TRUE,
54 ];
55
56 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
57
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.');
60
61 //update contribution amount
62 $params['id'] = $contribution['id'];
63 $params['fee_amount'] = 10;
64 $params['net_amount'] = 190;
65
66 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
67
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.');
70 }
71
72 /**
73 * Create() method with custom data.
74 */
75 public function testCreateWithCustomData() {
76 $contactId = $this->individualCreate();
77
78 //create custom data
79 $customGroup = $this->customGroupCreate(['extends' => 'Contribution']);
80 $customGroupID = $customGroup['id'];
81 $customGroup = $customGroup['values'][$customGroupID];
82
83 $fields = [
84 'label' => 'testFld',
85 'data_type' => 'String',
86 'html_type' => 'Text',
87 'is_active' => 1,
88 'custom_group_id' => $customGroupID,
89 ];
90 $customField = CRM_Core_BAO_CustomField::create($fields);
91
92 $params = [
93 'contact_id' => $contactId,
94 'currency' => 'USD',
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',
101 'id' => NULL,
102 'non_deductible_amount' => 0.00,
103 'total_amount' => 200.00,
104 'fee_amount' => 5,
105 'net_amount' => 195,
106 'trxn_id' => '22ereerwww322323',
107 'invoice_id' => '22ed39c9e9ee6ef6031621ce0eafe6da70',
108 'thankyou_date' => '20080522',
109 'skipCleanMoney' => TRUE,
110 ];
111
112 $params['custom'] = [
113 $customField->id => [
114 -1 => [
115 'value' => 'Test custom value',
116 'type' => 'String',
117 'custom_field_id' => $customField->id,
118 'custom_group_id' => $customGroupID,
119 'table_name' => $customGroup['table_name'],
120 'column_name' => $customField->column_name,
121 'file_id' => NULL,
122 ],
123 ],
124 ];
125
126 $contribution = CRM_Contribute_BAO_Contribution::create($params);
127
128 // Check that the custom field value is saved
129 $customValueParams = [
130 'entityID' => $contribution->id,
131 'custom_' . $customField->id => 1,
132 ];
133 $values = CRM_Core_BAO_CustomValueTable::getValues($customValueParams);
134 $this->assertEquals('Test custom value', $values['custom_' . $customField->id], 'Check the custom field value');
135
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.');
138 }
139
140 /**
141 * CRM-21026 Test ContributionCount after contribution created with disabled FT
142 */
143 public function testContributionCountDisabledFinancialType() {
144 $contactId = $this->individualCreate();
145 $financialType = [
146 'name' => 'grassvariety1' . substr(sha1(rand()), 0, 7),
147 'is_reserved' => 0,
148 'is_active' => 0,
149 ];
150 $finType = $this->callAPISuccess('financial_type', 'create', $financialType);
151 $params = [
152 'contact_id' => $contactId,
153 'currency' => 'USD',
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',
160 'id' => NULL,
161 'non_deductible_amount' => 0.00,
162 'total_amount' => 200.00,
163 'fee_amount' => 5,
164 'net_amount' => 195,
165 'trxn_id' => '22ereerwww322323',
166 'invoice_id' => '22ed39c9e9ee6ef6031621ce0eafe6da70',
167 'thankyou_date' => '20080522',
168 ];
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);
173 }
174
175 /**
176 * DeleteContribution() method
177 */
178 public function testDeleteContribution() {
179 $contactId = $this->individualCreate();
180
181 $params = [
182 'contact_id' => $contactId,
183 'currency' => 'USD',
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',
190 'id' => NULL,
191 'non_deductible_amount' => 0.00,
192 'total_amount' => 200.00,
193 'fee_amount' => 5,
194 'net_amount' => 195,
195 'trxn_id' => '33ereerwww322323',
196 'invoice_id' => '33ed39c9e9ee6ef6031621ce0eafe6da70',
197 'thankyou_date' => '20080522',
198 'sequential' => TRUE,
199 ];
200
201 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
202
203 CRM_Contribute_BAO_Contribution::deleteContribution($contribution['id']);
204
205 $this->assertDBNull('CRM_Contribute_DAO_Contribution', $contribution['trxn_id'],
206 'id', 'trxn_id', 'Database check for deleted Contribution.'
207 );
208 }
209
210 /**
211 * Create honor-contact method.
212 */
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";
217
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;
224 }
225
226 $params = [
227 'prefix_id' => 3,
228 'first_name' => $firstName,
229 'last_name' => $lastName,
230 'email-1' => $email,
231 ];
232 $softParam = ['soft_credit_type_id' => 1];
233
234 $null = [];
235 $honoreeContactId = CRM_Contact_BAO_Contact::createProfileContact($params, $null,
236 NULL, NULL, $honoreeProfileId
237 );
238
239 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName,
240 'Database check for created honor contact record.'
241 );
242 //create contribution on behalf of honary.
243
244 $contactId = $this->individualCreate(['first_name' => 'John', 'last_name' => 'Doe']);
245
246 $param = [
247 'contact_id' => $contactId,
248 'currency' => 'USD',
249 'financial_type_id' => 4,
250 'contribution_status_id' => 1,
251 'receive_date' => date('Ymd'),
252 'total_amount' => 66,
253 'sequential' => 1,
254 ];
255
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'];
262
263 //Create Soft Contribution for honoree contact
264 CRM_Contribute_BAO_ContributionSoft::add($softParam);
265
266 $this->assertDBCompareValue('CRM_Contribute_DAO_ContributionSoft', $id, 'contact_id',
267 'contribution_id', $honoreeContactId, 'Check DB for honor contact of the contribution'
268 );
269 //get honorary information
270 $getHonorContact = CRM_Contribute_BAO_Contribution::getHonorContacts($honoreeContactId);
271 $this->assertEquals([
272 $id => [
273 'honor_type' => 'In Honor of',
274 'honorId' => $contactId,
275 'display_name' => 'Mr. John Doe II',
276 'type' => 'Event Fee',
277 'type_id' => '4',
278 'amount' => '$ 66.00',
279 'source' => NULL,
280 'receive_date' => date('Y-m-d 00:00:00'),
281 'contribution_status' => 'Completed',
282 ],
283 ], $getHonorContact);
284
285 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $honoreeContactId, 'first_name', 'id', $firstName,
286 'Database check for created honor contact record.'
287 );
288
289 //get annual contribution information
290 $annual = CRM_Contribute_BAO_Contribution::annual($contactId);
291
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'
295 );
296 }
297
298 /**
299 * Test that financial type data is not added to the annual query if acls not enabled.
300 */
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);
309
310 // Run it to make sure it's not bad sql.
311 CRM_Core_DAO::executeQuery($sql);
312 $this->disableFinancialACLs();
313 }
314
315 /**
316 * Test the annual query returns a correct result when multiple line items are present.
317 */
318 public function testAnnualWithMultipleLineItems() {
319 $contactID = $this->createLoggedInUserWithFinancialACL();
320 $this->createContributionWithTwoLineItemsAgainstPriceSet([
321 'contact_id' => $contactID,
322 ]
323 );
324 $this->enableFinancialACLs();
325 $sql = CRM_Contribute_BAO_Contribution::getAnnualQuery([$contactID]);
326 $result = CRM_Core_DAO::executeQuery($sql);
327 $result->fetch();
328 $this->assertEquals(300, $result->amount);
329 $this->assertEquals(1, $result->count);
330 $this->disableFinancialACLs();
331 }
332
333 /**
334 * Test that financial type data is not added to the annual query if acls not enabled.
335 */
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);
344 }
345
346 /**
347 * Test that financial type data is not added to the annual query if acls not enabled.
348 */
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);
357 }
358
359 /**
360 * Add ACL denying values LIKE '0'.
361 *
362 * @param string $entity
363 * @param string $clauses
364 */
365 public function aclIdNoZero($entity, &$clauses) {
366 if ($entity != 'Contribution') {
367 return;
368 }
369 $clauses['id'] = "NOT IN (0)";
370 }
371
372 /**
373 * Display sort name during.
374 * Update multiple contributions
375 * sortName();
376 */
377 public function testsortName() {
378 $params = [
379 'first_name' => 'Shane',
380 'last_name' => 'Whatson',
381 'contact_type' => 'Individual',
382 ];
383
384 $contact = CRM_Contact_BAO_Contact::add($params);
385
386 //Now check $contact is object of contact DAO..
387 $this->assertInstanceOf('CRM_Contact_DAO_Contact', $contact, 'Check for created object');
388
389 $contactId = $contact->id;
390 $param = [
391 'contact_id' => $contactId,
392 'currency' => 'USD',
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',
399 'id' => NULL,
400 'non_deductible_amount' => 0.00,
401 'total_amount' => 300.00,
402 'fee_amount' => 5,
403 'net_amount' => 295,
404 'trxn_id' => '22ereerwww323',
405 'invoice_id' => '22ed39c9e9ee621ce0eafe6da70',
406 'thankyou_date' => '20080522',
407 'sequential' => TRUE,
408 ];
409
410 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
411
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.');
414
415 //display sort name during Update multiple contributions
416 $sortName = CRM_Contribute_BAO_Contribution::sortName($contribution['id']);
417
418 $this->assertEquals('Whatson, Shane', $sortName, 'Check for sort name.');
419 }
420
421 /**
422 * Add premium during online Contribution.
423 *
424 * AddPremium();
425 */
426 public function testAddPremium() {
427 $contactId = $this->individualCreate();
428
429 $params = [
430 'name' => 'TEST Premium',
431 'sku' => 111,
432 'imageOption' => 'noImage',
433 'MAX_FILE_SIZE' => 2097152,
434 'price' => 100.00,
435 'cost' => 90.00,
436 'min_contribution' => 100,
437 'is_active' => 1,
438 ];
439 $premium = CRM_Contribute_BAO_Product::create($params);
440
441 $this->assertEquals('TEST Premium', $premium->name, 'Check for premium name.');
442
443 $contributionParams = [
444 'contact_id' => $contactId,
445 'currency' => 'USD',
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',
452 'id' => NULL,
453 'non_deductible_amount' => 0.00,
454 'total_amount' => 300.00,
455 'fee_amount' => 5,
456 'net_amount' => 295,
457 'trxn_id' => '33erdfrwvw434',
458 'invoice_id' => '98ed34f7u9hh672ce0eafe8fb92',
459 'thankyou_date' => '20080522',
460 'sequential' => TRUE,
461 ];
462 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams)['values'][0];
463
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.');
466
467 //parameter for adding premium to contribution
468 $data = [
469 'product_id' => $premium->id,
470 'contribution_id' => $contribution['id'],
471 'product_option' => NULL,
472 'quantity' => 1,
473 ];
474 $contributionProduct = CRM_Contribute_BAO_Contribution::addPremium($data);
475 $this->assertEquals($contributionProduct->product_id, $premium->id, 'Check for Product id .');
476
477 //Delete Product
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.'
481 );
482 }
483
484 /**
485 * Check duplicate contribution id.
486 * during the contribution import
487 * checkDuplicateIds();
488 */
489 public function testcheckDuplicateIds() {
490 $contactId = $this->individualCreate();
491
492 $param = [
493 'contact_id' => $contactId,
494 'currency' => 'USD',
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',
501 'id' => NULL,
502 'non_deductible_amount' => 0.00,
503 'total_amount' => 300.00,
504 'fee_amount' => 5,
505 'net_amount' => 295,
506 'trxn_id' => '76ereeswww835',
507 'invoice_id' => '93ed39a9e9hd621bs0eafe3da82',
508 'thankyou_date' => '20080522',
509 'sequential' => TRUE,
510 ];
511
512 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
513
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.');
516 $data = [
517 'id' => $contribution['id'],
518 'trxn_id' => $contribution['trxn_id'],
519 'invoice_id' => $contribution['invoice_id'],
520 ];
521 $contributionID = CRM_Contribute_BAO_Contribution::checkDuplicateIds($data);
522 $this->assertEquals($contributionID, $contribution['id'], 'Check for duplicate transcation id .');
523 }
524
525 /**
526 * Check credit note id creation
527 * when a contribution is cancelled or refunded
528 * createCreditNoteId();
529 */
530 public function testCreateCreditNoteId() {
531 $contactId = $this->individualCreate();
532
533 $param = [
534 'contact_id' => $contactId,
535 'currency' => 'USD',
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',
542 'id' => NULL,
543 'non_deductible_amount' => 0.00,
544 'total_amount' => 300.00,
545 'fee_amount' => 5,
546 'net_amount' => 295,
547 'trxn_id' => '76ereeswww835',
548 'invoice_id' => '93ed39a9e9hd621bs0eafe3da82',
549 'thankyou_date' => '20080522',
550 'sequential' => TRUE,
551 ];
552
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.');
557 }
558
559 /**
560 * Create() method (create and update modes).
561 */
562 public function testIsPaymentFlag() {
563 $contactId = $this->individualCreate();
564
565 $params = [
566 'contact_id' => $contactId,
567 'currency' => 'USD',
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,
576 'fee_amount' => 5,
577 'net_amount' => 195,
578 'trxn_id' => '22ereerwww4444xx',
579 'invoice_id' => '86ed39c9e9ee6ef6541621ce0eafe7eb81',
580 'thankyou_date' => '20080522',
581 'sequential' => TRUE,
582 ];
583 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
584
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.');
587
588 $trxnArray = [
589 'trxn_id' => $params['trxn_id'],
590 'is_payment' => 1,
591 ];
592 $defaults = [];
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];
599
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.');
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(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.');
612 }
613
614 /**
615 * Create() method (create and update modes).
616 */
617 public function testIsPaymentFlagForPending() {
618 $contactId = $this->individualCreate();
619
620 $params = [
621 'contact_id' => $contactId,
622 'currency' => 'USD',
623 'financial_type_id' => 1,
624 'contribution_status_id' => 2,
625 'payment_instrument_id' => 1,
626 'source' => 'STUDENT',
627 'is_pay_later' => 1,
628 'receive_date' => '20080522000000',
629 'receipt_date' => '20080522000000',
630 'non_deductible_amount' => 0.00,
631 'total_amount' => 200.00,
632 'fee_amount' => 5,
633 'net_amount' => 195,
634 'trxn_id' => '22ereerwww4444yy',
635 'invoice_id' => '86ed39c9e9yy6ef6541621ce0eafe7eb81',
636 'thankyou_date' => '20080522',
637 'sequential' => TRUE,
638 ];
639
640 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
641
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.');
644
645 $trxnArray = [
646 'trxn_id' => $params['trxn_id'],
647 'is_payment' => 0,
648 ];
649 $defaults = [];
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;
658
659 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
660
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.');
663 $trxnArray = [
664 'trxn_id' => $params['trxn_id'],
665 'is_payment' => 1,
666 ];
667 $defaults = [];
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.');
673 }
674
675 /**
676 * addPayments() method (add and edit modes of participant).
677 *
678 * Add Payments is part of an old, flawed, code flow.
679 */
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);
688 }
689
690 /**
691 * checks db values for financial item
692 */
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";
698
699 $queryParams[1] = [$contribution->id, 'Integer'];
700 $queryParams[2] = [$toFinancialAccount, 'Integer'];
701
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');
707 }
708 }
709
710 /**
711 * assignProportionalLineItems() method (add and edit modes of participant)
712 *
713 * @throws \CRM_Core_Exception
714 * @throws \CiviCRM_API3_Exception
715 */
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"');
722 $params = [
723 'contribution_id' => $contribution->id,
724 'total_amount' => 150.00,
725 ];
726 $trxn = new CRM_Financial_DAO_FinancialTrxn();
727 $trxn->orderBy('id DESC');
728 $trxn->find(TRUE);
729 CRM_Contribute_BAO_Contribution::assignProportionalLineItems($params, $trxn->id, $contribution->total_amount);
730 $this->checkItemValues($contribution);
731 }
732
733 /**
734 * Add participant with contribution
735 *
736 * @return array
737 *
738 * @throws \CRM_Core_Exception
739 * @throws \CiviCRM_API3_Exception
740 */
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;
747 $paramsField = [
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,
757 'weight' => 1,
758 'options_per_line' => 1,
759 'is_active' => ['1' => 1, '2' => 1],
760 'price_set_id' => $this->priceSetID,
761 'is_enter_qty' => 1,
762 'financial_type_id' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
763 ];
764 $priceField = CRM_Price_BAO_PriceField::create($paramsField);
765 $eventParams = [
766 'id' => $this->_eventId,
767 'financial_type_id' => 4,
768 'is_monetary' => 1,
769 ];
770 CRM_Event_BAO_Event::create($eventParams);
771 CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_eventId, $priceSetId);
772
773 $priceFields = $this->callAPISuccess('PriceFieldValue', 'get', ['price_field_id' => $priceField->id]);
774 $participantParams = [
775 'financial_type_id' => 4,
776 'event_id' => $this->_eventId,
777 'role_id' => 1,
778 'status_id' => 14,
779 'fee_currency' => 'USD',
780 'contact_id' => $this->_contactId,
781 ];
782 $participant = CRM_Event_BAO_Participant::add($participantParams);
783 $contributionParams = [
784 'total_amount' => 300,
785 'currency' => 'USD',
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],
793 ];
794
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'],
801 'qty' => 1,
802 'unit_price' => $priceField['amount'],
803 'line_total' => $priceField['amount'],
804 'financial_type_id' => $priceField['financial_type_id'],
805 ];
806 }
807 $contributionParams['line_item'] = $lineItems;
808 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams)['values'][0];
809
810 $paymentParticipant = [
811 'participant_id' => $participant->id,
812 'contribution_id' => $contribution['id'],
813 ];
814 CRM_Event_BAO_ParticipantPayment::create($paymentParticipant);
815
816 $contributionObject = new CRM_Contribute_BAO_Contribution();
817 $contributionObject->id = $contribution['id'];
818 $contributionObject->find(TRUE);
819
820 return $contributionObject;
821 }
822
823 /**
824 * checkLineItems() check if total amount matches the sum of line total
825 */
826 public function testcheckLineItems() {
827 $params = [
828 'contact_id' => 202,
829 'receive_date' => '2010-01-20',
830 'total_amount' => 100,
831 'financial_type_id' => 3,
832 'line_items' => [
833 [
834 'line_item' => [
835 [
836 'entity_table' => 'civicrm_contribution',
837 'price_field_id' => 8,
838 'price_field_value_id' => 16,
839 'label' => 'test 1',
840 'qty' => 1,
841 'unit_price' => 100,
842 'line_total' => 100,
843 ],
844 [
845 'entity_table' => 'civicrm_contribution',
846 'price_field_id' => 8,
847 'price_field_value_id' => 17,
848 'label' => 'Test 2',
849 'qty' => 1,
850 'unit_price' => 200,
851 'line_total' => 200,
852 'financial_type_id' => 1,
853 ],
854 ],
855 'params' => [],
856 ],
857 ],
858 ];
859
860 try {
861 CRM_Contribute_BAO_Contribution::checkLineItems($params);
862 $this->fail("Missed expected exception");
863 }
864 catch (CRM_Contribute_Exception_CheckLineItemsException $e) {
865 $this->assertEquals(
866 CRM_Contribute_Exception_CheckLineItemsException::LINE_ITEM_DIFFERRING_TOTAL_EXCEPTON_MSG,
867 $e->getMessage()
868 );
869 }
870
871 $this->assertEquals(3, $params['line_items'][0]['line_item'][0]['financial_type_id']);
872 $params['total_amount'] = 300;
873
874 CRM_Contribute_BAO_Contribution::checkLineItems($params);
875 }
876
877 /**
878 * Tests CRM_Contribute_BAO_Contribution::checkLineItems() method works with
879 * floating point values.
880 */
881 public function testCheckLineItemsWithFloatingPointValues() {
882 $params = [
883 'contact_id' => 202,
884 'receive_date' => date('Y-m-d'),
885 'total_amount' => 16.67,
886 'financial_type_id' => 3,
887 'line_items' => [
888 [
889 'line_item' => [
890 [
891 'entity_table' => 'civicrm_contribution',
892 'price_field_id' => 8,
893 'price_field_value_id' => 16,
894 'label' => 'test 1',
895 'qty' => 1,
896 'unit_price' => 14.85,
897 'line_total' => 14.85,
898 ],
899 [
900 'entity_table' => 'civicrm_contribution',
901 'price_field_id' => 8,
902 'price_field_value_id' => 17,
903 'label' => 'Test 2',
904 'qty' => 1,
905 'unit_price' => 1.66,
906 'line_total' => 1.66,
907 'financial_type_id' => 1,
908 ],
909 [
910 'entity_table' => 'civicrm_contribution',
911 'price_field_id' => 8,
912 'price_field_value_id' => 17,
913 'label' => 'Test 2',
914 'qty' => 1,
915 'unit_price' => 0.16,
916 'line_total' => 0.16,
917 'financial_type_id' => 1,
918 ],
919 ],
920 'params' => [],
921 ],
922 ],
923 ];
924
925 $foundException = FALSE;
926
927 try {
928 CRM_Contribute_BAO_Contribution::checkLineItems($params);
929 }
930 catch (CRM_Contribute_Exception_CheckLineItemsException $e) {
931 $foundException = TRUE;
932 }
933
934 $this->assertFalse($foundException);
935 }
936
937 /**
938 * Test activity amount updation.
939 */
940 public function testActivityCreate() {
941 $contactId = $this->individualCreate();
942 $defaults = [];
943
944 $params = [
945 'contact_id' => $contactId,
946 'currency' => 'USD',
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',
958 'sequential' => 1,
959 ];
960
961 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
962
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.');
965
966 // Check amount in activity.
967 $activityParams = [
968 'source_record_id' => $contribution['id'],
969 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Contribution'),
970 ];
971 // @todo use api instead.
972 $activity = CRM_Activity_BAO_Activity::retrieve($activityParams, $defaults);
973
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.');
976
977 $params['id'] = $contribution['id'];
978 $params['total_amount'] = 200;
979
980 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
981
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.');
984
985 // Retrieve activity again.
986 $activity = CRM_Activity_BAO_Activity::retrieve($activityParams, $defaults);
987
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.');
990 }
991
992 /**
993 * Test allowUpdateRevenueRecognitionDate.
994 *
995 * @throws \CRM_Core_Exception
996 */
997 public function testAllowUpdateRevenueRecognitionDate() {
998 $contactId = $this->individualCreate();
999 $params = [
1000 'contact_id' => $contactId,
1001 'receive_date' => '2010-01-20',
1002 'total_amount' => 100,
1003 'financial_type_id' => 4,
1004 'contribution_status_id' => 'Pending',
1005 ];
1006 $order = $this->callAPISuccess('Order', 'create', $params);
1007 $allowUpdate = CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($order['id']);
1008 $this->assertTrue($allowUpdate);
1009
1010 $event = $this->eventCreate();
1011 $params = [
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',
1017 ];
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'],
1025 'qty' => 1,
1026 'unit_price' => $priceField['amount'],
1027 'line_total' => $priceField['amount'],
1028 'financial_type_id' => $priceField['financial_type_id'],
1029 'entity_table' => 'civicrm_participant',
1030 ];
1031 }
1032 $params['line_items'][] = [
1033 'line_item' => $lineItems,
1034 'params' => [
1035 'contact_id' => $contactId,
1036 'event_id' => $event['id'],
1037 'status_id' => 1,
1038 'role_id' => 1,
1039 'register_date' => '2007-07-21 00:00:00',
1040 'source' => 'Online Event Registration: API Testing',
1041 ],
1042 ];
1043 $order = $this->callAPISuccess('Order', 'create', $params);
1044 $allowUpdate = CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($order['id']);
1045 $this->assertFalse($allowUpdate);
1046
1047 $params = [
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',
1053 ];
1054 $membershipType = $this->membershipTypeCreate();
1055 $priceFields = $this->createPriceSet();
1056 $lineItems = [];
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'],
1063 'qty' => 1,
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,
1069 ];
1070 }
1071 $params['line_items'][] = [
1072 'line_item' => [array_pop($lineItems)],
1073 'params' => [
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',
1080 'is_override' => 1,
1081 'status_id' => 1,
1082 ],
1083 ];
1084 $order = $this->callAPISuccess('Order', 'create', $params);
1085 $allowUpdate = CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($order['id']);
1086 $this->assertFalse($allowUpdate);
1087 }
1088
1089 /**
1090 * Test calculateFinancialItemAmount().
1091 */
1092 public function testcalculateFinancialItemAmount() {
1093 $testParams = [
1094 [
1095 'params' => [],
1096 'amountParams' => [
1097 'line_total' => 100,
1098 'previous_line_total' => 300,
1099 'diff' => 1,
1100 ],
1101 'context' => 'changedAmount',
1102 'expectedItemAmount' => -200,
1103 ],
1104 [
1105 'params' => [],
1106 'amountParams' => [
1107 'line_total' => 100,
1108 'previous_line_total' => 100,
1109 'diff' => -1,
1110 ],
1111 // Most contexts are ignored. Removing refs to change payment instrument so placeholder.
1112 'context' => 'not null',
1113 'expectedItemAmount' => -100,
1114 ],
1115 [
1116 'params' => [
1117 'is_quick_config' => TRUE,
1118 'total_amount' => 110,
1119 'tax_amount' => 10,
1120 ],
1121 'amountParams' => [
1122 'item_amount' => 100,
1123 ],
1124 'context' => 'changedAmount',
1125 'expectedItemAmount' => 100,
1126 ],
1127 [
1128 'params' => [
1129 'is_quick_config' => TRUE,
1130 'total_amount' => 110,
1131 'tax_amount' => 10,
1132 ],
1133 'amountParams' => [
1134 'item_amount' => NULL,
1135 ],
1136 'context' => 'changedAmount',
1137 'expectedItemAmount' => 110,
1138 ],
1139 [
1140 'params' => [
1141 'is_quick_config' => TRUE,
1142 'total_amount' => 110,
1143 'tax_amount' => 10,
1144 ],
1145 'amountParams' => [
1146 'item_amount' => NULL,
1147 ],
1148 'context' => NULL,
1149 'expectedItemAmount' => 100,
1150 ],
1151 ];
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.');
1155 }
1156 }
1157
1158 /**
1159 * Test recording of amount with comma separator.
1160 *
1161 * @throws \CRM_Core_Exception
1162 */
1163 public function testCommaSeparatorAmount() {
1164 $contactId = $this->individualCreate();
1165
1166 $params = [
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'],
1176 ];
1177
1178 $contribution = $this->callAPISuccess('Order', 'create', $params);
1179 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
1180 $financialTrxn = $this->callAPISuccessGetSingle(
1181 'FinancialTrxn',
1182 [
1183 'id' => $lastFinancialTrxnId['financialTrxnId'],
1184 'return' => ['total_amount'],
1185 ]
1186 );
1187 $this->assertEquals($financialTrxn['total_amount'], 8000, 'Invalid amount.');
1188 }
1189
1190 /**
1191 * Test for function getSalesTaxFinancialAccounts().
1192 */
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.');
1203 }
1204
1205 /**
1206 * Test for function createProportionalEntry().
1207 *
1208 * @param string $thousandSeparator
1209 * punctuation used to refer to thousands.
1210 *
1211 * @dataProvider getThousandSeparators
1212 */
1213 public function testCreateProportionalEntry($thousandSeparator) {
1214 $this->setCurrencySeparators($thousandSeparator);
1215 list($contribution, $financialAccount) = $this->createContributionWithTax();
1216 $params = [
1217 'total_amount' => 55,
1218 'to_financial_account_id' => $financialAccount->financial_account_id,
1219 'payment_instrument_id' => 1,
1220 'trxn_date' => date('Ymd'),
1221 'status_id' => 1,
1222 'entity_id' => $contribution['id'],
1223 ];
1224 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'create', $params);
1225 $entityParams = [
1226 'contribution_total_amount' => $contribution['total_amount'],
1227 'trxn_total_amount' => 55,
1228 'line_item_amount' => 100,
1229 ];
1230 $previousLineItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($contribution['id']);
1231 $eftParams = [
1232 'entity_table' => 'civicrm_financial_item',
1233 'entity_id' => $previousLineItem['id'],
1234 'financial_trxn_id' => (string) $financialTrxn['id'],
1235 ];
1236 CRM_Contribute_BAO_Contribution::createProportionalEntry($entityParams, $eftParams);
1237 $trxnTestArray = array_merge($eftParams, [
1238 'amount' => '50.00',
1239 ]);
1240 $this->callAPISuccessGetSingle('EntityFinancialTrxn', $eftParams, $trxnTestArray);
1241 }
1242
1243 /**
1244 * Test for function createProportionalEntry with zero amount().
1245 *
1246 * @param string $thousandSeparator
1247 * punctuation used to refer to thousands.
1248 *
1249 * @dataProvider getThousandSeparators
1250 */
1251 public function testCreateProportionalEntryZeroAmount($thousandSeparator) {
1252 $this->setCurrencySeparators($thousandSeparator);
1253 list($contribution, $financialAccount) = $this->createContributionWithTax(['total_amount' => 0]);
1254 $params = [
1255 'total_amount' => 0,
1256 'to_financial_account_id' => $financialAccount->financial_account_id,
1257 'payment_instrument_id' => 1,
1258 'trxn_date' => date('Ymd'),
1259 'status_id' => 1,
1260 'entity_id' => $contribution['id'],
1261 ];
1262 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'create', $params);
1263 $entityParams = [
1264 'contribution_total_amount' => $contribution['total_amount'],
1265 'trxn_total_amount' => 0,
1266 'line_item_amount' => 0,
1267 ];
1268 $previousLineItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($contribution['id']);
1269 $eftParams = [
1270 'entity_table' => 'civicrm_financial_item',
1271 'entity_id' => $previousLineItem['id'],
1272 'financial_trxn_id' => (string) $financialTrxn['id'],
1273 ];
1274 CRM_Contribute_BAO_Contribution::createProportionalEntry($entityParams, $eftParams);
1275 $trxnTestArray = array_merge($eftParams, [
1276 'amount' => '0.00',
1277 ]);
1278 $this->callAPISuccessGetSingle('EntityFinancialTrxn', $eftParams, $trxnTestArray);
1279 }
1280
1281 /**
1282 * Test for function getLastFinancialItemIds().
1283 */
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.');
1291 }
1292 }
1293
1294 /**
1295 * Test to ensure proportional entries are creating when adding a payment..
1296 *
1297 * In this test we create a pending contribution for $110 consisting of $100 contribution and $10 tax.
1298 *
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).
1302 */
1303 public function testCreateProportionalFinancialEntriesViaPaymentCreate() {
1304 list($contribution, $financialAccount) = $this->createContributionWithTax([], FALSE);
1305 $params = [
1306 'total_amount' => 50,
1307 'to_financial_account_id' => $financialAccount->financial_account_id,
1308 'payment_instrument_id' => 1,
1309 'trxn_date' => date('Ymd'),
1310 'status_id' => 1,
1311 'entity_id' => $contribution['id'],
1312 'contribution_id' => $contribution['id'],
1313 ];
1314 $financialTrxn = $this->callAPISuccess('Payment', 'create', $params);
1315 $eftParams = [
1316 'entity_table' => 'civicrm_financial_item',
1317 'financial_trxn_id' => $financialTrxn['id'],
1318 ];
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.');
1324 }
1325 }
1326
1327 /**
1328 * Test to check if amount is proportionally asigned for PI change.
1329 */
1330 public function testProportionallyAssignedForPIChange() {
1331 list($contribution, $financialAccount) = $this->createContributionWithTax();
1332 $params = [
1333 'id' => $contribution['id'],
1334 'payment_instrument_id' => 3,
1335 ];
1336 $this->callAPISuccess('Contribution', 'create', $params);
1337 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
1338 $eftParams = [
1339 'entity_table' => 'civicrm_financial_item',
1340 'financial_trxn_id' => $lastFinancialTrxnId['financialTrxnId'],
1341 ];
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.');
1347 }
1348 }
1349
1350 /**
1351 * Function to create contribution with tax.
1352 */
1353 public function createContributionWithTax($params = [], $isCompleted = TRUE) {
1354 if (!isset($params['total_amount'])) {
1355 $params['total_amount'] = 100;
1356 }
1357 $contactId = $this->individualCreate();
1358 $this->enableTaxAndInvoicing();
1359 $financialType = $this->createFinancialType();
1360 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1361 $form = new CRM_Contribute_Form_Contribution();
1362
1363 $form->testSubmit([
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',
1371 [
1372 'contact_id' => $contactId,
1373 'return' => ['tax_amount', 'total_amount'],
1374 ]
1375 );
1376 return [$contribution, $financialAccount];
1377 }
1378
1379 /**
1380 * Test processOnBehalfOrganization() function.
1381 */
1382 public function testProcessOnBehalfOrganization() {
1383 $orgInfo = [
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',
1391 ];
1392 $contactID = $this->individualCreate();
1393 $orgId = $this->organizationCreate(['organization_name' => 'testorg1']);
1394 $orgCount = $this->callAPISuccessGetCount('Contact', [
1395 'contact_type' => "Organization",
1396 'organization_name' => "testorg1",
1397 ]);
1398 $this->assertEquals($orgCount, 1);
1399
1400 $values = $params = [];
1401 $behalfOrganization = [
1402 'organization_name' => 'testorg1',
1403 'phone' => [
1404 1 => [
1405 'phone' => $orgInfo['phone'],
1406 'is_primary' => 1,
1407 ],
1408 ],
1409 'email' => [
1410 1 => [
1411 'email' => $orgInfo['email'],
1412 'is_primary' => 1,
1413 ],
1414 ],
1415 'address' => [
1416 3 => [
1417 'street_address' => $orgInfo['street_address'],
1418 'city' => $orgInfo['city'],
1419 'location_type_id' => 3,
1420 'postal_code' => $orgInfo['postal_code'],
1421 'country' => 'US',
1422 'state_province' => 'AA',
1423 'is_primary' => 1,
1424 ],
1425 ],
1426 ];
1427 $fields = [
1428 'organization_name' => 1,
1429 'phone-3-1' => 1,
1430 'email-3' => 1,
1431 'street_address-3' => 1,
1432 'city-3' => 1,
1433 'postal_code-3' => 1,
1434 'country-3' => 1,
1435 'state_province-3' => 1,
1436 ];
1437 CRM_Contribute_Form_Contribution_Confirm::processOnBehalfOrganization($behalfOrganization, $contactID, $values, $params, $fields);
1438
1439 //Check whether new organisation is not created.
1440 $result = $this->callAPISuccess('Contact', 'get', [
1441 'contact_type' => "Organization",
1442 'organization_name' => "testorg1",
1443 ]);
1444 $this->assertEquals($result['count'], 1);
1445
1446 //Assert all org values are updated.
1447 foreach ($orgInfo as $key => $val) {
1448 $this->assertEquals($result['values'][$orgId][$key], $val);
1449 }
1450
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);
1455 }
1456
1457 /**
1458 * Test for replaceContributionTokens.
1459 * This function tests whether the contribution tokens are replaced with values from contribution.
1460 */
1461 public function testReplaceContributionTokens() {
1462 $customGroup = $this->customGroupCreate(['extends' => 'Contribution', 'title' => 'contribution stuff']);
1463 $customField = $this->customFieldOptionValueCreate($customGroup, 'myCustomField');
1464 $contactId1 = $this->individualCreate();
1465 $params = [
1466 'contact_id' => $contactId1,
1467 'receive_date' => '20120511',
1468 'total_amount' => 100.00,
1469 'financial_type_id' => 1,
1470 'trxn_id' => 12345,
1471 'invoice_id' => 67890,
1472 'source' => 'SSF',
1473 'contribution_status_id' => 2,
1474 "custom_{$customField['id']}" => 'value1',
1475 ];
1476 $contribution1 = $this->contributionCreate($params);
1477 $contactId2 = $this->individualCreate();
1478 $params = [
1479 'contact_id' => $contactId2,
1480 'receive_date' => '20150511',
1481 'total_amount' => 200.00,
1482 'financial_type_id' => 1,
1483 'trxn_id' => 6789,
1484 'invoice_id' => 12345,
1485 'source' => 'ABC',
1486 'contribution_status_id' => 1,
1487 "custom_{$customField['id']}" => 'value2',
1488 ];
1489 $contribution2 = $this->contributionCreate($params);
1490 $ids = [$contribution1, $contribution2];
1491
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>";
1498
1499 $subjectToken = CRM_Utils_Token::getTokens($subject);
1500 $messageToken = CRM_Utils_Token::getTokens($text);
1501 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
1502
1503 $contributionDetails = CRM_Contribute_BAO_Contribution::replaceContributionTokens(
1504 $ids,
1505 $subject,
1506 $subjectToken,
1507 $text,
1508 $html,
1509 $messageToken,
1510 TRUE
1511 );
1512
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");
1518 }
1519
1520 /**
1521 * Test for contribution with deferred revenue.
1522 */
1523 public function testContributionWithDeferredRevenue() {
1524 $contactId = $this->individualCreate();
1525 Civi::settings()->set('deferred_revenue_enabled', TRUE);
1526 $params = [
1527 'contact_id' => $contactId,
1528 'receive_date' => '20120511',
1529 'total_amount' => 100.00,
1530 'financial_type_id' => 'Event Fee',
1531 'trxn_id' => 12345,
1532 'invoice_id' => 67890,
1533 'source' => 'SSF',
1534 'contribution_status_id' => 'Completed',
1535 'revenue_recognition_date' => date('Ymd', strtotime("+3 month")),
1536 ];
1537 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1538
1539 $this->callAPISuccessGetCount('EntityFinancialTrxn', [
1540 'entity_table' => "civicrm_contribution",
1541 'entity_id' => $contribution['id'],
1542 ], 2);
1543
1544 $checkAgainst = [
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',
1548 ];
1549 $result = $this->callAPISuccessGetSingle('EntityFinancialTrxn', [
1550 'return' => [
1551 "financial_trxn_id.from_financial_account_id.name",
1552 "financial_trxn_id.to_financial_account_id.name",
1553 "financial_trxn_id",
1554 ],
1555 'entity_table' => "civicrm_contribution",
1556 'entity_id' => $contribution['id'],
1557 'financial_trxn_id.is_payment' => 0,
1558 ], $checkAgainst);
1559
1560 $result = $this->callAPISuccessGetSingle('EntityFinancialTrxn', [
1561 'entity_table' => "civicrm_financial_item",
1562 'financial_trxn_id' => $result['financial_trxn_id'],
1563 'return' => ['entity_id'],
1564 ]);
1565
1566 $checkAgainst = [
1567 'financial_account_id.name' => 'Deferred Revenue - Event Fee',
1568 'id' => $result['entity_id'],
1569 ];
1570 $result = $this->callAPISuccessGetSingle('FinancialItem', [
1571 'id' => $result['entity_id'],
1572 'return' => ["financial_account_id.name"],
1573 ], $checkAgainst);
1574 }
1575
1576 /**
1577 * https://lab.civicrm.org/dev/financial/issues/56
1578 * Changing financial type on a contribution records correct financial items
1579 */
1580 public function testChangingFinancialTypeWithoutTax() {
1581 $ids = $values = [];
1582 $contactId = $this->individualCreate();
1583 $params = [
1584 'contact_id' => $contactId,
1585 'receive_date' => date('YmdHis'),
1586 'total_amount' => 100.00,
1587 'financial_type_id' => 'Donation',
1588 'contribution_status_id' => 'Completed',
1589 ];
1590 /* first test the scenario when sending an email */
1591 $contributionId = $this->callAPISuccess(
1592 'contribution',
1593 'create',
1594 $params
1595 )['id'];
1596
1597 // Update Financial Type.
1598 $this->callAPISuccess('contribution', 'create', [
1599 'id' => $contributionId,
1600 'financial_type_id' => 'Event Fee',
1601 ]);
1602
1603 // Get line item
1604 $lineItem = $this->callAPISuccessGetSingle('LineItem', [
1605 'contribution_id' => $contributionId,
1606 'return' => ["financial_type_id.name", "line_total"],
1607 ]);
1608
1609 $this->assertEquals(
1610 $lineItem['line_total'],
1611 100.00,
1612 'Invalid line amount.'
1613 );
1614
1615 $this->assertEquals(
1616 $lineItem['financial_type_id.name'],
1617 'Event Fee',
1618 'Invalid Financial Type stored.'
1619 );
1620
1621 // Get Financial Items.
1622 $financialItems = $this->callAPISuccess('FinancialItem', 'get', [
1623 'entity_id' => $lineItem['id'],
1624 'sequential' => 1,
1625 'entity_table' => 'civicrm_line_item',
1626 'options' => ['sort' => "id"],
1627 'return' => ["financial_account_id.name", "amount", "description"],
1628 ]);
1629
1630 $this->assertEquals($financialItems['count'], 3, 'Count mismatch.');
1631
1632 $toCheck = [
1633 ['Donation', 100.00],
1634 ['Donation', -100.00],
1635 ['Event Fee', 100.00],
1636 ];
1637
1638 foreach ($financialItems['values'] as $key => $values) {
1639 $this->assertEquals(
1640 $values['financial_account_id.name'],
1641 $toCheck[$key][0],
1642 'Invalid Financial Account stored.'
1643 );
1644 $this->assertEquals(
1645 $values['amount'],
1646 $toCheck[$key][1],
1647 'Amount mismatch.'
1648 );
1649 $this->assertEquals(
1650 $values['description'],
1651 'Contribution Amount',
1652 'Description mismatch.'
1653 );
1654 }
1655
1656 // Check transactions.
1657 $financialTransactions = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
1658 'return' => ["financial_trxn_id"],
1659 'entity_table' => "civicrm_contribution",
1660 'entity_id' => $contributionId,
1661 'sequential' => 1,
1662 ]);
1663 $this->assertEquals($financialTransactions['count'], 3, 'Count mismatch.');
1664
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],
1670 ], 2);
1671 }
1672 }
1673
1674 /**
1675 * CRM-21424 Check if the receipt update is set after composing the receipt message
1676 */
1677 public function testSendMailUpdateReceiptDate() {
1678 $ids = $values = [];
1679 $contactId = $this->individualCreate();
1680 $params = [
1681 'contact_id' => $contactId,
1682 'receive_date' => '20120511',
1683 'total_amount' => 100.00,
1684 'financial_type_id' => 'Donation',
1685 'source' => 'SSF',
1686 'contribution_status_id' => 'Completed',
1687 ];
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');
1698
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');
1710 }
1711
1712 }