Merge pull request #3614 from eileenmcnaughton/CRM-14951
[civicrm-core.git] / CRM / Contribute / Form / AbstractEditPayment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 usefusul, 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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * This class generates form components for processing a contribution
38 *
39 */
40 class CRM_Contribute_Form_AbstractEditPayment extends CRM_Core_Form {
41 public $_mode;
42
43 public $_action;
44
45 public $_bltID;
46
47 public $_fields;
48
49 public $_paymentProcessor;
50 public $_recurPaymentProcessors;
51
52 public $_processors;
53
54 /**
55 * the id of the contribution that we are proceessing
56 *
57 * @var int
58 * @public
59 */
60 public $_id;
61
62 /**
63 * the id of the premium that we are proceessing
64 *
65 * @var int
66 * @public
67 */
68 public $_premiumID = NULL;
69
70 /**
71 * @var CRM_Contribute_DAO_ContributionProduct
72 */
73 public $_productDAO = NULL;
74
75 /**
76 * the id of the note
77 *
78 * @var int
79 * @public
80 */
81 public $_noteID;
82
83 /**
84 * the id of the contact associated with this contribution
85 *
86 * @var int
87 * @public
88 */
89 public $_contactID;
90
91 /**
92 * the id of the pledge payment that we are processing
93 *
94 * @var int
95 * @public
96 */
97 public $_ppID;
98
99 /**
100 * the id of the pledge that we are processing
101 *
102 * @var int
103 * @public
104 */
105 public $_pledgeID;
106
107 /**
108 * is this contribution associated with an online
109 * financial transaction
110 *
111 * @var boolean
112 * @public
113 */
114 public $_online = FALSE;
115
116 /**
117 * Stores all product option
118 *
119 * @var array
120 * @public
121 */
122 public $_options;
123
124 /**
125 * stores the honor id
126 *
127 * @var int
128 * @public
129 */
130 public $_honorID = NULL;
131
132 /**
133 * Store the contribution Type ID
134 *
135 * @var array
136 */
137 public $_contributionType;
138
139 /**
140 * The contribution values if an existing contribution
141 */
142 public $_values;
143
144 /**
145 * The pledge values if this contribution is associated with pledge
146 */
147 public $_pledgeValues;
148
149 public $_contributeMode = 'direct';
150
151 public $_context;
152
153 public $_compId;
154
155 /*
156 * Store the line items if price set used.
157 */
158 public $_lineItems;
159
160 protected $_formType;
161 protected $_cdType;
162
163 /**
164 * @param $id
165 */
166 public function showRecordLinkMesssage($id) {
167 $statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $id, 'contribution_status_id');
168 if (CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name') == 'Partially paid') {
169 if ($pid = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'participant_id', 'contribution_id')) {
170 $recordPaymentLink = CRM_Utils_System::url('civicrm/payment',
171 "reset=1&id={$pid}&cid={$this->_contactID}&action=add&component=event"
172 );
173 CRM_Core_Session::setStatus(ts('Please use the <a href="%1">Record Payment</a> form if you have received an additional payment for this Partially paid contribution record.', array(1 => $recordPaymentLink)), ts('Notice'), 'alert');
174 }
175 }
176 }
177
178 /**
179 * @param $id
180 * @param $values
181 */
182 public function buildValuesAndAssignOnline_Note_Type($id, &$values) {
183 $ids = array();
184 $params = array('id' => $id);
185 CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
186
187 //Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
188 $this->_online = FALSE;
189 $fids = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($id);
190 if (!empty($fids['financialTrxnId'])) {
191 $this->_online = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
192 }
193
194 // Also don't allow user to update some fields for recurring contributions.
195 if (!$this->_online) {
196 $this->_online = CRM_Utils_Array::value('contribution_recur_id', $values);
197 }
198
199 $this->assign('isOnline', $this->_online ? TRUE : FALSE);
200
201 //to get note id
202 $daoNote = new CRM_Core_BAO_Note();
203 $daoNote->entity_table = 'civicrm_contribution';
204 $daoNote->entity_id = $id;
205 if ($daoNote->find(TRUE)) {
206 $this->_noteID = $daoNote->id;
207 $values['note'] = $daoNote->note;
208 }
209 $this->_contributionType = $values['financial_type_id'];
210 }
211
212 /**
213 * @param string $type eg 'Contribution'
214 * @param string $subType
215 * @param int $entityId
216 */
217 public function applyCustomData($type, $subType, $entityId) {
218 $this->set('type', $type);
219 $this->set('subType', $subType);
220 $this->set('entityId', $entityId);
221
222 CRM_Custom_Form_CustomData::preProcess($this, NULL, $subType, 1, $type, $entityId);
223 CRM_Custom_Form_CustomData::buildQuickForm($this);
224 CRM_Custom_Form_CustomData::setDefaultValues($this);
225 }
226
227 /**
228 * @param $id
229 * @todo - this function is a long way, non standard of saying $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->id = $id; $dao->find();
230 */
231 public function assignPremiumProduct($id) { //to get Premium id
232 $sql = "
233 SELECT *
234 FROM civicrm_contribution_product
235 WHERE contribution_id = {$id}
236 ";
237 $dao = CRM_Core_DAO::executeQuery($sql,
238 CRM_Core_DAO::$_nullArray
239 );
240 if ($dao->fetch()) {
241 $this->_premiumID = $dao->id;
242 $this->_productDAO = $dao;
243 }
244 $dao->free();
245 }
246
247 /**
248 * This function process contribution related objects.
249 */
250 protected function updateRelatedComponent($contributionId, $statusId, $previousStatusId = NULL) {
251 $statusMsg = NULL;
252 if (!$contributionId || !$statusId) {
253 return $statusMsg;
254 }
255
256 $params = array(
257 'contribution_id' => $contributionId,
258 'contribution_status_id' => $statusId,
259 'previous_contribution_status_id' => $previousStatusId,
260 );
261
262 $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params);
263
264 if (!is_array($updateResult) ||
265 !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) ||
266 !is_array($updatedComponents) ||
267 empty($updatedComponents)
268 ) {
269 return $statusMsg;
270 }
271
272 // get the user display name.
273 $sql = "
274 SELECT display_name as displayName
275 FROM civicrm_contact
276 LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
277 WHERE civicrm_contribution.id = {$contributionId}";
278 $userDisplayName = CRM_Core_DAO::singleValueQuery($sql);
279
280 // get the status message for user.
281 foreach ($updatedComponents as $componentName => $updatedStatusId) {
282
283 if ($componentName == 'CiviMember') {
284 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
285 CRM_Member_PseudoConstant::membershipStatus()
286 );
287 if ($updatedStatusName == 'Cancelled') {
288 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
289 }
290 elseif ($updatedStatusName == 'Expired') {
291 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
292 }
293 else {
294 $endDate = CRM_Utils_Array::value('membership_end_date', $updateResult);
295 if ($endDate) {
296 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
297 array(
298 1 => $userDisplayName,
299 2 => $endDate
300 )
301 );
302 }
303 }
304 }
305
306 if ($componentName == 'CiviEvent') {
307 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
308 CRM_Event_PseudoConstant::participantStatus()
309 );
310 if ($updatedStatusName == 'Cancelled') {
311 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
312 }
313 elseif ($updatedStatusName == 'Registered') {
314 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
315 }
316 }
317
318 if ($componentName == 'CiviPledge') {
319 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
320 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
321 );
322 if ($updatedStatusName == 'Cancelled') {
323 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
324 }
325 elseif ($updatedStatusName == 'Failed') {
326 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
327 }
328 elseif ($updatedStatusName == 'Completed') {
329 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
330 }
331 }
332 }
333
334 return $statusMsg;
335 }
336
337 /**
338 * @return array (0 => array(int $ppId => string $label), 1 => array(...payproc details...))
339 */
340 public function getValidProcessorsAndAssignFutureStartDate() {
341 $validProcessors = array();
342 // restrict to payment_type = 1 (credit card only) and billing mode 1 and 3
343 $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, "billing_mode IN ( 1, 3 ) AND payment_type = 1");
344
345 foreach ($processors as $ppID => $label) {
346 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
347 // at this stage only Authorize.net has been tested to support future start dates so if it's enabled let the template know
348 // to show receive date
349 $processorsSupportingFutureStartDate = array('AuthNet');
350 if (in_array($paymentProcessor['payment_processor_type'], $processorsSupportingFutureStartDate)) {
351 $this->assign('processorSupportsFutureStartDate', TRUE);
352 }
353 if ($paymentProcessor['payment_processor_type'] == 'PayPal' && !$paymentProcessor['user_name']) {
354 continue;
355 }
356 elseif ($paymentProcessor['payment_processor_type'] == 'Dummy' && $this->_mode == 'live') {
357 continue;
358 }
359 else {
360 $paymentObject = CRM_Core_Payment::singleton($this->_mode, $paymentProcessor, $this);
361 $error = $paymentObject->checkConfig();
362 if (empty($error)) {
363 $validProcessors[$ppID] = $label;
364 }
365 $paymentObject = NULL;
366 }
367 }
368 if (empty($validProcessors)) {
369 CRM_Core_Error::fatal(ts('You will need to configure the %1 settings for your Payment Processor before you can submit credit card transactions.', array(1 => $this->_mode)));
370 }
371 else {
372 return array($validProcessors, $paymentProcessor);
373 }
374 }
375
376 /**
377 * Assign billing type id to bltID
378 *
379 * @return void
380 */
381 public function assignBillingType() {
382 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
383 $this->_bltID = array_search('Billing', $locationTypes);
384 if (!$this->_bltID) {
385 CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
386 }
387 $this->set('bltID', $this->_bltID);
388 $this->assign('bltID', $this->_bltID);
389 }
390
391 /**
392 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
393 */
394 public function assignProcessors() {
395 //ensure that processor has a valid config
396 //only valid processors get display to user
397 if ($this->_mode) {
398 list($this->_processors, $paymentProcessor) = $this->getValidProcessorsAndAssignFutureStartDate();
399
400 //get the valid recurring processors.
401 $recurring = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
402 $this->_recurPaymentProcessors = array_intersect_assoc($this->_processors, $recurring);
403 }
404 $this->assign('recurringPaymentProcessorIds',
405 empty($this->_recurPaymentProcessors) ? '' : implode(',', array_keys($this->_recurPaymentProcessors))
406 );
407
408 // this required to show billing block
409 $this->assign_by_ref('paymentProcessor', $paymentProcessor);
410 $this->assign('hidePayPalExpress', TRUE);
411 }
412
413 /**
414 * @param $submittedValues
415 *
416 * @return mixed
417 */
418 public function getCurrency($submittedValues) { // get current currency from DB or use default currency
419 $config = CRM_Core_Config::singleton();
420
421 $currentCurrency = CRM_Utils_Array::value('currency',
422 $this->_values,
423 $config->defaultCurrency
424 );
425
426 // use submitted currency if present else use current currency
427 $result = CRM_Utils_Array::value('currency',
428 $submittedValues,
429 $currentCurrency
430 );
431 return $result;
432 }
433
434 /**
435 * @param $financialTypeId
436 *
437 * @return array
438 */
439 public function getFinancialAccounts($financialTypeId) {
440 $financialAccounts = array();
441 CRM_Core_PseudoConstant::populate($financialAccounts,
442 'CRM_Financial_DAO_EntityFinancialAccount',
443 $all = TRUE,
444 $retrieve = 'financial_account_id',
445 $filter = NULL,
446 " entity_id = {$financialTypeId} ", NULL, 'account_relationship');
447 return $financialAccounts;
448 }
449
450 /**
451 * @param $financialTypeId
452 * @param $relationTypeId
453 *
454 * @return mixed
455 */
456 public function getFinancialAccount($financialTypeId, $relationTypeId) {
457 $financialAccounts = $this->getFinancialAccounts($financialTypeId);
458 return CRM_Utils_Array::value($relationTypeId, $financialAccounts);
459 }
460
461 public function preProcessPledge() {
462 //get the payment values associated with given pledge payment id OR check for payments due.
463 $this->_pledgeValues = array();
464 if ($this->_ppID) {
465 $payParams = array('id' => $this->_ppID);
466
467 CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
468 $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
469 $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
470 $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
471
472 //get all status
473 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
474 if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
475 CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
476 }
477
478 //get the pledge values associated with given pledge payment.
479
480 $ids = array();
481 $pledgeParams = array('id' => $this->_pledgeID);
482 CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
483 $this->assign('ppID', $this->_ppID);
484 }
485 else {
486 // Not making a pledge payment, so if adding a new contribution we should check if pledge payment(s) are due for this contact so we can alert the user. CRM-5206
487 if (isset($this->_contactID)) {
488 $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
489
490 if (!empty($contactPledges)) {
491 $payments = $paymentsDue = NULL;
492 $multipleDue = FALSE;
493 foreach ($contactPledges as $key => $pledgeId) {
494 $payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
495 if ($payments) {
496 if ($paymentsDue) {
497 $multipleDue = TRUE;
498 break;
499 }
500 else {
501 $paymentsDue = $payments;
502 }
503 }
504 }
505 if ($multipleDue) {
506 // Show link to pledge tab since more than one pledge has a payment due
507 $pledgeTab = CRM_Utils_System::url('civicrm/contact/view',
508 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
509 );
510 CRM_Core_Session::setStatus(ts('This contact has pending or overdue pledge payments. <a href="%1">Click here to view their Pledges tab</a> and verify whether this contribution should be applied as a pledge payment.', array(1 => $pledgeTab)), ts('Notice'), 'alert');
511 }
512 elseif ($paymentsDue) {
513 // Show user link to oldest Pending or Overdue pledge payment
514 $ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
515 $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
516 if ($this->_mode) {
517 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
518 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
519 );
520 }
521 else {
522 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
523 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
524 );
525 }
526 CRM_Core_Session::setStatus(ts('This contact has a pending or overdue pledge payment of %2 which is scheduled for %3. <a href="%1">Click here to enter a pledge payment</a>.', array(
527 1 => $ppUrl,
528 2 => $ppAmountDue,
529 3 => $ppSchedDate
530 )), ts('Notice'), 'alert');
531 }
532 }
533 }
534 }
535 }
536
537 /**
538 * @param $submittedValues
539 *
540 * @return mixed
541 */
542 public function unsetCreditCardFields($submittedValues) {
543 //Offline Contribution.
544 $unsetParams = array(
545 'payment_processor_id',
546 "email-{$this->_bltID}",
547 'hidden_buildCreditCard',
548 'hidden_buildDirectDebit',
549 'billing_first_name',
550 'billing_middle_name',
551 'billing_last_name',
552 'street_address-5',
553 "city-{$this->_bltID}",
554 "state_province_id-{$this->_bltID}",
555 "postal_code-{$this->_bltID}",
556 "country_id-{$this->_bltID}",
557 'credit_card_number',
558 'cvv2',
559 'credit_card_exp_date',
560 'credit_card_type',
561 );
562 foreach ($unsetParams as $key) {
563 if (isset($submittedValues[$key])) {
564 unset($submittedValues[$key]);
565 }
566 }
567 return $submittedValues;
568 }
569
570 }