5376860bc893dc7e99212d968a2ec63c7c9aef19
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
36
37 /**
38 * Static field for all the contribution information that we can potentially import
39 *
40 * @var array
41 */
42 static $_importableFields = NULL;
43
44 /**
45 * Static field for all the contribution information that we can potentially export
46 *
47 * @var array
48 */
49 static $_exportableFields = NULL;
50
51 /**
52 * Field for all the objects related to this contribution
53 * @var array of objects (e.g membership object, participant object)
54 */
55 public $_relatedObjects = array();
56
57 /**
58 * Field for the component - either 'event' (participant) or 'contribute'
59 * (any item related to a contribution page e.g. membership, pledge, contribution)
60 * This is used for composing messages because they have dependency on the
61 * contribution_page or event page - although over time we may eliminate that
62 *
63 * @var string component or event
64 */
65 public $_component = NULL;
66
67 /**
68 * 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 // check if activity record exist for this contribution, if
371 // not add activity
372 $activity = new CRM_Activity_DAO_Activity();
373 $activity->source_record_id = $contribution->id;
374 $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
375 'Contribution',
376 'name'
377 );
378 if (!$activity->find(TRUE)) {
379 CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
380 }
381 else {
382 // CRM-13237 : if activity record found, update it with campaign id of contribution
383 CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
384 }
385
386 // Handle soft credit and / or link to personal campaign page
387 $softIDs = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id);
388
389 //Delete PCP against this contribution and create new on submitted PCP information
390 $pcpId = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id, TRUE);
391 if ($pcpId) {
392 $deleteParams = array('id' => $pcpId);
393 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
394 }
395 if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
396 $softParams = array();
397 $softParams['contribution_id'] = $contribution->id;
398 $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
399 $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
400 $pcp['pcp_made_through_id'], 'contact_id'
401 );
402 $softParams['currency'] = $contribution->currency;
403 $softParams['amount'] = $contribution->total_amount;
404 $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
405 $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
406 $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
407 $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
408 $contributionSoft = CRM_Contribute_BAO_ContributionSoft::add($softParams);
409 //Send notification to owner for PCP
410 if ($contributionSoft->pcp_id) {
411 CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
412 }
413 }
414 if (isset($params['soft_credit'])) {
415 $softParams = $params['soft_credit'];
416
417 if (!empty($softIDs)) {
418 foreach ($softIDs as $softID) {
419 if (!in_array($softID, $params['soft_credit_ids'])) {
420 $deleteParams = array('id' => $softID);
421 CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
422 }
423 }
424 }
425
426 foreach ($softParams as $softParam) {
427 $softParam['contribution_id'] = $contribution->id;
428 $softParam['currency'] = $contribution->currency;
429 //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
430 if (empty($softParam['amount'])) {
431 $softParam['amount'] = $contribution->total_amount;
432 }
433 CRM_Contribute_BAO_ContributionSoft::add($softParam);
434 }
435 }
436
437 $transaction->commit();
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 if (!empty($params['receive_date'])) {
1636 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
1637 $membership->end_date,
1638 $membership->join_date,
1639 $params['receive_date'],
1640 FALSE,
1641 $membership->membership_type_id,
1642 (array) $membership
1643 );
1644 $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id);
1645 $membership->save();
1646 }
1647
1648 if ($currentMembership) {
1649 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL);
1650 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms);
1651 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1652 }
1653 else {
1654 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms);
1655 }
1656
1657 //get the status for membership.
1658 $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'],
1659 $dates['end_date'],
1660 $dates['join_date'],
1661 'today',
1662 TRUE,
1663 $membership->membership_type_id,
1664 (array) $membership
1665 );
1666
1667 $formattedParams = array(
1668 'status_id' => CRM_Utils_Array::value('id', $calcStatus,
1669 array_search('Current', $membershipStatuses)
1670 ),
1671 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format),
1672 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format),
1673 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format),
1674 );
1675
1676 CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams);
1677
1678 $membership->copyValues($formattedParams);
1679 $membership->save();
1680
1681 //updating the membership log
1682 $membershipLog = array();
1683 $membershipLog = $formattedParams;
1684 $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format);
1685 $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date'];
1686
1687 $membershipLog['start_date'] = $logStartDate;
1688 $membershipLog['membership_id'] = $membership->id;
1689 $membershipLog['modified_id'] = $membership->contact_id;
1690 $membershipLog['modified_date'] = date('Ymd');
1691 $membershipLog['membership_type_id'] = $membership->membership_type_id;
1692
1693 CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
1694
1695 //update related Memberships.
1696 CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams);
1697
1698 $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'],
1699 '%B %E%f, %Y'
1700 );
1701 $updateResult['updatedComponents']['CiviMember'] = $membership->status_id;
1702 if ($processContributionObject) {
1703 $processContribution = TRUE;
1704 }
1705
1706 CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
1707 }
1708 }
1709 }
1710
1711 if ($participant) {
1712 $updatedStatusId = array_search('Registered', $participantStatuses);
1713 CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE);
1714
1715 $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId;
1716 if ($processContributionObject) {
1717 $processContribution = TRUE;
1718 }
1719 }
1720
1721 if ($pledgePayment) {
1722 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId);
1723
1724 $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId;
1725 if ($processContributionObject) {
1726 $processContribution = TRUE;
1727 }
1728 }
1729 }
1730
1731 // process contribution object.
1732 if ($processContribution) {
1733 $contributionParams = array();
1734 $fields = array(
1735 'contact_id',
1736 'total_amount',
1737 'receive_date',
1738 'is_test',
1739 'campaign_id',
1740 'payment_instrument_id',
1741 'trxn_id',
1742 'invoice_id',
1743 'financial_type_id',
1744 'contribution_status_id',
1745 'non_deductible_amount',
1746 'receipt_date',
1747 'check_number',
1748 );
1749 foreach ($fields as $field) {
1750 if (empty($params[$field])) {
1751 continue;
1752 }
1753 $contributionParams[$field] = $params[$field];
1754 }
1755
1756 $ids = array('contribution' => $contributionId);
1757 $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1758 }
1759
1760 return $updateResult;
1761 }
1762
1763 /**
1764 * Returns all contribution related object ids.
1765 *
1766 * @param $contributionId
1767 *
1768 * @return array
1769 */
1770 public static function getComponentDetails($contributionId) {
1771 $componentDetails = $pledgePayment = array();
1772 if (!$contributionId) {
1773 return $componentDetails;
1774 }
1775
1776 $query = "
1777 SELECT c.id as contribution_id,
1778 c.contact_id as contact_id,
1779 c.contribution_recur_id,
1780 mp.membership_id as membership_id,
1781 m.membership_type_id as membership_type_id,
1782 pp.participant_id as participant_id,
1783 p.event_id as event_id,
1784 pgp.id as pledge_payment_id
1785 FROM civicrm_contribution c
1786 LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
1787 LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
1788 LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
1789 LEFT JOIN civicrm_membership m ON m.id = mp.membership_id
1790 LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id
1791 WHERE c.id = $contributionId";
1792
1793 $dao = CRM_Core_DAO::executeQuery($query);
1794 $componentDetails = array();
1795
1796 while ($dao->fetch()) {
1797 $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute';
1798 $componentDetails['contact_id'] = $dao->contact_id;
1799 if ($dao->event_id) {
1800 $componentDetails['event'] = $dao->event_id;
1801 }
1802 if ($dao->participant_id) {
1803 $componentDetails['participant'] = $dao->participant_id;
1804 }
1805 if ($dao->membership_id) {
1806 if (!isset($componentDetails['membership'])) {
1807 $componentDetails['membership'] = $componentDetails['membership_type'] = array();
1808 }
1809 $componentDetails['membership'][] = $dao->membership_id;
1810 $componentDetails['membership_type'][] = $dao->membership_type_id;
1811 }
1812 if ($dao->pledge_payment_id) {
1813 $pledgePayment[] = $dao->pledge_payment_id;
1814 }
1815 if ($dao->contribution_recur_id) {
1816 $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
1817 }
1818 }
1819
1820 if ($pledgePayment) {
1821 $componentDetails['pledge_payment'] = $pledgePayment;
1822 }
1823
1824 return $componentDetails;
1825 }
1826
1827 /**
1828 * @param int $contactId
1829 * @param bool $includeSoftCredit
1830 *
1831 * @return null|string
1832 */
1833 public static function contributionCount($contactId, $includeSoftCredit = TRUE) {
1834 if (!$contactId) {
1835 return 0;
1836 }
1837
1838 $contactContributionsSQL = "
1839 SELECT contribution.id AS id
1840 FROM civicrm_contribution contribution
1841 WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} ";
1842
1843 $contactSoftCreditContributionsSQL = "
1844 SELECT contribution.id
1845 FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution
1846 ON ( contribution.id = softContribution.contribution_id )
1847 WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} ";
1848 $query = "SELECT count( x.id ) count FROM ( ";
1849 $query .= $contactContributionsSQL;
1850
1851 if ($includeSoftCredit) {
1852 $query .= " UNION ";
1853 $query .= $contactSoftCreditContributionsSQL;
1854 }
1855
1856 $query .= ") x";
1857
1858 return CRM_Core_DAO::singleValueQuery($query);
1859 }
1860
1861 /**
1862 * Get individual id for onbehalf contribution.
1863 *
1864 * @param int $contributionId
1865 * Contribution id.
1866 * @param int $contributorId
1867 * Contributor id.
1868 *
1869 * @return array
1870 * containing organization id and individual id
1871 */
1872 public static function getOnbehalfIds($contributionId, $contributorId = NULL) {
1873
1874 $ids = array();
1875
1876 if (!$contributionId) {
1877 return $ids;
1878 }
1879
1880 // fetch contributor id if null
1881 if (!$contributorId) {
1882 $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1883 $contributionId, 'contact_id'
1884 );
1885 }
1886
1887 $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
1888 $activityTypeId = array_search('Contribution', $activityTypeIds);
1889
1890 if ($activityTypeId && $contributorId) {
1891 $activityQuery = "
1892 SELECT civicrm_activity_contact.contact_id
1893 FROM civicrm_activity_contact
1894 INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id
1895 WHERE civicrm_activity.activity_type_id = %1
1896 AND civicrm_activity.source_record_id = %2
1897 AND civicrm_activity_contact.record_type_id = %3
1898 ";
1899
1900 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
1901 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1902
1903 $params = array(
1904 1 => array($activityTypeId, 'Integer'),
1905 2 => array($contributionId, 'Integer'),
1906 3 => array($sourceID, 'Integer'),
1907 );
1908
1909 $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params);
1910
1911 // for on behalf contribution source is individual and contributor is organization
1912 if ($sourceContactId && $sourceContactId != $contributorId) {
1913 $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name');
1914 // get rel type id for employee of relation
1915 foreach ($relationshipTypeIds as $id => $typeVals) {
1916 if ($typeVals['name_a_b'] == 'Employee of') {
1917 $relationshipTypeId = $id;
1918 break;
1919 }
1920 }
1921
1922 $rel = new CRM_Contact_DAO_Relationship();
1923 $rel->relationship_type_id = $relationshipTypeId;
1924 $rel->contact_id_a = $sourceContactId;
1925 $rel->contact_id_b = $contributorId;
1926 if ($rel->find(TRUE)) {
1927 $ids['individual_id'] = $rel->contact_id_a;
1928 $ids['organization_id'] = $rel->contact_id_b;
1929 }
1930 }
1931 }
1932
1933 return $ids;
1934 }
1935
1936 /**
1937 * @return array
1938 */
1939 public static function getContributionDates() {
1940 $config = CRM_Core_Config::singleton();
1941 $currentMonth = date('m');
1942 $currentDay = date('d');
1943 if ((int ) $config->fiscalYearStart['M'] > $currentMonth ||
1944 ((int ) $config->fiscalYearStart['M'] == $currentMonth &&
1945 (int ) $config->fiscalYearStart['d'] > $currentDay
1946 )
1947 ) {
1948 $year = date('Y') - 1;
1949 }
1950 else {
1951 $year = date('Y');
1952 }
1953 $year = array('Y' => $year);
1954 $yearDate = $config->fiscalYearStart;
1955 $yearDate = array_merge($year, $yearDate);
1956 $yearDate = CRM_Utils_Date::format($yearDate);
1957
1958 $monthDate = date('Ym') . '01';
1959
1960 $now = date('Ymd');
1961
1962 return array(
1963 'now' => $now,
1964 'yearDate' => $yearDate,
1965 'monthDate' => $monthDate,
1966 );
1967 }
1968
1969 /**
1970 * Load objects relations to contribution object.
1971 * Objects are stored in the $_relatedObjects property
1972 * In the first instance we are just moving functionality from BASEIpn -
1973 * @see http://issues.civicrm.org/jira/browse/CRM-9996
1974 *
1975 * Note that the unit test for the BaseIPN class tests this function
1976 *
1977 * @param array $input
1978 * Input as delivered from Payment Processor.
1979 * @param array $ids
1980 * Ids as Loaded by Payment Processor.
1981 * @param bool $required
1982 * Is Payment processor / contribution page required.
1983 * @param bool $loadAll
1984 * Load all related objects - even where id not passed in? (allows API to call this).
1985 *
1986 * @return bool
1987 * @throws Exception
1988 */
1989 public function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = FALSE) {
1990 if ($loadAll) {
1991 $ids = array_merge($this->getComponentDetails($this->id), $ids);
1992 if (empty($ids['contact']) && isset($this->contact_id)) {
1993 $ids['contact'] = $this->contact_id;
1994 }
1995 }
1996 if (empty($this->_component)) {
1997 if (!empty($ids['event'])) {
1998 $this->_component = 'event';
1999 }
2000 else {
2001 $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
2002 }
2003 }
2004 $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
2005 $contributionType = new CRM_Financial_BAO_FinancialType();
2006 $contributionType->id = $this->financial_type_id;
2007 if (!$contributionType->find(TRUE)) {
2008 throw new Exception("Could not find financial type record: " . $this->financial_type_id);
2009 }
2010 if (!empty($ids['contact'])) {
2011 $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
2012 $this->_relatedObjects['contact']->id = $ids['contact'];
2013 $this->_relatedObjects['contact']->find(TRUE);
2014 }
2015 $this->_relatedObjects['contributionType'] = $contributionType;
2016
2017 if ($this->_component == 'contribute') {
2018 // retrieve the other optional objects first so
2019 // stuff down the line can use this info and do things
2020 // CRM-6056
2021 //in any case get the memberships associated with the contribution
2022 //because we now support multiple memberships w/ price set
2023 // see if there are any other memberships to be considered for same contribution.
2024 $query = "
2025 SELECT membership_id
2026 FROM civicrm_membership_payment
2027 WHERE contribution_id = %1 ";
2028 $params = array(1 => array($this->id, 'Integer'));
2029
2030 $dao = CRM_Core_DAO::executeQuery($query, $params);
2031 while ($dao->fetch()) {
2032 if ($dao->membership_id) {
2033 if (!is_array($ids['membership'])) {
2034 $ids['membership'] = array();
2035 }
2036 $ids['membership'][] = $dao->membership_id;
2037 }
2038 }
2039
2040 if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
2041 foreach ($ids['membership'] as $id) {
2042 if (!empty($id)) {
2043 $membership = new CRM_Member_BAO_Membership();
2044 $membership->id = $id;
2045 if (!$membership->find(TRUE)) {
2046 throw new Exception("Could not find membership record: $id");
2047 }
2048 $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
2049 $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
2050 $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
2051 $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
2052 $membership->free();
2053 }
2054 }
2055 }
2056
2057 if (!empty($ids['pledge_payment'])) {
2058
2059 foreach ($ids['pledge_payment'] as $key => $paymentID) {
2060 if (empty($paymentID)) {
2061 continue;
2062 }
2063 $payment = new CRM_Pledge_BAO_PledgePayment();
2064 $payment->id = $paymentID;
2065 if (!$payment->find(TRUE)) {
2066 throw new Exception("Could not find pledge payment record: " . $paymentID);
2067 }
2068 $this->_relatedObjects['pledge_payment'][] = $payment;
2069 }
2070 }
2071
2072 if (!empty($ids['contributionRecur'])) {
2073 $recur = new CRM_Contribute_BAO_ContributionRecur();
2074 $recur->id = $ids['contributionRecur'];
2075 if (!$recur->find(TRUE)) {
2076 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
2077 }
2078 $this->_relatedObjects['contributionRecur'] = &$recur;
2079 //get payment processor id from recur object.
2080 $paymentProcessorID = $recur->payment_processor_id;
2081 }
2082 //for normal contribution get the payment processor id.
2083 if (!$paymentProcessorID) {
2084 if ($this->contribution_page_id) {
2085 // get the payment processor id from contribution page
2086 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
2087 $this->contribution_page_id,
2088 'payment_processor'
2089 );
2090 }
2091 //fail to load payment processor id.
2092 elseif (empty($ids['pledge_payment'])) {
2093 $loadObjectSuccess = TRUE;
2094 if ($required) {
2095 throw new Exception("Could not find contribution page for contribution record: " . $this->id);
2096 }
2097 return $loadObjectSuccess;
2098 }
2099 }
2100 }
2101 else {
2102 // we are in event mode
2103 // make sure event exists and is valid
2104 $event = new CRM_Event_BAO_Event();
2105 $event->id = $ids['event'];
2106 if ($ids['event'] &&
2107 !$event->find(TRUE)
2108 ) {
2109 throw new Exception("Could not find event: " . $ids['event']);
2110 }
2111
2112 $this->_relatedObjects['event'] = &$event;
2113
2114 $participant = new CRM_Event_BAO_Participant();
2115 $participant->id = $ids['participant'];
2116 if ($ids['participant'] &&
2117 !$participant->find(TRUE)
2118 ) {
2119 throw new Exception("Could not find participant: " . $ids['participant']);
2120 }
2121 $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
2122
2123 $this->_relatedObjects['participant'] = &$participant;
2124
2125 if (!$paymentProcessorID) {
2126 $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
2127 }
2128 }
2129
2130 if ($paymentProcessorID) {
2131 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID,
2132 $this->is_test ? 'test' : 'live'
2133 );
2134 $ids['paymentProcessor'] = $paymentProcessorID;
2135 $this->_relatedObjects['paymentProcessor'] = &$paymentProcessor;
2136 }
2137 elseif ($required) {
2138 throw new Exception("Could not find payment processor for contribution record: " . $this->id);
2139 }
2140
2141 return TRUE;
2142 }
2143
2144 /**
2145 * Create array of message information - ie. return html version, txt version, to field
2146 *
2147 * @param array $input
2148 * Incoming information.
2149 * - is_recur - should this be treated as recurring (not sure why you wouldn't
2150 * just check presence of recur object but maintaining legacy approach
2151 * to be careful)
2152 * @param array $ids
2153 * IDs of related objects.
2154 * @param array $values
2155 * Any values that may have already been compiled by calling process.
2156 * This is augmented by values 'gathered' by gatherMessageValues
2157 * @param bool $recur
2158 * @param bool $returnMessageText
2159 * Distinguishes between whether to send message or return.
2160 * message text. We are working towards this function ALWAYS returning message text & calling
2161 * function doing emails / pdfs with it
2162 *
2163 * @return array
2164 * messages
2165 * @throws Exception
2166 */
2167 public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
2168 if (empty($this->_relatedObjects)) {
2169 $this->loadRelatedObjects($input, $ids);
2170 }
2171 if (empty($this->_component)) {
2172 $this->_component = CRM_Utils_Array::value('component', $input);
2173 }
2174
2175 //not really sure what params might be passed in but lets merge em into values
2176 $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values);
2177 $template = CRM_Core_Smarty::singleton();
2178 $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText);
2179 //what does recur 'mean here - to do with payment processor return functionality but
2180 // what is the importance
2181 if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) {
2182 $paymentObject = &CRM_Core_Payment::singleton(
2183 $this->is_test ? 'test' : 'live',
2184 $this->_relatedObjects['paymentProcessor']
2185 );
2186
2187 $entityID = $entity = NULL;
2188 if (isset($ids['contribution'])) {
2189 $entity = 'contribution';
2190 $entityID = $ids['contribution'];
2191 }
2192 if (!empty($ids['membership'])) {
2193 //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
2194 // 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
2195 // line having loaded an array
2196 $ids['membership'] = (array) $ids['membership'];
2197 $entity = 'membership';
2198 $entityID = $ids['membership'][0];
2199 }
2200
2201 $url = $paymentObject->subscriptionURL($entityID, $entity);
2202 $template->assign('cancelSubscriptionUrl', $url);
2203
2204 $url = $paymentObject->subscriptionURL($entityID, $entity, 'billing');
2205 $template->assign('updateSubscriptionBillingUrl', $url);
2206
2207 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2208 $template->assign('updateSubscriptionUrl', $url);
2209
2210 if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
2211 //direct mode showing billing block, so use directIPN for temporary
2212 $template->assign('contributeMode', 'directIPN');
2213 }
2214 }
2215 // todo remove strtolower - check consistency
2216 if (strtolower($this->_component) == 'event') {
2217 return CRM_Event_BAO_Event::sendMail($ids['contact'], $values,
2218 $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText
2219 );
2220 }
2221 else {
2222 $values['contribution_id'] = $this->id;
2223 if (!empty($ids['related_contact'])) {
2224 $values['related_contact'] = $ids['related_contact'];
2225 if (isset($ids['onbehalf_dupe_alert'])) {
2226 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
2227 }
2228 $entityBlock = array(
2229 'contact_id' => $ids['contact'],
2230 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType',
2231 'Home', 'id', 'name'
2232 ),
2233 );
2234 $address = CRM_Core_BAO_Address::getValues($entityBlock);
2235 $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
2236 }
2237 $isTest = FALSE;
2238 if ($this->is_test) {
2239 $isTest = TRUE;
2240 }
2241 if (!empty($this->_relatedObjects['membership'])) {
2242 foreach ($this->_relatedObjects['membership'] as $membership) {
2243 if ($membership->id) {
2244 $values['isMembership'] = TRUE;
2245
2246 // need to set the membership values here
2247 $template->assign('membership_assign', 1);
2248 $template->assign('membership_name',
2249 CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)
2250 );
2251 $template->assign('mem_start_date', $membership->start_date);
2252 $template->assign('mem_join_date', $membership->join_date);
2253 $template->assign('mem_end_date', $membership->end_date);
2254 $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label');
2255 $template->assign('mem_status', $membership_status);
2256 if ($membership_status == 'Pending' && $membership->is_pay_later == 1) {
2257 $template->assign('is_pay_later', 1);
2258 }
2259
2260 // if separate payment there are two contributions recorded and the
2261 // admin will need to send a receipt for each of them separately.
2262 // we dont link the two in the db (but can potentially infer it if needed)
2263 $template->assign('is_separate_payment', 0);
2264
2265 if ($recur && $paymentObject) {
2266 $url = $paymentObject->subscriptionURL($membership->id, 'membership');
2267 $template->assign('cancelSubscriptionUrl', $url);
2268 $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing');
2269 $template->assign('updateSubscriptionBillingUrl', $url);
2270 $url = $paymentObject->subscriptionURL($entityID, $entity, 'update');
2271 $template->assign('updateSubscriptionUrl', $url);
2272 }
2273
2274 $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2275
2276 return $result;
2277 // otherwise if its about sending emails, continue sending without return, as we
2278 // don't want to exit the loop.
2279 }
2280 }
2281 }
2282 else {
2283 return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
2284 }
2285 }
2286 }
2287
2288 /**
2289 * Gather values for contribution mail - this function has been created
2290 * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
2291 * Values related to the contribution in question are gathered
2292 *
2293 * @param array $input
2294 * Input into function (probably from payment processor).
2295 * @param array $values
2296 * @param array $ids
2297 * The set of ids related to the input.
2298 *
2299 * @return array
2300 */
2301 public function _gatherMessageValues($input, &$values, $ids = array()) {
2302 // set display address of contributor
2303 if ($this->address_id) {
2304 $addressParams = array('id' => $this->address_id);
2305 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
2306 $addressDetails = array_values($addressDetails);
2307 $values['address'] = $addressDetails[0]['display'];
2308 }
2309 if ($this->_component == 'contribute') {
2310 if (isset($this->contribution_page_id)) {
2311 CRM_Contribute_BAO_ContributionPage::setValues(
2312 $this->contribution_page_id,
2313 $values
2314 );
2315 if ($this->contribution_page_id) {
2316 // CRM-8254 - override default currency if applicable
2317 $config = CRM_Core_Config::singleton();
2318 $config->defaultCurrency = CRM_Utils_Array::value(
2319 'currency',
2320 $values,
2321 $config->defaultCurrency
2322 );
2323 }
2324 }
2325 // no contribution page -probably back office
2326 else {
2327 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
2328 $values['is_email_receipt'] = 1;
2329 $values['title'] = 'Contribution';
2330 }
2331 // set lineItem for contribution
2332 if ($this->id) {
2333 $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
2334 if (!empty($lineItem)) {
2335 $itemId = key($lineItem);
2336 foreach ($lineItem as &$eachItem) {
2337 if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
2338 $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
2339 $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
2340 $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
2341 }
2342 }
2343 $values['lineItem'][0] = $lineItem;
2344 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
2345 }
2346 }
2347
2348 $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds(
2349 $this->id,
2350 $this->contact_id
2351 );
2352 // if this is onbehalf of contribution then set related contact
2353 if (!empty($relatedContact['individual_id'])) {
2354 $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
2355 }
2356 }
2357 else {
2358 // event
2359 $eventParams = array(
2360 'id' => $this->_relatedObjects['event']->id,
2361 );
2362 $values['event'] = array();
2363
2364 CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
2365
2366 //get location details
2367 $locationParams = array(
2368 'entity_id' => $this->_relatedObjects['event']->id,
2369 'entity_table' => 'civicrm_event',
2370 );
2371 $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
2372
2373 $ufJoinParams = array(
2374 'entity_table' => 'civicrm_event',
2375 'entity_id' => $ids['event'],
2376 'module' => 'CiviEvent',
2377 );
2378
2379 list($custom_pre_id,
2380 $custom_post_ids
2381 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
2382
2383 $values['custom_pre_id'] = $custom_pre_id;
2384 $values['custom_post_id'] = $custom_post_ids;
2385
2386 // set lineItem for event contribution
2387 if ($this->id) {
2388 $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
2389 if (!empty($participantIds)) {
2390 foreach ($participantIds as $pIDs) {
2391 $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
2392 if (!CRM_Utils_System::isNull($lineItem)) {
2393 $values['lineItem'][] = $lineItem;
2394 }
2395 }
2396 }
2397 }
2398 }
2399
2400 return $values;
2401 }
2402
2403 /**
2404 * Apply variables for message to smarty template - this function is part of analysing what is in the huge
2405 * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
2406 * Note we send directly from this function in some cases because it is only partly refactored
2407 * Don't call this function directly as the signature will change
2408 *
2409 * @param $values
2410 * @param $input
2411 * @param CRM_Core_SMARTY $template
2412 * @param bool $recur
2413 * @param bool $returnMessageText
2414 *
2415 * @return mixed
2416 */
2417 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) {
2418 $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
2419 $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
2420 $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
2421 if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
2422 $template->assign('useForMember', TRUE);
2423 }
2424 //assign honor information to receipt message
2425 $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
2426
2427 if (isset($softRecord['soft_credit'])) {
2428 //if id of contribution page is present
2429 if (!empty($values['id'])) {
2430 $values['honor'] = array(
2431 'honor_profile_values' => array(),
2432 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'),
2433 'honor_id' => $softRecord['soft_credit'][1]['contact_id'],
2434 );
2435 $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
2436
2437 $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
2438 $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
2439 }
2440 else {
2441 //offline contribution
2442 $softCreditTypes = $softCredits = array();
2443 foreach ($softRecord['soft_credit'] as $key => $softCredit) {
2444 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
2445 $softCredits[$key] = array(
2446 'Name' => $softCredit['contact_name'],
2447 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
2448 );
2449 }
2450 $template->assign('softCreditTypes', $softCreditTypes);
2451 $template->assign('softCredits', $softCredits);
2452 }
2453 }
2454
2455 $dao = new CRM_Contribute_DAO_ContributionProduct();
2456 $dao->contribution_id = $this->id;
2457 if ($dao->find(TRUE)) {
2458 $premiumId = $dao->product_id;
2459 $template->assign('option', $dao->product_option);
2460
2461 $productDAO = new CRM_Contribute_DAO_Product();
2462 $productDAO->id = $premiumId;
2463 $productDAO->find(TRUE);
2464 $template->assign('selectPremium', TRUE);
2465 $template->assign('product_name', $productDAO->name);
2466 $template->assign('price', $productDAO->price);
2467 $template->assign('sku', $productDAO->sku);
2468 }
2469 $template->assign('title', CRM_Utils_Array::value('title', $values));
2470 $amount = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL);
2471 if (empty($amount) && isset($this->total_amount)) {
2472 $amount = $this->total_amount;
2473 }
2474 $template->assign('amount', $amount);
2475 // add the new contribution values
2476 if (strtolower($this->_component) == 'contribute') {
2477 //PCP Info
2478 $softDAO = new CRM_Contribute_DAO_ContributionSoft();
2479 $softDAO->contribution_id = $this->id;
2480 if ($softDAO->find(TRUE)) {
2481 $template->assign('pcpBlock', TRUE);
2482 $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
2483 $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
2484 $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
2485
2486 //assign the pcp page title for email subject
2487 $pcpDAO = new CRM_PCP_DAO_PCP();
2488 $pcpDAO->id = $softDAO->pcp_id;
2489 if ($pcpDAO->find(TRUE)) {
2490 $template->assign('title', $pcpDAO->title);
2491 }
2492 }
2493 }
2494
2495 if ($this->financial_type_id) {
2496 $values['financial_type_id'] = $this->financial_type_id;
2497 }
2498
2499 $template->assign('trxn_id', $this->trxn_id);
2500 $template->assign('receive_date',
2501 CRM_Utils_Date::mysqlToIso($this->receive_date)
2502 );
2503 $template->assign('contributeMode', 'notify');
2504 $template->assign('action', $this->is_test ? 1024 : 1);
2505 $template->assign('receipt_text',
2506 CRM_Utils_Array::value('receipt_text',
2507 $values
2508 )
2509 );
2510 $template->assign('is_monetary', 1);
2511 $template->assign('is_recur', (bool) $recur);
2512 $template->assign('currency', $this->currency);
2513 $template->assign('address', CRM_Utils_Address::format($input));
2514 if ($this->_component == 'event') {
2515 $template->assign('title', $values['event']['title']);
2516 $participantRoles = CRM_Event_PseudoConstant::participantRole();
2517 $viewRoles = array();
2518 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
2519 $viewRoles[] = $participantRoles[$v];
2520 }
2521 $values['event']['participant_role'] = implode(', ', $viewRoles);
2522 $template->assign('event', $values['event']);
2523 $template->assign('location', $values['location']);
2524 $template->assign('customPre', $values['custom_pre_id']);
2525 $template->assign('customPost', $values['custom_post_id']);
2526
2527 $isTest = FALSE;
2528 if ($this->_relatedObjects['participant']->is_test) {
2529 $isTest = TRUE;
2530 }
2531
2532 $values['params'] = array();
2533 //to get email of primary participant.
2534 $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
2535 $primaryAmount[] = array(
2536 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail,
2537 'amount' => $this->_relatedObjects['participant']->fee_amount,
2538 );
2539 //build an array of cId/pId of participants
2540 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
2541 unset($additionalIDs[$this->_relatedObjects['participant']->id]);
2542 //send receipt to additional participant if exists
2543 if (count($additionalIDs)) {
2544 $template->assign('isPrimary', 0);
2545 $template->assign('customProfile', NULL);
2546 //set additionalParticipant true
2547 $values['params']['additionalParticipant'] = TRUE;
2548 foreach ($additionalIDs as $pId => $cId) {
2549 $amount = array();
2550 //to change the status pending to completed
2551 $additional = new CRM_Event_DAO_Participant();
2552 $additional->id = $pId;
2553 $additional->contact_id = $cId;
2554 $additional->find(TRUE);
2555 $additional->register_date = $this->_relatedObjects['participant']->register_date;
2556 $additional->status_id = 1;
2557 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
2558 //if additional participant dont have email
2559 //use display name.
2560 if (!$additionalParticipantInfo) {
2561 $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
2562 }
2563 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
2564 $primaryAmount[] = array(
2565 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo,
2566 'amount' => $additional->fee_amount,
2567 );
2568 $additional->save();
2569 $additional->free();
2570 $template->assign('amount', $amount);
2571 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
2572 }
2573 }
2574
2575 //build an array of custom profile and assigning it to template
2576 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
2577
2578 if (count($customProfile)) {
2579 $template->assign('customProfile', $customProfile);
2580 }
2581
2582 // for primary contact
2583 $values['params']['additionalParticipant'] = FALSE;
2584 $template->assign('isPrimary', 1);
2585 $template->assign('amount', $primaryAmount);
2586 $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
2587 if ($this->payment_instrument_id) {
2588 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
2589 $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
2590 }
2591 // carry paylater, since we did not created billing,
2592 // so need to pull email from primary location, CRM-4395
2593 $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
2594 }
2595 return $template;
2596 }
2597
2598 /**
2599 * Check whether payment processor supports
2600 * cancellation of contribution subscription
2601 *
2602 * @param int $contributionId
2603 * Contribution id.
2604 *
2605 * @param bool $isNotCancelled
2606 *
2607 * @return bool
2608 */
2609 public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) {
2610 $cacheKeyString = "$contributionId";
2611 $cacheKeyString .= $isNotCancelled ? '_1' : '_0';
2612
2613 static $supportsCancel = array();
2614
2615 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2616 $supportsCancel[$cacheKeyString] = FALSE;
2617 $isCancelled = FALSE;
2618
2619 if ($isNotCancelled) {
2620 $isCancelled = self::isSubscriptionCancelled($contributionId);
2621 }
2622
2623 $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj');
2624 if (!empty($paymentObject)) {
2625 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2626 }
2627 }
2628 return $supportsCancel[$cacheKeyString];
2629 }
2630
2631 /**
2632 * Check whether subscription is already cancelled.
2633 *
2634 * @param int $contributionId
2635 * Contribution id.
2636 *
2637 * @return string
2638 * contribution status
2639 */
2640 public static function isSubscriptionCancelled($contributionId) {
2641 $sql = "
2642 SELECT cr.contribution_status_id
2643 FROM civicrm_contribution_recur cr
2644 LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id )
2645 WHERE con.id = %1 LIMIT 1";
2646 $params = array(1 => array($contributionId, 'Integer'));
2647 $statusId = CRM_Core_DAO::singleValueQuery($sql, $params);
2648 $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId);
2649 if ($status == 'Cancelled') {
2650 return TRUE;
2651 }
2652 return FALSE;
2653 }
2654
2655 /**
2656 * Create all financial accounts entry.
2657 *
2658 * @param array $params
2659 * Contribution object, line item array and params for trxn.
2660 *
2661 *
2662 * @param array $financialTrxnValues
2663 *
2664 * @return null|object
2665 */
2666 public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) {
2667 $skipRecords = $update = $return = $isRelatedId = FALSE;
2668
2669 $additionalParticipantId = array();
2670 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2671
2672 if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') {
2673 $entityId = $params['participant_id'];
2674 $entityTable = 'civicrm_participant';
2675 $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId);
2676 }
2677 elseif (!empty($params['membership_id'])) {
2678 //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships
2679 // are created off one contribution should be handled elsewhere
2680 $entityId = $params['membership_id'];
2681 $entityTable = 'civicrm_membership';
2682 }
2683 else {
2684 $entityId = $params['contribution']->id;
2685 $entityTable = 'civicrm_contribution';
2686 }
2687
2688 if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') {
2689 $isRelatedId = TRUE;
2690 }
2691
2692 $entityID[] = $entityId;
2693 if (!empty($additionalParticipantId)) {
2694 $entityID += $additionalParticipantId;
2695 }
2696 // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated
2697 if (empty($params['prevContribution'])) {
2698 $entityID = NULL;
2699 }
2700 else {
2701 $update = TRUE;
2702 }
2703
2704 $statusId = $params['contribution']->contribution_status_id;
2705 // CRM-13964 partial payment
2706 if (CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Partially paid', $contributionStatuses)
2707 && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])
2708 ) {
2709 $partialAmtPay = $params['partial_amount_pay'];
2710 $partialAmtTotal = $params['partial_payment_total'];
2711
2712 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2713 $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2714 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
2715 $params['total_amount'] = $partialAmtPay;
2716
2717 $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']);
2718 if (empty($balanceTrxnInfo['trxn_id'])) {
2719 // create new balance transaction record
2720 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2721 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2722
2723 $balanceTrxnParams['total_amount'] = $partialAmtTotal;
2724 $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount;
2725 $balanceTrxnParams['contribution_id'] = $params['contribution']->id;
2726 $balanceTrxnParams['trxn_date'] = date('YmdHis');
2727 $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2728 $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2729 $balanceTrxnParams['currency'] = $params['contribution']->currency;
2730 $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id;
2731 $balanceTrxnParams['status_id'] = $statusId;
2732 $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2733 $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params);
2734 if (!empty($params['payment_processor'])) {
2735 $balanceTrxnParams['payment_processor_id'] = $params['payment_processor'];
2736 }
2737 CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams);
2738 }
2739 }
2740
2741 // build line item array if its not set in $params
2742 if (empty($params['line_item']) || $additionalParticipantId) {
2743 CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId);
2744 }
2745
2746 if (CRM_Utils_Array::value('contribution_status_id', $params) != array_search('Failed', $contributionStatuses) &&
2747 !(CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', $contributionStatuses) && !$params['contribution']->is_pay_later)
2748 ) {
2749 $skipRecords = TRUE;
2750 $pendingStatus = array(
2751 array_search('Pending', $contributionStatuses),
2752 array_search('In Progress', $contributionStatuses),
2753 );
2754 if (in_array(CRM_Utils_Array::value('contribution_status_id', $params), $pendingStatus)) {
2755 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
2756 $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId);
2757 }
2758 elseif (!empty($params['payment_processor'])) {
2759 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id');
2760 }
2761 elseif (!empty($params['payment_instrument_id'])) {
2762 $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']);
2763 }
2764 else {
2765 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
2766 $queryParams = array(1 => array($relationTypeId, 'Integer'));
2767 $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);
2768 }
2769
2770 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
2771 if (!isset($totalAmount) && !empty($params['prevContribution'])) {
2772 $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount;
2773 }
2774
2775 //build financial transaction params
2776 $trxnParams = array(
2777 'contribution_id' => $params['contribution']->id,
2778 'to_financial_account_id' => $params['to_financial_account_id'],
2779 'trxn_date' => date('YmdHis'),
2780 'total_amount' => $totalAmount,
2781 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
2782 'net_amount' => CRM_Utils_Array::value('net_amount', $params),
2783 'currency' => $params['contribution']->currency,
2784 'trxn_id' => $params['contribution']->trxn_id,
2785 'status_id' => $statusId,
2786 'payment_instrument_id' => $params['contribution']->payment_instrument_id,
2787 'check_number' => CRM_Utils_Array::value('check_number', $params),
2788 );
2789
2790 if (!empty($params['payment_processor'])) {
2791 $trxnParams['payment_processor_id'] = $params['payment_processor'];
2792 }
2793
2794 if (isset($fromFinancialAccountId)) {
2795 $trxnParams['from_financial_account_id'] = $fromFinancialAccountId;
2796 }
2797
2798 // consider external values passed for recording transaction entry
2799 if (!empty($financialTrxnValues)) {
2800 $trxnParams = array_merge($trxnParams, $financialTrxnValues);
2801 }
2802
2803 $params['trxnParams'] = $trxnParams;
2804
2805 if (!empty($params['prevContribution'])) {
2806 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount;
2807 $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount;
2808 $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount;
2809 $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id;
2810 $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id;
2811
2812 if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)
2813 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses))
2814 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses))
2815 ) {
2816 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
2817 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2818 }
2819
2820 //if financial type is changed
2821 if (!empty($params['financial_type_id']) &&
2822 $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id
2823 ) {
2824 $incomeTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
2825 $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $incomeTypeId);
2826 $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $incomeTypeId);
2827 if ($oldFinancialAccount != $newFinancialAccount) {
2828 $params['total_amount'] = 0;
2829 if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) {
2830 $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
2831 $params['prevContribution']->financial_type_id, $relationTypeId);
2832 }
2833 else {
2834 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
2835 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
2836 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
2837 }
2838 }
2839 self::updateFinancialAccounts($params, 'changeFinancialType');
2840 /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */
2841 $params['financial_account_id'] = $newFinancialAccount;
2842 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2843 self::updateFinancialAccounts($params);
2844 $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id'];
2845 }
2846 }
2847
2848 //Update contribution status
2849 $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
2850 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
2851 if (!empty($params['contribution_status_id']) &&
2852 $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
2853 ) {
2854 //Update Financial Records
2855 self::updateFinancialAccounts($params, 'changedStatus');
2856 }
2857
2858 // change Payment Instrument for a Completed contribution
2859 // first handle special case when contribution is changed from Pending to Completed status when initial payment
2860 // instrument is null and now new payment instrument is added along with the payment
2861 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
2862 $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params);
2863 if (array_key_exists('payment_instrument_id', $params)) {
2864 $params['trxnParams']['total_amount'] = -$trxnParams['total_amount'];
2865 if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) &&
2866 !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id)
2867 ) {
2868 //check if status is changed from Pending to Completed
2869 // do not update payment instrument changes for Pending to Completed
2870 if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) &&
2871 in_array($params['prevContribution']->contribution_status_id, $pendingStatus))
2872 ) {
2873 // for all other statuses create new financial records
2874 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2875 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2876 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2877 }
2878 }
2879 elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) ||
2880 !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) &&
2881 $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id
2882 ) {
2883 // for any other payment instrument changes create new financial records
2884 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2885 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2886 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2887 }
2888 elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) &&
2889 $params['contribution']->check_number != $params['prevContribution']->check_number
2890 ) {
2891 // another special case when check number is changed, create new financial records
2892 // create financial trxn with negative amount
2893 $params['trxnParams']['check_number'] = $params['prevContribution']->check_number;
2894 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2895 // create financial trxn with positive amount
2896 $params['trxnParams']['check_number'] = $params['contribution']->check_number;
2897 $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount'];
2898 self::updateFinancialAccounts($params, 'changePaymentInstrument');
2899 }
2900 }
2901
2902 //if Change contribution amount
2903 $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params);
2904 $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params);
2905 $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount;
2906 $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
2907 if (isset($totalAmount) &&
2908 $totalAmount != $params['prevContribution']->total_amount
2909 ) {
2910 //Update Financial Records
2911 $params['trxnParams']['from_financial_account_id'] = NULL;
2912 self::updateFinancialAccounts($params, 'changedAmount');
2913 }
2914 }
2915
2916 if (!$update) {
2917 // records finanical trxn and entity financial trxn
2918 // also make it available as return value
2919 $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
2920 $params['entity_id'] = $financialTxn->id;
2921 }
2922 }
2923 // record line items and finacial items
2924 if (empty($params['skipLineItem'])) {
2925 CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update);
2926 }
2927
2928 // create batch entry if batch_id is passed
2929 if (!empty($params['batch_id'])) {
2930 $entityParams = array(
2931 'batch_id' => $params['batch_id'],
2932 'entity_table' => 'civicrm_financial_trxn',
2933 'entity_id' => $financialTxn->id,
2934 );
2935 CRM_Batch_BAO_Batch::addBatchEntity($entityParams);
2936 }
2937
2938 // when a fee is charged
2939 if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) {
2940 CRM_Core_BAO_FinancialTrxn::recordFees($params);
2941 }
2942
2943 if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant'
2944 && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
2945 ) {
2946 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id');
2947 $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level);
2948 CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel);
2949 }
2950 unset($params['line_item']);
2951
2952 return $return;
2953 }
2954
2955 /**
2956 * Update all financial accounts entry.
2957 *
2958 * @param array $params
2959 * Contribution object, line item array and params for trxn.
2960 *
2961 * @param string $context
2962 * Update scenarios.
2963 *
2964 * @param null $skipTrxn
2965 *
2966 */
2967 public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) {
2968 $itemAmount = $trxnID = NULL;
2969 //get all the statuses
2970 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2971 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2972 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
2973 && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2974 && $context == 'changePaymentInstrument'
2975 ) {
2976 return;
2977 }
2978 if ($context == 'changedAmount' || $context == 'changeFinancialType') {
2979 $itemAmount = $params['trxnParams']['total_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount;
2980 }
2981 if ($context == 'changedStatus') {
2982 //get all the statuses
2983 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
2984
2985 if ($params['prevContribution']->contribution_status_id == array_search('Completed', $contributionStatus)
2986 && ($params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
2987 || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus))
2988 ) {
2989 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2990 }
2991 elseif (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
2992 && $params['prevContribution']->is_pay_later) || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus)
2993 ) {
2994 $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id;
2995 if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
2996 $params['trxnParams']['to_financial_account_id'] = NULL;
2997 $params['trxnParams']['total_amount'] = -$params['total_amount'];
2998 }
2999 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3000 $params['trxnParams']['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType(
3001 $financialTypeID, $relationTypeId);
3002 }
3003 $itemAmount = $params['trxnParams']['total_amount'];
3004 }
3005 elseif ($context == 'changePaymentInstrument') {
3006 if ($params['trxnParams']['total_amount'] < 0) {
3007 $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC');
3008 if (!empty($lastFinancialTrxnId['financialTrxnId'])) {
3009 $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id');
3010 $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id;
3011 }
3012 }
3013 else {
3014 $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id'];
3015 $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id;
3016 }
3017 }
3018 $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']);
3019 $params['entity_id'] = $trxn->id;
3020
3021 if ($context == 'changedStatus') {
3022 if (($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)
3023 || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatus))
3024 && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus))
3025 ) {
3026 $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'";
3027 $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'";
3028
3029 $entityParams = array(
3030 'entity_table' => 'civicrm_financial_item',
3031 'financial_trxn_id' => $trxn->id,
3032 );
3033 if (empty($params['line_item'])) {
3034 //CRM-15296
3035 //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items
3036 // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed
3037 // & this can be removed
3038 return;
3039 }
3040 foreach ($params['line_item'] as $fieldId => $fields) {
3041 foreach ($fields as $fieldValueId => $fieldValues) {
3042 $fparams = array(
3043 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'),
3044 2 => array($fieldValues['id'], 'Integer'),
3045 );
3046 CRM_Core_DAO::executeQuery($query, $fparams);
3047 $fparams = array(
3048 1 => array($fieldValues['id'], 'Integer'),
3049 );
3050 $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams);
3051 while ($financialItem->fetch()) {
3052 $entityParams['entity_id'] = $financialItem->id;
3053 $entityParams['amount'] = $financialItem->amount;
3054 CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams);
3055 }
3056 }
3057 }
3058 return;
3059 }
3060 }
3061 if ($context != 'changePaymentInstrument') {
3062 $itemParams['entity_table'] = 'civicrm_line_item';
3063 $trxnIds['id'] = $params['entity_id'];
3064 foreach ($params['line_item'] as $fieldId => $fields) {
3065 foreach ($fields as $fieldValueId => $fieldValues) {
3066 $prevParams['entity_id'] = $fieldValues['id'];
3067 $prevfinancialItem = CRM_Financial_BAO_FinancialItem::retrieve($prevParams, CRM_Core_DAO::$_nullArray);
3068
3069 $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date);
3070 if ($params['contribution']->receive_date) {
3071 $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date);
3072 }
3073
3074 $financialAccount = $prevfinancialItem->financial_account_id;
3075 if (!empty($params['financial_account_id'])) {
3076 $financialAccount = $params['financial_account_id'];
3077 }
3078
3079 $currency = $params['prevContribution']->currency;
3080 if ($params['contribution']->currency) {
3081 $currency = $params['contribution']->currency;
3082 }
3083 $diff = 1;
3084 if (!empty($params['is_quick_config'])) {
3085 $amount = $itemAmount;
3086 if (!$amount) {
3087 $amount = $params['total_amount'];
3088 }
3089 }
3090 else {
3091 if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)
3092 || $params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)
3093 ) {
3094 $diff = -1;
3095 }
3096 $amount = $diff * $fieldValues['line_total'];
3097 }
3098
3099 $itemParams = array(
3100 'transaction_date' => $receiveDate,
3101 'contact_id' => $params['prevContribution']->contact_id,
3102 'currency' => $currency,
3103 'amount' => $amount,
3104 'description' => $prevfinancialItem->description,
3105 'status_id' => $prevfinancialItem->status_id,
3106 'financial_account_id' => $financialAccount,
3107 'entity_table' => 'civicrm_line_item',
3108 'entity_id' => $fieldValues['id'],
3109 );
3110 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3111
3112 if ($fieldValues['tax_amount']) {
3113 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
3114 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
3115 $itemParams['amount'] = $diff * $fieldValues['tax_amount'];
3116 $itemParams['description'] = $taxTerm;
3117 if ($fieldValues['financial_type_id']) {
3118 $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']);
3119 }
3120 CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
3121 }
3122 }
3123 }
3124 }
3125 if ($context == 'changeFinancialType') {
3126 foreach ($params['line_item'] as &$lineItems) {
3127 foreach ($lineItems as &$line) {
3128 $line['financial_type_id'] = $params['financial_type_id'];
3129 }
3130 }
3131 }
3132 }
3133
3134 /**
3135 * Check status validation on update of a contribution.
3136 *
3137 * @param array $values
3138 * Previous form values before submit.
3139 *
3140 * @param array $fields
3141 * The input form values.
3142 *
3143 * @param array $errors
3144 * List of errors.
3145 *
3146 * @return bool
3147 */
3148 public static function checkStatusValidation($values, &$fields, &$errors) {
3149 if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) {
3150 $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id');
3151 if ($values['contribution_status_id'] == $fields['contribution_status_id']) {
3152 return FALSE;
3153 }
3154 }
3155 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
3156 $checkStatus = array(
3157 'Cancelled' => array('Completed', 'Refunded'),
3158 'Completed' => array('Cancelled', 'Refunded'),
3159 'Pending' => array('Cancelled', 'Completed', 'Failed'),
3160 'In Progress' => array('Cancelled', 'Completed', 'Failed'),
3161 'Refunded' => array('Cancelled', 'Completed'),
3162 );
3163
3164 if (!in_array($contributionStatuses[$fields['contribution_status_id']], $checkStatus[$contributionStatuses[$values['contribution_status_id']]])) {
3165 $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array(
3166 1 => $contributionStatuses[$values['contribution_status_id']],
3167 2 => $contributionStatuses[$fields['contribution_status_id']],
3168 ));
3169 }
3170 }
3171
3172 /**
3173 * Delete contribution of contact.
3174 *
3175 * CRM-12155
3176 *
3177 * @param int $contactId
3178 * Contact id.
3179 *
3180 */
3181 public static function deleteContactContribution($contactId) {
3182 $contribution = new CRM_Contribute_DAO_Contribution();
3183 $contribution->contact_id = $contactId;
3184 $contribution->find();
3185 while ($contribution->fetch()) {
3186 self::deleteContribution($contribution->id);
3187 }
3188 }
3189
3190 /**
3191 * Get options for a given contribution field.
3192 * @see CRM_Core_DAO::buildOptions
3193 *
3194 * @param string $fieldName
3195 * @param string $context see CRM_Core_DAO::buildOptionsContext.
3196 * @param array $props whatever is known about this dao object.
3197 *
3198 * @return array|bool
3199 */
3200 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3201 $className = __CLASS__;
3202 $params = array();
3203 switch ($fieldName) {
3204 // This field is not part of this object but the api supports it
3205 case 'payment_processor':
3206 $className = 'CRM_Contribute_BAO_ContributionPage';
3207 // Filter results by contribution page
3208 if (!empty($props['contribution_page_id'])) {
3209 $page = civicrm_api('contribution_page', 'getsingle', array(
3210 'version' => 3,
3211 'id' => ($props['contribution_page_id']),
3212 ));
3213 $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0);
3214 $params['condition'] = 'id IN (' . implode(',', $types) . ')';
3215 }
3216 break;
3217
3218 // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it
3219 case 'honor_type_id':
3220 $className = 'CRM_Contribute_BAO_ContributionSoft';
3221 $fieldName = 'soft_credit_type_id';
3222 $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')";
3223 break;
3224 }
3225 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3226 }
3227
3228 /**
3229 * Validate financial type.
3230 *
3231 * CRM-13231
3232 *
3233 * @param int $financialTypeId
3234 * Financial Type id.
3235 *
3236 * @param string $relationName
3237 *
3238 * @return array|bool
3239 */
3240 public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') {
3241 $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' "));
3242 $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId);
3243
3244 if (!$financialAccount) {
3245 return CRM_Contribute_PseudoConstant::financialType($financialTypeId);
3246 }
3247 return FALSE;
3248 }
3249
3250
3251 /**
3252 * Function to record additional payment for partial and refund contributions.
3253 *
3254 * @param int $contributionId
3255 * is the invoice contribution id (got created after processing participant payment).
3256 * @param array $trxnsData
3257 * to take user provided input of transaction details.
3258 * @param string $paymentType
3259 * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments.
3260 * @param int $participantId
3261 *
3262 * @return null|object
3263 */
3264 public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
3265 $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
3266 $getInfoOf['id'] = $contributionId;
3267 $defaults = array();
3268 $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
3269
3270 if ($paymentType == 'owed') {
3271 // build params for recording financial trxn entry
3272 $params['contribution'] = $contributionDAO;
3273 $params = array_merge($defaults, $params);
3274 $params['skipLineItem'] = TRUE;
3275 $params['partial_payment_total'] = $contributionDAO->total_amount;
3276 $params['partial_amount_pay'] = $trxnsData['total_amount'];
3277 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3278
3279 // record the entry
3280 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3281 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3282 $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3283
3284 $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
3285 if (!empty($trxnId)) {
3286 $trxnId = $trxnId['trxn_id'];
3287 }
3288 elseif (!empty($contributionDAO->payment_instrument_id)) {
3289 $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id);
3290 }
3291 else {
3292 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' "));
3293 $queryParams = array(1 => array($relationTypeId, 'Integer'));
3294 $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams);
3295 }
3296
3297 // update statuses
3298 // criteria for updates contribution total_amount == financial_trxns of partial_payments
3299 $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
3300 FROM civicrm_financial_trxn ft
3301 LEFT JOIN civicrm_entity_financial_trxn eft
3302 ON (ft.id = eft.financial_trxn_id)
3303 WHERE eft.entity_table = 'civicrm_contribution'
3304 AND eft.entity_id = {$contributionId}
3305 AND ft.to_financial_account_id != {$toFinancialAccount}
3306 AND ft.status_id = {$statusId}
3307 ";
3308 $sumOfPayments = CRM_Core_DAO::singleValueQuery($sql);
3309
3310 // update statuses
3311 if ($contributionDAO->total_amount == $sumOfPayments) {
3312 // update contribution status and
3313 // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed'
3314 $contributionDAO->contribution_status_id = $statusId;
3315 $contributionDAO->cancel_date = 'null';
3316 $contributionDAO->cancel_reason = NULL;
3317 $netAmount = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
3318 $contributionDAO->net_amount = $contributionDAO->net_amount + $netAmount;
3319 $contributionDAO->save();
3320
3321 //Change status of financial record too
3322 $financialTrxn->status_id = $statusId;
3323 $financialTrxn->save();
3324
3325 // note : not using the self::add method,
3326 // the reason because it performs 'status change' related code execution for financial records
3327 // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
3328 // are coded below i.e. just updating financial_item status to 'Paid'
3329
3330 if ($participantId) {
3331 // update participant status
3332 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3333 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3334 foreach ($ids as $val) {
3335 $participantUpdate['id'] = $val;
3336 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3337 CRM_Event_BAO_Participant::add($participantUpdate);
3338 }
3339 }
3340
3341 // update financial item statuses
3342 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3343 $paidStatus = array_search('Paid', $financialItemStatus);
3344
3345 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3346 $sqlFinancialItemUpdate = "
3347 UPDATE civicrm_financial_item fi
3348 LEFT JOIN civicrm_entity_financial_trxn eft
3349 ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')
3350 SET status_id = {$paidStatus}
3351 WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
3352 ";
3353 CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
3354 }
3355 }
3356 elseif ($paymentType == 'refund') {
3357 // build params for recording financial trxn entry
3358 $params['contribution'] = $contributionDAO;
3359 $params = array_merge($defaults, $params);
3360 $params['skipLineItem'] = TRUE;
3361 $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
3362 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
3363
3364 $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
3365 $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
3366 $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
3367 // record the entry
3368 $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
3369
3370 // note : not using the self::add method,
3371 // the reason because it performs 'status change' related code execution for financial records
3372 // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
3373 // are coded below i.e. just updating financial_item status to 'Paid'
3374 $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
3375
3376 // add financial item entry
3377 $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
3378 $getLine['entity_id'] = $contributionDAO->id;
3379 $getLine['entity_table'] = 'civicrm_contribution';
3380 $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
3381 if (!empty($lineItemId->id)) {
3382 $addFinancialEntry = array(
3383 'transaction_date' => $financialTrxn->trxn_date,
3384 'contact_id' => $contributionDAO->contact_id,
3385 'amount' => $financialTrxn->total_amount,
3386 'status_id' => array_search('Paid', $financialItemStatus),
3387 'entity_id' => $lineItemId->id,
3388 'entity_table' => 'civicrm_line_item',
3389 );
3390 $trxnIds['id'] = $financialTrxn->id;
3391 CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
3392 }
3393 if ($participantId) {
3394 // update participant status
3395 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
3396 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3397 foreach ($ids as $val) {
3398 $participantUpdate['id'] = $val;
3399 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
3400 CRM_Event_BAO_Participant::add($participantUpdate);
3401 }
3402 }
3403 }
3404
3405 // activity creation
3406 if (!empty($financialTrxn)) {
3407 if ($participantId) {
3408 $inputParams['id'] = $participantId;
3409 $values = array();
3410 $ids = array();
3411 $component = 'event';
3412 $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
3413 $entityObj = $entityObj[$participantId];
3414 }
3415 $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment';
3416
3417 self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId);
3418 }
3419 return $financialTrxn;
3420 }
3421
3422 /**
3423 * @param $entityObj
3424 * @param $trxnObj
3425 * @param $activityType
3426 * @param $component
3427 * @param int $contributionId
3428 *
3429 * @throws CRM_Core_Exception
3430 */
3431 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
3432 if ($component == 'event') {
3433 $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
3434 $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency);
3435 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
3436 $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
3437 $targetCid = $entityObj->contact_id;
3438 // source record id would be the contribution id
3439 $srcRecId = $contributionId;
3440 }
3441
3442 // activity params
3443 $activityParams = array(
3444 'source_contact_id' => $targetCid,
3445 'source_record_id' => $srcRecId,
3446 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
3447 $activityType,
3448 'name'
3449 ),
3450 'subject' => $subject,
3451 'activity_date_time' => $date,
3452 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
3453 'Completed',
3454 'name'
3455 ),
3456 'skipRecentView' => TRUE,
3457 );
3458
3459 // create activity with target contacts
3460 $session = CRM_Core_Session::singleton();
3461 $id = $session->get('userID');
3462 if ($id) {
3463 $activityParams['source_contact_id'] = $id;
3464 $activityParams['target_contact_id'][] = $targetCid;
3465 }
3466 CRM_Activity_BAO_Activity::create($activityParams);
3467 }
3468
3469 /**
3470 * Get list of payments displayed by Contribute_Page_PaymentInfo.
3471 *
3472 * @param int $id
3473 * @param $component
3474 * @param bool $getTrxnInfo
3475 * @param bool $usingLineTotal
3476 *
3477 * @return mixed
3478 */
3479 public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
3480 if ($component == 'event') {
3481 $entity = 'participant';
3482 $entityTable = 'civicrm_participant';
3483 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
3484
3485 if (!$contributionId) {
3486 if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
3487 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
3488 $id = $primaryParticipantId;
3489 }
3490 if (!$contributionId) {
3491 return;
3492 }
3493 }
3494 }
3495 $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
3496 $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
3497 $isBalance = NULL;
3498 if ($baseTrxnId) {
3499 $isBalance = TRUE;
3500 }
3501 else {
3502 $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId);
3503 $baseTrxnId = $baseTrxnId['financialTrxnId'];
3504 $isBalance = FALSE;
3505 }
3506 if (empty($total) || $usingLineTotal) {
3507 // for additional participants
3508 if ($entityTable == 'civicrm_participant') {
3509 $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
3510 $total = 0;
3511 foreach ($ids as $val) {
3512 $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable);
3513 }
3514 }
3515 else {
3516 $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
3517 }
3518 }
3519 else {
3520 $baseTrxnId = $total['trxn_id'];
3521 $total = $total['total_amount'];
3522 }
3523
3524 $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
3525 $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
3526
3527 $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
3528 $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3529 $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId);
3530
3531 if ($paymentBalance == 0 && $contributionIsPayLater) {
3532 $paymentBalance = $total;
3533 }
3534
3535 $info['total'] = $total;
3536 $info['paid'] = $total - $paymentBalance;
3537 $info['balance'] = $paymentBalance;
3538 $info['id'] = $id;
3539 $info['component'] = $component;
3540 $info['payLater'] = $contributionIsPayLater;
3541 $rows = array();
3542 if ($getTrxnInfo && $baseTrxnId) {
3543 // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account
3544 $sql = "
3545 SELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number
3546 FROM civicrm_contribution con
3547 LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')
3548 INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}
3549 WHERE con.id = {$contributionId}
3550 ";
3551
3552 // conditioned WHERE clause
3553 if ($isBalance) {
3554 // if balance trxn exists don't include details of it in transaction info
3555 $sql .= " AND ft.id != {$baseTrxnId} ";
3556 }
3557 $resultDAO = CRM_Core_DAO::executeQuery($sql);
3558
3559 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
3560 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
3561 while ($resultDAO->fetch()) {
3562 $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3563 $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id);
3564 $val = array(
3565 'total_amount' => $resultDAO->total_amount,
3566 'financial_type' => $financialTypes[$resultDAO->financial_type_id],
3567 'payment_instrument' => $paidByLabel,
3568 'receive_date' => $resultDAO->trxn_date,
3569 'trxn_id' => $resultDAO->trxn_id,
3570 'status' => $statuses[$resultDAO->status_id],
3571 );
3572 if ($paidByName == 'Check') {
3573 $val['check_number'] = $resultDAO->check_number;
3574 }
3575 $rows[] = $val;
3576 }
3577 $info['transaction'] = $rows;
3578 }
3579 return $info;
3580 }
3581
3582 /**
3583 * Get financial account id has 'Sales Tax Account is'
3584 * account relationship with financial type
3585 *
3586 * @param int $financialTypeId
3587 *
3588 * @return FinancialAccountId
3589 */
3590 public static function getFinancialAccountId($financialTypeId) {
3591 $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
3592 $searchParams = array(
3593 'entity_table' => 'civicrm_financial_type',
3594 'entity_id' => $financialTypeId,
3595 'account_relationship' => $accountRel,
3596 );
3597 $result = array();
3598 CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
3599
3600 return CRM_Utils_Array::value('financial_account_id', $result);
3601 }
3602
3603 /**
3604 * Check tax amount.
3605 *
3606 * @param array $params
3607 * @param bool $isLineItem
3608 *
3609 * @return mixed
3610 */
3611 public static function checkTaxAmount($params, $isLineItem = FALSE) {
3612 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
3613
3614 // Update contribution.
3615 if (!empty($params['id'])) {
3616 $id = $params['id'];
3617 $values = $ids = array();
3618 $contrbutionParams = array('id' => $id);
3619 $prevContributionValue = CRM_Contribute_BAO_Contribution::getValues($contrbutionParams, $values, $ids);
3620
3621 // To assign pervious finantial type on update of contribution
3622 if (!isset($params['financial_type_id'])) {
3623 $params['financial_type_id'] = $prevContributionValue->financial_type_id;
3624 }
3625 elseif (isset($params['financial_type_id']) && !array_key_exists($params['financial_type_id'], $taxRates)) {
3626 // Assisn tax Amount on update of contrbution
3627 if (!empty($prevContributionValue->tax_amount)) {
3628 $params['tax_amount'] = 'null';
3629 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3630 foreach ($params['line_item'] as $setID => $priceField) {
3631 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3632 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3633 }
3634 }
3635 }
3636 }
3637 }
3638
3639 // New Contrbution and update of contribution with tax rate financial type
3640 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) &&
3641 empty($params['skipLineItem']) && !$isLineItem
3642 ) {
3643 $taxRateParams = $taxRates[$params['financial_type_id']];
3644 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['total_amount'], $taxRateParams);
3645 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3646
3647 // Get Line Item on update of contribution
3648 if (isset($params['id'])) {
3649 CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id']));
3650 }
3651 else {
3652 CRM_Price_BAO_LineItem::getLineItemArray($params);
3653 }
3654 foreach ($params['line_item'] as $setID => $priceField) {
3655 foreach ($priceField as $priceFieldID => $priceFieldValue) {
3656 $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount'];
3657 }
3658 }
3659 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
3660 }
3661 elseif (isset($params['api.line_item.create'])) {
3662 // Update total amount of contribution using lineItem
3663 $taxAmountArray = array();
3664 foreach ($params['api.line_item.create'] as $key => $value) {
3665 if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) {
3666 $taxRate = $taxRates[$value['financial_type_id']];
3667 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate);
3668 $taxAmountArray[] = round($taxAmount['tax_amount'], 2);
3669 }
3670 }
3671 $params['tax_amount'] = array_sum($taxAmountArray);
3672 $params['total_amount'] = $params['total_amount'] + $params['tax_amount'];
3673 }
3674 else {
3675 // update line item of contrbution
3676 if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) {
3677 $taxRate = $taxRates[$params['financial_type_id']];
3678 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate);
3679 $params['tax_amount'] = round($taxAmount['tax_amount'], 2);
3680 }
3681 }
3682 return $params;
3683 }
3684
3685 /**
3686 * Check financial type validation on update of a contribution.
3687 *
3688 * @param Integer $financialTypeId
3689 * Value of latest Financial Type.
3690 *
3691 * @param Integer
3692 * Contribution Id.
3693 *
3694 * @param array $errors
3695 * List of errors.
3696 *
3697 * @return bool
3698 */
3699 public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
3700 if (!empty($financialTypeId)) {
3701 $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
3702 if ($oldFinancialTypeId == $financialTypeId) {
3703 return FALSE;
3704 }
3705 }
3706 $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
3707 $params = array(
3708 '1' => array($contributionId, 'Integer')
3709 );
3710 $result = CRM_Core_DAO::executeQuery($sql, $params);
3711 if ($result->N > 1) {
3712 $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.');
3713 }
3714 }
3715
3716 }