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