Merge pull request #15545 from eileenmcnaughton/pay_email_p
[civicrm-core.git] / CRM / Contribute / Form / AdditionalPayment.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 useful, 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-2019
32 */
33
34 /**
35 * This form records additional payments needed when event/contribution is partially paid.
36 */
37 class CRM_Contribute_Form_AdditionalPayment extends CRM_Contribute_Form_AbstractEditPayment {
38 public $_contributeMode = 'direct';
39
40 /**
41 * Id of the component entity
42 * @var int
43 */
44 public $_id = NULL;
45
46 protected $entity = 'Contribution';
47
48 protected $_owed = NULL;
49
50 protected $_refund = NULL;
51
52 /**
53 * @var int
54 * @deprecated - use parent $this->contactID
55 */
56 protected $_contactId = NULL;
57
58 protected $_contributorDisplayName = NULL;
59
60 protected $_contributorEmail = NULL;
61
62 protected $_toDoNotEmail = NULL;
63
64 protected $_paymentType = NULL;
65
66 protected $_contributionId = NULL;
67
68 protected $fromEmailId = NULL;
69
70 protected $_view = NULL;
71
72 public $_action = NULL;
73
74 /**
75 * Pre process form.
76 *
77 * @throws \CRM_Core_Exception
78 */
79 public function preProcess() {
80
81 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
82 parent::preProcess();
83 $this->_contactId = $this->_contactID;
84 $this->_component = CRM_Utils_Request::retrieve('component', 'String', $this, FALSE, 'contribution');
85 $this->_view = CRM_Utils_Request::retrieve('view', 'String', $this, FALSE);
86 $this->assign('component', $this->_component);
87 $this->assign('id', $this->_id);
88 $this->assign('suppressPaymentFormButtons', $this->isBeingCalledFromSelectorContext());
89
90 if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
91 $title = $this->assignPaymentInfoBlock();
92 CRM_Utils_System::setTitle($title);
93 return;
94 }
95 $entityType = 'contribution';
96 if ($this->_component == 'event') {
97 $entityType = 'participant';
98 $this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
99 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
100 }
101 else {
102 $this->_contributionId = $this->_id;
103 }
104
105 $paymentInfo = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($this->_id, $entityType);
106 $paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, FALSE, TRUE);
107
108 $this->_amtPaid = $paymentDetails['paid'];
109 $this->_amtTotal = $paymentDetails['total'];
110
111 if (!empty($paymentInfo['refund_due'])) {
112 $paymentAmt = $this->_refund = $paymentInfo['refund_due'];
113 $this->_paymentType = 'refund';
114 }
115 elseif (!empty($paymentInfo['amount_owed'])) {
116 $paymentAmt = $this->_owed = $paymentInfo['amount_owed'];
117 $this->_paymentType = 'owed';
118 }
119 else {
120 throw new CRM_Core_Exception(ts('No payment information found for this record'));
121 }
122
123 if (!empty($this->_mode) && $this->_paymentType == 'refund') {
124 throw new CRM_Core_Exception(ts('Credit card payment is not for Refund payments use'));
125 }
126
127 list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
128
129 $this->assign('contributionMode', $this->_mode);
130 $this->assign('contactId', $this->_contactID);
131 $this->assign('paymentType', $this->_paymentType);
132 $this->assign('paymentAmt', abs($paymentAmt));
133
134 $this->setPageTitle($this->_refund ? ts('Refund') : ts('Payment'));
135 }
136
137 /**
138 * Is this function being called from a datatable selector.
139 *
140 * If so we don't want to show the buttons.
141 *
142 * @throws \CRM_Core_Exception
143 */
144 protected function isBeingCalledFromSelectorContext() {
145 return CRM_Utils_Request::retrieve('selector', 'Positive');
146 }
147
148 /**
149 * This virtual function is used to set the default values of
150 * various form elements
151 *
152 * access public
153 *
154 * @return array
155 * reference to the array of default values
156 */
157
158 /**
159 * @return array
160 */
161 public function setDefaultValues() {
162 if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
163 return NULL;
164 }
165 $defaults = [];
166 if ($this->_mode) {
167 CRM_Core_Payment_Form::setDefaultValues($this, $this->_contactId);
168 $defaults = array_merge($defaults, $this->_defaults);
169 }
170
171 if (empty($defaults['trxn_date'])) {
172 $defaults['trxn_date'] = date('Y-m-d H:i:s');
173 }
174
175 if ($this->_refund) {
176 $defaults['total_amount'] = CRM_Utils_Money::format(abs($this->_refund), NULL, NULL, TRUE);
177 }
178 elseif ($this->_owed) {
179 $defaults['total_amount'] = CRM_Utils_Money::formatLocaleNumericRoundedForDefaultCurrency($this->_owed);
180 }
181
182 // Set $newCredit variable in template to control whether link to credit card mode is included
183 $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
184 return $defaults;
185 }
186
187 /**
188 * Build the form object.
189 */
190 public function buildQuickForm() {
191 if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
192 $this->addButtons([
193 [
194 'type' => 'cancel',
195 'name' => ts('Done'),
196 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
197 'isDefault' => TRUE,
198 ],
199 ]);
200 return;
201 }
202
203 CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer'));
204 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, NULL);
205
206 $attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialTrxn');
207
208 $label = ($this->_refund) ? ts('Refund Amount') : ts('Payment Amount');
209 $this->addMoney('total_amount',
210 $label,
211 TRUE,
212 $attributes['total_amount'],
213 TRUE, 'currency', NULL
214 );
215
216 //add receipt for offline contribution
217 $this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
218
219 if ($this->_component === 'event') {
220 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
221 }
222
223 $this->add('select', 'from_email_address', ts('Receipt From'), CRM_Financial_BAO_Payment::getValidFromEmailsForPayment($eventID));
224
225 $this->add('textarea', 'receipt_text', ts('Confirmation Message'));
226
227 $dateLabel = ($this->_refund) ? ts('Refund Date') : ts('Date Received');
228 $this->addField('trxn_date', ['entity' => 'FinancialTrxn', 'label' => $dateLabel, 'context' => 'Contribution'], FALSE, FALSE);
229
230 if ($this->_contactId && $this->_id) {
231 if ($this->_component == 'event') {
232 $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
233 $event = CRM_Event_BAO_Event::getEvents(0, $eventId);
234 $this->assign('eventName', $event[$eventId]);
235 }
236 }
237
238 $this->assign('displayName', $this->_contributorDisplayName);
239 $this->assign('component', $this->_component);
240 $this->assign('email', $this->_contributorEmail);
241
242 $js = NULL;
243 // render backoffice payment fields only on offline mode
244 if (!$this->_mode) {
245 $js = ['onclick' => "return verify( );"];
246
247 $this->add('select', 'payment_instrument_id',
248 ts('Payment Method'),
249 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(),
250 TRUE,
251 ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
252 );
253
254 $this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
255 $this->add('text', 'trxn_id', ts('Transaction ID'), ['class' => 'twelve'] + $attributes['trxn_id']);
256
257 $this->add('text', 'fee_amount', ts('Fee Amount'),
258 $attributes['fee_amount']
259 );
260 $this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
261
262 $this->add('text', 'net_amount', ts('Net Amount'),
263 $attributes['net_amount']
264 );
265 $this->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
266 }
267
268 $buttonName = $this->_refund ? 'Record Refund' : 'Record Payment';
269 $this->addButtons([
270 [
271 'type' => 'upload',
272 'name' => ts('%1', [1 => $buttonName]),
273 'js' => $js,
274 'isDefault' => TRUE,
275 ],
276 [
277 'type' => 'cancel',
278 'name' => ts('Cancel'),
279 ],
280 ]);
281 $mailingInfo = Civi::settings()->get('mailing_backend');
282 $this->assign('outBound_option', $mailingInfo['outBound_option']);
283
284 $this->addFormRule(['CRM_Contribute_Form_AdditionalPayment', 'formRule'], $this);
285 }
286
287 /**
288 * @param $fields
289 * @param $files
290 * @param $self
291 *
292 * @return array
293 */
294 public static function formRule($fields, $files, $self) {
295 $errors = [];
296 if ($self->_paymentType == 'owed' && $fields['total_amount'] > $self->_owed) {
297 $errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
298 }
299 if ($self->_paymentType == 'refund' && $fields['total_amount'] != abs($self->_refund)) {
300 $errors['total_amount'] = ts('Refund amount must equal refund due amount.');
301 }
302 $netAmt = (float) $fields['total_amount'] - (float) CRM_Utils_Array::value('fee_amount', $fields, 0);
303 if (!empty($fields['net_amount']) && $netAmt != $fields['net_amount']) {
304 $errors['net_amount'] = ts('Net amount should be equal to the difference between payment amount and fee amount.');
305 }
306 if ($self->_paymentProcessor['id'] === 0 && empty($fields['payment_instrument_id'])) {
307 $errors['payment_instrument_id'] = ts('Payment method is a required field');
308 }
309
310 return $errors;
311 }
312
313 /**
314 * Process the form submission.
315 */
316 public function postProcess() {
317 $submittedValues = $this->controller->exportValues($this->_name);
318 $this->submit($submittedValues);
319 $childTab = 'contribute';
320 if ($this->_component == 'event') {
321 $childTab = 'participant';
322 }
323 $session = CRM_Core_Session::singleton();
324 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
325 "reset=1&cid={$this->_contactId}&selectedChild={$childTab}"
326 ));
327 }
328
329 /**
330 * Process Payments.
331 *
332 * @param array $submittedValues
333 *
334 * @throws \CiviCRM_API3_Exception
335 */
336 public function submit($submittedValues) {
337 $this->_params = $submittedValues;
338 $this->beginPostProcess();
339 $this->_contributorContactID = $this->_contactID;
340 $this->processBillingAddress();
341 $participantId = NULL;
342 if ($this->_component == 'event') {
343 $participantId = $this->_id;
344 }
345
346 if ($this->_mode) {
347 // process credit card
348 $this->assign('contributeMode', 'direct');
349 $this->processCreditCard();
350 }
351
352 $trxnsData = $this->_params;
353 if ($this->_paymentType == 'refund') {
354 $trxnsData['total_amount'] = -$trxnsData['total_amount'];
355 }
356 $trxnsData['participant_id'] = $participantId;
357 $trxnsData['contribution_id'] = $this->_contributionId;
358 // From the
359 $trxnsData['is_send_contribution_notification'] = FALSE;
360 $paymentID = civicrm_api3('Payment', 'create', $trxnsData)['id'];
361
362 if ($this->_contributionId && CRM_Core_Permission::access('CiviMember')) {
363 $membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', ['contribution_id' => $this->_contributionId]);
364 if ($membershipPaymentCount) {
365 $this->ajaxResponse['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactID);
366 }
367 }
368 if ($this->_contributionId && CRM_Core_Permission::access('CiviEvent')) {
369 $participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', ['contribution_id' => $this->_contributionId]);
370 if ($participantPaymentCount) {
371 $this->ajaxResponse['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactID);
372 }
373 }
374
375 $statusMsg = ts('The payment record has been processed.');
376 // send email
377 if (!empty($paymentID) && !empty($this->_params['is_email_receipt'])) {
378 $sendResult = civicrm_api3('Payment', 'sendconfirmation', ['id' => $paymentID, 'from' => $submittedValues['from_email_address']])['values'][$paymentID];
379 if ($sendResult['is_sent']) {
380 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
381 }
382 }
383
384 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
385 }
386
387 public function processCreditCard() {
388 $config = CRM_Core_Config::singleton();
389 $session = CRM_Core_Session::singleton();
390
391 $now = date('YmdHis');
392 $fields = [];
393
394 // we need to retrieve email address
395 if ($this->_context == 'standalone' && !empty($this->_params['is_email_receipt'])) {
396 list($this->userDisplayName,
397 $this->userEmail
398 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
399 $this->assign('displayName', $this->userDisplayName);
400 }
401
402 $this->formatParamsForPaymentProcessor($this->_params);
403
404 $this->_params['amount'] = $this->_params['total_amount'];
405 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
406 // function to get correct amount level consistently. Remove setting of the amount level in
407 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
408 // to cover all variants.
409 $this->_params['amount_level'] = 0;
410 $this->_params['currencyID'] = CRM_Utils_Array::value('currency',
411 $this->_params,
412 $config->defaultCurrency
413 );
414
415 if (!empty($this->_params['trxn_date'])) {
416 $this->_params['receive_date'] = $this->_params['trxn_date'];
417 }
418
419 if (empty($this->_params['receive_date'])) {
420 $this->_params['receive_date'] = date('YmdHis');
421 }
422
423 if (empty($this->_params['invoice_id'])) {
424 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
425 }
426 else {
427 $this->_params['invoiceID'] = $this->_params['invoice_id'];
428 }
429
430 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
431 $this->_params,
432 $this->_bltID
433 ));
434
435 //Add common data to formatted params
436 $params = $this->_params;
437 CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
438 // at this point we've created a contact and stored its address etc
439 // all the payment processors expect the name and address to be in the
440 // so we copy stuff over to first_name etc.
441 $paymentParams = $this->_params;
442 $paymentParams['contactID'] = $this->_contactId;
443 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
444
445 $paymentParams['contributionPageID'] = NULL;
446 if (!empty($this->_params['is_email_receipt'])) {
447 $paymentParams['email'] = $this->_contributorEmail;
448 $paymentParams['is_email_receipt'] = TRUE;
449 }
450 else {
451 $paymentParams['is_email_receipt'] = $this->_params['is_email_receipt'] = FALSE;
452 }
453
454 $result = NULL;
455
456 if ($paymentParams['amount'] > 0.0) {
457 try {
458 // force a reget of the payment processor in case the form changed it, CRM-7179
459 $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
460 $result = $payment->doPayment($paymentParams);
461 }
462 catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
463 Civi::log()->error('Payment processor exception: ' . $e->getMessage());
464 $urlParams = "action=add&cid={$this->_contactId}&id={$this->_contributionId}&component={$this->_component}&mode={$this->_mode}";
465 CRM_Core_Error::statusBounce(CRM_Utils_System::url($e->getMessage(), 'civicrm/payment/add', $urlParams));
466 }
467 }
468
469 if (!empty($result)) {
470 $this->_params = array_merge($this->_params, $result);
471 }
472
473 if (empty($this->_params['receive_date'])) {
474 $this->_params['receive_date'] = $now;
475 }
476
477 $this->set('params', $this->_params);
478
479 // set source if not set
480 if (empty($this->_params['source'])) {
481 $userID = $session->get('userID');
482 $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
483 'sort_name'
484 );
485 $this->_params['source'] = ts('Submit Credit Card Payment by: %1', [1 => $userSortName]);
486 }
487 }
488
489 /**
490 * Wrapper for unit testing the post process submit function.
491 *
492 * @param array $params
493 * @param string|null $creditCardMode
494 * @param string $entityType
495 *
496 * @throws \CiviCRM_API3_Exception
497 */
498 public function testSubmit($params, $creditCardMode = NULL, $entityType = 'contribute') {
499 $this->_bltID = 5;
500 // Required because processCreditCard calls set method on this.
501 $_SERVER['REQUEST_METHOD'] = 'GET';
502 $this->controller = new CRM_Core_Controller();
503
504 $this->assignPaymentRelatedVariables();
505
506 if (!empty($params['contribution_id'])) {
507 $this->_contributionId = $params['contribution_id'];
508
509 $paymentInfo = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($this->_contributionId, $entityType);
510 $paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_contributionId, $entityType, FALSE, TRUE);
511
512 $this->_amtPaid = $paymentDetails['paid'];
513 $this->_amtTotal = $paymentDetails['total'];
514
515 if (!empty($paymentInfo['refund_due'])) {
516 $this->_refund = $paymentInfo['refund_due'];
517 $this->_paymentType = 'refund';
518 }
519 elseif (!empty($paymentInfo['amount_owed'])) {
520 $this->_owed = $paymentInfo['amount_owed'];
521 $this->_paymentType = 'owed';
522 }
523 }
524
525 if (!empty($params['contact_id'])) {
526 $this->_contactId = $params['contact_id'];
527 }
528
529 if ($creditCardMode) {
530 $this->_mode = $creditCardMode;
531 }
532
533 $this->_fields = [];
534 $this->set('cid', $this->_contactId);
535 parent::preProcess();
536 $this->submit($params);
537 }
538
539 }