Merge pull request #8217 from colemanw/role
[civicrm-core.git] / CRM / Contribute / BAO / Contribution / Utils.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 */
33class CRM_Contribute_BAO_Contribution_Utils {
34
35 /**
fe482240 36 * Process payment after confirmation.
6a488035 37 *
014c4014
TO
38 * @param CRM_Core_Form $form
39 * Form object.
40 * @param array $paymentParams
41 * Array with payment related key.
16b10e64 42 * value pairs
014c4014
TO
43 * @param int $contactID
44 * Contact id.
45 * @param int $contributionTypeId
46 * Financial type id.
b8950542 47 * @param int|string $component component id
449f4c90 48 * @param bool $isTest
49 * @param bool $isRecur
cc789d46
EM
50 *
51 * @throws CRM_Core_Exception
52 * @throws Exception
a6c01b45
CW
53 * @return array
54 * associated array
6a488035 55 *
6a488035 56 */
ae5ffbb7 57 public static function processConfirm(
a13f3d8c 58 &$form,
6a488035 59 &$paymentParams,
6a488035
TO
60 $contactID,
61 $contributionTypeId,
62 $component = 'contribution',
449f4c90 63 $isTest,
64 $isRecur
6a488035
TO
65 ) {
66 CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
4bd318e0 67 $lineItems = $form->_lineItem;
cc789d46 68 $isPaymentTransaction = self::isPaymentTransaction($form);
43b309d0 69
68642f9a
EM
70 $financialType = new CRM_Financial_DAO_FinancialType();
71 $financialType->id = $contributionTypeId;
72 $financialType->find(TRUE);
73 if ($financialType->is_deductible) {
74 $form->assign('is_deductible', TRUE);
75 $form->set('is_deductible', TRUE);
6a488035
TO
76 }
77
78 // add some financial type details to the params list
79 // if folks need to use it
d9659858 80 //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
68642f9a 81 $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $financialType->name;
6a488035 82 //CRM-11456
874c9be7 83 $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($contributionTypeId);
6a488035 84 $paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
5fb28746 85 $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
6a488035 86
f1fc3638 87 //fix for CRM-16317
35cd38f5 88 $form->_params['receive_date'] = date('YmdHis');
f1fc3638 89 $form->assign('receive_date',
90 CRM_Utils_Date::mysqlToIso($form->_params['receive_date'])
91 );
5fb28746 92 if ($isPaymentTransaction) {
f6261e9d 93
3febe800 94 $contributionParams = array(
95 'contact_id' => $contactID,
96 'line_item' => $lineItems,
97 'is_test' => $isTest,
98 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams, CRM_Utils_Array::value('campaign_id', $form->_values)),
99 'contribution_page_id' => $form->_id,
100 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
101 );
102 $isMonetary = !empty($form->_values['is_monetary']);
103 if ($isMonetary) {
104 if (empty($paymentParams['is_pay_later'])) {
105 // @todo look up payment_instrument_id on payment processor table.
106 $contributionParams['payment_instrument_id'] = 1;
107 }
108 }
ba013eea 109 $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution(
6a488035
TO
110 $form,
111 $paymentParams,
112 NULL,
3febe800 113 $contributionParams,
68642f9a 114 $financialType,
5fb28746 115 TRUE,
449f4c90 116 $form->_bltID,
117 $isRecur
6a488035
TO
118 );
119
5fb28746
EM
120 $paymentParams['contributionTypeID'] = $contributionTypeId;
121 $paymentParams['item_name'] = $form->_params['description'];
6a488035 122
5fb28746 123 if ($contribution && $form->_values['is_recur'] && $contribution->contribution_recur_id
6a488035 124 ) {
5fb28746 125 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
6a488035 126 }
6a488035 127
5fb28746
EM
128 $paymentParams['qfKey'] = $form->controller->_key;
129 if ($component == 'membership') {
130 return array('contribution' => $contribution);
6a488035 131 }
06d062ce 132
5fb28746
EM
133 $paymentParams['contributionID'] = $contribution->id;
134 //CRM-15297 deprecate contributionTypeID
135 $paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
136 $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
137 if (isset($paymentParams['contribution_source'])) {
138 $paymentParams['source'] = $paymentParams['contribution_source'];
6a488035 139 }
6a488035 140
5fb28746
EM
141 if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
142 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
6a488035
TO
143 }
144
510fa17f 145 if (!empty($form->_paymentProcessor)) {
5fb28746
EM
146 try {
147 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
148 if ($form->_contributeMode == 'notify') {
149 // We want to get rid of this & make it generic - eg. by making payment processing the last thing
150 // and always calling it first.
151 $form->postProcessHook();
152 }
153 $result = $payment->doPayment($paymentParams);
154 $form->_params = array_merge($form->_params, $result);
155 $form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
156 if (!empty($result['trxn_id'])) {
157 $contribution->trxn_id = $result['trxn_id'];
158 }
159 if (!empty($result['payment_status_id'])) {
160 $contribution->payment_status_id = $result['payment_status_id'];
161 }
162 $result['contribution'] = $contribution;
163 return $result;
68e61ad6 164 }
5fb28746
EM
165 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
166 // Clean up DB as appropriate.
167 if (!empty($paymentParams['contributionID'])) {
168 CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'],
169 $paymentParams['contactID'], $e->getMessage());
170 }
171 if (!empty($paymentParams['contributionRecurID'])) {
172 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
173 }
174
175 $result['is_payment_failure'] = TRUE;
176 $result['error'] = $e;
177 return $result;
68e61ad6 178 }
a7a33651 179 }
6a488035 180 }
222a33ae 181
5fb28746
EM
182 // Only pay later or unpaid should reach this point. The theory is that paylater should get a receipt now &
183 // processor
184 // transaction receipts should be outcome driven.
185 $form->set('params', $form->_params);
186 if (isset($paymentParams['contribution_source'])) {
187 $form->_params['source'] = $paymentParams['contribution_source'];
6a488035
TO
188 }
189
190 // get the price set values for receipt.
191 if ($form->_priceSetId && $form->_lineItem) {
192 $form->_values['lineItem'] = $form->_lineItem;
193 $form->_values['priceSetID'] = $form->_priceSetId;
194 }
195
5fb28746
EM
196 $form->_values['contribution_id'] = $contribution->id;
197 $form->_values['contribution_page_id'] = $contribution->contribution_page_id;
510fa17f 198 if ($form->_params['amount'] == 0) {
199 // This is kind of a back-up for pay-later $0 transactions.
200 // In other flows they pick up the manual processor & get dealt with above (I
201 // think that might be better...).
202 return array(
203 'payment_status_id' => 1,
204 'contribution' => $contribution,
205 'payment_processor_id' => 0,
206 );
207 }
5fb28746
EM
208 CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
209 $form->_values,
210 $contribution->is_test
211 );
6a488035
TO
212 }
213
cc789d46
EM
214 /**
215 * Is a payment being made.
216 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
217 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
c490a46a 218 * @param CRM_Core_Form $form
cc789d46
EM
219 *
220 * @return bool
221 */
222 static protected function isPaymentTransaction($form) {
22e263ad 223 if (!empty($form->_values['is_monetary']) && $form->_amount >= 0.0) {
cc789d46
EM
224 return TRUE;
225 }
226 return FALSE;
227
228 }
353ffa53 229
6a488035 230 /**
3c536a11 231 * Get the contribution details by month of the year.
6a488035 232 *
014c4014
TO
233 * @param int $param
234 * Year.
6a488035 235 *
a6c01b45
CW
236 * @return array
237 * associated array
6a488035 238 */
00be9182 239 public static function contributionChartMonthly($param) {
6a488035
TO
240 if ($param) {
241 $param = array(1 => array($param, 'Integer'));
242 }
243 else {
244 $param = date("Y");
245 $param = array(1 => array($param, 'Integer'));
246 }
247
248 $query = "
249 SELECT sum(contrib.total_amount) AS ctAmt,
250 MONTH( contrib.receive_date) AS contribMonth
251 FROM civicrm_contribution AS contrib
252INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
253 WHERE contrib.contact_id = contact.id
254 AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
255 AND contrib.contribution_status_id = 1
256 AND date_format(contrib.receive_date,'%Y') = %1
257 AND contact.is_deleted = 0
258 GROUP BY contribMonth
259 ORDER BY month(contrib.receive_date)";
260
261 $dao = CRM_Core_DAO::executeQuery($query, $param);
262
263 $params = NULL;
264 while ($dao->fetch()) {
265 if ($dao->contribMonth) {
266 $params['By Month'][$dao->contribMonth] = $dao->ctAmt;
267 }
268 }
269 return $params;
270 }
271
272 /**
fe482240 273 * Get the contribution details by year.
6a488035 274 *
a6c01b45
CW
275 * @return array
276 * associated array
6a488035 277 */
00be9182 278 public static function contributionChartYearly() {
6a488035
TO
279 $config = CRM_Core_Config::singleton();
280 $yearClause = "year(contrib.receive_date) as contribYear";
281 if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
a48278eb
KJ
282 $yearClause = "CASE
283 WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart['M'] . "
f813f78e 284 && DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart['d'] . " )
a48278eb
KJ
285 THEN
286 concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
287 ELSE
288 concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
289 END AS contribYear";
6a488035
TO
290 }
291
292 $query = "
293 SELECT sum(contrib.total_amount) AS ctAmt,
294 {$yearClause}
295 FROM civicrm_contribution AS contrib
296INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
297 WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
298 AND contrib.contribution_status_id = 1
299 AND contact.is_deleted = 0
300 GROUP BY contribYear
301 ORDER BY contribYear";
302 $dao = CRM_Core_DAO::executeQuery($query);
303
304 $params = NULL;
305 while ($dao->fetch()) {
306 if (!empty($dao->contribYear)) {
307 $params['By Year'][$dao->contribYear] = $dao->ctAmt;
308 }
309 }
310 return $params;
311 }
312
186c9c17 313 /**
c490a46a 314 * @param array $params
100fef9d 315 * @param int $contactID
186c9c17
EM
316 * @param $mail
317 */
00be9182 318 public static function createCMSUser(&$params, $contactID, $mail) {
6a488035
TO
319 // lets ensure we only create one CMS user
320 static $created = FALSE;
321
322 if ($created) {
323 return;
324 }
325 $created = TRUE;
326
a7488080 327 if (!empty($params['cms_create_account'])) {
6a488035
TO
328 $params['contactID'] = $contactID;
329 if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
330 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
331 }
332 }
333 }
334
186c9c17 335 /**
c490a46a 336 * @param array $params
186c9c17
EM
337 * @param string $type
338 *
339 * @return bool
340 */
00be9182 341 public static function _fillCommonParams(&$params, $type = 'paypal') {
6a488035
TO
342 if (array_key_exists('transaction', $params)) {
343 $transaction = &$params['transaction'];
344 }
345 else {
346 $transaction = &$params;
347 }
348
349 $params['contact_type'] = 'Individual';
350
351 $billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
352 if (!$billingLocTypeId) {
353 $billingLocTypeId = 1;
354 }
355 if (!CRM_Utils_System::isNull($params['address'])) {
356 $params['address'][1]['is_primary'] = 1;
357 $params['address'][1]['location_type_id'] = $billingLocTypeId;
358 }
359 if (!CRM_Utils_System::isNull($params['email'])) {
360 $params['email'] = array(
874c9be7 361 1 => array(
353ffa53 362 'email' => $params['email'],
6a488035 363 'location_type_id' => $billingLocTypeId,
ae5ffbb7 364 ),
353ffa53 365 );
6a488035
TO
366 }
367
368 if (isset($transaction['trxn_id'])) {
369 // set error message if transaction has already been processed.
370 $contribution = new CRM_Contribute_DAO_Contribution();
371 $contribution->trxn_id = $transaction['trxn_id'];
372 if ($contribution->find(TRUE)) {
373 $params['error'][] = ts('transaction already processed.');
374 }
375 }
376 else {
377 // generate a new transaction id, if not already exist
378 $transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
379 }
380
481a74f4 381 if (!isset($transaction['financial_type_id'])) {
6a488035
TO
382 $contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
383 $transaction['financial_type_id'] = $contributionTypes[0];
384 }
385
386 if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
387 $transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
388 }
389
390 if (!isset($transaction['invoice_id'])) {
391 $transaction['invoice_id'] = $transaction['trxn_id'];
392 }
393
394 $source = ts('ContributionProcessor: %1 API',
395 array(1 => ucfirst($type))
396 );
397 if (isset($transaction['source'])) {
398 $transaction['source'] = $source . ':: ' . $transaction['source'];
399 }
400 else {
401 $transaction['source'] = $source;
402 }
403
404 return TRUE;
405 }
406
186c9c17 407 /**
100fef9d 408 * @param int $contactID
186c9c17
EM
409 *
410 * @return mixed
411 */
00be9182 412 public static function getFirstLastDetails($contactID) {
6a488035
TO
413 static $_cache;
414
415 if (!$_cache) {
416 $_cache = array();
417 }
418
419 if (!isset($_cache[$contactID])) {
420 $sql = "
421SELECT total_amount, receive_date
422FROM civicrm_contribution c
423WHERE contact_id = %1
424ORDER BY receive_date ASC
425LIMIT 1
426";
427 $params = array(1 => array($contactID, 'Integer'));
428
429 $dao = CRM_Core_DAO::executeQuery($sql, $params);
430 $details = array(
431 'first' => NULL,
432 'last' => NULL,
433 );
434 if ($dao->fetch()) {
435 $details['first'] = array(
436 'total_amount' => $dao->total_amount,
437 'receive_date' => $dao->receive_date,
438 );
439 }
440
441 // flip asc and desc to get the last query
442 $sql = str_replace('ASC', 'DESC', $sql);
443 $dao = CRM_Core_DAO::executeQuery($sql, $params);
444 if ($dao->fetch()) {
445 $details['last'] = array(
446 'total_amount' => $dao->total_amount,
447 'receive_date' => $dao->receive_date,
448 );
449 }
450
451 $_cache[$contactID] = $details;
452 }
453 return $_cache[$contactID];
454 }
9d1c9154 455
456 /**
457 * Calculate the tax amount based on given tax rate.
458 *
014c4014
TO
459 * @param float $amount
460 * Amount of field.
461 * @param float $taxRate
462 * Tax rate of selected financial account for field.
9d1c9154 463 *
a6c01b45
CW
464 * @return array
465 * array of tax amount
9d1c9154 466 *
9d1c9154 467 */
468 public static function calculateTaxAmount($amount, $taxRate) {
469 $taxAmount = array();
c21d6df8 470 $taxAmount['tax_amount'] = round(($taxRate / 100) * CRM_Utils_Rule::cleanMoney($amount), 2);
9d1c9154 471
472 return $taxAmount;
473 }
96025800 474
6a488035 475}