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