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