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