Merge pull request #12464 from jaapjansma/issue_141
[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
TO
364
365 $ids = array(
366 'premium' => NULL,
367 );
368
6a488035
TO
369 $params = array(
370 'name' => 'TEST Premium',
371 'sku' => 111,
372 'imageOption' => 'noImage',
373 'MAX_FILE_SIZE' => 2097152,
374 'price' => 100.00,
375 'cost' => 90.00,
376 'min_contribution' => 100,
377 'is_active' => 1,
378 );
379 $premium = CRM_Contribute_BAO_ManagePremiums::add($params, $ids);
380
381 $this->assertEquals('TEST Premium', $premium->name, 'Check for premium name.');
382
6a488035
TO
383 $param = array(
384 'contact_id' => $contactId,
385 'currency' => 'USD',
92915c55 386 'financial_type_id' => 1,
6a488035
TO
387 'contribution_status_id' => 1,
388 'payment_instrument_id' => 1,
389 'source' => 'STUDENT',
390 'receive_date' => '20080522000000',
391 'receipt_date' => '20080522000000',
392 'id' => NULL,
393 'non_deductible_amount' => 0.00,
394 'total_amount' => 300.00,
395 'fee_amount' => 5,
396 'net_amount' => 295,
397 'trxn_id' => '33erdfrwvw434',
398 'invoice_id' => '98ed34f7u9hh672ce0eafe8fb92',
399 'thankyou_date' => '20080522',
d0c97775 400 'sequential' => TRUE,
6a488035 401 );
d0c97775 402 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
6a488035 403
d0c97775 404 $this->assertEquals($param['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
405 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
6a488035
TO
406
407 //parameter for adding premium to contribution
408 $data = array(
409 'product_id' => $premium->id,
d0c97775 410 'contribution_id' => $contribution['id'],
6a488035
TO
411 'product_option' => NULL,
412 'quantity' => 1,
413 );
414 $contributionProduct = CRM_Contribute_BAO_Contribution::addPremium($data);
415 $this->assertEquals($contributionProduct->product_id, $premium->id, 'Check for Product id .');
416
417 //Delete Product
418 CRM_Contribute_BAO_ManagePremiums::del($premium->id);
419 $this->assertDBNull('CRM_Contribute_DAO_Product', $premium->name,
420 'id', 'name', 'Database check for deleted Product.'
421 );
6a488035
TO
422 }
423
424 /**
fe482240 425 * Check duplicate contribution id.
6a488035
TO
426 * during the contribution import
427 * checkDuplicateIds();
428 */
00be9182 429 public function testcheckDuplicateIds() {
2449fe69 430 $contactId = $this->individualCreate();
6a488035
TO
431
432 $param = array(
433 'contact_id' => $contactId,
434 'currency' => 'USD',
92915c55 435 'financial_type_id' => 1,
6a488035
TO
436 'contribution_status_id' => 1,
437 'payment_instrument_id' => 1,
438 'source' => 'STUDENT',
439 'receive_date' => '20080522000000',
440 'receipt_date' => '20080522000000',
441 'id' => NULL,
442 'non_deductible_amount' => 0.00,
443 'total_amount' => 300.00,
444 'fee_amount' => 5,
445 'net_amount' => 295,
446 'trxn_id' => '76ereeswww835',
447 'invoice_id' => '93ed39a9e9hd621bs0eafe3da82',
448 'thankyou_date' => '20080522',
d0c97775 449 'sequential' => TRUE,
6a488035
TO
450 );
451
d0c97775 452 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
6a488035 453
d0c97775 454 $this->assertEquals($param['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
455 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
6a488035 456 $data = array(
d0c97775 457 'id' => $contribution['id'],
458 'trxn_id' => $contribution['trxn_id'],
459 'invoice_id' => $contribution['invoice_id'],
6a488035
TO
460 );
461 $contributionID = CRM_Contribute_BAO_Contribution::checkDuplicateIds($data);
d0c97775 462 $this->assertEquals($contributionID, $contribution['id'], 'Check for duplicate transcation id .');
6a488035 463 }
96025800 464
8022372f
GC
465 /**
466 * Check credit note id creation
467 * when a contribution is cancelled or refunded
468 * createCreditNoteId();
469 */
470 public function testCreateCreditNoteId() {
2449fe69 471 $contactId = $this->individualCreate();
8022372f
GC
472
473 $param = array(
474 'contact_id' => $contactId,
475 'currency' => 'USD',
476 'financial_type_id' => 1,
477 'contribution_status_id' => 3,
478 'payment_instrument_id' => 1,
479 'source' => 'STUDENT',
480 'receive_date' => '20080522000000',
481 'receipt_date' => '20080522000000',
482 'id' => NULL,
483 'non_deductible_amount' => 0.00,
484 'total_amount' => 300.00,
485 'fee_amount' => 5,
486 'net_amount' => 295,
487 'trxn_id' => '76ereeswww835',
488 'invoice_id' => '93ed39a9e9hd621bs0eafe3da82',
489 'thankyou_date' => '20080522',
d0c97775 490 'sequential' => TRUE,
8022372f
GC
491 );
492
493 $creditNoteId = CRM_Contribute_BAO_Contribution::createCreditNoteId();
d0c97775 494 $contribution = $this->callAPISuccess('Contribution', 'create', $param)['values'][0];
495 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
496 $this->assertEquals($creditNoteId, $contribution['creditnote_id'], 'Check if credit note id is created correctly.');
8022372f
GC
497 }
498
b04e4b11
PN
499 /**
500 * Create() method (create and update modes).
501 */
502 public function testIsPaymentFlag() {
2449fe69 503 $contactId = $this->individualCreate();
b04e4b11 504
d0c97775 505 $params = [
b04e4b11
PN
506 'contact_id' => $contactId,
507 'currency' => 'USD',
508 'financial_type_id' => 1,
509 'contribution_status_id' => 1,
510 'payment_instrument_id' => 1,
511 'source' => 'STUDENT',
512 'receive_date' => '20080522000000',
513 'receipt_date' => '20080522000000',
514 'non_deductible_amount' => 0.00,
515 'total_amount' => 200.00,
516 'fee_amount' => 5,
517 'net_amount' => 195,
518 'trxn_id' => '22ereerwww4444xx',
519 'invoice_id' => '86ed39c9e9ee6ef6541621ce0eafe7eb81',
520 'thankyou_date' => '20080522',
d0c97775 521 'sequential' => TRUE,
522 ];
523 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
b04e4b11 524
d0c97775 525 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id creation.');
526 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
b04e4b11
PN
527
528 $trxnArray = array(
529 'trxn_id' => $params['trxn_id'],
530 'is_payment' => 1,
531 );
532 $defaults = array();
533 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
4ba3c75f 534 $this->assertEquals(1, $financialTrxn->N, 'Mismatch count for is payment flag.');
b04e4b11 535 //update contribution amount
d0c97775 536 $params['id'] = $contribution['id'];
b04e4b11 537 $params['total_amount'] = 150;
d0c97775 538 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
b04e4b11 539
d0c97775 540 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id .');
541 $this->assertEquals($params['total_amount'], $contribution['total_amount'], 'Check for Amount updation.');
b04e4b11
PN
542 $trxnArray = array(
543 'trxn_id' => $params['trxn_id'],
544 'is_payment' => 1,
545 );
546 $defaults = array();
547 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
4ba3c75f 548 $this->assertEquals(2, $financialTrxn->N, 'Mismatch count for is payment flag.');
b04e4b11
PN
549 $trxnArray['is_payment'] = 0;
550 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
4ba3c75f 551 $this->assertEquals(1, $financialTrxn->N, 'Mismatch count for is payment flag.');
b04e4b11
PN
552 }
553
a387acc9
PN
554 /**
555 * Create() method (create and update modes).
556 */
557 public function testIsPaymentFlagForPending() {
2449fe69 558 $contactId = $this->individualCreate();
a387acc9
PN
559
560 $params = array(
561 'contact_id' => $contactId,
562 'currency' => 'USD',
563 'financial_type_id' => 1,
564 'contribution_status_id' => 2,
565 'payment_instrument_id' => 1,
566 'source' => 'STUDENT',
567 'is_pay_later' => 1,
568 'receive_date' => '20080522000000',
569 'receipt_date' => '20080522000000',
570 'non_deductible_amount' => 0.00,
571 'total_amount' => 200.00,
572 'fee_amount' => 5,
573 'net_amount' => 195,
574 'trxn_id' => '22ereerwww4444yy',
575 'invoice_id' => '86ed39c9e9yy6ef6541621ce0eafe7eb81',
576 'thankyou_date' => '20080522',
d0c97775 577 'sequential' => TRUE,
a387acc9
PN
578 );
579
d0c97775 580 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
a387acc9 581
d0c97775 582 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transaction id creation.');
583 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
a387acc9
PN
584
585 $trxnArray = array(
586 'trxn_id' => $params['trxn_id'],
587 'is_payment' => 0,
588 );
589 $defaults = array();
590 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
591 $this->assertEquals(2, $financialTrxn->N, 'Mismatch count for is payment flag.');
592 $trxnArray['is_payment'] = 1;
593 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
594 $this->assertEquals(NULL, $financialTrxn, 'Mismatch count for is payment flag.');
595 //update contribution amount
d0c97775 596 $params['id'] = $contribution['id'];
a387acc9
PN
597 $params['contribution_status_id'] = 1;
598
d0c97775 599 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
a387acc9 600
d0c97775 601 $this->assertEquals($params['trxn_id'], $contribution['trxn_id'], 'Check for transcation id .');
602 $this->assertEquals($params['contribution_status_id'], $contribution['contribution_status_id'], 'Check for status updation.');
a387acc9
PN
603 $trxnArray = array(
604 'trxn_id' => $params['trxn_id'],
605 'is_payment' => 1,
606 );
607 $defaults = array();
608 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
609 $this->assertEquals(1, $financialTrxn->N, 'Mismatch count for is payment flag.');
610 $trxnArray['is_payment'] = 0;
611 $financialTrxn = CRM_Core_BAO_FinancialTrxn::retrieve($trxnArray, $defaults);
612 $this->assertEquals(2, $financialTrxn->N, 'Mismatch count for is payment flag.');
a387acc9
PN
613 }
614
eec619df 615 /**
0a5651eb 616 * addPayments() method (add and edit modes of participant)
eec619df
PN
617 */
618 public function testAddPayments() {
619 list($lineItems, $contribution) = $this->addParticipantWithContribution();
d0c97775 620 CRM_Contribute_BAO_Contribution::addPayments([$contribution]);
0a5651eb
PN
621 $this->checkItemValues($contribution);
622 }
623
624 /**
625 * checks db values for financial item
626 */
624195c8 627 public function checkItemValues($contribution) {
876b8ab0 628 $toFinancialAccount = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount(4, 'Accounts Receivable Account is');
2449fe69 629 $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
630INNER JOIN civicrm_entity_financial_trxn eft1 ON (eft1.financial_trxn_id = eft.financial_trxn_id AND eft1.entity_table = 'civicrm_financial_item')
631WHERE eft.entity_id = %1 AND ft.to_financial_account_id <> %2";
632
633 $queryParams[1] = array($contribution->id, 'Integer');
634 $queryParams[2] = array($toFinancialAccount, 'Integer');
635
636 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
19084b68 637 $amounts = array(100.00, 50.00);
eec619df
PN
638 while ($dao->fetch()) {
639 $this->assertEquals(150.00, $dao->total_amount, 'Mismatch of total amount paid.');
19084b68 640 $this->assertEquals($dao->amount, array_pop($amounts), 'Mismatch of amount proportionally assigned to financial item');
eec619df 641 }
eec619df
PN
642 }
643
0a5651eb
PN
644 /**
645 * assignProportionalLineItems() method (add and edit modes of participant)
646 */
647 public function testAssignProportionalLineItems() {
648 list($lineItems, $contribution) = $this->addParticipantWithContribution();
0a5651eb
PN
649 $params = array(
650 'contribution_id' => $contribution->id,
651 'total_amount' => 150.00,
652 );
653 $trxn = new CRM_Financial_DAO_FinancialTrxn();
654 $trxn->orderBy('id DESC');
655 $trxn->find(TRUE);
8de1ade9 656 CRM_Contribute_BAO_Contribution::assignProportionalLineItems($params, $trxn->id, $contribution->total_amount);
0a5651eb
PN
657 $this->checkItemValues($contribution);
658 }
659
eec619df
PN
660 /**
661 * Add participant with contribution
662 *
663 * @return array
664 */
78c99516 665 public function addParticipantWithContribution() {
eec619df 666 // creating price set, price field
2449fe69 667 $this->_contactId = $this->individualCreate();
668 $event = $this->eventCreate();
669 $this->_eventId = $event['id'];
624195c8 670 $paramsSet['title'] = 'Price Set' . substr(sha1(rand()), 0, 4);
19084b68 671 $paramsSet['name'] = CRM_Utils_String::titleToVar($paramsSet['title']);
eec619df
PN
672 $paramsSet['is_active'] = TRUE;
673 $paramsSet['financial_type_id'] = 4;
674 $paramsSet['extends'] = 1;
675
676 $priceset = CRM_Price_BAO_PriceSet::create($paramsSet);
677 $priceSetId = $priceset->id;
678
679 //Checking for priceset added in the table.
680 $this->assertDBCompareValue('CRM_Price_BAO_PriceSet', $priceSetId, 'title',
681 'id', $paramsSet['title'], 'Check DB for created priceset'
682 );
683 $paramsField = array(
684 'label' => 'Price Field',
685 'name' => CRM_Utils_String::titleToVar('Price Field'),
686 'html_type' => 'CheckBox',
687 'option_label' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
688 'option_value' => array('1' => 100, '2' => 200),
689 'option_name' => array('1' => 'Price Field 1', '2' => 'Price Field 2'),
690 'option_weight' => array('1' => 1, '2' => 2),
691 'option_amount' => array('1' => 100, '2' => 200),
692 'is_display_amounts' => 1,
693 'weight' => 1,
694 'options_per_line' => 1,
695 'is_active' => array('1' => 1, '2' => 1),
696 'price_set_id' => $priceset->id,
697 'is_enter_qty' => 1,
698 'financial_type_id' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', 'Event Fee', 'id', 'name'),
699 );
700 $priceField = CRM_Price_BAO_PriceField::create($paramsField);
701 $eventParams = array(
702 'id' => $this->_eventId,
703 'financial_type_id' => 4,
704 'is_monetary' => 1,
705 );
706 CRM_Event_BAO_Event::create($eventParams);
707 CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_eventId, $priceSetId);
e4ba8498 708
eec619df
PN
709 $priceFields = $this->callAPISuccess('PriceFieldValue', 'get', array('price_field_id' => $priceField->id));
710 $participantParams = array(
711 'financial_type_id' => 4,
712 'event_id' => $this->_eventId,
713 'role_id' => 1,
714 'status_id' => 14,
715 'fee_currency' => 'USD',
716 'contact_id' => $this->_contactId,
717 );
718 $participant = CRM_Event_BAO_Participant::add($participantParams);
719 $contributionParams = array(
720 'total_amount' => 150,
721 'currency' => 'USD',
722 'contact_id' => $this->_contactId,
723 'financial_type_id' => 4,
724 'contribution_status_id' => 1,
725 'partial_payment_total' => 300.00,
f49cdeab 726 'partial_amount_to_pay' => 150,
eec619df
PN
727 'contribution_mode' => 'participant',
728 'participant_id' => $participant->id,
d0c97775 729 'sequential' => TRUE,
eec619df
PN
730 );
731
732 foreach ($priceFields['values'] as $key => $priceField) {
733 $lineItems[1][$key] = array(
734 'price_field_id' => $priceField['price_field_id'],
735 'price_field_value_id' => $priceField['id'],
736 'label' => $priceField['label'],
737 'field_title' => $priceField['label'],
738 'qty' => 1,
739 'unit_price' => $priceField['amount'],
740 'line_total' => $priceField['amount'],
741 'financial_type_id' => $priceField['financial_type_id'],
742 );
743 }
744 $contributionParams['line_item'] = $lineItems;
d0c97775 745 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams)['values'][0];
eec619df
PN
746
747 $paymentParticipant = array(
748 'participant_id' => $participant->id,
d0c97775 749 'contribution_id' => $contribution['id'],
eec619df 750 );
a5750507 751 CRM_Event_BAO_ParticipantPayment::create($paymentParticipant);
eec619df 752
d0c97775 753 $contributionObject = new CRM_Contribute_BAO_Contribution();
754 $contributionObject->id = $contribution['id'];
755 $contributionObject->find(TRUE);
756
757 return array($lineItems, $contributionObject);
eec619df
PN
758 }
759
5c8b902b 760 /**
a4a31ffe 761 * checkLineItems() check if total amount matches the sum of line total
5c8b902b
PN
762 */
763 public function testcheckLineItems() {
764 $params = array(
765 'contact_id' => 202,
766 'receive_date' => '2010-01-20',
767 'total_amount' => 100,
768 'financial_type_id' => 3,
769 'line_items' => array(
770 array(
771 'line_item' => array(
772 array(
773 'entity_table' => 'civicrm_contribution',
774 'price_field_id' => 8,
775 'price_field_value_id' => 16,
776 'label' => 'test 1',
777 'qty' => 1,
778 'unit_price' => 100,
779 'line_total' => 100,
780 ),
781 array(
782 'entity_table' => 'civicrm_contribution',
783 'price_field_id' => 8,
784 'price_field_value_id' => 17,
785 'label' => 'Test 2',
786 'qty' => 1,
787 'unit_price' => 200,
788 'line_total' => 200,
789 'financial_type_id' => 1,
790 ),
791 ),
a4a31ffe 792 'params' => array(),
5c8b902b 793 ),
a4a31ffe 794 ),
5c8b902b 795 );
af004c04 796 try {
2449fe69 797 CRM_Contribute_BAO_Contribution::checkLineItems($params);
af004c04
PN
798 $this->fail("Missed expected exception");
799 }
800 catch (Exception $e) {
801 $this->assertEquals("Line item total doesn't match with total amount.", $e->getMessage());
802 }
5c8b902b
PN
803 $this->assertEquals(3, $params['line_items'][0]['line_item'][0]['financial_type_id']);
804 $params['total_amount'] = 300;
af004c04 805 CRM_Contribute_BAO_Contribution::checkLineItems($params);
5c8b902b
PN
806 }
807
88f7a518
E
808 /**
809 * Test activity amount updation.
810 */
811 public function testActivityCreate() {
812 $contactId = $this->individualCreate();
813 $defaults = array();
814
815 $params = array(
816 'contact_id' => $contactId,
817 'currency' => 'USD',
818 'financial_type_id' => 1,
819 'contribution_status_id' => 1,
820 'payment_instrument_id' => 1,
821 'source' => 'STUDENT',
822 'receive_date' => '20080522000000',
823 'receipt_date' => '20080522000000',
824 'non_deductible_amount' => 0.00,
825 'total_amount' => 100.00,
826 'trxn_id' => '22ereerwww444444',
827 'invoice_id' => '86ed39c9e9ee6ef6031621ce0eafe7eb81',
828 'thankyou_date' => '20160519',
d0c97775 829 'sequential' => 1,
88f7a518
E
830 );
831
d0c97775 832 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
88f7a518 833
d0c97775 834 $this->assertEquals($params['total_amount'], $contribution['total_amount'], 'Check for total amount in contribution.');
835 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
88f7a518
E
836
837 // Check amount in activity.
838 $activityParams = array(
d0c97775 839 'source_record_id' => $contribution['id'],
d66c61b6 840 'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Contribution'),
88f7a518 841 );
d66c61b6 842 // @todo use api instead.
88f7a518
E
843 $activity = CRM_Activity_BAO_Activity::retrieve($activityParams, $defaults);
844
d0c97775 845 $this->assertEquals($contribution['id'], $activity->source_record_id, 'Check for activity associated with contribution.');
88f7a518
E
846 $this->assertEquals("$ 100.00 - STUDENT", $activity->subject, 'Check for total amount in activity.');
847
d0c97775 848 $params['id'] = $contribution['id'];
88f7a518
E
849 $params['total_amount'] = 200;
850
d0c97775 851 $contribution = $this->callAPISuccess('Contribution', 'create', $params)['values'][0];
88f7a518 852
d0c97775 853 $this->assertEquals($params['total_amount'], $contribution['total_amount'], 'Check for total amount in contribution.');
854 $this->assertEquals($contactId, $contribution['contact_id'], 'Check for contact id creation.');
88f7a518
E
855
856 // Retrieve activity again.
857 $activity = CRM_Activity_BAO_Activity::retrieve($activityParams, $defaults);
858
d0c97775 859 $this->assertEquals($contribution['id'], $activity->source_record_id, 'Check for activity associated with contribution.');
88f7a518
E
860 $this->assertEquals("$ 200.00 - STUDENT", $activity->subject, 'Check for total amount in activity.');
861 }
862
ce7fc91a
PN
863 /**
864 * Test checkContributeSettings.
865 */
866 public function testCheckContributeSettings() {
867 $settings = CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled');
868 $this->assertNull($settings);
869 $params = array(
870 'contribution_invoice_settings' => array(
871 'deferred_revenue_enabled' => '1',
872 ),
873 );
874 $this->callAPISuccess('Setting', 'create', $params);
875 $settings = CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled');
876 $this->assertEquals($settings, 1, 'Check for settings has failed');
877 }
878
5c3d600f
PN
879 /**
880 * Test allowUpdateRevenueRecognitionDate.
881 */
882 public function testAllowUpdateRevenueRecognitionDate() {
883 $contactId = $this->individualCreate();
884 $params = array(
885 'contact_id' => $contactId,
886 'receive_date' => '2010-01-20',
887 'total_amount' => 100,
4303ea89 888 'financial_type_id' => 4,
5c3d600f
PN
889 );
890 $order = $this->callAPISuccess('order', 'create', $params);
891 $allowUpdate = CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($order['id']);
892 $this->assertTrue($allowUpdate);
893
894 $event = $this->eventCreate();
895 $params = array(
896 'contact_id' => $contactId,
897 'receive_date' => '2010-01-20',
898 'total_amount' => 300,
8484a5f0 899 'financial_type_id' => $this->getFinancialTypeId('Event Fee'),
900 'contribution_status_id' => 'Completed',
5c3d600f
PN
901 );
902 $priceFields = $this->createPriceSet('event', $event['id']);
903 foreach ($priceFields['values'] as $key => $priceField) {
904 $lineItems[$key] = array(
905 'price_field_id' => $priceField['price_field_id'],
906 'price_field_value_id' => $priceField['id'],
907 'label' => $priceField['label'],
908 'field_title' => $priceField['label'],
909 'qty' => 1,
910 'unit_price' => $priceField['amount'],
911 'line_total' => $priceField['amount'],
912 'financial_type_id' => $priceField['financial_type_id'],
913 'entity_table' => 'civicrm_participant',
914 );
915 }
916 $params['line_items'][] = array(
917 'line_item' => $lineItems,
918 'params' => array(
919 'contact_id' => $contactId,
920 'event_id' => $event['id'],
921 'status_id' => 1,
922 'role_id' => 1,
923 'register_date' => '2007-07-21 00:00:00',
924 'source' => 'Online Event Registration: API Testing',
925 ),
926 );
927 $order = $this->callAPISuccess('order', 'create', $params);
928 $allowUpdate = CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($order['id']);
929 $this->assertFalse($allowUpdate);
930
931 $params = array(
932 'contact_id' => $contactId,
933 'receive_date' => '2010-01-20',
934 'total_amount' => 200,
8484a5f0 935 'financial_type_id' => $this->getFinancialTypeId('Member Dues'),
936 'contribution_status_id' => 'Completed',
5c3d600f
PN
937 );
938 $membershipType = $this->membershipTypeCreate();
939 $priceFields = $this->createPriceSet();
940 $lineItems = array();
941 foreach ($priceFields['values'] as $key => $priceField) {
942 $lineItems[$key] = array(
943 'price_field_id' => $priceField['price_field_id'],
944 'price_field_value_id' => $priceField['id'],
945 'label' => $priceField['label'],
946 'field_title' => $priceField['label'],
947 'qty' => 1,
948 'unit_price' => $priceField['amount'],
949 'line_total' => $priceField['amount'],
950 'financial_type_id' => $priceField['financial_type_id'],
951 'entity_table' => 'civicrm_membership',
952 'membership_type_id' => $membershipType,
953 );
954 }
955 $params['line_items'][] = array(
956 'line_item' => array(array_pop($lineItems)),
957 'params' => array(
958 'contact_id' => $contactId,
959 'membership_type_id' => $membershipType,
960 'join_date' => '2006-01-21',
961 'start_date' => '2006-01-21',
962 'end_date' => '2006-12-21',
963 'source' => 'Payment',
964 'is_override' => 1,
965 'status_id' => 1,
966 ),
967 );
968 $order = $this->callAPISuccess('order', 'create', $params);
969 $allowUpdate = CRM_Contribute_BAO_Contribution::allowUpdateRevenueRecognitionDate($order['id']);
970 $this->assertFalse($allowUpdate);
971 }
972
d9553c2e
PN
973 /**
974 * Test calculateFinancialItemAmount().
975 */
976 public function testcalculateFinancialItemAmount() {
977 $testParams = array(
978 array(
979 'params' => array(),
980 'amountParams' => array(
981 'line_total' => 100,
982 'previous_line_total' => 300,
983 'diff' => 1,
984 ),
985 'context' => 'changedAmount',
986 'expectedItemAmount' => -200,
987 ),
988 array(
989 'params' => array(),
990 'amountParams' => array(
991 'line_total' => 100,
992 'previous_line_total' => 100,
993 'diff' => -1,
994 ),
995 'context' => 'changePaymentInstrument',
996 'expectedItemAmount' => -100,
997 ),
998 array(
999 'params' => array(
1000 'is_quick_config' => TRUE,
1001 'total_amount' => 110,
1002 'tax_amount' => 10,
1003 ),
1004 'amountParams' => array(
1005 'item_amount' => 100,
1006 ),
1007 'context' => 'changedAmount',
1008 'expectedItemAmount' => 100,
1009 ),
1010 array(
1011 'params' => array(
1012 'is_quick_config' => TRUE,
1013 'total_amount' => 110,
1014 'tax_amount' => 10,
1015 ),
1016 'amountParams' => array(
1017 'item_amount' => NULL,
1018 ),
1019 'context' => 'changedAmount',
1020 'expectedItemAmount' => 110,
1021 ),
1022 array(
1023 'params' => array(
1024 'is_quick_config' => TRUE,
1025 'total_amount' => 110,
1026 'tax_amount' => 10,
1027 ),
1028 'amountParams' => array(
1029 'item_amount' => NULL,
1030 ),
1031 'context' => NULL,
1032 'expectedItemAmount' => 100,
1033 ),
1034 );
1035 foreach ($testParams as $params) {
1036 $itemAmount = CRM_Contribute_BAO_Contribution::calculateFinancialItemAmount($params['params'], $params['amountParams'], $params['context']);
1037 $this->assertEquals($itemAmount, $params['expectedItemAmount'], 'Invalid Financial Item amount.');
1038 }
1039 }
1040
d934a732
PN
1041 /**
1042 * Test recording of amount with comma separator.
1043 */
1044 public function testCommaSeparatorAmount() {
1045 $contactId = $this->individualCreate();
1046
1047 $params = array(
1048 'contact_id' => $contactId,
1049 'currency' => 'USD',
1050 'financial_type_id' => 1,
1051 'contribution_status_id' => 8,
1052 'payment_instrument_id' => 1,
1053 'receive_date' => '20080522000000',
1054 'receipt_date' => '20080522000000',
1055 'total_amount' => '20000.00',
1056 'partial_payment_total' => '20,000.00',
f49cdeab 1057 'partial_amount_to_pay' => '8,000.00',
d934a732
PN
1058 );
1059
d0c97775 1060 $contribution = $this->callAPISuccess('Contribution', 'create', $params);
1061 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
d934a732
PN
1062 $financialTrxn = $this->callAPISuccessGetSingle(
1063 'FinancialTrxn',
1064 array(
1065 'id' => $lastFinancialTrxnId['financialTrxnId'],
1066 'return' => array('total_amount'),
1067 )
1068 );
1069 $this->assertEquals($financialTrxn['total_amount'], 8000, 'Invalid Tax amount.');
1070 }
1071
adbc354b
PN
1072 /**
1073 * Test for function getSalesTaxFinancialAccounts().
1074 */
1075 public function testgetSalesTaxFinancialAccounts() {
1076 $this->enableTaxAndInvoicing();
1077 $financialType = $this->createFinancialType();
1078 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1079 $expectedResult = array($financialAccount->financial_account_id => $financialAccount->financial_account_id);
1080 $financialType = $this->createFinancialType();
1081 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1082 $expectedResult[$financialAccount->financial_account_id] = $financialAccount->financial_account_id;
1083 $salesTaxFinancialAccount = CRM_Contribute_BAO_Contribution::getSalesTaxFinancialAccounts();
1084 $this->assertTrue(($salesTaxFinancialAccount == $expectedResult), 'Function returned wrong values.');
1085 }
1086
0409b821
PN
1087 /**
1088 * Test for function createProportionalEntry().
83644f47 1089 *
1090 * @param string $thousandSeparator
1091 * punctuation used to refer to thousands.
1092 *
1093 * @dataProvider getThousandSeparators
0409b821 1094 */
83644f47 1095 public function testCreateProportionalEntry($thousandSeparator) {
1096 $this->setCurrencySeparators($thousandSeparator);
2a4a2f00 1097 list($contribution, $financialAccount) = $this->createContributionWithTax();
0409b821
PN
1098 $params = array(
1099 'total_amount' => 55,
1100 'to_financial_account_id' => $financialAccount->financial_account_id,
1101 'payment_instrument_id' => 1,
1102 'trxn_date' => date('Ymd'),
1103 'status_id' => 1,
0409b821 1104 'entity_id' => $contribution['id'],
0409b821 1105 );
3137781d 1106 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'create', $params);
0409b821
PN
1107 $entityParams = array(
1108 'contribution_total_amount' => $contribution['total_amount'],
1109 'trxn_total_amount' => 55,
1110 'line_item_amount' => 100,
1111 );
1112 $previousLineItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($contribution['id']);
1113 $eftParams = array(
1114 'entity_table' => 'civicrm_financial_item',
cf28d075 1115 'entity_id' => $previousLineItem['id'],
3137781d 1116 'financial_trxn_id' => (string) $financialTrxn['id'],
0409b821
PN
1117 );
1118 CRM_Contribute_BAO_Contribution::createProportionalEntry($entityParams, $eftParams);
1119 $trxnTestArray = array_merge($eftParams, array(
3137781d 1120 'amount' => '50.00',
0409b821 1121 ));
cf28d075 1122 $this->callAPISuccessGetSingle('EntityFinancialTrxn', $eftParams, $trxnTestArray);
0409b821
PN
1123 }
1124
c364c544
MW
1125 /**
1126 * Test for function createProportionalEntry with zero amount().
1127 *
1128 * @param string $thousandSeparator
1129 * punctuation used to refer to thousands.
1130 *
1131 * @dataProvider getThousandSeparators
1132 */
1133 public function testCreateProportionalEntryZeroAmount($thousandSeparator) {
1134 $this->setCurrencySeparators($thousandSeparator);
1135 list($contribution, $financialAccount) = $this->createContributionWithTax(array('total_amount' => 0));
1136 $params = array(
1137 'total_amount' => 0,
1138 'to_financial_account_id' => $financialAccount->financial_account_id,
1139 'payment_instrument_id' => 1,
1140 'trxn_date' => date('Ymd'),
1141 'status_id' => 1,
1142 'entity_id' => $contribution['id'],
1143 );
1144 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'create', $params);
1145 $entityParams = array(
1146 'contribution_total_amount' => $contribution['total_amount'],
1147 'trxn_total_amount' => 0,
1148 'line_item_amount' => 0,
1149 );
1150 $previousLineItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($contribution['id']);
1151 $eftParams = array(
1152 'entity_table' => 'civicrm_financial_item',
1153 'entity_id' => $previousLineItem['id'],
1154 'financial_trxn_id' => (string) $financialTrxn['id'],
1155 );
1156 CRM_Contribute_BAO_Contribution::createProportionalEntry($entityParams, $eftParams);
1157 $trxnTestArray = array_merge($eftParams, array(
1158 'amount' => '0.00',
1159 ));
1160 $this->callAPISuccessGetSingle('EntityFinancialTrxn', $eftParams, $trxnTestArray);
1161 }
1162
646bc565
PN
1163 /**
1164 * Test for function getLastFinancialItemIds().
1165 */
1166 public function testgetLastFinancialItemIds() {
2a4a2f00 1167 list($contribution, $financialAccount) = $this->createContributionWithTax();
646bc565
PN
1168 list($ftIds, $taxItems) = CRM_Contribute_BAO_Contribution::getLastFinancialItemIds($contribution['id']);
1169 $this->assertEquals(count($ftIds), 1, 'Invalid count.');
1170 $this->assertEquals(count($taxItems), 1, 'Invalid count.');
1171 foreach ($taxItems as $value) {
1172 $this->assertEquals($value['amount'], 10, 'Invalid tax amount.');
1173 }
1174 }
1175
2a4a2f00
PN
1176 /**
1177 * Test for function createProportionalFinancialEntries().
1178 */
1179 public function testcreateProportionalFinancialEntries() {
1180 list($contribution, $financialAccount) = $this->createContributionWithTax();
1181 $params = array(
3137781d 1182 'total_amount' => 50,
2a4a2f00
PN
1183 'to_financial_account_id' => $financialAccount->financial_account_id,
1184 'payment_instrument_id' => 1,
1185 'trxn_date' => date('Ymd'),
1186 'status_id' => 1,
2a4a2f00 1187 'entity_id' => $contribution['id'],
2a4a2f00 1188 );
3137781d 1189 $financialTrxn = $this->callAPISuccess('FinancialTrxn', 'create', $params);
2a4a2f00
PN
1190 $entityParams = array(
1191 'contribution_total_amount' => $contribution['total_amount'],
1192 'trxn_total_amount' => 55,
1193 'trxn_id' => $financialTrxn['id'],
1194 );
1195 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contribution['id']);
1196 list($ftIds, $taxItems) = CRM_Contribute_BAO_Contribution::getLastFinancialItemIds($contribution['id']);
1197 CRM_Contribute_BAO_Contribution::createProportionalFinancialEntries($entityParams, $lineItems, $ftIds, $taxItems);
1198 $eftParams = array(
1199 'entity_table' => 'civicrm_financial_item',
1200 'financial_trxn_id' => $financialTrxn['id'],
1201 );
1202 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'Get', $eftParams);
1203 $this->assertEquals($entityFinancialTrxn['count'], 2, 'Invalid count.');
1204 $testAmount = array(5, 50);
1205 foreach ($entityFinancialTrxn['values'] as $value) {
1206 $this->assertEquals($value['amount'], array_pop($testAmount), 'Invalid amount stored in civicrm_entity_financial_trxn.');
77641de4
PN
1207 }
1208 }
1209
1210 /**
1211 * Test to check if amount is proportionally asigned for PI change.
1212 */
1213 public function testProportionallyAssignedForPIChange() {
1214 list($contribution, $financialAccount) = $this->createContributionWithTax();
1215 $params = array(
1216 'id' => $contribution['id'],
1217 'payment_instrument_id' => 3,
1218 );
1219 $this->callAPISuccess('Contribution', 'create', $params);
1220 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
1221 $eftParams = array(
1222 'entity_table' => 'civicrm_financial_item',
1223 'financial_trxn_id' => $lastFinancialTrxnId['financialTrxnId'],
1224 );
1225 $entityFinancialTrxn = $this->callAPISuccess('EntityFinancialTrxn', 'Get', $eftParams);
1226 $this->assertEquals($entityFinancialTrxn['count'], 2, 'Invalid count.');
1227 $testAmount = array(10, 100);
1228 foreach ($entityFinancialTrxn['values'] as $value) {
1229 $this->assertEquals($value['amount'], array_pop($testAmount), 'Invalid amount stored in civicrm_entity_financial_trxn.');
2a4a2f00
PN
1230 }
1231 }
1232
646bc565
PN
1233 /**
1234 * Function to create contribution with tax.
1235 */
c364c544
MW
1236 public function createContributionWithTax($params = array()) {
1237 if (!isset($params['total_amount'])) {
1238 $params['total_amount'] = 100;
1239 }
646bc565
PN
1240 $contactId = $this->individualCreate();
1241 $this->enableTaxAndInvoicing();
1242 $financialType = $this->createFinancialType();
1243 $financialAccount = $this->relationForFinancialTypeWithFinancialAccount($financialType['id']);
1244 $form = new CRM_Contribute_Form_Contribution();
1245
1246 $form->testSubmit(array(
c364c544 1247 'total_amount' => $params['total_amount'],
646bc565 1248 'financial_type_id' => $financialType['id'],
646bc565
PN
1249 'contact_id' => $contactId,
1250 'contribution_status_id' => 1,
1251 'price_set_id' => 0,
1252 ),
1253 CRM_Core_Action::ADD
1254 );
1255 $contribution = $this->callAPISuccessGetSingle('Contribution',
1256 array(
1257 'contact_id' => $contactId,
1258 'return' => array('tax_amount', 'total_amount'),
1259 )
1260 );
2a4a2f00 1261 return array($contribution, $financialAccount);
646bc565
PN
1262 }
1263
75c07fde
JP
1264 /**
1265 * Test processOnBehalfOrganization() function.
1266 */
1267 public function testProcessOnBehalfOrganization() {
1268 $orgInfo = array(
1269 'phone' => '11111111',
1270 'email' => 'testorg@gmail.com',
1271 'street_address' => 'test Street',
1272 'city' => 'test City',
1273 'state_province' => 'AA',
1274 'postal_code' => '222222',
1275 'country' => 'United States',
1276 );
1277 $contactID = $this->individualCreate();
1278 $orgId = $this->organizationCreate(array('organization_name' => 'testorg1'));
1279 $orgCount = $this->callAPISuccessGetCount('Contact', array(
1280 'contact_type' => "Organization",
1281 'organization_name' => "testorg1",
1282 ));
1283 $this->assertEquals($orgCount, 1);
1284
1285 $values = $params = array();
1286 $behalfOrganization = array(
1287 'organization_name' => 'testorg1',
1288 'phone' => array(
1289 1 => array(
1290 'phone' => $orgInfo['phone'],
1291 'is_primary' => 1,
1292 ),
1293 ),
1294 'email' => array(
1295 1 => array(
1296 'email' => $orgInfo['email'],
1297 'is_primary' => 1,
1298 ),
1299 ),
1300 'address' => array(
1301 3 => array(
1302 'street_address' => $orgInfo['street_address'],
1303 'city' => $orgInfo['city'],
1304 'location_type_id' => 3,
1305 'postal_code' => $orgInfo['postal_code'],
1306 'country' => 'US',
1307 'state_province' => 'AA',
1308 'is_primary' => 1,
1309 ),
1310 ),
1311 );
1312 $fields = array(
1313 'organization_name' => 1,
1314 'phone-3-1' => 1,
1315 'email-3' => 1,
1316 'street_address-3' => 1,
1317 'city-3' => 1,
1318 'postal_code-3' => 1,
1319 'country-3' => 1,
1320 'state_province-3' => 1,
1321 );
1322 CRM_Contribute_Form_Contribution_Confirm::processOnBehalfOrganization($behalfOrganization, $contactID, $values, $params, $fields);
1323
1324 //Check whether new organisation is not created.
1325 $result = $this->callAPISuccess('Contact', 'get', array(
1326 'contact_type' => "Organization",
1327 'organization_name' => "testorg1",
1328 ));
1329 $this->assertEquals($result['count'], 1);
1330
1331 //Assert all org values are updated.
1332 foreach ($orgInfo as $key => $val) {
1333 $this->assertEquals($result['values'][$orgId][$key], $val);
1334 }
1335
1336 //Check if alert is assigned to params if more than 1 dupe exists.
1337 $orgId = $this->organizationCreate(array('organization_name' => 'testorg1', 'email' => 'testorg@gmail.com'));
1338 CRM_Contribute_Form_Contribution_Confirm::processOnBehalfOrganization($behalfOrganization, $contactID, $values, $params, $fields);
1339 $this->assertEquals($params['onbehalf_dupe_alert'], 1);
1340 }
1341
7e2ec997
E
1342 /**
1343 * Test for replaceContributionTokens.
1344 * This function tests whether the contribution tokens are replaced with values from contribution.
1345 */
1346 public function testReplaceContributionTokens() {
1347 $contactId1 = $this->individualCreate();
1348 $params = array(
1349 'contact_id' => $contactId1,
1350 'receive_date' => '20120511',
1351 'total_amount' => 100.00,
1352 'financial_type_id' => 1,
1353 'trxn_id' => 12345,
1354 'invoice_id' => 67890,
1355 'source' => 'SSF',
1356 'contribution_status_id' => 2,
1357 );
1358 $contribution1 = $this->contributionCreate($params);
1359 $contactId2 = $this->individualCreate();
1360 $params = array(
1361 'contact_id' => $contactId2,
1362 'receive_date' => '20150511',
1363 'total_amount' => 200.00,
1364 'financial_type_id' => 1,
1365 'trxn_id' => 6789,
1366 'invoice_id' => 12345,
1367 'source' => 'ABC',
1368 'contribution_status_id' => 1,
1369 );
1370 $contribution2 = $this->contributionCreate($params);
1371 $ids = array($contribution1, $contribution2);
1372
1373 $subject = "This is a test for contribution ID: {contribution.contribution_id}";
1374 $text = "Contribution Amount: {contribution.total_amount}";
1375 $html = "<p>Contribution Source: {contribution.contribution_source}</p></br>
1376 <p>Contribution Invoice ID: {contribution.invoice_id}</p></br>
1377 <p>Contribution Receive Date: {contribution.receive_date}</p></br>";
1378
1379 $subjectToken = CRM_Utils_Token::getTokens($subject);
1380 $messageToken = CRM_Utils_Token::getTokens($text);
1381 $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html));
1382
1383 $contributionDetails = CRM_Contribute_BAO_Contribution::replaceContributionTokens(
1384 $ids,
1385 $subject,
1386 $subjectToken,
1387 $text,
1388 $html,
1389 $messageToken,
1390 TRUE
1391 );
1392
1393 $this->assertEquals("Contribution Amount: $ 100.00", $contributionDetails[$contactId1]['text'], "The text does not match");
1394 $this->assertEquals("<p>Contribution Source: ABC</p></br>
1395 <p>Contribution Invoice ID: 12345</p></br>
1396 <p>Contribution Receive Date: May 11th, 2015</p></br>", $contributionDetails[$contactId2]['html'], "The html does not match");
1397 }
1398
7b5169d0
PN
1399 /**
1400 * Test for contribution with deferred revenue.
1401 */
1402 public function testContributionWithDeferredRevenue() {
1403 $contactId = $this->individualCreate();
1404 Civi::settings()->set('deferred_revenue_enabled', TRUE);
1405 $params = array(
1406 'contact_id' => $contactId,
1407 'receive_date' => '20120511',
1408 'total_amount' => 100.00,
1409 'financial_type_id' => 'Event Fee',
1410 'trxn_id' => 12345,
1411 'invoice_id' => 67890,
1412 'source' => 'SSF',
1413 'contribution_status_id' => 'Completed',
1414 'revenue_recognition_date' => date('Ymd', strtotime("+3 month")),
1415 );
1416 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1417
1418 $this->callAPISuccessGetCount('EntityFinancialTrxn', array(
1419 'entity_table' => "civicrm_contribution",
1420 'entity_id' => $contribution['id'],
1421 ), 2);
1422
1423 $checkAgainst = array(
1424 'financial_trxn_id.to_financial_account_id.name' => 'Deferred Revenue - Event Fee',
1425 'financial_trxn_id.from_financial_account_id.name' => 'Event Fee',
f818aed5 1426 'financial_trxn_id' => '2',
7b5169d0
PN
1427 );
1428 $result = $this->callAPISuccessGetSingle('EntityFinancialTrxn', array(
1429 'return' => array(
1430 "financial_trxn_id.from_financial_account_id.name",
1431 "financial_trxn_id.to_financial_account_id.name",
1432 "financial_trxn_id",
1433 ),
1434 'entity_table' => "civicrm_contribution",
1435 'entity_id' => $contribution['id'],
1436 'financial_trxn_id.is_payment' => 0,
1437 ), $checkAgainst);
1438
1439 $result = $this->callAPISuccessGetSingle('EntityFinancialTrxn', array(
1440 'entity_table' => "civicrm_financial_item",
1441 'financial_trxn_id' => $result['financial_trxn_id'],
1442 'return' => array('entity_id'),
1443 ));
1444
1445 $checkAgainst = array(
1446 'financial_account_id.name' => 'Deferred Revenue - Event Fee',
1447 'id' => $result['entity_id'],
1448 );
1449 $result = $this->callAPISuccessGetSingle('FinancialItem', array(
1450 'id' => $result['entity_id'],
1451 'return' => array("financial_account_id.name"),
1452 ), $checkAgainst);
1453 }
1454
1db3ddea
KE
1455 /**
1456 * CRM-21424 Check if the receipt update is set after composing the receipt message
1457 */
1458 public function testSendMailUpdateReceiptDate() {
1459 $ids = $values = array();
1460 $contactId = $this->individualCreate();
1461 $params = array(
1462 'contact_id' => $contactId,
1463 'receive_date' => '20120511',
1464 'total_amount' => 100.00,
1465 'financial_type_id' => 'Donation',
1466 'source' => 'SSF',
1467 'contribution_status_id' => 'Completed',
1468 );
1469 /* first test the scenario when sending an email */
1470 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1471 $contributionId = $contribution['id'];
1472 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After creating receipt date must be null');
1473 $input = array('receipt_update' => 0);
1474 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $contributionId, $values);
1475 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail, with the explicit instruction not to update receipt date stays null');
1476 $input = array('receipt_update' => 1);
1477 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $contributionId, $values);
1478 $this->assertDBNotNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail with the permission to allow update receipt date must be set');
1479
1480 /* repeat the same scenario for downloading a pdf */
1481 $contribution = $this->callAPISuccess('contribution', 'create', $params);
1482 $contributionId = $contribution['id'];
1483 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After creating receipt date must be null');
1484 $input = array('receipt_update' => 0);
1485 /* setting the lasast parameter (returnmessagetext) to TRUE is done by the download of the pdf */
1486 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $contributionId, $values, TRUE);
1487 $this->assertDBNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail, with the explicit instruction not to update receipt date stays null');
1488 $input = array('receipt_update' => 1);
1489 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $contributionId, $values, TRUE);
1490 $this->assertDBNotNull('CRM_Contribute_BAO_Contribution', $contributionId, 'receipt_date', 'id', 'After sendMail with the permission to allow update receipt date must be set');
1491 }
1492
6a488035 1493}