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