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