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