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