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