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