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