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