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