remove some @access from phpdoc
[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
91 */
92 public static function add(&$params, $ids = array()) {
93 if (empty($params)) {
94 return;
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 CRM_Contribute_BAO_ContributionSoft::add($softParams);
396 }
397 if (isset($params['soft_credit'])) {
398 $softParams = $params['soft_credit'];
399
400 if (!empty($softIDs)) {
401 foreach ($softIDs as $softID) {
402 if (!in_array($softID, $params['soft_credit_ids'])) {
403 $deleteParams = array('id' => $softID);
404 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
405 }
406 }
407 }
408
409 foreach ($softParams as $softParam) {
410 $softParam['contribution_id'] = $contribution->id;
411 $softParam['currency'] = $contribution->currency;
412 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
413 if (empty($softParam['amount'])) {
414 $softParam['amount'] = $contribution->total_amount;
415 }
416 CRM_Contribute_BAO_ContributionSoft::add($softParam);
417 }
418 }
419
420 $transaction->commit();
421
422 // do not add to recent items for import, CRM-4399
423 if (empty($params['skipRecentView'])) {
424 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
425 "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
426 );
427 // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
428 $titleFields = array(
429 'contact_id',
430 'total_amount',
431 'currency',
432 'financial_type_id',
433 );
434 $retrieveRequired = 0;
435 foreach ($titleFields as $titleField) {
436 if (!isset($contribution->$titleField)) {
437 $retrieveRequired = 1;
438 break;
439 }
440 }
441 if ($retrieveRequired == 1) {
442 $contribution->find(TRUE);
443 }
444 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
445 $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
446
447 $recentOther = array();
448 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
449 $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
450 "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
451 );
452 }
453
454 if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
455 $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
456 "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home"
457 );
458 }
459
460 // add the recently created Contribution
461 CRM_Utils_Recent::add($title,
462 $url,
463 $contribution->id,
464 'Contribution',
465 $contribution->contact_id,
466 NULL,
467 $recentOther
468 );
469 }
470
471 return $contribution;
472 }
473
474 /**
475 * Get the values for pseudoconstants for name->value and reverse.
476 *
477 * @param array $defaults
478 * (reference) the default values, some of which need to be resolved.
479 * @param bool $reverse
480 * True if we want to resolve the values in the reverse direction (value -> name).
481 *
482 * @return void
483 */
484 public static function resolveDefaults(&$defaults, $reverse = FALSE) {
485 self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse);
486 self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse);
487 self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse);
488 self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse);
489 }
490
491 /**
492 * convert associative array names to values
493 * and vice-versa.
494 *
495 * This function is used by both the web form layer and the api. Note that
496 * the api needs the name => value conversion, also the view layer typically
497 * requires value => name conversion
498 */
499 public static function lookupValue(&$defaults, $property, &$lookup, $reverse) {
500 $id = $property . '_id';
501
502 $src = $reverse ? $property : $id;
503 $dst = $reverse ? $id : $property;
504
505 if (!array_key_exists($src, $defaults)) {
506 return FALSE;
507 }
508
509 $look = $reverse ? array_flip($lookup) : $lookup;
510
511 if (is_array($look)) {
512 if (!array_key_exists($defaults[$src], $look)) {
513 return FALSE;
514 }
515 }
516 $defaults[$dst] = $look[$defaults[$src]];
517 return TRUE;
518 }
519
520 /**
521 * Takes a bunch of params that are needed to match certain criteria and
522 * retrieves the relevant objects. We'll tweak this function to be more
523 * full featured over a period of time. This is the inverse function of
524 * create. It also stores all the retrieved values in the default array
525 *
526 * @param array $params
527 * (reference ) an assoc array of name/value pairs.
528 * @param array $defaults
529 * (reference ) an assoc array to hold the name / value pairs.
530 * in a hierarchical manner
531 * @param array $ids
532 * (reference) the array that holds all the db ids.
533 *
534 * @return CRM_Contribute_BAO_Contribution
535 */
536 public static function retrieve(&$params, &$defaults, &$ids) {
537 $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids);
538 return $contribution;
539 }
540
541 /**
542 * Combine all the importable fields from the lower levels object
543 *
544 * The ordering is important, since currently we do not have a weight
545 * scheme. Adding weight is super important and should be done in the
546 * next week or so, before this can be called complete.
547 *
548 * @param string $contactType
549 * @param bool $status
550 *
551 * @return array
552 * array of importable Fields
553 */
554 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
555 if (!self::$_importableFields) {
556 if (!self::$_importableFields) {
557 self::$_importableFields = array();
558 }
559
560 if (!$status) {
561 $fields = array('' => array('title' => ts('- do not import -')));
562 }
563 else {
564 $fields = array('' => array('title' => ts('- Contribution Fields -')));
565 }
566
567 $note = CRM_Core_DAO_Note::import();
568 $tmpFields = CRM_Contribute_DAO_Contribution::import();
569 unset($tmpFields['option_value']);
570 $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute');
571 $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
572
573 // Using new Dedupe rule.
574 $ruleParams = array(
575 'contact_type' => $contactType,
576 'used' => 'Unsupervised',
577 );
578 $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
579 $tmpContactField = array();
580 if (is_array($fieldsArray)) {
581 foreach ($fieldsArray as $value) {
582 //skip if there is no dupe rule
583 if ($value == 'none') {
584 continue;
585 }
586 $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
587 $value,
588 'id',
589 'column_name'
590 );
591 $value = $customFieldId ? 'custom_' . $customFieldId : $value;
592 $tmpContactField[trim($value)] = $contactFields[trim($value)];
593 if (!$status) {
594 $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)');
595 }
596 else {
597 $title = $tmpContactField[trim($value)]['title'];
598 }
599 $tmpContactField[trim($value)]['title'] = $title;
600 }
601 }
602
603 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
604 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
605 $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)');
606 $fields = array_merge($fields, $tmpContactField);
607 $fields = array_merge($fields, $tmpFields);
608 $fields = array_merge($fields, $note);
609 $fields = array_merge($fields, $optionFields);
610 $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export());
611 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
612 self::$_importableFields = $fields;
613 }
614 return self::$_importableFields;
615 }
616
617 /**
618 * @return array
619 */
620 public static function &exportableFields() {
621 if (!self::$_exportableFields) {
622 if (!self::$_exportableFields) {
623 self::$_exportableFields = array();
624 }
625
626 $impFields = CRM_Contribute_DAO_Contribution::export();
627 $expFieldProduct = CRM_Contribute_DAO_Product::export();
628 $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export();
629 $typeField = CRM_Financial_DAO_FinancialType::export();
630 $financialAccount = CRM_Financial_DAO_FinancialAccount::export();
631 $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute');
632 $contributionStatus = array(
633 'contribution_status' => array(
634 'title' => ts('Contribution Status'),
635 'name' => 'contribution_status',
636 'data_type' => CRM_Utils_Type::T_STRING,
637 ),
638 );
639
640 $contributionPage = array(
641 'contribution_page' => array(
642 'title' => ts('Contribution Page'),
643 'name' => 'contribution_page',
644 'where' => 'civicrm_contribution_page.title',
645 'data_type' => CRM_Utils_Type::T_STRING
646 ));
647
648 $contributionNote = array(
649 'contribution_note' =>
650 array(
651 'title' => ts('Contribution Note'),
652 'name' => 'contribution_note',
653 'data_type' => CRM_Utils_Type::T_TEXT,
654 ),
655 );
656
657 $contributionRecurId = array(
658 'contribution_recur_id' => array(
659 'title' => ts('Recurring Contributions ID'),
660 'name' => 'contribution_recur_id',
661 'where' => 'civicrm_contribution.contribution_recur_id',
662 'data_type' => CRM_Utils_Type::T_INT,
663 ),
664 );
665
666 $extraFields = array(
667 'contribution_batch' => array(
668 'title' => ts('Batch Name'),
669 ),
670 );
671
672 $softCreditFields = array(
673 'contribution_soft_credit_name' => array(
674 'name' => 'contribution_soft_credit_name',
675 'title' => 'Soft Credit For',
676 'where' => 'civicrm_contact_d.display_name',
677 'data_type' => CRM_Utils_Type::T_STRING,
678 ),
679 'contribution_soft_credit_amount' => array(
680 'name' => 'contribution_soft_credit_amount',
681 'title' => 'Soft Credit Amount',
682 'where' => 'civicrm_contribution_soft.amount',
683 'data_type' => CRM_Utils_Type::T_MONEY,
684 ),
685 'contribution_soft_credit_type' => array(
686 'name' => 'contribution_soft_credit_type',
687 'title' => 'Soft Credit Type',
688 'where' => 'contribution_softcredit_type.label',
689 'data_type' => CRM_Utils_Type::T_STRING,
690 ),
691 'contribution_soft_credit_contribution_id' => array(
692 'name' => 'contribution_soft_credit_contribution_id',
693 'title' => 'Soft Credit For Contribution ID',
694 'where' => 'civicrm_contribution_soft.contribution_id',
695 'data_type' => CRM_Utils_Type::T_INT,
696 ),
697 );
698
699 $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct,
700 $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount,
701 CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')
702 );
703
704 self::$_exportableFields = $fields;
705 }
706
707 return self::$_exportableFields;
708 }
709
710 /**
711 * @param null $status
712 * @param null $startDate
713 * @param null $endDate
714 *
715 * @return array|null
716 */
717 public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
718 $where = array();
719 switch ($status) {
720 case 'Valid':
721 $where[] = 'contribution_status_id = 1';
722 break;
723
724 case 'Cancelled':
725 $where[] = 'contribution_status_id = 3';
726 break;
727 }
728
729 if ($startDate) {
730 $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'";
731 }
732 if ($endDate) {
733 $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'";
734 }
735
736 $whereCond = implode(' AND ', $where);
737
738 $query = "
739 SELECT sum( total_amount ) as total_amount,
740 count( civicrm_contribution.id ) as total_count,
741 currency
742 FROM civicrm_contribution
743 INNER JOIN civicrm_contact contact ON ( contact.id = civicrm_contribution.contact_id )
744 WHERE $whereCond
745 AND ( is_test = 0 OR is_test IS NULL )
746 AND contact.is_deleted = 0
747 GROUP BY currency
748 ";
749
750 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
751 $amount = array();
752 $count = 0;
753 while ($dao->fetch()) {
754 $count += $dao->total_count;
755 $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency);
756 }
757 if ($count) {
758 return array(
759 'amount' => implode(', ', $amount),
760 'count' => $count,
761 );
762 }
763 return NULL;
764 }
765
766 /**
767 * Delete the indirect records associated with this contribution first
768 *
769 * @param int $id
770 *
771 * @return mixed|null
772 * $results no of deleted Contribution on success, false otherwise
773 */
774 public static function deleteContribution($id) {
775 CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray);
776
777 $transaction = new CRM_Core_Transaction();
778
779 $results = NULL;
780 //delete activity record
781 $params = array(
782 'source_record_id' => $id,
783 // activity type id for contribution
784 'activity_type_id' => 6,
785 );
786
787 CRM_Activity_BAO_Activity::deleteActivity($params);
788
789 //delete billing address if exists for this contribution.
790 self::deleteAddress($id);
791
792 //update pledge and pledge payment, CRM-3961
793 CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id);
794
795 // remove entry from civicrm_price_set_entity, CRM-5095
796 if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) {
797 CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id);
798 }
799 // cleanup line items.
800 $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id');
801
802 // delete any related entity_financial_trxn, financial_trxn and financial_item records.
803 CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id);
804
805 if ($participantId) {
806 CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant');
807 }
808 else {
809 CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution');
810 }
811
812 //delete note.
813 $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution');
814 $noteId = key($note);
815 if ($noteId) {
816 CRM_Core_BAO_Note::del($noteId, FALSE);
817 }
818
819 $dao = new CRM_Contribute_DAO_Contribution();
820 $dao->id = $id;
821
822 $results = $dao->delete();
823
824 $transaction->commit();
825
826 CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao);
827
828 // delete the recently created Contribution
829 $contributionRecent = array(
830 'id' => $id,
831 'type' => 'Contribution',
832 );
833 CRM_Utils_Recent::del($contributionRecent);
834
835 return $results;
836 }
837
838 /**
839 * Check if there is a contribution with the same trxn_id or invoice_id
840 *
841 * @param array $input
842 * An assoc array of name/value pairs.
843 * @param array $duplicates
844 * (reference) store ids of duplicate contribs.
845 * @param int $id
846 *
847 * @return boolean
848 * true if duplicate, false otherwise
849 */
850 public static function checkDuplicate($input, &$duplicates, $id = NULL) {
851 if (!$id) {
852 $id = CRM_Utils_Array::value('id', $input);
853 }
854 $trxn_id = CRM_Utils_Array::value('trxn_id', $input);
855 $invoice_id = CRM_Utils_Array::value('invoice_id', $input);
856
857 $clause = array();
858 $input = array();
859
860 if ($trxn_id) {
861 $clause[] = "trxn_id = %1";
862 $input[1] = array($trxn_id, 'String');
863 }
864
865 if ($invoice_id) {
866 $clause[] = "invoice_id = %2";
867 $input[2] = array($invoice_id, 'String');
868 }
869
870 if (empty($clause)) {
871 return FALSE;
872 }
873
874 $clause = implode(' OR ', $clause);
875 if ($id) {
876 $clause = "( $clause ) AND id != %3";
877 $input[3] = array($id, 'Integer');
878 }
879
880 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
881 $dao = CRM_Core_DAO::executeQuery($query, $input);
882 $result = FALSE;
883 while ($dao->fetch()) {
884 $duplicates[] = $dao->id;
885 $result = TRUE;
886 }
887 return $result;
888 }
889
890 /**
891 * Takes an associative array and creates a contribution_product object
892 *
893 * the function extract all the params it needs to initialize the create a
894 * contribution_product object. the params array could contain additional unused name/value
895 * pairs
896 *
897 * @param array $params
898 * (reference) an assoc array of name/value pairs.
899 *
900 * @return CRM_Contribute_DAO_ContributionProduct
901 */
902 public static function addPremium(&$params) {
903 $contributionProduct = new CRM_Contribute_DAO_ContributionProduct();
904 $contributionProduct->copyValues($params);
905 return $contributionProduct->save();
906 }
907
908 /**
909 * Get list of contribution fields for profile
910 * For now we only allow custom contribution fields to be in
911 * profile
912 *
913 * @param bool $addExtraFields
914 * True if special fields needs to be added.
915 *
916 * @return array
917 * the list of contribution fields
918 */
919 public static function getContributionFields($addExtraFields = TRUE) {
920 $contributionFields = CRM_Contribute_DAO_Contribution::export();
921 $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute'));
922
923 if ($addExtraFields) {
924 $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields());
925 }
926
927 $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export());
928
929 foreach ($contributionFields as $key => $var) {
930 if ($key == 'contribution_contact_id') {
931 continue;
932 }
933 elseif ($key == 'contribution_campaign_id') {
934 $var['title'] = ts('Campaign');
935 }
936 $fields[$key] = $var;
937 }
938
939 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution'));
940 return $fields;
941 }
942
943 /**
944 * Add extra fields specific to contribtion
945 *
946 */
947 public static function getSpecialContributionFields() {
948 $extraFields = array(
949 'contribution_soft_credit_name' => array(
950 'name' => 'contribution_soft_credit_name',
951 'title' => 'Soft Credit Name',
952 'headerPattern' => '/^soft_credit_name$/i',
953 'where' => 'civicrm_contact_d.display_name',
954 ),
955 'contribution_soft_credit_email' => array(
956 'name' => 'contribution_soft_credit_email',
957 'title' => 'Soft Credit Email',
958 'headerPattern' => '/^soft_credit_email$/i',
959 'where' => 'soft_email.email',
960 ),
961 'contribution_soft_credit_phone' => array(
962 'name' => 'contribution_soft_credit_phone',
963 'title' => 'Soft Credit Phone',
964 'headerPattern' => '/^soft_credit_phone$/i',
965 'where' => 'soft_phone.phone',
966 ),
967 'contribution_soft_credit_contact_id' => array(
968 'name' => 'contribution_soft_credit_contact_id',
969 'title' => 'Soft Credit Contact ID',
970 'headerPattern' => '/^soft_credit_contact_id$/i',
971 'where' => 'civicrm_contribution_soft.contact_id',
972 ),
973 );
974
975 return $extraFields;
976 }
977
978 /**
979 * @param int $pageID
980 *
981 * @return array
982 */
983 public static function getCurrentandGoalAmount($pageID) {
984 $query = "
985 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
986 FROM civicrm_contribution_page p,
987 civicrm_contribution c
988 WHERE p.id = c.contribution_page_id
989 AND p.id = %1
990 AND c.cancel_date is null
991 GROUP BY p.id
992 ";
993
994 $config = CRM_Core_Config::singleton();
995 $params = array(1 => array($pageID, 'Integer'));
996 $dao = CRM_Core_DAO::executeQuery($query, $params);
997
998 if ($dao->fetch()) {
999 return array($dao->goal, $dao->total);
1000 }
1001 else {
1002 return array(NULL, NULL);
1003 }
1004 }
1005
1006 /**
1007 * Get list of contribution In Honor of contact Ids
1008 *
1009 * @param int $honorId
1010 * In Honor of Contact ID.
1011 *
1012 * @return array
1013 * list of contribution fields
1014 *
1015 */
1016 public static function getHonorContacts($honorId) {
1017 $params = array();
1018 $honorDAO = new CRM_Contribute_DAO_ContributionSoft();
1019 $honorDAO->contact_id = $honorId;
1020 $honorDAO->find();
1021
1022 $type = CRM_Contribute_PseudoConstant::financialType();
1023
1024 while ($honorDAO->fetch()) {
1025 $contributionDAO = new CRM_Contribute_DAO_Contribution();
1026 $contributionDAO->id = $honorDAO->contribution_id;
1027
1028 if ($contributionDAO->find(TRUE)) {
1029 $params[$contributionDAO->id]['honor_type'] = CRM_Core_OptionGroup::getLabel('soft_credit_type', $honorDAO->soft_credit_type_id, 'value');
1030 $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id;
1031 $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name');
1032 $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id];
1033 $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id;
1034 $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency);
1035 $params[$contributionDAO->id]['source'] = $contributionDAO->source;
1036 $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date;
1037 $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id);
1038 }
1039 }
1040
1041 return $params;
1042 }
1043
1044 /**
1045 * Get the sort name of a contact for a particular contribution
1046 *
1047 * @param int $id
1048 * Id of the contribution.
1049 *
1050 * @return null|string
1051 * sort name of the contact if found
1052 */
1053 public static function sortName($id) {
1054 $id = CRM_Utils_Type::escape($id, 'Integer');
1055
1056 $query = "
1057 SELECT civicrm_contact.sort_name
1058 FROM civicrm_contribution, civicrm_contact
1059 WHERE civicrm_contribution.contact_id = civicrm_contact.id
1060 AND civicrm_contribution.id = {$id}
1061 ";
1062 return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray);
1063 }
1064
1065 /**
1066 * @param int $contactID
1067 *
1068 * @return array
1069 */
1070 public static function annual($contactID) {
1071 if (is_array($contactID)) {
1072 $contactIDs = implode(',', $contactID);
1073 }
1074 else {
1075 $contactIDs = $contactID;
1076 }
1077
1078 $config = CRM_Core_Config::singleton();
1079 $startDate = $endDate = NULL;
1080
1081 $currentMonth = date('m');
1082 $currentDay = date('d');
1083 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1084 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1085 (int ) $config->fiscalYearStart['d'] > $currentDay
1086 )
1087 ) {
1088 $year = date('Y') - 1;
1089 }
1090 else {
1091 $year = date('Y');
1092 }
1093 $nextYear = $year + 1;
1094
1095 if ($config->fiscalYearStart) {
1096 if ($config->fiscalYearStart['M'] < 10) {
1097 $config->fiscalYearStart['M'] = '0' . $config->fiscalYearStart['M'];
1098 }
1099 if ($config->fiscalYearStart['d'] < 10) {
1100 $config->fiscalYearStart['d'] = '0' . $config->fiscalYearStart['d'];
1101 }
1102 $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d'];
1103 }
1104 else {
1105 $monthDay = '0101';
1106 }
1107 $startDate = "$year$monthDay";
1108 $endDate = "$nextYear$monthDay";
1109
1110 $query = "
1111 SELECT count(*) as count,
1112 sum(total_amount) as amount,
1113 avg(total_amount) as average,
1114 currency
1115 FROM civicrm_contribution b
1116 WHERE b.contact_id IN ( $contactIDs )
1117 AND b.contribution_status_id = 1
1118 AND b.is_test = 0
1119 AND b.receive_date >= $startDate
1120 AND b.receive_date < $endDate
1121 GROUP BY currency
1122 ";
1123 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1124 $count = 0;
1125 $amount = $average = array();
1126 while ($dao->fetch()) {
1127 if ($dao->count > 0 && $dao->amount > 0) {
1128 $count += $dao->count;
1129 $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency);
1130 $average[] = CRM_Utils_Money::format($dao->average, $dao->currency);
1131 }
1132 }
1133 if ($count > 0) {
1134 return array(
1135 $count,
1136 implode(',&nbsp;', $amount),
1137 implode(',&nbsp;', $average),
1138 );
1139 }
1140 return array(0, 0, 0);
1141 }
1142
1143 /**
1144 * Check if there is a contribution with the params passed in.
1145 * Used for trxn_id,invoice_id and contribution_id
1146 *
1147 * @param array $params
1148 * An assoc array of name/value pairs.
1149 *
1150 * @return array
1151 * contribution id if success else NULL
1152 */
1153 public static function checkDuplicateIds($params) {
1154 $dao = new CRM_Contribute_DAO_Contribution();
1155
1156 $clause = array();
1157 $input = array();
1158 foreach ($params as $k => $v) {
1159 if ($v) {
1160 $clause[] = "$k = '$v'";
1161 }
1162 }
1163 $clause = implode(' AND ', $clause);
1164 $query = "SELECT id FROM civicrm_contribution WHERE $clause";
1165 $dao = CRM_Core_DAO::executeQuery($query, $input);
1166
1167 while ($dao->fetch()) {
1168 $result = $dao->id;
1169 return $result;
1170 }
1171 return NULL;
1172 }
1173
1174 /**
1175 * Get the contribution details for component export
1176 *
1177 * @param int $exportMode
1178 * Export mode.
1179 * @param string $componentIds
1180 * Component ids.
1181 *
1182 * @return array
1183 * associated array
1184 *
1185 */
1186 public static function getContributionDetails($exportMode, $componentIds) {
1187 $paymentDetails = array();
1188 $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) ';
1189
1190 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
1191 $componentSelect = " civicrm_participant_payment.participant_id id";
1192 $additionalClause = "
1193 INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id
1194 AND civicrm_participant_payment.participant_id {$componentClause} )
1195 ";
1196 }
1197 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
1198 $componentSelect = " civicrm_membership_payment.membership_id id";
1199 $additionalClause = "
1200 INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id
1201 AND civicrm_membership_payment.membership_id {$componentClause} )
1202 ";
1203 }
1204 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
1205 $componentSelect = " civicrm_pledge_payment.id id";
1206 $additionalClause = "
1207 INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id
1208 AND civicrm_pledge_payment.pledge_id {$componentClause} )
1209 ";
1210 }
1211
1212 $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date,
1213 trxn_id, {$componentSelect}
1214 FROM civicrm_contribution
1215 LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument')
1216 LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value
1217 AND option_group_payment_instrument.id = payment_instrument.option_group_id )
1218 LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status')
1219 LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value
1220 AND option_group_contribution_status.id = contribution_status.option_group_id )
1221 {$additionalClause}
1222 ";
1223
1224 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1225
1226 while ($dao->fetch()) {
1227 $paymentDetails[$dao->id] = array(
1228 'total_amount' => $dao->total_amount,
1229 'contribution_status' => $dao->status,
1230 'receive_date' => $dao->receive_date,
1231 'pay_instru' => $dao->payment_instrument,
1232 'trxn_id' => $dao->trxn_id,
1233 );
1234 }
1235
1236 return $paymentDetails;
1237 }
1238
1239 /**
1240 * Create address associated with contribution record.
1241 *
1242 * @param array $params
1243 * @param int $billingLocationTypeID
1244 *
1245 * @return int
1246 * address id
1247 */
1248 public static function createAddress(&$params, $billingLocationTypeID) {
1249 $billingFields = array(
1250 'street_address',
1251 'city',
1252 'state_province_id',
1253 'postal_code',
1254 'country_id',
1255 );
1256
1257 //build address array
1258 $addressParams = array();
1259 $addressParams['location_type_id'] = $billingLocationTypeID;
1260 $addressParams['is_billing'] = 1;
1261
1262 $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params);
1263 $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params);
1264 $billingLastName = CRM_Utils_Array::value('billing_last_name', $params);
1265 $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}";
1266
1267 foreach ($billingFields as $value) {
1268 $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params);
1269 }
1270
1271 $address = CRM_Core_BAO_Address::add($addressParams, FALSE);
1272
1273 return $address->id;
1274 }
1275
1276 /**
1277 * Delete billing address record related contribution
1278 *
1279 * @param int $contributionId
1280 * @param int $contactId
1281 *
1282 */
1283 public static function deleteAddress($contributionId = NULL, $contactId = NULL) {
1284 $clauses = array();
1285 $contactJoin = NULL;
1286
1287 if ($contributionId) {
1288 $clauses[] = "cc.id = {$contributionId}";
1289 }
1290
1291 if ($contactId) {
1292 $clauses[] = "cco.id = {$contactId}";
1293 $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id";
1294 }
1295
1296 if (empty($clauses)) {
1297 CRM_Core_Error::fatal();
1298 }
1299
1300 $condition = implode(' OR ', $clauses);
1301
1302 $query = "
1303 SELECT ca.id
1304 FROM civicrm_address ca
1305 INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id
1306 $contactJoin
1307 WHERE $condition
1308 ";
1309 $dao = CRM_Core_DAO::executeQuery($query);
1310
1311 while ($dao->fetch()) {
1312 $params = array('id' => $dao->id);
1313 CRM_Core_BAO_Block::blockDelete('Address', $params);
1314 }
1315 }
1316
1317 /**
1318 * This function check online pending contribution associated w/
1319 * Online Event Registration or Online Membership signup.
1320 *
1321 * @param int $componentId
1322 * Participant/membership id.
1323 * @param string $componentName
1324 * Event/Membership.
1325 *
1326 * @return int
1327 * pending contribution id.
1328 */
1329 public static function checkOnlinePendingContribution($componentId, $componentName) {
1330 $contributionId = NULL;
1331 if (!$componentId ||
1332 !in_array($componentName, array('Event', 'Membership'))
1333 ) {
1334 return $contributionId;
1335 }
1336
1337 if ($componentName == 'Event') {
1338 $idName = 'participant_id';
1339 $componentTable = 'civicrm_participant';
1340 $paymentTable = 'civicrm_participant_payment';
1341 $source = ts('Online Event Registration');
1342 }
1343
1344 if ($componentName == 'Membership') {
1345 $idName = 'membership_id';
1346 $componentTable = 'civicrm_membership';
1347 $paymentTable = 'civicrm_membership_payment';
1348 $source = ts('Online Contribution');
1349 }
1350
1351 $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'));
1352
1353 $query = "
1354 SELECT component.id as {$idName},
1355 componentPayment.contribution_id as contribution_id,
1356 contribution.source source,
1357 contribution.contribution_status_id as contribution_status_id,
1358 contribution.is_pay_later as is_pay_later
1359 FROM $componentTable component
1360 LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id )
1361 LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id )
1362 WHERE component.id = {$componentId}";
1363
1364 $dao = CRM_Core_DAO::executeQuery($query);
1365
1366 while ($dao->fetch()) {
1367 if ($dao->contribution_id &&
1368 $dao->is_pay_later &&
1369 $dao->contribution_status_id == $pendingStatusId &&
1370 strpos($dao->source, $source) !== FALSE
1371 ) {
1372 $contributionId = $dao->contribution_id;
1373 $dao->free();
1374 }
1375 }
1376
1377 return $contributionId;
1378 }
1379
1380 /**
1381 * Update contribution as well as related objects.
1382 */
1383 public static function transitionComponents($params, $processContributionObject = FALSE) {
1384 // get minimum required values.
1385 $contactId = CRM_Utils_Array::value('contact_id', $params);
1386 $componentId = CRM_Utils_Array::value('component_id', $params);
1387 $componentName = CRM_Utils_Array::value('componentName', $params);
1388 $contributionId = CRM_Utils_Array::value('contribution_id', $params);
1389 $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params);
1390
1391 // if we already processed contribution object pass previous status id.
1392 $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params);
1393
1394 $updateResult = array();
1395
1396 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
1397
1398 // we process only ( Completed, Cancelled, or Failed ) contributions.
1399 if (!$contributionId ||
1400 !in_array($contributionStatusId, array(
1401 array_search('Completed', $contributionStatuses),
1402 array_search('Cancelled', $contributionStatuses),
1403 array_search('Failed', $contributionStatuses),
1404 ))
1405 ) {
1406 return $updateResult;
1407 }
1408
1409 if (!$componentName || !$componentId) {
1410 // get the related component details.
1411 $componentDetails = self::getComponentDetails($contributionId);
1412 }
1413 else {
1414 $componentDetails['contact_id'] = $contactId;
1415 $componentDetails['component'] = $componentName;
1416
1417 if ($componentName == 'event') {
1418 $componentDetails['participant'] = $componentId;
1419 }
1420 else {
1421 $componentDetails['membership'] = $componentId;
1422 }
1423 }
1424
1425 if (!empty($componentDetails['contact_id'])) {
1426 $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1427 $contributionId,
1428 'contact_id'
1429 );
1430 }
1431
1432 // do check for required ids.
1433 if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) {
1434 return $updateResult;
1435 }
1436
1437 //now we are ready w/ required ids, start processing.
1438
1439 $baseIPN = new CRM_Core_Payment_BaseIPN();
1440
1441 $input = $ids = $objects = array();
1442
1443 $input['component'] = CRM_Utils_Array::value('component', $componentDetails);
1444 $ids['contribution'] = $contributionId;
1445 $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails);
1446 $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails);
1447 $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails);
1448 $ids['event'] = CRM_Utils_Array::value('event', $componentDetails);
1449 $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails);
1450 $ids['contributionRecur'] = NULL;
1451 $ids['contributionPage'] = NULL;
1452
1453 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
1454 CRM_Core_Error::fatal();
1455 }
1456
1457 $memberships = &$objects['membership'];
1458 $participant = &$objects['participant'];
1459 $pledgePayment = &$objects['pledge_payment'];
1460 $contribution = &$objects['contribution'];
1461
1462 if ($pledgePayment) {
1463 $pledgePaymentIDs = array();
1464 foreach ($pledgePayment as $key => $object) {
1465 $pledgePaymentIDs[] = $object->id;
1466 }
1467 $pledgeID = $pledgePayment[0]->pledge_id;
1468 }
1469
1470 $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
1471
1472 if ($participant) {
1473 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
1474 $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
1475 $participant->id,
1476 'status_id'
1477 );
1478 }
1479 // we might want to process contribution object.
1480 $processContribution = FALSE;
1481 if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) {
1482 if (is_array($memberships)) {
1483 foreach ($memberships as $membership) {
1484 if ($membership) {
1485 $membership->status_id = array_search('Cancelled', $membershipStatuses);
1486 $membership->save();
1487
1488 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1489 if ($processContributionObject) {
1490 $processContribution = TRUE;
1491 }
1492 }
1493 }
1494 }
1495
1496 if ($participant) {
1497 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1498 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1499
1500 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1501 if ($processContributionObject) {
1502 $processContribution = TRUE;
1503 }
1504 }
1505
1506 if ($pledgePayment) {
1507 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1508
1509 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1510 if ($processContributionObject) {
1511 $processContribution = TRUE;
1512 }
1513 }
1514 }
1515 elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) {
1516 if (is_array($memberships)) {
1517 foreach ($memberships as $membership) {
1518 if ($membership) {
1519 $membership->status_id = array_search('Expired', $membershipStatuses);
1520 $membership->save();
1521
1522 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1523 if ($processContributionObject) {
1524 $processContribution = TRUE;
1525 }
1526 }
1527 }
1528 }
1529 if ($participant) {
1530 $updatedStatusId = array_search('Cancelled', $participantStatuses);
1531 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1532
1533 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1534 if ($processContributionObject) {
1535 $processContribution = TRUE;
1536 }
1537 }
1538
1539 if ($pledgePayment) {
1540 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1541
1542 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1543 if ($processContributionObject) {
1544 $processContribution = TRUE;
1545 }
1546 }
1547 }
1548 elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) {
1549
1550 // only pending contribution related object processed.
1551 if ($previousContriStatusId &&
1552 ($previousContriStatusId != array_search('Pending', $contributionStatuses))
1553 ) {
1554 // this is case when we already processed contribution object.
1555 return $updateResult;
1556 }
1557 elseif (!$previousContriStatusId &&
1558 $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)
1559 ) {
1560 // this is case when we are going to process contribution object later.
1561 return $updateResult;
1562 }
1563
1564 if (is_array($memberships)) {
1565 foreach ($memberships as $membership) {
1566 if ($membership) {
1567 $format = '%Y%m%d';
1568
1569 //CRM-4523
1570 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id,
1571 $membership->membership_type_id,
1572 $membership->is_test, $membership->id
1573 );
1574
1575 // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
1576 // this picks up membership type changes during renewals
1577 $sql = "
1578 SELECT membership_type_id
1579 FROM civicrm_membership_log
1580 WHERE membership_id=$membership->id
1581 ORDER BY id DESC
1582 LIMIT 1;";
1583 $dao = new CRM_Core_DAO;
1584 $dao->query($sql);
1585 if ($dao->fetch()) {
1586 if (!empty($dao->membership_type_id)) {
1587 $membership->membership_type_id = $dao->membership_type_id;
1588 $membership->save();
1589 }
1590 }
1591 // else fall back to using current membership type
1592 $dao->free();
1593
1594 // Figure out number of terms
1595 $numterms = 1;
1596 $lineitems = CRM_Price_BAO_LineItem::getLineItems($contributionId, 'contribution');
1597 foreach ($lineitems as $lineitem) {
1598 if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) {
1599 $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem);
1600
1601 // in case membership_num_terms comes through as null or zero
1602 $numterms = $numterms >= 1 ? $numterms : 1;
1603 break;
1604 }
1605 }
1606
1607 // CRM-15735-to update the membership status as per the contribution receive date
1608 if (!empty($params['receive_date'])) {
1609 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
1610 $membership->end_date,
1611 $membership->join_date,
1612 $params['receive_date'],
1613 FALSE,
1614 $membership->membership_type_id,
1615 (array) $membership
1616 );
1617 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
1618 $membership->save();
1619 }
1620
1621 if ($currentMembership) {
1622 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1623 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
1624 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1625 }
1626 else {
1627 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms);
1628 }
1629
1630 //get the status for membership.
1631 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1632 $dates['end_date'],
1633 $dates['join_date'],
1634 'today',
1635 TRUE,
1636 $membership->membership_type_id,
1637 (array) $membership
1638 );
1639
1640 $formattedParams = array(
1641 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1642 array_search('Current', $membershipStatuses)
1643 ),
1644 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1645 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1646 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1647 );
1648
1649 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
1650
1651 $membership->copyValues($formattedParams);
1652 $membership->save();
1653
1654 //updating the membership log
1655 $membershipLog = array();
1656 $membershipLog = $formattedParams;
1657 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1658 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
1659
1660 $membershipLog['start_date'] = $logStartDate;
1661 $membershipLog['membership_id'] = $membership->id;
1662 $membershipLog['modified_id'] = $membership->contact_id;
1663 $membershipLog['modified_date'] = date('Ymd');
1664 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1665
1666 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1667
1668 //update related Memberships.
1669 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
1670
1671 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1672 '%B %E%f, %Y'
1673 );
1674 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1675 if ($processContributionObject) {
1676 $processContribution = TRUE;
1677 }
1678
1679 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1680 }
1681 }
1682 }
1683
1684 if ($participant) {
1685 $updatedStatusId = array_search('Registered', $participantStatuses);
1686 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1687
1688 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1689 if ($processContributionObject) {
1690 $processContribution = TRUE;
1691 }
1692 }
1693
1694 if ($pledgePayment) {
1695 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1696
1697 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1698 if ($processContributionObject) {
1699 $processContribution = TRUE;
1700 }
1701 }
1702 }
1703
1704 // process contribution object.
1705 if ($processContribution) {
1706 $contributionParams = array();
1707 $fields = array(
1708 'contact_id',
1709 'total_amount',
1710 'receive_date',
1711 'is_test',
1712 'campaign_id',
1713 'payment_instrument_id',
1714 'trxn_id',
1715 'invoice_id',
1716 'financial_type_id',
1717 'contribution_status_id',
1718 'non_deductible_amount',
1719 'receipt_date',
1720 'check_number',
1721 );
1722 foreach ($fields as $field) {
1723 if (empty($params[$field])) {
1724 continue;
1725 }
1726 $contributionParams[$field] = $params[$field];
1727 }
1728
1729 $ids = array('contribution' => $contributionId);
1730 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1731 }
1732
1733 return $updateResult;
1734 }
1735
1736 /**
1737 * Returns all contribution related object ids.
1738 */
1739 public static function getComponentDetails($contributionId) {
1740 $componentDetails = $pledgePayment = array();
1741 if (!$contributionId) {
1742 return $componentDetails;
1743 }
1744
1745 $query = "
1746 SELECT c.id as contribution_id,
1747 c.contact_id as contact_id,
1748 mp.membership_id as membership_id,
1749 m.membership_type_id as membership_type_id,
1750 pp.participant_id as participant_id,
1751 p.event_id as event_id,
1752 pgp.id as pledge_payment_id
1753 FROM civicrm_contribution c
1754 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1755 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1756 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1757 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1758 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1759 WHERE c.id = $contributionId";
1760
1761 $dao = CRM_Core_DAO::executeQuery($query);
1762 $componentDetails = array();
1763
1764 while ($dao->fetch()) {
1765 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1766 $componentDetails['contact_id'] = $dao->contact_id;
1767 if ($dao->event_id) {
1768 $componentDetails['event'] = $dao->event_id;
1769 }
1770 if ($dao->participant_id) {
1771 $componentDetails['participant'] = $dao->participant_id;
1772 }
1773 if ($dao->membership_id) {
1774 if (!isset($componentDetails['membership'])) {
1775 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1776 }
1777 $componentDetails['membership'][] = $dao->membership_id;
1778 $componentDetails['membership_type'][] = $dao->membership_type_id;
1779 }
1780 if ($dao->pledge_payment_id) {
1781 $pledgePayment[] = $dao->pledge_payment_id;
1782 }
1783 }
1784
1785 if ($pledgePayment) {
1786 $componentDetails['pledge_payment'] = $pledgePayment;
1787 }
1788
1789 return $componentDetails;
1790 }
1791
1792 /**
1793 * @param int $contactId
1794 * @param bool $includeSoftCredit
1795 *
1796 * @return null|string
1797 */
1798 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1799 if (!$contactId) {
1800 return 0;
1801 }
1802
1803 $contactContributionsSQL = "
1804 SELECT contribution.id AS id
1805 FROM civicrm_contribution contribution
1806 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1807
1808 $contactSoftCreditContributionsSQL = "
1809 SELECT contribution.id
1810 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1811 ON ( contribution.id = softContribution.contribution_id )
1812 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1813 $query = "SELECT count( x.id ) count FROM ( ";
1814 $query .= $contactContributionsSQL;
1815
1816 if ($includeSoftCredit) {
1817 $query .= " UNION ";
1818 $query .= $contactSoftCreditContributionsSQL;
1819 }
1820
1821 $query .= ") x";
1822
1823 return CRM_Core_DAO::singleValueQuery($query);
1824 }
1825
1826 /**
1827 * Get individual id for onbehalf contribution
1828 *
1829 * @param int $contributionId
1830 * Contribution id.
1831 * @param int $contributorId
1832 * Contributor id.
1833 *
1834 * @return array
1835 * containing organization id and individual id
1836 */
1837 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1838
1839 $ids = array();
1840
1841 if (!$contributionId) {
1842 return $ids;
1843 }
1844
1845 // fetch contributor id if null
1846 if (!$contributorId) {
1847 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1848 $contributionId, 'contact_id'
1849 );
1850 }
1851
1852 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1853 $activityTypeId = array_search('Contribution', $activityTypeIds);
1854
1855 if ($activityTypeId && $contributorId) {
1856 $activityQuery = "
1857 SELECT civicrm_activity_contact.contact_id
1858 FROM civicrm_activity_contact
1859 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1860 WHERE civicrm_activity.activity_type_id = %1
1861 AND civicrm_activity.source_record_id = %2
1862 AND civicrm_activity_contact.record_type_id = %3
1863 ";
1864
1865 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1866 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1867
1868 $params = array(
1869 1 => array($activityTypeId, 'Integer'),
1870 2 => array($contributionId, 'Integer'),
1871 3 => array($sourceID, 'Integer'),
1872 );
1873
1874 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
1875
1876 // for on behalf contribution source is individual and contributor is organization
1877 if ($sourceContactId && $sourceContactId != $contributorId) {
1878 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
1879 // get rel type id for employee of relation
1880 foreach ($relationshipTypeIds as $id => $typeVals) {
1881 if ($typeVals['name_a_b'] == 'Employee of') {
1882 $relationshipTypeId = $id;
1883 break;
1884 }
1885 }
1886
1887 $rel = new CRM_Contact_DAO_Relationship();
1888 $rel->relationship_type_id = $relationshipTypeId;
1889 $rel->contact_id_a = $sourceContactId;
1890 $rel->contact_id_b = $contributorId;
1891 if ($rel->find(TRUE)) {
1892 $ids['individual_id'] = $rel->contact_id_a;
1893 $ids['organization_id'] = $rel->contact_id_b;
1894 }
1895 }
1896 }
1897
1898 return $ids;
1899 }
1900
1901 /**
1902 * @return array
1903 */
1904 public static function getContributionDates() {
1905 $config = CRM_Core_Config::singleton();
1906 $currentMonth = date('m');
1907 $currentDay = date('d');
1908 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1909 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1910 (int ) $config->fiscalYearStart['d'] > $currentDay
1911 )
1912 ) {
1913 $year = date('Y') - 1;
1914 }
1915 else {
1916 $year = date('Y');
1917 }
1918 $year = array('Y' => $year);
1919 $yearDate = $config->fiscalYearStart;
1920 $yearDate = array_merge($year, $yearDate);
1921 $yearDate = CRM_Utils_Date::format($yearDate);
1922
1923 $monthDate = date('Ym') . '01';
1924
1925 $now = date('Ymd');
1926
1927 return array(
1928 'now' => $now,
1929 'yearDate' => $yearDate,
1930 'monthDate' => $monthDate,
1931 );
1932 }
1933
1934 /**
1935 * Load objects relations to contribution object
1936 * Objects are stored in the $_relatedObjects property
1937 * In the first instance we are just moving functionality from BASEIpn -
1938 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1939 *
1940 * Note that the unit test for the BaseIPN class tests this function
1941 *
1942 * @param array $input
1943 * Input as delivered from Payment Processor.
1944 * @param array $ids
1945 * Ids as Loaded by Payment Processor.
1946 * @param bool $required
1947 * Is Payment processor / contribution page required.
1948 * @param bool $loadAll
1949 * Load all related objects - even where id not passed in? (allows API to call this).
1950 *
1951 * @return bool
1952 * @throws Exception
1953 */
1954 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1955 if ($loadAll) {
1956 $ids = array_merge($this->getComponentDetails($this->id), $ids);
1957 if (empty($ids['contact']) && isset($this->contact_id)) {
1958 $ids['contact'] = $this->contact_id;
1959 }
1960 }
1961 if (empty($this->_component)) {
1962 if (!empty($ids['event'])) {
1963 $this->_component = 'event';
1964 }
1965 else {
1966 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
1967 }
1968 }
1969 $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
1970 $contributionType = new CRM_Financial_BAO_FinancialType();
1971 $contributionType->id = $this->financial_type_id;
1972 if (!$contributionType->find(TRUE)) {
1973 throw new Exception("Could not find financial type record: " . $this->financial_type_id);
1974 }
1975 if (!empty($ids['contact'])) {
1976 $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
1977 $this->_relatedObjects['contact']->id = $ids['contact'];
1978 $this->_relatedObjects['contact']->find(TRUE);
1979 }
1980 $this->_relatedObjects['contributionType'] = $contributionType;
1981
1982 if ($this->_component == 'contribute') {
1983 // retrieve the other optional objects first so
1984 // stuff down the line can use this info and do things
1985 // CRM-6056
1986 //in any case get the memberships associated with the contribution
1987 //because we now support multiple memberships w/ price set
1988 // see if there are any other memberships to be considered for same contribution.
1989 $query = "
1990 SELECT membership_id
1991 FROM civicrm_membership_payment
1992 WHERE contribution_id = %1 ";
1993 $params = array(1 => array($this->id, 'Integer'));
1994
1995 $dao = CRM_Core_DAO::executeQuery($query, $params);
1996 while ($dao->fetch()) {
1997 if ($dao->membership_id) {
1998 if (!is_array($ids['membership'])) {
1999 $ids['membership'] = array();
2000 }
2001 $ids['membership'][] = $dao->membership_id;
2002 }
2003 }
2004
2005 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2006 foreach ($ids['membership'] as $id) {
2007 if (!empty($id)) {
2008 $membership = new CRM_Member_BAO_Membership();
2009 $membership->id = $id;
2010 if (!$membership->find(TRUE)) {
2011 throw new Exception("Could not find membership record: $id");
2012 }
2013 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
2014 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
2015 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
2016 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
2017 $membership->free();
2018 }
2019 }
2020 }
2021
2022 if (!empty($ids['pledge_payment'])) {
2023
2024 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2025 if (empty($paymentID)) {
2026 continue;
2027 }
2028 $payment = new CRM_Pledge_BAO_PledgePayment();
2029 $payment->id = $paymentID;
2030 if (!$payment->find(TRUE)) {
2031 throw new Exception("Could not find pledge payment record: " . $paymentID);
2032 }
2033 $this->_relatedObjects['pledge_payment'][] = $payment;
2034 }
2035 }
2036
2037 if (!empty($ids['contributionRecur'])) {
2038 $recur = new CRM_Contribute_BAO_ContributionRecur();
2039 $recur->id = $ids['contributionRecur'];
2040 if (!$recur->find(TRUE)) {
2041 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2042 }
2043 $this->_relatedObjects['contributionRecur'] = &$recur;
2044 //get payment processor id from recur object.
2045 $paymentProcessorID = $recur->payment_processor_id;
2046 }
2047 //for normal contribution get the payment processor id.
2048 if (!$paymentProcessorID) {
2049 if ($this->contribution_page_id) {
2050 // get the payment processor id from contribution page
2051 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2052 $this->contribution_page_id,
2053 'payment_processor'
2054 );
2055 }
2056 //fail to load payment processor id.
2057 elseif (empty($ids['pledge_payment'])) {
2058 $loadObjectSuccess = TRUE;
2059 if ($required) {
2060 throw new Exception("Could not find contribution page for contribution record: " . $this->id);
2061 }
2062 return $loadObjectSuccess;
2063 }
2064 }
2065 }
2066 else {
2067 // we are in event mode
2068 // make sure event exists and is valid
2069 $event = new CRM_Event_BAO_Event();
2070 $event->id = $ids['event'];
2071 if ($ids['event'] &&
2072 !$event->find(TRUE)
2073 ) {
2074 throw new Exception("Could not find event: " . $ids['event']);
2075 }
2076
2077 $this->_relatedObjects['event'] = &$event;
2078
2079 $participant = new CRM_Event_BAO_Participant();
2080 $participant->id = $ids['participant'];
2081 if ($ids['participant'] &&
2082 !$participant->find(TRUE)
2083 ) {
2084 throw new Exception("Could not find participant: " . $ids['participant']);
2085 }
2086 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2087
2088 $this->_relatedObjects['participant'] = &$participant;
2089
2090 if (!$paymentProcessorID) {
2091 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2092 }
2093 }
2094
2095 if ($paymentProcessorID) {
2096 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2097 $this->is_test ? 'test' : 'live'
2098 );
2099 $ids['paymentProcessor'] = $paymentProcessorID;
2100 $this->_relatedObjects['paymentProcessor'] = &$paymentProcessor;
2101 }
2102 elseif ($required) {
2103 throw new Exception("Could not find payment processor for contribution record: " . $this->id);
2104 }
2105
2106 return TRUE;
2107 }
2108
2109 /**
2110 * Create array of message information - ie. return html version, txt version, to field
2111 *
2112 * @param array $input
2113 * Incoming information.
2114 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2115 * just check presence of recur object but maintaining legacy approach
2116 * to be careful)
2117 * @param array $ids
2118 * IDs of related objects.
2119 * @param array $values
2120 * Any values that may have already been compiled by calling process.
2121 * This is augmented by values 'gathered' by gatherMessageValues
2122 * @param bool $recur
2123 * @param bool $returnMessageText
2124 * Distinguishes between whether to send message or return.
2125 * message text. We are working towards this function ALWAYS returning message text & calling
2126 * function doing emails / pdfs with it
2127 *
2128 * @return array
2129 * messages
2130 * @throws Exception
2131 */
2132 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2133 if (empty($this->_relatedObjects)) {
2134 $this->loadRelatedObjects($input, $ids);
2135 }
2136 if (empty($this->_component)) {
2137 $this->_component = CRM_Utils_Array::value('component', $input);
2138 }
2139
2140 //not really sure what params might be passed in but lets merge em into values
2141 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2142 $template = CRM_Core_Smarty::singleton();
2143 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2144 //what does recur 'mean here - to do with payment processor return functionality but
2145 // what is the importance
2146 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2147 $paymentObject = &CRM_Core_Payment::singleton(
2148 $this->is_test ? 'test' : 'live',
2149 $this->_relatedObjects['paymentProcessor']
2150 );
2151
2152 $entityID = $entity = NULL;
2153 if (isset($ids['contribution'])) {
2154 $entity = 'contribution';
2155 $entityID = $ids['contribution'];
2156 }
2157 if (!empty($ids['membership'])) {
2158 //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
2159 // 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
2160 // line having loaded an array
2161 $ids['membership'] = (array) $ids['membership'];
2162 $entity = 'membership';
2163 $entityID = $ids['membership'][0];
2164 }
2165
2166 $url = $paymentObject->subscriptionURL($entityID, $entity);
2167 $template->assign('cancelSubscriptionUrl', $url);
2168
2169 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2170 $template->assign('updateSubscriptionBillingUrl', $url);
2171
2172 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2173 $template->assign('updateSubscriptionUrl', $url);
2174
2175 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2176 //direct mode showing billing block, so use directIPN for temporary
2177 $template->assign('contributeMode', 'directIPN');
2178 }
2179 }
2180 // todo remove strtolower - check consistency
2181 if (strtolower($this->_component) == 'event') {
2182 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2183 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2184 );
2185 }
2186 else {
2187 $values['contribution_id'] = $this->id;
2188 if (!empty($ids['related_contact'])) {
2189 $values['related_contact'] = $ids['related_contact'];
2190 if (isset($ids['onbehalf_dupe_alert'])) {
2191 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2192 }
2193 $entityBlock = array(
2194 'contact_id' => $ids['contact'],
2195 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2196 'Home', 'id', 'name'
2197 ),
2198 );
2199 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2200 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2201 }
2202 $isTest = FALSE;
2203 if ($this->is_test) {
2204 $isTest = TRUE;
2205 }
2206 if (!empty($this->_relatedObjects['membership'])) {
2207 foreach ($this->_relatedObjects['membership'] as $membership) {
2208 if ($membership->id) {
2209 $values['isMembership'] = TRUE;
2210
2211 // need to set the membership values here
2212 $template->assign('membership_assign', 1);
2213 $template->assign('membership_name',
2214 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2215 );
2216 $template->assign('mem_start_date', $membership->start_date);
2217 $template->assign('mem_join_date', $membership->join_date);
2218 $template->assign('mem_end_date', $membership->end_date);
2219 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2220 $template->assign('mem_status', $membership_status);
2221 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2222 $template->assign('is_pay_later', 1);
2223 }
2224
2225 // if separate payment there are two contributions recorded and the
2226 // admin will need to send a receipt for each of them separately.
2227 // we dont link the two in the db (but can potentially infer it if needed)
2228 $template->assign('is_separate_payment', 0);
2229
2230 if ($recur && $paymentObject) {
2231 $url = $paymentObject->subscriptionURL($membership->id, 'membership');
2232 $template->assign('cancelSubscriptionUrl', $url);
2233 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2234 $template->assign('updateSubscriptionBillingUrl', $url);
2235 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2236 $template->assign('updateSubscriptionUrl', $url);
2237 }
2238
2239 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2240
2241 return $result;
2242 // otherwise if its about sending emails, continue sending without return, as we
2243 // don't want to exit the loop.
2244 }
2245 }
2246 }
2247 else {
2248 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2249 }
2250 }
2251 }
2252
2253 /**
2254 * Gather values for contribution mail - this function has been created
2255 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2256 * Values related to the contribution in question are gathered
2257 *
2258 * @param array $input
2259 * Input into function (probably from payment processor).
2260 * @param array $values
2261 * @param array $ids
2262 * The set of ids related to the input.
2263 *
2264 * @return array
2265 */
2266 public function _gatherMessageValues($input, &$values, $ids = array()) {
2267 // set display address of contributor
2268 if ($this->address_id) {
2269 $addressParams = array('id' => $this->address_id);
2270 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2271 $addressDetails = array_values($addressDetails);
2272 $values['address'] = $addressDetails[0]['display'];
2273 }
2274 if ($this->_component == 'contribute') {
2275 if (isset($this->contribution_page_id)) {
2276 CRM_Contribute_BAO_ContributionPage::setValues(
2277 $this->contribution_page_id,
2278 $values
2279 );
2280 if ($this->contribution_page_id) {
2281 // CRM-8254 - override default currency if applicable
2282 $config = CRM_Core_Config::singleton();
2283 $config->defaultCurrency = CRM_Utils_Array::value(
2284 'currency',
2285 $values,
2286 $config->defaultCurrency
2287 );
2288 }
2289 }
2290 // no contribution page -probably back office
2291 else {
2292 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2293 $values['is_email_receipt'] = 1;
2294 $values['title'] = 'Contribution';
2295 }
2296 // set lineItem for contribution
2297 if ($this->id) {
2298 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2299 if (!empty($lineItem)) {
2300 $itemId = key($lineItem);
2301 foreach ($lineItem as &$eachItem) {
2302 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
2303 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2304 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2305 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2306 }
2307 }
2308 $values['lineItem'][0] = $lineItem;
2309 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2310 }
2311 }
2312
2313 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2314 $this->id,
2315 $this->contact_id
2316 );
2317 // if this is onbehalf of contribution then set related contact
2318 if (!empty($relatedContact['individual_id'])) {
2319 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2320 }
2321 }
2322 else {
2323 // event
2324 $eventParams = array(
2325 'id' => $this->_relatedObjects['event']->id,
2326 );
2327 $values['event'] = array();
2328
2329 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2330
2331 //get location details
2332 $locationParams = array(
2333 'entity_id' => $this->_relatedObjects['event']->id,
2334 'entity_table' => 'civicrm_event',
2335 );
2336 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2337
2338 $ufJoinParams = array(
2339 'entity_table' => 'civicrm_event',
2340 'entity_id' => $ids['event'],
2341 'module' => 'CiviEvent',
2342 );
2343
2344 list($custom_pre_id,
2345 $custom_post_ids
2346 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2347
2348 $values['custom_pre_id'] = $custom_pre_id;
2349 $values['custom_post_id'] = $custom_post_ids;
2350
2351 // set lineItem for event contribution
2352 if ($this->id) {
2353 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2354 if (!empty($participantIds)) {
2355 foreach ($participantIds as $pIDs) {
2356 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2357 if (!CRM_Utils_System::isNull($lineItem)) {
2358 $values['lineItem'][] = $lineItem;
2359 }
2360 }
2361 }
2362 }
2363 }
2364
2365 return $values;
2366 }
2367
2368 /**
2369 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2370 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2371 * Note we send directly from this function in some cases because it is only partly refactored
2372 * Don't call this function directly as the signature will change
2373 *
2374 * @param $values
2375 * @param $input
2376 * @param CRM_Core_SMARTY $template
2377 * @param bool $recur
2378 * @param bool $returnMessageText
2379 *
2380 * @return mixed
2381 */
2382 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2383 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2384 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2385 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2386 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
2387 $template->assign('useForMember', TRUE);
2388 }
2389 //assign honor information to receipt message
2390 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
2391
2392 if (isset($softRecord['soft_credit'])) {
2393 //if id of contribution page is present
2394 if (!empty($values['id'])) {
2395 $values['honor'] = array(
2396 'honor_profile_values' => array(),
2397 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2398 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2399 );
2400 $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
2401
2402 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2403 $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2404 }
2405 else {
2406 //offline contribution
2407 $softCreditTypes = $softCredits = array();
2408 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2409 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2410 $softCredits[$key] = array(
2411 'Name' => $softCredit['contact_name'],
2412 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
2413 );
2414 }
2415 $template->assign('softCreditTypes', $softCreditTypes);
2416 $template->assign('softCredits', $softCredits);
2417 }
2418 }
2419
2420 $dao = new CRM_Contribute_DAO_ContributionProduct();
2421 $dao->contribution_id = $this->id;
2422 if ($dao->find(TRUE)) {
2423 $premiumId = $dao->product_id;
2424 $template->assign('option', $dao->product_option);
2425
2426 $productDAO = new CRM_Contribute_DAO_Product();
2427 $productDAO->id = $premiumId;
2428 $productDAO->find(TRUE);
2429 $template->assign('selectPremium', TRUE);
2430 $template->assign('product_name', $productDAO->name);
2431 $template->assign('price', $productDAO->price);
2432 $template->assign('sku', $productDAO->sku);
2433 }
2434 $template->assign('title', CRM_Utils_Array::value('title', $values));
2435 $amount = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
2436 if (empty($amount) && isset($this->total_amount)) {
2437 $amount = $this->total_amount;
2438 }
2439 $template->assign('amount', $amount);
2440 // add the new contribution values
2441 if (strtolower($this->_component) == 'contribute') {
2442 //PCP Info
2443 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2444 $softDAO->contribution_id = $this->id;
2445 if ($softDAO->find(TRUE)) {
2446 $template->assign('pcpBlock', TRUE);
2447 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2448 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2449 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2450
2451 //assign the pcp page title for email subject
2452 $pcpDAO = new CRM_PCP_DAO_PCP();
2453 $pcpDAO->id = $softDAO->pcp_id;
2454 if ($pcpDAO->find(TRUE)) {
2455 $template->assign('title', $pcpDAO->title);
2456 }
2457 }
2458 }
2459
2460 if ($this->financial_type_id) {
2461 $values['financial_type_id'] = $this->financial_type_id;
2462 }
2463
2464
2465 $template->assign('trxn_id', $this->trxn_id);
2466 $template->assign('receive_date',
2467 CRM_Utils_Date::mysqlToIso($this->receive_date)
2468 );
2469 $template->assign('contributeMode', 'notify');
2470 $template->assign('action', $this->is_test ? 1024 : 1);
2471 $template->assign('receipt_text',
2472 CRM_Utils_Array::value('receipt_text',
2473 $values
2474 )
2475 );
2476 $template->assign('is_monetary', 1);
2477 $template->assign('is_recur', (bool) $recur);
2478 $template->assign('currency', $this->currency);
2479 $template->assign('address', CRM_Utils_Address::format($input));
2480 if ($this->_component == 'event') {
2481 $template->assign('title', $values['event']['title']);
2482 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2483 $viewRoles = array();
2484 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2485 $viewRoles[] = $participantRoles[$v];
2486 }
2487 $values['event']['participant_role'] = implode(', ', $viewRoles);
2488 $template->assign('event', $values['event']);
2489 $template->assign('location', $values['location']);
2490 $template->assign('customPre', $values['custom_pre_id']);
2491 $template->assign('customPost', $values['custom_post_id']);
2492
2493 $isTest = FALSE;
2494 if ($this->_relatedObjects['participant']->is_test) {
2495 $isTest = TRUE;
2496 }
2497
2498 $values['params'] = array();
2499 //to get email of primary participant.
2500 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
2501 $primaryAmount[] = array(
2502 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
2503 'amount' => $this->_relatedObjects['participant']->fee_amount,
2504 );
2505 //build an array of cId/pId of participants
2506 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2507 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2508 //send receipt to additional participant if exists
2509 if (count($additionalIDs)) {
2510 $template->assign('isPrimary', 0);
2511 $template->assign('customProfile', NULL);
2512 //set additionalParticipant true
2513 $values['params']['additionalParticipant'] = TRUE;
2514 foreach ($additionalIDs as $pId => $cId) {
2515 $amount = array();
2516 //to change the status pending to completed
2517 $additional = new CRM_Event_DAO_Participant();
2518 $additional->id = $pId;
2519 $additional->contact_id = $cId;
2520 $additional->find(TRUE);
2521 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2522 $additional->status_id = 1;
2523 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2524 //if additional participant dont have email
2525 //use display name.
2526 if (!$additionalParticipantInfo) {
2527 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2528 }
2529 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
2530 $primaryAmount[] = array(
2531 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
2532 'amount' => $additional->fee_amount,
2533 );
2534 $additional->save();
2535 $additional->free();
2536 $template->assign('amount', $amount);
2537 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2538 }
2539 }
2540
2541 //build an array of custom profile and assigning it to template
2542 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2543
2544 if (count($customProfile)) {
2545 $template->assign('customProfile', $customProfile);
2546 }
2547
2548 // for primary contact
2549 $values['params']['additionalParticipant'] = FALSE;
2550 $template->assign('isPrimary', 1);
2551 $template->assign('amount', $primaryAmount);
2552 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2553 if ($this->payment_instrument_id) {
2554 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2555 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2556 }
2557 // carry paylater, since we did not created billing,
2558 // so need to pull email from primary location, CRM-4395
2559 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2560 }
2561 return $template;
2562 }
2563
2564 /**
2565 * Check whether payment processor supports
2566 * cancellation of contribution subscription
2567 *
2568 * @param int $contributionId
2569 * Contribution id.
2570 *
2571 * @param bool $isNotCancelled
2572 *
2573 * @return boolean
2574 */
2575 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2576 $cacheKeyString = "$contributionId";
2577 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2578
2579 static $supportsCancel = array();
2580
2581 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2582 $supportsCancel[$cacheKeyString] = FALSE;
2583 $isCancelled = FALSE;
2584
2585 if ($isNotCancelled) {
2586 $isCancelled = self::isSubscriptionCancelled($contributionId);
2587 }
2588
2589 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2590 if (!empty($paymentObject)) {
2591 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2592 }
2593 }
2594 return $supportsCancel[$cacheKeyString];
2595 }
2596
2597 /**
2598 * Check whether subscription is already cancelled
2599 *
2600 * @param int $contributionId
2601 * Contribution id.
2602 *
2603 * @return string
2604 * contribution status
2605 */
2606 public static function isSubscriptionCancelled($contributionId) {
2607 $sql = "
2608 SELECT cr.contribution_status_id
2609 FROM civicrm_contribution_recur cr
2610 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2611 WHERE con.id = %1 LIMIT 1";
2612 $params = array(1 => array($contributionId, 'Integer'));
2613 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
2614 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
2615 if ($status == 'Cancelled') {
2616 return TRUE;
2617 }
2618 return FALSE;
2619 }
2620
2621 /**
2622 * Create all financial accounts entry
2623 *
2624 * @param array $params
2625 * Contribution object, line item array and params for trxn.
2626 *
2627 *
2628 * @param array $financialTrxnValues
2629 *
2630 * @return null|object
2631 */
2632 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2633 $skipRecords = $update = $return = $isRelatedId = FALSE;
2634
2635 $additionalParticipantId = array();
2636 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2637
2638 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
2639 $entityId = $params['participant_id'];
2640 $entityTable = 'civicrm_participant';
2641 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
2642 }
2643 elseif (!empty($params['membership_id'])) {
2644 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2645 // are created off one contribution should be handled elsewhere
2646 $entityId = $params['membership_id'];
2647 $entityTable = 'civicrm_membership';
2648 }
2649 else {
2650 $entityId = $params['contribution']->id;
2651 $entityTable = 'civicrm_contribution';
2652 }
2653
2654 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
2655 $isRelatedId = TRUE;
2656 }
2657
2658 $entityID[] = $entityId;
2659 if (!empty($additionalParticipantId)) {
2660 $entityID += $additionalParticipantId;
2661 }
2662 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2663 if (empty($params['prevContribution'])) {
2664 $entityID = NULL;
2665 }
2666 else {
2667 $update = TRUE;
2668 }
2669
2670 $statusId = $params['contribution']->contribution_status_id;
2671 // CRM-13964 partial payment
2672 if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2673 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2674 ) {
2675 $partialAmtPay = $params['partial_amount_pay'];
2676 $partialAmtTotal = $params['partial_payment_total'];
2677
2678 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2679 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2680 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
2681 $params['total_amount'] = $partialAmtPay;
2682
2683 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']);
2684 if (empty($balanceTrxnInfo['trxn_id'])) {
2685 // create new balance transaction record
2686 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2687 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2688
2689 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2690 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2691 $balanceTrxnParams['contribution_id'] = $params['contribution']->id;
2692 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2693 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2694 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2695 $balanceTrxnParams['currency'] = $params['contribution']->currency;
2696 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id;
2697 $balanceTrxnParams['status_id'] = $statusId;
2698 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2699 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
2700 if (!empty($params['payment_processor'])) {
2701 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2702 }
2703 CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
2704 }
2705 }
2706
2707 // build line item array if its not set in $params
2708 if (empty($params['line_item']) || $additionalParticipantId) {
2709 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2710 }
2711
2712 if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2713 !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)
2714 ) {
2715 $skipRecords = TRUE;
2716 $pendingStatus = array(
2717 array_search('Pending', $contributionStatuses),
2718 array_search('In Progress', $contributionStatuses),
2719 );
2720 if (in_array(CRM_Utils_Array::value('contribution_status_id', $params), $pendingStatus)) {
2721 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2722 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2723 }
2724 elseif (!empty($params['payment_processor'])) {
2725 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2726 }
2727 elseif (!empty($params['payment_instrument_id'])) {
2728 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
2729 }
2730 else {
2731 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2732 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2733 $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);
2734 }
2735
2736 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
2737 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2738 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
2739 }
2740
2741 //build financial transaction params
2742 $trxnParams = array(
2743 'contribution_id' => $params['contribution']->id,
2744 'to_financial_account_id' => $params['to_financial_account_id'],
2745 'trxn_date' => date('YmdHis'),
2746 'total_amount' => $totalAmount,
2747 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
2748 'net_amount' => CRM_Utils_Array::value('net_amount', $params),
2749 'currency' => $params['contribution']->currency,
2750 'trxn_id' => $params['contribution']->trxn_id,
2751 'status_id' => $statusId,
2752 'payment_instrument_id' => $params['contribution']->payment_instrument_id,
2753 'check_number' => CRM_Utils_Array::value('check_number', $params),
2754 );
2755
2756 if (!empty($params['payment_processor'])) {
2757 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2758 }
2759
2760 if (isset($fromFinancialAccountId)) {
2761 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2762 }
2763
2764 // consider external values passed for recording transaction entry
2765 if (!empty($financialTrxnValues)) {
2766 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2767 }
2768
2769 $params['trxnParams'] = $trxnParams;
2770
2771 if (!empty($params['prevContribution'])) {
2772 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
2773 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
2774 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
2775 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
2776 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
2777
2778
2779 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
2780 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
2781 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
2782 ) {
2783 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2784 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2785 }
2786
2787 //if financial type is changed
2788 if (!empty($params['financial_type_id']) &&
2789 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
2790 ) {
2791 $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2792 $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId);
2793 $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId);
2794 if ($oldFinancialAccount != $newFinancialAccount) {
2795 $params['total_amount'] = 0;
2796 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
2797 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2798 $params['prevContribution']->financial_type_id, $relationTypeId);
2799 }
2800 else {
2801 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
2802 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2803 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2804 }
2805 }
2806 self::updateFinancialAccounts($params, 'changeFinancialType');
2807 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2808 $params['financial_account_id'] = $newFinancialAccount;
2809 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2810 self::updateFinancialAccounts($params);
2811 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2812 }
2813 }
2814
2815 //Update contribution status
2816 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
2817 if (!empty($params['contribution_status_id']) &&
2818 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
2819 ) {
2820 //Update Financial Records
2821 self::updateFinancialAccounts($params, 'changedStatus');
2822 }
2823
2824 // change Payment Instrument for a Completed contribution
2825 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2826 // instrument is null and now new payment instrument is added along with the payment
2827 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2828 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
2829 if (array_key_exists('payment_instrument_id', $params)) {
2830 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2831 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
2832 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)
2833 ) {
2834 //check if status is changed from Pending to Completed
2835 // do not update payment instrument changes for Pending to Completed
2836 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
2837 in_array($params['prevContribution']->contribution_status_id, $pendingStatus))
2838 ) {
2839 // for all other statuses create new financial records
2840 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2841 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2842 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2843 }
2844 }
2845 elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
2846 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
2847 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id
2848 ) {
2849 // for any other payment instrument changes create new financial records
2850 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2851 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2852 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2853 }
2854 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
2855 $params['contribution']->check_number != $params['prevContribution']->check_number
2856 ) {
2857 // another special case when check number is changed, create new financial records
2858 // create financial trxn with negative amount
2859 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2860 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2861 // create financial trxn with positive amount
2862 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
2863 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2864 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2865 }
2866 }
2867
2868 //if Change contribution amount
2869 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2870 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2871 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2872 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
2873 if (isset($totalAmount) &&
2874 $totalAmount != $params['prevContribution']->total_amount
2875 ) {
2876 //Update Financial Records
2877 $params['trxnParams']['from_financial_account_id'] = NULL;
2878 self::updateFinancialAccounts($params, 'changedAmount');
2879 }
2880 }
2881
2882 if (!$update) {
2883 // records finanical trxn and entity financial trxn
2884 // also make it available as return value
2885 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
2886 $params['entity_id'] = $financialTxn->id;
2887 }
2888 }
2889 // record line items and finacial items
2890 if (empty($params['skipLineItem'])) {
2891 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
2892 }
2893
2894 // create batch entry if batch_id is passed
2895 if (!empty($params['batch_id'])) {
2896 $entityParams = array(
2897 'batch_id' => $params['batch_id'],
2898 'entity_table' => 'civicrm_financial_trxn',
2899 'entity_id' => $financialTxn->id,
2900 );
2901 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
2902 }
2903
2904 // when a fee is charged
2905 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
2906 CRM_Core_BAO_FinancialTrxn::recordFees($params);
2907 }
2908
2909 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2910 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
2911 ) {
2912 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2913 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
2914 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
2915 }
2916 unset($params['line_item']);
2917
2918 return $return;
2919 }
2920
2921 /**
2922 * Update all financial accounts entry
2923 *
2924 * @param array $params
2925 * Contribution object, line item array and params for trxn.
2926 *
2927 * @param string $context
2928 * Update scenarios.
2929 *
2930 * @param null $skipTrxn
2931 *
2932 */
2933 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2934 $itemAmount = $trxnID = NULL;
2935 //get all the statuses
2936 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2937 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2938 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
2939 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2940 && $context == 'changePaymentInstrument'
2941 ) {
2942 return;
2943 }
2944 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
2945 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
2946 }
2947 if ($context == 'changedStatus') {
2948 //get all the statuses
2949 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2950
2951 if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2952 && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
2953 || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))
2954 ) {
2955 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2956 }
2957 elseif (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2958 && $params['prevContribution']->is_pay_later) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)
2959 ) {
2960 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
2961 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
2962 $params['trxnParams']['to_financial_account_id'] = NULL;
2963 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2964 }
2965 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2966 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2967 $financialTypeID, $relationTypeId);
2968 }
2969 $itemAmount = $params['trxnParams']['total_amount'];
2970 }
2971 elseif ($context == 'changePaymentInstrument') {
2972 if ($params['trxnParams']['total_amount'] < 0) {
2973 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
2974 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2975 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2976 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2977 }
2978 }
2979 else {
2980 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
2981 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2982 }
2983 }
2984 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
2985 $params['entity_id'] = $trxn->id;
2986
2987 if ($context == 'changedStatus') {
2988 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2989 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
2990 && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
2991 ) {
2992 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
2993 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
2994
2995 $entityParams = array(
2996 'entity_table' => 'civicrm_financial_item',
2997 'financial_trxn_id' => $trxn->id,
2998 );
2999 if (empty($params['line_item'])) {
3000 //CRM-15296
3001 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3002 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3003 // & this can be removed
3004 return;
3005 }
3006 foreach ($params['line_item'] as $fieldId => $fields) {
3007 foreach ($fields as $fieldValueId => $fieldValues) {
3008 $fparams = array(
3009 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3010 2 => array($fieldValues['id'], 'Integer'),
3011 );
3012 CRM_Core_DAO::executeQuery($query, $fparams);
3013 $fparams = array(
3014 1 => array($fieldValues['id'], 'Integer'),
3015 );
3016 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
3017 while ($financialItem->fetch()) {
3018 $entityParams['entity_id'] = $financialItem->id;
3019 $entityParams['amount'] = $financialItem->amount;
3020 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
3021 }
3022 }
3023 }
3024 return;
3025 }
3026 }
3027 if ($context != 'changePaymentInstrument') {
3028 $itemParams['entity_table'] = 'civicrm_line_item';
3029 $trxnIds['id'] = $params['entity_id'];
3030 foreach ($params['line_item'] as $fieldId => $fields) {
3031 foreach ($fields as $fieldValueId => $fieldValues) {
3032 $prevParams['entity_id'] = $fieldValues['id'];
3033 $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray);
3034
3035 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
3036 if ($params['contribution']->receive_date) {
3037 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
3038 }
3039
3040 $financialAccount = $prevfinancialItem->financial_account_id;
3041 if (!empty($params['financial_account_id'])) {
3042 $financialAccount = $params['financial_account_id'];
3043 }
3044
3045 $currency = $params['prevContribution']->currency;
3046 if ($params['contribution']->currency) {
3047 $currency = $params['contribution']->currency;
3048 }
3049 $diff = 1;
3050 if (!empty($params['is_quick_config'])) {
3051 $amount = $itemAmount;
3052 if (!$amount) {
3053 $amount = $params['total_amount'];
3054 }
3055 }
3056 else {
3057 if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)
3058 || $params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
3059 ) {
3060 $diff = -1;
3061 }
3062 $amount = $diff * $fieldValues['line_total'];
3063 }
3064
3065 $itemParams = array(
3066 'transaction_date' => $receiveDate,
3067 'contact_id' => $params['prevContribution']->contact_id,
3068 'currency' => $currency,
3069 'amount' => $amount,
3070 'description' => $prevfinancialItem->description,
3071 'status_id' => $prevfinancialItem->status_id,
3072 'financial_account_id' => $financialAccount,
3073 'entity_table' => 'civicrm_line_item',
3074 'entity_id' => $fieldValues['id'],
3075 );
3076 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3077
3078 if ($fieldValues['tax_amount']) {
3079 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
3080 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
3081 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3082 $itemParams['description'] = $taxTerm;
3083 if ($fieldValues['financial_type_id']) {
3084 $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']);
3085 }
3086 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3087 }
3088 }
3089 }
3090 }
3091 }
3092
3093 /**
3094 * Check status validation on update of a contribution
3095 *
3096 * @param array $values
3097 * Previous form values before submit.
3098 *
3099 * @param array $fields
3100 * The input form values.
3101 *
3102 * @param array $errors
3103 * List of errors.
3104 *
3105 * @return bool
3106 */
3107 public static function checkStatusValidation($values, &$fields, &$errors) {
3108 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
3109 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3110 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3111 return FALSE;
3112 }
3113 }
3114 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3115 $checkStatus = array(
3116 'Cancelled' => array('Completed', 'Refunded'),
3117 'Completed' => array('Cancelled', 'Refunded'),
3118 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3119 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3120 'Refunded' => array('Cancelled', 'Completed'),
3121 );
3122
3123 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3124 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3125 1 => $contributionStatuses[$values['contribution_status_id']],
3126 2 => $contributionStatuses[$fields['contribution_status_id']],
3127 ));
3128 }
3129 }
3130
3131 /**
3132 * Delete contribution of contact
3133 *
3134 * CRM-12155
3135 *
3136 * @param int $contactId
3137 * Contact id.
3138 *
3139 */
3140 public static function deleteContactContribution($contactId) {
3141 $contribution = new CRM_Contribute_DAO_Contribution();
3142 $contribution->contact_id = $contactId;
3143 $contribution->find();
3144 while ($contribution->fetch()) {
3145 self::deleteContribution($contribution->id);
3146 }
3147 }
3148
3149 /**
3150 * Get options for a given contribution field.
3151 * @see CRM_Core_DAO::buildOptions
3152 *
3153 * @param string $fieldName
3154 * @param string $context
3155 * @see CRM_Core_DAO::buildOptionsContext.
3156 * @param array $props
3157 * 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 }