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