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