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