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