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