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