Merge branch 4.5 into master
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35 class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
36
37 /**
38 * Static field for all the contribution information that we can potentially import
39 *
40 * @var array
41 */
42 static $_importableFields = NULL;
43
44 /**
45 * Static field for all the contribution information that we can potentially export
46 *
47 * @var array
48 */
49 static $_exportableFields = NULL;
50
51 /**
52 * Field for all the objects related to this contribution
53 * @var array of objects (e.g membership object, participant object)
54 */
55 public $_relatedObjects = array();
56
57 /**
58 * Field for the component - either 'event' (participant) or 'contribute'
59 * (any item related to a contribution page e.g. membership, pledge, contribution)
60 * This is used for composing messages because they have dependency on the
61 * contribution_page or event page - although over time we may eliminate that
62 *
63 * @var string component or event
64 */
65 public $_component = NULL;
66
67 /**
68 * Class constructor
69 *
70 * @return \CRM_Contribute_DAO_Contribution
71 */
72 /**
73 */
74 public function __construct() {
75 parent::__construct();
76 }
77
78 /**
79 * Takes an associative array and creates a contribution object
80 *
81 * the function extract all the params it needs to initialize the create a
82 * contribution object. the params array could contain additional unused name/value
83 * pairs
84 *
85 * @param array $params
86 * (reference ) an assoc array of name/value pairs.
87 * @param array $ids
88 * The array that holds all the db ids.
89 *
90 * @return CRM_Contribute_BAO_Contribution|void
91 */
92 public static function add(&$params, $ids = array()) {
93 if (empty($params)) {
94 return NULL;
95 }
96 //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array
97 $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params));
98 $duplicates = array();
99 if (self::checkDuplicate($params, $duplicates, $contributionID)) {
100 $error = CRM_Core_Error::singleton();
101 $d = implode(', ', $duplicates);
102 $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
103 'Fatal',
104 array($d),
105 "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d"
106 );
107 return $error;
108 }
109
110 // first clean up all the money fields
111 $moneyFields = array(
112 'total_amount',
113 'net_amount',
114 'fee_amount',
115 'non_deductible_amount',
116 );
117
118 //if priceset is used, no need to cleanup money
119 if (!empty($params['skipCleanMoney'])) {
120 unset($moneyFields[0]);
121 }
122
123 foreach ($moneyFields as $field) {
124 if (isset($params[$field])) {
125 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
126 }
127 }
128
129 //set defaults in create mode
130 if (!$contributionID) {
131 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
132 self::calculateMissingAmountParams($params);
133 }
134
135 if (!empty($params['payment_instrument_id'])) {
136 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name');
137 if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) {
138 $params['check_number'] = 'null';
139 }
140 }
141
142 $setPrevContribution = TRUE;
143 // CRM-13964 partial payment
144 if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) {
145 $partialAmtTotal = $params['partial_payment_total'];
146 $partialAmtPay = $params['partial_amount_pay'];
147 $params['total_amount'] = $partialAmtTotal;
148 if ($partialAmtPay < $partialAmtTotal) {
149 $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name');
150 $params['is_pay_later'] = 0;
151 $setPrevContribution = FALSE;
152 }
153 }
154
155 if ($contributionID) {
156 CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params);
157 }
158 else {
159 CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params);
160 }
161 $contribution = new CRM_Contribute_BAO_Contribution();
162 $contribution->copyValues($params);
163
164 $contribution->id = $contributionID;
165
166 if (!CRM_Utils_Rule::currencyCode($contribution->currency)) {
167 $config = CRM_Core_Config::singleton();
168 $contribution->currency = $config->defaultCurrency;
169 }
170
171 if ($contributionID && $setPrevContribution) {
172 $params['prevContribution'] = self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
173 }
174
175 $result = $contribution->save();
176
177 // Add financial_trxn details as part of fix for CRM-4724
178 $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params);
179 $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params);
180
181 //add Account details
182 $params['contribution'] = $contribution;
183 self::recordFinancialAccounts($params);
184
185 // reset the group contact cache for this group
186 CRM_Contact_BAO_GroupContactCache::remove();
187
188 if ($contributionID) {
189 CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution);
190 }
191 else {
192 CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution);
193 }
194
195 return $result;
196 }
197
198 /**
199 * Get defaults for new entity
200 * @return array
201 */
202 public static function getDefaults() {
203 return array(
204 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument',
205 FALSE, FALSE, FALSE, 'AND is_default = 1')
206 ),
207 'contribution_status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'),
208 );
209 }
210
211 /**
212 * Given the list of params in the params array, fetch the object
213 * and store the values in the values array
214 *
215 * @param array $params
216 * Input parameters to find object.
217 * @param array $values
218 * Output values of the object.
219 * @param array $ids
220 * The array that holds all the db ids.
221 *
222 * @return CRM_Contribute_BAO_Contribution|null the found object or null
223 */
224 public static function &getValues($params, &$values, &$ids) {
225 if (empty($params)) {
226 return NULL;
227 }
228 $contribution = new CRM_Contribute_BAO_Contribution();
229
230 $contribution->copyValues($params);
231
232 if ($contribution->find(TRUE)) {
233 $ids['contribution'] = $contribution->id;
234
235 CRM_Core_DAO::storeValues($contribution, $values);
236
237 return $contribution;
238 }
239 $null = NULL; // return by reference
240 return $null;
241 }
242
243 /**
244 * @param array $params
245 *
246 * @return mixed
247 */
248 public static function calculateMissingAmountParams(&$params) {
249 if (!isset($params['fee_amount'])) {
250 if (isset($params['total_amount']) && isset($params['net_amount'])) {
251 $params['fee_amount'] = $params['total_amount'] - $params['net_amount'];
252 }
253 else {
254 $params['fee_amount'] = 0;
255 }
256 }
257 if (!isset($params['net_amount'])) {
258 $params['net_amount'] = $params['total_amount'] - $params['fee_amount'];
259 }
260 }
261
262 /**
263 * Get the number of terms for this contribution for a given membership type
264 * based on querying the line item table and relevant price field values
265 * Note that any one contribution should only be able to have one line item relating to a particular membership
266 * type
267 *
268 * @param int $membershipTypeID
269 *
270 * @param int $contributionID
271 *
272 * @return int
273 */
274 public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) {
275 $numTerms = CRM_Core_DAO::singleValueQuery("
276 SELECT membership_num_terms FROM civicrm_line_item li
277 LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id
278 WHERE contribution_id = %1 AND membership_type_id = %2",
279 array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer'))
280 );
281 // default of 1 is precautionary
282 return empty($numTerms) ? 1 : $numTerms;
283 }
284
285 /**
286 * Takes an associative array and creates a contribution object
287 *
288 * @param array $params
289 * (reference ) an assoc array of name/value pairs.
290 * @param array $ids
291 * The array that holds all the db ids.
292 *
293 * @return CRM_Contribute_BAO_Contribution
294 */
295 public static function create(&$params, $ids = array()) {
296 $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
297 foreach ($dateFields as $df) {
298 if (isset($params[$df])) {
299 $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
300 }
301 }
302
303 $transaction = new CRM_Core_Transaction();
304
305 $contribution = self::add($params, $ids);
306
307 if (is_a($contribution, 'CRM_Core_Error')) {
308 $transaction->rollback();
309 return $contribution;
310 }
311
312 $params['contribution_id'] = $contribution->id;
313
314 if (!empty($params['custom']) &&
315 is_array($params['custom'])
316 ) {
317 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
318 }
319
320 $session = CRM_Core_Session::singleton();
321
322 if (!empty($params['note'])) {
323 $noteParams = array(
324 'entity_table' => 'civicrm_contribution',
325 'note' => $params['note'],
326 'entity_id' => $contribution->id,
327 'contact_id' => $session->get('userID'),
328 'modified_date' => date('Ymd'),
329 );
330 if (!$noteParams['contact_id']) {
331 $noteParams['contact_id'] = $params['contact_id'];
332 }
333 CRM_Core_BAO_Note::add($noteParams);
334 }
335
336 // make entry in batch entity batch table
337 if (!empty($params['batch_id'])) {
338 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
339 $titleFields = array(
340 'contact_id',
341 'total_amount',
342 'currency',
343 'financial_type_id',
344 );
345 $retrieveRequired = 0;
346 foreach ($titleFields as $titleField) {
347 if (!isset($contribution->$titleField)) {
348 $retrieveRequired = 1;
349 break;
350 }
351 }
352 if ($retrieveRequired == 1) {
353 $contribution->find(TRUE);
354 }
355 }
356
357 // check if activity record exist for this contribution, if
358 // not add activity
359 $activity = new CRM_Activity_DAO_Activity();
360 $activity->source_record_id = $contribution->id;
361 $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
362 'Contribution',
363 'name'
364 );
365 if (!$activity->find(TRUE)) {
366 CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
367 }
368 else {
369 // CRM-13237 : if activity record found, update it with campaign id of contribution
370 CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
371 }
372
373 // Handle soft credit and / or link to personal campaign page
374 $softIDs = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id);
375
376 //Delete PCP against this contribution and create new on submitted PCP information
377 $pcpId = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id, TRUE);
378 if ($pcpId) {
379 $deleteParams = array('id' => $pcpId);
380 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
381 }
382 if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
383 $softParams = array();
384 $softParams['contribution_id'] = $contribution->id;
385 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
386 $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
387 $pcp['pcp_made_through_id'], 'contact_id'
388 );
389 $softParams['currency'] = $contribution->currency;
390 $softParams['amount'] = $contribution->total_amount;
391 $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
392 $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
393 $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
394 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
395 $contributionSoft = CRM_Contribute_BAO_ContributionSoft::add($softParams);
396 //Send notification to owner for PCP
397 if ($contributionSoft->pcp_id) {
398 CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
399 }
400 }
401 if (isset($params['soft_credit'])) {
402 $softParams = $params['soft_credit'];
403
404 if (!empty($softIDs)) {
405 foreach ($softIDs as $softID) {
406 if (!in_array($softID, $params['soft_credit_ids'])) {
407 $deleteParams = array('id' => $softID);
408 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
409 }
410 }
411 }
412
413 foreach ($softParams as $softParam) {
414 $softParam['contribution_id'] = $contribution->id;
415 $softParam['currency'] = $contribution->currency;
416 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
417 if (empty($softParam['amount'])) {
418 $softParam['amount'] = $contribution->total_amount;
419 }
420 CRM_Contribute_BAO_ContributionSoft::add($softParam);
421 }
422 }
423
424 $transaction->commit();
425
426 // do not add to recent items for import, CRM-4399
427 if (empty($params['skipRecentView'])) {
428 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
429 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
430 );
431 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
432 $titleFields = array(
433 'contact_id',
434 'total_amount',
435 'currency',
436 'financial_type_id',
437 );
438 $retrieveRequired = 0;
439 foreach ($titleFields as $titleField) {
440 if (!isset($contribution->$titleField)) {
441 $retrieveRequired = 1;
442 break;
443 }
444 }
445 if ($retrieveRequired == 1) {
446 $contribution->find(TRUE);
447 }
448 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
449 $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
450
451 $recentOther = array();
452 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
453 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
454 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
455 );
456 }
457
458 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
459 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
460 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
461 );
462 }
463
464 // add the recently created Contribution
465 CRM_Utils_Recent::add($title,
466 $url,
467 $contribution->id,
468 'Contribution',
469 $contribution->contact_id,
470 NULL,
471 $recentOther
472 );
473 }
474
475 return $contribution;
476 }
477
478 /**
479 * Get the values for pseudoconstants for name->value and reverse.
480 *
481 * @param array $defaults
482 * (reference) the default values, some of which need to be resolved.
483 * @param bool $reverse
484 * True if we want to resolve the values in the reverse direction (value -> name).
485 *
486 * @return void
487 */
488 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
489 self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
490 self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
491 self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse);
492 self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
493 }
494
495 /**
496 * convert associative array names to values
497 * and vice-versa.
498 *
499 * This function is used by both the web form layer and the api. Note that
500 * the api needs the name => value conversion, also the view layer typically
501 * requires value => name conversion
502 */
503 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
504 $id = $property . '_id';
505
506 $src = $reverse ? $property : $id;
507 $dst = $reverse ? $id : $property;
508
509 if (!array_key_exists($src, $defaults)) {
510 return FALSE;
511 }
512
513 $look = $reverse ? array_flip($lookup) : $lookup;
514
515 if (is_array($look)) {
516 if (!array_key_exists($defaults[$src], $look)) {
517 return FALSE;
518 }
519 }
520 $defaults[$dst] = $look[$defaults[$src]];
521 return TRUE;
522 }
523
524 /**
525 * Takes a bunch of params that are needed to match certain criteria and
526 * retrieves the relevant objects. We'll tweak this function to be more
527 * full featured over a period of time. This is the inverse function of
528 * create. It also stores all the retrieved values in the default array
529 *
530 * @param array $params
531 * (reference ) an assoc array of name/value pairs.
532 * @param array $defaults
533 * (reference ) an assoc array to hold the name / value pairs.
534 * in a hierarchical manner
535 * @param array $ids
536 * (reference) the array that holds all the db ids.
537 *
538 * @return CRM_Contribute_BAO_Contribution
539 */
540 public static function retrieve(&$params, &$defaults, &$ids) {
541 $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
542 return $contribution;
543 }
544
545 /**
546 * Combine all the importable fields from the lower levels object
547 *
548 * The ordering is important, since currently we do not have a weight
549 * scheme. Adding weight is super important and should be done in the
550 * next week or so, before this can be called complete.
551 *
552 * @param string $contactType
553 * @param bool $status
554 *
555 * @return array
556 * array of importable Fields
557 */
558 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
559 if (!self::$_importableFields) {
560 if (!self::$_importableFields) {
561 self::$_importableFields = array();
562 }
563
564 if (!$status) {
565 $fields = array('' => array('title' => ts('- do not import -')));
566 }
567 else {
568 $fields = array('' => array('title' => ts('- Contribution Fields -')));
569 }
570
571 $note = CRM_Core_DAO_Note::import();
572 $tmpFields = CRM_Contribute_DAO_Contribution::import();
573 unset($tmpFields['option_value']);
574 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
575 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
576
577 // Using new Dedupe rule.
578 $ruleParams = array(
579 'contact_type' => $contactType,
580 'used' => 'Unsupervised',
581 );
582 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
583 $tmpContactField = array();
584 if (is_array($fieldsArray)) {
585 foreach ($fieldsArray as $value) {
586 //skip if there is no dupe rule
587 if ($value == 'none') {
588 continue;
589 }
590 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
591 $value,
592 'id',
593 'column_name'
594 );
595 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
596 $tmpContactField[trim($value)] = $contactFields[trim($value)];
597 if (!$status) {
598 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
599 }
600 else {
601 $title = $tmpContactField[trim($value)]['title'];
602 }
603 $tmpContactField[trim($value)]['title'] = $title;
604 }
605 }
606
607 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
608 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
609 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
610 $fields = array_merge($fields, $tmpContactField);
611 $fields = array_merge($fields, $tmpFields);
612 $fields = array_merge($fields, $note);
613 $fields = array_merge($fields, $optionFields);
614 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
615 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
616 self::$_importableFields = $fields;
617 }
618 return self::$_importableFields;
619 }
620
621 /**
622 * @return array
623 */
624 public static function &exportableFields() {
625 if (!self::$_exportableFields) {
626 if (!self::$_exportableFields) {
627 self::$_exportableFields = array();
628 }
629
630 $impFields = CRM_Contribute_DAO_Contribution::export();
631 $expFieldProduct = CRM_Contribute_DAO_Product::export();
632 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export();
633 $typeField = CRM_Financial_DAO_FinancialType::export();
634 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
635 $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute');
636 $contributionStatus = array(
637 'contribution_status' => array(
638 'title' => ts('Contribution Status'),
639 'name' => 'contribution_status',
640 'data_type' => CRM_Utils_Type::T_STRING,
641 ),
642 );
643
644 $contributionPage = array(
645 'contribution_page' => array(
646 'title' => ts('Contribution Page'),
647 'name' => 'contribution_page',
648 'where' => 'civicrm_contribution_page.title',
649 'data_type' => CRM_Utils_Type::T_STRING,
650 ),
651 );
652
653 $contributionNote = array(
654 'contribution_note' => array(
655 'title' => ts('Contribution Note'),
656 'name' => 'contribution_note',
657 'data_type' => CRM_Utils_Type::T_TEXT,
658 ),
659 );
660
661 $contributionRecurId = array(
662 'contribution_recur_id' => array(
663 'title' => ts('Recurring Contributions ID'),
664 'name' => 'contribution_recur_id',
665 'where' => 'civicrm_contribution.contribution_recur_id',
666 'data_type' => CRM_Utils_Type::T_INT,
667 ),
668 );
669
670 $extraFields = array(
671 'contribution_batch' => array(
672 'title' => ts('Batch Name'),
673 ),
674 );
675
676 $softCreditFields = array(
677 'contribution_soft_credit_name' => array(
678 'name' => 'contribution_soft_credit_name',
679 'title' => 'Soft Credit For',
680 'where' => 'civicrm_contact_d.display_name',
681 'data_type' => CRM_Utils_Type::T_STRING,
682 ),
683 'contribution_soft_credit_amount' => array(
684 'name' => 'contribution_soft_credit_amount',
685 'title' => 'Soft Credit Amount',
686 'where' => 'civicrm_contribution_soft.amount',
687 'data_type' => CRM_Utils_Type::T_MONEY,
688 ),
689 'contribution_soft_credit_type' => array(
690 'name' => 'contribution_soft_credit_type',
691 'title' => 'Soft Credit Type',
692 'where' => 'contribution_softcredit_type.label',
693 'data_type' => CRM_Utils_Type::T_STRING,
694 ),
695 'contribution_soft_credit_contribution_id' => array(
696 'name' => 'contribution_soft_credit_contribution_id',
697 'title' => 'Soft Credit For Contribution ID',
698 'where' => 'civicrm_contribution_soft.contribution_id',
699 'data_type' => CRM_Utils_Type::T_INT,
700 ),
701 );
702
703 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
704 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
705 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')
706 );
707
708 self::$_exportableFields = $fields;
709 }
710
711 return self::$_exportableFields;
712 }
713
714 /**
715 * @param null $status
716 * @param null $startDate
717 * @param null $endDate
718 *
719 * @return array|null
720 */
721 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
722 $where = array();
723 switch ($status) {
724 case 'Valid':
725 $where[] = 'contribution_status_id = 1';
726 break;
727
728 case 'Cancelled':
729 $where[] = 'contribution_status_id = 3';
730 break;
731 }
732
733 if ($startDate) {
734 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
735 }
736 if ($endDate) {
737 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
738 }
739
740 $whereCond = implode(' AND ', $where);
741
742 $query = "
743 SELECT sum( total_amount ) as total_amount,
744 count( civicrm_contribution.id ) as total_count,
745 currency
746 FROM civicrm_contribution
747 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
748 WHERE $whereCond
749 AND ( is_test = 0 OR is_test IS NULL )
750 AND contact.is_deleted = 0
751 GROUP BY currency
752 ";
753
754 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
755 $amount = array();
756 $count = 0;
757 while ($dao->fetch()) {
758 $count += $dao->total_count;
759 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
760 }
761 if ($count) {
762 return array(
763 'amount' => implode(', ', $amount),
764 'count' => $count,
765 );
766 }
767 return NULL;
768 }
769
770 /**
771 * Delete the indirect records associated with this contribution first
772 *
773 * @param int $id
774 *
775 * @return mixed|null
776 * $results no of deleted Contribution on success, false otherwise
777 */
778 public static function deleteContribution($id) {
779 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
780
781 $transaction = new CRM_Core_Transaction();
782
783 $results = NULL;
784 //delete activity record
785 $params = array(
786 'source_record_id' => $id,
787 // activity type id for contribution
788 'activity_type_id' => 6,
789 );
790
791 CRM_Activity_BAO_Activity::deleteActivity($params);
792
793 //delete billing address if exists for this contribution.
794 self::deleteAddress($id);
795
796 //update pledge and pledge payment, CRM-3961
797 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
798
799 // remove entry from civicrm_price_set_entity, CRM-5095
800 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
801 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
802 }
803 // cleanup line items.
804 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
805
806 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
807 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
808
809 if ($participantId) {
810 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
811 }
812 else {
813 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
814 }
815
816 //delete note.
817 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
818 $noteId = key($note);
819 if ($noteId) {
820 CRM_Core_BAO_Note::del($noteId, FALSE);
821 }
822
823 $dao = new CRM_Contribute_DAO_Contribution();
824 $dao->id = $id;
825
826 $results = $dao->delete();
827
828 $transaction->commit();
829
830 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
831
832 // delete the recently created Contribution
833 $contributionRecent = array(
834 'id' => $id,
835 'type' => 'Contribution',
836 );
837 CRM_Utils_Recent::del($contributionRecent);
838
839 return $results;
840 }
841
842 /**
843 * Check if there is a contribution with the same trxn_id or invoice_id
844 *
845 * @param array $input
846 * An assoc array of name/value pairs.
847 * @param array $duplicates
848 * (reference) store ids of duplicate contribs.
849 * @param int $id
850 *
851 * @return bool
852 * true if duplicate, false otherwise
853 */
854 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
855 if (!$id) {
856 $id = CRM_Utils_Array::value('id', $input);
857 }
858 $trxn_id = CRM_Utils_Array::value('trxn_id', $input);
859 $invoice_id = CRM_Utils_Array::value('invoice_id', $input);
860
861 $clause = array();
862 $input = array();
863
864 if ($trxn_id) {
865 $clause[] = "trxn_id = %1";
866 $input[1] = array($trxn_id, 'String');
867 }
868
869 if ($invoice_id) {
870 $clause[] = "invoice_id = %2";
871 $input[2] = array($invoice_id, 'String');
872 }
873
874 if (empty($clause)) {
875 return FALSE;
876 }
877
878 $clause = implode(' OR ', $clause);
879 if ($id) {
880 $clause = "( $clause ) AND id != %3";
881 $input[3] = array($id, 'Integer');
882 }
883
884 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
885 $dao = CRM_Core_DAO::executeQuery($query, $input);
886 $result = FALSE;
887 while ($dao->fetch()) {
888 $duplicates[] = $dao->id;
889 $result = TRUE;
890 }
891 return $result;
892 }
893
894 /**
895 * Takes an associative array and creates a contribution_product object
896 *
897 * the function extract all the params it needs to initialize the create a
898 * contribution_product object. the params array could contain additional unused name/value
899 * pairs
900 *
901 * @param array $params
902 * (reference) an assoc array of name/value pairs.
903 *
904 * @return CRM_Contribute_DAO_ContributionProduct
905 */
906 public static function addPremium(&$params) {
907 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
908 $contributionProduct->copyValues($params);
909 return $contributionProduct->save();
910 }
911
912 /**
913 * Get list of contribution fields for profile
914 * For now we only allow custom contribution fields to be in
915 * profile
916 *
917 * @param bool $addExtraFields
918 * True if special fields needs to be added.
919 *
920 * @return array
921 * the list of contribution fields
922 */
923 public static function getContributionFields($addExtraFields = TRUE) {
924 $contributionFields = CRM_Contribute_DAO_Contribution::export();
925 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
926
927 if ($addExtraFields) {
928 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
929 }
930
931 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
932
933 foreach ($contributionFields as $key => $var) {
934 if ($key == 'contribution_contact_id') {
935 continue;
936 }
937 elseif ($key == 'contribution_campaign_id') {
938 $var['title'] = ts('Campaign');
939 }
940 $fields[$key] = $var;
941 }
942
943 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
944 return $fields;
945 }
946
947 /**
948 * Add extra fields specific to contribtion
949 *
950 */
951 public static function getSpecialContributionFields() {
952 $extraFields = array(
953 'contribution_soft_credit_name' => array(
954 'name' => 'contribution_soft_credit_name',
955 'title' => 'Soft Credit Name',
956 'headerPattern' => '/^soft_credit_name$/i',
957 'where' => 'civicrm_contact_d.display_name',
958 ),
959 'contribution_soft_credit_email' => array(
960 'name' => 'contribution_soft_credit_email',
961 'title' => 'Soft Credit Email',
962 'headerPattern' => '/^soft_credit_email$/i',
963 'where' => 'soft_email.email',
964 ),
965 'contribution_soft_credit_phone' => array(
966 'name' => 'contribution_soft_credit_phone',
967 'title' => 'Soft Credit Phone',
968 'headerPattern' => '/^soft_credit_phone$/i',
969 'where' => 'soft_phone.phone',
970 ),
971 'contribution_soft_credit_contact_id' => array(
972 'name' => 'contribution_soft_credit_contact_id',
973 'title' => 'Soft Credit Contact ID',
974 'headerPattern' => '/^soft_credit_contact_id$/i',
975 'where' => 'civicrm_contribution_soft.contact_id',
976 ),
977 );
978
979 return $extraFields;
980 }
981
982 /**
983 * @param int $pageID
984 *
985 * @return array
986 */
987 public static function getCurrentandGoalAmount($pageID) {
988 $query = "
989 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
990 FROM civicrm_contribution_page p,
991 civicrm_contribution c
992 WHERE p.id = c.contribution_page_id
993 AND p.id = %1
994 AND c.cancel_date is null
995 GROUP BY p.id
996 ";
997
998 $config = CRM_Core_Config::singleton();
999 $params = array(1 => array($pageID, 'Integer'));
1000 $dao = CRM_Core_DAO::executeQuery($query, $params);
1001
1002 if ($dao->fetch()) {
1003 return array($dao->goal, $dao->total);
1004 }
1005 else {
1006 return array(NULL, NULL);
1007 }
1008 }
1009
1010 /**
1011 * Get list of contribution In Honor of contact Ids
1012 *
1013 * @param int $honorId
1014 * In Honor of Contact ID.
1015 *
1016 * @return array
1017 * list of contribution fields
1018 *
1019 */
1020 public static function getHonorContacts($honorId) {
1021 $params = array();
1022 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1023 $honorDAO->contact_id = $honorId;
1024 $honorDAO->find();
1025
1026 $type = CRM_Contribute_PseudoConstant::financialType();
1027
1028 while ($honorDAO->fetch()) {
1029 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1030 $contributionDAO->id = $honorDAO->contribution_id;
1031
1032 if ($contributionDAO->find(TRUE)) {
1033 $params[$contributionDAO->id]['honor_type'] = CRM_Core_OptionGroup::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id, 'value');
1034 $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id;
1035 $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name');
1036 $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id];
1037 $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id;
1038 $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency);
1039 $params[$contributionDAO->id]['source'] = $contributionDAO->source;
1040 $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date;
1041 $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id);
1042 }
1043 }
1044
1045 return $params;
1046 }
1047
1048 /**
1049 * Get the sort name of a contact for a particular contribution
1050 *
1051 * @param int $id
1052 * Id of the contribution.
1053 *
1054 * @return null|string
1055 * sort name of the contact if found
1056 */
1057 public static function sortName($id) {
1058 $id = CRM_Utils_Type::escape($id, 'Integer');
1059
1060 $query = "
1061 SELECT civicrm_contact.sort_name
1062 FROM civicrm_contribution, civicrm_contact
1063 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1064 AND civicrm_contribution.id = {$id}
1065 ";
1066 return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray);
1067 }
1068
1069 /**
1070 * @param int $contactID
1071 *
1072 * @return array
1073 */
1074 public static function annual($contactID) {
1075 if (is_array($contactID)) {
1076 $contactIDs = implode(',', $contactID);
1077 }
1078 else {
1079 $contactIDs = $contactID;
1080 }
1081
1082 $config = CRM_Core_Config::singleton();
1083 $startDate = $endDate = NULL;
1084
1085 $currentMonth = date('m');
1086 $currentDay = date('d');
1087 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1088 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1089 (int ) $config->fiscalYearStart['d'] > $currentDay
1090 )
1091 ) {
1092 $year = date('Y') - 1;
1093 }
1094 else {
1095 $year = date('Y');
1096 }
1097 $nextYear = $year + 1;
1098
1099 if ($config->fiscalYearStart) {
1100 if ($config->fiscalYearStart['M'] < 10) {
1101 $config->fiscalYearStart['M'] = '0' . $config->fiscalYearStart['M'];
1102 }
1103 if ($config->fiscalYearStart['d'] < 10) {
1104 $config->fiscalYearStart['d'] = '0' . $config->fiscalYearStart['d'];
1105 }
1106 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
1107 }
1108 else {
1109 $monthDay = '0101';
1110 }
1111 $startDate = "$year$monthDay";
1112 $endDate = "$nextYear$monthDay";
1113
1114 $query = "
1115 SELECT count(*) as count,
1116 sum(total_amount) as amount,
1117 avg(total_amount) as average,
1118 currency
1119 FROM civicrm_contribution b
1120 WHERE b.contact_id IN ( $contactIDs )
1121 AND b.contribution_status_id = 1
1122 AND b.is_test = 0
1123 AND b.receive_date >= $startDate
1124 AND b.receive_date < $endDate
1125 GROUP BY currency
1126 ";
1127 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1128 $count = 0;
1129 $amount = $average = array();
1130 while ($dao->fetch()) {
1131 if ($dao->count > 0 && $dao->amount > 0) {
1132 $count += $dao->count;
1133 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1134 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1135 }
1136 }
1137 if ($count > 0) {
1138 return array(
1139 $count,
1140 implode(',&nbsp;', $amount),
1141 implode(',&nbsp;', $average),
1142 );
1143 }
1144 return array(0, 0, 0);
1145 }
1146
1147 /**
1148 * Check if there is a contribution with the params passed in.
1149 * Used for trxn_id,invoice_id and contribution_id
1150 *
1151 * @param array $params
1152 * An assoc array of name/value pairs.
1153 *
1154 * @return array
1155 * contribution id if success else NULL
1156 */
1157 public static function checkDuplicateIds($params) {
1158 $dao = new CRM_Contribute_DAO_Contribution();
1159
1160 $clause = array();
1161 $input = array();
1162 foreach ($params as $k => $v) {
1163 if ($v) {
1164 $clause[] = "$k = '$v'";
1165 }
1166 }
1167 $clause = implode(' AND ', $clause);
1168 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1169 $dao = CRM_Core_DAO::executeQuery($query, $input);
1170
1171 while ($dao->fetch()) {
1172 $result = $dao->id;
1173 return $result;
1174 }
1175 return NULL;
1176 }
1177
1178 /**
1179 * Get the contribution details for component export
1180 *
1181 * @param int $exportMode
1182 * Export mode.
1183 * @param string $componentIds
1184 * Component ids.
1185 *
1186 * @return array
1187 * associated array
1188 *
1189 */
1190 public static function getContributionDetails($exportMode, $componentIds) {
1191 $paymentDetails = array();
1192 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1193
1194 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1195 $componentSelect = " civicrm_participant_payment.participant_id id";
1196 $additionalClause = "
1197 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1198 AND civicrm_participant_payment.participant_id {$componentClause} )
1199 ";
1200 }
1201 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1202 $componentSelect = " civicrm_membership_payment.membership_id id";
1203 $additionalClause = "
1204 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1205 AND civicrm_membership_payment.membership_id {$componentClause} )
1206 ";
1207 }
1208 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1209 $componentSelect = " civicrm_pledge_payment.id id";
1210 $additionalClause = "
1211 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1212 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1213 ";
1214 }
1215
1216 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1217 trxn_id, {$componentSelect}
1218 FROM civicrm_contribution
1219 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1220 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1221 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1222 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1223 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1224 AND option_group_contribution_status.id = contribution_status.option_group_id )
1225 {$additionalClause}
1226 ";
1227
1228 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1229
1230 while ($dao->fetch()) {
1231 $paymentDetails[$dao->id] = array(
1232 'total_amount' => $dao->total_amount,
1233 'contribution_status' => $dao->status,
1234 'receive_date' => $dao->receive_date,
1235 'pay_instru' => $dao->payment_instrument,
1236 'trxn_id' => $dao->trxn_id,
1237 );
1238 }
1239
1240 return $paymentDetails;
1241 }
1242
1243 /**
1244 * Create address associated with contribution record.
1245 *
1246 * @param array $params
1247 * @param int $billingLocationTypeID
1248 *
1249 * @return int
1250 * address id
1251 */
1252 public static function createAddress(&$params, $billingLocationTypeID) {
1253 $billingFields = array(
1254 'street_address',
1255 'city',
1256 'state_province_id',
1257 'postal_code',
1258 'country_id',
1259 );
1260
1261 //build address array
1262 $addressParams = array();
1263 $addressParams['location_type_id'] = $billingLocationTypeID;
1264 $addressParams['is_billing'] = 1;
1265
1266 $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params);
1267 $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params);
1268 $billingLastName = CRM_Utils_Array::value('billing_last_name', $params);
1269 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
1270
1271 foreach ($billingFields as $value) {
1272 $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params);
1273 }
1274
1275 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
1276
1277 return $address->id;
1278 }
1279
1280 /**
1281 * Delete billing address record related contribution
1282 *
1283 * @param int $contributionId
1284 * @param int $contactId
1285 *
1286 */
1287 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1288 $clauses = array();
1289 $contactJoin = NULL;
1290
1291 if ($contributionId) {
1292 $clauses[] = "cc.id = {$contributionId}";
1293 }
1294
1295 if ($contactId) {
1296 $clauses[] = "cco.id = {$contactId}";
1297 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1298 }
1299
1300 if (empty($clauses)) {
1301 CRM_Core_Error::fatal();
1302 }
1303
1304 $condition = implode(' OR ', $clauses);
1305
1306 $query = "
1307 SELECT ca.id
1308 FROM civicrm_address ca
1309 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1310 $contactJoin
1311 WHERE $condition
1312 ";
1313 $dao = CRM_Core_DAO::executeQuery($query);
1314
1315 while ($dao->fetch()) {
1316 $params = array('id' => $dao->id);
1317 CRM_Core_BAO_Block::blockDelete('Address', $params);
1318 }
1319 }
1320
1321 /**
1322 * This function check online pending contribution associated w/
1323 * Online Event Registration or Online Membership signup.
1324 *
1325 * @param int $componentId
1326 * Participant/membership id.
1327 * @param string $componentName
1328 * Event/Membership.
1329 *
1330 * @return int
1331 * pending contribution id.
1332 */
1333 public static function checkOnlinePendingContribution($componentId, $componentName) {
1334 $contributionId = NULL;
1335 if (!$componentId ||
1336 !in_array($componentName, array('Event', 'Membership'))
1337 ) {
1338 return $contributionId;
1339 }
1340
1341 if ($componentName == 'Event') {
1342 $idName = 'participant_id';
1343 $componentTable = 'civicrm_participant';
1344 $paymentTable = 'civicrm_participant_payment';
1345 $source = ts('Online Event Registration');
1346 }
1347
1348 if ($componentName == 'Membership') {
1349 $idName = 'membership_id';
1350 $componentTable = 'civicrm_membership';
1351 $paymentTable = 'civicrm_membership_payment';
1352 $source = ts('Online Contribution');
1353 }
1354
1355 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1356
1357 $query = "
1358 SELECT component.id as {$idName},
1359 componentPayment.contribution_id as contribution_id,
1360 contribution.source source,
1361 contribution.contribution_status_id as contribution_status_id,
1362 contribution.is_pay_later as is_pay_later
1363 FROM $componentTable component
1364 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1365 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1366 WHERE component.id = {$componentId}";
1367
1368 $dao = CRM_Core_DAO::executeQuery($query);
1369
1370 while ($dao->fetch()) {
1371 if ($dao->contribution_id &&
1372 $dao->is_pay_later &&
1373 $dao->contribution_status_id == $pendingStatusId &&
1374 strpos($dao->source, $source) !== FALSE
1375 ) {
1376 $contributionId = $dao->contribution_id;
1377 $dao->free();
1378 }
1379 }
1380
1381 return $contributionId;
1382 }
1383
1384 /**
1385 * Update contribution as well as related objects.
1386 */
1387 public static function transitionComponents($params, $processContributionObject = FALSE) {
1388 // get minimum required values.
1389 $contactId = CRM_Utils_Array::value('contact_id', $params);
1390 $componentId = CRM_Utils_Array::value('component_id', $params);
1391 $componentName = CRM_Utils_Array::value('componentName', $params);
1392 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1393 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1394
1395 // if we already processed contribution object pass previous status id.
1396 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1397
1398 $updateResult = array();
1399
1400 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1401
1402 // we process only ( Completed, Cancelled, or Failed ) contributions.
1403 if (!$contributionId ||
1404 !in_array($contributionStatusId, array(
1405 array_search('Completed', $contributionStatuses),
1406 array_search('Cancelled', $contributionStatuses),
1407 array_search('Failed', $contributionStatuses),
1408 ))
1409 ) {
1410 return $updateResult;
1411 }
1412
1413 if (!$componentName || !$componentId) {
1414 // get the related component details.
1415 $componentDetails = self::getComponentDetails($contributionId);
1416 }
1417 else {
1418 $componentDetails['contact_id'] = $contactId;
1419 $componentDetails['component'] = $componentName;
1420
1421 if ($componentName == 'event') {
1422 $componentDetails['participant'] = $componentId;
1423 }
1424 else {
1425 $componentDetails['membership'] = $componentId;
1426 }
1427 }
1428
1429 if (!empty($componentDetails['contact_id'])) {
1430 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1431 $contributionId,
1432 'contact_id'
1433 );
1434 }
1435
1436 // do check for required ids.
1437 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
1438 return $updateResult;
1439 }
1440
1441 //now we are ready w/ required ids, start processing.
1442
1443 $baseIPN = new CRM_Core_Payment_BaseIPN();
1444
1445 $input = $ids = $objects = array();
1446
1447 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1448 $ids['contribution'] = $contributionId;
1449 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1450 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1451 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1452 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1453 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1454 $ids['contributionRecur'] = NULL;
1455 $ids['contributionPage'] = NULL;
1456
1457 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1458 CRM_Core_Error::fatal();
1459 }
1460
1461 $memberships = &$objects['membership'];
1462 $participant = &$objects['participant'];
1463 $pledgePayment = &$objects['pledge_payment'];
1464 $contribution = &$objects['contribution'];
1465
1466 if ($pledgePayment) {
1467 $pledgePaymentIDs = array();
1468 foreach ($pledgePayment as $key => $object) {
1469 $pledgePaymentIDs[] = $object->id;
1470 }
1471 $pledgeID = $pledgePayment[0]->pledge_id;
1472 }
1473
1474 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1475
1476 if ($participant) {
1477 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1478 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1479 $participant->id,
1480 'status_id'
1481 );
1482 }
1483 // we might want to process contribution object.
1484 $processContribution = FALSE;
1485 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1486 if (is_array($memberships)) {
1487 foreach ($memberships as $membership) {
1488 if ($membership) {
1489 $membership->status_id = array_search('Cancelled', $membershipStatuses);
1490 $membership->save();
1491
1492 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1493 if ($processContributionObject) {
1494 $processContribution = TRUE;
1495 }
1496 }
1497 }
1498 }
1499
1500 if ($participant) {
1501 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1502 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1503
1504 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1505 if ($processContributionObject) {
1506 $processContribution = TRUE;
1507 }
1508 }
1509
1510 if ($pledgePayment) {
1511 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1512
1513 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1514 if ($processContributionObject) {
1515 $processContribution = TRUE;
1516 }
1517 }
1518 }
1519 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1520 if (is_array($memberships)) {
1521 foreach ($memberships as $membership) {
1522 if ($membership) {
1523 $membership->status_id = array_search('Expired', $membershipStatuses);
1524 $membership->save();
1525
1526 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1527 if ($processContributionObject) {
1528 $processContribution = TRUE;
1529 }
1530 }
1531 }
1532 }
1533 if ($participant) {
1534 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1535 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1536
1537 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1538 if ($processContributionObject) {
1539 $processContribution = TRUE;
1540 }
1541 }
1542
1543 if ($pledgePayment) {
1544 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1545
1546 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1547 if ($processContributionObject) {
1548 $processContribution = TRUE;
1549 }
1550 }
1551 }
1552 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1553
1554 // only pending contribution related object processed.
1555 if ($previousContriStatusId &&
1556 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1557 ) {
1558 // this is case when we already processed contribution object.
1559 return $updateResult;
1560 }
1561 elseif (!$previousContriStatusId &&
1562 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1563 ) {
1564 // this is case when we are going to process contribution object later.
1565 return $updateResult;
1566 }
1567
1568 if (is_array($memberships)) {
1569 foreach ($memberships as $membership) {
1570 if ($membership) {
1571 $format = '%Y%m%d';
1572
1573 //CRM-4523
1574 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1575 $membership->membership_type_id,
1576 $membership->is_test, $membership->id
1577 );
1578
1579 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1580 // this picks up membership type changes during renewals
1581 $sql = "
1582 SELECT membership_type_id
1583 FROM civicrm_membership_log
1584 WHERE membership_id=$membership->id
1585 ORDER BY id DESC
1586 LIMIT 1;";
1587 $dao = new CRM_Core_DAO();
1588 $dao->query($sql);
1589 if ($dao->fetch()) {
1590 if (!empty($dao->membership_type_id)) {
1591 $membership->membership_type_id = $dao->membership_type_id;
1592 $membership->save();
1593 }
1594 }
1595 // else fall back to using current membership type
1596 $dao->free();
1597
1598 // Figure out number of terms
1599 $numterms = 1;
1600 $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
1601 foreach ($lineitems as $lineitem) {
1602 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1603 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
1604
1605 // in case membership_num_terms comes through as null or zero
1606 $numterms = $numterms >= 1 ? $numterms : 1;
1607 break;
1608 }
1609 }
1610
1611 // CRM-15735-to update the membership status as per the contribution receive date
1612 if (!empty($params['receive_date'])) {
1613 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
1614 $membership->end_date,
1615 $membership->join_date,
1616 $params['receive_date'],
1617 FALSE,
1618 $membership->membership_type_id,
1619 (array) $membership
1620 );
1621 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
1622 $membership->save();
1623 }
1624
1625 if ($currentMembership) {
1626 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1627 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
1628 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1629 }
1630 else {
1631 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms);
1632 }
1633
1634 //get the status for membership.
1635 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1636 $dates['end_date'],
1637 $dates['join_date'],
1638 'today',
1639 TRUE,
1640 $membership->membership_type_id,
1641 (array) $membership
1642 );
1643
1644 $formattedParams = array(
1645 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1646 array_search('Current', $membershipStatuses)
1647 ),
1648 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1649 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1650 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1651 );
1652
1653 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
1654
1655 $membership->copyValues($formattedParams);
1656 $membership->save();
1657
1658 //updating the membership log
1659 $membershipLog = array();
1660 $membershipLog = $formattedParams;
1661 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1662 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
1663
1664 $membershipLog['start_date'] = $logStartDate;
1665 $membershipLog['membership_id'] = $membership->id;
1666 $membershipLog['modified_id'] = $membership->contact_id;
1667 $membershipLog['modified_date'] = date('Ymd');
1668 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1669
1670 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1671
1672 //update related Memberships.
1673 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
1674
1675 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1676 '%B %E%f, %Y'
1677 );
1678 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1679 if ($processContributionObject) {
1680 $processContribution = TRUE;
1681 }
1682
1683 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1684 }
1685 }
1686 }
1687
1688 if ($participant) {
1689 $updatedStatusId = array_search('Registered', $participantStatuses);
1690 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1691
1692 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1693 if ($processContributionObject) {
1694 $processContribution = TRUE;
1695 }
1696 }
1697
1698 if ($pledgePayment) {
1699 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1700
1701 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1702 if ($processContributionObject) {
1703 $processContribution = TRUE;
1704 }
1705 }
1706 }
1707
1708 // process contribution object.
1709 if ($processContribution) {
1710 $contributionParams = array();
1711 $fields = array(
1712 'contact_id',
1713 'total_amount',
1714 'receive_date',
1715 'is_test',
1716 'campaign_id',
1717 'payment_instrument_id',
1718 'trxn_id',
1719 'invoice_id',
1720 'financial_type_id',
1721 'contribution_status_id',
1722 'non_deductible_amount',
1723 'receipt_date',
1724 'check_number',
1725 );
1726 foreach ($fields as $field) {
1727 if (empty($params[$field])) {
1728 continue;
1729 }
1730 $contributionParams[$field] = $params[$field];
1731 }
1732
1733 $ids = array('contribution' => $contributionId);
1734 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1735 }
1736
1737 return $updateResult;
1738 }
1739
1740 /**
1741 * Returns all contribution related object ids.
1742 */
1743 public static function getComponentDetails($contributionId) {
1744 $componentDetails = $pledgePayment = array();
1745 if (!$contributionId) {
1746 return $componentDetails;
1747 }
1748
1749 $query = "
1750 SELECT c.id as contribution_id,
1751 c.contact_id as contact_id,
1752 mp.membership_id as membership_id,
1753 m.membership_type_id as membership_type_id,
1754 pp.participant_id as participant_id,
1755 p.event_id as event_id,
1756 pgp.id as pledge_payment_id
1757 FROM civicrm_contribution c
1758 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1759 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1760 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1761 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1762 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1763 WHERE c.id = $contributionId";
1764
1765 $dao = CRM_Core_DAO::executeQuery($query);
1766 $componentDetails = array();
1767
1768 while ($dao->fetch()) {
1769 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1770 $componentDetails['contact_id'] = $dao->contact_id;
1771 if ($dao->event_id) {
1772 $componentDetails['event'] = $dao->event_id;
1773 }
1774 if ($dao->participant_id) {
1775 $componentDetails['participant'] = $dao->participant_id;
1776 }
1777 if ($dao->membership_id) {
1778 if (!isset($componentDetails['membership'])) {
1779 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1780 }
1781 $componentDetails['membership'][] = $dao->membership_id;
1782 $componentDetails['membership_type'][] = $dao->membership_type_id;
1783 }
1784 if ($dao->pledge_payment_id) {
1785 $pledgePayment[] = $dao->pledge_payment_id;
1786 }
1787 }
1788
1789 if ($pledgePayment) {
1790 $componentDetails['pledge_payment'] = $pledgePayment;
1791 }
1792
1793 return $componentDetails;
1794 }
1795
1796 /**
1797 * @param int $contactId
1798 * @param bool $includeSoftCredit
1799 *
1800 * @return null|string
1801 */
1802 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1803 if (!$contactId) {
1804 return 0;
1805 }
1806
1807 $contactContributionsSQL = "
1808 SELECT contribution.id AS id
1809 FROM civicrm_contribution contribution
1810 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1811
1812 $contactSoftCreditContributionsSQL = "
1813 SELECT contribution.id
1814 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1815 ON ( contribution.id = softContribution.contribution_id )
1816 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1817 $query = "SELECT count( x.id ) count FROM ( ";
1818 $query .= $contactContributionsSQL;
1819
1820 if ($includeSoftCredit) {
1821 $query .= " UNION ";
1822 $query .= $contactSoftCreditContributionsSQL;
1823 }
1824
1825 $query .= ") x";
1826
1827 return CRM_Core_DAO::singleValueQuery($query);
1828 }
1829
1830 /**
1831 * Get individual id for onbehalf contribution
1832 *
1833 * @param int $contributionId
1834 * Contribution id.
1835 * @param int $contributorId
1836 * Contributor id.
1837 *
1838 * @return array
1839 * containing organization id and individual id
1840 */
1841 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1842
1843 $ids = array();
1844
1845 if (!$contributionId) {
1846 return $ids;
1847 }
1848
1849 // fetch contributor id if null
1850 if (!$contributorId) {
1851 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1852 $contributionId, 'contact_id'
1853 );
1854 }
1855
1856 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1857 $activityTypeId = array_search('Contribution', $activityTypeIds);
1858
1859 if ($activityTypeId && $contributorId) {
1860 $activityQuery = "
1861 SELECT civicrm_activity_contact.contact_id
1862 FROM civicrm_activity_contact
1863 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1864 WHERE civicrm_activity.activity_type_id = %1
1865 AND civicrm_activity.source_record_id = %2
1866 AND civicrm_activity_contact.record_type_id = %3
1867 ";
1868
1869 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1870 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1871
1872 $params = array(
1873 1 => array($activityTypeId, 'Integer'),
1874 2 => array($contributionId, 'Integer'),
1875 3 => array($sourceID, 'Integer'),
1876 );
1877
1878 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
1879
1880 // for on behalf contribution source is individual and contributor is organization
1881 if ($sourceContactId && $sourceContactId != $contributorId) {
1882 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
1883 // get rel type id for employee of relation
1884 foreach ($relationshipTypeIds as $id => $typeVals) {
1885 if ($typeVals['name_a_b'] == 'Employee of') {
1886 $relationshipTypeId = $id;
1887 break;
1888 }
1889 }
1890
1891 $rel = new CRM_Contact_DAO_Relationship();
1892 $rel->relationship_type_id = $relationshipTypeId;
1893 $rel->contact_id_a = $sourceContactId;
1894 $rel->contact_id_b = $contributorId;
1895 if ($rel->find(TRUE)) {
1896 $ids['individual_id'] = $rel->contact_id_a;
1897 $ids['organization_id'] = $rel->contact_id_b;
1898 }
1899 }
1900 }
1901
1902 return $ids;
1903 }
1904
1905 /**
1906 * @return array
1907 */
1908 public static function getContributionDates() {
1909 $config = CRM_Core_Config::singleton();
1910 $currentMonth = date('m');
1911 $currentDay = date('d');
1912 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1913 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1914 (int ) $config->fiscalYearStart['d'] > $currentDay
1915 )
1916 ) {
1917 $year = date('Y') - 1;
1918 }
1919 else {
1920 $year = date('Y');
1921 }
1922 $year = array('Y' => $year);
1923 $yearDate = $config->fiscalYearStart;
1924 $yearDate = array_merge($year, $yearDate);
1925 $yearDate = CRM_Utils_Date::format($yearDate);
1926
1927 $monthDate = date('Ym') . '01';
1928
1929 $now = date('Ymd');
1930
1931 return array(
1932 'now' => $now,
1933 'yearDate' => $yearDate,
1934 'monthDate' => $monthDate,
1935 );
1936 }
1937
1938 /**
1939 * Load objects relations to contribution object
1940 * Objects are stored in the $_relatedObjects property
1941 * In the first instance we are just moving functionality from BASEIpn -
1942 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1943 *
1944 * Note that the unit test for the BaseIPN class tests this function
1945 *
1946 * @param array $input
1947 * Input as delivered from Payment Processor.
1948 * @param array $ids
1949 * Ids as Loaded by Payment Processor.
1950 * @param bool $required
1951 * Is Payment processor / contribution page required.
1952 * @param bool $loadAll
1953 * Load all related objects - even where id not passed in? (allows API to call this).
1954 *
1955 * @return bool
1956 * @throws Exception
1957 */
1958 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1959 if ($loadAll) {
1960 $ids = array_merge($this->getComponentDetails($this->id), $ids);
1961 if (empty($ids['contact']) && isset($this->contact_id)) {
1962 $ids['contact'] = $this->contact_id;
1963 }
1964 }
1965 if (empty($this->_component)) {
1966 if (!empty($ids['event'])) {
1967 $this->_component = 'event';
1968 }
1969 else {
1970 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
1971 }
1972 }
1973 $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
1974 $contributionType = new CRM_Financial_BAO_FinancialType();
1975 $contributionType->id = $this->financial_type_id;
1976 if (!$contributionType->find(TRUE)) {
1977 throw new Exception("Could not find financial type record: " . $this->financial_type_id);
1978 }
1979 if (!empty($ids['contact'])) {
1980 $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
1981 $this->_relatedObjects['contact']->id = $ids['contact'];
1982 $this->_relatedObjects['contact']->find(TRUE);
1983 }
1984 $this->_relatedObjects['contributionType'] = $contributionType;
1985
1986 if ($this->_component == 'contribute') {
1987 // retrieve the other optional objects first so
1988 // stuff down the line can use this info and do things
1989 // CRM-6056
1990 //in any case get the memberships associated with the contribution
1991 //because we now support multiple memberships w/ price set
1992 // see if there are any other memberships to be considered for same contribution.
1993 $query = "
1994 SELECT membership_id
1995 FROM civicrm_membership_payment
1996 WHERE contribution_id = %1 ";
1997 $params = array(1 => array($this->id, 'Integer'));
1998
1999 $dao = CRM_Core_DAO::executeQuery($query, $params);
2000 while ($dao->fetch()) {
2001 if ($dao->membership_id) {
2002 if (!is_array($ids['membership'])) {
2003 $ids['membership'] = array();
2004 }
2005 $ids['membership'][] = $dao->membership_id;
2006 }
2007 }
2008
2009 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2010 foreach ($ids['membership'] as $id) {
2011 if (!empty($id)) {
2012 $membership = new CRM_Member_BAO_Membership();
2013 $membership->id = $id;
2014 if (!$membership->find(TRUE)) {
2015 throw new Exception("Could not find membership record: $id");
2016 }
2017 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
2018 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
2019 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
2020 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
2021 $membership->free();
2022 }
2023 }
2024 }
2025
2026 if (!empty($ids['pledge_payment'])) {
2027
2028 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2029 if (empty($paymentID)) {
2030 continue;
2031 }
2032 $payment = new CRM_Pledge_BAO_PledgePayment();
2033 $payment->id = $paymentID;
2034 if (!$payment->find(TRUE)) {
2035 throw new Exception("Could not find pledge payment record: " . $paymentID);
2036 }
2037 $this->_relatedObjects['pledge_payment'][] = $payment;
2038 }
2039 }
2040
2041 if (!empty($ids['contributionRecur'])) {
2042 $recur = new CRM_Contribute_BAO_ContributionRecur();
2043 $recur->id = $ids['contributionRecur'];
2044 if (!$recur->find(TRUE)) {
2045 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2046 }
2047 $this->_relatedObjects['contributionRecur'] = &$recur;
2048 //get payment processor id from recur object.
2049 $paymentProcessorID = $recur->payment_processor_id;
2050 }
2051 //for normal contribution get the payment processor id.
2052 if (!$paymentProcessorID) {
2053 if ($this->contribution_page_id) {
2054 // get the payment processor id from contribution page
2055 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2056 $this->contribution_page_id,
2057 'payment_processor'
2058 );
2059 }
2060 //fail to load payment processor id.
2061 elseif (empty($ids['pledge_payment'])) {
2062 $loadObjectSuccess = TRUE;
2063 if ($required) {
2064 throw new Exception("Could not find contribution page for contribution record: " . $this->id);
2065 }
2066 return $loadObjectSuccess;
2067 }
2068 }
2069 }
2070 else {
2071 // we are in event mode
2072 // make sure event exists and is valid
2073 $event = new CRM_Event_BAO_Event();
2074 $event->id = $ids['event'];
2075 if ($ids['event'] &&
2076 !$event->find(TRUE)
2077 ) {
2078 throw new Exception("Could not find event: " . $ids['event']);
2079 }
2080
2081 $this->_relatedObjects['event'] = &$event;
2082
2083 $participant = new CRM_Event_BAO_Participant();
2084 $participant->id = $ids['participant'];
2085 if ($ids['participant'] &&
2086 !$participant->find(TRUE)
2087 ) {
2088 throw new Exception("Could not find participant: " . $ids['participant']);
2089 }
2090 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2091
2092 $this->_relatedObjects['participant'] = &$participant;
2093
2094 if (!$paymentProcessorID) {
2095 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2096 }
2097 }
2098
2099 if ($paymentProcessorID) {
2100 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2101 $this->is_test ? 'test' : 'live'
2102 );
2103 $ids['paymentProcessor'] = $paymentProcessorID;
2104 $this->_relatedObjects['paymentProcessor'] = &$paymentProcessor;
2105 }
2106 elseif ($required) {
2107 throw new Exception("Could not find payment processor for contribution record: " . $this->id);
2108 }
2109
2110 return TRUE;
2111 }
2112
2113 /**
2114 * Create array of message information - ie. return html version, txt version, to field
2115 *
2116 * @param array $input
2117 * Incoming information.
2118 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2119 * just check presence of recur object but maintaining legacy approach
2120 * to be careful)
2121 * @param array $ids
2122 * IDs of related objects.
2123 * @param array $values
2124 * Any values that may have already been compiled by calling process.
2125 * This is augmented by values 'gathered' by gatherMessageValues
2126 * @param bool $recur
2127 * @param bool $returnMessageText
2128 * Distinguishes between whether to send message or return.
2129 * message text. We are working towards this function ALWAYS returning message text & calling
2130 * function doing emails / pdfs with it
2131 *
2132 * @return array
2133 * messages
2134 * @throws Exception
2135 */
2136 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2137 if (empty($this->_relatedObjects)) {
2138 $this->loadRelatedObjects($input, $ids);
2139 }
2140 if (empty($this->_component)) {
2141 $this->_component = CRM_Utils_Array::value('component', $input);
2142 }
2143
2144 //not really sure what params might be passed in but lets merge em into values
2145 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2146 $template = CRM_Core_Smarty::singleton();
2147 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2148 //what does recur 'mean here - to do with payment processor return functionality but
2149 // what is the importance
2150 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2151 $paymentObject = &CRM_Core_Payment::singleton(
2152 $this->is_test ? 'test' : 'live',
2153 $this->_relatedObjects['paymentProcessor']
2154 );
2155
2156 $entityID = $entity = NULL;
2157 if (isset($ids['contribution'])) {
2158 $entity = 'contribution';
2159 $entityID = $ids['contribution'];
2160 }
2161 if (!empty($ids['membership'])) {
2162 //not sure whether is is possible for this not to be an array - load related contacts loads an array but this code was expecting a string
2163 // the addition of the casting is in case it could get here & be a string. Added in 4.6 - maybe remove later? This AuthorizeNetIPN & PaypalIPN tests hit this
2164 // line having loaded an array
2165 $ids['membership'] = (array) $ids['membership'];
2166 $entity = 'membership';
2167 $entityID = $ids['membership'][0];
2168 }
2169
2170 $url = $paymentObject->subscriptionURL($entityID, $entity);
2171 $template->assign('cancelSubscriptionUrl', $url);
2172
2173 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2174 $template->assign('updateSubscriptionBillingUrl', $url);
2175
2176 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2177 $template->assign('updateSubscriptionUrl', $url);
2178
2179 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2180 //direct mode showing billing block, so use directIPN for temporary
2181 $template->assign('contributeMode', 'directIPN');
2182 }
2183 }
2184 // todo remove strtolower - check consistency
2185 if (strtolower($this->_component) == 'event') {
2186 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2187 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2188 );
2189 }
2190 else {
2191 $values['contribution_id'] = $this->id;
2192 if (!empty($ids['related_contact'])) {
2193 $values['related_contact'] = $ids['related_contact'];
2194 if (isset($ids['onbehalf_dupe_alert'])) {
2195 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2196 }
2197 $entityBlock = array(
2198 'contact_id' => $ids['contact'],
2199 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2200 'Home', 'id', 'name'
2201 ),
2202 );
2203 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2204 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2205 }
2206 $isTest = FALSE;
2207 if ($this->is_test) {
2208 $isTest = TRUE;
2209 }
2210 if (!empty($this->_relatedObjects['membership'])) {
2211 foreach ($this->_relatedObjects['membership'] as $membership) {
2212 if ($membership->id) {
2213 $values['isMembership'] = TRUE;
2214
2215 // need to set the membership values here
2216 $template->assign('membership_assign', 1);
2217 $template->assign('membership_name',
2218 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2219 );
2220 $template->assign('mem_start_date', $membership->start_date);
2221 $template->assign('mem_join_date', $membership->join_date);
2222 $template->assign('mem_end_date', $membership->end_date);
2223 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2224 $template->assign('mem_status', $membership_status);
2225 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2226 $template->assign('is_pay_later', 1);
2227 }
2228
2229 // if separate payment there are two contributions recorded and the
2230 // admin will need to send a receipt for each of them separately.
2231 // we dont link the two in the db (but can potentially infer it if needed)
2232 $template->assign('is_separate_payment', 0);
2233
2234 if ($recur && $paymentObject) {
2235 $url = $paymentObject->subscriptionURL($membership->id, 'membership');
2236 $template->assign('cancelSubscriptionUrl', $url);
2237 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2238 $template->assign('updateSubscriptionBillingUrl', $url);
2239 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2240 $template->assign('updateSubscriptionUrl', $url);
2241 }
2242
2243 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2244
2245 return $result;
2246 // otherwise if its about sending emails, continue sending without return, as we
2247 // don't want to exit the loop.
2248 }
2249 }
2250 }
2251 else {
2252 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2253 }
2254 }
2255 }
2256
2257 /**
2258 * Gather values for contribution mail - this function has been created
2259 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2260 * Values related to the contribution in question are gathered
2261 *
2262 * @param array $input
2263 * Input into function (probably from payment processor).
2264 * @param array $values
2265 * @param array $ids
2266 * The set of ids related to the input.
2267 *
2268 * @return array
2269 */
2270 public function _gatherMessageValues($input, &$values, $ids = array()) {
2271 // set display address of contributor
2272 if ($this->address_id) {
2273 $addressParams = array('id' => $this->address_id);
2274 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2275 $addressDetails = array_values($addressDetails);
2276 $values['address'] = $addressDetails[0]['display'];
2277 }
2278 if ($this->_component == 'contribute') {
2279 if (isset($this->contribution_page_id)) {
2280 CRM_Contribute_BAO_ContributionPage::setValues(
2281 $this->contribution_page_id,
2282 $values
2283 );
2284 if ($this->contribution_page_id) {
2285 // CRM-8254 - override default currency if applicable
2286 $config = CRM_Core_Config::singleton();
2287 $config->defaultCurrency = CRM_Utils_Array::value(
2288 'currency',
2289 $values,
2290 $config->defaultCurrency
2291 );
2292 }
2293 }
2294 // no contribution page -probably back office
2295 else {
2296 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2297 $values['is_email_receipt'] = 1;
2298 $values['title'] = 'Contribution';
2299 }
2300 // set lineItem for contribution
2301 if ($this->id) {
2302 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2303 if (!empty($lineItem)) {
2304 $itemId = key($lineItem);
2305 foreach ($lineItem as &$eachItem) {
2306 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
2307 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2308 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2309 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2310 }
2311 }
2312 $values['lineItem'][0] = $lineItem;
2313 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2314 }
2315 }
2316
2317 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2318 $this->id,
2319 $this->contact_id
2320 );
2321 // if this is onbehalf of contribution then set related contact
2322 if (!empty($relatedContact['individual_id'])) {
2323 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2324 }
2325 }
2326 else {
2327 // event
2328 $eventParams = array(
2329 'id' => $this->_relatedObjects['event']->id,
2330 );
2331 $values['event'] = array();
2332
2333 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2334
2335 //get location details
2336 $locationParams = array(
2337 'entity_id' => $this->_relatedObjects['event']->id,
2338 'entity_table' => 'civicrm_event',
2339 );
2340 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2341
2342 $ufJoinParams = array(
2343 'entity_table' => 'civicrm_event',
2344 'entity_id' => $ids['event'],
2345 'module' => 'CiviEvent',
2346 );
2347
2348 list($custom_pre_id,
2349 $custom_post_ids
2350 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2351
2352 $values['custom_pre_id'] = $custom_pre_id;
2353 $values['custom_post_id'] = $custom_post_ids;
2354
2355 // set lineItem for event contribution
2356 if ($this->id) {
2357 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2358 if (!empty($participantIds)) {
2359 foreach ($participantIds as $pIDs) {
2360 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2361 if (!CRM_Utils_System::isNull($lineItem)) {
2362 $values['lineItem'][] = $lineItem;
2363 }
2364 }
2365 }
2366 }
2367 }
2368
2369 return $values;
2370 }
2371
2372 /**
2373 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2374 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2375 * Note we send directly from this function in some cases because it is only partly refactored
2376 * Don't call this function directly as the signature will change
2377 *
2378 * @param $values
2379 * @param $input
2380 * @param CRM_Core_SMARTY $template
2381 * @param bool $recur
2382 * @param bool $returnMessageText
2383 *
2384 * @return mixed
2385 */
2386 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2387 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2388 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2389 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2390 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
2391 $template->assign('useForMember', TRUE);
2392 }
2393 //assign honor information to receipt message
2394 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
2395
2396 if (isset($softRecord['soft_credit'])) {
2397 //if id of contribution page is present
2398 if (!empty($values['id'])) {
2399 $values['honor'] = array(
2400 'honor_profile_values' => array(),
2401 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2402 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2403 );
2404 $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
2405
2406 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2407 $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2408 }
2409 else {
2410 //offline contribution
2411 $softCreditTypes = $softCredits = array();
2412 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2413 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2414 $softCredits[$key] = array(
2415 'Name' => $softCredit['contact_name'],
2416 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
2417 );
2418 }
2419 $template->assign('softCreditTypes', $softCreditTypes);
2420 $template->assign('softCredits', $softCredits);
2421 }
2422 }
2423
2424 $dao = new CRM_Contribute_DAO_ContributionProduct();
2425 $dao->contribution_id = $this->id;
2426 if ($dao->find(TRUE)) {
2427 $premiumId = $dao->product_id;
2428 $template->assign('option', $dao->product_option);
2429
2430 $productDAO = new CRM_Contribute_DAO_Product();
2431 $productDAO->id = $premiumId;
2432 $productDAO->find(TRUE);
2433 $template->assign('selectPremium', TRUE);
2434 $template->assign('product_name', $productDAO->name);
2435 $template->assign('price', $productDAO->price);
2436 $template->assign('sku', $productDAO->sku);
2437 }
2438 $template->assign('title', CRM_Utils_Array::value('title', $values));
2439 $amount = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
2440 if (empty($amount) && isset($this->total_amount)) {
2441 $amount = $this->total_amount;
2442 }
2443 $template->assign('amount', $amount);
2444 // add the new contribution values
2445 if (strtolower($this->_component) == 'contribute') {
2446 //PCP Info
2447 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2448 $softDAO->contribution_id = $this->id;
2449 if ($softDAO->find(TRUE)) {
2450 $template->assign('pcpBlock', TRUE);
2451 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2452 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2453 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2454
2455 //assign the pcp page title for email subject
2456 $pcpDAO = new CRM_PCP_DAO_PCP();
2457 $pcpDAO->id = $softDAO->pcp_id;
2458 if ($pcpDAO->find(TRUE)) {
2459 $template->assign('title', $pcpDAO->title);
2460 }
2461 }
2462 }
2463
2464 if ($this->financial_type_id) {
2465 $values['financial_type_id'] = $this->financial_type_id;
2466 }
2467
2468 $template->assign('trxn_id', $this->trxn_id);
2469 $template->assign('receive_date',
2470 CRM_Utils_Date::mysqlToIso($this->receive_date)
2471 );
2472 $template->assign('contributeMode', 'notify');
2473 $template->assign('action', $this->is_test ? 1024 : 1);
2474 $template->assign('receipt_text',
2475 CRM_Utils_Array::value('receipt_text',
2476 $values
2477 )
2478 );
2479 $template->assign('is_monetary', 1);
2480 $template->assign('is_recur', (bool) $recur);
2481 $template->assign('currency', $this->currency);
2482 $template->assign('address', CRM_Utils_Address::format($input));
2483 if ($this->_component == 'event') {
2484 $template->assign('title', $values['event']['title']);
2485 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2486 $viewRoles = array();
2487 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2488 $viewRoles[] = $participantRoles[$v];
2489 }
2490 $values['event']['participant_role'] = implode(', ', $viewRoles);
2491 $template->assign('event', $values['event']);
2492 $template->assign('location', $values['location']);
2493 $template->assign('customPre', $values['custom_pre_id']);
2494 $template->assign('customPost', $values['custom_post_id']);
2495
2496 $isTest = FALSE;
2497 if ($this->_relatedObjects['participant']->is_test) {
2498 $isTest = TRUE;
2499 }
2500
2501 $values['params'] = array();
2502 //to get email of primary participant.
2503 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
2504 $primaryAmount[] = array(
2505 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
2506 'amount' => $this->_relatedObjects['participant']->fee_amount,
2507 );
2508 //build an array of cId/pId of participants
2509 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2510 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2511 //send receipt to additional participant if exists
2512 if (count($additionalIDs)) {
2513 $template->assign('isPrimary', 0);
2514 $template->assign('customProfile', NULL);
2515 //set additionalParticipant true
2516 $values['params']['additionalParticipant'] = TRUE;
2517 foreach ($additionalIDs as $pId => $cId) {
2518 $amount = array();
2519 //to change the status pending to completed
2520 $additional = new CRM_Event_DAO_Participant();
2521 $additional->id = $pId;
2522 $additional->contact_id = $cId;
2523 $additional->find(TRUE);
2524 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2525 $additional->status_id = 1;
2526 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2527 //if additional participant dont have email
2528 //use display name.
2529 if (!$additionalParticipantInfo) {
2530 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2531 }
2532 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
2533 $primaryAmount[] = array(
2534 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
2535 'amount' => $additional->fee_amount,
2536 );
2537 $additional->save();
2538 $additional->free();
2539 $template->assign('amount', $amount);
2540 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2541 }
2542 }
2543
2544 //build an array of custom profile and assigning it to template
2545 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2546
2547 if (count($customProfile)) {
2548 $template->assign('customProfile', $customProfile);
2549 }
2550
2551 // for primary contact
2552 $values['params']['additionalParticipant'] = FALSE;
2553 $template->assign('isPrimary', 1);
2554 $template->assign('amount', $primaryAmount);
2555 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2556 if ($this->payment_instrument_id) {
2557 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2558 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2559 }
2560 // carry paylater, since we did not created billing,
2561 // so need to pull email from primary location, CRM-4395
2562 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2563 }
2564 return $template;
2565 }
2566
2567 /**
2568 * Check whether payment processor supports
2569 * cancellation of contribution subscription
2570 *
2571 * @param int $contributionId
2572 * Contribution id.
2573 *
2574 * @param bool $isNotCancelled
2575 *
2576 * @return bool
2577 */
2578 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2579 $cacheKeyString = "$contributionId";
2580 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2581
2582 static $supportsCancel = array();
2583
2584 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2585 $supportsCancel[$cacheKeyString] = FALSE;
2586 $isCancelled = FALSE;
2587
2588 if ($isNotCancelled) {
2589 $isCancelled = self::isSubscriptionCancelled($contributionId);
2590 }
2591
2592 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2593 if (!empty($paymentObject)) {
2594 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2595 }
2596 }
2597 return $supportsCancel[$cacheKeyString];
2598 }
2599
2600 /**
2601 * Check whether subscription is already cancelled
2602 *
2603 * @param int $contributionId
2604 * Contribution id.
2605 *
2606 * @return string
2607 * contribution status
2608 */
2609 public static function isSubscriptionCancelled($contributionId) {
2610 $sql = "
2611 SELECT cr.contribution_status_id
2612 FROM civicrm_contribution_recur cr
2613 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2614 WHERE con.id = %1 LIMIT 1";
2615 $params = array(1 => array($contributionId, 'Integer'));
2616 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
2617 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
2618 if ($status == 'Cancelled') {
2619 return TRUE;
2620 }
2621 return FALSE;
2622 }
2623
2624 /**
2625 * Create all financial accounts entry
2626 *
2627 * @param array $params
2628 * Contribution object, line item array and params for trxn.
2629 *
2630 *
2631 * @param array $financialTrxnValues
2632 *
2633 * @return null|object
2634 */
2635 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2636 $skipRecords = $update = $return = $isRelatedId = FALSE;
2637
2638 $additionalParticipantId = array();
2639 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2640
2641 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
2642 $entityId = $params['participant_id'];
2643 $entityTable = 'civicrm_participant';
2644 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
2645 }
2646 elseif (!empty($params['membership_id'])) {
2647 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2648 // are created off one contribution should be handled elsewhere
2649 $entityId = $params['membership_id'];
2650 $entityTable = 'civicrm_membership';
2651 }
2652 else {
2653 $entityId = $params['contribution']->id;
2654 $entityTable = 'civicrm_contribution';
2655 }
2656
2657 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
2658 $isRelatedId = TRUE;
2659 }
2660
2661 $entityID[] = $entityId;
2662 if (!empty($additionalParticipantId)) {
2663 $entityID += $additionalParticipantId;
2664 }
2665 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2666 if (empty($params['prevContribution'])) {
2667 $entityID = NULL;
2668 }
2669 else {
2670 $update = TRUE;
2671 }
2672
2673 $statusId = $params['contribution']->contribution_status_id;
2674 // CRM-13964 partial payment
2675 if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2676 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2677 ) {
2678 $partialAmtPay = $params['partial_amount_pay'];
2679 $partialAmtTotal = $params['partial_payment_total'];
2680
2681 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2682 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2683 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
2684 $params['total_amount'] = $partialAmtPay;
2685
2686 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']);
2687 if (empty($balanceTrxnInfo['trxn_id'])) {
2688 // create new balance transaction record
2689 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2690 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2691
2692 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2693 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2694 $balanceTrxnParams['contribution_id'] = $params['contribution']->id;
2695 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2696 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2697 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2698 $balanceTrxnParams['currency'] = $params['contribution']->currency;
2699 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id;
2700 $balanceTrxnParams['status_id'] = $statusId;
2701 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2702 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
2703 if (!empty($params['payment_processor'])) {
2704 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2705 }
2706 CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
2707 }
2708 }
2709
2710 // build line item array if its not set in $params
2711 if (empty($params['line_item']) || $additionalParticipantId) {
2712 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2713 }
2714
2715 if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2716 !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)
2717 ) {
2718 $skipRecords = TRUE;
2719 $pendingStatus = array(
2720 array_search('Pending', $contributionStatuses),
2721 array_search('In Progress', $contributionStatuses),
2722 );
2723 if (in_array(CRM_Utils_Array::value('contribution_status_id', $params), $pendingStatus)) {
2724 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2725 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2726 }
2727 elseif (!empty($params['payment_processor'])) {
2728 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2729 }
2730 elseif (!empty($params['payment_instrument_id'])) {
2731 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
2732 }
2733 else {
2734 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2735 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2736 $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
2737 }
2738
2739 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
2740 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2741 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
2742 }
2743
2744 //build financial transaction params
2745 $trxnParams = array(
2746 'contribution_id' => $params['contribution']->id,
2747 'to_financial_account_id' => $params['to_financial_account_id'],
2748 'trxn_date' => date('YmdHis'),
2749 'total_amount' => $totalAmount,
2750 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
2751 'net_amount' => CRM_Utils_Array::value('net_amount', $params),
2752 'currency' => $params['contribution']->currency,
2753 'trxn_id' => $params['contribution']->trxn_id,
2754 'status_id' => $statusId,
2755 'payment_instrument_id' => $params['contribution']->payment_instrument_id,
2756 'check_number' => CRM_Utils_Array::value('check_number', $params),
2757 );
2758
2759 if (!empty($params['payment_processor'])) {
2760 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2761 }
2762
2763 if (isset($fromFinancialAccountId)) {
2764 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2765 }
2766
2767 // consider external values passed for recording transaction entry
2768 if (!empty($financialTrxnValues)) {
2769 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2770 }
2771
2772 $params['trxnParams'] = $trxnParams;
2773
2774 if (!empty($params['prevContribution'])) {
2775 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
2776 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
2777 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
2778 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
2779 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
2780
2781 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
2782 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
2783 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
2784 ) {
2785 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2786 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2787 }
2788
2789 //if financial type is changed
2790 if (!empty($params['financial_type_id']) &&
2791 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
2792 ) {
2793 $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2794 $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId);
2795 $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId);
2796 if ($oldFinancialAccount != $newFinancialAccount) {
2797 $params['total_amount'] = 0;
2798 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
2799 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2800 $params['prevContribution']->financial_type_id, $relationTypeId);
2801 }
2802 else {
2803 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
2804 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2805 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2806 }
2807 }
2808 self::updateFinancialAccounts($params, 'changeFinancialType');
2809 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2810 $params['financial_account_id'] = $newFinancialAccount;
2811 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2812 self::updateFinancialAccounts($params);
2813 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2814 }
2815 }
2816
2817 //Update contribution status
2818 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
2819 if (!empty($params['contribution_status_id']) &&
2820 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
2821 ) {
2822 //Update Financial Records
2823 self::updateFinancialAccounts($params, 'changedStatus');
2824 }
2825
2826 // change Payment Instrument for a Completed contribution
2827 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2828 // instrument is null and now new payment instrument is added along with the payment
2829 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2830 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
2831 if (array_key_exists('payment_instrument_id', $params)) {
2832 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2833 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
2834 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)
2835 ) {
2836 //check if status is changed from Pending to Completed
2837 // do not update payment instrument changes for Pending to Completed
2838 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
2839 in_array($params['prevContribution']->contribution_status_id, $pendingStatus))
2840 ) {
2841 // for all other statuses create new financial records
2842 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2843 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2844 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2845 }
2846 }
2847 elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
2848 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
2849 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id
2850 ) {
2851 // for any other payment instrument changes create new financial records
2852 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2853 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2854 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2855 }
2856 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
2857 $params['contribution']->check_number != $params['prevContribution']->check_number
2858 ) {
2859 // another special case when check number is changed, create new financial records
2860 // create financial trxn with negative amount
2861 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2862 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2863 // create financial trxn with positive amount
2864 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
2865 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2866 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2867 }
2868 }
2869
2870 //if Change contribution amount
2871 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2872 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2873 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2874 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
2875 if (isset($totalAmount) &&
2876 $totalAmount != $params['prevContribution']->total_amount
2877 ) {
2878 //Update Financial Records
2879 $params['trxnParams']['from_financial_account_id'] = NULL;
2880 self::updateFinancialAccounts($params, 'changedAmount');
2881 }
2882 }
2883
2884 if (!$update) {
2885 // records finanical trxn and entity financial trxn
2886 // also make it available as return value
2887 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
2888 $params['entity_id'] = $financialTxn->id;
2889 }
2890 }
2891 // record line items and finacial items
2892 if (empty($params['skipLineItem'])) {
2893 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
2894 }
2895
2896 // create batch entry if batch_id is passed
2897 if (!empty($params['batch_id'])) {
2898 $entityParams = array(
2899 'batch_id' => $params['batch_id'],
2900 'entity_table' => 'civicrm_financial_trxn',
2901 'entity_id' => $financialTxn->id,
2902 );
2903 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
2904 }
2905
2906 // when a fee is charged
2907 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
2908 CRM_Core_BAO_FinancialTrxn::recordFees($params);
2909 }
2910
2911 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2912 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
2913 ) {
2914 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2915 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
2916 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
2917 }
2918 unset($params['line_item']);
2919
2920 return $return;
2921 }
2922
2923 /**
2924 * Update all financial accounts entry
2925 *
2926 * @param array $params
2927 * Contribution object, line item array and params for trxn.
2928 *
2929 * @param string $context
2930 * Update scenarios.
2931 *
2932 * @param null $skipTrxn
2933 *
2934 */
2935 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2936 $itemAmount = $trxnID = NULL;
2937 //get all the statuses
2938 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2939 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2940 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
2941 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2942 && $context == 'changePaymentInstrument'
2943 ) {
2944 return;
2945 }
2946 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
2947 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
2948 }
2949 if ($context == 'changedStatus') {
2950 //get all the statuses
2951 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2952
2953 if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2954 && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
2955 || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))
2956 ) {
2957 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2958 }
2959 elseif (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2960 && $params['prevContribution']->is_pay_later) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)
2961 ) {
2962 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
2963 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
2964 $params['trxnParams']['to_financial_account_id'] = NULL;
2965 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2966 }
2967 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2968 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2969 $financialTypeID, $relationTypeId);
2970 }
2971 $itemAmount = $params['trxnParams']['total_amount'];
2972 }
2973 elseif ($context == 'changePaymentInstrument') {
2974 if ($params['trxnParams']['total_amount'] < 0) {
2975 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
2976 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2977 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2978 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2979 }
2980 }
2981 else {
2982 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2983 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2984 }
2985 }
2986 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
2987 $params['entity_id'] = $trxn->id;
2988
2989 if ($context == 'changedStatus') {
2990 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2991 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
2992 && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
2993 ) {
2994 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2995 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2996
2997 $entityParams = array(
2998 'entity_table' => 'civicrm_financial_item',
2999 'financial_trxn_id' => $trxn->id,
3000 );
3001 if (empty($params['line_item'])) {
3002 //CRM-15296
3003 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3004 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3005 // & this can be removed
3006 return;
3007 }
3008 foreach ($params['line_item'] as $fieldId => $fields) {
3009 foreach ($fields as $fieldValueId => $fieldValues) {
3010 $fparams = array(
3011 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3012 2 => array($fieldValues['id'], 'Integer'),
3013 );
3014 CRM_Core_DAO::executeQuery($query, $fparams);
3015 $fparams = array(
3016 1 => array($fieldValues['id'], 'Integer'),
3017 );
3018 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
3019 while ($financialItem->fetch()) {
3020 $entityParams['entity_id'] = $financialItem->id;
3021 $entityParams['amount'] = $financialItem->amount;
3022 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
3023 }
3024 }
3025 }
3026 return;
3027 }
3028 }
3029 if ($context != 'changePaymentInstrument') {
3030 $itemParams['entity_table'] = 'civicrm_line_item';
3031 $trxnIds['id'] = $params['entity_id'];
3032 foreach ($params['line_item'] as $fieldId => $fields) {
3033 foreach ($fields as $fieldValueId => $fieldValues) {
3034 $prevParams['entity_id'] = $fieldValues['id'];
3035 $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray);
3036
3037 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
3038 if ($params['contribution']->receive_date) {
3039 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
3040 }
3041
3042 $financialAccount = $prevfinancialItem->financial_account_id;
3043 if (!empty($params['financial_account_id'])) {
3044 $financialAccount = $params['financial_account_id'];
3045 }
3046
3047 $currency = $params['prevContribution']->currency;
3048 if ($params['contribution']->currency) {
3049 $currency = $params['contribution']->currency;
3050 }
3051 $diff = 1;
3052 if (!empty($params['is_quick_config'])) {
3053 $amount = $itemAmount;
3054 if (!$amount) {
3055 $amount = $params['total_amount'];
3056 }
3057 }
3058 else {
3059 if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)
3060 || $params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
3061 ) {
3062 $diff = -1;
3063 }
3064 $amount = $diff * $fieldValues['line_total'];
3065 }
3066
3067 $itemParams = array(
3068 'transaction_date' => $receiveDate,
3069 'contact_id' => $params['prevContribution']->contact_id,
3070 'currency' => $currency,
3071 'amount' => $amount,
3072 'description' => $prevfinancialItem->description,
3073 'status_id' => $prevfinancialItem->status_id,
3074 'financial_account_id' => $financialAccount,
3075 'entity_table' => 'civicrm_line_item',
3076 'entity_id' => $fieldValues['id'],
3077 );
3078 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3079
3080 if ($fieldValues['tax_amount']) {
3081 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
3082 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
3083 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3084 $itemParams['description'] = $taxTerm;
3085 if ($fieldValues['financial_type_id']) {
3086 $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']);
3087 }
3088 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3089 }
3090 }
3091 }
3092 }
3093 }
3094
3095 /**
3096 * Check status validation on update of a contribution
3097 *
3098 * @param array $values
3099 * Previous form values before submit.
3100 *
3101 * @param array $fields
3102 * The input form values.
3103 *
3104 * @param array $errors
3105 * List of errors.
3106 *
3107 * @return bool
3108 */
3109 public static function checkStatusValidation($values, &$fields, &$errors) {
3110 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
3111 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3112 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3113 return FALSE;
3114 }
3115 }
3116 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3117 $checkStatus = array(
3118 'Cancelled' => array('Completed', 'Refunded'),
3119 'Completed' => array('Cancelled', 'Refunded'),
3120 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3121 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3122 'Refunded' => array('Cancelled', 'Completed'),
3123 );
3124
3125 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3126 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3127 1 => $contributionStatuses[$values['contribution_status_id']],
3128 2 => $contributionStatuses[$fields['contribution_status_id']],
3129 ));
3130 }
3131 }
3132
3133 /**
3134 * Delete contribution of contact
3135 *
3136 * CRM-12155
3137 *
3138 * @param int $contactId
3139 * Contact id.
3140 *
3141 */
3142 public static function deleteContactContribution($contactId) {
3143 $contribution = new CRM_Contribute_DAO_Contribution();
3144 $contribution->contact_id = $contactId;
3145 $contribution->find();
3146 while ($contribution->fetch()) {
3147 self::deleteContribution($contribution->id);
3148 }
3149 }
3150
3151 /**
3152 * Get options for a given contribution field.
3153 * @see CRM_Core_DAO::buildOptions
3154 *
3155 * @param string $fieldName
3156 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3157 * @param array $props whatever is known about this dao object.
3158 *
3159 * @return array|bool
3160 */
3161 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3162 $className = __CLASS__;
3163 $params = array();
3164 switch ($fieldName) {
3165 // This field is not part of this object but the api supports it
3166 case 'payment_processor':
3167 $className = 'CRM_Contribute_BAO_ContributionPage';
3168 // Filter results by contribution page
3169 if (!empty($props['contribution_page_id'])) {
3170 $page = civicrm_api('contribution_page', 'getsingle', array(
3171 'version' => 3,
3172 'id' => ($props['contribution_page_id']),
3173 ));
3174 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3175 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3176 }
3177 break;
3178
3179 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3180 case 'honor_type_id':
3181 $className = 'CRM_Contribute_BAO_ContributionSoft';
3182 $fieldName = 'soft_credit_type_id';
3183 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3184 break;
3185 }
3186 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3187 }
3188
3189 /**
3190 * Validate financial type
3191 *
3192 * CRM-13231
3193 *
3194 * @param int $financialTypeId
3195 * Financial Type id.
3196 *
3197 * @param string $relationName
3198 *
3199 * @return array|bool
3200 */
3201 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3202 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3203 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
3204
3205 if (!$financialAccount) {
3206 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
3207 }
3208 return FALSE;
3209 }
3210
3211
3212 /**
3213 * Function to record additional payment for partial and refund contributions
3214 *
3215 * @param int $contributionId
3216 * is the invoice contribution id (got created after processing participant payment).
3217 * @param array $trxnsData
3218 * to take user provided input of transaction details.
3219 * @param string $paymentType
3220 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3221 * @param int $participantId
3222 *
3223 * @return null|object
3224 */
3225 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3226 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
3227 $getInfoOf['id'] = $contributionId;
3228 $defaults = array();
3229 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
3230
3231 if ($paymentType == 'owed') {
3232 // build params for recording financial trxn entry
3233 $params['contribution'] = $contributionDAO;
3234 $params = array_merge($defaults, $params);
3235 $params['skipLineItem'] = TRUE;
3236 $params['partial_payment_total'] = $contributionDAO->total_amount;
3237 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3238 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3239
3240 // record the entry
3241 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3242 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3243 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3244
3245 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
3246 if (!empty($trxnId)) {
3247 $trxnId = $trxnId['trxn_id'];
3248 }
3249 elseif (!empty($contributionDAO->payment_instrument_id)) {
3250 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
3251 }
3252 else {
3253 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3254 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3255 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3256 }
3257
3258 // update statuses
3259 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3260 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3261 FROM civicrm_financial_trxn ft
3262 LEFT JOIN civicrm_entity_financial_trxn eft
3263 ON (ft.id = eft.financial_trxn_id)
3264 WHERE eft.entity_table = 'civicrm_contribution'
3265 AND eft.entity_id = {$contributionId}
3266 AND ft.to_financial_account_id != {$toFinancialAccount}
3267 AND ft.status_id = {$statusId}
3268 ";
3269 $sumOfPayments = CRM_Core_DAO::singleValueQuery($sql);
3270
3271 // update statuses
3272 if ($contributionDAO->total_amount == $sumOfPayments) {
3273 // update contribution status and
3274 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3275 $contributionDAO->contribution_status_id = $statusId;
3276 $contributionDAO->cancel_date = 'null';
3277 $contributionDAO->cancel_reason = NULL;
3278 $netAmount = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
3279 $contributionDAO->net_amount = $contributionDAO->net_amount + $netAmount;
3280 $contributionDAO->save();
3281
3282 //Change status of financial record too
3283 $financialTrxn->status_id = $statusId;
3284 $financialTrxn->save();
3285
3286 // note : not using the self::add method,
3287 // the reason because it performs 'status change' related code execution for financial records
3288 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3289 // are coded below i.e. just updating financial_item status to 'Paid'
3290
3291 if ($participantId) {
3292 // update participant status
3293 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3294 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3295 foreach ($ids as $val) {
3296 $participantUpdate['id'] = $val;
3297 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3298 CRM_Event_BAO_Participant::add($participantUpdate);
3299 }
3300 }
3301
3302 // update financial item statuses
3303 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3304 $paidStatus = array_search('Paid', $financialItemStatus);
3305
3306 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3307 $sqlFinancialItemUpdate = "
3308 UPDATE civicrm_financial_item fi
3309 LEFT JOIN civicrm_entity_financial_trxn eft
3310 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3311 SET status_id = {$paidStatus}
3312 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3313 ";
3314 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
3315 }
3316 }
3317 elseif ($paymentType == 'refund') {
3318 // build params for recording financial trxn entry
3319 $params['contribution'] = $contributionDAO;
3320 $params = array_merge($defaults, $params);
3321 $params['skipLineItem'] = TRUE;
3322 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3323 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3324
3325 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3326 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3327 $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
3328 // record the entry
3329 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3330
3331 // note : not using the self::add method,
3332 // the reason because it performs 'status change' related code execution for financial records
3333 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3334 // are coded below i.e. just updating financial_item status to 'Paid'
3335 $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3336
3337 // add financial item entry
3338 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3339 $getLine['entity_id'] = $contributionDAO->id;
3340 $getLine['entity_table'] = 'civicrm_contribution';
3341 $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
3342 if (!empty($lineItemId->id)) {
3343 $addFinancialEntry = array(
3344 'transaction_date' => $financialTrxn->trxn_date,
3345 'contact_id' => $contributionDAO->contact_id,
3346 'amount' => $financialTrxn->total_amount,
3347 'status_id' => array_search('Paid', $financialItemStatus),
3348 'entity_id' => $lineItemId->id,
3349 'entity_table' => 'civicrm_line_item',
3350 );
3351 $trxnIds['id'] = $financialTrxn->id;
3352 CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
3353 }
3354 if ($participantId) {
3355 // update participant status
3356 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3357 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3358 foreach ($ids as $val) {
3359 $participantUpdate['id'] = $val;
3360 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3361 CRM_Event_BAO_Participant::add($participantUpdate);
3362 }
3363 }
3364 }
3365
3366 // activity creation
3367 if (!empty($financialTrxn)) {
3368 if ($participantId) {
3369 $inputParams['id'] = $participantId;
3370 $values = array();
3371 $ids = array();
3372 $component = 'event';
3373 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
3374 $entityObj = $entityObj[$participantId];
3375 }
3376 $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment';
3377
3378 self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3379 }
3380 return $financialTrxn;
3381 }
3382
3383 /**
3384 * @param $entityObj
3385 * @param $trxnObj
3386 * @param $activityType
3387 * @param $component
3388 * @param int $contributionId
3389 *
3390 * @throws CRM_Core_Exception
3391 */
3392 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3393 if ($component == 'event') {
3394 $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
3395 $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency);
3396 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
3397 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3398 $targetCid = $entityObj->contact_id;
3399 // source record id would be the contribution id
3400 $srcRecId = $contributionId;
3401 }
3402
3403 // activity params
3404 $activityParams = array(
3405 'source_contact_id' => $targetCid,
3406 'source_record_id' => $srcRecId,
3407 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
3408 $activityType,
3409 'name'
3410 ),
3411 'subject' => $subject,
3412 'activity_date_time' => $date,
3413 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
3414 'Completed',
3415 'name'
3416 ),
3417 'skipRecentView' => TRUE,
3418 );
3419
3420 // create activity with target contacts
3421 $session = CRM_Core_Session::singleton();
3422 $id = $session->get('userID');
3423 if ($id) {
3424 $activityParams['source_contact_id'] = $id;
3425 $activityParams['target_contact_id'][] = $targetCid;
3426 }
3427 CRM_Activity_BAO_Activity::create($activityParams);
3428 }
3429
3430 /**
3431 * Get list of payments displayed by Contribute_Page_PaymentInfo
3432 *
3433 * @param int $id
3434 * @param $component
3435 * @param bool $getTrxnInfo
3436 * @param bool $usingLineTotal
3437 *
3438 * @return mixed
3439 */
3440 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3441 if ($component == 'event') {
3442 $entity = 'participant';
3443 $entityTable = 'civicrm_participant';
3444 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3445
3446 if (!$contributionId) {
3447 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3448 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3449 $id = $primaryParticipantId;
3450 }
3451 if (!$contributionId) {
3452 return;
3453 }
3454 }
3455 }
3456 $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
3457 $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
3458 $isBalance = NULL;
3459 if ($baseTrxnId) {
3460 $isBalance = TRUE;
3461 }
3462 else {
3463 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3464 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3465 $isBalance = FALSE;
3466 }
3467 if (empty($total) || $usingLineTotal) {
3468 // for additional participants
3469 if ($entityTable == 'civicrm_participant') {
3470 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3471 $total = 0;
3472 foreach ($ids as $val) {
3473 $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable);
3474 }
3475 }
3476 else {
3477 $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
3478 }
3479 }
3480 else {
3481 $baseTrxnId = $total['trxn_id'];
3482 $total = $total['total_amount'];
3483 }
3484
3485 $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
3486 $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3487
3488 $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3489 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3490 $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId);
3491
3492 if ($paymentBalance == 0 && $contributionIsPayLater) {
3493 $paymentBalance = $total;
3494 }
3495
3496 $info['total'] = $total;
3497 $info['paid'] = $total - $paymentBalance;
3498 $info['balance'] = $paymentBalance;
3499 $info['id'] = $id;
3500 $info['component'] = $component;
3501 $info['payLater'] = $contributionIsPayLater;
3502 $rows = array();
3503 if ($getTrxnInfo && $baseTrxnId) {
3504 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3505 $sql = "
3506 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3507 FROM civicrm_contribution con
3508 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3509 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3510 WHERE con.id = {$contributionId}
3511 ";
3512
3513 // conditioned WHERE clause
3514 if ($isBalance) {
3515 // if balance trxn exists don't include details of it in transaction info
3516 $sql .= " AND ft.id != {$baseTrxnId} ";
3517 }
3518 $resultDAO = CRM_Core_DAO::executeQuery($sql);
3519
3520 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
3521 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
3522 while ($resultDAO->fetch()) {
3523 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3524 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3525 $val = array(
3526 'total_amount' => $resultDAO->total_amount,
3527 'financial_type' => $financialTypes[$resultDAO->financial_type_id],
3528 'payment_instrument' => $paidByLabel,
3529 'receive_date' => $resultDAO->trxn_date,
3530 'trxn_id' => $resultDAO->trxn_id,
3531 'status' => $statuses[$resultDAO->status_id],
3532 );
3533 if ($paidByName == 'Check') {
3534 $val['check_number'] = $resultDAO->check_number;
3535 }
3536 $rows[] = $val;
3537 }
3538 $info['transaction'] = $rows;
3539 }
3540 return $info;
3541 }
3542
3543 /**
3544 * Get financial account id has 'Sales Tax Account is'
3545 * account relationship with financial type
3546 *
3547 * @param int $financialTypeId
3548 *
3549 * @return FinancialAccountId
3550 */
3551 public static function getFinancialAccountId($financialTypeId) {
3552 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3553 $searchParams = array(
3554 'entity_table' => 'civicrm_financial_type',
3555 'entity_id' => $financialTypeId,
3556 'account_relationship' => $accountRel,
3557 );
3558 $result = array();
3559 CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
3560
3561 return CRM_Utils_Array::value('financial_account_id', $result);
3562 }
3563
3564 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3565 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
3566
3567 // Update contribution
3568 if (!empty($params['id'])) {
3569 $id = $params['id'];
3570 $values = $ids = array();
3571 $contrbutionParams = array('id' => $id);
3572 $prevContributionValue = CRM_Contribute_BAO_Contribution::getValues($contrbutionParams, $values, $ids);
3573
3574 // To assign pervious finantial type on update of contribution
3575 if (!isset($params['financial_type_id'])) {
3576 $params['financial_type_id'] = $prevContributionValue->financial_type_id;
3577 }
3578 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3579 // Assisn tax Amount on update of contrbution
3580 if (!empty($prevContributionValue->tax_amount)) {
3581 $params['tax_amount'] = 'null';
3582 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3583 foreach ($params['line_item'] as $setID => $priceField) {
3584 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3585 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3586 }
3587 }
3588 }
3589 }
3590 }
3591
3592 // New Contrbution and update of contribution with tax rate financial type
3593 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3594 empty($params['skipLineItem']) && !$isLineItem
3595 ) {
3596 $taxRateParams = $taxRates[$params['financial_type_id']];
3597 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['total_amount'], $taxRateParams);
3598 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3599
3600 // Get Line Item on update of contribution
3601 if (isset($params['id'])) {
3602 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3603 }
3604 else {
3605 CRM_Price_BAO_LineItem::getLineItemArray($params);
3606 }
3607 foreach ($params['line_item'] as $setID => $priceField) {
3608 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3609 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3610 }
3611 }
3612 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
3613 }
3614 elseif (isset($params['api.line_item.create'])) {
3615 // Update total amount of contribution using lineItem
3616 $taxAmountArray = array();
3617 foreach ($params['api.line_item.create'] as $key => $value) {
3618 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3619 $taxRate = $taxRates[$value['financial_type_id']];
3620 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
3621 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3622 }
3623 }
3624 $params['tax_amount'] = array_sum($taxAmountArray);
3625 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
3626 }
3627 else {
3628 // update line item of contrbution
3629 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3630 $taxRate = $taxRates[$params['financial_type_id']];
3631 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate);
3632 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3633 }
3634 }
3635 return $params;
3636 }
3637
3638 }