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