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