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