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