Switch to calling Payment.create api when processing a refund from AdditionalPayment...
[civicrm-core.git] / CRM / Financial / BAO / Payment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class contains payment related functions.
36 */
37 class CRM_Financial_BAO_Payment {
38
39 /**
40 * Function to process additional payment for partial and refund contributions.
41 *
42 * This function is called via API payment.create function. All forms that add payments
43 * should use this.
44 *
45 * @param array $params
46 * - contribution_id
47 * - total_amount
48 * - line_item
49 *
50 * @return \CRM_Financial_DAO_FinancialTrxn
51 *
52 * @throws \API_Exception
53 * @throws \CRM_Core_Exception
54 * @throws \CiviCRM_API3_Exception
55 */
56 public static function create($params) {
57 $contribution = civicrm_api3('Contribution', 'getsingle', ['id' => $params['contribution_id']]);
58 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($contribution['contribution_status_id'], 'name');
59
60 $isPaymentCompletesContribution = self::isPaymentCompletesContribution($params['contribution_id'], $params['total_amount']);
61
62 // For legacy reasons Pending payments are completed through completetransaction.
63 // @todo completetransaction should transition components but financial transactions
64 // should be handled through Payment.create.
65 $isSkipRecordingPaymentHereForLegacyHandlingReasons = ($contributionStatus == 'Pending' && $isPaymentCompletesContribution);
66
67 if (!$isSkipRecordingPaymentHereForLegacyHandlingReasons && $params['total_amount'] > 0) {
68 $trxn = CRM_Contribute_BAO_Contribution::recordPartialPayment($contribution, $params);
69
70 if (CRM_Utils_Array::value('line_item', $params) && !empty($trxn)) {
71 foreach ($params['line_item'] as $values) {
72 foreach ($values as $id => $amount) {
73 $p = ['id' => $id];
74 $check = CRM_Price_BAO_LineItem::retrieve($p, $defaults);
75 if (empty($check)) {
76 throw new API_Exception('Please specify a valid Line Item.');
77 }
78 // get financial item
79 $sql = "SELECT fi.id
80 FROM civicrm_financial_item fi
81 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
82 WHERE li.contribution_id = %1 AND li.id = %2";
83 $sqlParams = [
84 1 => [$params['contribution_id'], 'Integer'],
85 2 => [$id, 'Integer'],
86 ];
87 $fid = CRM_Core_DAO::singleValueQuery($sql, $sqlParams);
88 // Record Entity Financial Trxn
89 $eftParams = [
90 'entity_table' => 'civicrm_financial_item',
91 'financial_trxn_id' => $trxn->id,
92 'amount' => $amount,
93 'entity_id' => $fid,
94 ];
95 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
96 }
97 }
98 }
99 elseif (!empty($trxn)) {
100 CRM_Contribute_BAO_Contribution::assignProportionalLineItems($params, $trxn->id, $contribution['total_amount']);
101 }
102 }
103 elseif ($params['total_amount'] < 0) {
104 $trxn = self::recordRefundPayment($params['contribution_id'], $params, FALSE);
105 CRM_Contribute_BAO_Contribution::recordPaymentActivity($params['contribution_id'], CRM_Utils_Array::value('participant_id', $params), $params['total_amount'], $trxn->currency, $trxn->trxn_date);
106 }
107
108 if ($isPaymentCompletesContribution) {
109 if ($contributionStatus == 'Pending refund') {
110 // Ideally we could still call completetransaction as non-payment related actions should
111 // be outside this class. However, for now we just update the contribution here.
112 // Unit test cover in CRM_Event_BAO_AdditionalPaymentTest::testTransactionInfo.
113 civicrm_api3('Contribution', 'create',
114 [
115 'id' => $contribution['id'],
116 'contribution_status_id' => 'Completed',
117 ]
118 );
119 }
120 else {
121 civicrm_api3('Contribution', 'completetransaction', ['id' => $contribution['id']]);
122 // Get the trxn
123 $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
124 $ftParams = ['id' => $trxnId['financialTrxnId']];
125 $trxn = CRM_Core_BAO_FinancialTrxn::retrieve($ftParams, CRM_Core_DAO::$_nullArray);
126 }
127 }
128 elseif ($contributionStatus === 'Pending') {
129 civicrm_api3('Contribution', 'create',
130 [
131 'id' => $contribution['id'],
132 'contribution_status_id' => 'Partially paid',
133 ]
134 );
135 }
136
137 return $trxn;
138 }
139
140 /**
141 * Send an email confirming a payment that has been received.
142 *
143 * @param array $params
144 *
145 * @return array
146 */
147 public static function sendConfirmation($params) {
148
149 $entities = self::loadRelatedEntities($params['id']);
150 $sendTemplateParams = [
151 'groupName' => 'msg_tpl_workflow_contribution',
152 'valueName' => 'payment_or_refund_notification',
153 'PDFFilename' => ts('notification') . '.pdf',
154 'contactId' => $entities['contact']['id'],
155 'toName' => $entities['contact']['display_name'],
156 'toEmail' => $entities['contact']['email'],
157 'tplParams' => self::getConfirmationTemplateParameters($entities),
158 ];
159 return CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
160 }
161
162 /**
163 * Load entities related to the current payment id.
164 *
165 * This gives us all the data we need to send an email confirmation but avoiding
166 * getting anything not tested for the confirmations. We retrieve the 'full' event as
167 * it has been traditionally assigned in full.
168 *
169 * @param int $id
170 *
171 * @return array
172 * - contact = ['id' => x, 'display_name' => y, 'email' => z]
173 * - event = [.... full event details......]
174 * - contribution = ['id' => x],
175 * - payment = [payment info + payment summary info]
176 */
177 protected static function loadRelatedEntities($id) {
178 $entities = [];
179 $contributionID = (int) civicrm_api3('EntityFinancialTrxn', 'getvalue', [
180 'financial_trxn_id' => $id,
181 'entity_table' => 'civicrm_contribution',
182 'return' => 'entity_id',
183 ]);
184 $entities['contribution'] = ['id' => $contributionID];
185 $entities['payment'] = array_merge(civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $id]),
186 CRM_Contribute_BAO_Contribution::getPaymentInfo($contributionID)
187 );
188
189 $contactID = self::getPaymentContactID($contributionID);
190 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
191 $entities['contact'] = ['id' => $contactID, 'display_name' => $displayName, 'email' => $email];
192 $contact = civicrm_api3('Contact', 'getsingle', ['id' => $contactID, 'return' => 'email_greeting']);
193 $entities['contact']['email_greeting'] = $contact['email_greeting_display'];
194
195 $participantRecords = civicrm_api3('ParticipantPayment', 'get', [
196 'contribution_id' => $contributionID,
197 'api.Participant.get' => ['return' => 'event_id'],
198 'sequential' => 1,
199 ])['values'];
200 if (!empty($participantRecords)) {
201 $entities['event'] = civicrm_api3('Event', 'getsingle', ['id' => $participantRecords[0]['api.Participant.get']['values'][0]['event_id']]);
202 if (!empty($entities['event']['is_show_location'])) {
203 $locationParams = [
204 'entity_id' => $entities['event']['id'],
205 'entity_table' => 'civicrm_event',
206 ];
207 $entities['location'] = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
208 }
209 }
210
211 return $entities;
212 }
213
214 /**
215 * @param int $contributionID
216 *
217 * @return int
218 */
219 public static function getPaymentContactID($contributionID) {
220 $contribution = civicrm_api3('Contribution', 'getsingle', [
221 'id' => $contributionID ,
222 'return' => ['contact_id'],
223 ]);
224 return (int) $contribution['contact_id'];
225 }
226
227 /**
228 * @param array $entities
229 * Related entities as an array keyed by the various entities.
230 *
231 * @return array
232 * Values required for the notification
233 * - contact_id
234 * - template_variables
235 * - event (DAO of event if relevant)
236 */
237 public static function getConfirmationTemplateParameters($entities) {
238 $templateVariables = [
239 'contactDisplayName' => $entities['contact']['display_name'],
240 'emailGreeting' => $entities['contact']['email_greeting'],
241 'totalAmount' => $entities['payment']['total'],
242 'amountOwed' => $entities['payment']['balance'],
243 'totalPaid' => $entities['payment']['paid'],
244 'paymentAmount' => $entities['payment']['total_amount'],
245 'checkNumber' => CRM_Utils_Array::value('check_number', $entities['payment']),
246 'receive_date' => $entities['payment']['trxn_date'],
247 'paidBy' => CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $entities['payment']['payment_instrument_id']),
248 'isShowLocation' => (!empty($entities['event']) ? $entities['event']['is_show_location'] : FALSE),
249 'location' => CRM_Utils_Array::value('location', $entities),
250 'event' => CRM_Utils_Array::value('event', $entities),
251 'component' => (!empty($entities['event']) ? 'event' : 'contribution'),
252 'isRefund' => $entities['payment']['total_amount'] < 0,
253 'isAmountzero' => $entities['payment']['total_amount'] === 0,
254 'refundAmount' => ($entities['payment']['total_amount'] < 0 ? $entities['payment']['total_amount'] : NULL),
255 'paymentsComplete' => ($entities['payment']['balance'] == 0),
256 ];
257
258 return self::filterUntestedTemplateVariables($templateVariables);
259 }
260
261 /**
262 * Filter out any untested variables.
263 *
264 * This just serves to highlight if any variables are added without a unit test also being added.
265 *
266 * (if hit then add a unit test for the param & add to this array).
267 *
268 * @param array $params
269 *
270 * @return array
271 */
272 public static function filterUntestedTemplateVariables($params) {
273 $testedTemplateVariables = [
274 'contactDisplayName',
275 'totalAmount',
276 'amountOwed',
277 'paymentAmount',
278 'event',
279 'component',
280 'checkNumber',
281 'receive_date',
282 'paidBy',
283 'isShowLocation',
284 'location',
285 'isRefund',
286 'isAmountzero',
287 'refundAmount',
288 'totalPaid',
289 'paymentsComplete',
290 'emailGreeting',
291 ];
292 // These are assigned by the payment form - they still 'get through' from the
293 // form for now without being in here but we should ideally load
294 // and assign. Note we should update the tpl to use {if $billingName}
295 // and ditch contributeMode - although it might need to be deprecated rather than removed.
296 $todoParams = [
297 'contributeMode',
298 'billingName',
299 'address',
300 'credit_card_type',
301 'credit_card_number',
302 'credit_card_exp_date',
303 ];
304 $filteredParams = [];
305 foreach ($testedTemplateVariables as $templateVariable) {
306 // This will cause an a-notice if any are NOT set - by design. Ensuring
307 // they are set prevents leakage.
308 $filteredParams[$templateVariable] = $params[$templateVariable];
309 }
310 return $filteredParams;
311 }
312
313 /**
314 * @param $contributionId
315 * @param $trxnData
316 * @param $updateStatus
317 * - deprecate this param
318 *
319 * @todo - make this protected once recordAdditionalPayment no longer calls it.
320 *
321 * @return CRM_Financial_DAO_FinancialTrxn
322 */
323 protected static function recordRefundPayment($contributionId, $trxnData, $updateStatus) {
324 list($contributionDAO, $params) = self::getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId);
325
326 $params['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $trxnData, CRM_Utils_Array::value('payment_instrument_id', $params));
327
328 $paidStatus = CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
329 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionDAO->financial_type_id, 'Accounts Receivable Account is');
330 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
331
332 $trxnData['total_amount'] = $trxnData['net_amount'] = $trxnData['total_amount'];
333 $trxnData['from_financial_account_id'] = $arAccountId;
334 $trxnData['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Refunded');
335 // record the entry
336 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnData);
337
338 // note : not using the self::add method,
339 // the reason because it performs 'status change' related code execution for financial records
340 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
341 // are coded below i.e. just updating financial_item status to 'Paid'
342 if ($updateStatus) {
343 CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $completedStatusId);
344 }
345 // add financial item entry
346 $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionDAO->id);
347 if (!empty($lineItems)) {
348 foreach ($lineItems as $lineItemId => $lineItemValue) {
349 // don't record financial item for cancelled line-item
350 if ($lineItemValue['qty'] == 0) {
351 continue;
352 }
353 $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount / $contributionDAO->total_amount);
354 $addFinancialEntry = [
355 'transaction_date' => $financialTrxn->trxn_date,
356 'contact_id' => $contributionDAO->contact_id,
357 'amount' => round($paid, 2),
358 'currency' => $contributionDAO->currency,
359 'status_id' => $paidStatus,
360 'entity_id' => $lineItemId,
361 'entity_table' => 'civicrm_line_item',
362 ];
363 $trxnIds = ['id' => $financialTrxn->id];
364 CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
365 }
366 }
367 return $financialTrxn;
368 }
369
370 /**
371 * @param int $contributionId
372 * @param array $trxnData
373 * @param int $participantId
374 *
375 * @return \CRM_Core_BAO_FinancialTrxn
376 */
377 public static function recordPayment($contributionId, $trxnData, $participantId) {
378 list($contributionDAO, $params) = self::getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId);
379
380 $trxnData['trxn_date'] = !empty($trxnData['trxn_date']) ? $trxnData['trxn_date'] : date('YmdHis');
381 $params['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $trxnData, CRM_Utils_Array::value('payment_instrument_id', $params));
382
383 $paidStatus = CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
384 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionDAO->financial_type_id, 'Accounts Receivable Account is');
385 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
386
387 $params['partial_payment_total'] = $contributionDAO->total_amount;
388 $params['partial_amount_to_pay'] = $trxnData['total_amount'];
389 $trxnData['net_amount'] = !empty($trxnData['net_amount']) ? $trxnData['net_amount'] : $trxnData['total_amount'];
390 $params['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $trxnData);
391 $params['card_type_id'] = CRM_Utils_Array::value('card_type_id', $trxnData);
392 $params['check_number'] = CRM_Utils_Array::value('check_number', $trxnData);
393
394 // record the entry
395 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnData);
396 $toFinancialAccount = $arAccountId;
397 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
398 if (!empty($trxnId)) {
399 $trxnId = $trxnId['trxn_id'];
400 }
401 elseif (!empty($contributionDAO->payment_instrument_id)) {
402 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
403 }
404 else {
405 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
406 $queryParams = [1 => [$relationTypeId, 'Integer']];
407 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
408 }
409
410 // update statuses
411 // criteria for updates contribution total_amount == financial_trxns of partial_payments
412 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
413 FROM civicrm_financial_trxn ft
414 LEFT JOIN civicrm_entity_financial_trxn eft
415 ON (ft.id = eft.financial_trxn_id)
416 WHERE eft.entity_table = 'civicrm_contribution'
417 AND eft.entity_id = {$contributionId}
418 AND ft.to_financial_account_id != {$toFinancialAccount}
419 AND ft.status_id = {$completedStatusId}
420 ";
421 $query = CRM_Core_DAO::executeQuery($sql);
422 $query->fetch();
423 $sumOfPayments = $query->sum_of_payments;
424
425 // update statuses
426 if ($contributionDAO->total_amount == $sumOfPayments) {
427 // update contribution status and
428 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
429 $contributionDAO->contribution_status_id = $completedStatusId;
430 $contributionDAO->cancel_date = 'null';
431 $contributionDAO->cancel_reason = NULL;
432 $netAmount = !empty($trxnData['net_amount']) ? NULL : $trxnData['total_amount'];
433 $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
434 $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
435 $contributionDAO->save();
436
437 //Change status of financial record too
438 $financialTrxn->status_id = $completedStatusId;
439 $financialTrxn->save();
440
441 // note : not using the self::add method,
442 // the reason because it performs 'status change' related code execution for financial records
443 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
444 // are coded below i.e. just updating financial_item status to 'Paid'
445
446 if (!$participantId) {
447 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
448 }
449 if ($participantId) {
450 // update participant status
451 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
452 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
453 foreach ($ids as $val) {
454 $participantUpdate['id'] = $val;
455 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
456 CRM_Event_BAO_Participant::add($participantUpdate);
457 }
458 }
459
460 // Remove this - completeOrder does it.
461 CRM_Contribute_BAO_Contribution::updateMembershipBasedOnCompletionOfContribution(
462 $contributionDAO,
463 $contributionId,
464 $trxnData['trxn_date']
465 );
466
467 // update financial item statuses
468 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
469 $sqlFinancialItemUpdate = "
470 UPDATE civicrm_financial_item fi
471 LEFT JOIN civicrm_entity_financial_trxn eft
472 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
473 SET status_id = {$paidStatus}
474 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
475 ";
476 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
477 }
478 return $financialTrxn;
479 }
480
481 /**
482 * The recordFinancialTransactions function has capricious requirements for input parameters - load them.
483 *
484 * The function needs rework but for now we need to give it what it wants.
485 *
486 * @param int $contributionId
487 *
488 * @return array
489 */
490 protected static function getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId) {
491 $getInfoOf['id'] = $contributionId;
492 $defaults = [];
493 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
494
495 // build params for recording financial trxn entry
496 $params['contribution'] = $contributionDAO;
497 $params = array_merge($defaults, $params);
498 $params['skipLineItem'] = TRUE;
499 return [$contributionDAO, $params];
500 }
501
502 /**
503 * Does this payment complete the contribution
504 *
505 * @param int $contributionID
506 * @param float $paymentAmount
507 *
508 * @return bool
509 */
510 protected static function isPaymentCompletesContribution($contributionID, $paymentAmount) {
511 $outstandingBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionID);
512 $cmp = bccomp($paymentAmount, $outstandingBalance, 5);
513 return ($cmp == 0 || $cmp == 1);
514 }
515
516 }