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