use processor class to determine if backoffice processing is supported
[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() {
6a488035 351 $validProcessors = array();
fbcb6fba
EM
352 $defaultID = NULL;
353 $capabilities = array('BackOffice');
354 if ($this->_mode == 'live') {
355 $capabilities[] = 'LiveMode';
356 }
357 $processors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors($capabilities);
358 foreach ($processors as $id => $processor) {
359 if ($processor['is_default']) {
360 $defaultID = $id;
361 }
362 $validProcessors[$id] = ts($processor['name']);
6a488035
TO
363 }
364 if (empty($validProcessors)) {
fbcb6fba 365 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)));
6a488035
TO
366 }
367 else {
fbcb6fba 368 return array($validProcessors, $processors[$defaultID]['object']);
6a488035
TO
369 }
370 }
371
372 /**
373 * Assign billing type id to bltID
374 *
375 * @return void
376 */
377 public function assignBillingType() {
180409a4 378 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
6a488035
TO
379 $this->_bltID = array_search('Billing', $locationTypes);
380 if (!$this->_bltID) {
381 CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
382 }
383 $this->set('bltID', $this->_bltID);
384 $this->assign('bltID', $this->_bltID);
385 }
386
387 /**
388 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
389 */
390 public function assignProcessors() {
391 //ensure that processor has a valid config
392 //only valid processors get display to user
393 if ($this->_mode) {
fbcb6fba
EM
394 $this->assign(CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(array('supportsFutureRecurStartDate')), TRUE);
395 list($this->_processors, $paymentProcessor) = $this->getValidProcessors();
6a488035
TO
396
397 //get the valid recurring processors.
398 $recurring = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
399 $this->_recurPaymentProcessors = array_intersect_assoc($this->_processors, $recurring);
400 }
401 $this->assign('recurringPaymentProcessorIds',
402 empty($this->_recurPaymentProcessors) ? '' : implode(',', array_keys($this->_recurPaymentProcessors))
403 );
404
405 // this required to show billing block
03110609 406 // @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
6a488035 407 $this->assign_by_ref('paymentProcessor', $paymentProcessor);
6a488035
TO
408 }
409
186c9c17
EM
410 /**
411 * @param $submittedValues
412 *
413 * @return mixed
414 */
6a488035
TO
415 public function getCurrency($submittedValues) { // get current currency from DB or use default currency
416 $config = CRM_Core_Config::singleton();
417
418 $currentCurrency = CRM_Utils_Array::value('currency',
419 $this->_values,
420 $config->defaultCurrency
421 );
422
423 // use submitted currency if present else use current currency
424 $result = CRM_Utils_Array::value('currency',
425 $submittedValues,
426 $currentCurrency
427 );
428 return $result;
429 }
430
186c9c17
EM
431 /**
432 * @param $financialTypeId
433 *
434 * @return array
435 */
6a488035
TO
436 public function getFinancialAccounts($financialTypeId) {
437 $financialAccounts = array();
438 CRM_Core_PseudoConstant::populate($financialAccounts,
439 'CRM_Financial_DAO_EntityFinancialAccount',
440 $all = TRUE,
441 $retrieve = 'financial_account_id',
442 $filter = NULL,
443 " entity_id = {$financialTypeId} ", NULL, 'account_relationship');
444 return $financialAccounts;
445 }
446
186c9c17
EM
447 /**
448 * @param $financialTypeId
449 * @param $relationTypeId
450 *
451 * @return mixed
452 */
6a488035
TO
453 public function getFinancialAccount($financialTypeId, $relationTypeId) {
454 $financialAccounts = $this->getFinancialAccounts($financialTypeId);
455 return CRM_Utils_Array::value($relationTypeId, $financialAccounts);
456 }
457
458 public function preProcessPledge() {
459 //get the payment values associated with given pledge payment id OR check for payments due.
460 $this->_pledgeValues = array();
461 if ($this->_ppID) {
462 $payParams = array('id' => $this->_ppID);
463
464 CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
465 $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
466 $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
467 $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
468
469 //get all status
470 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
471 if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
472 CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
473 }
474
475 //get the pledge values associated with given pledge payment.
476
477 $ids = array();
478 $pledgeParams = array('id' => $this->_pledgeID);
479 CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
480 $this->assign('ppID', $this->_ppID);
481 }
482 else {
483 // 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
484 if (isset($this->_contactID)) {
485 $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
486
487 if (!empty($contactPledges)) {
488 $payments = $paymentsDue = NULL;
489 $multipleDue = FALSE;
490 foreach ($contactPledges as $key => $pledgeId) {
491 $payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
492 if ($payments) {
493 if ($paymentsDue) {
494 $multipleDue = TRUE;
495 break;
496 }
497 else {
498 $paymentsDue = $payments;
499 }
500 }
501 }
502 if ($multipleDue) {
503 // Show link to pledge tab since more than one pledge has a payment due
504 $pledgeTab = CRM_Utils_System::url('civicrm/contact/view',
505 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
506 );
507 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');
508 }
509 elseif ($paymentsDue) {
510 // Show user link to oldest Pending or Overdue pledge payment
511 $ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
512 $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
513 if ($this->_mode) {
514 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
515 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
516 );
517 }
518 else {
519 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
520 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
521 );
522 }
523 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(
524 1 => $ppUrl,
525 2 => $ppAmountDue,
526 3 => $ppSchedDate
527 )), ts('Notice'), 'alert');
528 }
529 }
530 }
531 }
532 }
533
186c9c17
EM
534 /**
535 * @param $submittedValues
536 *
537 * @return mixed
538 */
6a488035
TO
539 public function unsetCreditCardFields($submittedValues) {
540 //Offline Contribution.
541 $unsetParams = array(
542 'payment_processor_id',
543 "email-{$this->_bltID}",
544 'hidden_buildCreditCard',
545 'hidden_buildDirectDebit',
546 'billing_first_name',
547 'billing_middle_name',
548 'billing_last_name',
549 'street_address-5',
550 "city-{$this->_bltID}",
551 "state_province_id-{$this->_bltID}",
552 "postal_code-{$this->_bltID}",
553 "country_id-{$this->_bltID}",
554 'credit_card_number',
555 'cvv2',
556 'credit_card_exp_date',
557 'credit_card_type',
558 );
559 foreach ($unsetParams as $key) {
560 if (isset($submittedValues[$key])) {
561 unset($submittedValues[$key]);
562 }
563 }
564 return $submittedValues;
565 }
566
567}