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