Merge pull request #12290 from eileenmcnaughton/export
[civicrm-core.git] / CRM / Contribute / BAO / Contribution / Utils.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
32 */
33 class CRM_Contribute_BAO_Contribution_Utils {
34
35 /**
36 * Process payment after confirmation.
37 *
38 * @param CRM_Core_Form $form
39 * Form object.
40 * @param array $paymentParams
41 * Array with payment related key.
42 * value pairs
43 * @param int $contactID
44 * Contact id.
45 * @param int $financialTypeID
46 * Financial type id.
47 * @param bool $isTest
48 * @param bool $isRecur
49 *
50 * @throws CRM_Core_Exception
51 * @throws Exception
52 * @return array
53 * associated array
54 *
55 */
56 public static function processConfirm(
57 &$form,
58 &$paymentParams,
59 $contactID,
60 $financialTypeID,
61 $isTest,
62 $isRecur
63 ) {
64 CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
65 $isPaymentTransaction = self::isPaymentTransaction($form);
66
67 $financialType = new CRM_Financial_DAO_FinancialType();
68 $financialType->id = $financialTypeID;
69 $financialType->find(TRUE);
70 if ($financialType->is_deductible) {
71 $form->assign('is_deductible', TRUE);
72 $form->set('is_deductible', TRUE);
73 }
74
75 // add some financial type details to the params list
76 // if folks need to use it
77 //CRM-15297 deprecate contributionTypeID
78 $paymentParams['financial_type_id'] = $paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $financialType->id;
79 //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
80 $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $financialType->name;
81 //CRM-11456
82 $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($financialTypeID);
83 $paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
84 $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
85
86 //fix for CRM-16317
87 if (empty($form->_params['receive_date'])) {
88 $form->_params['receive_date'] = date('YmdHis');
89 }
90 if (!empty($form->_params['start_date'])) {
91 $form->_params['start_date'] = date('YmdHis');
92 }
93 $form->assign('receive_date',
94 CRM_Utils_Date::mysqlToIso($form->_params['receive_date'])
95 );
96
97 if (empty($form->_values['amount'])) {
98 // If the amount is not in _values[], set it
99 $form->_values['amount'] = $form->_params['amount'];
100 }
101
102 if ($isPaymentTransaction) {
103 $contributionParams = array(
104 'id' => CRM_Utils_Array::value('contribution_id', $paymentParams),
105 'contact_id' => $contactID,
106 'is_test' => $isTest,
107 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
108 );
109
110 // CRM-21200: Don't overwrite contribution details during 'Pay now' payment
111 if (empty($form->_params['contribution_id'])) {
112 $contributionParams['contribution_page_id'] = $form->_id;
113 $contributionParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $paymentParams, CRM_Utils_Array::value('campaign_id', $form->_values));
114 }
115 // In case of 'Pay now' payment, append the contribution source with new text 'Paid later via page ID: N.'
116 else {
117 // contribution.source only allows 255 characters so we are using ellipsify(...) to ensure it.
118 $contributionParams['source'] = CRM_Utils_String::ellipsify(
119 ts('Paid later via page ID: %1. %2', array(
120 1 => $form->_id,
121 2 => $contributionParams['source'],
122 )),
123 220 // eventually activity.description append price information to source text so keep it 220 to ensure string length doesn't exceed 255 characters.
124 );
125 }
126
127 if (isset($paymentParams['line_item'])) {
128 // @todo make sure this is consisently set at this point.
129 $contributionParams['line_item'] = $paymentParams['line_item'];
130 }
131 if (!empty($form->_paymentProcessor)) {
132 $contributionParams['payment_instrument_id'] = $paymentParams['payment_instrument_id'] = $form->_paymentProcessor['payment_instrument_id'];
133 }
134
135 // @todo this is the wrong place for this - it should be done as close to form submission
136 // as possible
137 $paymentParams['amount'] = CRM_Utils_Rule::cleanMoney($paymentParams['amount']);
138 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution(
139 $form,
140 $paymentParams,
141 NULL,
142 $contributionParams,
143 $financialType,
144 TRUE,
145 $form->_bltID,
146 $isRecur
147 );
148
149 $paymentParams['item_name'] = $form->_params['description'];
150
151 $paymentParams['qfKey'] = empty($paymentParams['qfKey']) ? $form->controller->_key : $paymentParams['qfKey'];
152 if ($paymentParams['skipLineItem']) {
153 // We are not processing the line item here because we are processing a membership.
154 // Do not continue with contribution processing in this function.
155 return array('contribution' => $contribution);
156 }
157
158 $paymentParams['contributionID'] = $contribution->id;
159 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
160 if (isset($paymentParams['contribution_source'])) {
161 $paymentParams['source'] = $paymentParams['contribution_source'];
162 }
163
164 if (CRM_Utils_Array::value('is_recur', $form->_params) && $contribution->contribution_recur_id) {
165 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
166 }
167 if (isset($paymentParams['contribution_source'])) {
168 $form->_params['source'] = $paymentParams['contribution_source'];
169 }
170
171 // get the price set values for receipt.
172 if ($form->_priceSetId && $form->_lineItem) {
173 $form->_values['lineItem'] = $form->_lineItem;
174 $form->_values['priceSetID'] = $form->_priceSetId;
175 }
176
177 $form->_values['contribution_id'] = $contribution->id;
178 $form->_values['contribution_page_id'] = $contribution->contribution_page_id;
179
180 if (!empty($form->_paymentProcessor)) {
181 try {
182 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
183 if ($form->_contributeMode == 'notify') {
184 // We want to get rid of this & make it generic - eg. by making payment processing the last thing
185 // and always calling it first.
186 $form->postProcessHook();
187 }
188 $result = $payment->doPayment($paymentParams);
189 $form->_params = array_merge($form->_params, $result);
190 $form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
191 if (!empty($result['trxn_id'])) {
192 $contribution->trxn_id = $result['trxn_id'];
193 }
194 if (!empty($result['payment_status_id'])) {
195 $contribution->payment_status_id = $result['payment_status_id'];
196 }
197 $result['contribution'] = $contribution;
198 if ($result['payment_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution',
199 'status_id', 'Pending') && $payment->isSendReceiptForPending()) {
200 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
201 $form->_values,
202 $contribution->is_test
203 );
204 }
205 return $result;
206 }
207 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
208 // Clean up DB as appropriate.
209 if (!empty($paymentParams['contributionID'])) {
210 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'],
211 $paymentParams['contactID'], $e->getMessage());
212 }
213 if (!empty($paymentParams['contributionRecurID'])) {
214 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
215 }
216
217 $result['is_payment_failure'] = TRUE;
218 $result['error'] = $e;
219 return $result;
220 }
221 }
222 }
223
224 // Only pay later or unpaid should reach this point, although pay later likely does not & is handled via the
225 // manual processor, so it's unclear what this set is for and whether the following send ever fires.
226 $form->set('params', $form->_params);
227
228 if ($form->_params['amount'] == 0) {
229 // This is kind of a back-up for pay-later $0 transactions.
230 // In other flows they pick up the manual processor & get dealt with above (I
231 // think that might be better...).
232 return array(
233 'payment_status_id' => 1,
234 'contribution' => $contribution,
235 'payment_processor_id' => 0,
236 );
237 }
238
239 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
240 $form->_values,
241 $contribution->is_test
242 );
243 }
244
245 /**
246 * Is a payment being made.
247 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
248 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
249 * @param CRM_Core_Form $form
250 *
251 * @return bool
252 */
253 static protected function isPaymentTransaction($form) {
254 return ($form->_amount >= 0.0) ? TRUE : FALSE;
255 }
256
257 /**
258 * Get the contribution details by month of the year.
259 *
260 * @param int $param
261 * Year.
262 *
263 * @return array
264 * associated array
265 */
266 public static function contributionChartMonthly($param) {
267 if ($param) {
268 $param = array(1 => array($param, 'Integer'));
269 }
270 else {
271 $param = date("Y");
272 $param = array(1 => array($param, 'Integer'));
273 }
274
275 $query = "
276 SELECT sum(contrib.total_amount) AS ctAmt,
277 MONTH( contrib.receive_date) AS contribMonth
278 FROM civicrm_contribution AS contrib
279 INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
280 WHERE contrib.contact_id = contact.id
281 AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
282 AND contrib.contribution_status_id = 1
283 AND date_format(contrib.receive_date,'%Y') = %1
284 AND contact.is_deleted = 0
285 GROUP BY contribMonth
286 ORDER BY month(contrib.receive_date)";
287
288 $dao = CRM_Core_DAO::executeQuery($query, $param);
289
290 $params = NULL;
291 while ($dao->fetch()) {
292 if ($dao->contribMonth) {
293 $params['By Month'][$dao->contribMonth] = $dao->ctAmt;
294 }
295 }
296 return $params;
297 }
298
299 /**
300 * Get the contribution details by year.
301 *
302 * @return array
303 * associated array
304 */
305 public static function contributionChartYearly() {
306 $config = CRM_Core_Config::singleton();
307 $yearClause = "year(contrib.receive_date) as contribYear";
308 if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
309 $yearClause = "CASE
310 WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart['M'] . "
311 && DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart['d'] . " )
312 THEN
313 concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
314 ELSE
315 concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
316 END AS contribYear";
317 }
318
319 $query = "
320 SELECT sum(contrib.total_amount) AS ctAmt,
321 {$yearClause}
322 FROM civicrm_contribution AS contrib
323 INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
324 WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
325 AND contrib.contribution_status_id = 1
326 AND contact.is_deleted = 0
327 GROUP BY contribYear
328 ORDER BY contribYear";
329 $dao = CRM_Core_DAO::executeQuery($query);
330
331 $params = NULL;
332 while ($dao->fetch()) {
333 if (!empty($dao->contribYear)) {
334 $params['By Year'][$dao->contribYear] = $dao->ctAmt;
335 }
336 }
337 return $params;
338 }
339
340 /**
341 * @param array $params
342 * @param int $contactID
343 * @param $mail
344 */
345 public static function createCMSUser(&$params, $contactID, $mail) {
346 // lets ensure we only create one CMS user
347 static $created = FALSE;
348
349 if ($created) {
350 return;
351 }
352 $created = TRUE;
353
354 if (!empty($params['cms_create_account'])) {
355 $params['contactID'] = !empty($params['onbehalf_contact_id']) ? $params['onbehalf_contact_id'] : $contactID;
356 if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
357 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
358 }
359 }
360 }
361
362 /**
363 * @param array $params
364 * @param string $type
365 *
366 * @return bool
367 */
368 public static function _fillCommonParams(&$params, $type = 'paypal') {
369 if (array_key_exists('transaction', $params)) {
370 $transaction = &$params['transaction'];
371 }
372 else {
373 $transaction = &$params;
374 }
375
376 $params['contact_type'] = 'Individual';
377
378 $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
379 if (!$billingLocTypeId) {
380 $billingLocTypeId = 1;
381 }
382 if (!CRM_Utils_System::isNull($params['address'])) {
383 $params['address'][1]['is_primary'] = 1;
384 $params['address'][1]['location_type_id'] = $billingLocTypeId;
385 }
386 if (!CRM_Utils_System::isNull($params['email'])) {
387 $params['email'] = array(
388 1 => array(
389 'email' => $params['email'],
390 'location_type_id' => $billingLocTypeId,
391 ),
392 );
393 }
394
395 if (isset($transaction['trxn_id'])) {
396 // set error message if transaction has already been processed.
397 $contribution = new CRM_Contribute_DAO_Contribution();
398 $contribution->trxn_id = $transaction['trxn_id'];
399 if ($contribution->find(TRUE)) {
400 $params['error'][] = ts('transaction already processed.');
401 }
402 }
403 else {
404 // generate a new transaction id, if not already exist
405 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
406 }
407
408 if (!isset($transaction['financial_type_id'])) {
409 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
410 $transaction['financial_type_id'] = $contributionTypes[0];
411 }
412
413 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
414 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
415 }
416
417 if (!isset($transaction['invoice_id'])) {
418 $transaction['invoice_id'] = $transaction['trxn_id'];
419 }
420
421 $source = ts('ContributionProcessor: %1 API',
422 array(1 => ucfirst($type))
423 );
424 if (isset($transaction['source'])) {
425 $transaction['source'] = $source . ':: ' . $transaction['source'];
426 }
427 else {
428 $transaction['source'] = $source;
429 }
430
431 return TRUE;
432 }
433
434 /**
435 * @param int $contactID
436 *
437 * @return mixed
438 */
439 public static function getFirstLastDetails($contactID) {
440 static $_cache;
441
442 if (!$_cache) {
443 $_cache = array();
444 }
445
446 if (!isset($_cache[$contactID])) {
447 $sql = "
448 SELECT total_amount, receive_date
449 FROM civicrm_contribution c
450 WHERE contact_id = %1
451 ORDER BY receive_date ASC
452 LIMIT 1
453 ";
454 $params = array(1 => array($contactID, 'Integer'));
455
456 $dao = CRM_Core_DAO::executeQuery($sql, $params);
457 $details = array(
458 'first' => NULL,
459 'last' => NULL,
460 );
461 if ($dao->fetch()) {
462 $details['first'] = array(
463 'total_amount' => $dao->total_amount,
464 'receive_date' => $dao->receive_date,
465 );
466 }
467
468 // flip asc and desc to get the last query
469 $sql = str_replace('ASC', 'DESC', $sql);
470 $dao = CRM_Core_DAO::executeQuery($sql, $params);
471 if ($dao->fetch()) {
472 $details['last'] = array(
473 'total_amount' => $dao->total_amount,
474 'receive_date' => $dao->receive_date,
475 );
476 }
477
478 $_cache[$contactID] = $details;
479 }
480 return $_cache[$contactID];
481 }
482
483 /**
484 * Calculate the tax amount based on given tax rate.
485 *
486 * @param float $amount
487 * Amount of field.
488 * @param float $taxRate
489 * Tax rate of selected financial account for field.
490 * @param bool $ugWeDoNotKnowIfItNeedsCleaning_Help
491 * This should ALWAYS BE FALSE and then be removed. A 'clean' money string uses a standardised format
492 * such as '1000.99' for one thousand $/Euro/CUR and ninety nine cents/units.
493 * However, we are in the habit of not necessarily doing that so need to grandfather in
494 * the new expectation.
495 *
496 * @return array
497 * array of tax amount
498 *
499 */
500 public static function calculateTaxAmount($amount, $taxRate, $ugWeDoNotKnowIfItNeedsCleaning_Help = FALSE) {
501 $taxAmount = array();
502 if ($ugWeDoNotKnowIfItNeedsCleaning_Help) {
503 Civi::log()->warning('Deprecated function, make sure money is in usable format before calling this.', array('civi.tag' => 'deprecated'));
504 $amount = CRM_Utils_Rule::cleanMoney($amount);
505 }
506 // There can not be any rounding at this stage - as this is prior to quantity multiplication
507 $taxAmount['tax_amount'] = ($taxRate / 100) * $amount;
508
509 return $taxAmount;
510 }
511
512 /**
513 * Format monetary amount: round and return to desired decimal place
514 * CRM-20145
515 *
516 * @param float $amount
517 * Monetary amount
518 * @param int $decimals
519 * How many decimal places to round to and return
520 *
521 * @return float
522 * Amount rounded and returned with the desired decimal places
523 */
524 public static function formatAmount($amount, $decimals = 2) {
525 return number_format((float) round($amount, (int) $decimals), (int) $decimals, '.', '');
526 }
527
528 /**
529 * Get contribution statuses by entity e.g. contribution, membership or 'participant'
530 *
531 * @param string $usedFor
532 * @param int $id
533 * Contribution ID
534 *
535 * @return array $statuses
536 * Array of contribution statuses in array('status id' => 'label') format
537 */
538 public static function getContributionStatuses($usedFor = 'contribution', $id = NULL) {
539 if ($usedFor == 'pledge') {
540 $statusNames = CRM_Pledge_BAO_Pledge::buildOptions('status_id', 'validate');
541 }
542 else {
543 $statusNames = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate');
544 }
545
546 $statusNamesToUnset = array();
547 // on create fetch statuses on basis of component
548 if (!$id) {
549 $statusNamesToUnset = array(
550 'Refunded',
551 'Chargeback',
552 'Pending refund',
553 );
554
555 // Event registration and New Membership backoffice form support partially paid payment,
556 // so exclude this status only for 'New Contribution' form
557 if ($usedFor == 'contribution') {
558 $statusNamesToUnset = array_merge($statusNamesToUnset, array(
559 'In Progress',
560 'Overdue',
561 'Partially paid',
562 ));
563 }
564 elseif ($usedFor == 'participant') {
565 $statusNamesToUnset = array_merge($statusNamesToUnset, array(
566 'Cancelled',
567 'Failed',
568 ));
569 }
570 elseif ($usedFor == 'membership') {
571 $statusNamesToUnset = array_merge($statusNamesToUnset, array(
572 'In Progress',
573 'Overdue',
574 ));
575 }
576 }
577 else {
578 $contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $id, 'contribution_status_id');
579 $name = CRM_Utils_Array::value($contributionStatus, $statusNames);
580 switch ($name) {
581 case 'Completed':
582 // [CRM-17498] Removing unsupported status change options.
583 $statusNamesToUnset = array_merge($statusNamesToUnset, array(
584 'Pending',
585 'Failed',
586 'Partially paid',
587 'Pending refund',
588 ));
589 break;
590
591 case 'Cancelled':
592 case 'Chargeback':
593 case 'Refunded':
594 $statusNamesToUnset = array_merge($statusNamesToUnset, array(
595 'Pending',
596 'Failed',
597 ));
598 break;
599
600 case 'Pending':
601 case 'In Progress':
602 $statusNamesToUnset = array_merge($statusNamesToUnset, array(
603 'Refunded',
604 'Chargeback',
605 ));
606 break;
607
608 case 'Failed':
609 $statusNamesToUnset = array_merge($statusNamesToUnset, array(
610 'Pending',
611 'Refunded',
612 'Chargeback',
613 'Completed',
614 'In Progress',
615 'Cancelled',
616 ));
617 break;
618 }
619 }
620
621 foreach ($statusNamesToUnset as $name) {
622 unset($statusNames[CRM_Utils_Array::key($name, $statusNames)]);
623 }
624
625 // based on filtered statuse names fetch the final list of statuses in array('id' => 'label') format
626 if ($usedFor == 'pledge') {
627 $statuses = CRM_Pledge_BAO_Pledge::buildOptions('status_id');
628 }
629 else {
630 $statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
631 }
632 foreach ($statuses as $statusID => $label) {
633 if (!array_key_exists($statusID, $statusNames)) {
634 unset($statuses[$statusID]);
635 }
636 }
637
638 return $statuses;
639 }
640
641 }