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