Merge pull request #4963 from rohankatkar/CRM-15830
[civicrm-core.git] / CRM / Price / BAO / PriceField.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 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * Business objects for managing price fields.
38 *
39 */
40 class CRM_Price_BAO_PriceField extends CRM_Price_DAO_PriceField {
41
42 protected $_options;
43
44 /**
45 * Takes an associative array and creates a price field object
46 *
47 * the function extract all the params it needs to initialize the create a
48 * price field object. the params array could contain additional unused name/value
49 * pairs
50 *
51 * @param array $params
52 * (reference) an assoc array of name/value pairs.
53 *
54 * @return CRM_Price_BAO_PriceField
55 */
56 public static function add(&$params) {
57 $priceFieldBAO = new CRM_Price_BAO_PriceField();
58
59 $priceFieldBAO->copyValues($params);
60
61 if ($id = CRM_Utils_Array::value('id', $params)) {
62 $priceFieldBAO->id = $id;
63 }
64
65 $priceFieldBAO->save();
66 return $priceFieldBAO;
67 }
68
69 /**
70 * Takes an associative array and creates a price field object
71 *
72 * This function is invoked from within the web form layer and also from the api layer
73 *
74 * @param array $params
75 * (reference) an assoc array of name/value pairs.
76 *
77 * @return CRM_Price_DAO_PriceField
78 */
79 public static function create(&$params) {
80 if (empty($params['id']) && empty($params['name'])) {
81 $params['name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 242));
82 }
83 $transaction = new CRM_Core_Transaction();
84
85 $priceField = self::add($params);
86
87 if (is_a($priceField, 'CRM_Core_Error')) {
88 $transaction->rollback();
89 return $priceField;
90 }
91
92 $optionsIds = array();
93 $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
94
95 if ($priceField->html_type == 'Text') {
96 $maxIndex = 1;
97
98 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
99 $fieldValue->price_field_id = $priceField->id;
100
101 // update previous field values( if any )
102 if ($fieldValue->find(TRUE)) {
103 $optionsIds['id'] = $fieldValue->id;
104 }
105 }
106 $defaultArray = array();
107 //html type would be empty in update scenario not sure what would happen ...
108 if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
109 $tempArray = array_keys($params['default_checkbox_option']);
110 foreach ($tempArray as $v) {
111 if ($params['option_amount'][$v]) {
112 $defaultArray[$v] = 1;
113 }
114 }
115 }
116 else {
117 if (!empty($params['default_option'])) {
118 $defaultArray[$params['default_option']] = 1;
119 }
120 }
121
122 for ($index = 1; $index <= $maxIndex; $index++) {
123 if (array_key_exists('option_amount', $params) &&
124 array_key_exists($index, $params['option_amount']) &&
125 (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) &&
126 !CRM_Utils_System::isNull($params['option_amount'][$index])
127 ) {
128 $options = array(
129 'price_field_id' => $priceField->id,
130 'label' => trim($params['option_label'][$index]),
131 'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64),
132 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])),
133 'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL),
134 'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL),
135 'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL),
136 'membership_type_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_type_id', $params), NULL),
137 'weight' => $params['option_weight'][$index],
138 'is_active' => 1,
139 'is_default' => CRM_Utils_Array::value($params['option_weight'][$index], $defaultArray) ? $defaultArray[$params['option_weight'][$index]] : 0,
140 'membership_num_terms' => NULL,
141 );
142
143 if ($options['membership_type_id']) {
144 $options['membership_num_terms'] = CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_num_terms', $params), 1);
145 }
146
147 if (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_financial_type_id', $params))) {
148 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
149 }
150 elseif (!empty($params['financial_type_id'])) {
151 $options['financial_type_id'] = $params['financial_type_id'];
152 }
153
154 if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
155 if ($opId = CRM_Utils_Array::value($index, $opIds)) {
156 $optionsIds['id'] = $opId;
157 }
158 else {
159 $optionsIds['id'] = NULL;
160 }
161 }
162 CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
163 }
164 }
165
166 $transaction->commit();
167 return $priceField;
168 }
169
170 /**
171 * Fetch object based on array of properties
172 *
173 * @param array $params
174 * (reference ) an assoc array of name/value pairs.
175 * @param array $defaults
176 * (reference ) an assoc array to hold the flattened values.
177 *
178 * @return CRM_Price_DAO_PriceField
179 */
180 public static function retrieve(&$params, &$defaults) {
181 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
182 }
183
184 /**
185 * Update the is_active flag in the db
186 *
187 * @param int $id
188 * Id of the database record.
189 * @param bool $is_active
190 * Value we want to set the is_active field.
191 *
192 * @return Object
193 * DAO object on sucess, null otherwise
194 *
195 */
196 public static function setIsActive($id, $is_active) {
197 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
198 }
199
200 public static function freezeIfEnabled(&$element, $fieldOptions) {
201 if (!empty($fieldOptions['is_full'])) {
202 $element->freeze();
203 }
204 return NULL;
205 }
206
207 /**
208 * Get the field title.
209 *
210 * @param int $id
211 * Id of field.
212 *
213 * @return string
214 * name
215 *
216 */
217 public static function getTitle($id) {
218 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
219 }
220
221 /**
222 * This function for building custom fields
223 *
224 * @param CRM_Core_Form $qf
225 * Form object (reference).
226 * @param string $elementName
227 * Name of the custom field.
228 * @param int $fieldId
229 * @param bool $inactiveNeeded
230 * @param bool $useRequired
231 * True if required else false.
232 * @param string $label
233 * Label for custom field.
234 *
235 * @param null $fieldOptions
236 * @param array $freezeOptions
237 *
238 * @return null
239 * @internal param bool $search true if used for search else false
240 */
241 public static function addQuickFormElement(
242 &$qf,
243 $elementName,
244 $fieldId,
245 $inactiveNeeded,
246 $useRequired = TRUE,
247 $label = NULL,
248 $fieldOptions = NULL,
249 $freezeOptions = array()
250 ) {
251
252 $field = new CRM_Price_DAO_PriceField();
253 $field->id = $fieldId;
254 if (!$field->find(TRUE)) {
255 /* FIXME: failure! */
256 return NULL;
257 }
258
259 $is_pay_later = 0;
260 if (isset($qf->_mode) && empty($qf->_mode)) {
261 $is_pay_later = 1;
262 }
263 elseif (isset($qf->_values)) {
264 $is_pay_later = CRM_Utils_Array::value('is_pay_later', $qf->_values);
265 }
266
267 $otherAmount = $qf->get('values');
268 $config = CRM_Core_Config::singleton();
269 $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', $config->defaultCurrency, 'symbol', 'name');
270 $qf->assign('currencySymbol', $currencySymbol);
271 // get currency name for price field and option attributes
272 $currencyName = $config->defaultCurrency;
273
274 if (!isset($label)) {
275 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
276 }
277
278 if ($field->name == 'contribution_amount') {
279 $qf->_contributionAmount = 1;
280 }
281
282 if (isset($qf->_online) && $qf->_online) {
283 $useRequired = FALSE;
284 }
285
286 $customOption = $fieldOptions;
287 if (!is_array($customOption)) {
288 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
289 }
290
291 //use value field.
292 $valueFieldName = 'amount';
293 $seperator = '|';
294 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
295 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
296 $displayOpt = CRM_Utils_Array::value('tax_display_settings', $invoiceSettings);
297 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
298 switch ($field->html_type) {
299 case 'Text':
300 $optionKey = key($customOption);
301 $count = CRM_Utils_Array::value('count', $customOption[$optionKey], '');
302 $max_value = CRM_Utils_Array::value('max_value', $customOption[$optionKey], '');
303 $taxAmount = CRM_Utils_Array::value('tax_amount', $customOption[$optionKey]);
304 if (isset($taxAmount) && $displayOpt && $invoicing) {
305 $qf->assign('displayOpt', $displayOpt);
306 $qf->assign('taxTerm', $taxTerm);
307 $qf->assign('invoicing', $invoicing);
308 }
309 $priceVal = implode($seperator, array(
310 $customOption[$optionKey][$valueFieldName] + $taxAmount,
311 $count,
312 $max_value,
313 ));
314
315 $extra = array();
316 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
317 foreach ($fieldOptions as &$fieldOption) {
318 if ($fieldOption['name'] == 'other_amount') {
319 $fieldOption['label'] = $fieldOption['label'] . ' ' . $currencySymbol;
320 }
321 }
322 $qf->assign('priceset', $elementName);
323 $extra = array('onclick' => 'useAmountOther();');
324 }
325
326 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
327 $useRequired = 0;
328 }
329 elseif (!empty($fieldOptions[$optionKey]['label'])) {
330 //check for label.
331 $label = $fieldOptions[$optionKey]['label'];
332 }
333
334 $element = &$qf->add('text', $elementName, $label,
335 array_merge($extra,
336 array(
337 'price' => json_encode(array($optionKey, $priceVal)),
338 'size' => '4',
339 )
340 ),
341 $useRequired && $field->is_required
342 );
343 if ($is_pay_later) {
344 $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
345 }
346
347 // CRM-6902 - Add "max" option for a price set field
348 if (in_array($optionKey, $freezeOptions)) {
349 self::freezeIfEnabled($element, $freezeOptions);
350 // CRM-14696 - Improve display for sold out price set options
351 $element->setLabel($label . '&nbsp;<span class="sold-out-option">' . ts('Sold out') . '</span>');
352 }
353
354 //CRM-10117
355 if (!empty($qf->_quickConfig)) {
356 $message = ts('Please enter a valid amount.');
357 $type = 'money';
358 }
359 else {
360 $message = ts('%1 must be a number (with or without decimal point).', array(1 => $label));
361 $type = 'numeric';
362 }
363 // integers will have numeric rule applied to them.
364 $qf->addRule($elementName, $message, $type);
365 break;
366
367 case 'Radio':
368 $choice = array();
369
370 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
371 $qf->assign('contriPriceset', $elementName);
372 }
373
374 foreach ($customOption as $opId => $opt) {
375 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
376 if ($field->is_display_amounts) {
377 $opt['label'] = !empty($opt['label']) ? $opt['label'] . '&nbsp;-&nbsp;' : '';
378 if (isset($taxAmount) && $invoicing) {
379 if ($displayOpt == 'Do_not_show') {
380 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName] + $taxAmount) . '</span>';
381 }
382 elseif ($displayOpt == 'Inclusive') {
383 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName] + $taxAmount) . '</span>';
384 $opt['label'] .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
385 }
386 else {
387 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span>';
388 $opt['label'] .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
389 }
390 }
391 else {
392 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span>';
393 }
394 }
395 $count = CRM_Utils_Array::value('count', $opt, '');
396 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
397 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
398 $extra = array(
399 'price' => json_encode(array($elementName, $priceVal)),
400 'data-amount' => $opt[$valueFieldName],
401 'data-currency' => $currencyName,
402 );
403 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
404 $extra += array('onclick' => 'clearAmountOther();');
405 }
406 elseif (!empty($qf->_quickConfig) && $field->name == 'membership_amount') {
407 $extra += array(
408 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
409 'membership-type' => $opt['membership_type_id'],
410 );
411 $qf->assign('membershipFieldID', $field->id);
412 }
413
414 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
415
416 if ($is_pay_later) {
417 $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
418 }
419
420 // CRM-6902 - Add "max" option for a price set field
421 if (in_array($opId, $freezeOptions)) {
422 self::freezeIfEnabled($choice[$opId], $customOption[$opId]);
423 // CRM-14696 - Improve display for sold out price set options
424 $choice[$opId]->setText('<span class="sold-out-option">' . $choice[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
425 }
426 }
427 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
428 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
429 array(
430 'onclick' => 'clearAmountOther();',
431 )
432 );
433 }
434
435 if (!$field->is_required) {
436 // add "none" option
437 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
438 $none = ts('Other Amount');
439 }
440 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
441 $none = ts('No thank you');
442 }
443 else {
444 $none = ts('- none -');
445 }
446
447 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
448 array('price' => json_encode(array($elementName, '0')))
449 );
450 }
451
452 $element = &$qf->addGroup($choice, $elementName, $label);
453
454 // make contribution field required for quick config when membership block is enabled
455 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
456 && !empty($qf->_membershipBlock) && !$field->is_required
457 ) {
458 $useRequired = $field->is_required = TRUE;
459 }
460
461 if ($useRequired && $field->is_required) {
462 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
463 }
464 break;
465
466 case 'Select':
467 $selectOption = $allowedOptions = $priceVal = array();
468
469 foreach ($customOption as $opt) {
470 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
471 $count = CRM_Utils_Array::value('count', $opt, '');
472 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
473
474 if ($field->is_display_amounts) {
475 $opt['label'] .= '&nbsp;-&nbsp;';
476 if (isset($taxAmount) && $invoicing) {
477 $opt['label'] = $opt['label'] . self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
478 }
479 else {
480 $opt['label'] = $opt['label'] . CRM_Utils_Money::format($opt[$valueFieldName]);
481 }
482 }
483
484 $selectOption[$opt['id']] = $opt['label'];
485 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
486
487 if (!in_array($opt['id'], $freezeOptions)) {
488 $allowedOptions[] = $opt['id'];
489 }
490 // CRM-14696 - Improve display for sold out price set options
491 else {
492 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
493 }
494
495 $selectOption[$opt['id']] = $opt['label'];
496
497 if ($is_pay_later) {
498 $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
499 }
500 }
501
502 $element = &$qf->add('select', $elementName, $label,
503 array(
504 '' => ts('- select -'),
505 ) + $selectOption,
506 $useRequired && $field->is_required,
507 array('price' => json_encode($priceVal))
508 );
509
510 // CRM-6902 - Add "max" option for a price set field
511 $button = substr($qf->controller->getButtonName(), -4);
512 if (!empty($freezeOptions) && $button != 'skip') {
513 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
514 }
515 break;
516
517 case 'CheckBox':
518
519 $check = array();
520 foreach ($customOption as $opId => $opt) {
521 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
522 $count = CRM_Utils_Array::value('count', $opt, '');
523 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
524
525 if ($field->is_display_amounts) {
526 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>&nbsp;-&nbsp;';
527 if (isset($taxAmount) && $invoicing) {
528 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
529 }
530 else {
531 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
532 }
533 }
534 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
535 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
536 array(
537 'price' => json_encode(array($opt['id'], $priceVal)),
538 'data-amount' => $opt[$valueFieldName],
539 'data-currency' => $currencyName,
540 )
541 );
542 if ($is_pay_later) {
543 $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], array('size' => '4'));
544 $qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
545 }
546 // CRM-6902 - Add "max" option for a price set field
547 if (in_array($opId, $freezeOptions)) {
548 self::freezeIfEnabled($check[$opId], $customOption[$opId]);
549 // CRM-14696 - Improve display for sold out price set options
550 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
551 }
552 }
553 $element = &$qf->addGroup($check, $elementName, $label);
554 if ($useRequired && $field->is_required) {
555 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
556 }
557 break;
558 }
559 if (isset($qf->_online) && $qf->_online) {
560 $element->freeze();
561 }
562 }
563
564 /**
565 * Retrieve a list of options for the specified field
566 *
567 * @param int $fieldId
568 * Price field ID.
569 * @param bool $inactiveNeeded
570 * Include inactive options.
571 * @param bool $reset
572 * Ignore stored values\.
573 *
574 * @return array
575 * array of options
576 */
577 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
578 static $options = array();
579
580 if ($reset || empty($options[$fieldId])) {
581 $values = array();
582 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
583 $options[$fieldId] = $values;
584 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
585
586 // ToDo - Code for Hook Invoke
587
588 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
589 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates)) {
590 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
591 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
592 $options[$fieldId][$priceFieldId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
593 }
594 }
595 }
596
597 return $options[$fieldId];
598 }
599
600 /**
601 * @param $optionLabel
602 * @param int $fid
603 *
604 * @return mixed
605 */
606 public static function getOptionId($optionLabel, $fid) {
607 if (!$optionLabel || !$fid) {
608 return;
609 }
610
611 $optionGroupName = "civicrm_price_field.amount.{$fid}";
612
613 $query = "
614 SELECT
615 option_value.id as id
616 FROM
617 civicrm_option_value option_value,
618 civicrm_option_group option_group
619 WHERE
620 option_group.name = %1
621 AND option_group.id = option_value.option_group_id
622 AND option_value.label = %2";
623
624 $dao = CRM_Core_DAO::executeQuery($query, array(
625 1 => array($optionGroupName, 'String'),
626 2 => array($optionLabel, 'String'),
627 ));
628
629 while ($dao->fetch()) {
630 return $dao->id;
631 }
632 }
633
634 /**
635 * Delete the price set field.
636 *
637 * @param int $id
638 * Field Id.
639 *
640 * @return bool
641 *
642 */
643 public static function deleteField($id) {
644 $field = new CRM_Price_DAO_PriceField();
645 $field->id = $id;
646
647 if ($field->find(TRUE)) {
648 // delete the options for this field
649 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
650
651 // reorder the weight before delete
652 $fieldValues = array('price_set_id' => $field->price_set_id);
653
654 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
655
656 // now delete the field
657 return $field->delete();
658 }
659
660 return NULL;
661 }
662
663 /**
664 * @return array
665 */
666 public static function &htmlTypes() {
667 static $htmlTypes = NULL;
668 if (!$htmlTypes) {
669 $htmlTypes = array(
670 'Text' => ts('Text / Numeric Quantity'),
671 'Select' => ts('Select'),
672 'Radio' => ts('Radio'),
673 'CheckBox' => ts('CheckBox'),
674 );
675 }
676 return $htmlTypes;
677 }
678
679 /**
680 * Validate the priceset
681 *
682 * @param int $priceSetId
683 * , array $fields.
684 *
685 * retrun the error string
686 *
687 * @param $fields
688 * @param $error
689 * @param bool $allowNoneSelection
690 *
691 */
692 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
693 // check for at least one positive
694 // amount price field should be selected.
695 $priceField = new CRM_Price_DAO_PriceField();
696 $priceField->price_set_id = $priceSetId;
697 $priceField->find();
698
699 $priceFields = array();
700
701 if ($allowNoneSelection) {
702 $noneSelectedPriceFields = array();
703 }
704
705 while ($priceField->fetch()) {
706 $key = "price_{$priceField->id}";
707
708 if ($allowNoneSelection) {
709 if (array_key_exists($key, $fields)) {
710 if ($fields[$key] == 0 && !$priceField->is_required) {
711 $noneSelectedPriceFields[] = $priceField->id;
712 }
713 }
714 }
715
716 if (!empty($fields[$key])) {
717 $priceFields[$priceField->id] = $fields[$key];
718 }
719 }
720
721 if (!empty($priceFields)) {
722 // we should has to have positive amount.
723 $sql = "
724 SELECT id, html_type
725 FROM civicrm_price_field
726 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
727 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
728 $htmlTypes = array();
729 while ($fieldDAO->fetch()) {
730 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
731 }
732
733 $selectedAmounts = array();
734
735 foreach ($htmlTypes as $fieldId => $type) {
736 $options = array();
737 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
738
739 if (empty($options)) {
740 continue;
741 }
742
743 if ($type == 'Text') {
744 foreach ($options as $opId => $option) {
745 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
746 break;
747 }
748 }
749 elseif (is_array($fields["price_{$fieldId}"])) {
750 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
751 $selectedAmounts[$opId] = $options[$opId]['amount'];
752 }
753 }
754 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
755 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
756 }
757 }
758
759 list($componentName) = explode(':', $fields['_qf_default']);
760 // now we have all selected amount in hand.
761 $totalAmount = array_sum($selectedAmounts);
762 if ($totalAmount < 0) {
763 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
764 }
765 }
766 else {
767 if ($allowNoneSelection) {
768 if (empty($noneSelectedPriceFields)) {
769 $error['_qf_default'] = ts('Please select at least one option from price set.');
770 }
771 }
772 else {
773 $error['_qf_default'] = ts('Please select at least one option from price set.');
774 }
775 }
776 }
777
778 /**
779 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
780 *
781 * @param array $opt
782 * @param string $valueFieldName
783 * Amount.
784 * @param string $displayOpt
785 * Tax display setting option.
786 *
787 * @return string
788 * tax label for custom field
789 *
790 */
791 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
792 if ($displayOpt == 'Do_not_show') {
793 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
794 }
795 elseif ($displayOpt == 'Inclusive') {
796 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
797 $label .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
798 }
799 else {
800 $label = CRM_Utils_Money::format($opt[$valueFieldName]);
801 $label .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
802 }
803
804 return $label;
805 }
806 }