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