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