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