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