Merge pull request #9949 from totten/master-hook-ev2
[civicrm-core.git] / CRM / Event / Form / ManageEvent / Fee.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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 * @package CRM
30 * @copyright CiviCRM LLC (c) 2004-2017
31 */
32
33 /**
34 * This class generates form components for Event Fees.
35 */
36 class CRM_Event_Form_ManageEvent_Fee extends CRM_Event_Form_ManageEvent {
37
38 /**
39 * Constants for number of options for data types of multiple option.
40 */
41 const NUM_OPTION = 11;
42
43 /**
44 * Constants for number of discounts for the event.
45 */
46 const NUM_DISCOUNT = 6;
47
48 /**
49 * Page action.
50 */
51 public $_action;
52
53 /**
54 * In Date.
55 */
56 private $_inDate;
57
58 /**
59 * Set variables up before form is built.
60 */
61 public function preProcess() {
62 parent::preProcess();
63 }
64
65 /**
66 * Set default values for the form.
67 *
68 * For edit/view mode the default values are retrieved from the database.
69 */
70 public function setDefaultValues() {
71 $parentDefaults = parent::setDefaultValues();
72
73 $eventId = $this->_id;
74 $params = array();
75 $defaults = array();
76 if (isset($eventId)) {
77 $params = array('id' => $eventId);
78 }
79
80 CRM_Event_BAO_Event::retrieve($params, $defaults);
81
82 if (isset($eventId)) {
83 $price_set_id = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventId, NULL, 1);
84
85 if ($price_set_id) {
86 $defaults['price_set_id'] = $price_set_id;
87 }
88 else {
89 $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventId, NULL);
90 if ($priceSetId) {
91 if ($isQuick = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
92 $this->assign('isQuick', $isQuick);
93 $priceField = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $priceSetId, 'id', 'price_set_id');
94 $options = array();
95 $priceFieldOptions = CRM_Price_BAO_PriceFieldValue::getValues($priceField, $options, 'weight', TRUE);
96 $defaults['price_field_id'] = $priceField;
97 $countRow = 0;
98 foreach ($options as $optionId => $optionValue) {
99 $countRow++;
100 $defaults['value'][$countRow] = CRM_Utils_Money::format($optionValue['amount'], NULL, '%a');
101 $defaults['label'][$countRow] = $optionValue['label'];
102 $defaults['name'][$countRow] = $optionValue['name'];
103 $defaults['weight'][$countRow] = $optionValue['weight'];
104 $defaults['price_field_value'][$countRow] = $optionValue['id'];
105 if ($optionValue['is_default']) {
106 $defaults['default'] = $countRow;
107 }
108 }
109 }
110 }
111 }
112 }
113
114 //check if discounted
115 $discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($this->_id, 'civicrm_event');
116 if (!empty($discountedEvent)) {
117 $defaults['is_discount'] = $i = 1;
118 $totalLables = $maxSize = $defaultDiscounts = array();
119 foreach ($discountedEvent as $optionGroupId) {
120 $defaults['discount_price_set'][] = $optionGroupId;
121 $name = $defaults["discount_name[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $optionGroupId, 'title');
122
123 list($defaults["discount_start_date[$i]"]) = CRM_Utils_Date::setDateDefaults(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
124 'start_date', 'price_set_id'
125 ));
126 list($defaults["discount_end_date[$i]"]) = CRM_Utils_Date::setDateDefaults(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
127 'end_date', 'price_set_id'
128 ));
129 $defaultDiscounts[] = CRM_Price_BAO_PriceSet::getSetDetail($optionGroupId);
130 $i++;
131 }
132
133 //avoid moving up value of lable when some labels don't
134 //have a value ,fixed for CRM-3088
135 $rowCount = 1;
136 foreach ($defaultDiscounts as $val) {
137 $discountFields = current($val);
138 $discountFields = current($discountFields['fields']);
139
140 foreach ($discountFields['options'] as $discountFieldsval) {
141 $defaults['discounted_label'][$discountFieldsval['weight']] = $discountFieldsval['label'];
142 $defaults['discounted_value'][$discountFieldsval['weight']][$rowCount] = CRM_Utils_Money::format($discountFieldsval['amount'], NULL, '%a');
143 $defaults['discount_option_id'][$rowCount][$discountFieldsval['weight']] = $discountFieldsval['id'];
144 if (!empty($discountFieldsval['is_default'])) {
145 $defaults['discounted_default'] = $discountFieldsval['weight'];
146 }
147 }
148 $rowCount++;
149 }
150 //CRM-12970
151 ksort($defaults['discounted_value']);
152 ksort($defaults['discounted_label']);
153 $rowCount = 1;
154 foreach ($defaults['discounted_label'] as $key => $value) {
155 if ($key != $rowCount) {
156 $defaults['discounted_label'][$rowCount] = $value;
157 $defaults['discounted_value'][$rowCount] = $defaults['discounted_value'][$key];
158 unset($defaults['discounted_value'][$key]);
159 unset($defaults['discounted_label'][$key]);
160 foreach ($defaults['discount_option_id'] as &$optionIds) {
161 if (array_key_exists($key, $optionIds)) {
162 $optionIds[$rowCount] = $optionIds[$key];
163 unset($optionIds[$key]);
164 }
165 }
166 }
167 $rowCount++;
168 }
169
170 $this->set('discountSection', 1);
171 $this->buildQuickForm();
172 }
173 elseif (!empty($defaults['label'])) {
174 //if Regular Fees are present in DB and event fee page is in update mode
175 $defaults['discounted_label'] = $defaults['label'];
176 }
177 elseif (!empty($this->_submitValues['label'])) {
178 //if event is newly created, use submitted values for
179 //discount labels
180 if (is_array($this->_submitValues['label'])) {
181 $k = 1;
182 foreach ($this->_submitValues['label'] as $value) {
183 if ($value) {
184 $defaults['discounted_label'][$k] = $value;
185 $k++;
186 }
187 }
188 }
189 }
190 $defaults['id'] = $eventId;
191 if (!empty($totalLables)) {
192 $maxKey = count($totalLables) - 1;
193 if (isset($maxKey) && !empty($totalLables[$maxKey]['value'])) {
194 foreach ($totalLables[$maxKey]['value'] as $i => $v) {
195 if ($totalLables[$maxKey]['amount_id'][$i] == CRM_Utils_Array::value('default_discount_fee_id', $defaults)) {
196 $defaults['discounted_default'] = $i;
197 break;
198 }
199 }
200 }
201 }
202
203 if (!isset($defaults['discounted_default'])) {
204 $defaults['discounted_default'] = 1;
205 }
206
207 if (!isset($defaults['is_monetary'])) {
208 $defaults['is_monetary'] = 1;
209 }
210
211 if (!isset($defaults['fee_label'])) {
212 $defaults['fee_label'] = ts('Event Fee(s)');
213 }
214
215 if (!isset($defaults['pay_later_text']) ||
216 empty($defaults['pay_later_text'])
217 ) {
218 $defaults['pay_later_text'] = ts('I will send payment by check');
219 }
220
221 $this->_showHide = new CRM_Core_ShowHideBlocks();
222 if (!$defaults['is_monetary']) {
223 $this->_showHide->addHide('event-fees');
224 }
225
226 if (isset($defaults['price_set_id'])) {
227 $this->_showHide->addHide('map-field');
228 }
229 $this->_showHide->addToTemplate();
230 $this->assign('inDate', $this->_inDate);
231
232 if (!empty($defaults['payment_processor'])) {
233 $defaults['payment_processor'] = str_replace(CRM_Core_DAO::VALUE_SEPARATOR, ',',
234 $defaults['payment_processor']
235 );
236 }
237 return $defaults;
238 }
239
240 /**
241 * Build the form object.
242 */
243 public function buildQuickForm() {
244
245 $this->addYesNo('is_monetary',
246 ts('Paid Event'),
247 NULL,
248 NULL,
249 array('onclick' => "return showHideByValue('is_monetary','0','event-fees','block','radio',false);")
250 );
251
252 //add currency element.
253 $this->addCurrency('currency', ts('Currency'), FALSE);
254
255 $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor();
256
257 $this->assign('paymentProcessor', $paymentProcessor);
258
259 $this->addEntityRef('payment_processor', ts('Payment Processor'), array(
260 'entity' => 'PaymentProcessor',
261 'multiple' => TRUE,
262 'api' => array(
263 'params' => array('domain_id' => CRM_Core_Config::domainID()),
264 ),
265 'select' => array('minimumInputLength' => 0),
266 ));
267
268 // financial type
269 if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() ||
270 (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && CRM_Core_Permission::check('administer CiviCRM Financial Types'))) {
271 $this->addSelect('financial_type_id');
272 }
273 else {
274 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::ADD);
275 $this->addSelect('financial_type_id', array('context' => 'search', 'options' => $financialTypes));
276 }
277 // add pay later options
278 $this->addElement('checkbox', 'is_pay_later', ts('Enable Pay Later option?'), NULL,
279 array('onclick' => "return showHideByValue('is_pay_later','','payLaterOptions','block','radio',false);")
280 );
281 $this->addElement('textarea', 'pay_later_text', ts('Pay Later Label'),
282 CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'pay_later_text'),
283 FALSE
284 );
285 $this->add('wysiwyg', 'pay_later_receipt', ts('Pay Later Instructions'), CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'pay_later_receipt'));
286
287 $this->addElement('checkbox', 'is_billing_required', ts('Billing address required'));
288 $this->add('text', 'fee_label', ts('Fee Label'));
289
290 $price = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviEvent');
291 if (CRM_Utils_System::isNull($price)) {
292 $this->assign('price', FALSE);
293 }
294 else {
295 $this->assign('price', TRUE);
296 }
297 $this->add('select', 'price_set_id', ts('Price Set'),
298 array(
299 '' => ts('- none -'),
300 ) + $price,
301 NULL, array('onchange' => "return showHideByValue('price_set_id', '', 'map-field', 'block', 'select', false);")
302 );
303 $default = array($this->createElement('radio', NULL, NULL, NULL, 0));
304 $this->add('hidden', 'price_field_id', '', array('id' => 'price_field_id'));
305 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
306 // label
307 $this->add('text', "label[$i]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'));
308 $this->add('hidden', "price_field_value[$i]", '', array('id' => "price_field_value[$i]"));
309
310 // value
311 $this->add('text', "value[$i]", ts('Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'));
312 $this->addRule("value[$i]", ts('Please enter a valid money value for this field (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
313
314 // default
315 $default[] = $this->createElement('radio', NULL, NULL, NULL, $i);
316 }
317
318 $this->addGroup($default, 'default');
319
320 $this->addElement('checkbox', 'is_discount', ts('Discounts by Signup Date?'), NULL,
321 array('onclick' => "warnDiscountDel(); return showHideByValue('is_discount','','discount','block','radio',false);")
322 );
323 $discountSection = $this->get('discountSection');
324
325 $this->assign('discountSection', $discountSection);
326
327 // form fields of Discount sets
328 $defaultOption = array();
329 $_showHide = new CRM_Core_ShowHideBlocks('', '');
330
331 for ($i = 1; $i <= self::NUM_DISCOUNT; $i++) {
332 //the show hide blocks
333 $showBlocks = 'discount_' . $i;
334 if ($i > 2) {
335 $_showHide->addHide($showBlocks);
336 }
337 else {
338 $_showHide->addShow($showBlocks);
339 }
340
341 //Increment by 1 of start date of previous end date.
342 if (is_array($this->_submitValues) &&
343 !empty($this->_submitValues['discount_name'][$i]) &&
344 !empty($this->_submitValues['discount_name'][$i + 1]) &&
345 isset($this->_submitValues['discount_end_date']) &&
346 isset($this->_submitValues['discount_end_date'][$i]) &&
347 $i < self::NUM_DISCOUNT - 1
348 ) {
349 $end_date = CRM_Utils_Date::processDate($this->_submitValues['discount_end_date'][$i]);
350 if (!empty($this->_submitValues['discount_end_date'][$i + 1])
351 && empty($this->_submitValues['discount_start_date'][$i + 1])
352 ) {
353 list($this->_submitValues['discount_start_date'][$i + 1]) = CRM_Utils_Date::setDateDefaults(date('Y-m-d', strtotime("+1 days $end_date")));
354 }
355 }
356 //Decrement by 1 of end date from next start date.
357 if ($i > 1 &&
358 is_array($this->_submitValues) &&
359 !empty($this->_submitValues['discount_name'][$i]) &&
360 !empty($this->_submitValues['discount_name'][$i - 1]) &&
361 isset($this->_submitValues['discount_start_date']) &&
362 isset($this->_submitValues['discount_start_date'][$i])
363 ) {
364 $start_date = CRM_Utils_Date::processDate($this->_submitValues['discount_start_date'][$i]);
365 if (!empty($this->_submitValues['discount_start_date'][$i])
366 && empty($this->_submitValues['discount_end_date'][$i - 1])
367 ) {
368 list($this->_submitValues['discount_end_date'][$i - 1]) = CRM_Utils_Date::setDateDefaults(date('Y-m-d', strtotime("-1 days $start_date")));
369 }
370 }
371
372 //discount name
373 $this->add('text', 'discount_name[' . $i . ']', ts('Discount Name'),
374 CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'title')
375 );
376
377 $this->add('hidden', "discount_price_set[$i]", '', array('id' => "discount_price_set[$i]"));
378
379 //discount start date
380 $this->addDate('discount_start_date[' . $i . ']', ts('Discount Start Date'), FALSE, array('formatType' => 'activityDate'));
381
382 //discount end date
383 $this->addDate('discount_end_date[' . $i . ']', ts('Discount End Date'), FALSE, array('formatType' => 'activityDate'));
384 }
385 $_showHide->addToTemplate();
386 $this->addElement('submit', $this->getButtonName('submit'), ts('Add Discount Set to Fee Table'),
387 array('class' => 'crm-form-submit cancel')
388 );
389 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
390 $deferredFinancialType = CRM_Financial_BAO_FinancialAccount::getDeferredFinancialType();
391 $this->assign('deferredFinancialType', array_keys($deferredFinancialType));
392 }
393 $this->buildAmountLabel();
394 parent::buildQuickForm();
395 }
396
397 /**
398 * Add local and global form rules.
399 */
400 public function addRules() {
401 $this->addFormRule(array('CRM_Event_Form_ManageEvent_Fee', 'formRule'));
402 }
403
404 /**
405 * Global validation rules for the form.
406 *
407 * @param array $values
408 * Posted values of the form.
409 *
410 * @return array
411 * list of errors to be posted back to the form
412 */
413 public static function formRule($values) {
414 $errors = array();
415 if (!empty($values['is_discount'])) {
416 $occurDiscount = array_count_values($values['discount_name']);
417 $countemptyrows = 0;
418 $countemptyvalue = 0;
419 for ($i = 1; $i <= self::NUM_DISCOUNT; $i++) {
420 $start_date = $end_date = NULL;
421 if (!empty($values['discount_name'][$i])) {
422 if (!empty($values['discount_start_date'][$i])) {
423 $start_date = ($values['discount_start_date'][$i]) ? CRM_Utils_Date::processDate($values['discount_start_date'][$i]) : 0;
424 }
425 if (!empty($values['discount_end_date'][$i])) {
426 $end_date = ($values['discount_end_date'][$i]) ? CRM_Utils_Date::processDate($values['discount_end_date'][$i]) : 0;
427 }
428
429 if ($start_date && $end_date && strcmp($end_date, $start_date) < 0) {
430 $errors["discount_end_date[$i]"] = ts('The discount end date cannot be prior to the start date.');
431 }
432
433 if (!$start_date && !$end_date) {
434 $errors["discount_start_date[$i]"] = $errors["discount_end_date[$i]"] = ts('Please specify either start date or end date.');
435 }
436
437 if ($i > 1) {
438 $end_date_1 = ($values['discount_end_date'][$i - 1]) ? CRM_Utils_Date::processDate($values['discount_end_date'][$i - 1]) : 0;
439 if ($start_date && $end_date_1 && strcmp($end_date_1, $start_date) >= 0) {
440 $errors["discount_start_date[$i]"] = ts('Select non-overlapping discount start date.');
441 }
442 elseif (!$start_date && !$end_date_1) {
443 $j = $i - 1;
444 $errors["discount_start_date[$i]"] = $errors["discount_end_date[$j]"] = ts('Select either of the dates.');
445 }
446 }
447
448 foreach ($occurDiscount as $key => $value) {
449 if ($value > 1 && $key <> '') {
450 if ($key == $values['discount_name'][$i]) {
451 $errors['discount_name[' . $i . ']'] = ts('%1 is already used for Discount Name.', array(1 => $key));
452 }
453 }
454 }
455
456 //validation for discount labels and values
457 for ($index = (self::NUM_OPTION); $index > 0; $index--) {
458 $label = TRUE;
459 if (empty($values['discounted_label'][$index]) && !empty($values['discounted_value'][$index][$i])) {
460 $label = FALSE;
461 if (!$label) {
462 $errors["discounted_label[{$index}]"] = ts('Label cannot be empty.');
463 }
464 }
465 if (!empty($values['discounted_label'][$index])) {
466 $duplicateIndex = CRM_Utils_Array::key($values['discounted_label'][$index], $values['discounted_label']);
467
468 if ((!($duplicateIndex === FALSE)) && (!($duplicateIndex == $index))) {
469 $errors["discounted_label[{$index}]"] = ts('Duplicate label value');
470 }
471 }
472 if (empty($values['discounted_label'][$index]) && empty($values['discounted_value'][$index][$i])) {
473 $countemptyrows++;
474 }
475 if (empty($values['discounted_value'][$index][$i])) {
476 $countemptyvalue++;
477 }
478 }
479 if (!empty($values['_qf_Fee_next']) && ($countemptyrows == 11 || $countemptyvalue == 11)) {
480 $errors["discounted_label[1]"] = $errors["discounted_value[1][$i]"] = ts('At least one fee should be entered for your Discount Set. If you do not see the table to enter discount fees, click the "Add Discount Set to Fee Table" button.');
481 }
482 }
483 }
484 }
485 if ($values['is_monetary']) {
486 //check if financial type is selected
487 if (!$values['financial_type_id']) {
488 $errors['financial_type_id'] = ts("Please select financial type.");
489 }
490
491 //check for the event fee label (mandatory)
492 if (!$values['fee_label']) {
493 $errors['fee_label'] = ts('Please enter the fee label for the paid event.');
494 }
495
496 if (empty($values['price_set_id'])) {
497 //check fee label and amount
498 $check = 0;
499 $optionKeys = array();
500 foreach ($values['label'] as $key => $val) {
501 if (trim($val) && trim($values['value'][$key])) {
502 $optionKeys[$key] = $key;
503 $check++;
504 }
505 }
506
507 $default = CRM_Utils_Array::value('default', $values);
508 if ($default && !in_array($default, $optionKeys)) {
509 $errors['default'] = ts('Please select an appropriate option as default.');
510 }
511
512 if (!$check) {
513 if (!$values['label'][1]) {
514 $errors['label[1]'] = ts('Please enter a label for at least one fee level.');
515 }
516 if (!$values['value'][1]) {
517 $errors['value[1]'] = ts('Please enter an amount for at least one fee level.');
518 }
519 }
520 }
521 if (isset($values['is_pay_later'])) {
522 if (empty($values['pay_later_text'])) {
523 $errors['pay_later_text'] = ts('Please enter the Pay Later prompt to be displayed on the Registration form.');
524 }
525 if (empty($values['pay_later_receipt'])) {
526 $errors['pay_later_receipt'] = ts('Please enter the Pay Later instructions to be displayed to your users.');
527 }
528 }
529 }
530 return empty($errors) ? TRUE : $errors;
531 }
532
533 public function buildAmountLabel() {
534 $default = array();
535 for ($i = 1; $i <= self::NUM_OPTION; $i++) {
536 // label
537 $this->add('text', "discounted_label[$i]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'));
538 // value
539 for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
540 $this->add('text', "discounted_value[$i][$j]", ts('Value'), array('size' => 10));
541 $this->addRule("discounted_value[$i][$j]", ts('Please enter a valid money value for this field (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
542 }
543
544 // default
545 $default[] = $this->createElement('radio', NULL, NULL, NULL, $i);
546 }
547
548 $this->addGroup($default, 'discounted_default');
549 }
550
551 /**
552 * Process the form.
553 */
554 public function postProcess() {
555 $eventTitle = '';
556 $params = $this->exportValues();
557
558 $this->set('discountSection', 0);
559
560 if (!empty($_POST['_qf_Fee_submit'])) {
561 $this->buildAmountLabel();
562 $this->set('discountSection', 2);
563 return;
564 }
565
566 if (!empty($params['payment_processor'])) {
567 $params['payment_processor'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['payment_processor']);
568 }
569 else {
570 $params['payment_processor'] = 'null';
571 }
572
573 $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, 0);
574 $params['is_billing_required'] = CRM_Utils_Array::value('is_billing_required', $params, 0);
575
576 if ($this->_id) {
577
578 // delete all the prior label values or discounts in the custom options table
579 // and delete a price set if one exists
580 //@todo note that this removes the reference from existing participants -
581 // even where there is not change - redress?
582 // note that a more tentative form of this is invoked by passing price_set_id as an array
583 // to event.create see CRM-14069
584 // @todo get all of this logic out of form layer (currently partially in BAO/api layer)
585 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_event', $this->_id)) {
586 CRM_Core_BAO_Discount::del($this->_id, 'civicrm_event');
587 }
588 }
589
590 if ($params['is_monetary']) {
591 if (!empty($params['price_set_id'])) {
592 //@todo this is now being done in the event BAO if passed price_set_id as an array
593 // per notes on that fn - looking at the api converting to an array
594 // so calling via the api may cause this to be done in the api
595 CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $params['price_set_id']);
596 if (!empty($params['price_field_id'])) {
597 $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
598 CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
599 }
600 }
601 else {
602 // if there are label / values, create custom options for them
603 $labels = CRM_Utils_Array::value('label', $params);
604 $values = CRM_Utils_Array::value('value', $params);
605 $default = CRM_Utils_Array::value('default', $params);
606 $options = array();
607 if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
608 for ($i = 1; $i < self::NUM_OPTION; $i++) {
609 if (!empty($labels[$i]) && !CRM_Utils_System::isNull($values[$i])) {
610 $options[] = array(
611 'label' => trim($labels[$i]),
612 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])),
613 'weight' => $i,
614 'is_active' => 1,
615 'is_default' => $default == $i,
616 );
617 }
618 }
619 if (!empty($options)) {
620 $params['default_fee_id'] = NULL;
621 if (empty($params['price_set_id'])) {
622 if (empty($params['price_field_id'])) {
623 $setParams['title'] = $eventTitle = ($this->_isTemplate) ? $this->_defaultValues['template_title'] : $this->_defaultValues['title'];
624 $eventTitle = strtolower(CRM_Utils_String::munge($eventTitle, '_', 245));
625 if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle, 'id', 'name')) {
626 $setParams['name'] = $eventTitle;
627 }
628 elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $this->_id, 'id', 'name')) {
629 $setParams['name'] = $eventTitle . '_' . $this->_id;
630 }
631 else {
632 $timeSec = explode('.', microtime(TRUE));
633 $setParams['name'] = $eventTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
634 }
635 $setParams['is_quick_config'] = 1;
636 $setParams['financial_type_id'] = $params['financial_type_id'];
637 $setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
638 $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
639
640 $fieldParams['name'] = strtolower(CRM_Utils_String::munge($params['fee_label'], '_', 245));
641 $fieldParams['price_set_id'] = $priceSet->id;
642 }
643 else {
644 foreach ($params['price_field_value'] as $arrayID => $fieldValueID) {
645 if (empty($params['label'][$arrayID]) && empty($params['value'][$arrayID]) && !empty($fieldValueID)) {
646 CRM_Price_BAO_PriceFieldValue::setIsActive($fieldValueID, '0');
647 unset($params['price_field_value'][$arrayID]);
648 }
649 }
650 $fieldParams['id'] = CRM_Utils_Array::value('price_field_id', $params);
651 $fieldParams['option_id'] = $params['price_field_value'];
652
653 $priceSet = new CRM_Price_BAO_PriceSet();
654 $priceSet->id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $params), 'price_set_id');
655
656 if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
657 CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $priceSet->id, 'financial_type_id', $params['financial_type_id']);
658 }
659 }
660 $fieldParams['label'] = $params['fee_label'];
661 $fieldParams['html_type'] = 'Radio';
662 CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $priceSet->id);
663 $fieldParams['option_label'] = $params['label'];
664 $fieldParams['option_amount'] = $params['value'];
665 $fieldParams['financial_type_id'] = $params['financial_type_id'];
666 foreach ($options as $value) {
667 $fieldParams['option_weight'][$value['weight']] = $value['weight'];
668 }
669 $fieldParams['default_option'] = $params['default'];
670 $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
671 }
672 }
673 }
674
675 $discountPriceSets = !empty($this->_defaultValues['discount_price_set']) ? $this->_defaultValues['discount_price_set'] : array();
676 $discountFieldIDs = !empty($this->_defaultValues['discount_option_id']) ? $this->_defaultValues['discount_option_id'] : array();
677 if (CRM_Utils_Array::value('is_discount', $params) == 1) {
678 // if there are discounted set of label / values,
679 // create custom options for them
680 $labels = CRM_Utils_Array::value('discounted_label', $params);
681 $values = CRM_Utils_Array::value('discounted_value', $params);
682 $default = CRM_Utils_Array::value('discounted_default', $params);
683
684 if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
685 for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
686 $discountOptions = array();
687 for ($i = 1; $i < self::NUM_OPTION; $i++) {
688 if (!empty($labels[$i]) &&
689 !CRM_Utils_System::isNull(CRM_Utils_Array::value($j, $values[$i]))
690 ) {
691 $discountOptions[] = array(
692 'label' => trim($labels[$i]),
693 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i][$j])),
694 'weight' => $i,
695 'is_active' => 1,
696 'is_default' => $default == $i,
697 );
698 }
699 }
700
701 if (!empty($discountOptions)) {
702 $fieldParams = array();
703 $params['default_discount_fee_id'] = NULL;
704 $keyCheck = $j - 1;
705 $setParams = array();
706 if (empty($discountPriceSets[$keyCheck])) {
707 if (!$eventTitle) {
708 $eventTitle = strtolower(CRM_Utils_String::munge($this->_defaultValues['title'], '_', 200));
709 }
710 $setParams['title'] = $params['discount_name'][$j];
711 if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j], 'id', 'name')) {
712 $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j];
713 }
714 elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id, 'id', 'name')) {
715 $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id;
716 }
717 else {
718 $timeSec = explode('.', microtime(TRUE));
719 $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . date('is', $timeSec[0]) . $timeSec[1];
720 }
721 $setParams['is_quick_config'] = 1;
722 $setParams['financial_type_id'] = $params['financial_type_id'];
723 $setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
724 $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
725 $priceSetID = $priceSet->id;
726 }
727 else {
728 $priceSetID = $discountPriceSets[$j - 1];
729 $setParams = array(
730 'title' => $params['discount_name'][$j],
731 'id' => $priceSetID,
732 );
733 if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
734 $setParams['financial_type_id'] = $params['financial_type_id'];
735 }
736 CRM_Price_BAO_PriceSet::create($setParams);
737 unset($discountPriceSets[$j - 1]);
738 $fieldParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $priceSetID, 'id', 'price_set_id');
739 }
740
741 $fieldParams['name'] = $fieldParams['label'] = $params['fee_label'];
742 $fieldParams['is_required'] = 1;
743 $fieldParams['price_set_id'] = $priceSetID;
744 $fieldParams['html_type'] = 'Radio';
745 $fieldParams['financial_type_id'] = $params['financial_type_id'];
746 foreach ($discountOptions as $value) {
747 $fieldParams['option_label'][$value['weight']] = $value['label'];
748 $fieldParams['option_amount'][$value['weight']] = $value['value'];
749 $fieldParams['option_weight'][$value['weight']] = $value['weight'];
750 if (!empty($value['is_default'])) {
751 $fieldParams['default_option'] = $value['weight'];
752 }
753 if (!empty($discountFieldIDs[$j]) && !empty($discountFieldIDs[$j][$value['weight']])) {
754 $fieldParams['option_id'][$value['weight']] = $discountFieldIDs[$j][$value['weight']];
755 unset($discountFieldIDs[$j][$value['weight']]);
756 }
757 }
758 //create discount priceset
759 $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
760 if (!empty($discountFieldIDs[$j])) {
761 foreach ($discountFieldIDs[$j] as $fID) {
762 CRM_Price_BAO_PriceFieldValue::setIsActive($fID, '0');
763 }
764 }
765
766 $discountParams = array(
767 'entity_table' => 'civicrm_event',
768 'entity_id' => $this->_id,
769 'price_set_id' => $priceSetID,
770 'start_date' => CRM_Utils_Date::processDate($params['discount_start_date'][$j]),
771 'end_date' => CRM_Utils_Date::processDate($params['discount_end_date'][$j]),
772 );
773 CRM_Core_BAO_Discount::add($discountParams);
774 }
775 }
776 }
777 }
778 if (!empty($discountPriceSets)) {
779 foreach ($discountPriceSets as $setId) {
780 CRM_Price_BAO_PriceSet::setIsQuickConfig($setId, 0);
781 }
782 }
783 }
784 }
785 else {
786 if (!empty($params['price_field_id'])) {
787 $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
788 CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
789 }
790 $params['financial_type_id'] = '';
791 $params['is_pay_later'] = 0;
792 $params['is_billing_required'] = 0;
793 }
794
795 //update 'is_billing_required'
796 if (empty($params['is_pay_later'])) {
797 $params['is_billing_required'] = FALSE;
798 }
799
800 //update events table
801 $params['id'] = $this->_id;
802 // skip update of financial type in price set
803 $params['skipFinancialType'] = TRUE;
804 CRM_Event_BAO_Event::add($params);
805
806 // Update tab "disabled" css class
807 $this->ajaxResponse['tabValid'] = !empty($params['is_monetary']);
808 parent::endPostProcess();
809 }
810
811 /**
812 * Return a descriptive name for the page, used in wizard header
813 *
814 * @return string
815 */
816 public function getTitle() {
817 return ts('Event Fees');
818 }
819
820 }