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