Merge pull request #13769 from eileenmcnaughton/matt
[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 // Check if pending contribution
62 $fullyPaidPayLater = ($contributionStatus == 'Pending' && $isPaymentCompletesContribution);
63 if ($contributionStatus == 'Pending') {
64 if ($isPaymentCompletesContribution) {
65 civicrm_api3('Contribution', 'completetransaction', ['id' => $contribution['id']]);
66 // Get the trxn
67 $trxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution['id'], 'DESC');
68 $ftParams = ['id' => $trxnId['financialTrxnId']];
69 $trxn = CRM_Core_BAO_FinancialTrxn::retrieve($ftParams, CRM_Core_DAO::$_nullArray);
70 }
71 else {
72 civicrm_api3('Contribution', 'create',
73 [
74 'id' => $contribution['id'],
75 'contribution_status_id' => 'Partially paid',
76 ]
77 );
78 }
79 }
80 if (!$fullyPaidPayLater) {
81 $trxn = CRM_Contribute_BAO_Contribution::recordPartialPayment($contribution, $params);
82 if ($isPaymentCompletesContribution) {
83 civicrm_api3('Contribution', 'completetransaction', array('id' => $contribution['id']));
84 }
85
86 if (CRM_Utils_Array::value('line_item', $params) && !empty($trxn)) {
87 foreach ($params['line_item'] as $values) {
88 foreach ($values as $id => $amount) {
89 $p = ['id' => $id];
90 $check = CRM_Price_BAO_LineItem::retrieve($p, $defaults);
91 if (empty($check)) {
92 throw new API_Exception('Please specify a valid Line Item.');
93 }
94 // get financial item
95 $sql = "SELECT fi.id
96 FROM civicrm_financial_item fi
97 INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item'
98 WHERE li.contribution_id = %1 AND li.id = %2";
99 $sqlParams = [
100 1 => [$params['contribution_id'], 'Integer'],
101 2 => [$id, 'Integer'],
102 ];
103 $fid = CRM_Core_DAO::singleValueQuery($sql, $sqlParams);
104 // Record Entity Financial Trxn
105 $eftParams = [
106 'entity_table' => 'civicrm_financial_item',
107 'financial_trxn_id' => $trxn->id,
108 'amount' => $amount,
109 'entity_id' => $fid,
110 ];
111 civicrm_api3('EntityFinancialTrxn', 'create', $eftParams);
112 }
113 }
114 }
115 elseif (!empty($trxn)) {
116 CRM_Contribute_BAO_Contribution::assignProportionalLineItems($params, $trxn->id, $contribution['total_amount']);
117 }
118 }
119
120 return $trxn;
121 }
122
123 /**
124 * Send an email confirming a payment that has been received.
125 *
126 * @param array $params
127 *
128 * @return array
129 */
130 public static function sendConfirmation($params) {
131
132 $entities = self::loadRelatedEntities($params['id']);
133 $sendTemplateParams = array(
134 'groupName' => 'msg_tpl_workflow_contribution',
135 'valueName' => 'payment_or_refund_notification',
136 'PDFFilename' => ts('notification') . '.pdf',
137 'contactId' => $entities['contact']['id'],
138 'toName' => $entities['contact']['display_name'],
139 'toEmail' => $entities['contact']['email'],
140 'tplParams' => self::getConfirmationTemplateParameters($entities),
141 );
142 return CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
143 }
144
145 /**
146 * Load entities related to the current payment id.
147 *
148 * This gives us all the data we need to send an email confirmation but avoiding
149 * getting anything not tested for the confirmations. We retrieve the 'full' event as
150 * it has been traditionally assigned in full.
151 *
152 * @param int $id
153 *
154 * @return array
155 * - contact = ['id' => x, 'display_name' => y, 'email' => z]
156 * - event = [.... full event details......]
157 * - contribution = ['id' => x],
158 * - payment = [payment info + payment summary info]
159 */
160 protected static function loadRelatedEntities($id) {
161 $entities = [];
162 $contributionID = (int) civicrm_api3('EntityFinancialTrxn', 'getvalue', [
163 'financial_trxn_id' => $id,
164 'entity_table' => 'civicrm_contribution',
165 'return' => 'entity_id',
166 ]);
167 $entities['contribution'] = ['id' => $contributionID];
168 $entities['payment'] = array_merge(civicrm_api3('FinancialTrxn', 'getsingle', ['id' => $id]),
169 CRM_Contribute_BAO_Contribution::getPaymentInfo($contributionID)
170 );
171
172 $contactID = self::getPaymentContactID($contributionID);
173 list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
174 $entities['contact'] = ['id' => $contactID, 'display_name' => $displayName, 'email' => $email];
175 $contact = civicrm_api3('Contact', 'getsingle', ['id' => $contactID, 'return' => 'email_greeting']);
176 $entities['contact']['email_greeting'] = $contact['email_greeting_display'];
177
178 $participantRecords = civicrm_api3('ParticipantPayment', 'get', [
179 'contribution_id' => $contributionID,
180 'api.Participant.get' => ['return' => 'event_id'],
181 'sequential' => 1,
182 ])['values'];
183 if (!empty($participantRecords)) {
184 $entities['event'] = civicrm_api3('Event', 'getsingle', ['id' => $participantRecords[0]['api.Participant.get']['values'][0]['event_id']]);
185 if (!empty($entities['event']['is_show_location'])) {
186 $locationParams = [
187 'entity_id' => $entities['event']['id'],
188 'entity_table' => 'civicrm_event',
189 ];
190 $entities['location'] = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
191 }
192 }
193
194 return $entities;
195 }
196
197 /**
198 * @param int $contributionID
199 *
200 * @return int
201 */
202 public static function getPaymentContactID($contributionID) {
203 $contribution = civicrm_api3('Contribution', 'getsingle', [
204 'id' => $contributionID ,
205 'return' => ['contact_id'],
206 ]);
207 return (int) $contribution['contact_id'];
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 if (!$participantId) {
363 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
364 }
365
366 $trxnData['trxn_date'] = !empty($trxnData['trxn_date']) ? $trxnData['trxn_date'] : date('YmdHis');
367 $params['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $trxnData, CRM_Utils_Array::value('payment_instrument_id', $params));
368
369 $paidStatus = CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
370 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionDAO->financial_type_id, 'Accounts Receivable Account is');
371 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
372
373 $params['partial_payment_total'] = $contributionDAO->total_amount;
374 $params['partial_amount_to_pay'] = $trxnData['total_amount'];
375 $trxnData['net_amount'] = !empty($trxnData['net_amount']) ? $trxnData['net_amount'] : $trxnData['total_amount'];
376 $params['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $trxnData);
377 $params['card_type_id'] = CRM_Utils_Array::value('card_type_id', $trxnData);
378 $params['check_number'] = CRM_Utils_Array::value('check_number', $trxnData);
379
380 // record the entry
381 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnData);
382 $toFinancialAccount = $arAccountId;
383 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
384 if (!empty($trxnId)) {
385 $trxnId = $trxnId['trxn_id'];
386 }
387 elseif (!empty($contributionDAO->payment_instrument_id)) {
388 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
389 }
390 else {
391 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
392 $queryParams = [1 => [$relationTypeId, 'Integer']];
393 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
394 }
395
396 // update statuses
397 // criteria for updates contribution total_amount == financial_trxns of partial_payments
398 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
399 FROM civicrm_financial_trxn ft
400 LEFT JOIN civicrm_entity_financial_trxn eft
401 ON (ft.id = eft.financial_trxn_id)
402 WHERE eft.entity_table = 'civicrm_contribution'
403 AND eft.entity_id = {$contributionId}
404 AND ft.to_financial_account_id != {$toFinancialAccount}
405 AND ft.status_id = {$completedStatusId}
406 ";
407 $query = CRM_Core_DAO::executeQuery($sql);
408 $query->fetch();
409 $sumOfPayments = $query->sum_of_payments;
410
411 // update statuses
412 if ($contributionDAO->total_amount == $sumOfPayments) {
413 // update contribution status and
414 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
415 $contributionDAO->contribution_status_id = $completedStatusId;
416 $contributionDAO->cancel_date = 'null';
417 $contributionDAO->cancel_reason = NULL;
418 $netAmount = !empty($trxnData['net_amount']) ? NULL : $trxnData['total_amount'];
419 $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
420 $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
421 $contributionDAO->save();
422
423 //Change status of financial record too
424 $financialTrxn->status_id = $completedStatusId;
425 $financialTrxn->save();
426
427 // note : not using the self::add method,
428 // the reason because it performs 'status change' related code execution for financial records
429 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
430 // are coded below i.e. just updating financial_item status to 'Paid'
431
432 if ($participantId) {
433 // update participant status
434 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
435 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
436 foreach ($ids as $val) {
437 $participantUpdate['id'] = $val;
438 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
439 CRM_Event_BAO_Participant::add($participantUpdate);
440 }
441 }
442
443 // Remove this - completeOrder does it.
444 CRM_Contribute_BAO_Contribution::updateMembershipBasedOnCompletionOfContribution(
445 $contributionDAO,
446 $contributionId,
447 $trxnData['trxn_date']
448 );
449
450 // update financial item statuses
451 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
452 $sqlFinancialItemUpdate = "
453 UPDATE civicrm_financial_item fi
454 LEFT JOIN civicrm_entity_financial_trxn eft
455 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
456 SET status_id = {$paidStatus}
457 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
458 ";
459 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
460 }
461 return $financialTrxn;
462 }
463
464 /**
465 * The recordFinancialTransactions function has capricious requirements for input parameters - load them.
466 *
467 * The function needs rework but for now we need to give it what it wants.
468 *
469 * @param int $contributionId
470 *
471 * @return array
472 */
473 protected static function getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId) {
474 $getInfoOf['id'] = $contributionId;
475 $defaults = [];
476 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
477
478 // build params for recording financial trxn entry
479 $params['contribution'] = $contributionDAO;
480 $params = array_merge($defaults, $params);
481 $params['skipLineItem'] = TRUE;
482 return [$contributionDAO, $params];
483 }
484
485 /**
486 * Does this payment complete the contribution
487 *
488 * @param int $contributionID
489 * @param float $paymentAmount
490 *
491 * @return bool
492 */
493 protected static function isPaymentCompletesContribution($contributionID, $paymentAmount) {
494 $outstandingBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionID);
495 $cmp = bccomp($paymentAmount, $outstandingBalance, 5);
496 return ($cmp == 0 || $cmp == 1);
497 }
498
499 }