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