Merge pull request #13695 from eileenmcnaughton/extract_activity
[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 // load related memberships on basis of $contributionDAO object
362 // @todo - this is done in the function that completes payments so it's being done twice.
363 // test & remove.
364 $contributionDAO->loadRelatedMembershipObjects();
365
366 if (!$participantId) {
367 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id');
368 }
369
370 $trxnData['trxn_date'] = !empty($trxnData['trxn_date']) ? $trxnData['trxn_date'] : date('YmdHis');
371 $params['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $trxnData, CRM_Utils_Array::value('payment_instrument_id', $params));
372
373 $paidStatus = CRM_Core_PseudoConstant::getKey('CRM_Financial_DAO_FinancialItem', 'status_id', 'Paid');
374 $arAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($contributionDAO->financial_type_id, 'Accounts Receivable Account is');
375 $completedStatusId = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
376
377 $params['partial_payment_total'] = $contributionDAO->total_amount;
378 $params['partial_amount_to_pay'] = $trxnData['total_amount'];
379 $trxnData['net_amount'] = !empty($trxnData['net_amount']) ? $trxnData['net_amount'] : $trxnData['total_amount'];
380 $params['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $trxnData);
381 $params['card_type_id'] = CRM_Utils_Array::value('card_type_id', $trxnData);
382 $params['check_number'] = CRM_Utils_Array::value('check_number', $trxnData);
383
384 // record the entry
385 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnData);
386 $toFinancialAccount = $arAccountId;
387 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
388 if (!empty($trxnId)) {
389 $trxnId = $trxnId['trxn_id'];
390 }
391 elseif (!empty($contributionDAO->payment_instrument_id)) {
392 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
393 }
394 else {
395 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
396 $queryParams = [1 => [$relationTypeId, 'Integer']];
397 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
398 }
399
400 // update statuses
401 // criteria for updates contribution total_amount == financial_trxns of partial_payments
402 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
403 FROM civicrm_financial_trxn ft
404 LEFT JOIN civicrm_entity_financial_trxn eft
405 ON (ft.id = eft.financial_trxn_id)
406 WHERE eft.entity_table = 'civicrm_contribution'
407 AND eft.entity_id = {$contributionId}
408 AND ft.to_financial_account_id != {$toFinancialAccount}
409 AND ft.status_id = {$completedStatusId}
410 ";
411 $query = CRM_Core_DAO::executeQuery($sql);
412 $query->fetch();
413 $sumOfPayments = $query->sum_of_payments;
414
415 // update statuses
416 if ($contributionDAO->total_amount == $sumOfPayments) {
417 // update contribution status and
418 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
419 $contributionDAO->contribution_status_id = $completedStatusId;
420 $contributionDAO->cancel_date = 'null';
421 $contributionDAO->cancel_reason = NULL;
422 $netAmount = !empty($trxnData['net_amount']) ? NULL : $trxnData['total_amount'];
423 $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
424 $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
425 $contributionDAO->save();
426
427 //Change status of financial record too
428 $financialTrxn->status_id = $completedStatusId;
429 $financialTrxn->save();
430
431 // note : not using the self::add method,
432 // the reason because it performs 'status change' related code execution for financial records
433 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
434 // are coded below i.e. just updating financial_item status to 'Paid'
435
436 if ($participantId) {
437 // update participant status
438 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
439 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
440 foreach ($ids as $val) {
441 $participantUpdate['id'] = $val;
442 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
443 CRM_Event_BAO_Participant::add($participantUpdate);
444 }
445 }
446
447 // Remove this - completeOrder does it.
448 CRM_Contribute_BAO_Contribution::updateMembershipBasedOnCompletionOfContribution(
449 $contributionDAO,
450 $contributionId,
451 $trxnData['trxn_date']
452 );
453
454 // update financial item statuses
455 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
456 $sqlFinancialItemUpdate = "
457 UPDATE civicrm_financial_item fi
458 LEFT JOIN civicrm_entity_financial_trxn eft
459 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
460 SET status_id = {$paidStatus}
461 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
462 ";
463 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
464 }
465 return $financialTrxn;
466 }
467
468 /**
469 * The recordFinancialTransactions function has capricious requirements for input parameters - load them.
470 *
471 * The function needs rework but for now we need to give it what it wants.
472 *
473 * @param int $contributionId
474 *
475 * @return array
476 */
477 protected static function getContributionAndParamsInFormatForRecordFinancialTransaction($contributionId) {
478 $getInfoOf['id'] = $contributionId;
479 $defaults = [];
480 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
481
482 // build params for recording financial trxn entry
483 $params['contribution'] = $contributionDAO;
484 $params = array_merge($defaults, $params);
485 $params['skipLineItem'] = TRUE;
486 return [$contributionDAO, $params];
487 }
488
489 /**
490 * Does this payment complete the contribution
491 *
492 * @param int $contributionID
493 * @param float $paymentAmount
494 *
495 * @return bool
496 */
497 protected static function isPaymentCompletesContribution($contributionID, $paymentAmount) {
498 $outstandingBalance = CRM_Contribute_BAO_Contribution::getContributionBalance($contributionID);
499 $cmp = bccomp($paymentAmount, $outstandingBalance, 5);
500 return ($cmp == 0 || $cmp == 1);
501 }
502
503 }