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