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