Merge pull request #4752 from davecivicrm/CRM-15180
[civicrm-core.git] / CRM / Price / BAO / PriceField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 * @access public
55 * @static
56 */
57 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 (reference) an assoc array of name/value pairs
76 *
77 * @return CRM_Price_DAO_PriceField object
78 * @access public
79 * @static
80 */
81 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 (reference ) an assoc array of name/value pairs
174 * @param array $defaults (reference ) an assoc array to hold the flattened values
175 *
176 * @return CRM_Price_DAO_PriceField object
177 * @access public
178 * @static
179 */
180 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 Id of the database record
188 * @param boolean $is_active Value we want to set the is_active field
189 *
190 * @return Object DAO object on sucess, null otherwise
191 *
192 * @access public
193 * @static
194 */
195 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 * Get the field title.
201 *
202 * @param int $id id of field.
203 *
204 * @return string name
205 *
206 * @access public
207 * @static
208 *
209 */
210 public static function getTitle($id) {
211 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
212 }
213
214 /**
215 * This function for building custom fields
216 *
217 * @param CRM_Core_Form $qf form object (reference)
218 * @param string $elementName name of the custom field
219 * @param int $fieldId
220 * @param boolean $inactiveNeeded
221 * @param boolean $useRequired true if required else false
222 * @param string $label label for custom field
223 *
224 * @param null $fieldOptions
225 * @param array $freezeOptions
226 *
227 * @return null
228 * @internal param bool $search true if used for search else false
229 * @access public
230 * @static
231 */
232 public static function addQuickFormElement(&$qf,
233 $elementName,
234 $fieldId,
235 $inactiveNeeded,
236 $useRequired = TRUE,
237 $label = NULL,
238 $fieldOptions = NULL,
239 $freezeOptions = array()
240 ) {
241
242 $field = new CRM_Price_DAO_PriceField();
243 $field->id = $fieldId;
244 if (!$field->find(TRUE)) {
245 /* FIXME: failure! */
246 return NULL;
247 }
248
249 $is_pay_later = 0;
250 if (isset($qf->_mode) && empty($qf->_mode)) {
251 $is_pay_later = 1;
252 }
253 elseif (isset($qf->_values)) {
254 $is_pay_later = CRM_Utils_Array::value( 'is_pay_later', $qf->_values);
255 }
256
257 $otherAmount = $qf->get('values');
258 $config = CRM_Core_Config::singleton();
259 $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency',$config->defaultCurrency,'symbol','name');
260 $qf->assign('currencySymbol', $currencySymbol);
261 // get currency name for price field and option attributes
262 $currencyName = $config->defaultCurrency;
263
264 if (!isset($label)) {
265 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
266 }
267
268 if ($field->name == 'contribution_amount') {
269 $qf->_contributionAmount = 1;
270 }
271
272 if (isset($qf->_online) && $qf->_online) {
273 $useRequired = FALSE;
274 }
275
276 $customOption = $fieldOptions;
277 if (!is_array($customOption)) {
278 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
279 }
280
281 //use value field.
282 $valueFieldName = 'amount';
283 $seperator = '|';
284 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
285 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
286 $displayOpt = CRM_Utils_Array::value('tax_display_settings', $invoiceSettings);
287 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
288 switch ($field->html_type) {
289 case 'Text':
290 $optionKey = key($customOption);
291 $count = CRM_Utils_Array::value('count', $customOption[$optionKey], '');
292 $max_value = CRM_Utils_Array::value('max_value', $customOption[$optionKey], '');
293 $taxAmount = CRM_Utils_Array::value('tax_amount', $customOption[$optionKey]);
294 if (isset($taxAmount) && $displayOpt && $invoicing) {
295 $qf->assign('displayOpt', $displayOpt);
296 $qf->assign('taxTerm', $taxTerm);
297 $qf->assign('invoicing', $invoicing);
298 }
299 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName] + $taxAmount, $count, $max_value));
300
301 $extra = array();
302 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
303 foreach($fieldOptions as &$fieldOption) {
304 if ($fieldOption['name'] == 'other_amount') {
305 $fieldOption['label'] = $fieldOption['label'] . ' ' . $currencySymbol;
306 }
307 }
308 $qf->assign('priceset', $elementName);
309 $extra = array('onclick' => 'useAmountOther();');
310 }
311
312 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
313 $useRequired = 0;
314 }
315 elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
316 $label = $fieldOptions[$optionKey]['label'];
317 }
318
319 $element = &$qf->add('text', $elementName, $label,
320 array_merge($extra,
321 array('price' => json_encode(array($optionKey, $priceVal)),
322 'size' => '4',
323 )
324 ),
325 $useRequired && $field->is_required
326 );
327 if ($is_pay_later) {
328 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
329 }
330
331 // CRM-6902 - Add "max" option for a price set field
332 if (in_array($optionKey, $freezeOptions)) {
333 $element->freeze();
334 // CRM-14696 - Styling for sold out Text input fields is handled in PriceSet.tpl
335 }
336
337 //CRM-10117
338 if (!empty($qf->_quickConfig)) {
339 $message = ts('Please enter a valid amount.');
340 $type = 'money';
341 }
342 else {
343 $message = ts('%1 must be a number (with or without decimal point).', array(1 => $label));
344 $type = 'numeric';
345 }
346 // integers will have numeric rule applied to them.
347 $qf->addRule($elementName, $message, $type);
348 break;
349
350 case 'Radio':
351 $choice = array();
352
353 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
354 $qf->assign('contriPriceset', $elementName);
355 }
356
357 foreach ($customOption as $opId => $opt) {
358 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
359 if ($field->is_display_amounts) {
360 $opt['label'] = !empty($opt['label']) ? $opt['label'] . '&nbsp;-&nbsp;' : '';
361 if (isset($taxAmount) && $invoicing) {
362 if ($displayOpt == 'Do_not_show') {
363 $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>';
364 }
365 else if ($displayOpt == 'Inclusive') {
366 $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>';
367 $opt['label'] .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
368 }
369 else {
370 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span>';
371 $opt['label'] .= '<span class="crm-price-amount-tax"> + '. CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
372 }
373 }
374 else {
375 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span>';
376 }
377 }
378 $count = CRM_Utils_Array::value('count', $opt, '');
379 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
380 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
381 $extra = array('price' => json_encode(array($elementName, $priceVal)),
382 'data-amount' => $opt[$valueFieldName],
383 'data-currency' => $currencyName,
384 );
385 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
386 $extra += array('onclick' => 'clearAmountOther();');
387 }
388 elseif (!empty($qf->_quickConfig) && $field->name == 'membership_amount') {
389 $extra += array(
390 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
391 'membership-type' => $opt['membership_type_id'],
392 );
393 $qf->assign('membershipFieldID',$field->id);
394 }
395
396 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
397
398 if ($is_pay_later) {
399 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
400 }
401
402 // CRM-6902 - Add "max" option for a price set field
403 if (in_array($opId, $freezeOptions)) {
404 $choice[$opId]->freeze();
405 // CRM-14696 - Improve display for sold out price set options
406 $choice[$opId]->setText('<span class="sold-out-option">' . $choice[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
407 }
408 }
409 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
410 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
411 array(
412 'onclick' => 'clearAmountOther();',
413 )
414 );
415 }
416
417 if (!$field->is_required) {
418 // add "none" option
419 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
420 $none = ts('Other Amount');
421 }
422 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
423 $none = ts('No thank you');
424 }
425 else {
426 $none = ts('- none -');
427 }
428
429 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
430 array('price' => json_encode(array($elementName, '0')))
431 );
432 }
433
434 $element = &$qf->addGroup($choice, $elementName, $label);
435
436 // make contribution field required for quick config when membership block is enabled
437 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
438 && !empty($qf->_membershipBlock) && !$field->is_required) {
439 $useRequired = $field->is_required = TRUE;
440 }
441
442 if ($useRequired && $field->is_required) {
443 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
444 }
445 break;
446
447 case 'Select':
448 $selectOption = $allowedOptions = $priceVal = array();
449
450 foreach ($customOption as $opt) {
451 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
452 $count = CRM_Utils_Array::value('count', $opt, '');
453 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
454
455 if ($field->is_display_amounts) {
456 $opt['label'] .= '&nbsp;-&nbsp;';
457 if (isset($taxAmount) && $invoicing) {
458 $opt['label'] = $opt['label'] . self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
459 }
460 else {
461 $opt['label'] = $opt['label'] . CRM_Utils_Money::format($opt[$valueFieldName]);
462 }
463 }
464
465 $selectOption[$opt['id']] = $opt['label'];
466 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
467
468 if (!in_array($opt['id'], $freezeOptions)) {
469 $allowedOptions[] = $opt['id'];
470 }
471 // CRM-14696 - Improve display for sold out price set options
472 else {
473 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
474 }
475
476 $selectOption[$opt['id']] = $opt['label'];
477
478 if ($is_pay_later) {
479 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
480 }
481 }
482
483 $element = &$qf->add('select', $elementName, $label,
484 array(
485 '' => ts('- select -')) + $selectOption,
486 $useRequired && $field->is_required,
487 array('price' => json_encode($priceVal))
488 );
489
490 // CRM-6902 - Add "max" option for a price set field
491 $button = substr($qf->controller->getButtonName(), -4);
492 if (!empty($freezeOptions) && $button != 'skip') {
493 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
494 }
495 break;
496
497 case 'CheckBox':
498
499 $check = array();
500 foreach ($customOption as $opId => $opt) {
501 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
502 $count = CRM_Utils_Array::value('count', $opt, '');
503 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
504
505 if ($field->is_display_amounts) {
506 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>&nbsp;-&nbsp;';
507 if (isset($taxAmount) && $invoicing) {
508 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
509 }
510 else {
511 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
512 }
513 }
514 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
515 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
516 array('price' => json_encode(array($opt['id'], $priceVal)),
517 'data-amount' => $opt[$valueFieldName],
518 'data-currency' => $currencyName,
519 )
520 );
521 if ($is_pay_later) {
522 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
523 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
524 }
525 // CRM-6902 - Add "max" option for a price set field
526 if (in_array($opId, $freezeOptions)) {
527 $check[$opId]->freeze();
528 // CRM-14696 - Improve display for sold out price set options
529 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
530 }
531 }
532 $element = &$qf->addGroup($check, $elementName, $label);
533 if ($useRequired && $field->is_required) {
534 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
535 }
536 break;
537 }
538 if (isset($qf->_online) && $qf->_online) {
539 $element->freeze();
540 }
541 }
542
543 /**
544 * Retrieve a list of options for the specified field
545 *
546 * @param int $fieldId price field ID
547 * @param bool $inactiveNeeded include inactive options
548 * @param bool $reset ignore stored values\
549 *
550 * @return array array of options
551 */
552 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
553 static $options = array();
554
555 if ($reset || empty($options[$fieldId])) {
556 $values = array();
557 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
558 $options[$fieldId] = $values;
559 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
560
561 // ToDo - Code for Hook Invoke
562
563 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
564 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates)) {
565 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
566 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
567 $options[$fieldId][$priceFieldId]['tax_amount'] = round($taxAmount['tax_amount'],2);
568 }
569 }
570 }
571
572 return $options[$fieldId];
573 }
574
575 /**
576 * @param $optionLabel
577 * @param int $fid
578 *
579 * @return mixed
580 */
581 public static function getOptionId($optionLabel, $fid) {
582 if (!$optionLabel || !$fid) {
583 return;
584 }
585
586 $optionGroupName = "civicrm_price_field.amount.{$fid}";
587
588 $query = "
589 SELECT
590 option_value.id as id
591 FROM
592 civicrm_option_value option_value,
593 civicrm_option_group option_group
594 WHERE
595 option_group.name = %1
596 AND option_group.id = option_value.option_group_id
597 AND option_value.label = %2";
598
599 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
600
601 while ($dao->fetch()) {
602 return $dao->id;
603 }
604 }
605
606 /**
607 * Delete the price set field.
608 *
609 * @param int $id Field Id
610 *
611 * @return boolean
612 *
613 * @access public
614 * @static
615 *
616 */
617 public static function deleteField($id) {
618 $field = new CRM_Price_DAO_PriceField();
619 $field->id = $id;
620
621 if ($field->find(TRUE)) {
622 // delete the options for this field
623 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
624
625 // reorder the weight before delete
626 $fieldValues = array('price_set_id' => $field->price_set_id);
627
628 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
629
630 // now delete the field
631 return $field->delete();
632 }
633
634 return NULL;
635 }
636
637 /**
638 * @return array
639 */
640 static function &htmlTypes() {
641 static $htmlTypes = NULL;
642 if (!$htmlTypes) {
643 $htmlTypes = array(
644 'Text' => ts('Text / Numeric Quantity'),
645 'Select' => ts('Select'),
646 'Radio' => ts('Radio'),
647 'CheckBox' => ts('CheckBox'),
648 );
649 }
650 return $htmlTypes;
651 }
652
653 /**
654 * Validate the priceset
655 *
656 * @param int $priceSetId , array $fields
657 *
658 * retrun the error string
659 *
660 * @param $fields
661 * @param $error
662 * @param bool $allowNoneSelection
663 *
664 * @access public
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 * @access public
763 * @static
764 *
765 */
766 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
767 if ($displayOpt == 'Do_not_show') {
768 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
769 }
770 else if ($displayOpt == 'Inclusive') {
771 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
772 $label .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
773 }
774 else {
775 $label = CRM_Utils_Money::format($opt[$valueFieldName]);
776 $label .= '<span class="crm-price-amount-tax"> + '. CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
777 }
778
779 return $label;
780 }
781 }
782