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