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