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