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