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