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