Merge pull request #15248 from MegaphoneJon/reporting-19
[civicrm-core.git] / tests / phpunit / api / v3 / PaymentTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Test APIv3 civicrm_contribute_* functions
30 *
31 * @package CiviCRM_APIv3
32 * @subpackage API_Contribution
33 * @group headless
34 */
35 class api_v3_PaymentTest extends CiviUnitTestCase {
36
37 protected $_individualId;
38
39 protected $_financialTypeId = 1;
40
41 /**
42 * Setup function.
43 *
44 * @throws \CRM_Core_Exception
45 */
46 public function setUp() {
47 parent::setUp();
48
49 $this->_apiversion = 3;
50 $this->_individualId = $this->individualCreate();
51 CRM_Core_Config::singleton()->userPermissionClass->permissions = [];
52 }
53
54 /**
55 * Clean up after each test.
56 *
57 * @throws \Exception
58 */
59 public function tearDown() {
60 $this->quickCleanUpFinancialEntities();
61 $this->quickCleanup(['civicrm_uf_match']);
62 unset(CRM_Core_Config::singleton()->userPermissionClass->permissions);
63 parent::tearDown();
64 }
65
66 /**
67 * Test Get Payment api.
68 *
69 * @throws \CRM_Core_Exception
70 */
71 public function testGetPayment() {
72 $p = [
73 'contact_id' => $this->_individualId,
74 'receive_date' => '2010-01-20',
75 'total_amount' => 100.00,
76 'financial_type_id' => $this->_financialTypeId,
77 'trxn_id' => 23456,
78 'contribution_status_id' => 1,
79 ];
80 $contribution = $this->callAPISuccess('contribution', 'create', $p);
81
82 $params = [
83 'contribution_id' => $contribution['id'],
84 'check_permissions' => TRUE,
85 ];
86 CRM_Core_Config::singleton()->userPermissionClass->permissions = ['access CiviCRM', 'administer CiviCRM'];
87 $payment = $this->callAPIFailure('payment', 'get', $params, 'API permission check failed for Payment/get call; insufficient permission: require access CiviCRM and access CiviContribute');
88
89 array_push(CRM_Core_Config::singleton()->userPermissionClass->permissions, 'access CiviContribute');
90 $payment = $this->callAPISuccess('payment', 'get', $params);
91
92 $payment = $this->callAPIAndDocument('payment', 'get', $params, __FUNCTION__, __FILE__);
93 $this->assertEquals(1, $payment['count']);
94
95 $expectedResult = [
96 $contribution['id'] => [
97 'total_amount' => 100,
98 'trxn_id' => 23456,
99 'trxn_date' => '2010-01-20 00:00:00',
100 'contribution_id' => $contribution['id'],
101 'is_payment' => 1,
102 ],
103 ];
104 $this->checkPaymentResult($payment, $expectedResult);
105 $this->callAPISuccess('Contribution', 'Delete', [
106 'id' => $contribution['id'],
107 ]);
108 $this->validateAllPayments();
109 }
110
111 /**
112 * Retrieve Payment using trxn_id.
113 *
114 * @throws \CRM_Core_Exception
115 */
116 public function testGetPaymentWithTrxnID() {
117 $this->_individualId2 = $this->individualCreate();
118 $params1 = [
119 'contact_id' => $this->_individualId,
120 'trxn_id' => 111111,
121 'total_amount' => 10,
122 ];
123 $contributionID1 = $this->contributionCreate($params1);
124
125 $params2 = [
126 'contact_id' => $this->_individualId2,
127 'trxn_id' => 222222,
128 'total_amount' => 20,
129 ];
130 $contributionID2 = $this->contributionCreate($params2);
131
132 $paymentParams = ['trxn_id' => 111111];
133 $payment = $this->callAPISuccess('payment', 'get', $paymentParams);
134 $expectedResult = [
135 $payment['id'] => [
136 'total_amount' => 10,
137 'trxn_id' => 111111,
138 'status_id' => 1,
139 'is_payment' => 1,
140 'contribution_id' => $contributionID1,
141 ],
142 ];
143 $this->checkPaymentResult($payment, $expectedResult);
144
145 $paymentParams = ['trxn_id' => 222222];
146 $payment = $this->callAPISuccess('payment', 'get', $paymentParams);
147 $expectedResult = [
148 $payment['id'] => [
149 'total_amount' => 20,
150 'trxn_id' => 222222,
151 'status_id' => 1,
152 'is_payment' => 1,
153 'contribution_id' => $contributionID2,
154 ],
155 ];
156 $this->checkPaymentResult($payment, $expectedResult);
157 $this->validateAllPayments();
158 }
159
160 /**
161 * Test email receipt for partial payment.
162 *
163 * @throws \CRM_Core_Exception
164 */
165 public function testPaymentEmailReceipt() {
166 $mut = new CiviMailUtils($this);
167 $contribution = $this->createPartiallyPaidParticipantOrder();
168 $event = $this->callAPISuccess('Event', 'get', []);
169 $this->addLocationToEvent($event['id']);
170 $params = [
171 'contribution_id' => $contribution['id'],
172 'total_amount' => 50,
173 'check_number' => '345',
174 'trxn_date' => '2018-08-13 17:57:56',
175 ];
176 $payment = $this->callAPISuccess('payment', 'create', $params);
177 $this->checkPaymentResult($payment, [
178 $payment['id'] => [
179 'from_financial_account_id' => 7,
180 'to_financial_account_id' => 6,
181 'total_amount' => 50,
182 'status_id' => 1,
183 'is_payment' => 1,
184 ],
185 ]);
186
187 $this->callAPISuccess('Payment', 'sendconfirmation', ['id' => $payment['id']]);
188 $mut->assertSubjects(['Payment Receipt - Annual CiviCRM meet - Mr. Anthony Anderson II']);
189 $mut->checkMailLog([
190 'From: "FIXME" <info@EXAMPLE.ORG>',
191 'Dear Anthony,',
192 'Total Fee: $ 300.00',
193 'This Payment Amount: $ 50.00',
194 //150 was paid in the 1st payment.
195 'Balance Owed: $ 100.00',
196 'Event Information and Location',
197 'Paid By: Check',
198 'Check Number: 345',
199 'Transaction Date: August 13th, 2018 5:57 PM',
200 'event place',
201 'streety street',
202 ]);
203 $mut->stop();
204 $mut->clearMessages();
205 $this->validateAllPayments();
206 }
207
208 /**
209 * Test email receipt for partial payment.
210 *
211 * @throws \CRM_Core_Exception
212 */
213 public function testPaymentEmailReceiptFullyPaid() {
214 $mut = new CiviMailUtils($this);
215 CRM_Core_Config::singleton()->userPermissionClass->permissions = ['access CiviContribute', 'edit contributions', 'access CiviCRM'];
216 $contribution = $this->createPartiallyPaidParticipantOrder();
217
218 $params = [
219 'contribution_id' => $contribution['id'],
220 'total_amount' => 150,
221 ];
222 $payment = $this->callAPISuccess('payment', 'create', $params);
223
224 // Here we set the email to an invalid email & use check_permissions, domain email should be used.
225 $email = $this->callAPISuccess('Email', 'create', ['contact_id' => 1, 'email' => 'bob@example.com']);
226 $this->callAPISuccess('Payment', 'sendconfirmation', ['id' => $payment['id'], 'from' => $email['id'], 'check_permissions' => 1]);
227 $mut->assertSubjects(['Payment Receipt - Annual CiviCRM meet - Mr. Anthony Anderson II', 'Registration Confirmation - Annual CiviCRM meet - Mr. Anthony Anderson II']);
228 $mut->checkMailLog([
229 'From: "FIXME" <info@EXAMPLE.ORG>',
230 'Dear Anthony,',
231 'Below you will find a receipt for this payment.',
232 'Total Fee: $ 300.00',
233 'This Payment Amount: $ 150.00',
234 'Balance Owed: $ 0.00',
235 'Thank you for completing this payment.',
236 ]);
237 $mut->stop();
238 $mut->clearMessages();
239 $this->validateAllPayments();
240 }
241
242 /**
243 * Test email receipt for partial payment.
244 *
245 * @dataProvider getThousandSeparators
246 *
247 * @param string $thousandSeparator
248 *
249 * @throws \CRM_Core_Exception
250 */
251 public function testRefundEmailReceipt($thousandSeparator) {
252 $this->setCurrencySeparators($thousandSeparator);
253 $decimalSeparator = ($thousandSeparator === ',' ? '.' : ',');
254 $mut = new CiviMailUtils($this);
255 $contribution = $this->createPartiallyPaidParticipantOrder();
256 $this->callAPISuccess('payment', 'create', [
257 'contribution_id' => $contribution['id'],
258 'total_amount' => 50,
259 'check_number' => '345',
260 'trxn_date' => '2018-08-13 17:57:56',
261 ]);
262
263 $payment = $this->callAPISuccess('payment', 'create', [
264 'contribution_id' => $contribution['id'],
265 'total_amount' => -30,
266 'trxn_date' => '2018-11-13 12:01:56',
267 'sequential' => TRUE,
268 ])['values'][0];
269
270 $expected = [
271 'from_financial_account_id' => 7,
272 'to_financial_account_id' => 6,
273 'total_amount' => -30,
274 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_FinancialTrxn', 'status_id', 'Refunded'),
275 'is_payment' => 1,
276 ];
277 foreach ($expected as $key => $value) {
278 $this->assertEquals($expected[$key], $payment[$key], 'mismatch on key ' . $key);
279 }
280
281 $this->callAPISuccess('Payment', 'sendconfirmation', ['id' => $payment['id']]);
282 $mut->assertSubjects(['Refund Notification - Annual CiviCRM meet - Mr. Anthony Anderson II']);
283 $mut->checkMailLog([
284 'Dear Anthony,',
285 'A refund has been issued based on changes in your registration selections.',
286 'Total Fee: $ 300' . $decimalSeparator . '00',
287 'Refund Amount: $ -30' . $decimalSeparator . '00',
288 'Event Information and Location',
289 'Paid By: Check',
290 'Transaction Date: November 13th, 2018 12:01 PM',
291 'Total Paid: $ 170' . $decimalSeparator . '00',
292 ]);
293 $mut->stop();
294 $mut->clearMessages();
295 $this->validateAllPayments();
296 }
297
298 /**
299 * Test adding a payment to a pending multi-line order.
300 *
301 * @throws \CRM_Core_Exception
302 */
303 public function testCreatePaymentPendingOrderNoLineItems() {
304 $order = $this->createPendingParticipantOrder();
305 $this->callAPISuccess('Payment', 'create', [
306 'order_id' => $order['id'],
307 'total_amount' => 50,
308 ]);
309 $this->validateAllPayments();
310 }
311
312 /**
313 * Test that Payment.create does not fail if the line items are missing.
314 *
315 * In the original spec it was anticipated that financial items would not be created
316 * for pending contributions in some circumstances. We've backed away from this and
317 * I mostly could not find a way to do it through the UI. But I did seem to once &
318 * I want to be sure that if they ARE missing no fatal occurs so this tests
319 * that in an artificial way.
320 *
321 * @throws \CRM_Core_Exception
322 */
323 public function testAddPaymentMissingFinancialItems() {
324 $contribution = $this->callAPISuccess('Contribution', 'create', [
325 'total_amount' => 50,
326 'financial_type_id' => 'Donation',
327 'contact_id' => $this->individualCreate(),
328 'contribution_status_id' => 'Pending',
329 ]);
330 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_financial_item');
331 $this->callAPISuccess('Payment', 'create', ['contribution_id' => $contribution['id'], 'payment_instrument_id' => 'Check', 'total_amount' => 5]);
332 $this->validateAllPayments();
333 }
334
335 /**
336 * Add participant with contribution
337 *
338 * @return array
339 *
340 * @throws \CRM_Core_Exception
341 */
342 protected function createPendingParticipantOrder() {
343 return $this->callAPISuccess('Order', 'create', $this->getParticipantOrderParams());
344 }
345
346 /**
347 * Test create payment api with no line item in params
348 *
349 * @throws \CRM_Core_Exception
350 */
351 public function testCreatePaymentNoLineItems() {
352 $contribution = $this->createPartiallyPaidParticipantOrder();
353
354 //Create partial payment
355 $params = [
356 'contribution_id' => $contribution['id'],
357 'total_amount' => 50,
358 ];
359 $payment = $this->callAPIAndDocument('payment', 'create', $params, __FUNCTION__, __FILE__);
360 $this->checkPaymentIsValid($payment['id'], $contribution['id']);
361
362 $params = [
363 'entity_table' => 'civicrm_financial_item',
364 'financial_trxn_id' => $payment['id'],
365 ];
366 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
367 $amounts = [33.33, 16.67];
368 foreach ($eft['values'] as $value) {
369 $this->assertEquals($value['amount'], array_pop($amounts));
370 }
371
372 // Now create payment to complete total amount of contribution
373 $params = [
374 'contribution_id' => $contribution['id'],
375 'total_amount' => 100,
376 ];
377 $payment = $this->callAPISuccess('payment', 'create', $params);
378 $expectedResult = [
379 $payment['id'] => [
380 'from_financial_account_id' => 7,
381 'to_financial_account_id' => 6,
382 'total_amount' => 100,
383 'status_id' => 1,
384 'is_payment' => 1,
385 ],
386 ];
387 $this->checkPaymentResult($payment, $expectedResult);
388 $params = [
389 'entity_table' => 'civicrm_financial_item',
390 'financial_trxn_id' => $payment['id'],
391 ];
392 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
393 $amounts = [66.67, 33.33];
394 foreach ($eft['values'] as $value) {
395 $this->assertEquals($value['amount'], array_pop($amounts));
396 }
397 // Check contribution for completed status
398 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id']]);
399
400 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Completed');
401 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 300.00);
402 $paymentParticipant = [
403 'contribution_id' => $contribution['id'],
404 ];
405 $participantPayment = $this->callAPISuccess('ParticipantPayment', 'getsingle', $paymentParticipant);
406 $participant = $this->callAPISuccess('participant', 'get', ['id' => $participantPayment['participant_id']]);
407 $this->assertEquals($participant['values'][$participant['id']]['participant_status'], 'Registered');
408 $this->callAPISuccess('Contribution', 'Delete', [
409 'id' => $contribution['id'],
410 ]);
411 $this->validateAllPayments();
412 }
413
414 /**
415 * Function to assert db values
416 *
417 * @throws \CRM_Core_Exception
418 */
419 public function checkPaymentResult($payment, $expectedResult) {
420 $refreshedPayment = $this->callAPISuccessGetSingle('Payment', ['financial_trxn_id' => $payment['id']]);
421 foreach ($expectedResult[$payment['id']] as $key => $value) {
422 $this->assertEquals($refreshedPayment[$key], $value, 'mismatch on ' . $key); $this->assertEquals($refreshedPayment[$key], $value, 'mismatch on ' . $key);
423 }
424 }
425
426 /**
427 * Test create payment api with line item in params
428 *
429 * @throws \CRM_Core_Exception
430 */
431 public function testCreatePaymentLineItems() {
432 $contribution = $this->createPartiallyPaidParticipantOrder();
433 $lineItems = $this->callAPISuccess('LineItem', 'get', ['contribution_id' => $contribution['id']])['values'];
434
435 // Create partial payment by passing line item array is params.
436 $params = [
437 'contribution_id' => $contribution['id'],
438 'total_amount' => 50,
439 ];
440 $amounts = [40, 10];
441 foreach ($lineItems as $id => $ignore) {
442 $params['line_item'][] = [$id => array_pop($amounts)];
443 }
444 $payment = $this->callAPIAndDocument('Payment', 'create', $params, __FUNCTION__, __FILE__, 'Payment with line item', 'CreatePaymentWithLineItems');
445 $this->checkPaymentIsValid($payment['id'], $contribution['id']);
446
447 $params = [
448 'entity_table' => 'civicrm_financial_item',
449 'financial_trxn_id' => $payment['id'],
450 'return' => ['entity_id.entity_id', 'amount'],
451 ];
452 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params)['values'];
453 $this->assertCount(2, $eft);
454 $amounts = [40, 10];
455 foreach ($eft as $value) {
456 $this->assertEquals($value['amount'], array_pop($amounts));
457 }
458
459 // Now create payment to complete total amount of contribution
460 $params = [
461 'contribution_id' => $contribution['id'],
462 'total_amount' => 100,
463 ];
464 $amounts = [80, 20];
465 foreach ($lineItems as $id => $ignore) {
466 $params['line_item'][] = [$id => array_pop($amounts)];
467 }
468 $payment = $this->callAPISuccess('Payment', 'create', $params);
469 $expectedResult = [
470 $payment['id'] => [
471 'from_financial_account_id' => 7,
472 'to_financial_account_id' => 6,
473 'total_amount' => 100,
474 'status_id' => 1,
475 'is_payment' => 1,
476 ],
477 ];
478 $this->checkPaymentResult($payment, $expectedResult);
479 $params = [
480 'entity_table' => 'civicrm_financial_item',
481 'financial_trxn_id' => $payment['id'],
482 ];
483 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params)['values'];
484 $this->assertCount(2, $eft);
485 $amounts = [80, 20];
486 foreach ($eft as $value) {
487 $this->assertEquals($value['amount'], array_pop($amounts));
488 }
489 // Check contribution for completed status
490 $contribution = $this->callAPISuccess('Contribution', 'get', ['id' => $contribution['id']]);
491
492 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Completed');
493 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 300.00);
494 $paymentParticipant = [
495 'contribution_id' => $contribution['id'],
496 ];
497 $participantPayment = $this->callAPISuccess('ParticipantPayment', 'getsingle', $paymentParticipant);
498 $participant = $this->callAPISuccess('participant', 'get', ['id' => $participantPayment['participant_id']]);
499 $this->assertEquals($participant['values'][$participant['id']]['participant_status'], 'Registered');
500 $this->validateAllPayments();
501 }
502
503 /**
504 * Test cancel payment api
505 *
506 * @throws \CRM_Core_Exception
507 */
508 public function testCancelPayment() {
509 CRM_Core_Config::singleton()->userPermissionClass->permissions = ['administer CiviCRM', 'access CiviContribute'];
510 $contribution = $this->createPartiallyPaidParticipantOrder();
511
512 $params = [
513 'contribution_id' => $contribution['id'],
514 ];
515
516 $payment = $this->callAPISuccess('payment', 'get', $params);
517 $this->assertEquals(1, $payment['count']);
518
519 $cancelParams = [
520 'id' => $payment['id'],
521 'check_permissions' => TRUE,
522 ];
523 $payment = $this->callAPIFailure('payment', 'cancel', $cancelParams, 'API permission check failed for Payment/cancel call; insufficient permission: require access CiviCRM and access CiviContribute and edit contributions');
524
525 array_push(CRM_Core_Config::singleton()->userPermissionClass->permissions, 'access CiviCRM', 'edit contributions');
526
527 $this->callAPIAndDocument('payment', 'cancel', $cancelParams, __FUNCTION__, __FILE__);
528
529 $payment = $this->callAPISuccess('payment', 'get', $params);
530 $this->assertEquals(2, $payment['count']);
531 $amounts = [-150.00, 150.00];
532 foreach ($payment['values'] as $value) {
533 $this->assertEquals($value['total_amount'], array_pop($amounts), 'Mismatch total amount');
534 }
535
536 $this->callAPISuccess('Contribution', 'Delete', [
537 'id' => $contribution['id'],
538 ]);
539 $this->validateAllPayments();
540 }
541
542 /**
543 * Test delete payment api
544 *
545 * @throws \CRM_Core_Exception
546 */
547 public function testDeletePayment() {
548 CRM_Core_Config::singleton()->userPermissionClass->permissions = ['administer CiviCRM', 'access CiviContribute'];
549 $contribution = $this->createPartiallyPaidParticipantOrder();
550
551 $params = [
552 'contribution_id' => $contribution['id'],
553 ];
554
555 $payment = $this->callAPISuccess('payment', 'get', $params);
556 $this->assertEquals(1, $payment['count']);
557
558 $deleteParams = [
559 'id' => $payment['id'],
560 'check_permissions' => TRUE,
561 ];
562 $payment = $this->callAPIFailure('payment', 'delete', $deleteParams, 'API permission check failed for Payment/delete call; insufficient permission: require access CiviCRM and access CiviContribute and delete in CiviContribute');
563
564 array_push(CRM_Core_Config::singleton()->userPermissionClass->permissions, 'access CiviCRM', 'delete in CiviContribute');
565 $this->callAPIAndDocument('payment', 'delete', $deleteParams, __FUNCTION__, __FILE__);
566
567 $payment = $this->callAPISuccess('payment', 'get', $params);
568 $this->assertEquals(0, $payment['count']);
569
570 $this->callAPISuccess('Contribution', 'Delete', [
571 'id' => $contribution['id'],
572 ]);
573 }
574
575 /**
576 * Test update payment api.
577 *
578 * 1) create a contribution for $300 with a partial payment of $150
579 * - this results in 2 financial transactions. The accounts receivable transaction is linked
580 * via entity_financial_trxns to the 2 line items. The $150 payment is not linked to the line items
581 * so the line items are fully allocated even though they are only half paid.
582 *
583 * 2) add a payment of $50 -
584 * This payment transaction IS linked to the line items so $350 of the $300 in line items is allocated
585 * but $200 is paid
586 *
587 * 3) update that payment to be $100
588 * This results in a negative and a positive payment ($50 & $100) - the negative payment results in
589 * financial_items but the positive payment does not.
590 *
591 * The final result is we have
592 * - 1 partly paid contribution of $300
593 * - payment financial_trxns totalling $250
594 * - 1 Accounts receivable financial_trxn totalling $300
595 * - 2 financial items totalling $300 linked to the Accounts receivable financial_trxn
596 * - 6 entries in the civicrm_entity_financial_trxn linked to line items - totalling $450.
597 * - 5 entries in the civicrm_entity_financial_trxn linked to contributions - totalling $550.
598 *
599 * @throws \CRM_Core_Exception
600 */
601 public function testUpdatePayment() {
602 CRM_Core_Config::singleton()->userPermissionClass->permissions = ['administer CiviCRM', 'access CiviContribute', 'edit contributions'];
603 $contribution = $this->createPartiallyPaidParticipantOrder();
604
605 //Create partial payment by passing line item array is params
606 $params = [
607 'contribution_id' => $contribution['id'],
608 'total_amount' => 50,
609 ];
610
611 $payment = $this->callAPISuccess('payment', 'create', $params);
612 $expectedResult = [
613 $payment['id'] => [
614 'from_financial_account_id' => 7,
615 'to_financial_account_id' => 6,
616 'total_amount' => 50,
617 'status_id' => 1,
618 'is_payment' => 1,
619 ],
620 ];
621 $this->checkPaymentResult($payment, $expectedResult);
622
623 $params = [
624 'entity_table' => 'civicrm_financial_item',
625 'financial_trxn_id' => $payment['id'],
626 ];
627 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
628 $amounts = [33.33, 16.67];
629 foreach ($eft['values'] as $value) {
630 $this->assertEquals($value['amount'], array_pop($amounts));
631 }
632
633 // update the amount for payment
634 $params = [
635 'contribution_id' => $contribution['id'],
636 'total_amount' => 100,
637 'id' => $payment['id'],
638 'check_permissions' => TRUE,
639 ];
640 // @todo - move this permissions test to it's own test - it just confuses here.
641 CRM_Core_Config::singleton()->userPermissionClass->permissions = ['administer CiviCRM', 'access CiviContribute'];
642 $this->callAPIFailure('payment', 'create', $params, 'API permission check failed for Payment/create call; insufficient permission: require access CiviCRM and access CiviContribute and edit contributions');
643
644 CRM_Core_Config::singleton()->userPermissionClass->permissions = ['administer CiviCRM', 'access CiviContribute', 'access CiviCRM', 'edit contributions'];
645 $payment = $this->callAPIAndDocument('payment', 'create', $params, __FUNCTION__, __FILE__, 'Update Payment', 'UpdatePayment');
646
647 $this->validateAllPayments();
648 // Check for proportional cancelled payment against lineitems.
649 $minParams = [
650 'entity_table' => 'civicrm_financial_item',
651 'financial_trxn_id' => $payment['id'] - 1,
652 ];
653
654 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $minParams)['values'];
655 $this->assertCount(2, $eft);
656 $amounts = [-33.33, -16.67];
657
658 foreach ($eft as $value) {
659 $this->assertEquals($value['amount'], array_pop($amounts));
660 }
661
662 // Check for proportional updated payment against lineitems.
663 $params = [
664 'entity_table' => 'civicrm_financial_item',
665 'financial_trxn_id' => $payment['id'],
666 ];
667 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params)['values'];
668 $amounts = [66.67, 33.33];
669 foreach ($eft as $value) {
670 $this->assertEquals($value['amount'], array_pop($amounts));
671 }
672 $items = $this->callAPISuccess('FinancialItem', 'get', [])['values'];
673 $this->assertCount(2, $items);
674 $itemSum = 0;
675 foreach ($items as $item) {
676 $this->assertEquals('civicrm_line_item', $item['entity_table']);
677 $itemSum += $item['amount'];
678 }
679 $this->assertEquals(300, $itemSum);
680
681 $params = [
682 'contribution_id' => $contribution['id'],
683 ];
684 $payment = $this->callAPISuccess('payment', 'get', $params);
685 $amounts = [100.00, -50.00, 50.00, 150.00];
686 foreach ($payment['values'] as $value) {
687 $amount = array_pop($amounts);
688 $this->assertEquals($value['total_amount'], $amount, 'Mismatch total amount');
689
690 // Check entity financial trxn created properly
691 $params = [
692 'entity_id' => $contribution['id'],
693 'entity_table' => 'civicrm_contribution',
694 'financial_trxn_id' => $value['id'],
695 ];
696 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
697 $this->assertEquals($eft['values'][$eft['id']]['amount'], $amount);
698 }
699
700 $this->callAPISuccess('Contribution', 'Delete', [
701 'id' => $contribution['id'],
702 ]);
703 $this->validateAllPayments();
704 }
705
706 /**
707 * Test create payment api for paylater contribution
708 *
709 * @throws \CRM_Core_Exception
710 */
711 public function testCreatePaymentPayLater() {
712 $this->createLoggedInUser();
713 $processorID = $this->paymentProcessorCreate();
714 $contributionParams = [
715 'total_amount' => 100,
716 'currency' => 'USD',
717 'contact_id' => $this->_individualId,
718 'financial_type_id' => 1,
719 'contribution_status_id' => 2,
720 'is_pay_later' => 1,
721 ];
722 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
723 //add payment for pay later transaction
724 $params = [
725 'contribution_id' => $contribution['id'],
726 'total_amount' => 100,
727 'card_type_id' => 'Visa',
728 'pan_truncation' => '1234',
729 'trxn_result_code' => 'Startling success',
730 'payment_instrument_id' => $processorID,
731 'trxn_id' => 1234,
732 ];
733 $payment = $this->callAPISuccess('Payment', 'create', $params);
734 $expectedResult = [
735 $payment['id'] => [
736 'from_financial_account_id' => 7,
737 'to_financial_account_id' => 6,
738 'total_amount' => 100,
739 'status_id' => 1,
740 'is_payment' => 1,
741 'card_type_id' => 1,
742 'pan_truncation' => '1234',
743 'trxn_result_code' => 'Startling success',
744 'trxn_id' => 1234,
745 'payment_instrument_id' => 1,
746 ],
747 ];
748 $this->checkPaymentResult($payment, $expectedResult);
749 // Check entity financial trxn created properly
750 $params = [
751 'entity_id' => $contribution['id'],
752 'entity_table' => 'civicrm_contribution',
753 'financial_trxn_id' => $payment['id'],
754 ];
755 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
756 $this->assertEquals($eft['values'][$eft['id']]['amount'], 100);
757 $params = [
758 'entity_table' => 'civicrm_financial_item',
759 'financial_trxn_id' => $payment['id'],
760 ];
761 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
762 $this->assertEquals($eft['values'][$eft['id']]['amount'], 100);
763 // Check contribution for completed status
764 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id']]);
765 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Completed');
766 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
767 $this->callAPISuccess('Contribution', 'Delete', [
768 'id' => $contribution['id'],
769 ]);
770 $this->validateAllPayments();
771 }
772
773 /**
774 * Test create payment api for pay later contribution with partial payment.
775 *
776 * https://lab.civicrm.org/dev/financial/issues/69
777 * @throws \CRM_Core_Exception
778 */
779 public function testCreatePaymentIncompletePaymentPartialPayment() {
780 $contributionParams = [
781 'total_amount' => 100,
782 'currency' => 'USD',
783 'contact_id' => $this->_individualId,
784 'financial_type_id' => 1,
785 'contribution_status_id' => 2,
786 ];
787 $contribution = $this->callAPISuccess('Contribution', 'create', $contributionParams);
788 $this->callAPISuccess('Payment', 'create', [
789 'contribution_id' => $contribution['id'],
790 'total_amount' => 50,
791 'payment_instrument_id' => 'Cash',
792 ]);
793 $payments = $this->callAPISuccess('Payment', 'get', ['contribution_id' => $contribution['id']])['values'];
794 $this->assertCount(1, $payments);
795 $this->validateAllPayments();
796 }
797
798 /**
799 * Test create payment api for pay later contribution with partial payment.
800 *
801 * @throws \CRM_Core_Exception
802 */
803 public function testCreatePaymentPayLaterPartialPayment() {
804 $this->createLoggedInUser();
805 $contributionParams = [
806 'total_amount' => 100,
807 'currency' => 'USD',
808 'contact_id' => $this->_individualId,
809 'financial_type_id' => 1,
810 'contribution_status_id' => 2,
811 'is_pay_later' => 1,
812 ];
813 $contribution = $this->callAPISuccess('Order', 'create', $contributionParams);
814 //Create partial payment
815 $params = [
816 'contribution_id' => $contribution['id'],
817 'total_amount' => 60,
818 ];
819 $payment = $this->callAPISuccess('Payment', 'create', $params);
820 $expectedResult = [
821 $payment['id'] => [
822 'total_amount' => 60,
823 'status_id' => 1,
824 'is_payment' => 1,
825 ],
826 ];
827 $this->checkPaymentResult($payment, $expectedResult);
828 // Check entity financial trxn created properly
829 $params = [
830 'entity_id' => $contribution['id'],
831 'entity_table' => 'civicrm_contribution',
832 'financial_trxn_id' => $payment['id'],
833 ];
834 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
835 $this->assertEquals($eft['values'][$eft['id']]['amount'], 60);
836 $params = [
837 'entity_table' => 'civicrm_financial_item',
838 'financial_trxn_id' => $payment['id'],
839 ];
840 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
841 $this->assertEquals($eft['values'][$eft['id']]['amount'], 60);
842 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id']]);
843 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Partially paid');
844 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
845 //Create full payment
846 $params = [
847 'contribution_id' => $contribution['id'],
848 'total_amount' => 40,
849 ];
850 // Rename the 'completed' status label first to check that we are not using the labels!
851 $this->callAPISuccess('OptionValue', 'get', ['name' => 'Completed', 'option_group_id' => 'contribution_status', 'api.OptionValue.create' => ['label' => 'Unicorn']]);
852 $payment = $this->callAPISuccess('Payment', 'create', $params);
853 $expectedResult = [
854 $payment['id'] => [
855 'from_financial_account_id' => 7,
856 'to_financial_account_id' => 6,
857 'total_amount' => 40,
858 'status_id' => 1,
859 'is_payment' => 1,
860 ],
861 ];
862 $this->checkPaymentResult($payment, $expectedResult);
863 // Check entity financial trxn created properly
864 $params = [
865 'entity_id' => $contribution['id'],
866 'entity_table' => 'civicrm_contribution',
867 'financial_trxn_id' => $payment['id'],
868 ];
869 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
870 $this->assertEquals($eft['values'][$eft['id']]['amount'], 40);
871 $params = [
872 'entity_table' => 'civicrm_financial_item',
873 'financial_trxn_id' => $payment['id'],
874 ];
875 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', $params);
876 $this->assertEquals($eft['values'][$eft['id']]['amount'], 40);
877 // Check contribution for completed status
878 $contribution = $this->callAPISuccess('contribution', 'get', ['id' => $contribution['id']]);
879 $this->assertEquals($contribution['values'][$contribution['id']]['contribution_status'], 'Unicorn');
880 $this->assertEquals($contribution['values'][$contribution['id']]['total_amount'], 100.00);
881 $this->callAPISuccess('Contribution', 'Delete', [
882 'id' => $contribution['id'],
883 ]);
884 $this->callAPISuccess('OptionValue', 'get', ['name' => 'Completed', 'option_group_id' => 'contribution_status', 'api.OptionValue.create' => ['label' => 'Completed']]);
885 $this->callAPISuccessGetCount('Activity', ['target_contact_id' => $this->_individualId, 'activity_type_id' => 'Payment'], 2);
886 $this->validateAllPayments();
887 }
888
889 /**
890 * Test that Payment.create uses the to_account of the payment processor.
891 *
892 * @throws \CiviCRM_API3_Exception
893 * @throws \CRM_Core_Exception
894 */
895 public function testPaymentWithProcessorWithOddFinancialAccount() {
896 $processor = $this->dummyProcessorCreate(['financial_account_id' => 'Deposit Bank Account', 'payment_instrument_id' => 'Cash']);
897 $processor2 = $this->dummyProcessorCreate(['financial_account_id' => 'Payment Processor Account', 'name' => 'p2', 'payment_instrument_id' => 'EFT']);
898 $contributionParams = [
899 'total_amount' => 100,
900 'currency' => 'USD',
901 'contact_id' => $this->_individualId,
902 'financial_type_id' => 1,
903 'contribution_status_id' => 'Pending',
904 ];
905 $order = $this->callAPISuccess('Order', 'create', $contributionParams);
906 $this->callAPISuccess('Payment', 'create', ['payment_processor_id' => $processor->getID(), 'total_amount' => 6, 'contribution_id' => $order['id']]);
907 $this->callAPISuccess('Payment', 'create', ['payment_processor_id' => $processor2->getID(), 'total_amount' => 15, 'contribution_id' => $order['id']]);
908 $payments = $this->callAPISuccess('Payment', 'get', ['sequential' => 1, 'contribution_id' => $order['id']])['values'];
909 $this->assertEquals('Deposit Bank Account', CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'to_financial_account_id', $payments[0]['to_financial_account_id']));
910 $this->assertEquals('Payment Processor Account', CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'to_financial_account_id', $payments[1]['to_financial_account_id']));
911 $this->assertEquals('Accounts Receivable', CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'from_financial_account_id', $payments[0]['from_financial_account_id']));
912 $this->assertEquals('Accounts Receivable', CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'from_financial_account_id', $payments[1]['from_financial_account_id']));
913 $this->assertEquals('Cash', CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $payments[0]['payment_instrument_id']));
914 $this->assertEquals('EFT', CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $payments[1]['payment_instrument_id']));
915 // $order = $this->callAPISuccessGetSingle('Order', ['id' => $processor->getID()]);
916 // $this->assertEquals('Cash', CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $order['payment_instrument_id']));
917 }
918
919 /**
920 * Add a location to our event.
921 *
922 * @param int $eventID
923 *
924 * @throws \CRM_Core_Exception
925 */
926 protected function addLocationToEvent($eventID) {
927 $addressParams = [
928 'name' => 'event place',
929 'street_address' => 'streety street',
930 'location_type_id' => 1,
931 'is_primary' => 1,
932 ];
933 // api requires contact_id - perhaps incorrectly but use add to get past that.
934 $address = CRM_Core_BAO_Address::add($addressParams);
935
936 $location = $this->callAPISuccess('LocBlock', 'create', ['address_id' => $address->id]);
937 $this->callAPISuccess('Event', 'create', [
938 'id' => $eventID,
939 'loc_block_id' => $location['id'],
940 'is_show_location' => TRUE,
941 ]);
942 $this->validateAllPayments();
943 }
944
945 /**
946 * Check the created payment is valid.
947 *
948 * This is probably over-testing really since we are repetitively checking a basic function...
949 *
950 * @param int $paymentID
951 * @param int $contributionID
952 * @param int $amount
953 *
954 * @throws \CRM_Core_Exception
955 */
956 protected function checkPaymentIsValid($paymentID, $contributionID, $amount = 50) {
957 $payment = $this->callAPISuccess('Payment', 'getsingle', ['financial_trxn_id' => $paymentID]);
958 $this->assertEquals(7, $payment['from_financial_account_id']);
959 $this->assertEquals(6, $payment['to_financial_account_id']);
960 $this->assertEquals(1, $payment['status_id']);
961 $this->assertEquals(1, $payment['is_payment']);
962 $this->assertEquals($amount, $payment['total_amount']);
963
964 $eft = $this->callAPISuccess('EntityFinancialTrxn', 'get', [
965 'entity_id' => $contributionID,
966 'entity_table' => 'civicrm_contribution',
967 'financial_trxn_id' => $payment['id'],
968 ]);
969
970 $this->assertEquals($eft['values'][$eft['id']]['amount'], $amount);
971 $this->validateAllPayments();
972 }
973
974 }