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