fixing processor based support
[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
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;
4691b077
EM
69
70 /**
71 * @var CRM_Contribute_DAO_ContributionProduct
72 */
6a488035
TO
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
186c9c17
EM
163 /**
164 * @param $id
165 */
d5397f2f
PJ
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
186c9c17
EM
178 /**
179 * @param $id
180 * @param $values
181 */
6a488035
TO
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);
a7488080 190 if (!empty($fids['financialTrxnId'])) {
6a488035
TO
191 $this->_online = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
192 }
eea16664 193
6a488035
TO
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 }
eea16664 198
6a488035
TO
199 $this->assign('isOnline', $this->_online ? TRUE : FALSE);
200
6a488035
TO
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'];
6a488035
TO
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
4691b077
EM
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 */
6a488035
TO
231 public function assignPremiumProduct($id) { //to get Premium id
232 $sql = "
233SELECT *
234FROM civicrm_contribution_product
235WHERE 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.
03110609
EM
249 *
250 * @param integer $contributionId
251 * @param integer $statusId
252 * @param integer|null $previousStatusId
253 *
254 * @return null|string
6a488035
TO
255 */
256 protected function updateRelatedComponent($contributionId, $statusId, $previousStatusId = NULL) {
257 $statusMsg = NULL;
258 if (!$contributionId || !$statusId) {
259 return $statusMsg;
260 }
261
262 $params = array(
263 'contribution_id' => $contributionId,
264 'contribution_status_id' => $statusId,
265 'previous_contribution_status_id' => $previousStatusId,
266 );
267
268 $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params);
269
270 if (!is_array($updateResult) ||
271 !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) ||
272 !is_array($updatedComponents) ||
273 empty($updatedComponents)
274 ) {
275 return $statusMsg;
276 }
277
278 // get the user display name.
279 $sql = "
280 SELECT display_name as displayName
281 FROM civicrm_contact
282LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
283 WHERE civicrm_contribution.id = {$contributionId}";
284 $userDisplayName = CRM_Core_DAO::singleValueQuery($sql);
285
286 // get the status message for user.
287 foreach ($updatedComponents as $componentName => $updatedStatusId) {
288
289 if ($componentName == 'CiviMember') {
290 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
291 CRM_Member_PseudoConstant::membershipStatus()
292 );
293 if ($updatedStatusName == 'Cancelled') {
294 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
295 }
296 elseif ($updatedStatusName == 'Expired') {
297 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
298 }
d008a264 299 else {
13299a2b
JM
300 $endDate = CRM_Utils_Array::value('membership_end_date', $updateResult);
301 if ($endDate) {
d008a264
JM
302 $statusMsg .= "<br />" . ts("Membership for %1 has been updated. The membership End Date is %2.",
303 array(
304 1 => $userDisplayName,
305 2 => $endDate
306 )
307 );
308 }
6a488035
TO
309 }
310 }
311
312 if ($componentName == 'CiviEvent') {
313 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
314 CRM_Event_PseudoConstant::participantStatus()
315 );
316 if ($updatedStatusName == 'Cancelled') {
317 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
318 }
319 elseif ($updatedStatusName == 'Registered') {
320 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
321 }
322 }
323
324 if ($componentName == 'CiviPledge') {
325 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
326 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
327 );
328 if ($updatedStatusName == 'Cancelled') {
329 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
330 }
331 elseif ($updatedStatusName == 'Failed') {
332 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
333 }
334 elseif ($updatedStatusName == 'Completed') {
335 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
336 }
337 }
338 }
339
340 return $statusMsg;
341 }
342
343 /**
344 * @return array (0 => array(int $ppId => string $label), 1 => array(...payproc details...))
345 */
fbcb6fba
EM
346 /**
347 * @return array of valid processors
348 * @throws Exception
349 */
350 public function getValidProcessors() {
fbcb6fba
EM
351 $defaultID = NULL;
352 $capabilities = array('BackOffice');
353 if ($this->_mode == 'live') {
354 $capabilities[] = 'LiveMode';
355 }
356 $processors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors($capabilities);
44b6505d
EM
357 return $processors;
358
6a488035
TO
359 }
360
361 /**
362 * Assign billing type id to bltID
363 *
44b6505d 364 * @throws CRM_Core_Exception
6a488035
TO
365 * @return void
366 */
367 public function assignBillingType() {
180409a4 368 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
6a488035
TO
369 $this->_bltID = array_search('Billing', $locationTypes);
370 if (!$this->_bltID) {
44b6505d 371 throw new CRM_Core_Exception(ts('Please set a location type of %1', array(1 => 'Billing')));
6a488035
TO
372 }
373 $this->set('bltID', $this->_bltID);
374 $this->assign('bltID', $this->_bltID);
375 }
376
377 /**
378 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
379 */
380 public function assignProcessors() {
381 //ensure that processor has a valid config
382 //only valid processors get display to user
44b6505d 383
6a488035 384 if ($this->_mode) {
fbcb6fba 385 $this->assign(CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(array('supportsFutureRecurStartDate')), TRUE);
44b6505d
EM
386 $processors = $this->getValidProcessors();
387 if (empty($processors)) {
388 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)));
389 }
390 $this->_processors = array();
391 foreach ($processors as $id => $processor) {
392 $this->_processors[$id] = ts($processor['name']);
393 }
6a488035
TO
394 //get the valid recurring processors.
395 $recurring = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
396 $this->_recurPaymentProcessors = array_intersect_assoc($this->_processors, $recurring);
397 }
398 $this->assign('recurringPaymentProcessorIds',
399 empty($this->_recurPaymentProcessors) ? '' : implode(',', array_keys($this->_recurPaymentProcessors))
400 );
401
402 // this required to show billing block
03110609 403 // @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 404 $this->assign_by_ref('paymentProcessor', $processor);
6a488035
TO
405 }
406
186c9c17
EM
407 /**
408 * @param $submittedValues
409 *
410 * @return mixed
411 */
6a488035
TO
412 public function getCurrency($submittedValues) { // get current currency from DB or use default currency
413 $config = CRM_Core_Config::singleton();
414
415 $currentCurrency = CRM_Utils_Array::value('currency',
416 $this->_values,
417 $config->defaultCurrency
418 );
419
420 // use submitted currency if present else use current currency
421 $result = CRM_Utils_Array::value('currency',
422 $submittedValues,
423 $currentCurrency
424 );
425 return $result;
426 }
427
186c9c17
EM
428 /**
429 * @param $financialTypeId
430 *
431 * @return array
432 */
6a488035
TO
433 public function getFinancialAccounts($financialTypeId) {
434 $financialAccounts = array();
435 CRM_Core_PseudoConstant::populate($financialAccounts,
436 'CRM_Financial_DAO_EntityFinancialAccount',
437 $all = TRUE,
438 $retrieve = 'financial_account_id',
439 $filter = NULL,
440 " entity_id = {$financialTypeId} ", NULL, 'account_relationship');
441 return $financialAccounts;
442 }
443
186c9c17
EM
444 /**
445 * @param $financialTypeId
446 * @param $relationTypeId
447 *
448 * @return mixed
449 */
6a488035
TO
450 public function getFinancialAccount($financialTypeId, $relationTypeId) {
451 $financialAccounts = $this->getFinancialAccounts($financialTypeId);
452 return CRM_Utils_Array::value($relationTypeId, $financialAccounts);
453 }
454
455 public function preProcessPledge() {
456 //get the payment values associated with given pledge payment id OR check for payments due.
457 $this->_pledgeValues = array();
458 if ($this->_ppID) {
459 $payParams = array('id' => $this->_ppID);
460
461 CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
462 $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
463 $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
464 $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
465
466 //get all status
467 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
468 if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
469 CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
470 }
471
472 //get the pledge values associated with given pledge payment.
473
474 $ids = array();
475 $pledgeParams = array('id' => $this->_pledgeID);
476 CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
477 $this->assign('ppID', $this->_ppID);
478 }
479 else {
480 // 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
481 if (isset($this->_contactID)) {
482 $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
483
484 if (!empty($contactPledges)) {
485 $payments = $paymentsDue = NULL;
486 $multipleDue = FALSE;
487 foreach ($contactPledges as $key => $pledgeId) {
488 $payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
489 if ($payments) {
490 if ($paymentsDue) {
491 $multipleDue = TRUE;
492 break;
493 }
494 else {
495 $paymentsDue = $payments;
496 }
497 }
498 }
499 if ($multipleDue) {
500 // Show link to pledge tab since more than one pledge has a payment due
501 $pledgeTab = CRM_Utils_System::url('civicrm/contact/view',
502 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
503 );
504 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');
505 }
506 elseif ($paymentsDue) {
507 // Show user link to oldest Pending or Overdue pledge payment
508 $ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
509 $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
510 if ($this->_mode) {
511 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
512 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
513 );
514 }
515 else {
516 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
517 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
518 );
519 }
520 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(
521 1 => $ppUrl,
522 2 => $ppAmountDue,
523 3 => $ppSchedDate
524 )), ts('Notice'), 'alert');
525 }
526 }
527 }
528 }
529 }
530
186c9c17
EM
531 /**
532 * @param $submittedValues
533 *
534 * @return mixed
535 */
6a488035
TO
536 public function unsetCreditCardFields($submittedValues) {
537 //Offline Contribution.
538 $unsetParams = array(
539 'payment_processor_id',
540 "email-{$this->_bltID}",
541 'hidden_buildCreditCard',
542 'hidden_buildDirectDebit',
543 'billing_first_name',
544 'billing_middle_name',
545 'billing_last_name',
546 'street_address-5',
547 "city-{$this->_bltID}",
548 "state_province_id-{$this->_bltID}",
549 "postal_code-{$this->_bltID}",
550 "country_id-{$this->_bltID}",
551 'credit_card_number',
552 'cvv2',
553 'credit_card_exp_date',
554 'credit_card_type',
555 );
556 foreach ($unsetParams as $key) {
557 if (isset($submittedValues[$key])) {
558 unset($submittedValues[$key]);
559 }
560 }
561 return $submittedValues;
562 }
563
564}