Merge pull request #11197 from agileware/CRM-21104
[civicrm-core.git] / CRM / Event / Form / EventFees.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 *
31 * @package CRM
8c9251b3 32 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
33 */
34
35/**
36 * This class generates form components for processing a participation fee block
37 */
38class CRM_Event_Form_EventFees {
39
40 /**
66f9e52b 41 * Set variables up before form is built.
6a488035 42 *
c490a46a 43 * @param CRM_Core_Form $form
6a488035 44 */
00be9182 45 public static function preProcess(&$form) {
6a488035
TO
46 //as when call come from register.php
47 if (!$form->_eventId) {
48 $form->_eventId = CRM_Utils_Request::retrieve('eventId', 'Positive', $form);
49 }
50
51 $form->_pId = CRM_Utils_Request::retrieve('participantId', 'Positive', $form);
52 $form->_discountId = CRM_Utils_Request::retrieve('discountId', 'Positive', $form);
53
54 $form->_fromEmails = CRM_Event_BAO_Event::getFromEmailIds($form->_eventId);
55
56 //CRM-6907 set event specific currency.
57 if ($form->_eventId &&
58 ($currency = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'currency'))
59 ) {
079dc599 60 CRM_Core_Config::singleton()->defaultCurrency = $currency;
6a488035
TO
61 }
62 }
63
64 /**
f3f00653 65 * This function sets the default values for the form in edit/view mode.
6a488035 66 *
c490a46a 67 * @param CRM_Core_Form $form
f3f00653 68 *
69 * @return array
6a488035 70 */
00be9182 71 public static function setDefaultValues(&$form) {
6a488035
TO
72 $defaults = array();
73
74 if ($form->_eventId) {
75 //get receipt text and financial type
481a74f4 76 $returnProperities = array('confirm_email_text', 'financial_type_id', 'campaign_id', 'start_date');
6a488035
TO
77 $details = array();
78 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $form->_eventId, $details, $returnProperities);
a7488080 79 if (!empty($details[$form->_eventId]['financial_type_id'])) {
6a488035
TO
80 $defaults[$form->_pId]['financial_type_id'] = $details[$form->_eventId]['financial_type_id'];
81 }
82 }
83
84 if ($form->_pId) {
85 $ids = array();
86 $params = array('id' => $form->_pId);
87
88 CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
89 if ($form->_action == CRM_Core_Action::UPDATE) {
90 $discounts = array();
91 if (!empty($form->_values['discount'])) {
92 foreach ($form->_values['discount'] as $key => $value) {
8567d0f8 93 $value = current($value);
6a488035
TO
94 $discounts[$key] = $value['name'];
95 }
96 }
97
8cc574cf 98 if ($form->_discountId && !empty($discounts[$defaults[$form->_pId]['discount_id']])) {
6a488035
TO
99 $form->assign('discount', $discounts[$defaults[$form->_pId]['discount_id']]);
100 }
101
102 $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
103 $form->assign('fee_level', CRM_Utils_Array::value('fee_level', $defaults[$form->_pId]));
104 }
105 $defaults[$form->_pId]['send_receipt'] = 0;
106 }
107 else {
18eaa61b 108 $defaults[$form->_pId]['send_receipt'] = (strtotime(CRM_Utils_Array::value('start_date', $details[$form->_eventId])) >= time()) ? 1 : 0;
8cc574cf 109 if ($form->_eventId && !empty($details[$form->_eventId]['confirm_email_text'])) {
6a488035
TO
110 //set receipt text
111 $defaults[$form->_pId]['receipt_text'] = $details[$form->_eventId]['confirm_email_text'];
112 }
113
53f56880 114 list($defaults[$form->_pId]['receive_date'], $defaults[$form->_pId]['receive_date_time']) = CRM_Utils_Date::setDateDefaults();
6a488035
TO
115 }
116
f55dc004 117 //CRM-11601 we should keep the record contribution
6a488035 118 //true by default while adding participant
d96cf288 119 if ($form->_action == CRM_Core_Action::ADD && !$form->_mode && $form->_isPaidEvent) {
6a488035
TO
120 $defaults[$form->_pId]['record_contribution'] = 1;
121 }
77b97be7 122
d96cf288 123 //CRM-13420
a7488080 124 if (empty($defaults['payment_instrument_id'])) {
d96cf288
DG
125 $defaults[$form->_pId]['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
126 }
6a488035 127 if ($form->_mode) {
6a488035
TO
128 $config = CRM_Core_Config::singleton();
129 // set default country from config if no country set
a7488080 130 if (empty($defaults[$form->_pId]["billing_country_id-{$form->_bltID}"])) {
6a488035
TO
131 $defaults[$form->_pId]["billing_country_id-{$form->_bltID}"] = $config->defaultContactCountry;
132 }
133
a7488080 134 if (empty($defaults["billing_state_province_id-{$form->_bltID}"])) {
cc44e307 135 $defaults[$form->_pId]["billing_state_province_id-{$form->_bltID}"] = $config->defaultContactStateProvince;
136 }
137
138 $billingDefaults = $form->getProfileDefaults('Billing', $form->_contactId);
139 $defaults[$form->_pId] = array_merge($defaults[$form->_pId], $billingDefaults);
140
6a488035
TO
141 // // hack to simplify credit card entry for testing
142 // $defaults[$form->_pId]['credit_card_type'] = 'Visa';
143 // $defaults[$form->_pId]['credit_card_number'] = '4807731747657838';
144 // $defaults[$form->_pId]['cvv2'] = '000';
145 // $defaults[$form->_pId]['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
146 }
147
8567d0f8
PN
148 // if user has selected discount use that to set default
149 if (isset($form->_discountId)) {
150 $defaults[$form->_pId]['discount_id'] = $form->_discountId;
151
152 //hack to set defaults for already selected discount value
153 if ($form->_action == CRM_Core_Action::UPDATE && !$form->_originalDiscountId) {
154 $form->_originalDiscountId = $defaults[$form->_pId]['discount_id'];
155 if ($form->_originalDiscountId) {
156 $defaults[$form->_pId]['discount_id'] = $form->_originalDiscountId;
157 }
158 }
159 $discountId = $form->_discountId;
160 }
161 else {
162 $discountId = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
163 }
8ef12e64 164
8567d0f8
PN
165 if ($discountId) {
166 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
167 }
168 else {
9da8dc8c 169 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $form->_eventId);
8567d0f8
PN
170 }
171
172 if (($form->_action == CRM_Core_Action::ADD) && $form->_eventId && $discountId) {
173 // this case is for add mode, where we show discount automatically
0479b4c8 174 $defaults[$form->_pId]['discount_id'] = $discountId;
8567d0f8
PN
175 }
176
8567d0f8 177 if ($priceSetId) {
6a488035
TO
178 // get price set default values, CRM-4090
179 if (in_array(get_class($form),
353ffa53
TO
180 array(
181 'CRM_Event_Form_Participant',
182 'CRM_Event_Form_Registration_Register',
183 'CRM_Event_Form_Registration_AdditionalParticipant',
184 )
185 )) {
6a488035
TO
186 $priceSetValues = self::setDefaultPriceSet($form->_pId, $form->_eventId);
187 if (!empty($priceSetValues)) {
188 $defaults[$form->_pId] = array_merge($defaults[$form->_pId], $priceSetValues);
189 }
190 }
8ef12e64 191
8cc574cf 192 if ($form->_action == CRM_Core_Action::ADD && !empty($form->_priceSet['fields'])) {
6a488035
TO
193 foreach ($form->_priceSet['fields'] as $key => $val) {
194 foreach ($val['options'] as $keys => $values) {
195 if ($values['is_default']) {
8cc574cf 196 if (get_class($form) != 'CRM_Event_Form_Participant' && !empty($values['is_full'])) {
6a488035
TO
197 continue;
198 }
199
200 if ($val['html_type'] == 'CheckBox') {
201 $defaults[$form->_pId]["price_{$key}"][$keys] = 1;
202 }
203 else {
204 $defaults[$form->_pId]["price_{$key}"] = $keys;
205 }
206 }
207 }
208 }
209 }
210
211 $form->assign('totalAmount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
212 if ($form->_action == CRM_Core_Action::UPDATE) {
213 $fee_level = $defaults[$form->_pId]['fee_level'];
214 CRM_Event_BAO_Participant::fixEventLevel($fee_level);
215 $form->assign('fee_level', $fee_level);
216 $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
217 }
218 }
6a488035
TO
219
220 //CRM-4453
a7488080 221 if (!empty($defaults[$form->_pId]['participant_fee_currency'])) {
6a488035
TO
222 $form->assign('fee_currency', $defaults[$form->_pId]['participant_fee_currency']);
223 }
224
225 // CRM-4395
226 if ($contriId = $form->get('onlinePendingContributionId')) {
610d2dac 227 $defaults[$form->_pId]['record_contribution'] = 1;
6a488035
TO
228 $contribution = new CRM_Contribute_DAO_Contribution();
229 $contribution->id = $contriId;
481a74f4 230 $contribution->find(TRUE);
353ffa53
TO
231 foreach (array(
232 'financial_type_id',
233 'payment_instrument_id',
234 'contribution_status_id',
235 'receive_date',
389bcebf 236 'total_amount',
353ffa53 237 ) as $f) {
6a488035
TO
238 if ($f == 'receive_date') {
239 list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults($contribution->$f);
240 }
241 else {
242 $defaults[$form->_pId][$f] = $contribution->$f;
243 }
244 }
245 }
246 return $defaults[$form->_pId];
247 }
248
249 /**
250 * This function sets the default values for price set.
251 *
100fef9d
CW
252 * @param int $participantID
253 * @param int $eventID
77b97be7
EM
254 * @param bool $includeQtyZero
255 *
3bdf1f3a 256 * @return array
6a488035 257 */
00be9182 258 public static function setDefaultPriceSet($participantID, $eventID = NULL, $includeQtyZero = TRUE) {
6a488035
TO
259 $defaults = array();
260 if (!$eventID && $participantID) {
261 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'event_id');
262 }
263 if (!$participantID || !$eventID) {
264 return $defaults;
265 }
266
267 // get price set ID.
9da8dc8c 268 $priceSetID = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID);
6a488035
TO
269 if (!$priceSetID) {
270 return $defaults;
271 }
272
273 // use line items for setdefault price set fields, CRM-4090
77dbdcbc 274 $lineItems[$participantID] = CRM_Price_BAO_LineItem::getLineItems($participantID, 'participant', FALSE, $includeQtyZero);
6a488035
TO
275
276 if (is_array($lineItems[$participantID]) &&
277 !CRM_Utils_System::isNull($lineItems[$participantID])
278 ) {
279
280 $priceFields = $htmlTypes = $optionValues = array();
281 foreach ($lineItems[$participantID] as $lineId => $items) {
282 $priceFieldId = CRM_Utils_Array::value('price_field_id', $items);
283 $priceOptionId = CRM_Utils_Array::value('price_field_value_id', $items);
284 if ($priceFieldId && $priceOptionId) {
285 $priceFields[$priceFieldId][] = $priceOptionId;
286 }
287 }
288
289 if (empty($priceFields)) {
290 return $defaults;
291 }
292
293 // get all price set field html types.
294 $sql = '
295SELECT id, html_type
296 FROM civicrm_price_field
297 WHERE id IN (' . implode(',', array_keys($priceFields)) . ')';
298 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
299 while ($fieldDAO->fetch()) {
300 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
301 }
302
303 foreach ($lineItems[$participantID] as $lineId => $items) {
304 $fieldId = $items['price_field_id'];
305 $htmlType = CRM_Utils_Array::value($fieldId, $htmlTypes);
306 if (!$htmlType) {
307 continue;
308 }
309
310 if ($htmlType == 'Text') {
311 $defaults["price_{$fieldId}"] = $items['qty'];
312 }
313 else {
314 $fieldOptValues = CRM_Utils_Array::value($fieldId, $priceFields);
315 if (!is_array($fieldOptValues)) {
316 continue;
317 }
318
319 foreach ($fieldOptValues as $optionId) {
320 if ($htmlType == 'CheckBox') {
321 $defaults["price_{$fieldId}"][$optionId] = TRUE;
322 }
323 else {
324 $defaults["price_{$fieldId}"] = $optionId;
325 break;
326 }
327 }
328 }
329 }
330 }
331
332 return $defaults;
333 }
334
335 /**
66f9e52b 336 * Build the form object.
6a488035 337 *
c490a46a 338 * @param CRM_Core_Form $form
6a488035 339 */
00be9182 340 public static function buildQuickForm(&$form) {
6a488035
TO
341 if ($form->_eventId) {
342 $form->_isPaidEvent = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'is_monetary');
343 if ($form->_isPaidEvent) {
344 $form->addElement('hidden', 'hidden_feeblock', 1);
345 }
346
347 // make sure this is for backoffice registration.
348 if ($form->getName() == 'Participant') {
349 $eventfullMsg = CRM_Event_BAO_Participant::eventFullMessage($form->_eventId, $form->_pId);
350 $form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, array('id' => 'hidden_eventFullMsg'));
351 }
352 }
353
354 if ($form->_pId) {
355 if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
353ffa53
TO
356 $form->_pId, 'contribution_id', 'participant_id'
357 )
358 ) {
6a488035
TO
359 $form->_online = TRUE;
360 }
361 }
362
363 if ($form->_isPaidEvent) {
364 $params = array('id' => $form->_eventId);
365 CRM_Event_BAO_Event::retrieve($params, $event);
366
367 //retrieve custom information
368 $form->_values = array();
369 CRM_Event_Form_Registration::initEventFee($form, $event['id']);
370 CRM_Event_Form_Registration_Register::buildAmount($form, TRUE, $form->_discountId);
371 $lineItem = array();
aaffa79f 372 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
03b412ae 373 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
a32709be 374 $totalTaxAmount = 0;
6a488035
TO
375 if (!CRM_Utils_System::isNull(CRM_Utils_Array::value('line_items', $form->_values))) {
376 $lineItem[] = $form->_values['line_items'];
a32709be
PB
377 foreach ($form->_values['line_items'] as $key => $value) {
378 $totalTaxAmount = $value['tax_amount'] + $totalTaxAmount;
379 }
6a488035 380 }
03b412ae
PB
381 if ($invoicing) {
382 $form->assign('totalTaxAmount', $totalTaxAmount);
383 }
6a488035
TO
384 $form->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
385 $discounts = array();
386 if (!empty($form->_values['discount'])) {
387 foreach ($form->_values['discount'] as $key => $value) {
8567d0f8 388 $value = current($value);
6a488035
TO
389 $discounts[$key] = $value['name'];
390 }
391
392 $element = $form->add('select', 'discount_id',
393 ts('Discount Set'),
394 array(
389bcebf 395 0 => ts('- select -'),
353ffa53 396 ) + $discounts,
6a488035 397 FALSE,
95e7a695 398 array('class' => "crm-select2")
6a488035
TO
399 );
400
401 if ($form->_online) {
402 $element->freeze();
403 }
404 }
6b136ad7 405 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
b55aa3de
PN
406 && !CRM_Utils_Array::value('fee', $form->_values)
407 && CRM_Utils_Array::value('snippet', $_REQUEST) == CRM_Core_Smarty::PRINT_NOFORM
f4322a77 408 ) {
593379ad 409 CRM_Core_Session::setStatus(ts('You do not have all the permissions needed for this page.'), 'Permission Denied', 'error');
f4322a77
PN
410 return FALSE;
411 }
0dc4ef42 412
413 CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, FALSE, TRUE, self::getDefaultPaymentInstrumentId());
414 if (!$form->_mode) {
6a488035
TO
415 $form->addElement('checkbox', 'record_contribution', ts('Record Payment?'), NULL,
416 array('onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);")
417 );
a4ef4eac 418 // Check permissions for financial type first
5256492b 419 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
573fd305 420 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $form->_action);
5256492b
E
421 }
422 else {
423 $financialTypes = CRM_Contribute_PseudoConstant::financialType();
424 }
6a488035
TO
425
426 $form->add('select', 'financial_type_id',
481a74f4 427 ts('Financial Type'),
a4ef4eac 428 array('' => ts('- select -')) + $financialTypes
6a488035
TO
429 );
430
53f56880 431 $form->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
6a488035
TO
432
433 $form->add('select', 'payment_instrument_id',
4db803dd 434 ts('Payment Method'),
6a488035
TO
435 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
436 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
437 );
438 // don't show transaction id in batch update mode
439 $path = CRM_Utils_System::currentPath();
440 $form->assign('showTransactionId', FALSE);
441 if ($path != 'civicrm/contact/search/basic') {
442 $form->add('text', 'trxn_id', ts('Transaction ID'));
443 $form->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
444 'objectExists', array('CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id')
445 );
446 $form->assign('showTransactionId', TRUE);
447 }
448
6a488035 449 $form->add('select', 'contribution_status_id',
7fe7b63d 450 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses('participant')
6a488035
TO
451 );
452
453 $form->add('text', 'check_number', ts('Check Number'),
454 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
455 );
456
b8c7e40c 457 $form->add('text', 'total_amount', ts('Amount'),
6a488035
TO
458 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'total_amount')
459 );
460 }
461 }
462 else {
463 $form->add('text', 'amount', ts('Event Fee(s)'));
464 }
465 $form->assign('onlinePendingContributionId', $form->get('onlinePendingContributionId'));
466
467 $form->assign('paid', $form->_isPaidEvent);
468
469 $form->addElement('checkbox',
470 'send_receipt',
471 ts('Send Confirmation?'), NULL,
472 array('onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);")
473 );
474
475 $form->add('select', 'from_email_address', ts('Receipt From'), $form->_fromEmails['from_email_id']);
476
477 $form->add('textarea', 'receipt_text', ts('Confirmation Message'));
478
479 // Retrieve the name and email of the contact - form will be the TO for receipt email ( only if context is not standalone)
480 if ($form->_context != 'standalone') {
481 if ($form->_contactId) {
482 list($form->_contributorDisplayName,
483 $form->_contributorEmail
353ffa53 484 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($form->_contactId);
6a488035
TO
485 $form->assign('email', $form->_contributorEmail);
486 }
487 else {
488 //show email block for batch update for event
489 $form->assign('batchEmail', TRUE);
490 }
491 }
492
aaffa79f 493 $mailingInfo = Civi::settings()->get('mailing_backend');
6a488035
TO
494 $form->assign('outBound_option', $mailingInfo['outBound_option']);
495 $form->assign('hasPayment', $form->_paymentId);
496 }
96025800 497
0dc4ef42 498 /**
499 * Get the default payment instrument id.
500 *
501 * @todo resolve relationship between this form & abstractEdit -which should be it's parent.
502 *
503 * @return int
504 */
505 protected static function getDefaultPaymentInstrumentId() {
506 $paymentInstrumentID = CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer');
507 if ($paymentInstrumentID) {
508 return $paymentInstrumentID;
509 }
510 return key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
511 }
512
6a488035 513}