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