Import from SVN (r45945, r596)
[civicrm-core.git] / CRM / Contribute / Form / AbstractEditPayment.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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);
167 if (CRM_Utils_Array::value('financialTrxnId', $fids)) {
168 $this->_online = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
169 }
170
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 }
175
176 $this->assign('isOnline', $this->_online ? TRUE : FALSE);
177
178 //unset the honor type id:when delete the honor_contact_id
179 //and edit the contribution, honoree infomation pane open
180 //since honor_type_id is present
181 if (!CRM_Utils_Array::value('honor_contact_id', $values)) {
182 unset($values['honor_type_id']);
183 }
184 //to get note id
185 $daoNote = new CRM_Core_BAO_Note();
186 $daoNote->entity_table = 'civicrm_contribution';
187 $daoNote->entity_id = $id;
188 if ($daoNote->find(TRUE)) {
189 $this->_noteID = $daoNote->id;
190 $values['note'] = $daoNote->note;
191 }
192 $this->_contributionType = $values['financial_type_id'];
193
194 $csParams = array('contribution_id' => $id);
195 $softCredit = CRM_Contribute_BAO_Contribution::getSoftContribution($csParams, TRUE);
196
197 if (CRM_Utils_Array::value('soft_credit_to', $softCredit)) {
198 $softCredit['sort_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
199 $softCredit['soft_credit_to'], 'sort_name'
200 );
201 }
202 $values['soft_credit_to'] = CRM_Utils_Array::value('sort_name', $softCredit);
203 $values['softID'] = CRM_Utils_Array::value('soft_credit_id', $softCredit);
204 $values['soft_contact_id'] = CRM_Utils_Array::value('soft_credit_to', $softCredit);
205
206 if (CRM_Utils_Array::value('pcp_id', $softCredit)) {
207 $pcpId = CRM_Utils_Array::value('pcp_id', $softCredit);
208 $pcpTitle = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcpId, 'title');
209 $contributionPageTitle = CRM_PCP_BAO_PCP::getPcpPageTitle($pcpId, 'contribute');
210 $values['pcp_made_through'] = CRM_Utils_Array::value('sort_name', $softCredit) . " :: " . $pcpTitle . " :: " . $contributionPageTitle;
211 $values['pcp_made_through_id'] = CRM_Utils_Array::value('pcp_id', $softCredit);
212 $values['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $softCredit);
213 $values['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $softCredit);
214 $values['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $softCredit);
215 }
216 }
217
218 /**
219 * @param string $type eg 'Contribution'
220 * @param string $subType
221 * @param int $entityId
222 */
223 public function applyCustomData($type, $subType, $entityId) {
224 $this->set('type', $type);
225 $this->set('subType', $subType);
226 $this->set('entityId', $entityId);
227
228 CRM_Custom_Form_CustomData::preProcess($this, NULL, $subType, 1, $type, $entityId);
229 CRM_Custom_Form_CustomData::buildQuickForm($this);
230 CRM_Custom_Form_CustomData::setDefaultValues($this);
231 }
232
233 public function assignPremiumProduct($id) { //to get Premium id
234 $sql = "
235SELECT *
236FROM civicrm_contribution_product
237WHERE contribution_id = {$id}
238";
239 $dao = CRM_Core_DAO::executeQuery($sql,
240 CRM_Core_DAO::$_nullArray
241 );
242 if ($dao->fetch()) {
243 $this->_premiumID = $dao->id;
244 $this->_productDAO = $dao;
245 }
246 $dao->free();
247 }
248
249 /**
250 * This function process contribution related objects.
251 */
252 protected function updateRelatedComponent($contributionId, $statusId, $previousStatusId = NULL) {
253 $statusMsg = NULL;
254 if (!$contributionId || !$statusId) {
255 return $statusMsg;
256 }
257
258 $params = array(
259 'contribution_id' => $contributionId,
260 'contribution_status_id' => $statusId,
261 'previous_contribution_status_id' => $previousStatusId,
262 );
263
264 $updateResult = CRM_Contribute_BAO_Contribution::transitionComponents($params);
265
266 if (!is_array($updateResult) ||
267 !($updatedComponents = CRM_Utils_Array::value('updatedComponents', $updateResult)) ||
268 !is_array($updatedComponents) ||
269 empty($updatedComponents)
270 ) {
271 return $statusMsg;
272 }
273
274 // get the user display name.
275 $sql = "
276 SELECT display_name as displayName
277 FROM civicrm_contact
278LEFT JOIN civicrm_contribution on (civicrm_contribution.contact_id = civicrm_contact.id )
279 WHERE civicrm_contribution.id = {$contributionId}";
280 $userDisplayName = CRM_Core_DAO::singleValueQuery($sql);
281
282 // get the status message for user.
283 foreach ($updatedComponents as $componentName => $updatedStatusId) {
284
285 if ($componentName == 'CiviMember') {
286 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
287 CRM_Member_PseudoConstant::membershipStatus()
288 );
289 if ($updatedStatusName == 'Cancelled') {
290 $statusMsg .= "<br />" . ts("Membership for %1 has been Cancelled.", array(1 => $userDisplayName));
291 }
292 elseif ($updatedStatusName == 'Expired') {
293 $statusMsg .= "<br />" . ts("Membership for %1 has been Expired.", array(1 => $userDisplayName));
294 }
295 elseif ($endDate = CRM_Utils_Array::value('membership_end_date', $updateResult)) {
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 if ($componentName == 'CiviEvent') {
306 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
307 CRM_Event_PseudoConstant::participantStatus()
308 );
309 if ($updatedStatusName == 'Cancelled') {
310 $statusMsg .= "<br />" . ts("Event Registration for %1 has been Cancelled.", array(1 => $userDisplayName));
311 }
312 elseif ($updatedStatusName == 'Registered') {
313 $statusMsg .= "<br />" . ts("Event Registration for %1 has been updated.", array(1 => $userDisplayName));
314 }
315 }
316
317 if ($componentName == 'CiviPledge') {
318 $updatedStatusName = CRM_Utils_Array::value($updatedStatusId,
319 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
320 );
321 if ($updatedStatusName == 'Cancelled') {
322 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Cancelled.", array(1 => $userDisplayName));
323 }
324 elseif ($updatedStatusName == 'Failed') {
325 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been Failed.", array(1 => $userDisplayName));
326 }
327 elseif ($updatedStatusName == 'Completed') {
328 $statusMsg .= "<br />" . ts("Pledge Payment for %1 has been updated.", array(1 => $userDisplayName));
329 }
330 }
331 }
332
333 return $statusMsg;
334 }
335
336 /**
337 * @return array (0 => array(int $ppId => string $label), 1 => array(...payproc details...))
338 */
339 public function getValidProcessorsAndAssignFutureStartDate() {
340 $validProcessors = array();
341 $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, "billing_mode IN ( 1, 3 )");
342
343 foreach ($processors as $ppID => $label) {
344 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
345 // at this stage only Authorize.net has been tested to support future start dates so if it's enabled let the template know
346 // to show receive date
347 $processorsSupportingFutureStartDate = array('AuthNet');
348 if (in_array($paymentProcessor['payment_processor_type'], $processorsSupportingFutureStartDate)) {
349 $this->assign('processorSupportsFutureStartDate', TRUE);
350 }
351 if ($paymentProcessor['payment_processor_type'] == 'PayPal' && !$paymentProcessor['user_name']) {
352 continue;
353 }
354 elseif ($paymentProcessor['payment_processor_type'] == 'Dummy' && $this->_mode == 'live') {
355 continue;
356 }
357 else {
358 $paymentObject = CRM_Core_Payment::singleton($this->_mode, $paymentProcessor, $this);
359 $error = $paymentObject->checkConfig();
360 if (empty($error)) {
361 $validProcessors[$ppID] = $label;
362 }
363 $paymentObject = NULL;
364 }
365 }
366 if (empty($validProcessors)) {
367 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)));
368 }
369 else {
370 return array($validProcessors, $paymentProcessor);
371 }
372 }
373
374 /**
375 * Assign billing type id to bltID
376 *
377 * @return void
378 */
379 public function assignBillingType() {
380 $locationTypes = CRM_Core_PseudoConstant::locationType();
381 $this->_bltID = array_search('Billing', $locationTypes);
382 if (!$this->_bltID) {
383 CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
384 }
385 $this->set('bltID', $this->_bltID);
386 $this->assign('bltID', $this->_bltID);
387 }
388
389 /**
390 * Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
391 */
392 public function assignProcessors() {
393 //ensure that processor has a valid config
394 //only valid processors get display to user
395 if ($this->_mode) {
396 list($this->_processors, $paymentProcessor) = $this->getValidProcessorsAndAssignFutureStartDate();
397
398 //get the valid recurring processors.
399 $recurring = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
400 $this->_recurPaymentProcessors = array_intersect_assoc($this->_processors, $recurring);
401 }
402 $this->assign('recurringPaymentProcessorIds',
403 empty($this->_recurPaymentProcessors) ? '' : implode(',', array_keys($this->_recurPaymentProcessors))
404 );
405
406 // this required to show billing block
407 $this->assign_by_ref('paymentProcessor', $paymentProcessor);
408 $this->assign('hidePayPalExpress', TRUE);
409 }
410
411 public function getCurrency($submittedValues) { // get current currency from DB or use default currency
412 $config = CRM_Core_Config::singleton();
413
414 $currentCurrency = CRM_Utils_Array::value('currency',
415 $this->_values,
416 $config->defaultCurrency
417 );
418
419 // use submitted currency if present else use current currency
420 $result = CRM_Utils_Array::value('currency',
421 $submittedValues,
422 $currentCurrency
423 );
424 return $result;
425 }
426
427 public function getFinancialAccounts($financialTypeId) {
428 $financialAccounts = array();
429 CRM_Core_PseudoConstant::populate($financialAccounts,
430 'CRM_Financial_DAO_EntityFinancialAccount',
431 $all = TRUE,
432 $retrieve = 'financial_account_id',
433 $filter = NULL,
434 " entity_id = {$financialTypeId} ", NULL, 'account_relationship');
435 return $financialAccounts;
436 }
437
438 public function getFinancialAccount($financialTypeId, $relationTypeId) {
439 $financialAccounts = $this->getFinancialAccounts($financialTypeId);
440 return CRM_Utils_Array::value($relationTypeId, $financialAccounts);
441 }
442
443 public function preProcessPledge() {
444 //get the payment values associated with given pledge payment id OR check for payments due.
445 $this->_pledgeValues = array();
446 if ($this->_ppID) {
447 $payParams = array('id' => $this->_ppID);
448
449 CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
450 $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
451 $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
452 $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
453
454 //get all status
455 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
456 if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
457 CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
458 }
459
460 //get the pledge values associated with given pledge payment.
461
462 $ids = array();
463 $pledgeParams = array('id' => $this->_pledgeID);
464 CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
465 $this->assign('ppID', $this->_ppID);
466 }
467 else {
468 // 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
469 if (isset($this->_contactID)) {
470 $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
471
472 if (!empty($contactPledges)) {
473 $payments = $paymentsDue = NULL;
474 $multipleDue = FALSE;
475 foreach ($contactPledges as $key => $pledgeId) {
476 $payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
477 if ($payments) {
478 if ($paymentsDue) {
479 $multipleDue = TRUE;
480 break;
481 }
482 else {
483 $paymentsDue = $payments;
484 }
485 }
486 }
487 if ($multipleDue) {
488 // Show link to pledge tab since more than one pledge has a payment due
489 $pledgeTab = CRM_Utils_System::url('civicrm/contact/view',
490 "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
491 );
492 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');
493 }
494 elseif ($paymentsDue) {
495 // Show user link to oldest Pending or Overdue pledge payment
496 $ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
497 $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
498 if ($this->_mode) {
499 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
500 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
501 );
502 }
503 else {
504 $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
505 "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
506 );
507 }
508 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(
509 1 => $ppUrl,
510 2 => $ppAmountDue,
511 3 => $ppSchedDate
512 )), ts('Notice'), 'alert');
513 }
514 }
515 }
516 }
517 }
518
519 public function unsetCreditCardFields($submittedValues) {
520 //Offline Contribution.
521 $unsetParams = array(
522 'payment_processor_id',
523 "email-{$this->_bltID}",
524 'hidden_buildCreditCard',
525 'hidden_buildDirectDebit',
526 'billing_first_name',
527 'billing_middle_name',
528 'billing_last_name',
529 'street_address-5',
530 "city-{$this->_bltID}",
531 "state_province_id-{$this->_bltID}",
532 "postal_code-{$this->_bltID}",
533 "country_id-{$this->_bltID}",
534 'credit_card_number',
535 'cvv2',
536 'credit_card_exp_date',
537 'credit_card_type',
538 );
539 foreach ($unsetParams as $key) {
540 if (isset($submittedValues[$key])) {
541 unset($submittedValues[$key]);
542 }
543 }
544 return $submittedValues;
545 }
546
547}