manual merge of fixes for CRM-13981
[civicrm-core.git] / CRM / Contribute / Form / AdditionalPayment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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 form records additional payments needed when
38 * event/contribution is partially paid
39 *
40 */
41 class CRM_Contribute_Form_AdditionalPayment extends CRM_Contribute_Form_AbstractEditPayment {
42 public $_contributeMode = 'direct';
43
44 /**
45 * related component whose financial payment is being processed
46 *
47 * @var string
48 * @public
49 */
50 protected $_component = NULL;
51
52 /**
53 * id of the component entity
54 */
55 public $_id = NULL;
56
57 protected $_owed = NULL;
58
59 protected $_refund = NULL;
60
61 protected $_contactId = NULL;
62
63 protected $_contributorDisplayName = NULL;
64
65 protected $_contributorEmail = NULL;
66
67 protected $_toDoNotEmail = NULL;
68
69 protected $_paymentType = NULL;
70
71 protected $_contributionId = NULL;
72
73 protected $fromEmailId = NULL;
74
75 public function preProcess() {
76 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
77 $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
78 $this->_component = CRM_Utils_Request::retrieve('component', 'String', $this, TRUE);
79 $this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
80 $this->_formType = CRM_Utils_Array::value('formType', $_GET);
81
82 $enitityType = NULL;
83 if ($this->_component == 'event') {
84 $enitityType = 'participant';
85 $this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
86 }
87
88 $paymentInfo = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($this->_id, $enitityType);
89
90 if (!empty($paymentInfo['refund_due'])) {
91 $paymentAmt = $this->_refund = $paymentInfo['refund_due'];
92 $this->_paymentType = 'refund';
93 }
94 elseif (!empty($paymentInfo['amount_owed'])) {
95 $paymentAmt = $this->_owed = $paymentInfo['amount_owed'];
96 $this->_paymentType = 'owed';
97 }
98 else {
99 CRM_Core_Error::fatal(ts('No payment information found for this record'));
100 }
101
102 list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
103 //set the payment mode - _mode property is defined in parent class
104 $this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
105
106 $this->assignProcessors();
107
108 // also check for billing information
109 // get the billing location type
110 $this->assignBillingType();
111
112 $this->assign('contributionMode', $this->_mode);
113 $this->assign('contactId', $this->_contactId);
114 $this->assign('component', $this->_component);
115 $this->assign('id', $this->_id);
116 $this->assign('paymentType', $this->_paymentType);
117 $this->assign('paymentAmt', $paymentAmt);
118
119 $this->_paymentProcessor = array('billing_mode' => 1);
120
121 $title = ($this->_refund) ? "Refund for {$this->_contributorDisplayName}" : "Payment from {$this->_contributorDisplayName}";
122 if ($title) {
123 CRM_Utils_System::setTitle(ts('%1', array(1 => $title)));
124 }
125 }
126
127 public function setDefaultValues() {
128 if ($this->_mode) {
129 $defaults = $this->_values;
130
131 $config = CRM_Core_Config::singleton();
132 // set default country from config if no country set
133 if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
134 $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
135 }
136
137 if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
138 $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
139 }
140
141 $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactId);
142 $defaults = array_merge($defaults, $billingDefaults);
143
144 // now fix all state country selectors, set correct state based on country
145 CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults);
146 }
147
148 // Set $newCredit variable in template to control whether link to credit card mode is included
149 CRM_Core_Payment::allowBackofficeCreditCard($this);
150 }
151
152 public function buildQuickForm() {
153 $ccPane = NULL;
154 if ($this->_mode) {
155 if (CRM_Utils_Array::value('payment_type', $this->_processors) & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT
156 ) {
157 $ccPane = array(ts('Direct Debit Information') => 'DirectDebit');
158 }
159 else {
160 $ccPane = array(ts('Credit Card Information') => 'CreditCard');
161 }
162 $defaults = $this->_values;
163 $showAdditionalInfo = FALSE;
164
165 foreach ($ccPane as $name => $type) {
166 if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) ||
167 CRM_Utils_Array::value("hidden_{$type}", $defaults)
168 ) {
169 $showAdditionalInfo = TRUE;
170 $allPanes[$name]['open'] = 'true';
171 }
172
173 $urlParams = "snippet=4&formType={$type}";
174 if ($this->_mode) {
175 $urlParams .= "&mode={$this->_mode}";
176 }
177 $open = 'false';
178 if ($type == 'CreditCard' ||
179 $type == 'DirectDebit'
180 ) {
181 $open = 'true';
182 }
183
184 $allPanes[$name] = array(
185 'url' => CRM_Utils_System::url('civicrm/payment/add', $urlParams),
186 'open' => $open,
187 'id' => $type
188 );
189
190 if ($type == 'CreditCard') {
191 $this->add('hidden', 'hidden_CreditCard', 1);
192 CRM_Core_Payment_Form::buildCreditCard($this, TRUE);
193 }
194 elseif ($type == 'DirectDebit') {
195 $this->add('hidden', 'hidden_DirectDebit', 1);
196 CRM_Core_Payment_Form::buildDirectDebit($this, TRUE);
197 }
198 $qfKey = $this->controller->_key;
199 $this->assign('qfKey', $qfKey);
200 $this->assign('allPanes', $allPanes);
201 $this->assign('showAdditionalInfo', $showAdditionalInfo);
202
203 if ($this->_formType) {
204 $this->assign('formType', $this->_formType);
205 return;
206 }
207 }
208 }
209 $attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialTrxn');
210
211 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, NULL);
212 $this->add('select', 'financial_type_id',
213 ts('Financial Type'),
214 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(),
215 TRUE
216 );
217 $label = ($this->_refund) ? 'Refund Amount' : 'Payment Amount';
218 $this->addMoney('total_amount',
219 ts('%1', array(1 => $label)),
220 FALSE,
221 $attributes['total_amount'],
222 TRUE, 'currency', NULL
223 );
224
225 if (!$this->_mode) {
226 $this->add('select', 'payment_instrument_id',
227 ts('Paid By'),
228 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
229 TRUE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
230 );
231 }
232
233 $this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
234 $trxnId = $this->add('text', 'trxn_id', ts('Transaction ID'), $attributes['trxn_id']);
235
236 //add receipt for offline contribution
237 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
238
239 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
240
241 // add various dates
242 $this->addDateTime('trxn_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
243
244 if ($this->_contactId && $this->_id) {
245 if ($this->_component == 'event') {
246 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
247 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
248 $this->assign('eventName', $event[$eventId]);
249 }
250 }
251
252 $this->assign('displayName', $this->_contributorDisplayName);
253 $this->assign('component', $this->_component);
254 $this->assign('email', $this->_contributorEmail);
255
256 $this->add('text', 'fee_amount', ts('Fee Amount'),
257 $attributes['fee_amount']
258 );
259 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
260
261 $this->add('text', 'net_amount', ts('Net Amount'),
262 $attributes['net_amount']
263 );
264 $this->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
265
266 $js = NULL;
267 if (!$this->_mode) {
268 $js = array('onclick' => "return verify( );");
269 }
270
271 $buttonName = $this->_refund ? 'Record Refund' : 'Record Payment';
272 $this->addButtons(array(
273 array(
274 'type' => 'upload',
275 'name' => ts('%1', array(1 => $buttonName)),
276 'js' => $js,
277 'isDefault' => TRUE
278 ),
279 array(
280 'type' => 'cancel',
281 'name' => ts('Cancel')
282 ),
283 )
284 );
285
286
287 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
288 'mailing_backend'
289 );
290 $this->assign('outBound_option', $mailingInfo['outBound_option']);
291
292 $this->addFormRule(array('CRM_Contribute_Form_AdditionalPayment', 'formRule'), $this);
293 }
294
295 static function formRule($fields, $files, $self) {
296 $errors = array();
297 if ($self->_paymentType == 'owed' && $fields['total_amount'] > $self->_owed) {
298 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
299 }
300 if ($self->_paymentType == 'refund' && $fields['total_amount'] != $self->_refund) {
301 $errors['total_amount'] = ts('Refund amount should not differ');
302 }
303 $netAmt = $fields['total_amount'] - $fields['fee_amount'];
304 if (!empty($fields['net_amount']) && $netAmt != $fields['net_amount']) {
305 $errors['net_amount'] = ts('Net amount should be difference of payment amount and fee amount');
306 }
307 return $errors;
308 }
309
310 public function postProcess() {
311 $participantId = NULL;
312 if ($this->_component == 'event') {
313 $participantId = $this->_id;
314 }
315 $submittedValues = $this->controller->exportValues($this->_name);
316 $submittedValues['trxn_date'] = CRM_Utils_Date::processDate($submittedValues['trxn_date'], $submittedValues['trxn_date_time']);
317
318 if ($this->_mode) {
319 // process credit card
320 $this->processCreditCard($submittedValues);
321 }
322 else {
323 $result = CRM_Contribute_BAO_Contribution::recordAdditionPayment($this->_contributionId, $submittedValues, $this->_paymentType, $participantId);
324
325 // email sending
326 if (!empty($result) && !empty($submittedValues['is_email_receipt'])) {
327 $submittedValues['contact_id'] = $this->_contactId;
328 $submittedValues['contribution_id'] = $this->_contributionId;
329
330 // to get 'from email id' for send receipt
331 $this->fromEmailId = $submittedValues['from_email_address'];
332 $sendReceipt = self::emailReceipt($this, $submittedValues);
333 }
334
335 $statusMsg = ts('The payment record has been processed.');
336 if (!empty($submittedValues['is_email_receipt']) && $sendReceipt) {
337 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
338 }
339 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
340
341 $session = CRM_Core_Session::singleton();
342 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
343 "reset=1&cid={$this->_contactId}&selectedChild=participant"
344 ));
345 }
346 }
347
348 public function processCreditCard($submittedValues) {
349 $config = CRM_Core_Config::singleton();
350 $session = CRM_Core_Session::singleton();
351
352 $unsetParams = array(
353 'trxn_id',
354 'payment_instrument_id',
355 'contribution_status_id',
356 );
357 foreach ($unsetParams as $key) {
358 if (isset($submittedValues[$key])) {
359 unset($submittedValues[$key]);
360 }
361 }
362
363 //Get the rquire fields value only.
364 $params = $this->_params = $submittedValues;
365
366 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
367 $this->_mode
368 );
369
370 //get the payment processor id as per mode.
371 $this->_params['payment_processor'] = $params['payment_processor_id'] =
372 $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
373
374 $now = date('YmdHis');
375 $fields = array();
376
377 // we need to retrieve email address
378 if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
379 list($this->userDisplayName,
380 $this->userEmail
381 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
382 $this->assign('displayName', $this->userDisplayName);
383 }
384
385 //set email for primary location.
386 $fields['email-Primary'] = 1;
387 $params['email-Primary'] = $this->_contributorEmail;
388
389 // now set the values for the billing location.
390 foreach ($this->_fields as $name => $dontCare) {
391 $fields[$name] = 1;
392 }
393
394 // also add location name to the array
395 $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
396 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
397 $fields["address_name-{$this->_bltID}"] = 1;
398
399 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
400 $this->_contactId,
401 'contact_type'
402 );
403
404 $nameFields = array('first_name', 'middle_name', 'last_name');
405 foreach ($nameFields as $name) {
406 $fields[$name] = 1;
407 if (array_key_exists("billing_$name", $params)) {
408 $params[$name] = $params["billing_{$name}"];
409 $params['preserveDBName'] = TRUE;
410 }
411 }
412
413 if (!empty($params['source'])) {
414 unset($params['source']);
415 }
416 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields,
417 $this->_contactId,
418 NULL, NULL,
419 $ctype
420 );
421
422 // add all the additioanl payment params we need
423 $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
424 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
425
426 if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
427 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
428 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
429 }
430 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
431 $this->_params['amount'] = $this->_params['total_amount'];
432 $this->_params['amount_level'] = 0;
433 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
434 $this->_params,
435 $config->defaultCurrency
436 );
437 $this->_params['payment_action'] = 'Sale';
438 if (!empty($this->_params['trxn_date'])) {
439 $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['trxn_date'], $this->_params['receive_date_time']);
440 }
441
442 if (empty($this->_params['invoice_id'])) {
443 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
444 }
445 else {
446 $this->_params['invoiceID'] = $this->_params['invoice_id'];
447 }
448
449 //Add common data to formatted params
450 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
451 // at this point we've created a contact and stored its address etc
452 // all the payment processors expect the name and address to be in the
453 // so we copy stuff over to first_name etc.
454 $paymentParams = $this->_params;
455 $paymentParams['contactID'] = $this->_contactId;
456 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
457
458 $contributionType = new CRM_Financial_DAO_FinancialType();
459 $contributionType->id = $params['financial_type_id'];
460 if (!$contributionType->find(TRUE)) {
461 CRM_Core_Error::fatal('Could not find a system table');
462 }
463
464 // add some financial type details to the params list
465 // if folks need to use it
466 $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
467 $paymentParams['contributionPageID'] = NULL;
468 if (!empty($this->_params['is_email_receipt'])) {
469 $paymentParams['email'] = $this->_contributorEmail;
470 $paymentParams['is_email_receipt'] = 1;
471 }
472 else {
473 $paymentParams['is_email_receipt'] = 0;
474 $this->_params['is_email_receipt'] = 0;
475 }
476 if (!empty($this->_params['receive_date'])) {
477 $paymentParams['receive_date'] = $this->_params['receive_date'];
478 }
479 if (!empty($this->_params['receive_date'])) {
480 $paymentParams['receive_date'] = $this->_params['receive_date'];
481 }
482
483 $result = NULL;
484
485 if ($paymentParams['amount'] > 0.0) {
486 // force a reget of the payment processor in case the form changed it, CRM-7179
487 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
488 $result = $payment->doDirectPayment($paymentParams);
489 }
490
491 if (is_a($result, 'CRM_Core_Error')) {
492 //set the contribution mode.
493 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_id}&component={$this->_component}";
494 if ($this->_mode) {
495 $urlParams .= "&mode={$this->_mode}";
496 }
497 CRM_Core_Error::displaySessionError($result);
498 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/payment/add', $urlParams));
499 }
500
501 if ($result) {
502 $this->_params = array_merge($this->_params, $result);
503 }
504
505 $this->_params['receive_date'] = $now;
506
507 $this->set('params', $this->_params);
508 $this->assign('trxn_id', $result['trxn_id']);
509 $this->assign('receive_date', $this->_params['receive_date']);
510
511 // set source if not set
512 if (empty($this->_params['source'])) {
513 $userID = $session->get('userID');
514 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
515 'sort_name'
516 );
517 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
518 }
519
520 // process the additional payment
521 $trxnRecord = CRM_Contribute_BAO_Contribution::recordAdditionPayment($this->_contributionId, $submittedValues, $this->_paymentType, $participantId);
522
523 if ($trxnRecord->id && !empty($this->_params['is_email_receipt'])) {
524 $sendReceipt = self::emailReceipt($this, $this->_params);
525 }
526
527 if ($trxnRecord->id) {
528 $statusMsg = ts('The payment record has been processed.');
529 if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
530 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
531 }
532 CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
533 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
534 "reset=1&cid={$this->_contactId}&selectedChild=participant"
535 ));
536 }
537 }
538
539 static function emailReceipt(&$form, &$params) {
540 // email receipt sending
541 }
542 }