Commit | Line | Data |
---|---|---|
6a488035 | 1 | <?php |
6a488035 TO |
2 | /* |
3 | +--------------------------------------------------------------------+ | |
7e9e8871 | 4 | | CiviCRM version 4.7 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
0f03f337 | 6 | | Copyright CiviCRM LLC (c) 2004-2017 | |
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 | |
0f03f337 | 31 | * @copyright CiviCRM LLC (c) 2004-2017 |
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 | ||
9c472292 PN |
49 | /** |
50 | * Static field to hold financial trxn id's. | |
51 | * | |
52 | * @var array | |
53 | */ | |
54 | static $_trxnIDs = NULL; | |
55 | ||
6a488035 | 56 | /** |
100fef9d | 57 | * Field for all the objects related to this contribution |
6a488035 TO |
58 | * @var array of objects (e.g membership object, participant object) |
59 | */ | |
60 | public $_relatedObjects = array(); | |
61 | ||
62 | /** | |
100fef9d | 63 | * Field for the component - either 'event' (participant) or 'contribute' |
6a488035 TO |
64 | * (any item related to a contribution page e.g. membership, pledge, contribution) |
65 | * This is used for composing messages because they have dependency on the | |
66 | * contribution_page or event page - although over time we may eliminate that | |
67 | * | |
68 | * @var string component or event | |
69 | */ | |
70 | public $_component = NULL; | |
71 | ||
0be43473 EM |
72 | /** |
73 | * Possibly obsolete variable. | |
74 | * | |
75 | * If you use it please explain why it is set in the create function here. | |
76 | * | |
77 | * @var string | |
78 | */ | |
79 | public $trxn_result_code; | |
80 | ||
186c9c17 | 81 | /** |
fe482240 | 82 | * Class constructor. |
186c9c17 | 83 | */ |
00be9182 | 84 | public function __construct() { |
6a488035 TO |
85 | parent::__construct(); |
86 | } | |
87 | ||
88 | /** | |
fe482240 | 89 | * Takes an associative array and creates a contribution object. |
6a488035 TO |
90 | * |
91 | * the function extract all the params it needs to initialize the create a | |
92 | * contribution object. the params array could contain additional unused name/value | |
93 | * pairs | |
94 | * | |
014c4014 TO |
95 | * @param array $params |
96 | * (reference ) an assoc array of name/value pairs. | |
97 | * @param array $ids | |
98 | * The array that holds all the db ids. | |
6a488035 | 99 | * |
bed98343 | 100 | * @return CRM_Contribute_BAO_Contribution|void |
6a488035 | 101 | */ |
00be9182 | 102 | public static function add(&$params, $ids = array()) { |
6a488035 | 103 | if (empty($params)) { |
bed98343 | 104 | return NULL; |
6a488035 | 105 | } |
504a78f6 | 106 | //per http://wiki.civicrm.org/confluence/display/CRM/Database+layer we are moving away from $ids array |
107 | $contributionID = CRM_Utils_Array::value('contribution', $ids, CRM_Utils_Array::value('id', $params)); | |
6a488035 | 108 | $duplicates = array(); |
504a78f6 | 109 | if (self::checkDuplicate($params, $duplicates, $contributionID)) { |
6a488035 TO |
110 | $error = CRM_Core_Error::singleton(); |
111 | $d = implode(', ', $duplicates); | |
112 | $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION, | |
113 | 'Fatal', | |
114 | array($d), | |
115 | "Duplicate error - existing contribution record(s) have a matching Transaction ID or Invoice ID. Contribution record ID(s) are: $d" | |
116 | ); | |
117 | return $error; | |
118 | } | |
119 | ||
120 | // first clean up all the money fields | |
121 | $moneyFields = array( | |
122 | 'total_amount', | |
123 | 'net_amount', | |
124 | 'fee_amount', | |
125 | 'non_deductible_amount', | |
126 | ); | |
ae06c851 | 127 | |
6a488035 | 128 | //if priceset is used, no need to cleanup money |
a7488080 | 129 | if (!empty($params['skipCleanMoney'])) { |
6a488035 TO |
130 | unset($moneyFields[0]); |
131 | } | |
132 | ||
133 | foreach ($moneyFields as $field) { | |
134 | if (isset($params[$field])) { | |
135 | $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]); | |
136 | } | |
137 | } | |
48ea0708 | 138 | |
16e268ad | 139 | //set defaults in create mode |
140 | if (!$contributionID) { | |
141 | CRM_Core_DAO::setCreateDefaults($params, self::getDefaults()); | |
142 | } | |
143 | ||
b929cdb4 | 144 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
4add5adb GC |
145 | //if contribution is created with cancelled or refunded status, add credit note id |
146 | if (!empty($params['contribution_status_id'])) { | |
52da5b1e | 147 | // @todo - should we include Chargeback? If so use self::isContributionStatusNegative($params['contribution_status_id']) |
4add5adb | 148 | if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus) |
16e268ad | 149 | || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus)) |
4add5adb | 150 | ) { |
8d20d89c | 151 | if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") { |
4add5adb GC |
152 | $params['creditnote_id'] = self::createCreditNoteId(); |
153 | } | |
154 | } | |
155 | } | |
76c28c8d DG |
156 | else { |
157 | // Since the fee amount is expecting this (later on) ensure it is always set. | |
158 | // It would only not be set for an update where it is unchanged. | |
16e268ad | 159 | $params['contribution_status_id'] = civicrm_api3('Contribution', 'getvalue', array('id' => $contributionID, 'return' => 'contribution_status_id')); |
76c28c8d | 160 | } |
4add5adb | 161 | |
8cf6bd83 PN |
162 | if (!$contributionID |
163 | && CRM_Utils_Array::value('membership_id', $params) | |
164 | && self::checkContributeSettings('deferred_revenue_enabled') | |
165 | ) { | |
166 | $memberStartDate = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $params['membership_id'], 'start_date'); | |
167 | if ($memberStartDate) { | |
168 | $params['revenue_recognition_date'] = date('Ymd', strtotime($memberStartDate)); | |
169 | } | |
170 | } | |
080a561b | 171 | self::calculateMissingAmountParams($params, $contributionID); |
6a488035 | 172 | |
a7488080 | 173 | if (!empty($params['payment_instrument_id'])) { |
6a488035 TO |
174 | $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument('name'); |
175 | if ($params['payment_instrument_id'] != array_search('Check', $paymentInstruments)) { | |
176 | $params['check_number'] = 'null'; | |
177 | } | |
178 | } | |
179 | ||
5e494d5c | 180 | $setPrevContribution = TRUE; |
f8325309 | 181 | // CRM-13964 partial payment |
5e494d5c PJ |
182 | if (!empty($params['partial_payment_total']) && !empty($params['partial_amount_pay'])) { |
183 | $partialAmtTotal = $params['partial_payment_total']; | |
184 | $partialAmtPay = $params['partial_amount_pay']; | |
185 | $params['total_amount'] = $partialAmtTotal; | |
186 | if ($partialAmtPay < $partialAmtTotal) { | |
ede1935f | 187 | $params['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Partially paid', 'name'); |
5e494d5c PJ |
188 | $params['is_pay_later'] = 0; |
189 | $setPrevContribution = FALSE; | |
f8325309 PJ |
190 | } |
191 | } | |
19393e51 | 192 | if ($contributionID && $setPrevContribution) { |
2912ed09 | 193 | $params['prevContribution'] = self::getOriginalContribution($contributionID); |
19393e51 | 194 | } |
ede1935f | 195 | |
3adac159 | 196 | // CRM-16189 |
96039749 | 197 | CRM_Financial_BAO_FinancialAccount::checkFinancialTypeHasDeferred($params, $contributionID); |
0193c00f | 198 | if ($contributionID && !empty($params['revenue_recognition_date']) && !empty($params['prevContribution']) |
e937b376 | 199 | && !($contributionStatus[$params['prevContribution']->contribution_status_id] == 'Pending') |
1a55f42e PN |
200 | && !self::allowUpdateRevenueRecognitionDate($contributionID) |
201 | ) { | |
202 | unset($params['revenue_recognition_date']); | |
203 | } | |
96039749 | 204 | |
bf4385cb SL |
205 | if (!isset($params['tax_amount']) && $setPrevContribution && (isset($params['total_amount']) || |
206 | isset($params['financial_type_id']))) { | |
1fca875f | 207 | $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params); |
2912ed09 | 208 | } |
209 | ||
504a78f6 | 210 | if ($contributionID) { |
211 | CRM_Utils_Hook::pre('edit', 'Contribution', $contributionID, $params); | |
6a488035 TO |
212 | } |
213 | else { | |
214 | CRM_Utils_Hook::pre('create', 'Contribution', NULL, $params); | |
215 | } | |
6a488035 TO |
216 | $contribution = new CRM_Contribute_BAO_Contribution(); |
217 | $contribution->copyValues($params); | |
218 | ||
504a78f6 | 219 | $contribution->id = $contributionID; |
6a488035 | 220 | |
10cd9458 | 221 | if (empty($contribution->id)) { |
222 | // (only) on 'create', make sure that a valid currency is set (CRM-16845) | |
223 | if (!CRM_Utils_Rule::currencyCode($contribution->currency)) { | |
4e92d4f4 | 224 | $contribution->currency = CRM_Core_Config::singleton()->defaultCurrency; |
10cd9458 | 225 | } |
6a488035 TO |
226 | } |
227 | ||
6a488035 TO |
228 | $result = $contribution->save(); |
229 | ||
230 | // Add financial_trxn details as part of fix for CRM-4724 | |
231 | $contribution->trxn_result_code = CRM_Utils_Array::value('trxn_result_code', $params); | |
232 | $contribution->payment_processor = CRM_Utils_Array::value('payment_processor', $params); | |
233 | ||
234 | //add Account details | |
235 | $params['contribution'] = $contribution; | |
0aaf8fe9 | 236 | self::recordFinancialAccounts($params); |
6a488035 | 237 | |
91259407 | 238 | if (self::isUpdateToRecurringContribution($params)) { |
239 | CRM_Contribute_BAO_ContributionRecur::updateOnNewPayment( | |
d4009c22 | 240 | (!empty($params['contribution_recur_id']) ? $params['contribution_recur_id'] : $params['prevContribution']->contribution_recur_id), |
91259407 | 241 | $contributionStatus[$params['contribution_status_id']] |
242 | ); | |
243 | } | |
244 | ||
2b68a50c | 245 | CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush(); |
6a488035 | 246 | |
504a78f6 | 247 | if ($contributionID) { |
6a488035 TO |
248 | CRM_Utils_Hook::post('edit', 'Contribution', $contribution->id, $contribution); |
249 | } | |
250 | else { | |
251 | CRM_Utils_Hook::post('create', 'Contribution', $contribution->id, $contribution); | |
252 | } | |
253 | ||
254 | return $result; | |
255 | } | |
256 | ||
91259407 | 257 | /** |
258 | * Is this contribution updating an existing recurring contribution. | |
259 | * | |
260 | * We need to upd the status of the linked recurring contribution if we have a new payment against it, or the initial | |
261 | * pending payment is being confirmed (or failing). | |
262 | * | |
263 | * @param array $params | |
264 | * | |
265 | * @return bool | |
266 | */ | |
267 | public static function isUpdateToRecurringContribution($params) { | |
268 | if (!empty($params['contribution_recur_id']) && empty($params['id'])) { | |
269 | return TRUE; | |
270 | } | |
271 | if (empty($params['prevContribution']) || empty($params['contribution_status_id'])) { | |
272 | return FALSE; | |
273 | } | |
274 | if (empty($params['contribution_recur_id']) && empty($params['prevContribution']->contribution_recur_id)) { | |
275 | return FALSE; | |
276 | } | |
277 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); | |
278 | if ($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatus)) { | |
279 | return TRUE; | |
280 | } | |
281 | return FALSE; | |
282 | } | |
283 | ||
44a2db2b | 284 | /** |
fe482240 | 285 | * Get defaults for new entity. |
44a2db2b EM |
286 | * @return array |
287 | */ | |
00be9182 | 288 | public static function getDefaults() { |
44a2db2b EM |
289 | return array( |
290 | 'payment_instrument_id' => key(CRM_Core_OptionGroup::values('payment_instrument', | |
291 | FALSE, FALSE, FALSE, 'AND is_default = 1') | |
292 | ), | |
293 | 'contribution_status_id' => CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'), | |
294 | ); | |
44a2db2b EM |
295 | } |
296 | ||
6a488035 | 297 | /** |
9a7e53b0 | 298 | * Fetch the object and store the values in the values array. |
6a488035 | 299 | * |
014c4014 TO |
300 | * @param array $params |
301 | * Input parameters to find object. | |
302 | * @param array $values | |
303 | * Output values of the object. | |
304 | * @param array $ids | |
305 | * The array that holds all the db ids. | |
6a488035 | 306 | * |
a380f4a0 EM |
307 | * @return CRM_Contribute_BAO_Contribution|null |
308 | * The found object or null | |
6a488035 | 309 | */ |
0816949d | 310 | public static function getValues($params, &$values, &$ids) { |
6a488035 TO |
311 | if (empty($params)) { |
312 | return NULL; | |
313 | } | |
314 | $contribution = new CRM_Contribute_BAO_Contribution(); | |
315 | ||
316 | $contribution->copyValues($params); | |
317 | ||
318 | if ($contribution->find(TRUE)) { | |
319 | $ids['contribution'] = $contribution->id; | |
320 | ||
321 | CRM_Core_DAO::storeValues($contribution, $values); | |
322 | ||
323 | return $contribution; | |
324 | } | |
7e5524d4 TO |
325 | $null = NULL; // return by reference |
326 | return $null; | |
6a488035 TO |
327 | } |
328 | ||
99cdd94d | 329 | /** |
330 | * Get the values and resolve the most common mappings. | |
331 | * | |
332 | * Since contribution status is resolved in almost every function that calls getValues it makes | |
333 | * sense to have an extra function to resolve it rather than repeat the code. | |
334 | * | |
335 | * Think carefully before adding more mappings to be resolved as there could be performance implications | |
336 | * if this function starts to be called from more iterative functions. | |
337 | * | |
338 | * @param array $params | |
339 | * Input parameters to find object. | |
340 | * | |
341 | * @return array | |
342 | * Array of the found contribution. | |
343 | * @throws CRM_Core_Exception | |
344 | */ | |
345 | public static function getValuesWithMappings($params) { | |
346 | $values = $ids = array(); | |
347 | $contribution = self::getValues($params, $values, $ids); | |
348 | if (is_null($contribution)) { | |
349 | throw new CRM_Core_Exception('No contribution found'); | |
350 | } | |
351 | $values['contribution_status'] = CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $values['contribution_status_id']); | |
352 | return $values; | |
353 | } | |
354 | ||
44a2db2b | 355 | /** |
0be43473 | 356 | * Calculate net_amount & fee_amount if they are not set. |
44a2db2b | 357 | * |
0be43473 EM |
358 | * Net amount should be total - fee. |
359 | * This should only be called for new contributions. | |
360 | * | |
361 | * @param array $params | |
362 | * Params for a new contribution before they are saved. | |
080a561b | 363 | * @param int|null $contributionID |
364 | * Contribution ID if we are dealing with an update. | |
365 | * | |
366 | * @throws \CiviCRM_API3_Exception | |
44a2db2b | 367 | */ |
080a561b | 368 | public static function calculateMissingAmountParams(&$params, $contributionID) { |
369 | if (!$contributionID && !isset($params['fee_amount'])) { | |
44a2db2b EM |
370 | if (isset($params['total_amount']) && isset($params['net_amount'])) { |
371 | $params['fee_amount'] = $params['total_amount'] - $params['net_amount']; | |
372 | } | |
373 | else { | |
374 | $params['fee_amount'] = 0; | |
375 | } | |
376 | } | |
377 | if (!isset($params['net_amount'])) { | |
080a561b | 378 | if (!$contributionID) { |
379 | $params['net_amount'] = $params['total_amount'] - $params['fee_amount']; | |
380 | } | |
381 | else { | |
382 | if (isset($params['fee_amount']) || isset($params['total_amount'])) { | |
383 | // We have an existing contribution and fee_amount or total_amount has been passed in but not net_amount. | |
384 | // net_amount may need adjusting. | |
385 | $contribution = civicrm_api3('Contribution', 'getsingle', array( | |
386 | 'id' => $contributionID, | |
387 | 'return' => array('total_amount', 'net_amount'), | |
388 | )); | |
389 | $totalAmount = isset($params['total_amount']) ? $params['total_amount'] : CRM_Utils_Array::value('total_amount', $contribution); | |
390 | $feeAmount = isset($params['fee_amount']) ? $params['fee_amount'] : CRM_Utils_Array::value('fee_amount', $contribution); | |
391 | $params['net_amount'] = $totalAmount - $feeAmount; | |
392 | } | |
393 | } | |
44a2db2b EM |
394 | } |
395 | } | |
396 | ||
0816949d EM |
397 | /** |
398 | * @param $params | |
399 | * @param $billingLocationTypeID | |
400 | * | |
401 | * @return array | |
402 | */ | |
403 | protected static function getBillingAddressParams($params, $billingLocationTypeID) { | |
404 | $hasBillingField = FALSE; | |
405 | $billingFields = array( | |
406 | 'street_address', | |
407 | 'city', | |
408 | 'state_province_id', | |
409 | 'postal_code', | |
410 | 'country_id', | |
411 | ); | |
412 | ||
413 | //build address array | |
414 | $addressParams = array(); | |
415 | $addressParams['location_type_id'] = $billingLocationTypeID; | |
416 | $addressParams['is_billing'] = 1; | |
417 | ||
418 | $billingFirstName = CRM_Utils_Array::value('billing_first_name', $params); | |
419 | $billingMiddleName = CRM_Utils_Array::value('billing_middle_name', $params); | |
420 | $billingLastName = CRM_Utils_Array::value('billing_last_name', $params); | |
421 | $addressParams['address_name'] = "{$billingFirstName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingMiddleName}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$billingLastName}"; | |
422 | ||
423 | foreach ($billingFields as $value) { | |
424 | $addressParams[$value] = CRM_Utils_Array::value("billing_{$value}-{$billingLocationTypeID}", $params); | |
425 | if (!empty($addressParams[$value])) { | |
426 | $hasBillingField = TRUE; | |
427 | } | |
428 | } | |
429 | return array($hasBillingField, $addressParams); | |
430 | } | |
431 | ||
432 | /** | |
433 | * Get address params ready to be passed to the payment processor. | |
434 | * | |
435 | * We need address params in a couple of formats. For the payment processor we wan state_province_id-5. | |
436 | * To create an address we need state_province_id. | |
437 | * | |
438 | * @param array $params | |
439 | * @param int $billingLocationTypeID | |
440 | * | |
441 | * @return array | |
442 | */ | |
443 | public static function getPaymentProcessorReadyAddressParams($params, $billingLocationTypeID) { | |
444 | list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID); | |
445 | foreach ($addressParams as $name => $field) { | |
446 | if (substr($name, 0, 8) == 'billing_') { | |
447 | $addressParams[substr($name, 9)] = $addressParams[$field]; | |
448 | } | |
449 | } | |
450 | return array($hasBillingField, $addressParams); | |
451 | } | |
452 | ||
2243fe93 EM |
453 | /** |
454 | * Get the number of terms for this contribution for a given membership type | |
455 | * based on querying the line item table and relevant price field values | |
456 | * Note that any one contribution should only be able to have one line item relating to a particular membership | |
457 | * type | |
a284891b | 458 | * |
2243fe93 EM |
459 | * @param int $membershipTypeID |
460 | * | |
a284891b EM |
461 | * @param int $contributionID |
462 | * | |
2243fe93 EM |
463 | * @return int |
464 | */ | |
a284891b | 465 | public function getNumTermsByContributionAndMembershipType($membershipTypeID, $contributionID) { |
f2b2a3ff | 466 | $numTerms = CRM_Core_DAO::singleValueQuery(" |
2243fe93 EM |
467 | SELECT membership_num_terms FROM civicrm_line_item li |
468 | LEFT JOIN civicrm_price_field_value v ON li.price_field_value_id = v.id | |
29347f3d | 469 | WHERE contribution_id = %1 AND membership_type_id = %2", |
f2b2a3ff | 470 | array(1 => array($contributionID, 'Integer'), 2 => array($membershipTypeID, 'Integer')) |
2243fe93 EM |
471 | ); |
472 | // default of 1 is precautionary | |
473 | return empty($numTerms) ? 1 : $numTerms; | |
474 | } | |
475 | ||
6a488035 | 476 | /** |
fe482240 | 477 | * Takes an associative array and creates a contribution object. |
6a488035 | 478 | * |
014c4014 TO |
479 | * @param array $params |
480 | * (reference ) an assoc array of name/value pairs. | |
481 | * @param array $ids | |
482 | * The array that holds all the db ids. | |
6a488035 | 483 | * |
16b10e64 | 484 | * @return CRM_Contribute_BAO_Contribution |
6a488035 | 485 | */ |
00be9182 | 486 | public static function create(&$params, $ids = array()) { |
46d173ef | 487 | $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date', 'revenue_recognition_date'); |
6a488035 TO |
488 | foreach ($dateFields as $df) { |
489 | if (isset($params[$df])) { | |
490 | $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]); | |
491 | } | |
492 | } | |
493 | ||
4add5adb GC |
494 | //if contribution is created with cancelled or refunded status, add credit note id |
495 | if (!empty($params['contribution_status_id'])) { | |
496 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); | |
497 | ||
498 | if (($params['contribution_status_id'] == array_search('Refunded', $contributionStatus) | |
499 | || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus)) | |
500 | ) { | |
8d20d89c | 501 | if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") { |
4add5adb GC |
502 | $params['creditnote_id'] = self::createCreditNoteId(); |
503 | } | |
504 | } | |
505 | } | |
506 | ||
6a488035 TO |
507 | $transaction = new CRM_Core_Transaction(); |
508 | ||
6a488035 TO |
509 | $contribution = self::add($params, $ids); |
510 | ||
511 | if (is_a($contribution, 'CRM_Core_Error')) { | |
512 | $transaction->rollback(); | |
513 | return $contribution; | |
514 | } | |
515 | ||
516 | $params['contribution_id'] = $contribution->id; | |
517 | ||
a7488080 | 518 | if (!empty($params['custom']) && |
6a488035 TO |
519 | is_array($params['custom']) |
520 | ) { | |
521 | CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id); | |
522 | } | |
523 | ||
524 | $session = CRM_Core_Session::singleton(); | |
525 | ||
a7488080 | 526 | if (!empty($params['note'])) { |
6a488035 TO |
527 | $noteParams = array( |
528 | 'entity_table' => 'civicrm_contribution', | |
529 | 'note' => $params['note'], | |
530 | 'entity_id' => $contribution->id, | |
531 | 'contact_id' => $session->get('userID'), | |
532 | 'modified_date' => date('Ymd'), | |
533 | ); | |
534 | if (!$noteParams['contact_id']) { | |
535 | $noteParams['contact_id'] = $params['contact_id']; | |
536 | } | |
504a78f6 | 537 | CRM_Core_BAO_Note::add($noteParams); |
6a488035 TO |
538 | } |
539 | ||
540 | // make entry in batch entity batch table | |
a7488080 | 541 | if (!empty($params['batch_id'])) { |
6a488035 TO |
542 | // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params |
543 | $titleFields = array( | |
544 | 'contact_id', | |
545 | 'total_amount', | |
546 | 'currency', | |
547 | 'financial_type_id', | |
548 | ); | |
d37ade2e | 549 | $retrieveRequired = 0; |
6a488035 | 550 | foreach ($titleFields as $titleField) { |
f2b2a3ff | 551 | if (!isset($contribution->$titleField)) { |
d37ade2e | 552 | $retrieveRequired = 1; |
6a488035 TO |
553 | break; |
554 | } | |
555 | } | |
d37ade2e | 556 | if ($retrieveRequired == 1) { |
2cfc0f58 | 557 | $contribution->find(TRUE); |
6a488035 TO |
558 | } |
559 | } | |
560 | ||
7a13735b | 561 | CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution); |
2cfc0f58 | 562 | |
6a488035 TO |
563 | $transaction->commit(); |
564 | ||
464ff9cc EM |
565 | // check if activity record exist for this contribution, if |
566 | // not add activity | |
567 | $activity = new CRM_Activity_DAO_Activity(); | |
568 | $activity->source_record_id = $contribution->id; | |
569 | $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', | |
570 | 'Contribution', | |
571 | 'name' | |
572 | ); | |
6e143f06 WA |
573 | |
574 | //CRM-18406: Update activity when edit contribution. | |
575 | if ($activity->find(TRUE)) { | |
464ff9cc EM |
576 | // CRM-13237 : if activity record found, update it with campaign id of contribution |
577 | CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id); | |
6e143f06 | 578 | $contribution->activity_id = $activity->id; |
464ff9cc | 579 | } |
3f160c1c | 580 | if (empty($contribution->contact_id)) { |
581 | $contribution->find(TRUE); | |
582 | } | |
6e143f06 | 583 | CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline'); |
464ff9cc | 584 | |
6a488035 | 585 | // do not add to recent items for import, CRM-4399 |
a7488080 | 586 | if (empty($params['skipRecentView'])) { |
6a488035 TO |
587 | $url = CRM_Utils_System::url('civicrm/contact/view/contribution', |
588 | "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" | |
589 | ); | |
590 | // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params | |
591 | $titleFields = array( | |
592 | 'contact_id', | |
593 | 'total_amount', | |
594 | 'currency', | |
595 | 'financial_type_id', | |
596 | ); | |
d37ade2e | 597 | $retrieveRequired = 0; |
6a488035 | 598 | foreach ($titleFields as $titleField) { |
f2b2a3ff | 599 | if (!isset($contribution->$titleField)) { |
d37ade2e | 600 | $retrieveRequired = 1; |
6a488035 TO |
601 | break; |
602 | } | |
603 | } | |
f2b2a3ff | 604 | if ($retrieveRequired == 1) { |
2cfc0f58 | 605 | $contribution->find(TRUE); |
6a488035 TO |
606 | } |
607 | $contributionTypes = CRM_Contribute_PseudoConstant::financialType(); | |
608 | $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')'; | |
609 | ||
610 | $recentOther = array(); | |
611 | if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) { | |
612 | $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', | |
613 | "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" | |
614 | ); | |
615 | } | |
616 | ||
617 | if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) { | |
618 | $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', | |
619 | "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home" | |
620 | ); | |
621 | } | |
622 | ||
623 | // add the recently created Contribution | |
624 | CRM_Utils_Recent::add($title, | |
625 | $url, | |
626 | $contribution->id, | |
627 | 'Contribution', | |
628 | $contribution->contact_id, | |
629 | NULL, | |
630 | $recentOther | |
631 | ); | |
632 | } | |
633 | ||
634 | return $contribution; | |
635 | } | |
636 | ||
637 | /** | |
638 | * Get the values for pseudoconstants for name->value and reverse. | |
639 | * | |
014c4014 TO |
640 | * @param array $defaults |
641 | * (reference) the default values, some of which need to be resolved. | |
642 | * @param bool $reverse | |
643 | * True if we want to resolve the values in the reverse direction (value -> name). | |
6a488035 | 644 | */ |
00be9182 | 645 | public static function resolveDefaults(&$defaults, $reverse = FALSE) { |
6a488035 TO |
646 | self::lookupValue($defaults, 'financial_type', CRM_Contribute_PseudoConstant::financialType(), $reverse); |
647 | self::lookupValue($defaults, 'payment_instrument', CRM_Contribute_PseudoConstant::paymentInstrument(), $reverse); | |
648 | self::lookupValue($defaults, 'contribution_status', CRM_Contribute_PseudoConstant::contributionStatus(), $reverse); | |
649 | self::lookupValue($defaults, 'pcp', CRM_Contribute_PseudoConstant::pcPage(), $reverse); | |
650 | } | |
651 | ||
652 | /** | |
74ab7ba8 | 653 | * Convert associative array names to values and vice-versa. |
6a488035 TO |
654 | * |
655 | * This function is used by both the web form layer and the api. Note that | |
656 | * the api needs the name => value conversion, also the view layer typically | |
657 | * requires value => name conversion | |
74ab7ba8 EM |
658 | * |
659 | * @param array $defaults | |
660 | * @param string $property | |
661 | * @param array $lookup | |
662 | * @param bool $reverse | |
663 | * | |
664 | * @return bool | |
6a488035 | 665 | */ |
00be9182 | 666 | public static function lookupValue(&$defaults, $property, &$lookup, $reverse) { |
6a488035 TO |
667 | $id = $property . '_id'; |
668 | ||
669 | $src = $reverse ? $property : $id; | |
670 | $dst = $reverse ? $id : $property; | |
671 | ||
672 | if (!array_key_exists($src, $defaults)) { | |
673 | return FALSE; | |
674 | } | |
675 | ||
676 | $look = $reverse ? array_flip($lookup) : $lookup; | |
677 | ||
678 | if (is_array($look)) { | |
679 | if (!array_key_exists($defaults[$src], $look)) { | |
680 | return FALSE; | |
681 | } | |
682 | } | |
683 | $defaults[$dst] = $look[$defaults[$src]]; | |
684 | return TRUE; | |
685 | } | |
686 | ||
687 | /** | |
fe482240 EM |
688 | * Retrieve DB object based on input parameters. |
689 | * | |
690 | * It also stores all the retrieved values in the default array. | |
6a488035 | 691 | * |
014c4014 TO |
692 | * @param array $params |
693 | * (reference ) an assoc array of name/value pairs. | |
694 | * @param array $defaults | |
695 | * (reference ) an assoc array to hold the name / value pairs. | |
6a488035 | 696 | * in a hierarchical manner |
014c4014 TO |
697 | * @param array $ids |
698 | * (reference) the array that holds all the db ids. | |
6a488035 | 699 | * |
16b10e64 | 700 | * @return CRM_Contribute_BAO_Contribution |
6a488035 | 701 | */ |
00be9182 | 702 | public static function retrieve(&$params, &$defaults, &$ids) { |
6a488035 TO |
703 | $contribution = CRM_Contribute_BAO_Contribution::getValues($params, $defaults, $ids); |
704 | return $contribution; | |
705 | } | |
706 | ||
707 | /** | |
fe482240 | 708 | * Combine all the importable fields from the lower levels object. |
6a488035 TO |
709 | * |
710 | * The ordering is important, since currently we do not have a weight | |
711 | * scheme. Adding weight is super important and should be done in the | |
712 | * next week or so, before this can be called complete. | |
713 | * | |
8efea814 EM |
714 | * @param string $contactType |
715 | * @param bool $status | |
716 | * | |
a6c01b45 CW |
717 | * @return array |
718 | * array of importable Fields | |
6a488035 | 719 | */ |
00be9182 | 720 | public static function &importableFields($contactType = 'Individual', $status = TRUE) { |
6a488035 TO |
721 | if (!self::$_importableFields) { |
722 | if (!self::$_importableFields) { | |
723 | self::$_importableFields = array(); | |
724 | } | |
725 | ||
726 | if (!$status) { | |
727 | $fields = array('' => array('title' => ts('- do not import -'))); | |
728 | } | |
729 | else { | |
730 | $fields = array('' => array('title' => ts('- Contribution Fields -'))); | |
731 | } | |
732 | ||
733 | $note = CRM_Core_DAO_Note::import(); | |
734 | $tmpFields = CRM_Contribute_DAO_Contribution::import(); | |
735 | unset($tmpFields['option_value']); | |
736 | $optionFields = CRM_Core_OptionValue::getFields($mode = 'contribute'); | |
c2585c5b | 737 | $contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL); |
6a488035 TO |
738 | |
739 | // Using new Dedupe rule. | |
740 | $ruleParams = array( | |
c2585c5b | 741 | 'contact_type' => $contactType, |
f2b2a3ff | 742 | 'used' => 'Unsupervised', |
6a488035 TO |
743 | ); |
744 | $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); | |
c2585c5b | 745 | $tmpContactField = array(); |
6a488035 TO |
746 | if (is_array($fieldsArray)) { |
747 | foreach ($fieldsArray as $value) { | |
748 | //skip if there is no dupe rule | |
749 | if ($value == 'none') { | |
750 | continue; | |
751 | } | |
752 | $customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', | |
753 | $value, | |
754 | 'id', | |
755 | 'column_name' | |
756 | ); | |
757 | $value = $customFieldId ? 'custom_' . $customFieldId : $value; | |
c2585c5b | 758 | $tmpContactField[trim($value)] = $contactFields[trim($value)]; |
6a488035 | 759 | if (!$status) { |
c2585c5b | 760 | $title = $tmpContactField[trim($value)]['title'] . ' ' . ts('(match to contact)'); |
6a488035 TO |
761 | } |
762 | else { | |
c2585c5b | 763 | $title = $tmpContactField[trim($value)]['title']; |
6a488035 | 764 | } |
c2585c5b | 765 | $tmpContactField[trim($value)]['title'] = $title; |
6a488035 TO |
766 | } |
767 | } | |
768 | ||
c2585c5b | 769 | $tmpContactField['external_identifier'] = $contactFields['external_identifier']; |
770 | $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)'); | |
6a488035 | 771 | $tmpFields['contribution_contact_id']['title'] = $tmpFields['contribution_contact_id']['title'] . ' ' . ts('(match to contact)'); |
c2585c5b | 772 | $fields = array_merge($fields, $tmpContactField); |
6a488035 TO |
773 | $fields = array_merge($fields, $tmpFields); |
774 | $fields = array_merge($fields, $note); | |
775 | $fields = array_merge($fields, $optionFields); | |
776 | $fields = array_merge($fields, CRM_Financial_DAO_FinancialType::export()); | |
777 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')); | |
778 | self::$_importableFields = $fields; | |
779 | } | |
780 | return self::$_importableFields; | |
781 | } | |
782 | ||
186c9c17 | 783 | /** |
e9ff5391 | 784 | * Combine all the exportable fields from the lower level objects. |
785 | * | |
786 | * @param bool $checkPermission | |
787 | * | |
186c9c17 | 788 | * @return array |
e9ff5391 | 789 | * array of exportable Fields |
186c9c17 | 790 | */ |
5837835b | 791 | public static function &exportableFields($checkPermission = TRUE) { |
6a488035 TO |
792 | if (!self::$_exportableFields) { |
793 | if (!self::$_exportableFields) { | |
794 | self::$_exportableFields = array(); | |
795 | } | |
796 | ||
f2b2a3ff TO |
797 | $impFields = CRM_Contribute_DAO_Contribution::export(); |
798 | $expFieldProduct = CRM_Contribute_DAO_Product::export(); | |
799 | $expFieldsContrib = CRM_Contribute_DAO_ContributionProduct::export(); | |
800 | $typeField = CRM_Financial_DAO_FinancialType::export(); | |
801 | $financialAccount = CRM_Financial_DAO_FinancialAccount::export(); | |
802 | $optionField = CRM_Core_OptionValue::getFields($mode = 'contribute'); | |
6a488035 TO |
803 | $contributionStatus = array( |
804 | 'contribution_status' => array( | |
805 | 'title' => ts('Contribution Status'), | |
806 | 'name' => 'contribution_status', | |
21dfd5f5 TO |
807 | 'data_type' => CRM_Utils_Type::T_STRING, |
808 | ), | |
f2b2a3ff | 809 | ); |
6a488035 | 810 | |
3c151c70 | 811 | $contributionPage = array( |
812 | 'contribution_page' => array( | |
813 | 'title' => ts('Contribution Page'), | |
814 | 'name' => 'contribution_page', | |
815 | 'where' => 'civicrm_contribution_page.title', | |
a130e045 | 816 | 'data_type' => CRM_Utils_Type::T_STRING, |
bed98343 | 817 | ), |
a130e045 | 818 | ); |
3c151c70 | 819 | |
6a488035 | 820 | $contributionNote = array( |
a130e045 DG |
821 | 'contribution_note' => array( |
822 | 'title' => ts('Contribution Note'), | |
823 | 'name' => 'contribution_note', | |
824 | 'data_type' => CRM_Utils_Type::T_TEXT, | |
825 | ), | |
6a488035 TO |
826 | ); |
827 | ||
828 | $contributionRecurId = array( | |
9d72cede | 829 | 'contribution_recur_id' => array( |
6a488035 TO |
830 | 'title' => ts('Recurring Contributions ID'), |
831 | 'name' => 'contribution_recur_id', | |
832 | 'where' => 'civicrm_contribution.contribution_recur_id', | |
21dfd5f5 TO |
833 | 'data_type' => CRM_Utils_Type::T_INT, |
834 | ), | |
f2b2a3ff | 835 | ); |
6a488035 TO |
836 | |
837 | $extraFields = array( | |
82a43d71 | 838 | 'contribution_batch' => array( |
21dfd5f5 TO |
839 | 'title' => ts('Batch Name'), |
840 | ), | |
6a488035 TO |
841 | ); |
842 | ||
124b978e WA |
843 | // CRM-17787 |
844 | $campaignTitle = array( | |
845 | 'contribution_campaign_title' => array( | |
846 | 'title' => ts('Campaign Title'), | |
847 | 'name' => 'campaign_title', | |
848 | 'where' => 'civicrm_campaign.title', | |
849 | 'data_type' => CRM_Utils_Type::T_STRING, | |
850 | ), | |
851 | ); | |
81ec6180 DS |
852 | $softCreditFields = array( |
853 | 'contribution_soft_credit_name' => array( | |
854 | 'name' => 'contribution_soft_credit_name', | |
855 | 'title' => 'Soft Credit For', | |
856 | 'where' => 'civicrm_contact_d.display_name', | |
21dfd5f5 | 857 | 'data_type' => CRM_Utils_Type::T_STRING, |
81ec6180 DS |
858 | ), |
859 | 'contribution_soft_credit_amount' => array( | |
860 | 'name' => 'contribution_soft_credit_amount', | |
861 | 'title' => 'Soft Credit Amount', | |
862 | 'where' => 'civicrm_contribution_soft.amount', | |
21dfd5f5 | 863 | 'data_type' => CRM_Utils_Type::T_MONEY, |
81ec6180 DS |
864 | ), |
865 | 'contribution_soft_credit_type' => array( | |
866 | 'name' => 'contribution_soft_credit_type', | |
867 | 'title' => 'Soft Credit Type', | |
868 | 'where' => 'contribution_softcredit_type.label', | |
21dfd5f5 | 869 | 'data_type' => CRM_Utils_Type::T_STRING, |
81ec6180 DS |
870 | ), |
871 | 'contribution_soft_credit_contribution_id' => array( | |
872 | 'name' => 'contribution_soft_credit_contribution_id', | |
873 | 'title' => 'Soft Credit For Contribution ID', | |
874 | 'where' => 'civicrm_contribution_soft.contribution_id', | |
21dfd5f5 | 875 | 'data_type' => CRM_Utils_Type::T_INT, |
81ec6180 | 876 | ), |
5850d2e9 | 877 | 'contribution_soft_credit_contact_id' => array( |
878 | 'name' => 'contribution_soft_credit_contact_id', | |
879 | 'title' => 'Soft Credit For Contact ID', | |
9a74243e | 880 | 'where' => 'civicrm_contact_d.id', |
5850d2e9 | 881 | 'data_type' => CRM_Utils_Type::T_INT, |
882 | ), | |
81ec6180 DS |
883 | ); |
884 | ||
6ffab5b7 WA |
885 | // CRM-16713 - contribution search by Premiums on 'Find Contribution' form. |
886 | $premiums = array( | |
887 | 'contribution_product_id' => array( | |
888 | 'title' => ts('Premium'), | |
889 | 'name' => 'contribution_product_id', | |
890 | 'where' => 'civicrm_product.id', | |
891 | 'data_type' => CRM_Utils_Type::T_INT, | |
892 | ), | |
893 | ); | |
894 | ||
3c151c70 | 895 | $fields = array_merge($impFields, $typeField, $contributionStatus, $contributionPage, $optionField, $expFieldProduct, |
124b978e | 896 | $expFieldsContrib, $contributionNote, $contributionRecurId, $extraFields, $softCreditFields, $financialAccount, $premiums, $campaignTitle, |
5837835b | 897 | CRM_Core_BAO_CustomField::getFieldsForImport('Contribution', FALSE, FALSE, FALSE, $checkPermission) |
6a488035 TO |
898 | ); |
899 | ||
900 | self::$_exportableFields = $fields; | |
901 | } | |
902 | ||
903 | return self::$_exportableFields; | |
904 | } | |
905 | ||
186c9c17 EM |
906 | /** |
907 | * @param null $status | |
908 | * @param null $startDate | |
909 | * @param null $endDate | |
910 | * | |
911 | * @return array|null | |
912 | */ | |
00be9182 | 913 | public static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) { |
6a488035 TO |
914 | $where = array(); |
915 | switch ($status) { | |
916 | case 'Valid': | |
917 | $where[] = 'contribution_status_id = 1'; | |
918 | break; | |
919 | ||
920 | case 'Cancelled': | |
921 | $where[] = 'contribution_status_id = 3'; | |
922 | break; | |
923 | } | |
924 | ||
925 | if ($startDate) { | |
926 | $where[] = "receive_date >= '" . CRM_Utils_Type::escape($startDate, 'Timestamp') . "'"; | |
927 | } | |
928 | if ($endDate) { | |
929 | $where[] = "receive_date <= '" . CRM_Utils_Type::escape($endDate, 'Timestamp') . "'"; | |
930 | } | |
40c655aa | 931 | CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes); |
54d8de6b | 932 | if ($financialTypes) { |
40c655aa E |
933 | $where[] = "c.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")"; |
934 | $where[] = "i.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")"; | |
935 | } | |
54d8de6b E |
936 | else { |
937 | $where[] = "c.financial_type_id IN (0)"; | |
938 | } | |
6a488035 TO |
939 | |
940 | $whereCond = implode(' AND ', $where); | |
941 | ||
942 | $query = " | |
943 | SELECT sum( total_amount ) as total_amount, | |
54d8de6b | 944 | count( c.id ) as total_count, |
6a488035 | 945 | currency |
54d8de6b E |
946 | FROM civicrm_contribution c |
947 | INNER JOIN civicrm_contact contact ON ( contact.id = c.contact_id ) | |
948 | LEFT JOIN civicrm_line_item i ON ( i.contribution_id = c.id AND i.entity_table = 'civicrm_contribution' ) | |
6a488035 TO |
949 | WHERE $whereCond |
950 | AND ( is_test = 0 OR is_test IS NULL ) | |
951 | AND contact.is_deleted = 0 | |
952 | GROUP BY currency | |
953 | "; | |
954 | ||
9d2678f4 | 955 | $dao = CRM_Core_DAO::executeQuery($query); |
6a488035 | 956 | $amount = array(); |
f2b2a3ff | 957 | $count = 0; |
6a488035 TO |
958 | while ($dao->fetch()) { |
959 | $count += $dao->total_count; | |
960 | $amount[] = CRM_Utils_Money::format($dao->total_amount, $dao->currency); | |
961 | } | |
962 | if ($count) { | |
f2b2a3ff TO |
963 | return array( |
964 | 'amount' => implode(', ', $amount), | |
6a488035 TO |
965 | 'count' => $count, |
966 | ); | |
967 | } | |
968 | return NULL; | |
969 | } | |
970 | ||
971 | /** | |
fe482240 | 972 | * Delete the indirect records associated with this contribution first. |
6a488035 | 973 | * |
100fef9d | 974 | * @param int $id |
8efea814 | 975 | * |
72b3a70c CW |
976 | * @return mixed|null |
977 | * $results no of deleted Contribution on success, false otherwise | |
6a488035 | 978 | */ |
00be9182 | 979 | public static function deleteContribution($id) { |
6a488035 TO |
980 | CRM_Utils_Hook::pre('delete', 'Contribution', $id, CRM_Core_DAO::$_nullArray); |
981 | ||
982 | $transaction = new CRM_Core_Transaction(); | |
983 | ||
984 | $results = NULL; | |
985 | //delete activity record | |
986 | $params = array( | |
987 | 'source_record_id' => $id, | |
988 | // activity type id for contribution | |
989 | 'activity_type_id' => 6, | |
990 | ); | |
991 | ||
992 | CRM_Activity_BAO_Activity::deleteActivity($params); | |
993 | ||
994 | //delete billing address if exists for this contribution. | |
995 | self::deleteAddress($id); | |
996 | ||
997 | //update pledge and pledge payment, CRM-3961 | |
998 | CRM_Pledge_BAO_PledgePayment::resetPledgePayment($id); | |
999 | ||
1000 | // remove entry from civicrm_price_set_entity, CRM-5095 | |
9da8dc8c | 1001 | if (CRM_Price_BAO_PriceSet::getFor('civicrm_contribution', $id)) { |
1002 | CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution', $id); | |
6a488035 TO |
1003 | } |
1004 | // cleanup line items. | |
1005 | $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $id, 'participant_id', 'contribution_id'); | |
1006 | ||
de1c25e1 PN |
1007 | // delete any related entity_financial_trxn, financial_trxn and financial_item records. |
1008 | CRM_Core_BAO_FinancialTrxn::deleteFinancialTrxn($id); | |
6a488035 TO |
1009 | |
1010 | if ($participantId) { | |
1011 | CRM_Price_BAO_LineItem::deleteLineItems($participantId, 'civicrm_participant'); | |
1012 | } | |
1013 | else { | |
1014 | CRM_Price_BAO_LineItem::deleteLineItems($id, 'civicrm_contribution'); | |
1015 | } | |
1016 | ||
1017 | //delete note. | |
1018 | $note = CRM_Core_BAO_Note::getNote($id, 'civicrm_contribution'); | |
1019 | $noteId = key($note); | |
1020 | if ($noteId) { | |
1021 | CRM_Core_BAO_Note::del($noteId, FALSE); | |
1022 | } | |
1023 | ||
1024 | $dao = new CRM_Contribute_DAO_Contribution(); | |
1025 | $dao->id = $id; | |
1026 | ||
1027 | $results = $dao->delete(); | |
1028 | ||
1029 | $transaction->commit(); | |
1030 | ||
1031 | CRM_Utils_Hook::post('delete', 'Contribution', $dao->id, $dao); | |
1032 | ||
1033 | // delete the recently created Contribution | |
1034 | $contributionRecent = array( | |
1035 | 'id' => $id, | |
1036 | 'type' => 'Contribution', | |
1037 | ); | |
1038 | CRM_Utils_Recent::del($contributionRecent); | |
1039 | ||
1040 | return $results; | |
1041 | } | |
1042 | ||
7758bd2b EM |
1043 | /** |
1044 | * React to a financial transaction (payment) failure. | |
1045 | * | |
1046 | * Prior to CRM-16417 these were simply removed from the database but it has been agreed that seeing attempted | |
1047 | * payments is important for forensic and outreach reasons. | |
1048 | * | |
06d062ce | 1049 | * @param int $contributionID |
ad37ac8e | 1050 | * @param int $contactID |
06d062ce | 1051 | * @param string $message |
ad37ac8e | 1052 | * |
1053 | * @throws \CiviCRM_API3_Exception | |
7758bd2b | 1054 | */ |
06d062ce EM |
1055 | public static function failPayment($contributionID, $contactID, $message) { |
1056 | civicrm_api3('activity', 'create', array( | |
1057 | 'activity_type_id' => 'Failed Payment', | |
1058 | 'details' => $message, | |
1059 | 'subject' => ts('Payment failed at payment processor'), | |
1060 | 'source_record_id' => $contributionID, | |
1061 | 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() : | |
1062 | $contactID, | |
1063 | )); | |
7758bd2b EM |
1064 | } |
1065 | ||
6a488035 | 1066 | /** |
fe482240 | 1067 | * Check if there is a contribution with the same trxn_id or invoice_id. |
6a488035 | 1068 | * |
014c4014 TO |
1069 | * @param array $input |
1070 | * An assoc array of name/value pairs. | |
1071 | * @param array $duplicates | |
16b10e64 | 1072 | * (reference) store ids of duplicate contribs. |
100fef9d | 1073 | * @param int $id |
6a488035 | 1074 | * |
a130e045 | 1075 | * @return bool |
a6c01b45 | 1076 | * true if duplicate, false otherwise |
6a488035 | 1077 | */ |
00be9182 | 1078 | public static function checkDuplicate($input, &$duplicates, $id = NULL) { |
6a488035 TO |
1079 | if (!$id) { |
1080 | $id = CRM_Utils_Array::value('id', $input); | |
1081 | } | |
1082 | $trxn_id = CRM_Utils_Array::value('trxn_id', $input); | |
1083 | $invoice_id = CRM_Utils_Array::value('invoice_id', $input); | |
1084 | ||
1085 | $clause = array(); | |
1086 | $input = array(); | |
1087 | ||
1088 | if ($trxn_id) { | |
1089 | $clause[] = "trxn_id = %1"; | |
1090 | $input[1] = array($trxn_id, 'String'); | |
1091 | } | |
1092 | ||
1093 | if ($invoice_id) { | |
1094 | $clause[] = "invoice_id = %2"; | |
1095 | $input[2] = array($invoice_id, 'String'); | |
1096 | } | |
1097 | ||
1098 | if (empty($clause)) { | |
1099 | return FALSE; | |
1100 | } | |
1101 | ||
1102 | $clause = implode(' OR ', $clause); | |
1103 | if ($id) { | |
1104 | $clause = "( $clause ) AND id != %3"; | |
1105 | $input[3] = array($id, 'Integer'); | |
1106 | } | |
1107 | ||
f2b2a3ff TO |
1108 | $query = "SELECT id FROM civicrm_contribution WHERE $clause"; |
1109 | $dao = CRM_Core_DAO::executeQuery($query, $input); | |
6a488035 TO |
1110 | $result = FALSE; |
1111 | while ($dao->fetch()) { | |
1112 | $duplicates[] = $dao->id; | |
1113 | $result = TRUE; | |
1114 | } | |
1115 | return $result; | |
1116 | } | |
1117 | ||
1118 | /** | |
fe482240 | 1119 | * Takes an associative array and creates a contribution_product object. |
6a488035 TO |
1120 | * |
1121 | * the function extract all the params it needs to initialize the create a | |
1122 | * contribution_product object. the params array could contain additional unused name/value | |
1123 | * pairs | |
1124 | * | |
014c4014 | 1125 | * @param array $params |
16b10e64 | 1126 | * (reference) an assoc array of name/value pairs. |
6a488035 | 1127 | * |
16b10e64 | 1128 | * @return CRM_Contribute_DAO_ContributionProduct |
6a488035 | 1129 | */ |
00be9182 | 1130 | public static function addPremium(&$params) { |
6a488035 TO |
1131 | $contributionProduct = new CRM_Contribute_DAO_ContributionProduct(); |
1132 | $contributionProduct->copyValues($params); | |
1133 | return $contributionProduct->save(); | |
1134 | } | |
1135 | ||
1136 | /** | |
fe482240 | 1137 | * Get list of contribution fields for profile. |
6a488035 TO |
1138 | * For now we only allow custom contribution fields to be in |
1139 | * profile | |
1140 | * | |
014c4014 TO |
1141 | * @param bool $addExtraFields |
1142 | * True if special fields needs to be added. | |
6a488035 | 1143 | * |
a6c01b45 CW |
1144 | * @return array |
1145 | * the list of contribution fields | |
6a488035 | 1146 | */ |
00be9182 | 1147 | public static function getContributionFields($addExtraFields = TRUE) { |
6a488035 TO |
1148 | $contributionFields = CRM_Contribute_DAO_Contribution::export(); |
1149 | $contributionFields = array_merge($contributionFields, CRM_Core_OptionValue::getFields($mode = 'contribute')); | |
1150 | ||
1151 | if ($addExtraFields) { | |
1152 | $contributionFields = array_merge($contributionFields, self::getSpecialContributionFields()); | |
1153 | } | |
1154 | ||
1155 | $contributionFields = array_merge($contributionFields, CRM_Financial_DAO_FinancialType::export()); | |
1156 | ||
1157 | foreach ($contributionFields as $key => $var) { | |
1158 | if ($key == 'contribution_contact_id') { | |
1159 | continue; | |
1160 | } | |
1161 | elseif ($key == 'contribution_campaign_id') { | |
1162 | $var['title'] = ts('Campaign'); | |
1163 | } | |
1164 | $fields[$key] = $var; | |
1165 | } | |
1166 | ||
1167 | $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Contribution')); | |
1168 | return $fields; | |
1169 | } | |
1170 | ||
1171 | /** | |
74ab7ba8 | 1172 | * Add extra fields specific to contribution. |
6a488035 | 1173 | */ |
00be9182 | 1174 | public static function getSpecialContributionFields() { |
6a488035 | 1175 | $extraFields = array( |
81ec6180 DS |
1176 | 'contribution_soft_credit_name' => array( |
1177 | 'name' => 'contribution_soft_credit_name', | |
6a488035 TO |
1178 | 'title' => 'Soft Credit Name', |
1179 | 'headerPattern' => '/^soft_credit_name$/i', | |
1180 | 'where' => 'civicrm_contact_d.display_name', | |
1181 | ), | |
81ec6180 DS |
1182 | 'contribution_soft_credit_email' => array( |
1183 | 'name' => 'contribution_soft_credit_email', | |
6a488035 TO |
1184 | 'title' => 'Soft Credit Email', |
1185 | 'headerPattern' => '/^soft_credit_email$/i', | |
1186 | 'where' => 'soft_email.email', | |
1187 | ), | |
81ec6180 DS |
1188 | 'contribution_soft_credit_phone' => array( |
1189 | 'name' => 'contribution_soft_credit_phone', | |
6a488035 TO |
1190 | 'title' => 'Soft Credit Phone', |
1191 | 'headerPattern' => '/^soft_credit_phone$/i', | |
1192 | 'where' => 'soft_phone.phone', | |
1193 | ), | |
81ec6180 DS |
1194 | 'contribution_soft_credit_contact_id' => array( |
1195 | 'name' => 'contribution_soft_credit_contact_id', | |
6a488035 TO |
1196 | 'title' => 'Soft Credit Contact ID', |
1197 | 'headerPattern' => '/^soft_credit_contact_id$/i', | |
1198 | 'where' => 'civicrm_contribution_soft.contact_id', | |
1199 | ), | |
03ad81ae AH |
1200 | 'contribution_pcp_title' => array( |
1201 | 'name' => 'contribution_pcp_title', | |
1202 | 'title' => 'Personal Campaign Page Title', | |
1203 | 'headerPattern' => '/^contribution_pcp_title$/i', | |
1204 | 'where' => 'contribution_pcp.title', | |
1205 | ), | |
6a488035 TO |
1206 | ); |
1207 | ||
1208 | return $extraFields; | |
1209 | } | |
1210 | ||
186c9c17 | 1211 | /** |
100fef9d | 1212 | * @param int $pageID |
186c9c17 EM |
1213 | * |
1214 | * @return array | |
1215 | */ | |
00be9182 | 1216 | public static function getCurrentandGoalAmount($pageID) { |
6a488035 TO |
1217 | $query = " |
1218 | SELECT p.goal_amount as goal, sum( c.total_amount ) as total | |
1219 | FROM civicrm_contribution_page p, | |
1220 | civicrm_contribution c | |
1221 | WHERE p.id = c.contribution_page_id | |
1222 | AND p.id = %1 | |
1223 | AND c.cancel_date is null | |
1224 | GROUP BY p.id | |
1225 | "; | |
1226 | ||
1227 | $config = CRM_Core_Config::singleton(); | |
1228 | $params = array(1 => array($pageID, 'Integer')); | |
f2b2a3ff | 1229 | $dao = CRM_Core_DAO::executeQuery($query, $params); |
6a488035 TO |
1230 | |
1231 | if ($dao->fetch()) { | |
1232 | return array($dao->goal, $dao->total); | |
1233 | } | |
1234 | else { | |
1235 | return array(NULL, NULL); | |
1236 | } | |
1237 | } | |
1238 | ||
6a488035 | 1239 | /** |
2449fe69 | 1240 | * Get list of contributions which credit the passed in contact ID. |
1241 | * | |
1242 | * The returned array provides details about the original contribution & donor. | |
1243 | * | |
1244 | * @todo - this is a confusing function called from one place. It has a test. It would be | |
1245 | * nice to deprecate it. | |
6a488035 | 1246 | * |
014c4014 TO |
1247 | * @param int $honorId |
1248 | * In Honor of Contact ID. | |
6a488035 | 1249 | * |
72b3a70c CW |
1250 | * @return array |
1251 | * list of contribution fields | |
6a488035 | 1252 | */ |
00be9182 | 1253 | public static function getHonorContacts($honorId) { |
6a488035 | 1254 | $params = array(); |
8381af80 | 1255 | $honorDAO = new CRM_Contribute_DAO_ContributionSoft(); |
1256 | $honorDAO->contact_id = $honorId; | |
6a488035 TO |
1257 | $honorDAO->find(); |
1258 | ||
6a488035 TO |
1259 | $type = CRM_Contribute_PseudoConstant::financialType(); |
1260 | ||
1261 | while ($honorDAO->fetch()) { | |
8381af80 | 1262 | $contributionDAO = new CRM_Contribute_DAO_Contribution(); |
1263 | $contributionDAO->id = $honorDAO->contribution_id; | |
1264 | ||
1265 | if ($contributionDAO->find(TRUE)) { | |
43321dd5 | 1266 | $params[$contributionDAO->id]['honor_type'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id); |
8381af80 | 1267 | $params[$contributionDAO->id]['honorId'] = $contributionDAO->contact_id; |
1268 | $params[$contributionDAO->id]['display_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contributionDAO->contact_id, 'display_name'); | |
1269 | $params[$contributionDAO->id]['type'] = $type[$contributionDAO->financial_type_id]; | |
1270 | $params[$contributionDAO->id]['type_id'] = $contributionDAO->financial_type_id; | |
1271 | $params[$contributionDAO->id]['amount'] = CRM_Utils_Money::format($contributionDAO->total_amount, $contributionDAO->currency); | |
1272 | $params[$contributionDAO->id]['source'] = $contributionDAO->source; | |
1273 | $params[$contributionDAO->id]['receive_date'] = $contributionDAO->receive_date; | |
1274 | $params[$contributionDAO->id]['contribution_status'] = CRM_Contribute_PseudoConstant::contributionStatus($contributionDAO->contribution_status_id); | |
1275 | } | |
6a488035 TO |
1276 | } |
1277 | ||
1278 | return $params; | |
1279 | } | |
1280 | ||
1281 | /** | |
fe482240 | 1282 | * Get the sort name of a contact for a particular contribution. |
6a488035 | 1283 | * |
014c4014 TO |
1284 | * @param int $id |
1285 | * Id of the contribution. | |
6a488035 | 1286 | * |
72b3a70c CW |
1287 | * @return null|string |
1288 | * sort name of the contact if found | |
6a488035 | 1289 | */ |
00be9182 | 1290 | public static function sortName($id) { |
6a488035 TO |
1291 | $id = CRM_Utils_Type::escape($id, 'Integer'); |
1292 | ||
1293 | $query = " | |
1294 | SELECT civicrm_contact.sort_name | |
1295 | FROM civicrm_contribution, civicrm_contact | |
1296 | WHERE civicrm_contribution.contact_id = civicrm_contact.id | |
1297 | AND civicrm_contribution.id = {$id} | |
1298 | "; | |
9d2678f4 | 1299 | return CRM_Core_DAO::singleValueQuery($query); |
6a488035 TO |
1300 | } |
1301 | ||
186c9c17 | 1302 | /** |
100fef9d | 1303 | * @param int $contactID |
186c9c17 EM |
1304 | * |
1305 | * @return array | |
1306 | */ | |
00be9182 | 1307 | public static function annual($contactID) { |
6a488035 TO |
1308 | if (is_array($contactID)) { |
1309 | $contactIDs = implode(',', $contactID); | |
1310 | } | |
1311 | else { | |
1312 | $contactIDs = $contactID; | |
1313 | } | |
1314 | ||
1315 | $config = CRM_Core_Config::singleton(); | |
1316 | $startDate = $endDate = NULL; | |
1317 | ||
1318 | $currentMonth = date('m'); | |
1319 | $currentDay = date('d'); | |
1320 | if ((int ) $config->fiscalYearStart['M'] > $currentMonth || | |
1321 | ((int ) $config->fiscalYearStart['M'] == $currentMonth && | |
1322 | (int ) $config->fiscalYearStart['d'] > $currentDay | |
1323 | ) | |
1324 | ) { | |
1325 | $year = date('Y') - 1; | |
1326 | } | |
1327 | else { | |
1328 | $year = date('Y'); | |
1329 | } | |
1330 | $nextYear = $year + 1; | |
1331 | ||
1332 | if ($config->fiscalYearStart) { | |
4f25b5f5 TO |
1333 | $newFiscalYearStart = $config->fiscalYearStart; |
1334 | if ($newFiscalYearStart['M'] < 10) { | |
1335 | $newFiscalYearStart['M'] = '0' . $newFiscalYearStart['M']; | |
6a488035 | 1336 | } |
4f25b5f5 TO |
1337 | if ($newFiscalYearStart['d'] < 10) { |
1338 | $newFiscalYearStart['d'] = '0' . $newFiscalYearStart['d']; | |
6a488035 | 1339 | } |
4f25b5f5 | 1340 | $config->fiscalYearStart = $newFiscalYearStart; |
6a488035 TO |
1341 | $monthDay = $config->fiscalYearStart['M'] . $config->fiscalYearStart['d']; |
1342 | } | |
1343 | else { | |
1344 | $monthDay = '0101'; | |
1345 | } | |
1346 | $startDate = "$year$monthDay"; | |
1347 | $endDate = "$nextYear$monthDay"; | |
48069ca1 | 1348 | CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes); |
40c655aa | 1349 | $additionalWhere = " AND b.financial_type_id IN (0)"; |
fb260b73 | 1350 | $liWhere = " AND i.financial_type_id IN (0)"; |
7fb041e3 | 1351 | if (!empty($financialTypes)) { |
40c655aa E |
1352 | $additionalWhere = " AND b.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ") AND i.id IS NULL"; |
1353 | $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")"; | |
7fb041e3 | 1354 | } |
6a488035 TO |
1355 | $query = " |
1356 | SELECT count(*) as count, | |
1357 | sum(total_amount) as amount, | |
1358 | avg(total_amount) as average, | |
1359 | currency | |
1360 | FROM civicrm_contribution b | |
b880a5ce | 1361 | LEFT JOIN civicrm_line_item i ON i.contribution_id = b.id AND i.entity_table = 'civicrm_contribution' $liWhere |
6a488035 TO |
1362 | WHERE b.contact_id IN ( $contactIDs ) |
1363 | AND b.contribution_status_id = 1 | |
1364 | AND b.is_test = 0 | |
1365 | AND b.receive_date >= $startDate | |
1366 | AND b.receive_date < $endDate | |
ad37ac8e | 1367 | $additionalWhere |
6a488035 TO |
1368 | GROUP BY currency |
1369 | "; | |
33621c4f | 1370 | $dao = CRM_Core_DAO::executeQuery($query); |
f2b2a3ff | 1371 | $count = 0; |
6a488035 TO |
1372 | $amount = $average = array(); |
1373 | while ($dao->fetch()) { | |
1374 | if ($dao->count > 0 && $dao->amount > 0) { | |
1375 | $count += $dao->count; | |
1376 | $amount[] = CRM_Utils_Money::format($dao->amount, $dao->currency); | |
1377 | $average[] = CRM_Utils_Money::format($dao->average, $dao->currency); | |
1378 | } | |
1379 | } | |
1380 | if ($count > 0) { | |
1381 | return array( | |
1382 | $count, | |
1383 | implode(', ', $amount), | |
1384 | implode(', ', $average), | |
1385 | ); | |
1386 | } | |
1387 | return array(0, 0, 0); | |
1388 | } | |
1389 | ||
1390 | /** | |
1391 | * Check if there is a contribution with the params passed in. | |
a380f4a0 | 1392 | * |
6a488035 TO |
1393 | * Used for trxn_id,invoice_id and contribution_id |
1394 | * | |
014c4014 TO |
1395 | * @param array $params |
1396 | * An assoc array of name/value pairs. | |
6a488035 | 1397 | * |
a6c01b45 CW |
1398 | * @return array |
1399 | * contribution id if success else NULL | |
6a488035 | 1400 | */ |
00be9182 | 1401 | public static function checkDuplicateIds($params) { |
6a488035 TO |
1402 | $dao = new CRM_Contribute_DAO_Contribution(); |
1403 | ||
1404 | $clause = array(); | |
1405 | $input = array(); | |
1406 | foreach ($params as $k => $v) { | |
1407 | if ($v) { | |
1408 | $clause[] = "$k = '$v'"; | |
1409 | } | |
1410 | } | |
1411 | $clause = implode(' AND ', $clause); | |
f2b2a3ff TO |
1412 | $query = "SELECT id FROM civicrm_contribution WHERE $clause"; |
1413 | $dao = CRM_Core_DAO::executeQuery($query, $input); | |
6a488035 TO |
1414 | |
1415 | while ($dao->fetch()) { | |
1416 | $result = $dao->id; | |
1417 | return $result; | |
1418 | } | |
1419 | return NULL; | |
1420 | } | |
1421 | ||
1422 | /** | |
fe482240 | 1423 | * Get the contribution details for component export. |
6a488035 | 1424 | * |
014c4014 TO |
1425 | * @param int $exportMode |
1426 | * Export mode. | |
1427 | * @param string $componentIds | |
1428 | * Component ids. | |
6a488035 | 1429 | * |
a6c01b45 CW |
1430 | * @return array |
1431 | * associated array | |
6a488035 | 1432 | */ |
00be9182 | 1433 | public static function getContributionDetails($exportMode, $componentIds) { |
6a488035 TO |
1434 | $paymentDetails = array(); |
1435 | $componentClause = ' IN ( ' . implode(',', $componentIds) . ' ) '; | |
1436 | ||
1437 | if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { | |
1438 | $componentSelect = " civicrm_participant_payment.participant_id id"; | |
1439 | $additionalClause = " | |
1440 | INNER JOIN civicrm_participant_payment ON (civicrm_contribution.id = civicrm_participant_payment.contribution_id | |
1441 | AND civicrm_participant_payment.participant_id {$componentClause} ) | |
1442 | "; | |
1443 | } | |
1444 | elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { | |
1445 | $componentSelect = " civicrm_membership_payment.membership_id id"; | |
1446 | $additionalClause = " | |
1447 | INNER JOIN civicrm_membership_payment ON (civicrm_contribution.id = civicrm_membership_payment.contribution_id | |
1448 | AND civicrm_membership_payment.membership_id {$componentClause} ) | |
1449 | "; | |
1450 | } | |
1451 | elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { | |
1452 | $componentSelect = " civicrm_pledge_payment.id id"; | |
1453 | $additionalClause = " | |
1454 | INNER JOIN civicrm_pledge_payment ON (civicrm_contribution.id = civicrm_pledge_payment.contribution_id | |
1455 | AND civicrm_pledge_payment.pledge_id {$componentClause} ) | |
1456 | "; | |
1457 | } | |
1458 | ||
1459 | $query = " SELECT total_amount, contribution_status.name as status_id, contribution_status.label as status, payment_instrument.name as payment_instrument, receive_date, | |
1460 | trxn_id, {$componentSelect} | |
1461 | FROM civicrm_contribution | |
1462 | LEFT JOIN civicrm_option_group option_group_payment_instrument ON ( option_group_payment_instrument.name = 'payment_instrument') | |
1463 | LEFT JOIN civicrm_option_value payment_instrument ON (civicrm_contribution.payment_instrument_id = payment_instrument.value | |
1464 | AND option_group_payment_instrument.id = payment_instrument.option_group_id ) | |
1465 | LEFT JOIN civicrm_option_group option_group_contribution_status ON (option_group_contribution_status.name = 'contribution_status') | |
1466 | LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.contribution_status_id = contribution_status.value | |
1467 | AND option_group_contribution_status.id = contribution_status.option_group_id ) | |
1468 | {$additionalClause} | |
1469 | "; | |
1470 | ||
c7940124 | 1471 | $dao = CRM_Core_DAO::executeQuery($query); |
6a488035 TO |
1472 | |
1473 | while ($dao->fetch()) { | |
1474 | $paymentDetails[$dao->id] = array( | |
1475 | 'total_amount' => $dao->total_amount, | |
1476 | 'contribution_status' => $dao->status, | |
1477 | 'receive_date' => $dao->receive_date, | |
1478 | 'pay_instru' => $dao->payment_instrument, | |
1479 | 'trxn_id' => $dao->trxn_id, | |
1480 | ); | |
1481 | } | |
1482 | ||
1483 | return $paymentDetails; | |
1484 | } | |
1485 | ||
1486 | /** | |
c490a46a | 1487 | * Create address associated with contribution record. |
6a488035 | 1488 | * |
4914efff EM |
1489 | * As long as there is one or more billing field in the parameters we will create the address. |
1490 | * | |
1491 | * (historically the decision to create or not was based on the payment 'type' but these lines are greyer than once | |
1492 | * thought). | |
1493 | * | |
014c4014 | 1494 | * @param array $params |
c490a46a | 1495 | * @param int $billingLocationTypeID |
fd31fa4c | 1496 | * |
72b3a70c CW |
1497 | * @return int |
1498 | * address id | |
6a488035 | 1499 | */ |
4914efff | 1500 | public static function createAddress($params, $billingLocationTypeID) { |
0816949d | 1501 | list($hasBillingField, $addressParams) = self::getBillingAddressParams($params, $billingLocationTypeID); |
4914efff EM |
1502 | if ($hasBillingField) { |
1503 | $address = CRM_Core_BAO_Address::add($addressParams, FALSE); | |
739a8336 | 1504 | return $address->id; |
6a488035 | 1505 | } |
739a8336 | 1506 | return NULL; |
6a488035 | 1507 | |
6a488035 TO |
1508 | } |
1509 | ||
6a488035 | 1510 | /** |
fe482240 | 1511 | * Delete billing address record related contribution. |
6a488035 | 1512 | * |
c490a46a CW |
1513 | * @param int $contributionId |
1514 | * @param int $contactId | |
6a488035 | 1515 | */ |
00be9182 | 1516 | public static function deleteAddress($contributionId = NULL, $contactId = NULL) { |
6a488035 TO |
1517 | $clauses = array(); |
1518 | $contactJoin = NULL; | |
1519 | ||
1520 | if ($contributionId) { | |
1521 | $clauses[] = "cc.id = {$contributionId}"; | |
1522 | } | |
1523 | ||
1524 | if ($contactId) { | |
1525 | $clauses[] = "cco.id = {$contactId}"; | |
1526 | $contactJoin = "INNER JOIN civicrm_contact cco ON cc.contact_id = cco.id"; | |
1527 | } | |
1528 | ||
1529 | if (empty($clauses)) { | |
1530 | CRM_Core_Error::fatal(); | |
1531 | } | |
1532 | ||
1533 | $condition = implode(' OR ', $clauses); | |
1534 | ||
1535 | $query = " | |
1536 | SELECT ca.id | |
1537 | FROM civicrm_address ca | |
1538 | INNER JOIN civicrm_contribution cc ON cc.address_id = ca.id | |
1539 | $contactJoin | |
1540 | WHERE $condition | |
1541 | "; | |
1542 | $dao = CRM_Core_DAO::executeQuery($query); | |
1543 | ||
1544 | while ($dao->fetch()) { | |
1545 | $params = array('id' => $dao->id); | |
1546 | CRM_Core_BAO_Block::blockDelete('Address', $params); | |
1547 | } | |
1548 | } | |
1549 | ||
1550 | /** | |
1551 | * This function check online pending contribution associated w/ | |
1552 | * Online Event Registration or Online Membership signup. | |
1553 | * | |
014c4014 TO |
1554 | * @param int $componentId |
1555 | * Participant/membership id. | |
1556 | * @param string $componentName | |
1557 | * Event/Membership. | |
6a488035 | 1558 | * |
16b10e64 CW |
1559 | * @return int |
1560 | * pending contribution id. | |
6a488035 | 1561 | */ |
00be9182 | 1562 | public static function checkOnlinePendingContribution($componentId, $componentName) { |
6a488035 TO |
1563 | $contributionId = NULL; |
1564 | if (!$componentId || | |
1565 | !in_array($componentName, array('Event', 'Membership')) | |
1566 | ) { | |
1567 | return $contributionId; | |
1568 | } | |
1569 | ||
1570 | if ($componentName == 'Event') { | |
f2b2a3ff | 1571 | $idName = 'participant_id'; |
6a488035 | 1572 | $componentTable = 'civicrm_participant'; |
f2b2a3ff TO |
1573 | $paymentTable = 'civicrm_participant_payment'; |
1574 | $source = ts('Online Event Registration'); | |
6a488035 TO |
1575 | } |
1576 | ||
1577 | if ($componentName == 'Membership') { | |
f2b2a3ff | 1578 | $idName = 'membership_id'; |
6a488035 | 1579 | $componentTable = 'civicrm_membership'; |
f2b2a3ff TO |
1580 | $paymentTable = 'civicrm_membership_payment'; |
1581 | $source = ts('Online Contribution'); | |
6a488035 TO |
1582 | } |
1583 | ||
1584 | $pendingStatusId = array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')); | |
1585 | ||
1586 | $query = " | |
1587 | SELECT component.id as {$idName}, | |
1588 | componentPayment.contribution_id as contribution_id, | |
1589 | contribution.source source, | |
1590 | contribution.contribution_status_id as contribution_status_id, | |
1591 | contribution.is_pay_later as is_pay_later | |
1592 | FROM $componentTable component | |
1593 | LEFT JOIN $paymentTable componentPayment ON ( componentPayment.{$idName} = component.id ) | |
1594 | LEFT JOIN civicrm_contribution contribution ON ( componentPayment.contribution_id = contribution.id ) | |
1595 | WHERE component.id = {$componentId}"; | |
1596 | ||
1597 | $dao = CRM_Core_DAO::executeQuery($query); | |
1598 | ||
1599 | while ($dao->fetch()) { | |
1600 | if ($dao->contribution_id && | |
1601 | $dao->is_pay_later && | |
1602 | $dao->contribution_status_id == $pendingStatusId && | |
1603 | strpos($dao->source, $source) !== FALSE | |
1604 | ) { | |
1605 | $contributionId = $dao->contribution_id; | |
1606 | $dao->free(); | |
1607 | } | |
1608 | } | |
1609 | ||
1610 | return $contributionId; | |
1611 | } | |
1612 | ||
1613 | /** | |
16b10e64 | 1614 | * Update contribution as well as related objects. |
74ab7ba8 | 1615 | * |
f8c94f00 | 1616 | * This function by-passes hooks - to address this - don't use this function. |
1617 | * | |
1f7c01e4 | 1618 | * @deprecated |
1619 | * | |
1620 | * Use api contribute.completetransaction | |
1621 | * For failures use failPayment (preferably exposing by api in the process). | |
1622 | * | |
74ab7ba8 EM |
1623 | * @param array $params |
1624 | * @param bool $processContributionObject | |
1625 | * | |
1626 | * @return array | |
1627 | * @throws \Exception | |
6a488035 | 1628 | */ |
00be9182 | 1629 | public static function transitionComponents($params, $processContributionObject = FALSE) { |
6a488035 TO |
1630 | // get minimum required values. |
1631 | $contactId = CRM_Utils_Array::value('contact_id', $params); | |
1632 | $componentId = CRM_Utils_Array::value('component_id', $params); | |
1633 | $componentName = CRM_Utils_Array::value('componentName', $params); | |
1634 | $contributionId = CRM_Utils_Array::value('contribution_id', $params); | |
1635 | $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params); | |
1636 | ||
1637 | // if we already processed contribution object pass previous status id. | |
1638 | $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params); | |
1639 | ||
1640 | $updateResult = array(); | |
1641 | ||
1642 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); | |
1643 | ||
1644 | // we process only ( Completed, Cancelled, or Failed ) contributions. | |
1645 | if (!$contributionId || | |
f2b2a3ff TO |
1646 | !in_array($contributionStatusId, array( |
1647 | array_search('Completed', $contributionStatuses), | |
1648 | array_search('Cancelled', $contributionStatuses), | |
1649 | array_search('Failed', $contributionStatuses), | |
1650 | )) | |
6a488035 TO |
1651 | ) { |
1652 | return $updateResult; | |
1653 | } | |
1654 | ||
1655 | if (!$componentName || !$componentId) { | |
1656 | // get the related component details. | |
1657 | $componentDetails = self::getComponentDetails($contributionId); | |
1658 | } | |
1659 | else { | |
1660 | $componentDetails['contact_id'] = $contactId; | |
1661 | $componentDetails['component'] = $componentName; | |
1662 | ||
1663 | if ($componentName == 'event') { | |
1664 | $componentDetails['participant'] = $componentId; | |
1665 | } | |
1666 | else { | |
1667 | $componentDetails['membership'] = $componentId; | |
1668 | } | |
1669 | } | |
1670 | ||
a7488080 | 1671 | if (!empty($componentDetails['contact_id'])) { |
6a488035 TO |
1672 | $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', |
1673 | $contributionId, | |
1674 | 'contact_id' | |
1675 | ); | |
1676 | } | |
1677 | ||
1678 | // do check for required ids. | |
8cc574cf | 1679 | if (empty($componentDetails['membership']) && empty($componentDetails['participant']) && empty($componentDetails['pledge_payment']) || empty($componentDetails['contact_id'])) { |
6a488035 TO |
1680 | return $updateResult; |
1681 | } | |
1682 | ||
1683 | //now we are ready w/ required ids, start processing. | |
1684 | ||
1685 | $baseIPN = new CRM_Core_Payment_BaseIPN(); | |
1686 | ||
1687 | $input = $ids = $objects = array(); | |
1688 | ||
1689 | $input['component'] = CRM_Utils_Array::value('component', $componentDetails); | |
1690 | $ids['contribution'] = $contributionId; | |
1691 | $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails); | |
1692 | $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails); | |
1693 | $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails); | |
1694 | $ids['event'] = CRM_Utils_Array::value('event', $componentDetails); | |
1695 | $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails); | |
1696 | $ids['contributionRecur'] = NULL; | |
1697 | $ids['contributionPage'] = NULL; | |
1698 | ||
1699 | if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) { | |
1700 | CRM_Core_Error::fatal(); | |
1701 | } | |
1702 | ||
f2b2a3ff TO |
1703 | $memberships = &$objects['membership']; |
1704 | $participant = &$objects['participant']; | |
6a488035 | 1705 | $pledgePayment = &$objects['pledge_payment']; |
f2b2a3ff | 1706 | $contribution = &$objects['contribution']; |
6a488035 TO |
1707 | |
1708 | if ($pledgePayment) { | |
1709 | $pledgePaymentIDs = array(); | |
1710 | foreach ($pledgePayment as $key => $object) { | |
1711 | $pledgePaymentIDs[] = $object->id; | |
1712 | } | |
1713 | $pledgeID = $pledgePayment[0]->pledge_id; | |
1714 | } | |
1715 | ||
6a488035 TO |
1716 | $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus(); |
1717 | ||
1718 | if ($participant) { | |
1719 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); | |
1720 | $oldStatus = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', | |
1721 | $participant->id, | |
1722 | 'status_id' | |
1723 | ); | |
1724 | } | |
1725 | // we might want to process contribution object. | |
1726 | $processContribution = FALSE; | |
1727 | if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) { | |
1728 | if (is_array($memberships)) { | |
1729 | foreach ($memberships as $membership) { | |
1730 | if ($membership) { | |
1731 | $membership->status_id = array_search('Cancelled', $membershipStatuses); | |
1732 | $membership->save(); | |
1733 | ||
1734 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; | |
1735 | if ($processContributionObject) { | |
1736 | $processContribution = TRUE; | |
1737 | } | |
1738 | } | |
1739 | } | |
1740 | } | |
1741 | ||
1742 | if ($participant) { | |
1743 | $updatedStatusId = array_search('Cancelled', $participantStatuses); | |
1744 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); | |
1745 | ||
1746 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; | |
1747 | if ($processContributionObject) { | |
1748 | $processContribution = TRUE; | |
1749 | } | |
1750 | } | |
1751 | ||
1752 | if ($pledgePayment) { | |
1753 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); | |
1754 | ||
1755 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; | |
1756 | if ($processContributionObject) { | |
1757 | $processContribution = TRUE; | |
1758 | } | |
1759 | } | |
1760 | } | |
1761 | elseif ($contributionStatusId == array_search('Failed', $contributionStatuses)) { | |
1762 | if (is_array($memberships)) { | |
1763 | foreach ($memberships as $membership) { | |
1764 | if ($membership) { | |
1765 | $membership->status_id = array_search('Expired', $membershipStatuses); | |
1766 | $membership->save(); | |
1767 | ||
1768 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; | |
1769 | if ($processContributionObject) { | |
1770 | $processContribution = TRUE; | |
1771 | } | |
1772 | } | |
1773 | } | |
1774 | } | |
1775 | if ($participant) { | |
1776 | $updatedStatusId = array_search('Cancelled', $participantStatuses); | |
1777 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); | |
1778 | ||
1779 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; | |
1780 | if ($processContributionObject) { | |
1781 | $processContribution = TRUE; | |
1782 | } | |
1783 | } | |
1784 | ||
1785 | if ($pledgePayment) { | |
1786 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); | |
1787 | ||
1788 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; | |
1789 | if ($processContributionObject) { | |
1790 | $processContribution = TRUE; | |
1791 | } | |
1792 | } | |
1793 | } | |
1794 | elseif ($contributionStatusId == array_search('Completed', $contributionStatuses)) { | |
1795 | ||
1796 | // only pending contribution related object processed. | |
1797 | if ($previousContriStatusId && | |
1798 | ($previousContriStatusId != array_search('Pending', $contributionStatuses)) | |
1799 | ) { | |
1800 | // this is case when we already processed contribution object. | |
1801 | return $updateResult; | |
1802 | } | |
1803 | elseif (!$previousContriStatusId && | |
1804 | $contribution->contribution_status_id != array_search('Pending', $contributionStatuses) | |
1805 | ) { | |
1806 | // this is case when we are going to process contribution object later. | |
1807 | return $updateResult; | |
1808 | } | |
1809 | ||
1810 | if (is_array($memberships)) { | |
1811 | foreach ($memberships as $membership) { | |
1812 | if ($membership) { | |
1813 | $format = '%Y%m%d'; | |
1814 | ||
1815 | //CRM-4523 | |
1816 | $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, | |
1817 | $membership->membership_type_id, | |
1818 | $membership->is_test, $membership->id | |
1819 | ); | |
1820 | ||
1821 | // CRM-8141 update the membership type with the value recorded in log when membership created/renewed | |
1822 | // this picks up membership type changes during renewals | |
1823 | $sql = " | |
1824 | SELECT membership_type_id | |
1825 | FROM civicrm_membership_log | |
1826 | WHERE membership_id=$membership->id | |
1827 | ORDER BY id DESC | |
1828 | LIMIT 1;"; | |
a130e045 | 1829 | $dao = new CRM_Core_DAO(); |
6a488035 TO |
1830 | $dao->query($sql); |
1831 | if ($dao->fetch()) { | |
1832 | if (!empty($dao->membership_type_id)) { | |
1833 | $membership->membership_type_id = $dao->membership_type_id; | |
1834 | $membership->save(); | |
1835 | } | |
1836 | } | |
1837 | // else fall back to using current membership type | |
1838 | $dao->free(); | |
1839 | ||
9c09f5b7 AH |
1840 | // Figure out number of terms |
1841 | $numterms = 1; | |
77dbdcbc | 1842 | $lineitems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId); |
9c09f5b7 AH |
1843 | foreach ($lineitems as $lineitem) { |
1844 | if ($membership->membership_type_id == CRM_Utils_Array::value('membership_type_id', $lineitem)) { | |
1845 | $numterms = CRM_Utils_Array::value('membership_num_terms', $lineitem); | |
2d77a516 | 1846 | |
9c09f5b7 AH |
1847 | // in case membership_num_terms comes through as null or zero |
1848 | $numterms = $numterms >= 1 ? $numterms : 1; | |
1849 | break; | |
1850 | } | |
1851 | } | |
1852 | ||
e8c64fab | 1853 | // CRM-15735-to update the membership status as per the contribution receive date |
35874a67 | 1854 | $joinDate = NULL; |
e8c64fab | 1855 | if (!empty($params['receive_date'])) { |
35874a67 | 1856 | $joinDate = $params['receive_date']; |
e8c64fab | 1857 | $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date, |
1858 | $membership->end_date, | |
1859 | $membership->join_date, | |
1860 | $params['receive_date'], | |
1861 | FALSE, | |
1862 | $membership->membership_type_id, | |
1863 | (array) $membership | |
1864 | ); | |
1865 | $membership->status_id = CRM_Utils_Array::value('id', $status, $membership->status_id); | |
1866 | $membership->save(); | |
1867 | } | |
1868 | ||
6a488035 | 1869 | if ($currentMembership) { |
9c09f5b7 AH |
1870 | CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, NULL); |
1871 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, NULL, NULL, $numterms); | |
6a488035 TO |
1872 | $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); |
1873 | } | |
1874 | else { | |
35874a67 | 1875 | $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms); |
6a488035 TO |
1876 | } |
1877 | ||
1878 | //get the status for membership. | |
1879 | $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], | |
1880 | $dates['end_date'], | |
1881 | $dates['join_date'], | |
1882 | 'today', | |
5f11bbcc EM |
1883 | TRUE, |
1884 | $membership->membership_type_id, | |
1885 | (array) $membership | |
6a488035 TO |
1886 | ); |
1887 | ||
c2585c5b | 1888 | $formattedParams = array( |
6a488035 TO |
1889 | 'status_id' => CRM_Utils_Array::value('id', $calcStatus, |
1890 | array_search('Current', $membershipStatuses) | |
1891 | ), | |
1892 | 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), | |
1893 | 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), | |
1894 | 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), | |
1895 | ); | |
1896 | ||
c2585c5b | 1897 | CRM_Utils_Hook::pre('edit', 'Membership', $membership->id, $formattedParams); |
6a488035 | 1898 | |
c2585c5b | 1899 | $membership->copyValues($formattedParams); |
6a488035 TO |
1900 | $membership->save(); |
1901 | ||
1902 | //updating the membership log | |
1903 | $membershipLog = array(); | |
c2585c5b | 1904 | $membershipLog = $formattedParams; |
f2b2a3ff TO |
1905 | $logStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('log_start_date', $dates), $format); |
1906 | $logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : $formattedParams['start_date']; | |
6a488035 TO |
1907 | |
1908 | $membershipLog['start_date'] = $logStartDate; | |
1909 | $membershipLog['membership_id'] = $membership->id; | |
1910 | $membershipLog['modified_id'] = $membership->contact_id; | |
1911 | $membershipLog['modified_date'] = date('Ymd'); | |
1912 | $membershipLog['membership_type_id'] = $membership->membership_type_id; | |
1913 | ||
1914 | CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); | |
1915 | ||
1916 | //update related Memberships. | |
c2585c5b | 1917 | CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formattedParams); |
6a488035 | 1918 | |
0f07bb06 | 1919 | //CRM-19678: No Membership Renewal Activity is created when a Pay Later is set to Completed |
1920 | CRM_Activity_BAO_Activity::addActivity($membership, 'Membership Renewal', $membership->contact_id); | |
1921 | ||
6a488035 TO |
1922 | $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], |
1923 | '%B %E%f, %Y' | |
1924 | ); | |
1925 | $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; | |
1926 | if ($processContributionObject) { | |
1927 | $processContribution = TRUE; | |
1928 | } | |
1929 | ||
1930 | CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership); | |
1931 | } | |
1932 | } | |
1933 | } | |
1934 | ||
1935 | if ($participant) { | |
1936 | $updatedStatusId = array_search('Registered', $participantStatuses); | |
1937 | CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, TRUE); | |
1938 | ||
1939 | $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; | |
1940 | if ($processContributionObject) { | |
1941 | $processContribution = TRUE; | |
1942 | } | |
1943 | } | |
1944 | ||
1945 | if ($pledgePayment) { | |
1946 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); | |
1947 | ||
1948 | $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; | |
1949 | if ($processContributionObject) { | |
1950 | $processContribution = TRUE; | |
1951 | } | |
1952 | } | |
1953 | } | |
1954 | ||
1955 | // process contribution object. | |
1956 | if ($processContribution) { | |
1957 | $contributionParams = array(); | |
1958 | $fields = array( | |
f2b2a3ff TO |
1959 | 'contact_id', |
1960 | 'total_amount', | |
1961 | 'receive_date', | |
1962 | 'is_test', | |
1963 | 'campaign_id', | |
1964 | 'payment_instrument_id', | |
1965 | 'trxn_id', | |
1966 | 'invoice_id', | |
1967 | 'financial_type_id', | |
1968 | 'contribution_status_id', | |
1969 | 'non_deductible_amount', | |
1970 | 'receipt_date', | |
1971 | 'check_number', | |
6a488035 TO |
1972 | ); |
1973 | foreach ($fields as $field) { | |
a7488080 | 1974 | if (empty($params[$field])) { |
6a488035 TO |
1975 | continue; |
1976 | } | |
1977 | $contributionParams[$field] = $params[$field]; | |
1978 | } | |
1979 | ||
1980 | $ids = array('contribution' => $contributionId); | |
1981 | $contribution = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); | |
1982 | } | |
1983 | ||
1984 | return $updateResult; | |
1985 | } | |
1986 | ||
1987 | /** | |
16b10e64 | 1988 | * Returns all contribution related object ids. |
7a9ab499 EM |
1989 | * |
1990 | * @param $contributionId | |
1991 | * | |
1992 | * @return array | |
6a488035 | 1993 | */ |
291ca04f | 1994 | public static function getComponentDetails($contributionId) { |
6a488035 TO |
1995 | $componentDetails = $pledgePayment = array(); |
1996 | if (!$contributionId) { | |
1997 | return $componentDetails; | |
1998 | } | |
1999 | ||
2000 | $query = " | |
2001 | SELECT c.id as contribution_id, | |
2002 | c.contact_id as contact_id, | |
d97c96dc | 2003 | c.contribution_recur_id, |
6a488035 TO |
2004 | mp.membership_id as membership_id, |
2005 | m.membership_type_id as membership_type_id, | |
2006 | pp.participant_id as participant_id, | |
2007 | p.event_id as event_id, | |
2008 | pgp.id as pledge_payment_id | |
2009 | FROM civicrm_contribution c | |
2010 | LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id | |
2011 | LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id | |
2012 | LEFT JOIN civicrm_participant p ON pp.participant_id = p.id | |
2013 | LEFT JOIN civicrm_membership m ON m.id = mp.membership_id | |
2014 | LEFT JOIN civicrm_pledge_payment pgp ON pgp.contribution_id = c.id | |
2015 | WHERE c.id = $contributionId"; | |
2016 | ||
2017 | $dao = CRM_Core_DAO::executeQuery($query); | |
2018 | $componentDetails = array(); | |
2019 | ||
2020 | while ($dao->fetch()) { | |
2021 | $componentDetails['component'] = $dao->participant_id ? 'event' : 'contribute'; | |
2022 | $componentDetails['contact_id'] = $dao->contact_id; | |
2023 | if ($dao->event_id) { | |
2024 | $componentDetails['event'] = $dao->event_id; | |
2025 | } | |
2026 | if ($dao->participant_id) { | |
2027 | $componentDetails['participant'] = $dao->participant_id; | |
2028 | } | |
2029 | if ($dao->membership_id) { | |
2030 | if (!isset($componentDetails['membership'])) { | |
2031 | $componentDetails['membership'] = $componentDetails['membership_type'] = array(); | |
2032 | } | |
2033 | $componentDetails['membership'][] = $dao->membership_id; | |
2034 | $componentDetails['membership_type'][] = $dao->membership_type_id; | |
2035 | } | |
2036 | if ($dao->pledge_payment_id) { | |
2037 | $pledgePayment[] = $dao->pledge_payment_id; | |
2038 | } | |
d97c96dc EM |
2039 | if ($dao->contribution_recur_id) { |
2040 | $componentDetails['contributionRecur'] = $dao->contribution_recur_id; | |
2041 | } | |
6a488035 TO |
2042 | } |
2043 | ||
2044 | if ($pledgePayment) { | |
2045 | $componentDetails['pledge_payment'] = $pledgePayment; | |
2046 | } | |
2047 | ||
2048 | return $componentDetails; | |
2049 | } | |
2050 | ||
186c9c17 | 2051 | /** |
100fef9d | 2052 | * @param int $contactId |
186c9c17 EM |
2053 | * @param bool $includeSoftCredit |
2054 | * | |
2055 | * @return null|string | |
2056 | */ | |
00be9182 | 2057 | public static function contributionCount($contactId, $includeSoftCredit = TRUE) { |
6a488035 TO |
2058 | if (!$contactId) { |
2059 | return 0; | |
2060 | } | |
d3426391 | 2061 | CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes); |
7fb041e3 | 2062 | $additionalWhere = " AND contribution.financial_type_id IN (0)"; |
9cec2e9f | 2063 | $liWhere = " AND i.financial_type_id IN (0)"; |
7fb041e3 | 2064 | if (!empty($financialTypes)) { |
40c655aa E |
2065 | $additionalWhere = " AND contribution.financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")"; |
2066 | $liWhere = " AND i.financial_type_id NOT IN (" . implode(',', array_keys($financialTypes)) . ")"; | |
7fb041e3 | 2067 | } |
bbde790f RN |
2068 | $contactContributionsSQL = " |
2069 | SELECT contribution.id AS id | |
2070 | FROM civicrm_contribution contribution | |
ad37ac8e | 2071 | LEFT JOIN civicrm_line_item i ON i.contribution_id = contribution.id AND i.entity_table = 'civicrm_contribution' $liWhere |
2072 | WHERE contribution.is_test = 0 AND contribution.contact_id = {$contactId} | |
2073 | $additionalWhere | |
9cec2e9f | 2074 | AND i.id IS NULL"; |
bbde790f | 2075 | |
bbde790f RN |
2076 | $contactSoftCreditContributionsSQL = " |
2077 | SELECT contribution.id | |
2078 | FROM civicrm_contribution contribution INNER JOIN civicrm_contribution_soft softContribution | |
2079 | ON ( contribution.id = softContribution.contribution_id ) | |
2080 | WHERE contribution.is_test = 0 AND softContribution.contact_id = {$contactId} "; | |
2081 | $query = "SELECT count( x.id ) count FROM ( "; | |
2082 | $query .= $contactContributionsSQL; | |
2083 | ||
6a488035 | 2084 | if ($includeSoftCredit) { |
bbde790f RN |
2085 | $query .= " UNION "; |
2086 | $query .= $contactSoftCreditContributionsSQL; | |
6a488035 | 2087 | } |
bbde790f | 2088 | |
bbde790f | 2089 | $query .= ") x"; |
6a488035 TO |
2090 | |
2091 | return CRM_Core_DAO::singleValueQuery($query); | |
2092 | } | |
2093 | ||
b3b7f4c5 | 2094 | /** |
2095 | * Repeat a transaction as part of a recurring series. | |
2096 | * | |
2097 | * Only call this via the api as it is being refactored. The intention is that the repeatTransaction function | |
2098 | * (possibly living on the ContributionRecur BAO) would be called first to create a pending contribution with a | |
2099 | * subsequent call to the contribution.completetransaction api. | |
2100 | * | |
2101 | * The completeTransaction functionality has historically been overloaded to both complete and repeat payments. | |
2102 | * | |
2103 | * @param CRM_Contribute_BAO_Contribution $contribution | |
2104 | * @param array $input | |
2105 | * @param array $contributionParams | |
43c8d1dd | 2106 | * @param int $paymentProcessorID |
b3b7f4c5 | 2107 | * |
2108 | * @return array | |
43c8d1dd | 2109 | * @throws CiviCRM_API3_Exception |
b3b7f4c5 | 2110 | */ |
43c8d1dd | 2111 | protected static function repeatTransaction(&$contribution, &$input, $contributionParams, $paymentProcessorID) { |
b3b7f4c5 | 2112 | if (!empty($contribution->id)) { |
2113 | return FALSE; | |
2114 | } | |
2115 | if (empty($contribution->id)) { | |
2116 | // Unclear why this would only be set for repeats. | |
2117 | if (!empty($input['amount'])) { | |
2118 | $contribution->total_amount = $contributionParams['total_amount'] = $input['amount']; | |
2119 | } | |
43c8d1dd | 2120 | |
c02c17df | 2121 | if (!empty($contributionParams['contribution_recur_id'])) { |
2122 | $recurringContribution = civicrm_api3('ContributionRecur', 'getsingle', array( | |
2123 | 'id' => $contributionParams['contribution_recur_id'], | |
2124 | )); | |
2125 | if (!empty($recurringContribution['campaign_id'])) { | |
2126 | // CRM-17718 the campaign id on the contribution recur record should get precedence. | |
2127 | $contributionParams['campaign_id'] = $recurringContribution['campaign_id']; | |
2128 | } | |
7f4ef731 | 2129 | if (!empty($recurringContribution['financial_type_id'])) { |
2130 | // CRM-17718 the campaign id on the contribution recur record should get precedence. | |
2131 | $contributionParams['financial_type_id'] = $recurringContribution['financial_type_id']; | |
2132 | } | |
c02c17df | 2133 | } |
43c8d1dd | 2134 | $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution( |
2135 | $contributionParams['contribution_recur_id'], | |
2136 | array_intersect_key($contributionParams, array('total_amount' => TRUE, 'financial_type_id' => TRUE)) | |
2137 | ); | |
2138 | $input['line_item'] = $contributionParams['line_item'] = $templateContribution['line_item']; | |
2139 | ||
f8c94f00 | 2140 | $contributionParams['status_id'] = 'Pending'; |
3c49d90c | 2141 | if (isset($contributionParams['financial_type_id'])) { |
2142 | // Give precedence to passed in type. | |
2143 | $contribution->financial_type_id = $contributionParams['financial_type_id']; | |
2144 | } | |
2145 | else { | |
2146 | $contributionParams['financial_type_id'] = $templateContribution['financial_type_id']; | |
2147 | } | |
b3b7f4c5 | 2148 | $contributionParams['contact_id'] = $templateContribution['contact_id']; |
f8c94f00 | 2149 | $contributionParams['source'] = empty($templateContribution['source']) ? ts('Recurring contribution') : $templateContribution['source']; |
43c8d1dd | 2150 | |
44fec73b BS |
2151 | //CRM-18805 -- Contribution page not recorded on recurring transactions, Recurring contribution payments |
2152 | //do not create CC or BCC emails or profile notifications. | |
2153 | //The if is just to be safe. Not sure if we can ever arrive with this unset | |
8536e5a0 | 2154 | // but per CRM-19478 it seems it can be 'null' |
2155 | if (isset($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) { | |
4194dd55 | 2156 | $contributionParams['contribution_page_id'] = $contribution->contribution_page_id; |
a4facb5c | 2157 | } |
44fec73b | 2158 | |
b3b7f4c5 | 2159 | $createContribution = civicrm_api3('Contribution', 'create', $contributionParams); |
2160 | $contribution->id = $createContribution['id']; | |
f8c94f00 | 2161 | CRM_Contribute_BAO_ContributionRecur::copyCustomValues($contributionParams['contribution_recur_id'], $contribution->id); |
b3b7f4c5 | 2162 | return TRUE; |
2163 | } | |
2164 | } | |
2165 | ||
6a488035 | 2166 | /** |
fe482240 | 2167 | * Get individual id for onbehalf contribution. |
6a488035 | 2168 | * |
014c4014 TO |
2169 | * @param int $contributionId |
2170 | * Contribution id. | |
2171 | * @param int $contributorId | |
2172 | * Contributor id. | |
6a488035 | 2173 | * |
a6c01b45 CW |
2174 | * @return array |
2175 | * containing organization id and individual id | |
6a488035 | 2176 | */ |
00be9182 | 2177 | public static function getOnbehalfIds($contributionId, $contributorId = NULL) { |
6a488035 TO |
2178 | |
2179 | $ids = array(); | |
2180 | ||
2181 | if (!$contributionId) { | |
2182 | return $ids; | |
2183 | } | |
2184 | ||
2185 | // fetch contributor id if null | |
2186 | if (!$contributorId) { | |
2187 | $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', | |
2188 | $contributionId, 'contact_id' | |
2189 | ); | |
2190 | } | |
2191 | ||
2192 | $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'); | |
2193 | $activityTypeId = array_search('Contribution', $activityTypeIds); | |
2194 | ||
2195 | if ($activityTypeId && $contributorId) { | |
2196 | $activityQuery = " | |
2d77a516 DL |
2197 | SELECT civicrm_activity_contact.contact_id |
2198 | FROM civicrm_activity_contact | |
2199 | INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id | |
2200 | WHERE civicrm_activity.activity_type_id = %1 | |
2201 | AND civicrm_activity.source_record_id = %2 | |
2202 | AND civicrm_activity_contact.record_type_id = %3 | |
2203 | "; | |
6a488035 | 2204 | |
e7e657f0 | 2205 | $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); |
2d77a516 DL |
2206 | $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); |
2207 | ||
2208 | $params = array( | |
2209 | 1 => array($activityTypeId, 'Integer'), | |
6a488035 | 2210 | 2 => array($contributionId, 'Integer'), |
2d77a516 | 2211 | 3 => array($sourceID, 'Integer'), |
6a488035 TO |
2212 | ); |
2213 | ||
2214 | $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params); | |
2215 | ||
2216 | // for on behalf contribution source is individual and contributor is organization | |
2217 | if ($sourceContactId && $sourceContactId != $contributorId) { | |
2218 | $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name'); | |
2219 | // get rel type id for employee of relation | |
2220 | foreach ($relationshipTypeIds as $id => $typeVals) { | |
2221 | if ($typeVals['name_a_b'] == 'Employee of') { | |
2222 | $relationshipTypeId = $id; | |
2223 | break; | |
2224 | } | |
2225 | } | |
2226 | ||
2227 | $rel = new CRM_Contact_DAO_Relationship(); | |
2228 | $rel->relationship_type_id = $relationshipTypeId; | |
2229 | $rel->contact_id_a = $sourceContactId; | |
2230 | $rel->contact_id_b = $contributorId; | |
2231 | if ($rel->find(TRUE)) { | |
2232 | $ids['individual_id'] = $rel->contact_id_a; | |
2233 | $ids['organization_id'] = $rel->contact_id_b; | |
2234 | } | |
2235 | } | |
2236 | } | |
2237 | ||
2238 | return $ids; | |
2239 | } | |
2240 | ||
2241 | /** | |
2242 | * @return array | |
6a488035 | 2243 | */ |
00be9182 | 2244 | public static function getContributionDates() { |
f2b2a3ff | 2245 | $config = CRM_Core_Config::singleton(); |
6a488035 | 2246 | $currentMonth = date('m'); |
f2b2a3ff | 2247 | $currentDay = date('d'); |
6a488035 TO |
2248 | if ((int ) $config->fiscalYearStart['M'] > $currentMonth || |
2249 | ((int ) $config->fiscalYearStart['M'] == $currentMonth && | |
2250 | (int ) $config->fiscalYearStart['d'] > $currentDay | |
2251 | ) | |
2252 | ) { | |
2253 | $year = date('Y') - 1; | |
2254 | } | |
2255 | else { | |
2256 | $year = date('Y'); | |
2257 | } | |
f2b2a3ff | 2258 | $year = array('Y' => $year); |
6a488035 TO |
2259 | $yearDate = $config->fiscalYearStart; |
2260 | $yearDate = array_merge($year, $yearDate); | |
2261 | $yearDate = CRM_Utils_Date::format($yearDate); | |
2262 | ||
2263 | $monthDate = date('Ym') . '01'; | |
2264 | ||
2265 | $now = date('Ymd'); | |
2266 | ||
2267 | return array( | |
2268 | 'now' => $now, | |
2269 | 'yearDate' => $yearDate, | |
2270 | 'monthDate' => $monthDate, | |
2271 | ); | |
2272 | } | |
2273 | ||
16b10e64 | 2274 | /** |
fe482240 | 2275 | * Load objects relations to contribution object. |
6a488035 TO |
2276 | * Objects are stored in the $_relatedObjects property |
2277 | * In the first instance we are just moving functionality from BASEIpn - | |
16b10e64 CW |
2278 | * @see http://issues.civicrm.org/jira/browse/CRM-9996 |
2279 | * | |
2280 | * Note that the unit test for the BaseIPN class tests this function | |
6a488035 | 2281 | * |
014c4014 TO |
2282 | * @param array $input |
2283 | * Input as delivered from Payment Processor. | |
2284 | * @param array $ids | |
2285 | * Ids as Loaded by Payment Processor. | |
014c4014 TO |
2286 | * @param bool $loadAll |
2287 | * Load all related objects - even where id not passed in? (allows API to call this). | |
186c9c17 EM |
2288 | * |
2289 | * @return bool | |
2290 | * @throws Exception | |
2291 | */ | |
276e3ec6 | 2292 | public function loadRelatedObjects(&$input, &$ids, $loadAll = FALSE) { |
f2b2a3ff TO |
2293 | if ($loadAll) { |
2294 | $ids = array_merge($this->getComponentDetails($this->id), $ids); | |
2295 | if (empty($ids['contact']) && isset($this->contact_id)) { | |
6a488035 TO |
2296 | $ids['contact'] = $this->contact_id; |
2297 | } | |
2298 | } | |
2299 | if (empty($this->_component)) { | |
f2b2a3ff | 2300 | if (!empty($ids['event'])) { |
6a488035 TO |
2301 | $this->_component = 'event'; |
2302 | } | |
2303 | else { | |
2304 | $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute')); | |
2305 | } | |
2306 | } | |
474ebab9 | 2307 | |
2b57dd9f | 2308 | // If the object is not fully populated then make sure it is - this is a more about legacy paths & cautious |
2309 | // refactoring than anything else, and has unit test coverage. | |
2310 | if (empty($this->financial_type_id)) { | |
2311 | $this->find(TRUE); | |
2312 | } | |
2313 | ||
474ebab9 | 2314 | $paymentProcessorID = CRM_Utils_Array::value('payment_processor_id', $input, CRM_Utils_Array::value( |
2315 | 'paymentProcessor', | |
2316 | $ids | |
2317 | )); | |
2318 | ||
2319 | if (!$paymentProcessorID && $this->contribution_page_id) { | |
2320 | $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', | |
2321 | $this->contribution_page_id, | |
2322 | 'payment_processor' | |
2323 | ); | |
ef6ae9af | 2324 | if ($paymentProcessorID) { |
2325 | $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromContributionPage; | |
2326 | } | |
474ebab9 | 2327 | } |
2328 | ||
2b57dd9f | 2329 | $ids['contributionType'] = $this->financial_type_id; |
2330 | $ids['financialType'] = $this->financial_type_id; | |
2331 | ||
2332 | $entities = array( | |
2333 | 'contact' => 'CRM_Contact_BAO_Contact', | |
2334 | 'contributionRecur' => 'CRM_Contribute_BAO_ContributionRecur', | |
2335 | 'contributionType' => 'CRM_Financial_BAO_FinancialType', | |
2336 | 'financialType' => 'CRM_Financial_BAO_FinancialType', | |
2337 | ); | |
2338 | foreach ($entities as $entity => $bao) { | |
2339 | if (!empty($ids[$entity])) { | |
2340 | $this->_relatedObjects[$entity] = new $bao(); | |
2341 | $this->_relatedObjects[$entity]->id = $ids[$entity]; | |
2342 | if (!$this->_relatedObjects[$entity]->find(TRUE)) { | |
2343 | throw new CRM_Core_Exception($entity . ' could not be loaded'); | |
2344 | } | |
474ebab9 | 2345 | } |
474ebab9 | 2346 | } |
2347 | ||
2b57dd9f | 2348 | if (!empty($ids['contributionRecur']) && !$paymentProcessorID) { |
2349 | $paymentProcessorID = $this->_relatedObjects['contributionRecur']->payment_processor_id; | |
6a488035 | 2350 | } |
6a488035 | 2351 | |
474ebab9 | 2352 | if (!empty($ids['pledge_payment'])) { |
2353 | foreach ($ids['pledge_payment'] as $key => $paymentID) { | |
2354 | if (empty($paymentID)) { | |
2355 | continue; | |
2356 | } | |
2357 | $payment = new CRM_Pledge_BAO_PledgePayment(); | |
2358 | $payment->id = $paymentID; | |
2359 | if (!$payment->find(TRUE)) { | |
2360 | throw new Exception("Could not find pledge payment record: " . $paymentID); | |
2361 | } | |
2362 | $this->_relatedObjects['pledge_payment'][] = $payment; | |
2363 | } | |
2364 | } | |
2365 | ||
4ae9c8ac | 2366 | $this->loadRelatedMembershipObjects($ids); |
aadcdd50 | 2367 | |
2368 | if ($this->_component != 'contribute') { | |
6a488035 TO |
2369 | // we are in event mode |
2370 | // make sure event exists and is valid | |
2371 | $event = new CRM_Event_BAO_Event(); | |
2372 | $event->id = $ids['event']; | |
2373 | if ($ids['event'] && | |
2374 | !$event->find(TRUE) | |
2375 | ) { | |
2376 | throw new Exception("Could not find event: " . $ids['event']); | |
2377 | } | |
2378 | ||
2379 | $this->_relatedObjects['event'] = &$event; | |
2380 | ||
2381 | $participant = new CRM_Event_BAO_Participant(); | |
2382 | $participant->id = $ids['participant']; | |
2383 | if ($ids['participant'] && | |
2384 | !$participant->find(TRUE) | |
2385 | ) { | |
2386 | throw new Exception("Could not find participant: " . $ids['participant']); | |
2387 | } | |
2388 | $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date); | |
2389 | ||
2390 | $this->_relatedObjects['participant'] = &$participant; | |
2391 | ||
474ebab9 | 2392 | // get the payment processor id from event - this is inaccurate see CRM-16923 |
2393 | // in future we should look at throwing an exception here rather than an dubious guess. | |
6a488035 TO |
2394 | if (!$paymentProcessorID) { |
2395 | $paymentProcessorID = $this->_relatedObjects['event']->payment_processor; | |
ef6ae9af | 2396 | if ($paymentProcessorID) { |
2397 | $intentionalEnotice = $CRM16923AnUnreliableMethodHasBeenUserToDeterminePaymentProcessorFromEvent; | |
2398 | } | |
6a488035 TO |
2399 | } |
2400 | } | |
2401 | ||
6a488035 TO |
2402 | if ($paymentProcessorID) { |
2403 | $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, | |
2404 | $this->is_test ? 'test' : 'live' | |
2405 | ); | |
2406 | $ids['paymentProcessor'] = $paymentProcessorID; | |
d6944518 | 2407 | $this->_relatedObjects['paymentProcessor'] = $paymentProcessor; |
6a488035 | 2408 | } |
5bfb071e | 2409 | return TRUE; |
6a488035 TO |
2410 | } |
2411 | ||
16b10e64 | 2412 | /** |
6a488035 TO |
2413 | * Create array of message information - ie. return html version, txt version, to field |
2414 | * | |
014c4014 TO |
2415 | * @param array $input |
2416 | * Incoming information. | |
16b10e64 | 2417 | * - is_recur - should this be treated as recurring (not sure why you wouldn't |
6a488035 TO |
2418 | * just check presence of recur object but maintaining legacy approach |
2419 | * to be careful) | |
014c4014 TO |
2420 | * @param array $ids |
2421 | * IDs of related objects. | |
2422 | * @param array $values | |
2423 | * Any values that may have already been compiled by calling process. | |
6a488035 | 2424 | * This is augmented by values 'gathered' by gatherMessageValues |
16b10e64 | 2425 | * @param bool $recur |
014c4014 TO |
2426 | * @param bool $returnMessageText |
2427 | * Distinguishes between whether to send message or return. | |
6a488035 TO |
2428 | * message text. We are working towards this function ALWAYS returning message text & calling |
2429 | * function doing emails / pdfs with it | |
16b10e64 | 2430 | * |
a6c01b45 CW |
2431 | * @return array |
2432 | * messages | |
186c9c17 EM |
2433 | * @throws Exception |
2434 | */ | |
00be9182 | 2435 | public function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) { |
4ff927bc | 2436 | $this->loadRelatedObjects($input, $ids); |
2437 | ||
6a488035 TO |
2438 | if (empty($this->_component)) { |
2439 | $this->_component = CRM_Utils_Array::value('component', $input); | |
2440 | } | |
2441 | ||
2442 | //not really sure what params might be passed in but lets merge em into values | |
2443 | $values = array_merge($this->_gatherMessageValues($input, $values, $ids), $values); | |
d9924163 E |
2444 | if (!empty($input['receipt_date'])) { |
2445 | $values['receipt_date'] = $input['receipt_date']; | |
2446 | } | |
2447 | ||
6a488035 TO |
2448 | $template = CRM_Core_Smarty::singleton(); |
2449 | $this->_assignMessageVariablesToTemplate($values, $input, $template, $recur, $returnMessageText); | |
2450 | //what does recur 'mean here - to do with payment processor return functionality but | |
2451 | // what is the importance | |
2452 | if ($recur && !empty($this->_relatedObjects['paymentProcessor'])) { | |
35cd38f5 | 2453 | $paymentObject = Civi\Payment\System::singleton()->getByProcessor($this->_relatedObjects['paymentProcessor']); |
6a488035 TO |
2454 | |
2455 | $entityID = $entity = NULL; | |
2456 | if (isset($ids['contribution'])) { | |
2457 | $entity = 'contribution'; | |
2458 | $entityID = $ids['contribution']; | |
2459 | } | |
dccb668e EM |
2460 | if (!empty($ids['membership'])) { |
2461 | //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 | |
2462 | // 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 | |
2463 | // line having loaded an array | |
2464 | $ids['membership'] = (array) $ids['membership']; | |
6a488035 | 2465 | $entity = 'membership'; |
dccb668e | 2466 | $entityID = $ids['membership'][0]; |
6a488035 TO |
2467 | } |
2468 | ||
3e473c0b | 2469 | $template->assign('cancelSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'cancel')); |
66df7769 | 2470 | $template->assign('updateSubscriptionBillingUrl', $paymentObject->subscriptionURL($entityID, $entity, 'billing')); |
2471 | $template->assign('updateSubscriptionUrl', $paymentObject->subscriptionURL($entityID, $entity, 'update')); | |
6a488035 TO |
2472 | |
2473 | if ($this->_relatedObjects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) { | |
2474 | //direct mode showing billing block, so use directIPN for temporary | |
2475 | $template->assign('contributeMode', 'directIPN'); | |
2476 | } | |
2477 | } | |
2478 | // todo remove strtolower - check consistency | |
2479 | if (strtolower($this->_component) == 'event') { | |
66df7769 | 2480 | $eventParams = array('id' => $this->_relatedObjects['participant']->event_id); |
2481 | $values['event'] = array(); | |
2482 | ||
2483 | CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); | |
2484 | ||
2485 | //get location details | |
2486 | $locationParams = array('entity_id' => $this->_relatedObjects['participant']->event_id, 'entity_table' => 'civicrm_event'); | |
2487 | $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); | |
2488 | ||
2489 | $ufJoinParams = array( | |
2490 | 'entity_table' => 'civicrm_event', | |
2491 | 'entity_id' => $ids['event'], | |
2492 | 'module' => 'CiviEvent', | |
2493 | ); | |
2494 | ||
2495 | list($custom_pre_id, | |
2496 | $custom_post_ids | |
2497 | ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); | |
2498 | ||
2499 | $values['custom_pre_id'] = $custom_pre_id; | |
2500 | $values['custom_post_id'] = $custom_post_ids; | |
ec5b3633 | 2501 | //for tasks 'Change Participant Status' and 'Update multiple Contributions' case |
66df7769 | 2502 | //and cases involving status updation through ipn |
2503 | // whatever that means! | |
95e5776c | 2504 | // total_amount appears to be the preferred input param & it is unclear why we support amount here |
2505 | // perhaps we should throw an e-notice if amount is set & force total_amount? | |
2506 | if (!empty($input['amount'])) { | |
2507 | $values['totalAmount'] = $input['amount']; | |
2508 | } | |
66df7769 | 2509 | |
2510 | if ($values['event']['is_email_confirm']) { | |
2511 | $values['is_email_receipt'] = 1; | |
2512 | } | |
b7bef093 | 2513 | |
2b65b515 | 2514 | if (!empty($ids['contribution'])) { |
2515 | $values['contributionId'] = $ids['contribution']; | |
2516 | } | |
b7bef093 | 2517 | |
6a488035 TO |
2518 | return CRM_Event_BAO_Event::sendMail($ids['contact'], $values, |
2519 | $this->_relatedObjects['participant']->id, $this->is_test, $returnMessageText | |
2520 | ); | |
2521 | } | |
2522 | else { | |
2523 | $values['contribution_id'] = $this->id; | |
a7488080 | 2524 | if (!empty($ids['related_contact'])) { |
6a488035 TO |
2525 | $values['related_contact'] = $ids['related_contact']; |
2526 | if (isset($ids['onbehalf_dupe_alert'])) { | |
2527 | $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert']; | |
2528 | } | |
2529 | $entityBlock = array( | |
2530 | 'contact_id' => $ids['contact'], | |
2531 | 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', | |
2532 | 'Home', 'id', 'name' | |
2533 | ), | |
2534 | ); | |
2535 | $address = CRM_Core_BAO_Address::getValues($entityBlock); | |
2536 | $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']); | |
2537 | } | |
2538 | $isTest = FALSE; | |
2539 | if ($this->is_test) { | |
2540 | $isTest = TRUE; | |
2541 | } | |
2542 | if (!empty($this->_relatedObjects['membership'])) { | |
2543 | foreach ($this->_relatedObjects['membership'] as $membership) { | |
2544 | if ($membership->id) { | |
85dea18b | 2545 | $values['isMembership'] = TRUE; |
858f7096 | 2546 | $values['membership_assign'] = TRUE; |
6a488035 TO |
2547 | |
2548 | // need to set the membership values here | |
6a488035 TO |
2549 | $template->assign('membership_name', |
2550 | CRM_Member_PseudoConstant::membershipType($membership->membership_type_id) | |
2551 | ); | |
2552 | $template->assign('mem_start_date', $membership->start_date); | |
2553 | $template->assign('mem_join_date', $membership->join_date); | |
2554 | $template->assign('mem_end_date', $membership->end_date); | |
2555 | $membership_status = CRM_Member_PseudoConstant::membershipStatus($membership->status_id, NULL, 'label'); | |
2556 | $template->assign('mem_status', $membership_status); | |
2557 | if ($membership_status == 'Pending' && $membership->is_pay_later == 1) { | |
c2358f41 | 2558 | $values['is_pay_later'] = 1; |
6a488035 TO |
2559 | } |
2560 | ||
6a488035 | 2561 | if ($recur && $paymentObject) { |
3e473c0b | 2562 | $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'cancel'); |
6a488035 TO |
2563 | $template->assign('cancelSubscriptionUrl', $url); |
2564 | $url = $paymentObject->subscriptionURL($membership->id, 'membership', 'billing'); | |
2565 | $template->assign('updateSubscriptionBillingUrl', $url); | |
2566 | $url = $paymentObject->subscriptionURL($entityID, $entity, 'update'); | |
2567 | $template->assign('updateSubscriptionUrl', $url); | |
2568 | } | |
2569 | ||
2570 | $result = CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); | |
2571 | ||
2572 | return $result; | |
2573 | // otherwise if its about sending emails, continue sending without return, as we | |
2574 | // don't want to exit the loop. | |
2575 | } | |
2576 | } | |
2577 | } | |
2578 | else { | |
2579 | return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText); | |
2580 | } | |
2581 | } | |
2582 | } | |
2583 | ||
16b10e64 | 2584 | /** |
6a488035 TO |
2585 | * Gather values for contribution mail - this function has been created |
2586 | * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function | |
2587 | * Values related to the contribution in question are gathered | |
2588 | * | |
014c4014 TO |
2589 | * @param array $input |
2590 | * Input into function (probably from payment processor). | |
16b10e64 | 2591 | * @param array $values |
014c4014 | 2592 | * @param array $ids |
16b10e64 | 2593 | * The set of ids related to the input. |
6a488035 | 2594 | * |
a6c01b45 | 2595 | * @return array |
186c9c17 | 2596 | */ |
00be9182 | 2597 | public function _gatherMessageValues($input, &$values, $ids = array()) { |
6a488035 TO |
2598 | // set display address of contributor |
2599 | if ($this->address_id) { | |
f2b2a3ff TO |
2600 | $addressParams = array('id' => $this->address_id); |
2601 | $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id'); | |
2602 | $addressDetails = array_values($addressDetails); | |
6a488035 | 2603 | } |
2b221bad TM |
2604 | // Else we assign the billing address of the contribution contact. |
2605 | else { | |
2606 | $addressParams = array('contact_id' => $this->contact_id, 'is_billing' => 1); | |
2a0df9d9 | 2607 | $addressDetails = (array) CRM_Core_BAO_Address::getValues($addressParams); |
2608 | $addressDetails = array_values($addressDetails); | |
2b221bad | 2609 | } |
2a0df9d9 | 2610 | |
2611 | if (!empty($addressDetails[0]['display'])) { | |
2612 | $values['address'] = $addressDetails[0]['display']; | |
2613 | } | |
2614 | ||
6a488035 | 2615 | if ($this->_component == 'contribute') { |
a49aa7dd TM |
2616 | //get soft contributions |
2617 | $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id, TRUE); | |
2618 | if (!empty($softContributions)) { | |
2619 | $values['softContributions'] = $softContributions['soft_credit']; | |
2620 | } | |
6a488035 | 2621 | if (isset($this->contribution_page_id)) { |
f99a6f98 | 2622 | $values = $this->addContributionPageValuesToValuesHeavyHandedly($values); |
6a488035 TO |
2623 | if ($this->contribution_page_id) { |
2624 | // CRM-8254 - override default currency if applicable | |
2625 | $config = CRM_Core_Config::singleton(); | |
2626 | $config->defaultCurrency = CRM_Utils_Array::value( | |
2627 | 'currency', | |
2628 | $values, | |
2629 | $config->defaultCurrency | |
2630 | ); | |
2631 | } | |
2632 | } | |
2633 | // no contribution page -probably back office | |
2634 | else { | |
2635 | // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id) | |
2636 | $values['is_email_receipt'] = 1; | |
2637 | $values['title'] = 'Contribution'; | |
2638 | } | |
2639 | // set lineItem for contribution | |
2640 | if ($this->id) { | |
270ff672 | 2641 | $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->id); |
2642 | if (!empty($lineItems)) { | |
2643 | $firstLineItem = reset($lineItems); | |
2644 | $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $firstLineItem['price_set_id'], 'return' => 'is_quick_config, id')); | |
2645 | $values['priceSetID'] = $priceSet['id']; | |
2646 | foreach ($lineItems as &$eachItem) { | |
7c063f32 | 2647 | if (isset($this->_relatedObjects['membership']) |
2648 | && is_array($this->_relatedObjects['membership']) | |
2649 | && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) { | |
6a488035 TO |
2650 | $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date); |
2651 | $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date); | |
2652 | $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date); | |
2653 | } | |
270ff672 | 2654 | // This is actually used in conjunction with is_quick_config in the template & we should deprecate it. |
2655 | // However, that does create upgrade pain so would be better to be phased in. | |
2656 | $values['useForMember'] = !$priceSet['is_quick_config']; | |
6a488035 | 2657 | } |
270ff672 | 2658 | $values['lineItem'][0] = $lineItems; |
f2b2a3ff | 2659 | } |
6a488035 TO |
2660 | } |
2661 | ||
2662 | $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds( | |
2663 | $this->id, | |
2664 | $this->contact_id | |
2665 | ); | |
2666 | // if this is onbehalf of contribution then set related contact | |
a7488080 | 2667 | if (!empty($relatedContact['individual_id'])) { |
6a488035 TO |
2668 | $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id']; |
2669 | } | |
2670 | } | |
2671 | else { | |
2672 | // event | |
2673 | $eventParams = array( | |
2674 | 'id' => $this->_relatedObjects['event']->id, | |
2675 | ); | |
2676 | $values['event'] = array(); | |
2677 | ||
2678 | CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); | |
7089d2d8 TM |
2679 | // add custom fields for event |
2680 | $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this->_relatedObjects['event'], $this->_relatedObjects['event']->id); | |
2681 | ||
2682 | $eventCustomGroup = array(); | |
2683 | foreach ($eventGroupTree as $key => $group) { | |
2684 | if ($key === 'info') { | |
2685 | continue; | |
2686 | } | |
2687 | ||
2688 | foreach ($group['fields'] as $k => $customField) { | |
2689 | $groupLabel = $group['title']; | |
2690 | if (!empty($customField['customValue'])) { | |
2691 | foreach ($customField['customValue'] as $customFieldValues) { | |
2692 | $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues); | |
2693 | } | |
2694 | } | |
2695 | } | |
2696 | } | |
2697 | $values['event']['customGroup'] = $eventCustomGroup; | |
2698 | ||
2699 | //get participant details | |
2700 | $participantParams = array( | |
2701 | 'id' => $this->_relatedObjects['participant']->id, | |
2702 | ); | |
2703 | ||
2704 | $values['participant'] = array(); | |
2705 | ||
2706 | CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds); | |
2707 | // add custom fields for event | |
2708 | $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this->_relatedObjects['participant'], $this->_relatedObjects['participant']->id); | |
2709 | $participantCustomGroup = array(); | |
2710 | foreach ($participantGroupTree as $key => $group) { | |
2711 | if ($key === 'info') { | |
2712 | continue; | |
2713 | } | |
2714 | ||
2715 | foreach ($group['fields'] as $k => $customField) { | |
2716 | $groupLabel = $group['title']; | |
2717 | if (!empty($customField['customValue'])) { | |
2718 | foreach ($customField['customValue'] as $customFieldValues) { | |
2719 | $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues); | |
2720 | } | |
2721 | } | |
2722 | } | |
2723 | } | |
2724 | $values['participant']['customGroup'] = $participantCustomGroup; | |
6a488035 TO |
2725 | |
2726 | //get location details | |
2727 | $locationParams = array( | |
2728 | 'entity_id' => $this->_relatedObjects['event']->id, | |
2729 | 'entity_table' => 'civicrm_event', | |
2730 | ); | |
2731 | $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); | |
2732 | ||
2733 | $ufJoinParams = array( | |
2734 | 'entity_table' => 'civicrm_event', | |
f2b2a3ff TO |
2735 | 'entity_id' => $ids['event'], |
2736 | 'module' => 'CiviEvent', | |
6a488035 TO |
2737 | ); |
2738 | ||
2739 | list($custom_pre_id, | |
f2b2a3ff TO |
2740 | $custom_post_ids |
2741 | ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); | |
6a488035 TO |
2742 | |
2743 | $values['custom_pre_id'] = $custom_pre_id; | |
2744 | $values['custom_post_id'] = $custom_post_ids; | |
2745 | ||
2746 | // set lineItem for event contribution | |
2747 | if ($this->id) { | |
2748 | $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id); | |
2749 | if (!empty($participantIds)) { | |
2750 | foreach ($participantIds as $pIDs) { | |
2751 | $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs); | |
2752 | if (!CRM_Utils_System::isNull($lineItem)) { | |
2753 | $values['lineItem'][] = $lineItem; | |
2754 | } | |
2755 | } | |
2756 | } | |
2757 | } | |
2758 | } | |
2759 | ||
7089d2d8 TM |
2760 | $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $this->id); |
2761 | ||
2762 | $customGroup = array(); | |
2763 | foreach ($groupTree as $key => $group) { | |
2764 | if ($key === 'info') { | |
2765 | continue; | |
2766 | } | |
2767 | ||
2768 | foreach ($group['fields'] as $k => $customField) { | |
2769 | $groupLabel = $group['title']; | |
2770 | if (!empty($customField['customValue'])) { | |
2771 | foreach ($customField['customValue'] as $customFieldValues) { | |
2772 | $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues); | |
2773 | } | |
2774 | } | |
2775 | } | |
2776 | } | |
2777 | $values['customGroup'] = $customGroup; | |
2778 | ||
6a488035 TO |
2779 | return $values; |
2780 | } | |
2781 | ||
2782 | /** | |
9daadfce | 2783 | * Assign message variables to template but try to break the habit. |
2784 | * | |
2785 | * In order to get away from leaky variables it is better to ensure variables are set in values and assign them | |
2786 | * from the send function. Otherwise smarty variables can leak if this is called more than once - e.g. processing | |
2787 | * multiple recurring payments for processors like IATS that use tokens. | |
2788 | * | |
6a488035 TO |
2789 | * Apply variables for message to smarty template - this function is part of analysing what is in the huge |
2790 | * function & breaking it down into manageable chunks. Eventually it will be refactored into something else | |
9daadfce | 2791 | * Note we send directly from this function in some cases because it is only partly refactored. |
2792 | * | |
2793 | * Don't call this function directly as the signature will change. | |
02af3683 EM |
2794 | * |
2795 | * @param $values | |
2796 | * @param $input | |
5a4f6742 | 2797 | * @param CRM_Core_SMARTY $template |
02af3683 EM |
2798 | * @param bool $recur |
2799 | * @param bool $returnMessageText | |
2800 | * | |
2801 | * @return mixed | |
6a488035 | 2802 | */ |
f2b2a3ff | 2803 | public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE) { |
6a488035 TO |
2804 | $template->assign('first_name', $this->_relatedObjects['contact']->first_name); |
2805 | $template->assign('last_name', $this->_relatedObjects['contact']->last_name); | |
2806 | $template->assign('displayName', $this->_relatedObjects['contact']->display_name); | |
367b5943 | 2807 | |
2808 | // For some unit tests contribution cannot contain paymentProcessor information | |
2809 | $billingMode = empty($this->_relatedObjects['paymentProcessor']) ? CRM_Core_Payment::BILLING_MODE_NOTIFY : $this->_relatedObjects['paymentProcessor']['billing_mode']; | |
2810 | $template->assign('contributeMode', CRM_Utils_Array::value($billingMode, CRM_Core_SelectValues::contributeMode())); | |
2811 | ||
02af3683 | 2812 | //assign honor information to receipt message |
8af73472 | 2813 | $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id); |
6a488035 | 2814 | |
8af73472 | 2815 | if (isset($softRecord['soft_credit'])) { |
7305d3e6 | 2816 | //if id of contribution page is present |
2817 | if (!empty($values['id'])) { | |
2818 | $values['honor'] = array( | |
2819 | 'honor_profile_values' => array(), | |
2820 | 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'), | |
2821 | 'honor_id' => $softRecord['soft_credit'][1]['contact_id'], | |
2822 | ); | |
6a488035 | 2823 | |
f2b2a3ff | 2824 | $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']); |
7305d3e6 | 2825 | $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id')); |
2826 | } | |
2827 | else { | |
2828 | //offline contribution | |
2829 | $softCreditTypes = $softCredits = array(); | |
2830 | foreach ($softRecord['soft_credit'] as $key => $softCredit) { | |
2831 | $softCreditTypes[$key] = $softCredit['soft_credit_type_label']; | |
2832 | $softCredits[$key] = array( | |
2833 | 'Name' => $softCredit['contact_name'], | |
21dfd5f5 | 2834 | 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']), |
7305d3e6 | 2835 | ); |
2836 | } | |
2837 | $template->assign('softCreditTypes', $softCreditTypes); | |
2838 | $template->assign('softCredits', $softCredits); | |
2839 | } | |
6a488035 TO |
2840 | } |
2841 | ||
2842 | $dao = new CRM_Contribute_DAO_ContributionProduct(); | |
2843 | $dao->contribution_id = $this->id; | |
2844 | if ($dao->find(TRUE)) { | |
2845 | $premiumId = $dao->product_id; | |
2846 | $template->assign('option', $dao->product_option); | |
2847 | ||
2848 | $productDAO = new CRM_Contribute_DAO_Product(); | |
2849 | $productDAO->id = $premiumId; | |
2850 | $productDAO->find(TRUE); | |
2851 | $template->assign('selectPremium', TRUE); | |
2852 | $template->assign('product_name', $productDAO->name); | |
2853 | $template->assign('price', $productDAO->price); | |
2854 | $template->assign('sku', $productDAO->sku); | |
2855 | } | |
f2b2a3ff | 2856 | $template->assign('title', CRM_Utils_Array::value('title', $values)); |
858f7096 | 2857 | $values['amount'] = CRM_Utils_Array::value('total_amount', $input, (CRM_Utils_Array::value('amount', $input)), NULL); |
2858 | if (!$values['amount'] && isset($this->total_amount)) { | |
2859 | $values['amount'] = $this->total_amount; | |
6a488035 | 2860 | } |
858f7096 | 2861 | |
6a488035 TO |
2862 | // add the new contribution values |
2863 | if (strtolower($this->_component) == 'contribute') { | |
2864 | //PCP Info | |
2865 | $softDAO = new CRM_Contribute_DAO_ContributionSoft(); | |
2866 | $softDAO->contribution_id = $this->id; | |
2867 | if ($softDAO->find(TRUE)) { | |
2868 | $template->assign('pcpBlock', TRUE); | |
2869 | $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll); | |
2870 | $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname); | |
2871 | $template->assign('pcp_personal_note', $softDAO->pcp_personal_note); | |
2872 | ||
2873 | //assign the pcp page title for email subject | |
2874 | $pcpDAO = new CRM_PCP_DAO_PCP(); | |
2875 | $pcpDAO->id = $softDAO->pcp_id; | |
2876 | if ($pcpDAO->find(TRUE)) { | |
2877 | $template->assign('title', $pcpDAO->title); | |
2878 | } | |
2879 | } | |
2880 | } | |
2881 | ||
2882 | if ($this->financial_type_id) { | |
2883 | $values['financial_type_id'] = $this->financial_type_id; | |
2884 | } | |
2885 | ||
6a488035 TO |
2886 | $template->assign('trxn_id', $this->trxn_id); |
2887 | $template->assign('receive_date', | |
5bab7daf | 2888 | CRM_Utils_Date::processDate($this->receive_date) |
6a488035 | 2889 | ); |
76e8d9c4 | 2890 | $values['receipt_date'] = (empty($this->receipt_date) ? NULL : $this->receipt_date); |
6a488035 TO |
2891 | $template->assign('action', $this->is_test ? 1024 : 1); |
2892 | $template->assign('receipt_text', | |
2893 | CRM_Utils_Array::value('receipt_text', | |
2894 | $values | |
2895 | ) | |
2896 | ); | |
2897 | $template->assign('is_monetary', 1); | |
2898 | $template->assign('is_recur', (bool) $recur); | |
2899 | $template->assign('currency', $this->currency); | |
2900 | $template->assign('address', CRM_Utils_Address::format($input)); | |
7089d2d8 TM |
2901 | if (!empty($values['customGroup'])) { |
2902 | $template->assign('customGroup', $values['customGroup']); | |
2903 | } | |
a49aa7dd TM |
2904 | if (!empty($values['softContributions'])) { |
2905 | $template->assign('softContributions', $values['softContributions']); | |
2906 | } | |
6a488035 TO |
2907 | if ($this->_component == 'event') { |
2908 | $template->assign('title', $values['event']['title']); | |
2909 | $participantRoles = CRM_Event_PseudoConstant::participantRole(); | |
2910 | $viewRoles = array(); | |
2911 | foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) { | |
2912 | $viewRoles[] = $participantRoles[$v]; | |
2913 | } | |
2914 | $values['event']['participant_role'] = implode(', ', $viewRoles); | |
2915 | $template->assign('event', $values['event']); | |
7089d2d8 | 2916 | $template->assign('participant', $values['participant']); |
6a488035 TO |
2917 | $template->assign('location', $values['location']); |
2918 | $template->assign('customPre', $values['custom_pre_id']); | |
2919 | $template->assign('customPost', $values['custom_post_id']); | |
2920 | ||
2921 | $isTest = FALSE; | |
2922 | if ($this->_relatedObjects['participant']->is_test) { | |
2923 | $isTest = TRUE; | |
2924 | } | |
2925 | ||
2926 | $values['params'] = array(); | |
2927 | //to get email of primary participant. | |
2928 | $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id'); | |
f2b2a3ff TO |
2929 | $primaryAmount[] = array( |
2930 | 'label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, | |
21dfd5f5 | 2931 | 'amount' => $this->_relatedObjects['participant']->fee_amount, |
f2b2a3ff | 2932 | ); |
6a488035 TO |
2933 | //build an array of cId/pId of participants |
2934 | $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE); | |
2935 | unset($additionalIDs[$this->_relatedObjects['participant']->id]); | |
2936 | //send receipt to additional participant if exists | |
2937 | if (count($additionalIDs)) { | |
2938 | $template->assign('isPrimary', 0); | |
2939 | $template->assign('customProfile', NULL); | |
2940 | //set additionalParticipant true | |
2941 | $values['params']['additionalParticipant'] = TRUE; | |
2942 | foreach ($additionalIDs as $pId => $cId) { | |
2943 | $amount = array(); | |
2944 | //to change the status pending to completed | |
2945 | $additional = new CRM_Event_DAO_Participant(); | |
2946 | $additional->id = $pId; | |
2947 | $additional->contact_id = $cId; | |
2948 | $additional->find(TRUE); | |
2949 | $additional->register_date = $this->_relatedObjects['participant']->register_date; | |
2950 | $additional->status_id = 1; | |
2951 | $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id'); | |
2952 | //if additional participant dont have email | |
2953 | //use display name. | |
2954 | if (!$additionalParticipantInfo) { | |
2955 | $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id); | |
2956 | } | |
2957 | $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount); | |
f2b2a3ff TO |
2958 | $primaryAmount[] = array( |
2959 | 'label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, | |
21dfd5f5 | 2960 | 'amount' => $additional->fee_amount, |
f2b2a3ff | 2961 | ); |
6a488035 TO |
2962 | $additional->save(); |
2963 | $additional->free(); | |
2964 | $template->assign('amount', $amount); | |
2965 | CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText); | |
2966 | } | |
2967 | } | |
2968 | ||
2969 | //build an array of custom profile and assigning it to template | |
2970 | $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest); | |
2971 | ||
2972 | if (count($customProfile)) { | |
2973 | $template->assign('customProfile', $customProfile); | |
2974 | } | |
2975 | ||
2976 | // for primary contact | |
2977 | $values['params']['additionalParticipant'] = FALSE; | |
2978 | $template->assign('isPrimary', 1); | |
2979 | $template->assign('amount', $primaryAmount); | |
2980 | $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date)); | |
2981 | if ($this->payment_instrument_id) { | |
2982 | $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); | |
2983 | $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]); | |
2984 | } | |
2985 | // carry paylater, since we did not created billing, | |
2986 | // so need to pull email from primary location, CRM-4395 | |
2987 | $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later; | |
2988 | } | |
2989 | return $template; | |
2990 | } | |
2991 | ||
2992 | /** | |
100fef9d | 2993 | * Check whether payment processor supports |
6a488035 TO |
2994 | * cancellation of contribution subscription |
2995 | * | |
014c4014 TO |
2996 | * @param int $contributionId |
2997 | * Contribution id. | |
6a488035 | 2998 | * |
77b97be7 EM |
2999 | * @param bool $isNotCancelled |
3000 | * | |
a130e045 | 3001 | * @return bool |
6a488035 | 3002 | */ |
00be9182 | 3003 | public static function isCancelSubscriptionSupported($contributionId, $isNotCancelled = TRUE) { |
6a488035 TO |
3004 | $cacheKeyString = "$contributionId"; |
3005 | $cacheKeyString .= $isNotCancelled ? '_1' : '_0'; | |
3006 | ||
3007 | static $supportsCancel = array(); | |
3008 | ||
3009 | if (!array_key_exists($cacheKeyString, $supportsCancel)) { | |
3010 | $supportsCancel[$cacheKeyString] = FALSE; | |
3011 | $isCancelled = FALSE; | |
3012 | ||
3013 | if ($isNotCancelled) { | |
3014 | $isCancelled = self::isSubscriptionCancelled($contributionId); | |
3015 | } | |
3016 | ||
3017 | $paymentObject = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($contributionId, 'contribute', 'obj'); | |
3018 | if (!empty($paymentObject)) { | |
1524a007 | 3019 | $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled; |
6a488035 TO |
3020 | } |
3021 | } | |
3022 | return $supportsCancel[$cacheKeyString]; | |
3023 | } | |
3024 | ||
3025 | /** | |
fe482240 | 3026 | * Check whether subscription is already cancelled. |
6a488035 | 3027 | * |
014c4014 TO |
3028 | * @param int $contributionId |
3029 | * Contribution id. | |
6a488035 | 3030 | * |
a6c01b45 CW |
3031 | * @return string |
3032 | * contribution status | |
6a488035 | 3033 | */ |
00be9182 | 3034 | public static function isSubscriptionCancelled($contributionId) { |
6a488035 TO |
3035 | $sql = " |
3036 | SELECT cr.contribution_status_id | |
3037 | FROM civicrm_contribution_recur cr | |
3038 | LEFT JOIN civicrm_contribution con ON ( cr.id = con.contribution_recur_id ) | |
3039 | WHERE con.id = %1 LIMIT 1"; | |
f2b2a3ff | 3040 | $params = array(1 => array($contributionId, 'Integer')); |
6a488035 | 3041 | $statusId = CRM_Core_DAO::singleValueQuery($sql, $params); |
f2b2a3ff | 3042 | $status = CRM_Contribute_PseudoConstant::contributionStatus($statusId); |
6a488035 TO |
3043 | if ($status == 'Cancelled') { |
3044 | return TRUE; | |
3045 | } | |
3046 | return FALSE; | |
3047 | } | |
3048 | ||
3049 | /** | |
fe482240 | 3050 | * Create all financial accounts entry. |
6a488035 | 3051 | * |
014c4014 TO |
3052 | * @param array $params |
3053 | * Contribution object, line item array and params for trxn. | |
6a488035 | 3054 | * |
6a488035 | 3055 | * |
02af3683 | 3056 | * @param array $financialTrxnValues |
77b97be7 EM |
3057 | * |
3058 | * @return null|object | |
6a488035 | 3059 | */ |
00be9182 | 3060 | public static function recordFinancialAccounts(&$params, $financialTrxnValues = NULL) { |
cb579c66 | 3061 | $skipRecords = $update = $return = $isRelatedId = FALSE; |
02af3683 | 3062 | |
d37ade2e | 3063 | $additionalParticipantId = array(); |
6a488035 | 3064 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
10fd773f | 3065 | $contributionStatus = empty($params['contribution_status_id']) ? NULL : $contributionStatuses[$params['contribution_status_id']]; |
6a488035 TO |
3066 | |
3067 | if (CRM_Utils_Array::value('contribution_mode', $params) == 'participant') { | |
3068 | $entityId = $params['participant_id']; | |
3069 | $entityTable = 'civicrm_participant'; | |
d37ade2e | 3070 | $additionalParticipantId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($entityId); |
6a488035 | 3071 | } |
8aa7457a EM |
3072 | elseif (!empty($params['membership_id'])) { |
3073 | //so far $params['membership_id'] should only be set coming in from membershipBAO::create so the situation where multiple memberships | |
3074 | // are created off one contribution should be handled elsewhere | |
3075 | $entityId = $params['membership_id']; | |
3076 | $entityTable = 'civicrm_membership'; | |
3077 | } | |
6a488035 TO |
3078 | else { |
3079 | $entityId = $params['contribution']->id; | |
3080 | $entityTable = 'civicrm_contribution'; | |
3081 | } | |
4d34aefa | 3082 | |
cb579c66 PN |
3083 | if (CRM_Utils_Array::value('contribution_mode', $params) == 'membership') { |
3084 | $isRelatedId = TRUE; | |
3085 | } | |
85dea18b | 3086 | |
464bb009 | 3087 | $entityID[] = $entityId; |
d37ade2e | 3088 | if (!empty($additionalParticipantId)) { |
3089 | $entityID += $additionalParticipantId; | |
464bb009 | 3090 | } |
4d34aefa | 3091 | // prevContribution appears to mean - original contribution object- ie copy of contribution from before the update started that is being updated |
a7488080 | 3092 | if (empty($params['prevContribution'])) { |
6a488035 TO |
3093 | $entityID = NULL; |
3094 | } | |
e005ab6b PN |
3095 | else { |
3096 | $update = TRUE; | |
3097 | } | |
4d34aefa | 3098 | |
f8325309 PJ |
3099 | $statusId = $params['contribution']->contribution_status_id; |
3100 | // CRM-13964 partial payment | |
4e92d4f4 | 3101 | if ($contributionStatus == 'Partially paid' |
f2b2a3ff TO |
3102 | && !empty($params['partial_payment_total']) && !empty($params['partial_amount_pay']) |
3103 | ) { | |
ede1935f PJ |
3104 | $partialAmtPay = $params['partial_amount_pay']; |
3105 | $partialAmtTotal = $params['partial_payment_total']; | |
3106 | ||
0f602e3f PJ |
3107 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
3108 | $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); | |
f8325309 | 3109 | $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); |
ede1935f | 3110 | $params['total_amount'] = $partialAmtPay; |
0f602e3f | 3111 | |
ede1935f | 3112 | $balanceTrxnInfo = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($params['contribution']->id, $params['financial_type_id']); |
0f602e3f | 3113 | if (empty($balanceTrxnInfo['trxn_id'])) { |
ede1935f PJ |
3114 | // create new balance transaction record |
3115 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); | |
3116 | $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); | |
3117 | ||
0f602e3f | 3118 | $balanceTrxnParams['total_amount'] = $partialAmtTotal; |
ede1935f PJ |
3119 | $balanceTrxnParams['to_financial_account_id'] = $toFinancialAccount; |
3120 | $balanceTrxnParams['contribution_id'] = $params['contribution']->id; | |
2d8ae159 | 3121 | $balanceTrxnParams['trxn_date'] = !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'); |
ede1935f PJ |
3122 | $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); |
3123 | $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('net_amount', $params); | |
3124 | $balanceTrxnParams['currency'] = $params['contribution']->currency; | |
3125 | $balanceTrxnParams['trxn_id'] = $params['contribution']->trxn_id; | |
3126 | $balanceTrxnParams['status_id'] = $statusId; | |
3127 | $balanceTrxnParams['payment_instrument_id'] = $params['contribution']->payment_instrument_id; | |
3128 | $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params); | |
a246714d PN |
3129 | if (!empty($balanceTrxnParams['from_financial_account_id']) && |
3130 | ($statusId == array_search('Completed', $contributionStatuses) || $statusId == array_search('Partially paid', $contributionStatuses)) | |
3131 | ) { | |
3132 | $balanceTrxnParams['is_payment'] = 1; | |
3133 | } | |
a7488080 | 3134 | if (!empty($params['payment_processor'])) { |
ede1935f PJ |
3135 | $balanceTrxnParams['payment_processor_id'] = $params['payment_processor']; |
3136 | } | |
14b74ca6 | 3137 | $financialTxn = CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams); |
ede1935f | 3138 | } |
f8325309 PJ |
3139 | } |
3140 | ||
6a488035 | 3141 | // build line item array if its not set in $params |
a7488080 | 3142 | if (empty($params['line_item']) || $additionalParticipantId) { |
cb579c66 | 3143 | CRM_Price_BAO_LineItem::getLineItemArray($params, $entityID, str_replace('civicrm_', '', $entityTable), $isRelatedId); |
6a488035 TO |
3144 | } |
3145 | ||
4e92d4f4 | 3146 | if ($contributionStatus != 'Failed' && |
3147 | !($contributionStatus == 'Pending' && !$params['contribution']->is_pay_later) | |
f2b2a3ff | 3148 | ) { |
6a488035 | 3149 | $skipRecords = TRUE; |
f2b2a3ff | 3150 | $pendingStatus = array( |
4e92d4f4 | 3151 | 'Pending', |
3152 | 'In Progress', | |
f2b2a3ff | 3153 | ); |
4e92d4f4 | 3154 | if (in_array($contributionStatus, $pendingStatus)) { |
bf2cf926 | 3155 | $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship( |
3156 | $params['financial_type_id'], | |
3157 | 'Accounts Receivable Account is' | |
3158 | ); | |
6a488035 | 3159 | } |
a7488080 | 3160 | elseif (!empty($params['payment_processor'])) { |
6a488035 | 3161 | $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($params['payment_processor'], 'civicrm_payment_processor', 'financial_account_id'); |
bf722049 | 3162 | $params['payment_instrument_id'] = civicrm_api3('PaymentProcessor', 'getvalue', array( |
3163 | 'id' => $params['payment_processor'], | |
3164 | 'return' => 'payment_instrument_id', | |
3165 | )); | |
6a488035 | 3166 | } |
a7488080 | 3167 | elseif (!empty($params['payment_instrument_id'])) { |
6a488035 TO |
3168 | $params['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($params['payment_instrument_id']); |
3169 | } | |
3170 | else { | |
ac7514c2 PN |
3171 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); |
3172 | $queryParams = array(1 => array($relationTypeId, 'Integer')); | |
3173 | $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 |
3174 | } |
3175 | ||
3176 | $totalAmount = CRM_Utils_Array::value('total_amount', $params); | |
8cc574cf | 3177 | if (!isset($totalAmount) && !empty($params['prevContribution'])) { |
6a488035 TO |
3178 | $totalAmount = $params['total_amount'] = $params['prevContribution']->total_amount; |
3179 | } | |
3180 | //build financial transaction params | |
3181 | $trxnParams = array( | |
3182 | 'contribution_id' => $params['contribution']->id, | |
3183 | 'to_financial_account_id' => $params['to_financial_account_id'], | |
2d8ae159 | 3184 | 'trxn_date' => !empty($params['contribution']->receive_date) ? $params['contribution']->receive_date : date('YmdHis'), |
6a488035 TO |
3185 | 'total_amount' => $totalAmount, |
3186 | 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params), | |
60a2aeee | 3187 | 'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount), |
6a488035 TO |
3188 | 'currency' => $params['contribution']->currency, |
3189 | 'trxn_id' => $params['contribution']->trxn_id, | |
f8325309 | 3190 | 'status_id' => $statusId, |
bf722049 | 3191 | 'payment_instrument_id' => CRM_Utils_Array::value('payment_instrument_id', $params, $params['contribution']->payment_instrument_id), |
6a488035 TO |
3192 | 'check_number' => CRM_Utils_Array::value('check_number', $params), |
3193 | ); | |
8a0c74ae | 3194 | if ($contributionStatus == 'Refunded' || $contributionStatus == 'Chargeback' || $contributionStatus == 'Cancelled') { |
10fd773f | 3195 | $trxnParams['trxn_date'] = !empty($params['contribution']->cancel_date) ? $params['contribution']->cancel_date : date('YmdHis'); |
797d4c52 | 3196 | if (isset($params['refund_trxn_id'])) { |
3197 | // CRM-17751 allow a separate trxn_id for the refund to be passed in via api & form. | |
3198 | $trxnParams['trxn_id'] = $params['refund_trxn_id']; | |
3199 | } | |
10fd773f | 3200 | } |
a246714d | 3201 | //CRM-16259, set is_payment flag for non pending status |
0170d873 | 3202 | if (!in_array($contributionStatus, $pendingStatus)) { |
a246714d PN |
3203 | $trxnParams['is_payment'] = 1; |
3204 | } | |
a7488080 | 3205 | if (!empty($params['payment_processor'])) { |
8ef12e64 | 3206 | $trxnParams['payment_processor_id'] = $params['payment_processor']; |
6a488035 | 3207 | } |
0f602e3f PJ |
3208 | |
3209 | if (isset($fromFinancialAccountId)) { | |
3210 | $trxnParams['from_financial_account_id'] = $fromFinancialAccountId; | |
3211 | } | |
3212 | ||
3213 | // consider external values passed for recording transaction entry | |
02af3683 EM |
3214 | if (!empty($financialTrxnValues)) { |
3215 | $trxnParams = array_merge($trxnParams, $financialTrxnValues); | |
0f602e3f PJ |
3216 | } |
3217 | ||
6a488035 TO |
3218 | $params['trxnParams'] = $trxnParams; |
3219 | ||
a7488080 | 3220 | if (!empty($params['prevContribution'])) { |
99cdd94d | 3221 | $updated = FALSE; |
404f77c9 PN |
3222 | $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $params['prevContribution']->total_amount; |
3223 | $params['trxnParams']['fee_amount'] = $params['prevContribution']->fee_amount; | |
3224 | $params['trxnParams']['net_amount'] = $params['prevContribution']->net_amount; | |
797d4c52 | 3225 | if (!isset($params['trxnParams']['trxn_id'])) { |
3226 | // Actually I have no idea why we are overwriting any values from the previous contribution. | |
3227 | // (filling makes sense to me). However, only protecting this value as I really really know we | |
3228 | // don't want this one overwritten. | |
3229 | // CRM-17751. | |
3230 | $params['trxnParams']['trxn_id'] = $params['prevContribution']->trxn_id; | |
3231 | } | |
404f77c9 | 3232 | $params['trxnParams']['status_id'] = $params['prevContribution']->contribution_status_id; |
48ea0708 | 3233 | |
182228d5 | 3234 | if (!(($params['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses) |
f2b2a3ff TO |
3235 | || $params['prevContribution']->contribution_status_id == array_search('In Progress', $contributionStatuses)) |
3236 | && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses)) | |
3237 | ) { | |
182228d5 PN |
3238 | $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id; |
3239 | $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; | |
3240 | } | |
85dea18b | 3241 | |
404f77c9 | 3242 | //if financial type is changed |
a7488080 | 3243 | if (!empty($params['financial_type_id']) && |
f2b2a3ff TO |
3244 | $params['contribution']->financial_type_id != $params['prevContribution']->financial_type_id |
3245 | ) { | |
8cf6bd83 PN |
3246 | $accountRelationship = 'Income Account is'; |
3247 | if (!empty($params['revenue_recognition_date']) || $params['prevContribution']->revenue_recognition_date) { | |
3248 | $accountRelationship = 'Deferred Revenue Account is'; | |
3249 | } | |
3250 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '$accountRelationship' ")); | |
3251 | $oldFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $relationTypeId); | |
3252 | $newFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['financial_type_id'], $relationTypeId); | |
404f77c9 PN |
3253 | if ($oldFinancialAccount != $newFinancialAccount) { |
3254 | $params['total_amount'] = 0; | |
b81ee58c | 3255 | if (in_array($params['contribution']->contribution_status_id, $pendingStatus)) { |
404f77c9 PN |
3256 | $params['trxnParams']['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType( |
3257 | $params['prevContribution']->financial_type_id, $relationTypeId); | |
3258 | } | |
3259 | else { | |
3260 | $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC'); | |
a7488080 | 3261 | if (!empty($lastFinancialTrxnId['financialTrxnId'])) { |
404f77c9 PN |
3262 | $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id'); |
3263 | } | |
3264 | } | |
3265 | self::updateFinancialAccounts($params, 'changeFinancialType'); | |
3266 | /* $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; */ | |
3267 | $params['financial_account_id'] = $newFinancialAccount; | |
8cf6bd83 | 3268 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $trxnParams['total_amount']; |
404f77c9 PN |
3269 | self::updateFinancialAccounts($params); |
3270 | $params['trxnParams']['to_financial_account_id'] = $trxnParams['to_financial_account_id']; | |
99cdd94d | 3271 | $updated = TRUE; |
8cf6bd83 | 3272 | $params['deferred_financial_account_id'] = $newFinancialAccount; |
404f77c9 | 3273 | } |
6a488035 | 3274 | } |
48ea0708 | 3275 | |
6a488035 | 3276 | //Update contribution status |
404f77c9 | 3277 | $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id; |
797d4c52 | 3278 | if (!isset($params['refund_trxn_id'])) { |
3279 | // CRM-17751 This has previously been deliberately set. No explanation as to why one variant | |
3280 | // gets preference over another so I am only 'protecting' a very specific tested flow | |
3281 | // and letting natural justice take care of the rest. | |
3282 | $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; | |
3283 | } | |
a7488080 | 3284 | if (!empty($params['contribution_status_id']) && |
f2b2a3ff TO |
3285 | $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id |
3286 | ) { | |
6a488035 TO |
3287 | //Update Financial Records |
3288 | self::updateFinancialAccounts($params, 'changedStatus'); | |
99cdd94d | 3289 | $updated = TRUE; |
6a488035 TO |
3290 | } |
3291 | ||
3292 | // change Payment Instrument for a Completed contribution | |
3293 | // first handle special case when contribution is changed from Pending to Completed status when initial payment | |
3294 | // instrument is null and now new payment instrument is added along with the payment | |
404f77c9 PN |
3295 | $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id; |
3296 | $params['trxnParams']['check_number'] = CRM_Utils_Array::value('check_number', $params); | |
6a488035 | 3297 | if (array_key_exists('payment_instrument_id', $params)) { |
f2b2a3ff | 3298 | $params['trxnParams']['total_amount'] = -$trxnParams['total_amount']; |
6a488035 | 3299 | if (CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id) && |
f2b2a3ff TO |
3300 | !CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) |
3301 | ) { | |
6a488035 TO |
3302 | //check if status is changed from Pending to Completed |
3303 | // do not update payment instrument changes for Pending to Completed | |
3304 | if (!($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatuses) && | |
f2b2a3ff TO |
3305 | in_array($params['prevContribution']->contribution_status_id, $pendingStatus)) |
3306 | ) { | |
6a488035 TO |
3307 | // for all other statuses create new financial records |
3308 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); | |
d9814f68 PN |
3309 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
3310 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); | |
99cdd94d | 3311 | $updated = TRUE; |
6a488035 TO |
3312 | } |
3313 | } | |
4c9b6178 | 3314 | elseif ((!CRM_Utils_System::isNull($params['contribution']->payment_instrument_id) || |
f2b2a3ff TO |
3315 | !CRM_Utils_System::isNull($params['prevContribution']->payment_instrument_id)) && |
3316 | $params['contribution']->payment_instrument_id != $params['prevContribution']->payment_instrument_id | |
3317 | ) { | |
6a488035 TO |
3318 | // for any other payment instrument changes create new financial records |
3319 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); | |
d9814f68 PN |
3320 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; |
3321 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); | |
99cdd94d | 3322 | $updated = TRUE; |
6a488035 | 3323 | } |
4c9b6178 | 3324 | elseif (!CRM_Utils_System::isNull($params['contribution']->check_number) && |
f2b2a3ff TO |
3325 | $params['contribution']->check_number != $params['prevContribution']->check_number |
3326 | ) { | |
6a488035 TO |
3327 | // another special case when check number is changed, create new financial records |
3328 | // create financial trxn with negative amount | |
6a488035 TO |
3329 | $params['trxnParams']['check_number'] = $params['prevContribution']->check_number; |
3330 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); | |
3331 | // create financial trxn with positive amount | |
3332 | $params['trxnParams']['check_number'] = $params['contribution']->check_number; | |
3333 | $params['total_amount'] = $params['trxnParams']['total_amount'] = $trxnParams['total_amount']; | |
3334 | self::updateFinancialAccounts($params, 'changePaymentInstrument'); | |
99cdd94d | 3335 | $updated = TRUE; |
6a488035 TO |
3336 | } |
3337 | } | |
48ea0708 | 3338 | |
404f77c9 PN |
3339 | //if Change contribution amount |
3340 | $params['trxnParams']['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); | |
3341 | $params['trxnParams']['net_amount'] = CRM_Utils_Array::value('net_amount', $params); | |
d9814f68 | 3342 | $params['trxnParams']['total_amount'] = $trxnParams['total_amount'] = $params['total_amount'] = $totalAmount; |
404f77c9 PN |
3343 | $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id; |
3344 | if (isset($totalAmount) && | |
f2b2a3ff TO |
3345 | $totalAmount != $params['prevContribution']->total_amount |
3346 | ) { | |
404f77c9 PN |
3347 | //Update Financial Records |
3348 | $params['trxnParams']['from_financial_account_id'] = NULL; | |
404f77c9 | 3349 | self::updateFinancialAccounts($params, 'changedAmount'); |
99cdd94d | 3350 | $updated = TRUE; |
3351 | } | |
3352 | ||
3353 | if (!$updated) { | |
3354 | // Looks like we might have a data correction update. | |
3355 | // This would be a case where a transaction id has been entered but it is incorrect & | |
3356 | // the person goes back in & fixes it, as opposed to a new transaction. | |
3357 | // Currently the UI doesn't support multiple refunds against a single transaction & we are only supporting | |
3358 | // the data fix scenario. | |
3359 | // CRM-17751. | |
3360 | if (isset($params['refund_trxn_id'])) { | |
3361 | $refundIDs = CRM_Core_BAO_FinancialTrxn::getRefundTransactionIDs($params['id']); | |
48714ae7 | 3362 | if (!empty($refundIDs['financialTrxnId']) && $refundIDs['trxn_id'] != $params['refund_trxn_id']) { |
99cdd94d | 3363 | civicrm_api3('FinancialTrxn', 'create', array('id' => $refundIDs['financialTrxnId'], 'trxn_id' => $params['refund_trxn_id'])); |
3364 | } | |
3365 | } | |
6a488035 | 3366 | } |
6a488035 TO |
3367 | } |
3368 | ||
3369 | if (!$update) { | |
1c19e0a3 PJ |
3370 | // records finanical trxn and entity financial trxn |
3371 | // also make it available as return value | |
9c472292 | 3372 | self::recordAlwaysAccountsReceivable($trxnParams, $params); |
1c19e0a3 | 3373 | $return = $financialTxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); |
3d93e98e PN |
3374 | $params['entity_id'] = $financialTxn->id; |
3375 | if (empty($params['partial_payment_total']) && empty($params['partial_amount_pay'])) { | |
3376 | self::$_trxnIDs[] = $financialTxn->id; | |
3377 | } | |
6a488035 | 3378 | } |
e005ab6b | 3379 | } |
b44e3f84 | 3380 | // record line items and financial items |
a7488080 | 3381 | if (empty($params['skipLineItem'])) { |
e005ab6b | 3382 | CRM_Price_BAO_LineItem::processPriceSet($entityId, CRM_Utils_Array::value('line_item', $params), $params['contribution'], $entityTable, $update); |
6a488035 TO |
3383 | } |
3384 | ||
14b74ca6 | 3385 | // create batch entry if batch_id is passed and |
3386 | // ensure no batch entry is been made on 'Pending' or 'Failed' contribution, CRM-16611 | |
3387 | if (!empty($params['batch_id']) && !empty($financialTxn)) { | |
6a488035 TO |
3388 | $entityParams = array( |
3389 | 'batch_id' => $params['batch_id'], | |
3390 | 'entity_table' => 'civicrm_financial_trxn', | |
3391 | 'entity_id' => $financialTxn->id, | |
e005ab6b | 3392 | ); |
6a488035 TO |
3393 | CRM_Batch_BAO_Batch::addBatchEntity($entityParams); |
3394 | } | |
3395 | ||
3396 | // when a fee is charged | |
8cc574cf | 3397 | if (!empty($params['fee_amount']) && (empty($params['prevContribution']) || $params['contribution']->fee_amount != $params['prevContribution']->fee_amount) && $skipRecords) { |
6a488035 TO |
3398 | CRM_Core_BAO_FinancialTrxn::recordFees($params); |
3399 | } | |
3400 | ||
a7488080 | 3401 | if (!empty($params['prevContribution']) && $entityTable == 'civicrm_participant' |
f2b2a3ff TO |
3402 | && $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id |
3403 | ) { | |
6a488035 TO |
3404 | $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $entityId, 'event_id'); |
3405 | $feeLevel[] = str_replace('\ 1', '', $params['prevContribution']->amount_level); | |
3406 | CRM_Event_BAO_Participant::createDiscountTrxn($eventID, $params, $feeLevel); | |
3407 | } | |
3408 | unset($params['line_item']); | |
7b361924 | 3409 | self::$_trxnIDs = NULL; |
1c19e0a3 | 3410 | return $return; |
6a488035 TO |
3411 | } |
3412 | ||
3413 | /** | |
fe482240 | 3414 | * Update all financial accounts entry. |
6a488035 | 3415 | * |
014c4014 TO |
3416 | * @param array $params |
3417 | * Contribution object, line item array and params for trxn. | |
6a488035 | 3418 | * |
014c4014 TO |
3419 | * @param string $context |
3420 | * Update scenarios. | |
6a488035 | 3421 | * |
77b97be7 EM |
3422 | * @param null $skipTrxn |
3423 | * | |
6a488035 | 3424 | */ |
00be9182 | 3425 | public static function updateFinancialAccounts(&$params, $context = NULL, $skipTrxn = NULL) { |
6a488035 TO |
3426 | $itemAmount = $trxnID = NULL; |
3427 | //get all the statuses | |
3428 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); | |
67d61c72 | 3429 | $previousContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['prevContribution']->contribution_status_id, 'name'); |
3430 | if (($previousContributionStatus == 'Pending' | |
3431 | || $previousContributionStatus == 'In Progress') | |
b81ee58c | 3432 | && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus) |
f2b2a3ff TO |
3433 | && $context == 'changePaymentInstrument' |
3434 | ) { | |
6a488035 TO |
3435 | return; |
3436 | } | |
8084abdd PN |
3437 | if ((($previousContributionStatus == 'Partially paid' |
3438 | && $params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)) | |
19f6eba2 | 3439 | || ($previousContributionStatus == 'Pending' && $params['prevContribution']->is_pay_later == TRUE |
8084abdd | 3440 | && $params['contribution']->contribution_status_id == array_search('Partially paid', $contributionStatus))) |
827e15a4 E |
3441 | && $context == 'changedStatus' |
3442 | ) { | |
3443 | return; | |
3444 | } | |
6a488035 | 3445 | if ($context == 'changedAmount' || $context == 'changeFinancialType') { |
16c30586 | 3446 | $itemAmount = $params['trxnParams']['total_amount'] = $params['trxnParams']['net_amount'] = $params['total_amount'] - $params['prevContribution']->total_amount; |
6a488035 TO |
3447 | } |
3448 | if ($context == 'changedStatus') { | |
3449 | //get all the statuses | |
3450 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); | |
a7f2802f | 3451 | $cancelledTaxAmount = 0; |
67d61c72 | 3452 | if ($previousContributionStatus == 'Completed' |
52da5b1e | 3453 | && (self::isContributionStatusNegative($params['contribution']->contribution_status_id)) |
f2b2a3ff TO |
3454 | ) { |
3455 | $params['trxnParams']['total_amount'] = -$params['total_amount']; | |
a7f2802f | 3456 | $cancelledTaxAmount = CRM_Utils_Array::value('tax_amount', $params, '0.00'); |
8d20d89c | 3457 | if (empty($params['contribution']->creditnote_id) || $params['contribution']->creditnote_id == "null") { |
4add5adb GC |
3458 | $creditNoteId = self::createCreditNoteId(); |
3459 | CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId); | |
8762d39a | 3460 | } |
6a488035 | 3461 | } |
67d61c72 | 3462 | elseif (($previousContributionStatus == 'Pending' |
3463 | && $params['prevContribution']->is_pay_later) || $previousContributionStatus == 'In Progress' | |
f2b2a3ff | 3464 | ) { |
6a488035 | 3465 | $financialTypeID = CRM_Utils_Array::value('financial_type_id', $params) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id; |
ec04cb12 GC |
3466 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
3467 | $arAccountId = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeID, $relationTypeId); | |
3468 | ||
6a488035 | 3469 | if ($params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) { |
ec04cb12 | 3470 | $params['trxnParams']['to_financial_account_id'] = $arAccountId; |
f2b2a3ff | 3471 | $params['trxnParams']['total_amount'] = -$params['total_amount']; |
8762d39a | 3472 | if (is_null($params['contribution']->creditnote_id) || $params['contribution']->creditnote_id == "null") { |
4add5adb GC |
3473 | $creditNoteId = self::createCreditNoteId(); |
3474 | CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $params['contribution']->id, 'creditnote_id', $creditNoteId); | |
8762d39a | 3475 | } |
6a488035 | 3476 | } |
ec04cb12 GC |
3477 | else { |
3478 | $params['trxnParams']['from_financial_account_id'] = $arAccountId; | |
3479 | } | |
6a488035 | 3480 | } |
a7f2802f | 3481 | $itemAmount = $params['trxnParams']['total_amount'] + $cancelledTaxAmount; |
6a488035 TO |
3482 | } |
3483 | elseif ($context == 'changePaymentInstrument') { | |
b001aaef | 3484 | $params['trxnParams']['net_amount'] = $params['trxnParams']['total_amount']; |
bf4385cb SL |
3485 | $deferredFinancialAccount = CRM_Utils_Array::value('deferred_financial_account_id', $params); |
3486 | if (empty($deferredFinancialAccount)) { | |
3487 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Deferred Revenue Account is' ")); | |
3488 | $deferredFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($params['prevContribution']->financial_type_id, $relationTypeId); | |
3489 | } | |
3490 | $lastFinancialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($params['prevContribution']->id, 'DESC', FALSE, NULL, $deferredFinancialAccount); | |
230be83b SL |
3491 | if (!empty($lastFinancialTrxnId['financialTrxnId'])) { |
3492 | if ($params['total_amount'] != $params['trxnParams']['total_amount']) { | |
bf4385cb | 3493 | $params['trxnParams']['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $lastFinancialTrxnId['financialTrxnId'], 'to_financial_account_id'); |
230be83b | 3494 | $params['trxnParams']['payment_instrument_id'] = $params['prevContribution']->payment_instrument_id; |
122250ec SL |
3495 | } |
3496 | else { | |
bf4385cb | 3497 | $params['trxnParams']['to_financial_account_id'] = $params['to_financial_account_id']; |
122250ec SL |
3498 | $params['trxnParams']['payment_instrument_id'] = $params['contribution']->payment_instrument_id; |
3499 | } | |
6a488035 TO |
3500 | } |
3501 | } | |
6a488035 TO |
3502 | |
3503 | if ($context == 'changedStatus') { | |
67d61c72 | 3504 | if (($previousContributionStatus == 'Pending' |
3505 | || $previousContributionStatus == 'In Progress') | |
f2b2a3ff TO |
3506 | && ($params['contribution']->contribution_status_id == array_search('Completed', $contributionStatus)) |
3507 | ) { | |
3b624e58 EM |
3508 | if (empty($params['line_item'])) { |
3509 | //CRM-15296 | |
3510 | //@todo - check with Joe regarding this situation - payment processors create pending transactions with no line items | |
3511 | // when creating recurring membership payment - there are 2 lines to comment out in contributonPageTest if fixed | |
3512 | // & this can be removed | |
3513 | return; | |
3514 | } | |
9c472292 | 3515 | self::recordAlwaysAccountsReceivable($params['trxnParams'], $params); |
b34861f3 | 3516 | $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']); |
9c472292 | 3517 | $params['entity_id'] = self::$_trxnIDs[] = $trxn->id; |
b34861f3 | 3518 | $query = "UPDATE civicrm_financial_item SET status_id = %1 WHERE entity_id = %2 and entity_table = 'civicrm_line_item'"; |
3519 | $sql = "SELECT id, amount FROM civicrm_financial_item WHERE entity_id = %1 and entity_table = 'civicrm_line_item'"; | |
3520 | ||
3521 | $entityParams = array( | |
3522 | 'entity_table' => 'civicrm_financial_item', | |
b34861f3 | 3523 | ); |
6a488035 TO |
3524 | foreach ($params['line_item'] as $fieldId => $fields) { |
3525 | foreach ($fields as $fieldValueId => $fieldValues) { | |
3526 | $fparams = array( | |
3527 | 1 => array(CRM_Core_OptionGroup::getValue('financial_item_status', 'Paid', 'name'), 'Integer'), | |
3528 | 2 => array($fieldValues['id'], 'Integer'), | |
3529 | ); | |
6a488035 | 3530 | CRM_Core_DAO::executeQuery($query, $fparams); |
464bb009 PN |
3531 | $fparams = array( |
3532 | 1 => array($fieldValues['id'], 'Integer'), | |
3533 | ); | |
3534 | $financialItem = CRM_Core_DAO::executeQuery($sql, $fparams); | |
3535 | while ($financialItem->fetch()) { | |
3536 | $entityParams['entity_id'] = $financialItem->id; | |
3537 | $entityParams['amount'] = $financialItem->amount; | |
9c472292 PN |
3538 | foreach (self::$_trxnIDs as $tID) { |
3539 | $entityParams['financial_trxn_id'] = $tID; | |
3540 | CRM_Financial_BAO_FinancialItem::createEntityTrxn($entityParams); | |
3541 | } | |
464bb009 | 3542 | } |
6a488035 TO |
3543 | } |
3544 | } | |
3545 | return; | |
3546 | } | |
3547 | } | |
b34861f3 | 3548 | $trxn = CRM_Core_BAO_FinancialTrxn::create($params['trxnParams']); |
3549 | $params['entity_id'] = $trxn->id; | |
6a488035 TO |
3550 | if ($context != 'changePaymentInstrument') { |
3551 | $itemParams['entity_table'] = 'civicrm_line_item'; | |
3552 | $trxnIds['id'] = $params['entity_id']; | |
3553 | foreach ($params['line_item'] as $fieldId => $fields) { | |
3554 | foreach ($fields as $fieldValueId => $fieldValues) { | |
8cf6bd83 | 3555 | $prevFinancialItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($fieldValues['id']); |
6a488035 TO |
3556 | $receiveDate = CRM_Utils_Date::isoToMysql($params['prevContribution']->receive_date); |
3557 | if ($params['contribution']->receive_date) { | |
3558 | $receiveDate = CRM_Utils_Date::isoToMysql($params['contribution']->receive_date); | |
3559 | } | |
3560 | ||
bf2cf926 | 3561 | $financialAccount = self::getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem); |
6a488035 TO |
3562 | |
3563 | $currency = $params['prevContribution']->currency; | |
3564 | if ($params['contribution']->currency) { | |
3565 | $currency = $params['contribution']->currency; | |
3566 | } | |
05e92f54 | 3567 | $diff = 1; |
52da5b1e | 3568 | if ($context == 'changeFinancialType' || self::isContributionStatusNegative($params['contribution']->contribution_status_id)) { |
a7f2802f PN |
3569 | $diff = -1; |
3570 | } | |
a7488080 | 3571 | if (!empty($params['is_quick_config'])) { |
6a488035 TO |
3572 | $amount = $itemAmount; |
3573 | if (!$amount) { | |
3574 | $amount = $params['total_amount']; | |
3575 | } | |
3576 | } | |
3577 | else { | |
6a488035 TO |
3578 | $amount = $diff * $fieldValues['line_total']; |
3579 | } | |
3580 | ||
3581 | $itemParams = array( | |
3582 | 'transaction_date' => $receiveDate, | |
3583 | 'contact_id' => $params['prevContribution']->contact_id, | |
3584 | 'currency' => $currency, | |
3585 | 'amount' => $amount, | |
bf2cf926 | 3586 | 'description' => $prevFinancialItem->description, |
3587 | 'status_id' => $prevFinancialItem->status_id, | |
6a488035 TO |
3588 | 'financial_account_id' => $financialAccount, |
3589 | 'entity_table' => 'civicrm_line_item', | |
21dfd5f5 | 3590 | 'entity_id' => $fieldValues['id'], |
6a488035 | 3591 | ); |
8cf6bd83 PN |
3592 | $financialItem = CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds); |
3593 | $params['line_item'][$fieldId][$fieldValueId]['deferred_line_total'] = $amount; | |
3594 | $params['line_item'][$fieldId][$fieldValueId]['financial_item_id'] = $financialItem->id; | |
c40e1ff4 | 3595 | |
3596 | if ($fieldValues['tax_amount']) { | |
aaffa79f | 3597 | $invoiceSettings = Civi::settings()->get('contribution_invoice_settings'); |
5a18a545 | 3598 | $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings); |
c40e1ff4 | 3599 | $itemParams['amount'] = $diff * $fieldValues['tax_amount']; |
5a18a545 | 3600 | $itemParams['description'] = $taxTerm; |
c40e1ff4 | 3601 | if ($fieldValues['financial_type_id']) { |
5a18a545 | 3602 | $itemParams['financial_account_id'] = self::getFinancialAccountId($fieldValues['financial_type_id']); |
c40e1ff4 | 3603 | } |
3604 | CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds); | |
3605 | } | |
6a488035 TO |
3606 | } |
3607 | } | |
3608 | } | |
423ae5b1 | 3609 | if ($context == 'changeFinancialType') { |
6535ff79 | 3610 | $params['skipLineItem'] = FALSE; |
423ae5b1 PN |
3611 | foreach ($params['line_item'] as &$lineItems) { |
3612 | foreach ($lineItems as &$line) { | |
3613 | $line['financial_type_id'] = $params['financial_type_id']; | |
3614 | } | |
3615 | } | |
3616 | } | |
bf4385cb SL |
3617 | if ($context == 'changePaymentInstrument') { |
3618 | foreach ($params['line_item'] as $lineitems) { | |
3619 | foreach ($lineitems as $fieldValueId => $fieldValues) { | |
3620 | $prevFinancialItem = CRM_Financial_BAO_FinancialItem::getPreviousFinancialItem($fieldValues['id']); | |
bf4385cb SL |
3621 | // save to entity_financial_trxn table |
3622 | $entityFinancialTrxnParams = array( | |
3623 | 'entity_table' => "civicrm_financial_item", | |
3624 | 'entity_id' => $prevFinancialItem->id, | |
3625 | 'financial_trxn_id' => $trxn->id, | |
3626 | 'amount' => $trxn->total_amount, | |
bf4385cb | 3627 | ); |
230be83b | 3628 | civicrm_api3('entityFinancialTrxn', 'create', $entityFinancialTrxnParams); |
bf4385cb SL |
3629 | } |
3630 | } | |
3631 | } | |
8cf6bd83 | 3632 | CRM_Core_BAO_FinancialTrxn::createDeferredTrxn(CRM_Utils_Array::value('line_item', $params), $params['contribution'], TRUE, $context); |
6a488035 TO |
3633 | } |
3634 | ||
52da5b1e | 3635 | /** |
3636 | * Is this contribution status a reversal. | |
3637 | * | |
3638 | * If so we would expect to record a negative value in the financial_trxn table. | |
3639 | * | |
3640 | * @param int $status_id | |
3641 | * | |
3642 | * @return bool | |
3643 | */ | |
3644 | public static function isContributionStatusNegative($status_id) { | |
3645 | $reversalStatuses = array('Cancelled', 'Chargeback', 'Refunded'); | |
3646 | return in_array(CRM_Contribute_PseudoConstant::contributionStatus($status_id, 'name'), $reversalStatuses); | |
3647 | } | |
3648 | ||
6a488035 | 3649 | /** |
fe482240 | 3650 | * Check status validation on update of a contribution. |
6a488035 | 3651 | * |
014c4014 TO |
3652 | * @param array $values |
3653 | * Previous form values before submit. | |
6a488035 | 3654 | * |
014c4014 TO |
3655 | * @param array $fields |
3656 | * The input form values. | |
6a488035 | 3657 | * |
014c4014 TO |
3658 | * @param array $errors |
3659 | * List of errors. | |
6a488035 | 3660 | * |
77b97be7 | 3661 | * @return bool |
6a488035 | 3662 | */ |
00be9182 | 3663 | public static function checkStatusValidation($values, &$fields, &$errors) { |
8cc574cf | 3664 | if (CRM_Utils_System::isNull($values) && !empty($fields['id'])) { |
c71ae314 PN |
3665 | $values['contribution_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $fields['id'], 'contribution_status_id'); |
3666 | if ($values['contribution_status_id'] == $fields['contribution_status_id']) { | |
3667 | return FALSE; | |
3668 | } | |
3669 | } | |
6a488035 TO |
3670 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
3671 | $checkStatus = array( | |
3672 | 'Cancelled' => array('Completed', 'Refunded'), | |
52da5b1e | 3673 | 'Completed' => array('Cancelled', 'Refunded', 'Chargeback'), |
8084abdd | 3674 | 'Pending' => array('Cancelled', 'Completed', 'Failed', 'Partially paid'), |
f73acc78 | 3675 | 'In Progress' => array('Cancelled', 'Completed', 'Failed'), |
21dfd5f5 | 3676 | 'Refunded' => array('Cancelled', 'Completed'), |
827e15a4 | 3677 | 'Partially paid' => array('Completed'), |
6a488035 TO |
3678 | ); |
3679 | ||
da017017 PN |
3680 | if (!in_array($contributionStatuses[$fields['contribution_status_id']], |
3681 | CRM_Utils_Array::value($contributionStatuses[$values['contribution_status_id']], $checkStatus, array())) | |
3682 | ) { | |
f2b2a3ff | 3683 | $errors['contribution_status_id'] = ts("Cannot change contribution status from %1 to %2.", array( |
353ffa53 TO |
3684 | 1 => $contributionStatuses[$values['contribution_status_id']], |
3685 | 2 => $contributionStatuses[$fields['contribution_status_id']], | |
3686 | )); | |
6a488035 TO |
3687 | } |
3688 | } | |
c3d24ba7 PN |
3689 | |
3690 | /** | |
fe482240 | 3691 | * Delete contribution of contact. |
c3d24ba7 PN |
3692 | * |
3693 | * CRM-12155 | |
3694 | * | |
014c4014 TO |
3695 | * @param int $contactId |
3696 | * Contact id. | |
c3d24ba7 | 3697 | * |
c3d24ba7 | 3698 | */ |
00be9182 | 3699 | public static function deleteContactContribution($contactId) { |
c3d24ba7 PN |
3700 | $contribution = new CRM_Contribute_DAO_Contribution(); |
3701 | $contribution->contact_id = $contactId; | |
3702 | $contribution->find(); | |
3703 | while ($contribution->fetch()) { | |
3704 | self::deleteContribution($contribution->id); | |
3705 | } | |
3706 | } | |
16c0ec8d CW |
3707 | |
3708 | /** | |
3709 | * Get options for a given contribution field. | |
3710 | * @see CRM_Core_DAO::buildOptions | |
3711 | * | |
014c4014 | 3712 | * @param string $fieldName |
bed98343 | 3713 | * @param string $context see CRM_Core_DAO::buildOptionsContext. |
3714 | * @param array $props whatever is known about this dao object. | |
77b97be7 | 3715 | * |
a130e045 | 3716 | * @return array|bool |
16c0ec8d CW |
3717 | */ |
3718 | public static function buildOptions($fieldName, $context = NULL, $props = array()) { | |
3719 | $className = __CLASS__; | |
3720 | $params = array(); | |
3721 | switch ($fieldName) { | |
3722 | // This field is not part of this object but the api supports it | |
3723 | case 'payment_processor': | |
3724 | $className = 'CRM_Contribute_BAO_ContributionPage'; | |
3725 | // Filter results by contribution page | |
3726 | if (!empty($props['contribution_page_id'])) { | |
03a8c3dc | 3727 | $page = civicrm_api('contribution_page', 'getsingle', array( |
3728 | 'version' => 3, | |
21dfd5f5 | 3729 | 'id' => ($props['contribution_page_id']), |
03a8c3dc | 3730 | )); |
16c0ec8d CW |
3731 | $types = (array) CRM_Utils_Array::value('payment_processor', $page, 0); |
3732 | $params['condition'] = 'id IN (' . implode(',', $types) . ')'; | |
3733 | } | |
33a429d4 | 3734 | break; |
ea100cb5 | 3735 | |
33a429d4 CW |
3736 | // CRM-13981 This field was combined with soft_credits in 4.5 but the api still supports it |
3737 | case 'honor_type_id': | |
3738 | $className = 'CRM_Contribute_BAO_ContributionSoft'; | |
3739 | $fieldName = 'soft_credit_type_id'; | |
3740 | $params['condition'] = "v.name IN ('in_honor_of','in_memory_of')"; | |
3741 | break; | |
16c0ec8d CW |
3742 | } |
3743 | return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context); | |
3744 | } | |
03a8c3dc | 3745 | |
3b67ab13 | 3746 | /** |
fe482240 | 3747 | * Validate financial type. |
3b67ab13 PN |
3748 | * |
3749 | * CRM-13231 | |
3750 | * | |
014c4014 TO |
3751 | * @param int $financialTypeId |
3752 | * Financial Type id. | |
3b67ab13 | 3753 | * |
77b97be7 EM |
3754 | * @param string $relationName |
3755 | * | |
3756 | * @return array|bool | |
3b67ab13 | 3757 | */ |
00be9182 | 3758 | public static function validateFinancialType($financialTypeId, $relationName = 'Expense Account is') { |
3b67ab13 PN |
3759 | $expenseTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE '{$relationName}' ")); |
3760 | $financialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $expenseTypeId); | |
3761 | ||
3762 | if (!$financialAccount) { | |
3763 | return CRM_Contribute_PseudoConstant::financialType($financialTypeId); | |
3764 | } | |
3765 | return FALSE; | |
3766 | } | |
16c0ec8d | 3767 | |
3d7de127 | 3768 | |
d424ffde | 3769 | /** |
fe482240 | 3770 | * Function to record additional payment for partial and refund contributions. |
3d7de127 | 3771 | * |
014c4014 | 3772 | * @param int $contributionId |
16b10e64 | 3773 | * is the invoice contribution id (got created after processing participant payment). |
d424ffde | 3774 | * @param array $trxnsData |
16b10e64 | 3775 | * to take user provided input of transaction details. |
014c4014 TO |
3776 | * @param string $paymentType |
3777 | * 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments. | |
100fef9d | 3778 | * @param int $participantId |
186c9c17 EM |
3779 | * |
3780 | * @return null|object | |
3781 | */ | |
ebfaa544 | 3782 | public static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL, $updateStatus = TRUE) { |
0f602e3f | 3783 | $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name'); |
e8cf3013 PJ |
3784 | $getInfoOf['id'] = $contributionId; |
3785 | $defaults = array(); | |
3786 | $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray); | |
af0fda98 | 3787 | if (!$participantId) { |
545ca071 | 3788 | $participantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $contributionId, 'participant_id', 'contribution_id'); |
af0fda98 | 3789 | } |
e8cf3013 PJ |
3790 | |
3791 | if ($paymentType == 'owed') { | |
3792 | // build params for recording financial trxn entry | |
3793 | $params['contribution'] = $contributionDAO; | |
3794 | $params = array_merge($defaults, $params); | |
3795 | $params['skipLineItem'] = TRUE; | |
3796 | $params['partial_payment_total'] = $contributionDAO->total_amount; | |
3797 | $params['partial_amount_pay'] = $trxnsData['total_amount']; | |
3798 | $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis'); | |
60a2aeee | 3799 | $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount']; |
e8cf3013 PJ |
3800 | |
3801 | // record the entry | |
3802 | $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData); | |
3803 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); | |
3804 | $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId); | |
0f602e3f | 3805 | |
e8cf3013 | 3806 | $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id); |
921bca19 DG |
3807 | if (!empty($trxnId)) { |
3808 | $trxnId = $trxnId['trxn_id']; | |
3809 | } | |
3810 | elseif (!empty($contributionDAO->payment_instrument_id)) { | |
3811 | $trxnId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contributionDAO->payment_instrument_id); | |
3812 | } | |
3813 | else { | |
3814 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); | |
3815 | $queryParams = array(1 => array($relationTypeId, 'Integer')); | |
3816 | $trxnId = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = %1", $queryParams); | |
3817 | } | |
0f602e3f | 3818 | |
e8cf3013 PJ |
3819 | // update statuses |
3820 | // criteria for updates contribution total_amount == financial_trxns of partial_payments | |
b8adb851 | 3821 | $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total |
0f602e3f | 3822 | FROM civicrm_financial_trxn ft |
a695703f PJ |
3823 | LEFT JOIN civicrm_entity_financial_trxn eft |
3824 | ON (ft.id = eft.financial_trxn_id) | |
3825 | WHERE eft.entity_table = 'civicrm_contribution' | |
3826 | AND eft.entity_id = {$contributionId} | |
3827 | AND ft.to_financial_account_id != {$toFinancialAccount} | |
3828 | AND ft.status_id = {$statusId} | |
0f602e3f | 3829 | "; |
b8adb851 | 3830 | $query = CRM_Core_DAO::executeQuery($sql); |
3831 | $query->fetch(); | |
3832 | $sumOfPayments = $query->sum_of_payments; | |
e8cf3013 PJ |
3833 | |
3834 | // update statuses | |
3835 | if ($contributionDAO->total_amount == $sumOfPayments) { | |
921bca19 DG |
3836 | // update contribution status and |
3837 | // clean cancel info (if any) if prev. contribution was updated in case of 'Refunded' => 'Completed' | |
3838 | $contributionDAO->contribution_status_id = $statusId; | |
3839 | $contributionDAO->cancel_date = 'null'; | |
3840 | $contributionDAO->cancel_reason = NULL; | |
b8adb851 | 3841 | $netAmount = !empty($trxnsData['net_amount']) ? NULL : $trxnsData['total_amount']; |
3842 | $contributionDAO->net_amount = $query->net_amount_total + $netAmount; | |
3843 | $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount; | |
921bca19 DG |
3844 | $contributionDAO->save(); |
3845 | ||
3846 | //Change status of financial record too | |
3847 | $financialTrxn->status_id = $statusId; | |
3848 | $financialTrxn->save(); | |
3849 | ||
e8cf3013 PJ |
3850 | // note : not using the self::add method, |
3851 | // the reason because it performs 'status change' related code execution for financial records | |
3852 | // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates | |
3853 | // are coded below i.e. just updating financial_item status to 'Paid' | |
e8cf3013 PJ |
3854 | |
3855 | if ($participantId) { | |
3856 | // update participant status | |
e8cf3013 | 3857 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
28e4e707 PJ |
3858 | $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); |
3859 | foreach ($ids as $val) { | |
3860 | $participantUpdate['id'] = $val; | |
3861 | $participantUpdate['status_id'] = array_search('Registered', $participantStatuses); | |
3862 | CRM_Event_BAO_Participant::add($participantUpdate); | |
3863 | } | |
e8cf3013 PJ |
3864 | } |
3865 | ||
3866 | // update financial item statuses | |
3867 | $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id'); | |
3868 | $paidStatus = array_search('Paid', $financialItemStatus); | |
3869 | ||
5684b818 | 3870 | $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); |
e8cf3013 PJ |
3871 | $sqlFinancialItemUpdate = " |
3872 | UPDATE civicrm_financial_item fi | |
3873 | LEFT JOIN civicrm_entity_financial_trxn eft | |
3874 | ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item') | |
3875 | SET status_id = {$paidStatus} | |
5684b818 | 3876 | WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']}) |
e8cf3013 PJ |
3877 | "; |
3878 | CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate); | |
3879 | } | |
3880 | } | |
3881 | elseif ($paymentType == 'refund') { | |
3882 | // build params for recording financial trxn entry | |
3883 | $params['contribution'] = $contributionDAO; | |
3884 | $params = array_merge($defaults, $params); | |
3885 | $params['skipLineItem'] = TRUE; | |
3886 | $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis'); | |
f2b2a3ff | 3887 | $trxnsData['total_amount'] = -$trxnsData['total_amount']; |
e8cf3013 | 3888 | |
1010c4e1 PJ |
3889 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); |
3890 | $trxnsData['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId); | |
e8cf3013 PJ |
3891 | $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name'); |
3892 | // record the entry | |
3893 | $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData); | |
3894 | ||
aac57c29 PJ |
3895 | // note : not using the self::add method, |
3896 | // the reason because it performs 'status change' related code execution for financial records | |
e8cf3013 | 3897 | // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates |
aac57c29 | 3898 | // are coded below i.e. just updating financial_item status to 'Paid' |
ebfaa544 PN |
3899 | if ($updateStatus) { |
3900 | $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId); | |
3901 | } | |
e8cf3013 PJ |
3902 | // add financial item entry |
3903 | $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id'); | |
4ab71644 E |
3904 | $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionDAO->id); |
3905 | if (!empty($lineItems)) { | |
3906 | foreach ($lineItems as $lineItemId => $lineItemValue) { | |
3907 | $paid = $lineItemValue['line_total'] * ($financialTrxn->total_amount / $contributionDAO->total_amount); | |
3908 | $addFinancialEntry = array( | |
3909 | 'transaction_date' => $financialTrxn->trxn_date, | |
3910 | 'contact_id' => $contributionDAO->contact_id, | |
3911 | 'amount' => round($paid, 2), | |
3912 | 'status_id' => array_search('Paid', $financialItemStatus), | |
3913 | 'entity_id' => $lineItemId, | |
3914 | 'entity_table' => 'civicrm_line_item', | |
3915 | ); | |
3916 | $trxnIds['id'] = $financialTrxn->id; | |
3917 | CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds); | |
3918 | } | |
615a1e0f | 3919 | } |
0f602e3f PJ |
3920 | if ($participantId) { |
3921 | // update participant status | |
0f602e3f | 3922 | $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); |
28e4e707 PJ |
3923 | $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); |
3924 | foreach ($ids as $val) { | |
3925 | $participantUpdate['id'] = $val; | |
3926 | $participantUpdate['status_id'] = array_search('Registered', $participantStatuses); | |
3927 | CRM_Event_BAO_Participant::add($participantUpdate); | |
3928 | } | |
0f602e3f | 3929 | } |
0f602e3f | 3930 | } |
bd99f5fe | 3931 | |
e8cf3013 | 3932 | // activity creation |
bd99f5fe PJ |
3933 | if (!empty($financialTrxn)) { |
3934 | if ($participantId) { | |
3935 | $inputParams['id'] = $participantId; | |
3936 | $values = array(); | |
3937 | $ids = array(); | |
3938 | $component = 'event'; | |
3939 | $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids); | |
3940 | $entityObj = $entityObj[$participantId]; | |
3941 | } | |
685dc433 PN |
3942 | else { |
3943 | $entityObj = $contributionDAO; | |
3944 | $component = 'contribution'; | |
3945 | } | |
bd99f5fe PJ |
3946 | $activityType = ($paymentType == 'refund') ? 'Refund' : 'Payment'; |
3947 | ||
66526669 | 3948 | self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component, $contributionId); |
bd99f5fe PJ |
3949 | } |
3950 | return $financialTrxn; | |
3951 | } | |
3952 | ||
186c9c17 EM |
3953 | /** |
3954 | * @param $entityObj | |
3955 | * @param $trxnObj | |
3956 | * @param $activityType | |
3957 | * @param $component | |
100fef9d | 3958 | * @param int $contributionId |
186c9c17 EM |
3959 | * |
3960 | * @throws CRM_Core_Exception | |
3961 | */ | |
00be9182 | 3962 | public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) { |
bd99f5fe | 3963 | if ($component == 'event') { |
685dc433 | 3964 | $title = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title'); |
bd99f5fe | 3965 | } |
685dc433 PN |
3966 | else { |
3967 | $title = ts('Contribution'); | |
3968 | } | |
3969 | $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency); | |
3970 | $subject = "{$paymentAmount} - Offline {$activityType} for {$title}"; | |
3971 | $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date); | |
3972 | $targetCid = $entityObj->contact_id; | |
3973 | // source record id would be the contribution id | |
3974 | $srcRecId = $contributionId; | |
bd99f5fe PJ |
3975 | |
3976 | // activity params | |
3977 | $activityParams = array( | |
3978 | 'source_contact_id' => $targetCid, | |
3979 | 'source_record_id' => $srcRecId, | |
3980 | 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', | |
3981 | $activityType, | |
3982 | 'name' | |
3983 | ), | |
3984 | 'subject' => $subject, | |
3985 | 'activity_date_time' => $date, | |
3986 | 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', | |
3987 | 'Completed', | |
3988 | 'name' | |
3989 | ), | |
3990 | 'skipRecentView' => TRUE, | |
3991 | ); | |
3992 | ||
3993 | // create activity with target contacts | |
3994 | $session = CRM_Core_Session::singleton(); | |
3995 | $id = $session->get('userID'); | |
3996 | if ($id) { | |
3997 | $activityParams['source_contact_id'] = $id; | |
3998 | $activityParams['target_contact_id'][] = $targetCid; | |
3999 | } | |
4000 | CRM_Activity_BAO_Activity::create($activityParams); | |
0f602e3f | 4001 | } |
16c0ec8d | 4002 | |
186c9c17 | 4003 | /** |
fe482240 | 4004 | * Get list of payments displayed by Contribute_Page_PaymentInfo. |
8cf01b22 | 4005 | * |
100fef9d | 4006 | * @param int $id |
186c9c17 EM |
4007 | * @param $component |
4008 | * @param bool $getTrxnInfo | |
4009 | * @param bool $usingLineTotal | |
4010 | * | |
4011 | * @return mixed | |
4012 | */ | |
00be9182 | 4013 | public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) { |
29c61b58 PJ |
4014 | if ($component == 'event') { |
4015 | $entity = 'participant'; | |
e8cf3013 | 4016 | $entityTable = 'civicrm_participant'; |
29c61b58 | 4017 | $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id'); |
ae53df5f PJ |
4018 | |
4019 | if (!$contributionId) { | |
4020 | if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) { | |
4021 | $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id'); | |
4022 | $id = $primaryParticipantId; | |
4023 | } | |
22825dfc | 4024 | if (!$contributionId) { |
4025 | return; | |
ae53df5f PJ |
4026 | } |
4027 | } | |
29c61b58 | 4028 | } |
d4c0653f | 4029 | else { |
4030 | $contributionId = $id; | |
4031 | $entity = 'contribution'; | |
4032 | $entityTable = 'civicrm_contribution'; | |
4033 | } | |
4034 | ||
29c61b58 | 4035 | $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId); |
1010c4e1 | 4036 | $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL; |
4d193d61 | 4037 | if (!$baseTrxnId) { |
5684b818 PJ |
4038 | $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); |
4039 | $baseTrxnId = $baseTrxnId['financialTrxnId']; | |
5684b818 | 4040 | } |
18fdfcc3 | 4041 | if (!CRM_Utils_Array::value('total_amount', $total) || $usingLineTotal) { |
685dc433 | 4042 | $total = CRM_Price_BAO_LineItem::getLineTotal($contributionId); |
bc2eeabb PJ |
4043 | } |
4044 | else { | |
4045 | $baseTrxnId = $total['trxn_id']; | |
4046 | $total = $total['total_amount']; | |
4047 | } | |
1010c4e1 | 4048 | |
bc2eeabb | 4049 | $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total); |
356579e9 | 4050 | $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later'); |
8cf01b22 DG |
4051 | |
4052 | $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' ")); | |
4053 | $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id'); | |
4054 | $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId); | |
4055 | ||
356579e9 PJ |
4056 | if ($paymentBalance == 0 && $contributionIsPayLater) { |
4057 | $paymentBalance = $total; | |
4058 | } | |
4059 | ||
29c61b58 PJ |
4060 | $info['total'] = $total; |
4061 | $info['paid'] = $total - $paymentBalance; | |
4062 | $info['balance'] = $paymentBalance; | |
4063 | $info['id'] = $id; | |
4064 | $info['component'] = $component; | |
356579e9 | 4065 | $info['payLater'] = $contributionIsPayLater; |
bc2eeabb PJ |
4066 | $rows = array(); |
4067 | if ($getTrxnInfo && $baseTrxnId) { | |
8cf01b22 | 4068 | // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account |
29c61b58 | 4069 | $sql = " |
3636b520 | 4070 | SELECT GROUP_CONCAT(fa.`name`) as financial_account, |
4071 | ft.total_amount, | |
4072 | ft.payment_instrument_id, | |
4073 | ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number, con.currency | |
4074 | ||
636b20c5 | 4075 | FROM civicrm_contribution con |
4076 | LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution') | |
4077 | INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id | |
4d193d61 | 4078 | AND ft.to_financial_account_id != %2 |
636b20c5 | 4079 | INNER JOIN civicrm_entity_financial_trxn ef ON (ef.financial_trxn_id = ft.id AND ef.entity_table = 'civicrm_financial_item') |
4080 | LEFT JOIN civicrm_financial_item fi ON fi.id = ef.entity_id | |
4081 | INNER JOIN civicrm_financial_account fa ON fa.id = fi.financial_account_id | |
4082 | ||
7fedcca5 | 4083 | WHERE con.id = %1 AND ft.is_payment = 1 |
3636b520 | 4084 | GROUP BY ft.id"; |
4d193d61 PN |
4085 | $queryParams = array( |
4086 | 1 => array($contributionId, 'Integer'), | |
4087 | 2 => array($feeFinancialAccount, 'Integer'), | |
4d193d61 PN |
4088 | ); |
4089 | $resultDAO = CRM_Core_DAO::executeQuery($sql, $queryParams); | |
536b8316 | 4090 | $statuses = CRM_Contribute_PseudoConstant::contributionStatus(); |
636b20c5 | 4091 | |
f2b2a3ff | 4092 | while ($resultDAO->fetch()) { |
536b8316 PJ |
4093 | $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); |
4094 | $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); | |
4095 | $val = array( | |
29c61b58 | 4096 | 'total_amount' => $resultDAO->total_amount, |
636b20c5 | 4097 | 'financial_type' => $resultDAO->financial_account, |
536b8316 | 4098 | 'payment_instrument' => $paidByLabel, |
29c61b58 PJ |
4099 | 'receive_date' => $resultDAO->trxn_date, |
4100 | 'trxn_id' => $resultDAO->trxn_id, | |
4101 | 'status' => $statuses[$resultDAO->status_id], | |
7e7e2e3f | 4102 | 'currency' => $resultDAO->currency, |
29c61b58 | 4103 | ); |
536b8316 PJ |
4104 | if ($paidByName == 'Check') { |
4105 | $val['check_number'] = $resultDAO->check_number; | |
4106 | } | |
4107 | $rows[] = $val; | |
29c61b58 PJ |
4108 | } |
4109 | $info['transaction'] = $rows; | |
4110 | } | |
4111 | return $info; | |
4112 | } | |
5a18a545 | 4113 | |
4114 | /** | |
2912ed09 | 4115 | * Get financial account id has 'Sales Tax Account is' account relationship with financial type. |
5a18a545 | 4116 | * |
100fef9d | 4117 | * @param int $financialTypeId |
5a18a545 | 4118 | * |
2912ed09 | 4119 | * @return int |
4120 | * Financial Account Id | |
5a18a545 | 4121 | */ |
00be9182 | 4122 | public static function getFinancialAccountId($financialTypeId) { |
5a18a545 | 4123 | $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' ")); |
4124 | $searchParams = array( | |
4125 | 'entity_table' => 'civicrm_financial_type', | |
4126 | 'entity_id' => $financialTypeId, | |
4127 | 'account_relationship' => $accountRel, | |
4128 | ); | |
4129 | $result = array(); | |
f2b2a3ff | 4130 | CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result); |
5a18a545 | 4131 | |
f2b2a3ff | 4132 | return CRM_Utils_Array::value('financial_account_id', $result); |
5a18a545 | 4133 | } |
b5935203 | 4134 | |
7a9ab499 | 4135 | /** |
2912ed09 | 4136 | * Get the tax amount (misnamed function). |
7a9ab499 EM |
4137 | * |
4138 | * @param array $params | |
4139 | * @param bool $isLineItem | |
4140 | * | |
2912ed09 | 4141 | * @return array |
7a9ab499 | 4142 | */ |
115fa278 | 4143 | public static function checkTaxAmount($params, $isLineItem = FALSE) { |
b5935203 | 4144 | $taxRates = CRM_Core_PseudoConstant::getTaxRates(); |
4145 | ||
7a9ab499 | 4146 | // Update contribution. |
b5935203 | 4147 | if (!empty($params['id'])) { |
2912ed09 | 4148 | // CRM-19126 and CRM-19152 If neither total or financial_type_id are set on an update |
4149 | // there are no tax implications - early return. | |
4150 | if (!isset($params['total_amount']) && !isset($params['financial_type_id'])) { | |
4151 | return $params; | |
4152 | } | |
4153 | if (empty($params['prevContribution'])) { | |
4154 | $params['prevContribution'] = self::getOriginalContribution($params['id']); | |
4155 | } | |
a76b8bd8 | 4156 | |
4157 | foreach (array('total_amount', 'financial_type_id', 'fee_amount') as $field) { | |
2912ed09 | 4158 | if (!isset($params[$field])) { |
4159 | if ($field == 'total_amount' && $params['prevContribution']->tax_amount) { | |
4160 | // Tax amount gets added back on later.... | |
4161 | $params['total_amount'] = $params['prevContribution']->total_amount - | |
4162 | $params['prevContribution']->tax_amount; | |
99a4cd32 SL |
4163 | } |
4164 | else { | |
2912ed09 | 4165 | $params[$field] = $params['prevContribution']->$field; |
4166 | if ($params[$field] != $params['prevContribution']->$field) { | |
2912ed09 | 4167 | } |
99a4cd32 SL |
4168 | } |
4169 | } | |
b107e882 | 4170 | } |
a76b8bd8 | 4171 | |
2912ed09 | 4172 | self::calculateMissingAmountParams($params, $params['id']); |
4173 | if (!array_key_exists($params['financial_type_id'], $taxRates)) { | |
4174 | // Assign tax Amount on update of contribution | |
4175 | if (!empty($params['prevContribution']->tax_amount)) { | |
b5935203 | 4176 | $params['tax_amount'] = 'null'; |
4177 | CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id'])); | |
4178 | foreach ($params['line_item'] as $setID => $priceField) { | |
4179 | foreach ($priceField as $priceFieldID => $priceFieldValue) { | |
4180 | $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; | |
4181 | } | |
4182 | } | |
4183 | } | |
4184 | } | |
4185 | } | |
4186 | ||
2912ed09 | 4187 | // New Contribution and update of contribution with tax rate financial type |
5525990d | 4188 | if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && |
f2b2a3ff TO |
4189 | empty($params['skipLineItem']) && !$isLineItem |
4190 | ) { | |
4191 | $taxRateParams = $taxRates[$params['financial_type_id']]; | |
def7e770 | 4192 | $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount(CRM_Utils_Array::value('total_amount', $params), $taxRateParams); |
f2b2a3ff | 4193 | $params['tax_amount'] = round($taxAmount['tax_amount'], 2); |
b5935203 | 4194 | |
f2b2a3ff TO |
4195 | // Get Line Item on update of contribution |
4196 | if (isset($params['id'])) { | |
4197 | CRM_Price_BAO_LineItem::getLineItemArray($params, array($params['id'])); | |
4198 | } | |
4199 | else { | |
4200 | CRM_Price_BAO_LineItem::getLineItemArray($params); | |
4201 | } | |
4202 | foreach ($params['line_item'] as $setID => $priceField) { | |
4203 | foreach ($priceField as $priceFieldID => $priceFieldValue) { | |
4204 | $params['line_item'][$setID][$priceFieldID]['tax_amount'] = $params['tax_amount']; | |
b5935203 | 4205 | } |
5525990d | 4206 | } |
def7e770 | 4207 | $params['total_amount'] = CRM_Utils_Array::value('total_amount', $params) + $params['tax_amount']; |
f2b2a3ff | 4208 | } |
4c9b6178 | 4209 | elseif (isset($params['api.line_item.create'])) { |
5525990d | 4210 | // Update total amount of contribution using lineItem |
b5935203 | 4211 | $taxAmountArray = array(); |
4212 | foreach ($params['api.line_item.create'] as $key => $value) { | |
4213 | if (isset($value['financial_type_id']) && array_key_exists($value['financial_type_id'], $taxRates)) { | |
f2b2a3ff | 4214 | $taxRate = $taxRates[$value['financial_type_id']]; |
5525990d | 4215 | $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($value['line_total'], $taxRate); |
b5935203 | 4216 | $taxAmountArray[] = round($taxAmount['tax_amount'], 2); |
4217 | } | |
4218 | } | |
4219 | $params['tax_amount'] = array_sum($taxAmountArray); | |
5525990d | 4220 | $params['total_amount'] = $params['total_amount'] + $params['tax_amount']; |
b5935203 | 4221 | } |
4222 | else { | |
4223 | // update line item of contrbution | |
4224 | if (isset($params['financial_type_id']) && array_key_exists($params['financial_type_id'], $taxRates) && $isLineItem) { | |
4225 | $taxRate = $taxRates[$params['financial_type_id']]; | |
4226 | $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($params['line_total'], $taxRate); | |
4227 | $params['tax_amount'] = round($taxAmount['tax_amount'], 2); | |
4228 | } | |
4229 | } | |
4230 | return $params; | |
4231 | } | |
96025800 | 4232 | |
4d47ad17 PN |
4233 | /** |
4234 | * Check financial type validation on update of a contribution. | |
4235 | * | |
4236 | * @param Integer $financialTypeId | |
4237 | * Value of latest Financial Type. | |
4238 | * | |
8499d1ea | 4239 | * @param Integer $contributionId |
4d47ad17 PN |
4240 | * Contribution Id. |
4241 | * | |
4242 | * @param array $errors | |
4243 | * List of errors. | |
4244 | * | |
4245 | * @return bool | |
4246 | */ | |
4247 | public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) { | |
4248 | if (!empty($financialTypeId)) { | |
4249 | $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id'); | |
4250 | if ($oldFinancialTypeId == $financialTypeId) { | |
4251 | return FALSE; | |
4252 | } | |
4253 | } | |
4254 | $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;'; | |
4255 | $params = array( | |
8499d1ea | 4256 | '1' => array($contributionId, 'Integer'), |
4d47ad17 PN |
4257 | ); |
4258 | $result = CRM_Core_DAO::executeQuery($sql, $params); | |
4259 | if ($result->N > 1) { | |
4260 | $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.'); | |
4261 | } | |
4262 | } | |
4263 | ||
6d0cf504 EM |
4264 | /** |
4265 | * Update related pledge payment payments. | |
4266 | * | |
5e27919e EM |
4267 | * This function has been refactored out of the back office contribution form and may |
4268 | * still overlap with other functions. | |
4269 | * | |
6d0cf504 EM |
4270 | * @param string $action |
4271 | * @param int $pledgePaymentID | |
4272 | * @param int $contributionID | |
4273 | * @param bool $adjustTotalAmount | |
4274 | * @param float $total_amount | |
4275 | * @param float $original_total_amount | |
4276 | * @param int $contribution_status_id | |
4277 | * @param int $original_contribution_status_id | |
4278 | */ | |
5e27919e | 4279 | public static function updateRelatedPledge( |
6d0cf504 EM |
4280 | $action, |
4281 | $pledgePaymentID, | |
4282 | $contributionID, | |
4283 | $adjustTotalAmount, | |
4284 | $total_amount, | |
4285 | $original_total_amount, | |
4286 | $contribution_status_id, | |
4287 | $original_contribution_status_id | |
4288 | ) { | |
8e776a1a SB |
4289 | if (!$pledgePaymentID && $action & CRM_Core_Action::ADD && !$contributionID) { |
4290 | return; | |
4291 | } | |
4292 | ||
6d0cf504 EM |
4293 | if ($pledgePaymentID) { |
4294 | //store contribution id in payment record. | |
4295 | CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID); | |
4296 | } | |
4297 | else { | |
4298 | $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', | |
4299 | $contributionID, | |
4300 | 'id', | |
4301 | 'contribution_id' | |
4302 | ); | |
4303 | } | |
fcdf24a4 | 4304 | |
8e776a1a | 4305 | if (!$pledgePaymentID) { |
fcdf24a4 SB |
4306 | return; |
4307 | } | |
6d0cf504 EM |
4308 | $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', |
4309 | $contributionID, | |
4310 | 'pledge_id', | |
4311 | 'contribution_id' | |
4312 | ); | |
4313 | ||
4314 | $updatePledgePaymentStatus = FALSE; | |
4315 | ||
4316 | // If either the status or the amount has changed we update the pledge status. | |
4317 | if ($action & CRM_Core_Action::ADD) { | |
4318 | $updatePledgePaymentStatus = TRUE; | |
4319 | } | |
4320 | elseif ($action & CRM_Core_Action::UPDATE && (($original_contribution_status_id != $contribution_status_id) || | |
4321 | ($original_total_amount != $total_amount)) | |
4322 | ) { | |
4323 | $updatePledgePaymentStatus = TRUE; | |
4324 | } | |
4325 | ||
4326 | if ($updatePledgePaymentStatus) { | |
4327 | CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, | |
4328 | array($pledgePaymentID), | |
4329 | $contribution_status_id, | |
4330 | NULL, | |
4331 | $total_amount, | |
4332 | $adjustTotalAmount | |
4333 | ); | |
4334 | } | |
4335 | } | |
456b0145 | 4336 | |
ae6884ce | 4337 | /** |
4338 | * Compute the stats values | |
4339 | * | |
23ce9a3a | 4340 | * @param $stat either 'mode' or 'median' |
4341 | * @param $sql | |
4342 | * @param $alias of civicrm_contribution | |
ae6884ce | 4343 | */ |
4344 | public static function computeStats($stat, $sql, $alias = NULL) { | |
899439b0 | 4345 | $mode = $median = array(); |
23ce9a3a | 4346 | switch ($stat) { |
ae6884ce | 4347 | case 'mode': |
4348 | $modeDAO = CRM_Core_DAO::executeQuery($sql); | |
4349 | while ($modeDAO->fetch()) { | |
4350 | if ($modeDAO->civicrm_contribution_total_amount_count > 1) { | |
4351 | $mode[] = CRM_Utils_Money::format($modeDAO->amount, $modeDAO->currency); | |
4352 | } | |
4353 | else { | |
4354 | $mode[] = 'N/A'; | |
4355 | } | |
4356 | } | |
4357 | return $mode; | |
4358 | ||
4359 | case 'median': | |
ae6884ce | 4360 | $currencies = CRM_Core_OptionGroup::values('currencies_enabled'); |
4361 | foreach ($currencies as $currency => $val) { | |
e9ec4119 | 4362 | $midValue = 0; |
ae6884ce | 4363 | $where = "AND {$alias}.currency = '{$currency}'"; |
4364 | $rowCount = CRM_Core_DAO::singleValueQuery("SELECT count(*) as count {$sql} {$where}"); | |
4365 | ||
4366 | $even = FALSE; | |
4367 | $offset = 1; | |
4368 | $medianRow = floor($rowCount / 2); | |
4369 | if ($rowCount % 2 == 0 && !empty($medianRow)) { | |
4370 | $even = TRUE; | |
4371 | $offset++; | |
4372 | $medianRow--; | |
4373 | } | |
4374 | ||
4375 | $medianValue = "SELECT {$alias}.total_amount as median | |
4376 | {$sql} {$where} | |
4377 | ORDER BY median LIMIT {$medianRow},{$offset}"; | |
4378 | $medianValDAO = CRM_Core_DAO::executeQuery($medianValue); | |
4379 | while ($medianValDAO->fetch()) { | |
4380 | if ($even) { | |
4381 | $midValue = $midValue + $medianValDAO->median; | |
4382 | } | |
4383 | else { | |
4384 | $median[] = CRM_Utils_Money::format($medianValDAO->median, $currency); | |
4385 | } | |
4386 | } | |
4387 | if ($even) { | |
23ce9a3a | 4388 | $midValue = $midValue / 2; |
ae6884ce | 4389 | $median[] = CRM_Utils_Money::format($midValue, $currency); |
4390 | } | |
4391 | } | |
4392 | return $median; | |
4393 | ||
23ce9a3a | 4394 | default: |
ae6884ce | 4395 | return; |
4396 | } | |
4397 | } | |
4398 | ||
3c49d90c | 4399 | /** |
4400 | * Is there only one line item attached to the contribution. | |
4401 | * | |
4402 | * @param int $id | |
4403 | * Contribution ID. | |
4404 | * | |
4405 | * @return bool | |
4406 | * @throws \CiviCRM_API3_Exception | |
4407 | */ | |
4408 | public static function isSingleLineItem($id) { | |
467fe956 | 4409 | $lineItemCount = civicrm_api3('LineItem', 'getcount', array('contribution_id' => $id)); |
3c49d90c | 4410 | return ($lineItemCount == 1); |
4411 | } | |
4412 | ||
db59bb73 EM |
4413 | /** |
4414 | * Complete an order. | |
4415 | * | |
4416 | * Do not call this directly - use the contribution.completetransaction api as this function is being refactored. | |
4417 | * | |
4418 | * Currently overloaded to complete a transaction & repeat a transaction - fix! | |
4419 | * | |
4420 | * Moving it out of the BaseIPN class is just the first step. | |
4421 | * | |
4422 | * @param array $input | |
4423 | * @param array $ids | |
4424 | * @param array $objects | |
4425 | * @param CRM_Core_Transaction $transaction | |
4426 | * @param int $recur | |
4427 | * @param CRM_Contribute_BAO_Contribution $contribution | |
4428 | * @param bool $isRecurring | |
4b6c8c1e | 4429 | * Duplication of param needs review. Only used by AuthorizeNetIPN |
db59bb73 | 4430 | * @param int $isFirstOrLastRecurringPayment |
4b6c8c1e | 4431 | * Deprecated param only used by AuthorizeNetIPN. |
db59bb73 | 4432 | */ |
59626c7f | 4433 | public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment) { |
db59bb73 | 4434 | $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id; |
66df7769 | 4435 | // The previous details are used when calculating line items so keep it before any code that 'does something' |
4436 | if (!empty($contribution->id)) { | |
4437 | $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), | |
4438 | CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); | |
4439 | } | |
b3b7f4c5 | 4440 | $inputContributionWhiteList = array( |
4441 | 'fee_amount', | |
4442 | 'net_amount', | |
4443 | 'trxn_id', | |
4444 | 'check_number', | |
4445 | 'payment_instrument_id', | |
4446 | 'is_test', | |
1c98b2d6 | 4447 | 'campaign_id', |
12829b5d | 4448 | 'receive_date', |
d9924163 | 4449 | 'receipt_date', |
d5580ed4 | 4450 | 'contribution_status_id', |
b3b7f4c5 | 4451 | ); |
3c49d90c | 4452 | if (self::isSingleLineItem($primaryContributionID)) { |
4453 | $inputContributionWhiteList[] = 'financial_type_id'; | |
4454 | } | |
b3b7f4c5 | 4455 | |
7f4ef731 | 4456 | $participant = CRM_Utils_Array::value('participant', $objects); |
4457 | $memberships = CRM_Utils_Array::value('membership', $objects); | |
4458 | $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects); | |
294cc627 | 4459 | $recurringContributionID = (empty($recurContrib->id)) ? NULL : $recurContrib->id; |
7f4ef731 | 4460 | $event = CRM_Utils_Array::value('event', $objects); |
b3b7f4c5 | 4461 | |
43c8d1dd | 4462 | $paymentProcessorId = ''; |
4463 | if (isset($objects['paymentProcessor'])) { | |
4464 | if (is_array($objects['paymentProcessor'])) { | |
4465 | $paymentProcessorId = $objects['paymentProcessor']['id']; | |
4466 | } | |
4467 | else { | |
4468 | $paymentProcessorId = $objects['paymentProcessor']->id; | |
4469 | } | |
4470 | } | |
4471 | ||
b929cdb4 | 4472 | $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'); |
4473 | ||
b3b7f4c5 | 4474 | $contributionParams = array_merge(array( |
b929cdb4 | 4475 | 'contribution_status_id' => $completedContributionStatusID, |
7f4ef731 | 4476 | 'source' => self::getRecurringContributionDescription($contribution, $event), |
b3b7f4c5 | 4477 | ), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1) |
4478 | )); | |
bf722049 | 4479 | $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId; |
b3b7f4c5 | 4480 | |
294cc627 | 4481 | if ($recurringContributionID) { |
4482 | $contributionParams['contribution_recur_id'] = $recurringContributionID; | |
b3b7f4c5 | 4483 | } |
7f4ef731 | 4484 | $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis')); |
4485 | ||
4486 | if (empty($contributionParams['receive_date']) && $changeDate) { | |
4487 | $contributionParams['receive_date'] = $changeDate; | |
4488 | } | |
4489 | ||
43c8d1dd | 4490 | self::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId); |
7f4ef731 | 4491 | $contributionParams['financial_type_id'] = $contribution->financial_type_id; |
db59bb73 EM |
4492 | |
4493 | if (is_numeric($memberships)) { | |
4494 | $memberships = array($objects['membership']); | |
4495 | } | |
4496 | ||
db59bb73 EM |
4497 | $values = array(); |
4498 | if (isset($input['is_email_receipt'])) { | |
4499 | $values['is_email_receipt'] = $input['is_email_receipt']; | |
4500 | } | |
b3b7f4c5 | 4501 | |
db59bb73 EM |
4502 | if ($input['component'] == 'contribute') { |
4503 | if ($contribution->contribution_page_id) { | |
7f4ef731 | 4504 | // Figure out what we gain from this. |
5602ee2b | 4505 | // Note that we may have overwritten the is_email_receipt input, fix that below. |
db59bb73 | 4506 | CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values); |
db59bb73 | 4507 | } |
294cc627 | 4508 | elseif ($recurContrib && $recurringContributionID) { |
db59bb73 EM |
4509 | $values['amount'] = $recurContrib->amount; |
4510 | $values['financial_type_id'] = $objects['contributionType']->id; | |
4511 | $values['title'] = $source = ts('Offline Recurring Contribution'); | |
db59bb73 EM |
4512 | } |
4513 | ||
5602ee2b | 4514 | if (isset($input['is_email_receipt'])) { |
4515 | // CRM-19601 - we may have overwritten this above. | |
4516 | $values['is_email_receipt'] = $input['is_email_receipt']; | |
4517 | } | |
4518 | elseif ($recurContrib && $recurringContributionID) { | |
db59bb73 EM |
4519 | //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting |
4520 | // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden. | |
4521 | $values['is_email_receipt'] = $recurContrib->is_email_receipt; | |
4522 | } | |
4523 | ||
db59bb73 | 4524 | if (!empty($memberships)) { |
db59bb73 EM |
4525 | foreach ($memberships as $membershipTypeIdKey => $membership) { |
4526 | if ($membership) { | |
4ff927bc | 4527 | $membershipParams = array( |
4528 | 'id' => $membership->id, | |
4529 | 'contact_id' => $membership->contact_id, | |
4530 | 'is_test' => $membership->is_test, | |
4531 | 'membership_type_id' => $membership->membership_type_id, | |
4532 | ); | |
db59bb73 | 4533 | |
1f7c01e4 | 4534 | $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], |
4535 | $membershipParams['membership_type_id'], | |
4536 | $membershipParams['is_test'], | |
4537 | $membershipParams['id'] | |
db59bb73 EM |
4538 | ); |
4539 | ||
4540 | // CRM-8141 update the membership type with the value recorded in log when membership created/renewed | |
4541 | // this picks up membership type changes during renewals | |
4542 | $sql = " | |
4543 | SELECT membership_type_id | |
4544 | FROM civicrm_membership_log | |
1f7c01e4 | 4545 | WHERE membership_id={$membershipParams['id']} |
db59bb73 EM |
4546 | ORDER BY id DESC |
4547 | LIMIT 1;"; | |
1f7c01e4 | 4548 | $dao = CRM_Core_DAO::executeQuery($sql); |
db59bb73 EM |
4549 | if ($dao->fetch()) { |
4550 | if (!empty($dao->membership_type_id)) { | |
1f7c01e4 | 4551 | $membershipParams['membership_type_id'] = $dao->membership_type_id; |
db59bb73 | 4552 | } |
db59bb73 | 4553 | } |
db59bb73 EM |
4554 | $dao->free(); |
4555 | ||
4ff927bc | 4556 | $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType( |
4557 | $membershipParams['membership_type_id'], | |
4558 | $primaryContributionID | |
4559 | ); | |
4b6c8c1e | 4560 | $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL); |
db59bb73 EM |
4561 | if ($currentMembership) { |
4562 | /* | |
4563 | * Fixed FOR CRM-4433 | |
4564 | * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status | |
4565 | * when Contribution mode is notify and membership is for renewal ) | |
4566 | */ | |
4567 | CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate); | |
4568 | ||
4569 | // @todo - we should pass membership_type_id instead of null here but not | |
4570 | // adding as not sure of testing | |
1f7c01e4 | 4571 | $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], |
4ff927bc | 4572 | $changeDate, NULL, $membershipParams['num_terms'] |
db59bb73 EM |
4573 | ); |
4574 | ||
1f7c01e4 | 4575 | $dates['join_date'] = $currentMembership['join_date']; |
db59bb73 | 4576 | } |
db59bb73 EM |
4577 | |
4578 | //get the status for membership. | |
4579 | $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], | |
4580 | $dates['end_date'], | |
4581 | $dates['join_date'], | |
4582 | 'today', | |
4583 | TRUE, | |
1f7c01e4 | 4584 | $membershipParams['membership_type_id'], |
4585 | $membershipParams | |
db59bb73 EM |
4586 | ); |
4587 | ||
c31bec3d | 4588 | $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New'); |
db59bb73 EM |
4589 | //we might be renewing membership, |
4590 | //so make status override false. | |
1f7c01e4 | 4591 | $membershipParams['is_override'] = FALSE; |
f8d3033b | 4592 | //CRM-17723 - reset static $relatedContactIds array() |
4593 | $var = TRUE; | |
4594 | CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE); | |
1f7c01e4 | 4595 | civicrm_api3('Membership', 'create', $membershipParams); |
b95fe31c | 4596 | //CRM-19600: Add Membership Renewal activity |
4597 | CRM_Activity_BAO_Activity::addActivity($membership, 'Membership Renewal', $membership->contact_id); | |
db59bb73 EM |
4598 | } |
4599 | } | |
db59bb73 EM |
4600 | } |
4601 | } | |
4602 | else { | |
0bad10e7 | 4603 | if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) { |
7f4ef731 | 4604 | if ($event->is_email_confirm) { |
66df7769 | 4605 | // @todo this should be set by the function that sends the mail after sending. |
4606 | $contributionParams['receipt_date'] = $changeDate; | |
4607 | } | |
4608 | $participantParams['id'] = $participant->id; | |
1c98b2d6 | 4609 | $participantParams['status_id'] = 'Registered'; |
66df7769 | 4610 | civicrm_api3('Participant', 'create', $participantParams); |
db59bb73 | 4611 | } |
db59bb73 EM |
4612 | } |
4613 | ||
b3b7f4c5 | 4614 | $contributionParams['id'] = $contribution->id; |
db59bb73 | 4615 | |
7150b1c8 | 4616 | // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem |
0e6ccb2e K |
4617 | // unsetting it here does NOT cause any other contribution test to fail! |
4618 | unset($contributionParams['financial_type_id']); | |
734d2daa | 4619 | $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams); |
db59bb73 EM |
4620 | |
4621 | // Add new soft credit against current $contribution. | |
4622 | if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) { | |
4623 | CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id); | |
4624 | } | |
4625 | ||
db59bb73 EM |
4626 | $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array( |
4627 | 'labelColumn' => 'name', | |
4628 | 'flip' => 1, | |
4629 | )); | |
43c8d1dd | 4630 | if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) { |
db59bb73 EM |
4631 | $input['payment_processor'] = $paymentProcessorId; |
4632 | } | |
db59bb73 EM |
4633 | |
4634 | if (!empty($contribution->_relatedObjects['participant'])) { | |
4635 | $input['contribution_mode'] = 'participant'; | |
4636 | $input['participant_id'] = $contribution->_relatedObjects['participant']->id; | |
db59bb73 EM |
4637 | } |
4638 | elseif (!empty($contribution->_relatedObjects['membership'])) { | |
db59bb73 | 4639 | $input['contribution_mode'] = 'membership'; |
d5580ed4 | 4640 | $contribution->contribution_status_id = $contributionParams['contribution_status_id']; |
b34861f3 | 4641 | $contribution->trxn_id = CRM_Utils_Array::value('trxn_id', $input); |
4642 | $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date); | |
db59bb73 | 4643 | } |
db59bb73 EM |
4644 | |
4645 | CRM_Core_Error::debug_log_message("Contribution record updated successfully"); | |
4646 | $transaction->commit(); | |
4647 | ||
294cc627 | 4648 | CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution->id, $recurringContributionID, |
43c8d1dd | 4649 | $contributionParams['contribution_status_id'], $input['amount']); |
db59bb73 EM |
4650 | |
4651 | // create an activity record | |
4652 | if ($input['component'] == 'contribute') { | |
4653 | //CRM-4027 | |
4654 | $targetContactID = NULL; | |
4655 | if (!empty($ids['related_contact'])) { | |
4656 | $targetContactID = $contribution->contact_id; | |
4657 | $contribution->contact_id = $ids['related_contact']; | |
4658 | } | |
4659 | CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); | |
4660 | // event | |
4661 | } | |
4662 | else { | |
4663 | CRM_Activity_BAO_Activity::addActivity($participant); | |
4664 | } | |
4665 | ||
4666 | // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending | |
4667 | // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set | |
4668 | if (!array_key_exists('is_email_receipt', $values) || | |
4669 | $values['is_email_receipt'] == 1 | |
4670 | ) { | |
ec7e3954 E |
4671 | civicrm_api3('Contribution', 'sendconfirmation', array( |
4672 | 'id' => $contribution->id, | |
4673 | 'payment_processor_id' => $paymentProcessorId, | |
4674 | )); | |
db59bb73 EM |
4675 | CRM_Core_Error::debug_log_message("Receipt sent"); |
4676 | } | |
4677 | ||
4678 | CRM_Core_Error::debug_log_message("Success: Database updated"); | |
4679 | if ($isRecurring) { | |
4680 | CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, | |
4681 | $isFirstOrLastRecurringPayment); | |
4682 | } | |
734d2daa | 4683 | return $contributionResult; |
db59bb73 EM |
4684 | } |
4685 | ||
4686 | /** | |
4687 | * Send receipt from contribution. | |
4688 | * | |
4689 | * Do not call this directly - it is being refactored. use contribution.sendmessage api call. | |
4690 | * | |
4691 | * Note that the compose message part has been moved to contribution | |
4692 | * In general LoadObjects is called first to get the objects but the composeMessageArray function now calls it. | |
4693 | * | |
4694 | * @param array $input | |
4695 | * Incoming data from Payment processor. | |
4696 | * @param array $ids | |
4697 | * Related object IDs. | |
ec7e3954 | 4698 | * @param int $contributionID |
db59bb73 EM |
4699 | * @param array $values |
4700 | * Values related to objects that have already been loaded. | |
4701 | * @param bool $recur | |
4702 | * Is it part of a recurring contribution. | |
4703 | * @param bool $returnMessageText | |
4704 | * Should text be returned instead of sent. This. | |
4705 | * is because the function is also used to generate pdfs | |
4706 | * | |
4707 | * @return array | |
ec7e3954 E |
4708 | * @throws \CRM_Core_Exception |
4709 | * @throws \CiviCRM_API3_Exception | |
db59bb73 | 4710 | */ |
ec7e3954 E |
4711 | public static function sendMail(&$input, &$ids, $contributionID, &$values, $recur = FALSE, |
4712 | $returnMessageText = FALSE) { | |
db59bb73 | 4713 | $input['is_recur'] = $recur; |
ec7e3954 E |
4714 | |
4715 | $contribution = new CRM_Contribute_BAO_Contribution(); | |
4716 | $contribution->id = $contributionID; | |
4717 | if (!$contribution->find(TRUE)) { | |
4718 | throw new CRM_Core_Exception('Contribution does not exist'); | |
4719 | } | |
4720 | $contribution->loadRelatedObjects($input, $ids, TRUE); | |
db59bb73 EM |
4721 | // set receipt from e-mail and name in value |
4722 | if (!$returnMessageText) { | |
58d8c7e2 | 4723 | $userID = CRM_Core_Session::singleton()->getLoggedInContactID(); |
db59bb73 EM |
4724 | if (!empty($userID)) { |
4725 | list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID); | |
4726 | $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $input, $userEmail); | |
4727 | $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $input, $userName); | |
4728 | } | |
4729 | } | |
76e8d9c4 E |
4730 | |
4731 | $return = $contribution->composeMessageArray($input, $ids, $values, $recur, $returnMessageText); | |
cc7b912f | 4732 | // Contribution ID should really always be set. But ? |
76e8d9c4 | 4733 | if (!$returnMessageText && (!isset($input['receipt_update']) || $input['receipt_update']) && empty($contribution->receipt_date)) { |
cc7b912f | 4734 | civicrm_api3('Contribution', 'create', array('receipt_date' => 'now', 'id' => $contribution->id)); |
4735 | } | |
76e8d9c4 | 4736 | return $return; |
db59bb73 EM |
4737 | } |
4738 | ||
1844808f GC |
4739 | /** |
4740 | * Generate credit note id with next avaible number | |
4741 | * | |
1844808f GC |
4742 | * @return string |
4743 | * Credit Note Id. | |
4744 | */ | |
4add5adb | 4745 | public static function createCreditNoteId() { |
aaffa79f | 4746 | $prefixValue = Civi::settings()->get('contribution_invoice_settings'); |
1844808f | 4747 | |
8d20d89c | 4748 | $creditNoteNum = CRM_Core_DAO::singleValueQuery("SELECT count(creditnote_id) as creditnote_number FROM civicrm_contribution"); |
1844808f GC |
4749 | $creditNoteId = NULL; |
4750 | ||
4751 | do { | |
4752 | $creditNoteNum++; | |
4753 | $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $creditNoteNum; | |
4754 | $result = civicrm_api3('Contribution', 'getcount', array( | |
4755 | 'sequential' => 1, | |
4756 | 'creditnote_id' => $creditNoteId, | |
4757 | )); | |
4758 | } while ($result > 0); | |
4759 | ||
1844808f GC |
4760 | return $creditNoteId; |
4761 | } | |
4762 | ||
4ae9c8ac | 4763 | /** |
4764 | * Load related memberships. | |
4765 | * | |
4766 | * Note that in theory it should be possible to retrieve these from the line_item table | |
4767 | * with the membership_payment table being deprecated. Attempting to do this here causes tests to fail | |
4768 | * as it seems the api is not correctly linking the line items when the contribution is created in the flow | |
4769 | * where the contribution is created in the API, followed by the membership (using the api) followed by the membership | |
4770 | * payment. The membership payment BAO does have code to address this but it doesn't appear to be working. | |
4771 | * | |
4772 | * I don't know if it never worked or broke as a result of https://issues.civicrm.org/jira/browse/CRM-14918. | |
4773 | * | |
4774 | * @param array $ids | |
4775 | * | |
4776 | * @throws Exception | |
4777 | */ | |
4778 | public function loadRelatedMembershipObjects(&$ids) { | |
4779 | $query = " | |
4780 | SELECT membership_id | |
4781 | FROM civicrm_membership_payment | |
4782 | WHERE contribution_id = %1 "; | |
4783 | $params = array(1 => array($this->id, 'Integer')); | |
356bfcaf | 4784 | $ids['membership'] = (array) CRM_Utils_Array::value('membership', $ids, array()); |
4ae9c8ac | 4785 | |
4786 | $dao = CRM_Core_DAO::executeQuery($query, $params); | |
4787 | while ($dao->fetch()) { | |
356bfcaf | 4788 | if ($dao->membership_id && !in_array($dao->membership_id, $ids['membership'])) { |
4789 | $ids['membership'][$dao->membership_id] = $dao->membership_id; | |
4ae9c8ac | 4790 | } |
4791 | } | |
4792 | ||
4793 | if (array_key_exists('membership', $ids) && is_array($ids['membership'])) { | |
4794 | foreach ($ids['membership'] as $id) { | |
4795 | if (!empty($id)) { | |
4796 | $membership = new CRM_Member_BAO_Membership(); | |
4797 | $membership->id = $id; | |
4798 | if (!$membership->find(TRUE)) { | |
4799 | throw new Exception("Could not find membership record: $id"); | |
4800 | } | |
4801 | $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date); | |
4802 | $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date); | |
4803 | $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date); | |
4804 | $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership; | |
4805 | $membership->free(); | |
4806 | } | |
4807 | } | |
4808 | } | |
4809 | } | |
4810 | ||
6b18d1bd PN |
4811 | /** |
4812 | * This function is used to record partial payments for contribution | |
4813 | * | |
4814 | * @param array $contribution | |
4815 | * | |
4816 | * @param array $params | |
4817 | * | |
4818 | * @return object | |
4819 | */ | |
4820 | public static function recordPartialPayment($contribution, $params) { | |
4821 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); | |
4822 | $pendingStatus = array( | |
4823 | array_search('Pending', $contributionStatuses), | |
4824 | array_search('In Progress', $contributionStatuses), | |
4825 | ); | |
4826 | $statusId = array_search('Completed', $contributionStatuses); | |
4827 | if (in_array(CRM_Utils_Array::value('contribution_status_id', $contribution), $pendingStatus)) { | |
4828 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); | |
4829 | $balanceTrxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($contribution['financial_type_id'], $relationTypeId); | |
4830 | } | |
4831 | elseif (!empty($params['payment_processor'])) { | |
4832 | $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getFinancialAccount($contribution['payment_processor'], 'civicrm_payment_processor', 'financial_account_id'); | |
4833 | } | |
4834 | elseif (!empty($params['payment_instrument_id'])) { | |
4835 | $balanceTrxnParams['to_financial_account_id'] = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount($contribution['payment_instrument_id']); | |
4836 | } | |
4837 | else { | |
4838 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('financial_account_type', NULL, " AND v.name LIKE 'Asset' ")); | |
4839 | $queryParams = array(1 => array($relationTypeId, 'Integer')); | |
4840 | $balanceTrxnParams['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); | |
4841 | } | |
4842 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); | |
4843 | $fromFinancialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($contribution['financial_type_id'], $relationTypeId); | |
4844 | $balanceTrxnParams['from_financial_account_id'] = $fromFinancialAccountId; | |
4845 | $balanceTrxnParams['total_amount'] = $params['total_amount']; | |
4846 | $balanceTrxnParams['contribution_id'] = $params['contribution_id']; | |
4847 | $balanceTrxnParams['trxn_date'] = !empty($params['contribution_receive_date']) ? $params['contribution_receive_date'] : date('YmdHis'); | |
4848 | $balanceTrxnParams['fee_amount'] = CRM_Utils_Array::value('fee_amount', $params); | |
4849 | $balanceTrxnParams['net_amount'] = CRM_Utils_Array::value('total_amount', $params); | |
4850 | $balanceTrxnParams['currency'] = $contribution['currency']; | |
4851 | $balanceTrxnParams['trxn_id'] = CRM_Utils_Array::value('contribution_trxn_id', $params, NULL); | |
4852 | $balanceTrxnParams['status_id'] = $statusId; | |
4853 | $balanceTrxnParams['payment_instrument_id'] = CRM_Utils_Array::value('payment_instrument_id', $params, $contribution['payment_instrument_id']); | |
4854 | $balanceTrxnParams['check_number'] = CRM_Utils_Array::value('check_number', $params); | |
4855 | if ($fromFinancialAccountId != NULL && | |
4856 | ($statusId == array_search('Completed', $contributionStatuses) || $statusId == array_search('Partially paid', $contributionStatuses)) | |
4857 | ) { | |
4858 | $balanceTrxnParams['is_payment'] = 1; | |
4859 | } | |
4860 | if (!empty($params['payment_processor'])) { | |
4861 | $balanceTrxnParams['payment_processor_id'] = $params['payment_processor']; | |
4862 | } | |
4863 | return CRM_Core_BAO_FinancialTrxn::create($balanceTrxnParams); | |
4864 | } | |
4865 | ||
7f4ef731 | 4866 | /** |
467fe956 | 4867 | * Get the description (source field) for the recurring contribution. |
4868 | * | |
4869 | * @param CRM_Contribute_BAO_Contribution $contribution | |
4870 | * @param CRM_Event_DAO_Event|null $event | |
4871 | * | |
4872 | * @return array | |
4873 | * @throws \CiviCRM_API3_Exception | |
4874 | */ | |
7f4ef731 | 4875 | protected static function getRecurringContributionDescription($contribution, $event) { |
6046ccbb | 4876 | if (!empty($contribution->source)) { |
7b9947fb ML |
4877 | return $contribution->source; |
4878 | } | |
4052b01e | 4879 | elseif (!empty($contribution->contribution_page_id) && is_numeric($contribution->contribution_page_id)) { |
7f4ef731 | 4880 | $contributionPageTitle = civicrm_api3('ContributionPage', 'getvalue', array( |
4881 | 'id' => $contribution->contribution_page_id, | |
4882 | 'return' => 'title', | |
4883 | )); | |
4884 | return ts('Online Contribution') . ': ' . $contributionPageTitle; | |
4885 | } | |
467fe956 | 4886 | elseif ($event) { |
7f4ef731 | 4887 | return ts('Online Event Registration') . ': ' . $event->title; |
4888 | } | |
bef53ccf | 4889 | elseif (!empty($contribution->contribution_recur_id)) { |
4890 | return 'recurring contribution'; | |
4891 | } | |
4892 | return ''; | |
7f4ef731 | 4893 | } |
4894 | ||
0618910b PN |
4895 | /** |
4896 | * Function to add payments for contribution | |
4897 | * for Partially Paid status | |
4898 | * | |
0618910b | 4899 | * @param array $contributions |
958a4abe | 4900 | * @param array $contributionStatusId |
0618910b PN |
4901 | * |
4902 | */ | |
955ee56e | 4903 | public static function addPayments($contributions, $contributionStatusId = NULL) { |
e4ba8498 | 4904 | // get financial trxn which is a payment |
57dcb94e | 4905 | $ftSql = "SELECT ft.id, ft.total_amount |
b34861f3 | 4906 | FROM civicrm_financial_trxn ft |
0618910b | 4907 | INNER JOIN civicrm_entity_financial_trxn eft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_contribution' |
57dcb94e | 4908 | WHERE eft.entity_id = %1 AND ft.is_payment = 1 ORDER BY ft.id DESC LIMIT 1"; |
e8403178 PN |
4909 | $contributionStatus = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array( |
4910 | 'labelColumn' => 'name', | |
4911 | )); | |
69ea45f2 | 4912 | foreach ($contributions as $k => $contribution) { |
e8403178 | 4913 | if (!($contributionStatus[$contribution->contribution_status_id] == 'Partially paid' |
958a4abe | 4914 | || CRM_Utils_Array::value($contributionStatusId, $contributionStatus) == 'Partially paid') |
e8403178 | 4915 | ) { |
69ea45f2 PN |
4916 | continue; |
4917 | } | |
57dcb94e | 4918 | $ftDao = CRM_Core_DAO::executeQuery($ftSql, array(1 => array($contribution->id, 'Integer'))); |
2a21b19d | 4919 | $ftDao->fetch(); |
2a21b19d | 4920 | |
955ee56e PN |
4921 | // store financial item Proportionaly. |
4922 | $trxnParams = array( | |
4923 | 'total_amount' => $ftDao->total_amount, | |
4924 | 'contribution_id' => $contribution->id, | |
dea99e05 | 4925 | ); |
955ee56e | 4926 | self::assignProportionalLineItems($trxnParams, $ftDao->id, $contribution->total_amount); |
0618910b PN |
4927 | } |
4928 | } | |
4929 | ||
27d9f6c5 | 4930 | /** |
1b7fd6d4 | 4931 | * Function use to store line item proportionaly in |
27d9f6c5 PN |
4932 | * in entity financial trxn table |
4933 | * | |
955ee56e | 4934 | * @param array $trxnParams |
8de1ade9 PN |
4935 | * |
4936 | * @param Integer $trxnId | |
4937 | * | |
4938 | * @param float $contributionTotalAmount | |
27d9f6c5 PN |
4939 | * |
4940 | */ | |
955ee56e PN |
4941 | public static function assignProportionalLineItems($trxnParams, $trxnId, $contributionTotalAmount) { |
4942 | $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($trxnParams['contribution_id']); | |
27d9f6c5 PN |
4943 | if (!empty($lineItems)) { |
4944 | // get financial item | |
4945 | $sql = "SELECT fi.id, li.price_field_value_id | |
4946 | FROM civicrm_financial_item fi | |
fa7a1ebd | 4947 | INNER JOIN civicrm_line_item li ON li.id = fi.entity_id and fi.entity_table = 'civicrm_line_item' |
27d9f6c5 | 4948 | WHERE li.contribution_id = %1"; |
955ee56e | 4949 | $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($trxnParams['contribution_id'], 'Integer'))); |
27d9f6c5 PN |
4950 | while ($dao->fetch()) { |
4951 | $ftIds[$dao->price_field_value_id] = $dao->id; | |
4952 | } | |
3e00a301 PN |
4953 | $eftParams = array( |
4954 | 'entity_table' => 'civicrm_financial_item', | |
8de1ade9 | 4955 | 'financial_trxn_id' => $trxnId, |
3e00a301 | 4956 | ); |
27d9f6c5 | 4957 | foreach ($lineItems as $key => $value) { |
955ee56e PN |
4958 | if ($value['qty'] == 0) { |
4959 | continue; | |
4960 | } | |
4961 | $paid = $value['line_total'] * ($trxnParams['total_amount'] / $contributionTotalAmount); | |
27d9f6c5 | 4962 | // Record Entity Financial Trxn |
9b1d8402 | 4963 | $eftParams['amount'] = round($paid, 2); |
3e00a301 PN |
4964 | $eftParams['entity_id'] = $ftIds[$value['price_field_value_id']]; |
4965 | ||
4966 | civicrm_api3('EntityFinancialTrxn', 'create', $eftParams); | |
27d9f6c5 PN |
4967 | } |
4968 | } | |
4969 | } | |
4970 | ||
5c8b902b | 4971 | /** |
4106ce71 | 4972 | * Function to check line items |
5c8b902b PN |
4973 | * |
4974 | * @param array $params | |
4975 | * array of order params. | |
4976 | * | |
5c8b902b PN |
4977 | */ |
4978 | public static function checkLineItems(&$params) { | |
4979 | $totalAmount = CRM_Utils_Array::value('total_amount', $params); | |
4980 | $lineItemAmount = 0; | |
4981 | foreach ($params['line_items'] as &$lineItems) { | |
4982 | foreach ($lineItems['line_item'] as &$item) { | |
4983 | if (empty($item['financial_type_id'])) { | |
4984 | $item['financial_type_id'] = $params['financial_type_id']; | |
4985 | } | |
4986 | $lineItemAmount += $item['line_total']; | |
4987 | } | |
4988 | } | |
4989 | if (!isset($totalAmount)) { | |
4990 | $params['total_amount'] = $lineItemAmount; | |
4991 | } | |
4992 | elseif ($totalAmount != $lineItemAmount) { | |
af004c04 | 4993 | throw new API_Exception("Line item total doesn't match with total amount."); |
5c8b902b | 4994 | } |
5c8b902b PN |
4995 | } |
4996 | ||
bf2cf926 | 4997 | /** |
4998 | * Get the financial account for the item associated with the new transaction. | |
4999 | * | |
5000 | * @param array $params | |
5001 | * @param CRM_Financial_BAO_FinancialItem $prevFinancialItem | |
5002 | * | |
5003 | * @return int | |
5004 | */ | |
5005 | public static function getFinancialAccountForStatusChangeTrxn($params, $prevFinancialItem) { | |
5006 | ||
5007 | if (!empty($params['financial_account_id'])) { | |
5008 | return $params['financial_account_id']; | |
5009 | } | |
5010 | $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus($params['contribution_status_id'], 'name'); | |
5011 | $preferredAccountsRelationships = array( | |
5012 | 'Refunded' => 'Credit/Contra Revenue Account is', | |
5013 | 'Chargeback' => 'Chargeback Account is', | |
5014 | ); | |
5015 | if (in_array($contributionStatus, array_keys($preferredAccountsRelationships))) { | |
5016 | $financialTypeID = !empty($params['financial_type_id']) ? $params['financial_type_id'] : $params['prevContribution']->financial_type_id; | |
5017 | return CRM_Financial_BAO_FinancialAccount::getFinancialAccountForFinancialTypeByRelationship( | |
5018 | $financialTypeID, | |
5019 | $preferredAccountsRelationships[$contributionStatus] | |
5020 | ); | |
5021 | } | |
5022 | return $prevFinancialItem->financial_account_id; | |
5023 | } | |
5024 | ||
f99a6f98 | 5025 | /** |
5026 | * ContributionPage values were being imposed onto values. | |
5027 | * | |
5028 | * I have made this explicit and removed the couple (is_recur, is_pay_later) we | |
5029 | * REALLY didn't want superimposed. The rest are left there in their overkill out | |
5030 | * of cautiousness. | |
5031 | * | |
5032 | * The rationale for making this explicit is that it was a case of carefully set values being | |
5033 | * seemingly randonly overwritten without much care. In general I think array randomly setting | |
5034 | * variables en mass is risky. | |
5035 | * | |
5036 | * @param array $values | |
5037 | * | |
5038 | * @return array | |
5039 | */ | |
5040 | protected function addContributionPageValuesToValuesHeavyHandedly(&$values) { | |
5041 | $contributionPageValues = array(); | |
5042 | CRM_Contribute_BAO_ContributionPage::setValues( | |
5043 | $this->contribution_page_id, | |
5044 | $contributionPageValues | |
5045 | ); | |
5046 | $valuesToCopy = array( | |
5047 | // These are the values that I believe to be useful. | |
e4dcb541 | 5048 | 'id', |
f99a6f98 | 5049 | 'title', |
5050 | 'is_email_receipt', | |
5051 | 'pay_later_receipt', | |
5052 | 'pay_later_text', | |
5053 | 'receipt_from_email', | |
5054 | 'receipt_from_name', | |
5055 | 'receipt_text', | |
ee1dffa7 | 5056 | 'custom_pre_id', |
f99a6f98 | 5057 | 'custom_post_id', |
5058 | 'honoree_profile_id', | |
5059 | 'onbehalf_profile_id', | |
ee1dffa7 | 5060 | 'honor_block_is_active', |
f99a6f98 | 5061 | // Kinda might be - but would be on the contribution... |
5062 | 'campaign_id', | |
5063 | 'currency', | |
5064 | // Included for 'fear of regression' but can't justify any use for these.... | |
5065 | 'intro_text', | |
5066 | 'payment_processor', | |
5067 | 'financial_type_id', | |
5068 | 'amount_block_is_active', | |
5069 | 'bcc_receipt', | |
5070 | 'cc_receipt', | |
5071 | 'created_date', | |
5072 | 'created_id', | |
5073 | 'default_amount_id', | |
5074 | 'end_date', | |
5075 | 'footer_text', | |
5076 | 'goal_amount', | |
5077 | 'initial_amount_help_text', | |
5078 | 'initial_amount_label', | |
5079 | 'intro_text', | |
5080 | 'is_allow_other_amount', | |
5081 | 'is_billing_required', | |
5082 | 'is_confirm_enabled', | |
5083 | 'is_credit_card_only', | |
5084 | 'is_monetary', | |
5085 | 'is_partial_payment', | |
5086 | 'is_recur_installments', | |
5087 | 'is_recur_interval', | |
5088 | 'is_share', | |
5089 | 'max_amount', | |
5090 | 'min_amount', | |
5091 | 'min_initial_amount', | |
5092 | 'recur_frequency_unit', | |
5093 | 'start_date', | |
5094 | 'thankyou_footer', | |
5095 | 'thankyou_text', | |
5096 | 'thankyou_title', | |
5097 | ||
5098 | ); | |
5099 | foreach ($valuesToCopy as $valueToCopy) { | |
5100 | if (isset($contributionPageValues[$valueToCopy])) { | |
5101 | $values[$valueToCopy] = $contributionPageValues[$valueToCopy]; | |
5102 | } | |
5103 | } | |
5104 | return $values; | |
5105 | } | |
5106 | ||
ce7fc91a PN |
5107 | /** |
5108 | * Get values of CiviContribute Settings | |
5109 | * and check if its enabled or not. | |
756661dc PN |
5110 | * Note: The CiviContribute settings are stored as single entry in civicrm_setting |
5111 | * in serialized form. Usually this should be stored as flat settings for each form fields | |
5112 | * as per CiviCRM standards. Since this would take more effort to change the current behaviour of CiviContribute | |
5113 | * settings we will live with an inconsistency because it's too hard to change for now. | |
5114 | * https://github.com/civicrm/civicrm-core/pull/8562#issuecomment-227874245 | |
ce7fc91a PN |
5115 | * |
5116 | * | |
5117 | * @param string $name | |
5118 | * @return string | |
5119 | * | |
5120 | */ | |
5121 | public static function checkContributeSettings($name = NULL) { | |
5122 | $contributeSettings = Civi::settings()->get('contribution_invoice_settings'); | |
5123 | ||
5124 | if ($name) { | |
5125 | return CRM_Utils_Array::value($name, $contributeSettings); | |
5126 | } | |
5127 | return $contributeSettings; | |
5128 | } | |
5129 | ||
643413a0 | 5130 | /** |
5131 | * This function process contribution related objects. | |
5132 | * | |
5133 | * @param int $contributionId | |
5134 | * @param int $statusId | |
5135 | * @param int|null $previousStatusId | |
5136 | * | |
5137 | * @param string $receiveDate | |
5138 | * | |
5139 | * @return null|string | |
5140 | */ | |
5141 | public static function transitionComponentWithReturnMessage($contributionId, $statusId, $previousStatusId = NULL, $receiveDate = NULL) { | |
5142 | $statusMsg = NULL; | |
5143 | if (!$contributionId || !$statusId) { | |
5144 | return $statusMsg; | |
5145 | } | |
5146 | ||
5147 | $params = array( | |
5148 | 'contribution_id' => $contributionId, | |
5149 | 'contribution_status_id' => $statusId, | |
5150 | 'previous_contribution_status_id' => $previousStatusId, | |
5151 | 'receive_date' => $receiveDate, | |
5152 | ); | |
5153 | ||
5154 | $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params); | |
5155 | ||
5156 | if (!is_array($updateResult) || | |
5157 | !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) || | |
5158 | !is_array($updatedComponents) || | |
5159 | empty($updatedComponents) | |
5160 | ) { | |
5161 | return $statusMsg; | |
5162 | } | |
5163 | ||
5164 | // get the user display name. | |
5165 | $sql = " | |
5166 | SELECT display_name as displayName | |
5167 | FROM civicrm_contact | |
5168 | LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id ) | |
5169 | WHERE civicrm_contribution.id = {$contributionId}"; | |
5170 | $userDisplayName = CRM_Core_DAO::singleValueQuery($sql); | |
5171 | ||
5172 | // get the status message for user. | |
5173 | foreach ($updatedComponents as $componentName => $updatedStatusId) { | |
5174 | ||
5175 | if ($componentName == 'CiviMember') { | |
5176 | $updatedStatusName = CRM_Utils_Array::value($updatedStatusId, | |
5177 | CRM_Member_PseudoConstant::membershipStatus() | |
5178 | ); | |
5179 | if ($updatedStatusName == 'Cancelled') { | |
5180 | $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName)); | |
5181 | } | |
5182 | elseif ($updatedStatusName == 'Expired') { | |
5183 | $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName)); | |
5184 | } | |
5185 | else { | |
5186 | $endDate = CRM_Utils_Array::value('membership_end_date', $updateResult); | |
5187 | if ($endDate) { | |
5188 | $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.", | |
5189 | array( | |
5190 | 1 => $userDisplayName, | |
5191 | 2 => $endDate, | |
5192 | ) | |
5193 | ); | |
5194 | } | |
5195 | } | |
5196 | } | |
5197 | ||
5198 | if ($componentName == 'CiviEvent') { | |
5199 | $updatedStatusName = CRM_Utils_Array::value($updatedStatusId, | |
5200 | CRM_Event_PseudoConstant::participantStatus() | |
5201 | ); | |
5202 | if ($updatedStatusName == 'Cancelled') { | |
5203 | $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName)); | |
5204 | } | |
5205 | elseif ($updatedStatusName == 'Registered') { | |
5206 | $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName)); | |
5207 | } | |
5208 | } | |
5209 | ||
5210 | if ($componentName == 'CiviPledge') { | |
5211 | $updatedStatusName = CRM_Utils_Array::value($updatedStatusId, | |
5212 | CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name') | |
5213 | ); | |
5214 | if ($updatedStatusName == 'Cancelled') { | |
5215 | $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName)); | |
5216 | } | |
5217 | elseif ($updatedStatusName == 'Failed') { | |
5218 | $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName)); | |
5219 | } | |
5220 | elseif ($updatedStatusName == 'Completed') { | |
5221 | $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName)); | |
5222 | } | |
5223 | } | |
5224 | } | |
5225 | ||
5226 | return $statusMsg; | |
5227 | } | |
5228 | ||
2912ed09 | 5229 | /** |
5230 | * Get the contribution as it is in the database before being updated. | |
5231 | * | |
5232 | * @param int $contributionID | |
5233 | * | |
5234 | * @return array | |
5235 | */ | |
5236 | private static function getOriginalContribution($contributionID) { | |
5237 | return self::getValues(array('id' => $contributionID), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); | |
5238 | } | |
5239 | ||
94183dd6 SL |
5240 | /** |
5241 | * Assign Test Value. | |
5242 | * | |
5243 | * @param string $fieldName | |
5244 | * @param array $fieldDef | |
5245 | * @param int $counter | |
5246 | */ | |
5247 | protected function assignTestValue($fieldName, &$fieldDef, $counter) { | |
5248 | if ($fieldName == 'tax_amount') { | |
5249 | $this->{$fieldName} = "0.00"; | |
5250 | } | |
5251 | elseif ($fieldName == 'net_amount') { | |
5252 | $this->{$fieldName} = "2.00"; | |
5253 | } | |
5254 | elseif ($fieldName == 'total_amount') { | |
5255 | $this->{$fieldName} = "3.00"; | |
5256 | } | |
5257 | elseif ($fieldName == 'fee_amount') { | |
5258 | $this->{$fieldName} = "1.00"; | |
5259 | } | |
5260 | else { | |
5261 | parent::assignTestValues($fieldName, $fieldDef, $counter); | |
5262 | } | |
5263 | } | |
5264 | ||
623712fb PN |
5265 | /** |
5266 | * Check if contribution has participant/membership payment. | |
5267 | * | |
5268 | * @param int $contributionId | |
5269 | * Contribution ID | |
5270 | * | |
5271 | * @return bool | |
5272 | */ | |
5273 | public static function allowUpdateRevenueRecognitionDate($contributionId) { | |
5274 | // get line item for contribution | |
77dbdcbc | 5275 | $lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contributionId); |
623712fb PN |
5276 | // check if line item is for membership or participant |
5277 | foreach ($lineItems as $items) { | |
5278 | if ($items['entity_table'] == 'civicrm_participant') { | |
6f148218 | 5279 | $flag = FALSE; |
623712fb PN |
5280 | break; |
5281 | } | |
5282 | elseif ($items['entity_table'] == 'civicrm_membership') { | |
6f148218 | 5283 | $flag = FALSE; |
623712fb PN |
5284 | } |
5285 | else { | |
6f148218 | 5286 | $flag = TRUE; |
623712fb PN |
5287 | break; |
5288 | } | |
5289 | } | |
5290 | return $flag; | |
5291 | } | |
5292 | ||
14b1ab0c PN |
5293 | /** |
5294 | * Create Accounts Receivable financial trxn entry for Completed Contribution. | |
5295 | * | |
9c472292 PN |
5296 | * @param array $trxnParams |
5297 | * Financial trxn params | |
5298 | * @param string $contributionParams | |
5299 | * Contribution Params | |
a9c48769 | 5300 | * |
9c472292 | 5301 | * @return string |
14b1ab0c | 5302 | */ |
9c472292 | 5303 | public static function recordAlwaysAccountsReceivable(&$trxnParams, $contributionParams) { |
14b1ab0c PN |
5304 | if (!self::checkContributeSettings('always_post_to_accounts_receivable')) { |
5305 | return NULL; | |
5306 | } | |
9c472292 | 5307 | $statusId = $contributionParams['contribution']->contribution_status_id; |
14b1ab0c | 5308 | $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); |
a9c48769 | 5309 | $contributionStatus = empty($statusId) ? NULL : $contributionStatuses[$statusId]; |
352cae98 | 5310 | $previousContributionStatus = empty($contributionParams['prevContribution']) ? NULL : $contributionStatuses[$contributionParams['prevContribution']->contribution_status_id]; |
14b1ab0c | 5311 | // Return if contribution status is not completed. |
352cae98 PN |
5312 | if (!($contributionStatus == 'Completed' && (empty($previousContributionStatus) |
5313 | || (!empty($previousContributionStatus) && $previousContributionStatus == 'Pending' | |
5314 | && $contributionParams['prevContribution']->is_pay_later == 0 | |
5315 | ))) | |
5316 | ) { | |
14b1ab0c PN |
5317 | return NULL; |
5318 | } | |
352cae98 | 5319 | |
9c472292 PN |
5320 | $params = $trxnParams; |
5321 | $financialTypeID = CRM_Utils_Array::value('financial_type_id', $contributionParams) ? $contributionParams['financial_type_id'] : $contributionParams['prevContribution']->financial_type_id; | |
5322 | $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' ")); | |
5323 | $arAccountId = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeID, $relationTypeId); | |
5324 | $params['to_financial_account_id'] = $arAccountId; | |
5325 | $params['status_id'] = array_search('Pending', $contributionStatuses); | |
5326 | $params['is_payment'] = FALSE; | |
5327 | $trxn = CRM_Core_BAO_FinancialTrxn::create($params); | |
5328 | self::$_trxnIDs[] = $trxn->id; | |
5329 | $trxnParams['from_financial_account_id'] = $params['to_financial_account_id']; | |
14b1ab0c PN |
5330 | } |
5331 | ||
d9553c2e PN |
5332 | /** |
5333 | * Calculate financial item amount when contribution is updated. | |
5334 | * | |
5335 | * @param array $params | |
5336 | * contribution params | |
5337 | * @param array $amountParams | |
5338 | * | |
5339 | * @param string $context | |
5340 | * | |
5341 | * @return float | |
5342 | */ | |
5343 | public static function calculateFinancialItemAmount($params, $amountParams, $context) { | |
5344 | if (!empty($params['is_quick_config'])) { | |
5345 | $amount = $amountParams['item_amount']; | |
5346 | if (!$amount) { | |
5347 | $amount = $params['total_amount']; | |
5348 | if ($context === NULL) { | |
5349 | $amount -= CRM_Utils_Array::value('tax_amount', $params, 0); | |
5350 | } | |
5351 | } | |
5352 | } | |
5353 | else { | |
5354 | $amount = $amountParams['line_total']; | |
5355 | if ($context == 'changedAmount') { | |
5356 | $amount -= $amountParams['previous_line_total']; | |
5357 | } | |
5358 | $amount *= $amountParams['diff']; | |
5359 | } | |
5360 | return $amount; | |
5361 | } | |
5362 | ||
5ce9cbe9 | 5363 | } |