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