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