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