Merge pull request #348 from colemanw/ts
[civicrm-core.git] / CRM / Event / Form / EventFees.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 /**
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 None
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' );
82 $details = array();
83 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $form->_eventId, $details, $returnProperities);
84 if ( CRM_Utils_Array::value( 'financial_type_id', $details[$form->_eventId] ) ) {
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 $discounts[$key] = $value['name'];
99 }
100 }
101
102 if ($form->_discountId) {
103 $form->assign('discount', $discounts[$defaults[$form->_pId]['discount_id']]);
104 }
105
106 $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
107 $form->assign('fee_level', CRM_Utils_Array::value('fee_level', $defaults[$form->_pId]));
108 }
109 $defaults[$form->_pId]['send_receipt'] = 0;
110 }
111 else {
112 $defaults[$form->_pId]['send_receipt'] = 1;
113 if ($form->_eventId && CRM_Utils_Array::value('confirm_email_text', $details[$form->_eventId])) {
114 //set receipt text
115 $defaults[$form->_pId]['receipt_text'] = $details[$form->_eventId]['confirm_email_text'];
116 }
117
118 list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults();
119 }
120
121 //CRM-11601 we should keep the record contribution
122 //true by default while adding participant
123 if ($form->_action == CRM_Core_Action::ADD && !$form->_mode && $form->_isPaidEvent) {
124 $defaults[$form->_pId]['record_contribution'] = 1;
125 }
126
127 if ($form->_mode) {
128 $fields = array();
129
130 foreach ($form->_fields as $name => $dontCare) {
131 $fields[$name] = 1;
132 }
133
134 $names = array(
135 'first_name', 'middle_name', 'last_name', "street_address-{$form->_bltID}",
136 "city-{$form->_bltID}", "postal_code-{$form->_bltID}", "country_id-{$form->_bltID}",
137 "state_province_id-{$form->_bltID}",
138 );
139 foreach ($names as $name) {
140 $fields[$name] = 1;
141 }
142
143 $fields["state_province-{$form->_bltID}"] = 1;
144 $fields["country-{$form->_bltID}"] = 1;
145 $fields["email-{$form->_bltID}"] = 1;
146 $fields['email-Primary'] = 1;
147
148 if ($form->_contactId) {
149 CRM_Core_BAO_UFGroup::setProfileDefaults($form->_contactId, $fields, $form->_defaults);
150 }
151
152 // use primary email address if billing email address is empty
153 if (empty($form->_defaults["email-{$form->_bltID}"]) &&
154 !empty($form->_defaults['email-Primary'])
155 ) {
156 $defaults[$form->_pId]["email-{$form->_bltID}"] = $form->_defaults['email-Primary'];
157 }
158
159 foreach ($names as $name) {
160 if (!empty($form->_defaults[$name])) {
161 $defaults[$form->_pId]['billing_' . $name] = $form->_defaults[$name];
162 }
163 }
164
165 $config = CRM_Core_Config::singleton();
166 // set default country from config if no country set
167 if (!CRM_Utils_Array::value("billing_country_id-{$form->_bltID}", $defaults[$form->_pId])) {
168 $defaults[$form->_pId]["billing_country_id-{$form->_bltID}"] = $config->defaultContactCountry;
169 }
170
171 // // hack to simplify credit card entry for testing
172 // $defaults[$form->_pId]['credit_card_type'] = 'Visa';
173 // $defaults[$form->_pId]['credit_card_number'] = '4807731747657838';
174 // $defaults[$form->_pId]['cvv2'] = '000';
175 // $defaults[$form->_pId]['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
176 }
177
178 if ($priceSetId = CRM_Price_BAO_Set::getFor('civicrm_event', $form->_eventId)) {
179 // get price set default values, CRM-4090
180 if (in_array(get_class($form),
181 array(
182 'CRM_Event_Form_Participant',
183 'CRM_Event_Form_Registration_Register',
184 'CRM_Event_Form_Registration_AdditionalParticipant',
185 )
186 )) {
187 $priceSetValues = self::setDefaultPriceSet($form->_pId, $form->_eventId);
188 if (!empty($priceSetValues)) {
189 $defaults[$form->_pId] = array_merge($defaults[$form->_pId], $priceSetValues);
190 }
191 }
192 if ($form->_action == CRM_Core_Action::ADD && CRM_Utils_Array::value('fields', $form->_priceSet)) {
193 foreach ($form->_priceSet['fields'] as $key => $val) {
194 foreach ($val['options'] as $keys => $values) {
195 if ($values['is_default']) {
196 if (get_class($form) != 'CRM_Event_Form_Participant' &&
197 CRM_Utils_Array::value('is_full', $values)
198 ) {
199 continue;
200 }
201
202 if ($val['html_type'] == 'CheckBox') {
203 $defaults[$form->_pId]["price_{$key}"][$keys] = 1;
204 }
205 else {
206 $defaults[$form->_pId]["price_{$key}"] = $keys;
207 }
208 }
209 }
210 }
211 }
212
213 $form->assign('totalAmount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
214 if ($form->_action == CRM_Core_Action::UPDATE) {
215 $fee_level = $defaults[$form->_pId]['fee_level'];
216 CRM_Event_BAO_Participant::fixEventLevel($fee_level);
217 $form->assign('fee_level', $fee_level);
218 $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
219 }
220 }
221 else {
222 $optionGroupId = NULL;
223
224 // if user has selected discount use that to set default
225 if (isset($form->_discountId)) {
226 $defaults[$form->_pId]['discount_id'] = $form->_discountId;
227
228 //hack to set defaults for already selected discount value
229 if ($form->_action == CRM_Core_Action::UPDATE && !$form->_originalDiscountId) {
230 $form->_originalDiscountId = $defaults[$form->_pId]['discount_id'];
231 if ($form->_originalDiscountId) {
232 $optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount',
233 $form->_originalDiscountId,
234 'option_group_id'
235 );
236 $defaults[$form->_pId]['discount_id'] = $form->_originalDiscountId;
237 }
238 }
239 }
240
241 if (($form->_action == CRM_Core_Action::ADD)) {
242 // this case is for add mode, where we show discount automatically
243 if (!isset($form->_discountId)) {
244 $discountId = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
245 }
246 else {
247 $discountId = $form->_discountId;
248 }
249
250 if ($form->_eventId && $discountId) {
251 $defaultDiscountId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
252 $form->_eventId,
253 'default_discount_fee_id'
254 );
255 if ($defaultDiscountId) {
256 $discountKey = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue',
257 $defaultDiscountId,
258 'weight'
259 );
260 }
261
262 $defaults[$form->_pId]['discount_id'] = $discountId;
263
264 $defaults[$form->_pId]['amount'] = key(array_slice($form->_values['discount'][$discountId],
265 $discountKey - 1,
266 $discountKey,
267 TRUE
268 ));
269 $optionGroupId =
270 CRM_Core_DAO::getFieldValue(
271 'CRM_Core_DAO_Discount',
272 $discountId,
273 'option_group_id'
274 );
275 }
276 else {
277 if ($form->_eventId) {
278 $defaults[$form->_pId]['amount'] =
279 CRM_Core_DAO::getFieldValue(
280 'CRM_Event_DAO_Event',
281 $form->_eventId,
282 'default_fee_id'
283 );
284 }
285 }
286 }
287
288 if (CRM_Utils_Array::value('event_id', $defaults[$form->_pId])
289 && ($form->_action == CRM_Core_Action::UPDATE || $form->_allowConfirmation)
290 ) {
291 if (!empty($form->_feeBlock)) {
292 $feeLevel = CRM_Utils_Array::value('fee_level',
293 $defaults[$form->_pId]
294 );
295 $feeAmount = CRM_Utils_Array::value('fee_amount',
296 $defaults[$form->_pId]
297 );
298 foreach ($form->_feeBlock as $amountId => $amountInfo) {
299 if ($amountInfo['label'] == $feeLevel &&
300 $amountInfo['value'] == $feeAmount
301 ) {
302 $defaults[$form->_pId]['amount'] = $amountInfo['amount_id'];
303 }
304
305 // if amount is not set do fuzzy matching
306 if (!isset($defaults[$form->_pId]['amount'])) {
307 // if only level use that
308 if ($amountInfo['label'] == $feeLevel) {
309 $defaults[$form->_pId]['amount'] = $amountInfo['amount_id'];
310 }
311 elseif (strpos($feeLevel, $amountInfo['label']) !== FALSE) {
312 $defaults[$form->_pId]['amount'] = $amountInfo['amount_id'];
313 }
314 elseif ($amountInfo['value'] == $feeAmount) {
315 // if amount matches use that
316 $defaults[$form->_pId]['amount'] = $amountInfo['amount_id'];
317 }
318 }
319 }
320 }
321 }
322 $form->assign('amountId', CRM_Utils_Array::value('amount', $defaults[$form->_pId]));
323 }
324
325 //CRM-4453
326 if (CRM_Utils_Array::value('participant_fee_currency', $defaults[$form->_pId])) {
327 $form->assign('fee_currency', $defaults[$form->_pId]['participant_fee_currency']);
328 }
329
330 // CRM-4395
331 if ($contriId = $form->get('onlinePendingContributionId')) {
332 $contribution = new CRM_Contribute_DAO_Contribution();
333 $contribution->id = $contriId;
334 $contribution->find( true );
335 foreach( array('financial_type_id', 'payment_instrument_id','contribution_status_id', 'receive_date', 'total_amount' ) as $f ) {
336 if ($f == 'receive_date') {
337 list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults($contribution->$f);
338 }
339 else {
340 $defaults[$form->_pId][$f] = $contribution->$f;
341 }
342 }
343 }
344 return $defaults[$form->_pId];
345 }
346
347 /**
348 * This function sets the default values for price set.
349 *
350 * @access public
351 *
352 * @return None
353 */
354 static function setDefaultPriceSet($participantID, $eventID = NULL) {
355 $defaults = array();
356 if (!$eventID && $participantID) {
357 $eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'event_id');
358 }
359 if (!$participantID || !$eventID) {
360 return $defaults;
361 }
362
363 // get price set ID.
364 $priceSetID = CRM_Price_BAO_Set::getFor('civicrm_event', $eventID);
365 if (!$priceSetID) {
366 return $defaults;
367 }
368
369 // use line items for setdefault price set fields, CRM-4090
370 $lineItems[$participantID] = CRM_Price_BAO_LineItem::getLineItems($participantID);
371
372 if (is_array($lineItems[$participantID]) &&
373 !CRM_Utils_System::isNull($lineItems[$participantID])
374 ) {
375
376 $priceFields = $htmlTypes = $optionValues = array();
377 foreach ($lineItems[$participantID] as $lineId => $items) {
378 $priceFieldId = CRM_Utils_Array::value('price_field_id', $items);
379 $priceOptionId = CRM_Utils_Array::value('price_field_value_id', $items);
380 if ($priceFieldId && $priceOptionId) {
381 $priceFields[$priceFieldId][] = $priceOptionId;
382 }
383 }
384
385 if (empty($priceFields)) {
386 return $defaults;
387 }
388
389 // get all price set field html types.
390 $sql = '
391SELECT id, html_type
392 FROM civicrm_price_field
393 WHERE id IN (' . implode(',', array_keys($priceFields)) . ')';
394 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
395 while ($fieldDAO->fetch()) {
396 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
397 }
398
399 foreach ($lineItems[$participantID] as $lineId => $items) {
400 $fieldId = $items['price_field_id'];
401 $htmlType = CRM_Utils_Array::value($fieldId, $htmlTypes);
402 if (!$htmlType) {
403 continue;
404 }
405
406 if ($htmlType == 'Text') {
407 $defaults["price_{$fieldId}"] = $items['qty'];
408 }
409 else {
410 $fieldOptValues = CRM_Utils_Array::value($fieldId, $priceFields);
411 if (!is_array($fieldOptValues)) {
412 continue;
413 }
414
415 foreach ($fieldOptValues as $optionId) {
416 if ($htmlType == 'CheckBox') {
417 $defaults["price_{$fieldId}"][$optionId] = TRUE;
418 }
419 else {
420 $defaults["price_{$fieldId}"] = $optionId;
421 break;
422 }
423 }
424 }
425 }
426 }
427
428 return $defaults;
429 }
430
431 /**
432 * Function to build the form
433 *
434 * @return None
435 * @access public
436 */
437 static function buildQuickForm(&$form) {
438 if ($form->_eventId) {
439 $form->_isPaidEvent = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'is_monetary');
440 if ($form->_isPaidEvent) {
441 $form->addElement('hidden', 'hidden_feeblock', 1);
442 }
443
444 // make sure this is for backoffice registration.
445 if ($form->getName() == 'Participant') {
446 $eventfullMsg = CRM_Event_BAO_Participant::eventFullMessage($form->_eventId, $form->_pId);
447 $form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, array('id' => 'hidden_eventFullMsg'));
448 }
449 }
450
451 if ($form->_pId) {
452 if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
453 $form->_pId, 'contribution_id', 'participant_id'
454 )) {
455 $form->_online = TRUE;
456 }
457 }
458
459 if ($form->_isPaidEvent) {
460 $params = array('id' => $form->_eventId);
461 CRM_Event_BAO_Event::retrieve($params, $event);
462
463 //retrieve custom information
464 $form->_values = array();
465 CRM_Event_Form_Registration::initEventFee($form, $event['id']);
466 CRM_Event_Form_Registration_Register::buildAmount($form, TRUE, $form->_discountId);
467 $lineItem = array();
468 if (!CRM_Utils_System::isNull(CRM_Utils_Array::value('line_items', $form->_values))) {
469 $lineItem[] = $form->_values['line_items'];
470 }
471 $form->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
472 $discounts = array();
473 if (!empty($form->_values['discount'])) {
474 foreach ($form->_values['discount'] as $key => $value) {
475 $discounts[$key] = $value['name'];
476 }
477
478 $element = $form->add('select', 'discount_id',
479 ts('Discount Set'),
480 array(
481 0 => ts('- select -')) + $discounts,
482 FALSE,
483 array('onchange' => "buildFeeBlock( {$form->_eventId}, this.value );")
484 );
485
486 if ($form->_online) {
487 $element->freeze();
488 }
489 }
490 if ($form->_mode) {
491 CRM_Core_Payment_Form::buildCreditCard($form, TRUE);
492 }
493 elseif (!$form->_mode) {
494 $form->addElement('checkbox', 'record_contribution', ts('Record Payment?'), NULL,
495 array('onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);")
496 );
497
498 $form->add('select', 'financial_type_id',
499 ts( 'Financial Type' ),
500 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType()
501 );
502
503 $form->addDate('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDate'));
504
505 $form->add('select', 'payment_instrument_id',
506 ts('Paid By'),
507 array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
508 FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
509 );
510 // don't show transaction id in batch update mode
511 $path = CRM_Utils_System::currentPath();
512 $form->assign('showTransactionId', FALSE);
513 if ($path != 'civicrm/contact/search/basic') {
514 $form->add('text', 'trxn_id', ts('Transaction ID'));
515 $form->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
516 'objectExists', array('CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id')
517 );
518 $form->assign('showTransactionId', TRUE);
519 }
520
521 $allowStatuses = array();
522 $statuses = CRM_Contribute_PseudoConstant::contributionStatus();
523 if ($form->get('onlinePendingContributionId')) {
524 $statusNames = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
525 foreach ($statusNames as $val => $name) {
526 if (in_array($name, array(
527 'In Progress', 'Overdue'))) {
528 continue;
529 }
530 $allowStatuses[$val] = $statuses[$val];
531 }
532 }
533 else {
534 $allowStatuses = $statuses;
535 }
536 $form->add('select', 'contribution_status_id',
537 ts('Payment Status'), $allowStatuses
538 );
539
540 $form->add('text', 'check_number', ts('Check Number'),
541 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
542 );
543
544 $form->add('text', 'total_amount', ts('Total Amount'),
545 CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'total_amount')
546 );
547 }
548 }
549 else {
550 $form->add('text', 'amount', ts('Event Fee(s)'));
551 }
552 $form->assign('onlinePendingContributionId', $form->get('onlinePendingContributionId'));
553
554 $form->assign('paid', $form->_isPaidEvent);
555
556 $form->addElement('checkbox',
557 'send_receipt',
558 ts('Send Confirmation?'), NULL,
559 array('onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);")
560 );
561
562 $form->add('select', 'from_email_address', ts('Receipt From'), $form->_fromEmails['from_email_id']);
563
564 $form->add('textarea', 'receipt_text', ts('Confirmation Message'));
565
566 // Retrieve the name and email of the contact - form will be the TO for receipt email ( only if context is not standalone)
567 if ($form->_context != 'standalone') {
568 if ($form->_contactId) {
569 list($form->_contributorDisplayName,
570 $form->_contributorEmail
571 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($form->_contactId);
572 $form->assign('email', $form->_contributorEmail);
573 }
574 else {
575 //show email block for batch update for event
576 $form->assign('batchEmail', TRUE);
577 }
578 }
579
580 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
581 'mailing_backend'
582 );
583 $form->assign('outBound_option', $mailingInfo['outBound_option']);
584 $form->assign('hasPayment', $form->_paymentId);
585 }
586}
587