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