Merge pull request #40 from pratikshad/VAT-578-source
[civicrm-core.git] / CRM / Price / BAO / PriceField.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * Business objects for managing price fields.
38 *
39 */
9da8dc8c 40class CRM_Price_BAO_PriceField extends CRM_Price_DAO_PriceField {
6a488035
TO
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 *
77b97be7
EM
51 * @param array $params (reference ) an assoc array of name/value pairs
52 *
53 * @internal param array $ids the array that holds all the db ids
6a488035 54 *
9da8dc8c 55 * @return object CRM_Price_BAO_PriceField object
6a488035
TO
56 * @access public
57 * @static
58 */
59 static function &add(&$params) {
9da8dc8c 60 $priceFieldBAO = new CRM_Price_BAO_PriceField();
6a488035
TO
61
62 $priceFieldBAO->copyValues($params);
63
64 if ($id = CRM_Utils_Array::value('id', $params)) {
65 $priceFieldBAO->id = $id;
66 }
67
68 $priceFieldBAO->save();
69 return $priceFieldBAO;
70 }
71
72 /**
73 * takes an associative array and creates a price field object
74 *
75 * This function is invoked from within the web form layer and also from the api layer
76 *
77 * @param array $params (reference) an assoc array of name/value pairs
78 *
9da8dc8c 79 * @return object CRM_Price_DAO_PriceField object
6a488035
TO
80 * @access public
81 * @static
82 */
83 static function create(&$params) {
84 $transaction = new CRM_Core_Transaction();
85
86 $priceField = self::add($params);
87
88 if (is_a($priceField, 'CRM_Core_Error')) {
89 $transaction->rollback();
90 return $priceField;
91 }
92
93 $options = $optionsIds = array();
94 $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
95
96 if ($priceField->html_type == 'Text') {
97 $maxIndex = 1;
98
9da8dc8c 99 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
6a488035
TO
100 $fieldValue->price_field_id = $priceField->id;
101
102 // update previous field values( if any )
103 if ($fieldValue->find(TRUE)) {
104 $optionsIds['id'] = $fieldValue->id;
105 }
106 }
107 $defaultArray = array();
108 if ($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 {
a7488080 117 if (!empty($params['default_option'])) {
6a488035
TO
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']) &&
8cc574cf 125 (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) &&
6a488035
TO
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];
a7488080 149 } elseif (!empty($params['financial_type_id'])) {
6a488035
TO
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 }
9da8dc8c 160 CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
6a488035
TO
161 }
162 }
163
164 $transaction->commit();
165 return $priceField;
166 }
167
168 /**
169 * Takes a bunch of params that are needed to match certain criteria and
170 * retrieves the relevant objects. Typically the valid params are only
171 * contact_id. We'll tweak this function to be more full featured over a period
172 * of time. This is the inverse function of create. It also stores all the retrieved
173 * values in the default array
174 *
175 * @param array $params (reference ) an assoc array of name/value pairs
176 * @param array $defaults (reference ) an assoc array to hold the flattened values
177 *
9da8dc8c 178 * @return object CRM_Price_DAO_PriceField object
6a488035
TO
179 * @access public
180 * @static
181 */
182 static function retrieve(&$params, &$defaults) {
9da8dc8c 183 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
6a488035
TO
184 }
185
186 /**
187 * update the is_active flag in the db
188 *
189 * @param int $id Id of the database record
190 * @param boolean $is_active Value we want to set the is_active field
191 *
192 * @return Object DAO object on sucess, null otherwise
193 *
194 * @access public
195 * @static
196 */
197 static function setIsActive($id, $is_active) {
9da8dc8c 198 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
6a488035
TO
199 }
200
201 /**
202 * Get the field title.
203 *
204 * @param int $id id of field.
205 *
206 * @return string name
207 *
208 * @access public
209 * @static
210 *
211 */
212 public static function getTitle($id) {
9da8dc8c 213 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
6a488035
TO
214 }
215
216 /**
217 * This function for building custom fields
218 *
77b97be7
EM
219 * @param object $qf form object (reference)
220 * @param string $elementName name of the custom field
221 * @param $fieldId
6a488035 222 * @param boolean $inactiveNeeded
77b97be7
EM
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 $feezeOptions
6a488035 228 *
77b97be7
EM
229 * @return null
230 * @internal param bool $search true if used for search else false
6a488035
TO
231 * @access public
232 * @static
233 */
234 public static function addQuickFormElement(&$qf,
235 $elementName,
236 $fieldId,
237 $inactiveNeeded,
535a8e1e
CW
238 $useRequired = TRUE,
239 $label = NULL,
6a488035
TO
240 $fieldOptions = NULL,
241 $feezeOptions = array()
242 ) {
243
9da8dc8c 244 $field = new CRM_Price_DAO_PriceField();
6a488035
TO
245 $field->id = $fieldId;
246 if (!$field->find(TRUE)) {
247 /* FIXME: failure! */
248 return NULL;
249 }
366fe2a3 250
6a488035
TO
251 $is_pay_later = 0;
252 if (isset($qf->_mode) && empty($qf->_mode)) {
253 $is_pay_later = 1;
254 }
255 elseif (isset($qf->_values)) {
256 $is_pay_later = CRM_Utils_Array::value( 'is_pay_later', $qf->_values);
257 }
258
259 $otherAmount = $qf->get('values');
260 $config = CRM_Core_Config::singleton();
261 $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency',$config->defaultCurrency,'symbol','name');
262 $qf->assign('currencySymbol', $currencySymbol);
263 // get currency name for price field and option attributes
264 $currencyName = $config->defaultCurrency;
265
266 if (!isset($label)) {
15831617 267 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
6a488035
TO
268 }
269
270 if ($field->name == 'contribution_amount') {
271 $qf->_contributionAmount = 1;
272 }
273
274 if (isset($qf->_online) && $qf->_online) {
275 $useRequired = FALSE;
276 }
277
278 $customOption = $fieldOptions;
279 if (!is_array($customOption)) {
9da8dc8c 280 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
6a488035
TO
281 }
282
283 //use value field.
284 $valueFieldName = 'amount';
285 $seperator = '|';
e0f7075f 286 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
5ebee375 287 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
288 $displayOpt = CRM_Utils_Array::value('tax_display_settings', $invoiceSettings);
6a488035
TO
289 switch ($field->html_type) {
290 case 'Text':
291 $optionKey = key($customOption);
535a8e1e 292 $count = CRM_Utils_Array::value('count', $customOption[$optionKey], '');
6a488035 293 $max_value = CRM_Utils_Array::value('max_value', $customOption[$optionKey], '');
9d1c9154 294 $taxAmount = CRM_Utils_Array::value('tax_amount', $customOption[$optionKey]);
5ebee375 295 if (isset($taxAmount) && $displayOpt) {
dc428161 296 $qf->assign('displayOpt', $displayOpt);
5ebee375 297 $qf->assign('taxTerm', $taxTerm);
dc428161 298 }
299 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName] + $taxAmount, $count, $max_value));
6a488035
TO
300
301 $extra = array();
15831617 302 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
6a488035
TO
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();');
6a488035
TO
310 }
311
15831617 312 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
6a488035 313 $useRequired = 0;
366fe2a3 314 }
a7488080 315 elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
6a488035
TO
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
332 if (in_array($optionKey, $feezeOptions)) {
333 $element->freeze();
334 }
335
336 //CRM-10117
15831617 337 if (!empty($qf->_quickConfig)) {
6a488035
TO
338 $message = ts('Please enter a valid amount.');
339 $type = 'money';
366fe2a3 340 }
6a488035
TO
341 else {
342 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
343 $type = 'positiveInteger';
344 }
345 // integers will have numeric rule applied to them.
346 $qf->addRule($elementName, $message, $type);
347 break;
348
349 case 'Radio':
350 $choice = array();
351
15831617 352 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
6a488035
TO
353 $qf->assign('contriPriceset', $elementName);
354 }
355
356 foreach ($customOption as $opId => $opt) {
9d1c9154 357 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
6a488035 358 if ($field->is_display_amounts) {
0d8afee2 359 $opt['label'] = !empty($opt['label']) ? $opt['label'] : '';
5ebee375 360 if (isset($taxAmount)) {
dc428161 361 if ($displayOpt == 'Do_not_show') {
362 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName] + $taxAmount) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
363 }
364 else if ($displayOpt == 'Inclusive') {
365 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName] + $taxAmount) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
a13f764f 366 $opt['label'] .= '<span class="crm-price-amount-label"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
dc428161 367 }
368 else {
369 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
a13f764f 370 $opt['label'] .= '<span class="crm-price-amount-label"> + '. CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
dc428161 371 }
372 }
373 else {
374 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
375 }
6a488035 376 }
535a8e1e 377 $count = CRM_Utils_Array::value('count', $opt, '');
6a488035 378 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
dc428161 379 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
6a488035
TO
380 $extra = array('price' => json_encode(array($elementName, $priceVal)),
381 'data-amount' => $opt[$valueFieldName],
382 'data-currency' => $currencyName,
383 );
15831617 384 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
6a488035 385 $extra += array('onclick' => 'clearAmountOther();');
366fe2a3 386 }
15831617 387 elseif (!empty($qf->_quickConfig) && $field->name == 'membership_amount') {
6a488035
TO
388 $extra += array(
389 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
390 'membership-type' => $opt['membership_type_id'],
366fe2a3 391 );
6a488035
TO
392 $qf->assign('membershipFieldID',$field->id);
393 }
366fe2a3 394
6a488035
TO
395 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
396
397 if ($is_pay_later) {
398 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
399 }
400
401 // CRM-6902
402 if (in_array($opId, $feezeOptions)) {
403 $choice[$opId]->freeze();
404 }
405 }
15831617 406 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
6a488035 407 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
abcf506a
PN
408 array(
409 'onclick' => 'clearAmountOther();',
410 )
6a488035
TO
411 );
412 }
413
414 if (!$field->is_required) {
415 // add "none" option
a7488080 416 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
6a488035 417 $none = ts('Other Amount');
366fe2a3 418 }
8cc574cf 419 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
6a488035 420 $none = ts('No thank you');
366fe2a3 421 }
6a488035
TO
422 else {
423 $none = ts('- none -');
424 }
425
426 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
427 array('price' => json_encode(array($elementName, '0')))
428 );
429 }
430
431 $element = &$qf->addGroup($choice, $elementName, $label);
432
433 // make contribution field required for quick config when membership block is enabled
abcf506a 434 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
15831617 435 && !empty($qf->_membershipBlock) && !$field->is_required) {
6a488035
TO
436 $useRequired = $field->is_required = TRUE;
437 }
438
439 if ($useRequired && $field->is_required) {
440 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
441 }
442 break;
443
444 case 'Select':
445 $selectOption = $allowedOptions = $priceVal = array();
446
447 foreach ($customOption as $opt) {
9d1c9154 448 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
6a488035
TO
449 $count = CRM_Utils_Array::value('count', $opt, '');
450 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
6a488035
TO
451
452 if ($field->is_display_amounts) {
453 $opt['label'] .= '&nbsp;-&nbsp;';
5ebee375 454 if (isset($taxAmount)) {
455 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
dc428161 456 }
457 else {
458 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
459 }
6a488035
TO
460 }
461 $selectOption[$opt['id']] = $opt['label'];
dc428161 462 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
6a488035
TO
463
464 if (!in_array($opt['id'], $feezeOptions)) {
465 $allowedOptions[] = $opt['id'];
466 }
467 if ($is_pay_later) {
468 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
469 }
470 }
471 $element = &$qf->add('select', $elementName, $label,
472 array(
473 '' => ts('- select -')) + $selectOption,
474 $useRequired && $field->is_required,
475 array('price' => json_encode($priceVal))
476 );
477
478 // CRM-6902
479 $button = substr($qf->controller->getButtonName(), -4);
480 if (!empty($feezeOptions) && $button != 'skip') {
481 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
482 }
483 break;
484
485 case 'CheckBox':
486
487 $check = array();
488 foreach ($customOption as $opId => $opt) {
9d1c9154 489 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
535a8e1e 490 $count = CRM_Utils_Array::value('count', $opt, '');
6a488035 491 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
6a488035
TO
492
493 if ($field->is_display_amounts) {
494 $opt['label'] .= '&nbsp;-&nbsp;';
5ebee375 495 if (isset($taxAmount)) {
496 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
dc428161 497 }
498 else {
499 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
500 }
6a488035 501 }
dc428161 502 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
6a488035
TO
503 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
504 array('price' => json_encode(array($opt['id'], $priceVal)),
505 'data-amount' => $opt[$valueFieldName],
506 'data-currency' => $currencyName,
507 )
508 );
509 if ($is_pay_later) {
510 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
511 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
512 }
513 // CRM-6902
514 if (in_array($opId, $feezeOptions)) {
515 $check[$opId]->freeze();
516 }
517 }
518 $element = &$qf->addGroup($check, $elementName, $label);
519 if ($useRequired && $field->is_required) {
520 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
521 }
522 break;
523 }
524 if (isset($qf->_online) && $qf->_online) {
525 $element->freeze();
526 }
527 }
528
529 /**
530 * Retrieve a list of options for the specified field
531 *
532 * @param int $fieldId price field ID
533 * @param bool $inactiveNeeded include inactive options
534 * @param bool $reset ignore stored values\
535 *
536 * @return array array of options
537 */
538 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
539 static $options = array();
540
541 if ($reset || empty($options[$fieldId])) {
542 $values = array();
9da8dc8c 543 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
6a488035 544 $options[$fieldId] = $values;
dc428161 545 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
546
547 // ToDo - Code for Hook Invoke
548
549 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
550 if (array_key_exists($priceFieldValues['financial_type_id'], $taxRates)) {
551 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
9d1c9154 552 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
dc428161 553 $options[$fieldId][$priceFieldId]['tax_amount'] = round($taxAmount['tax_amount'],2);
554 }
555 }
6a488035
TO
556 }
557
558 return $options[$fieldId];
559 }
560
561 public static function getOptionId($optionLabel, $fid) {
562 if (!$optionLabel || !$fid) {
563 return;
564 }
565
566 $optionGroupName = "civicrm_price_field.amount.{$fid}";
567
568 $query = "
569SELECT
570 option_value.id as id
571FROM
572 civicrm_option_value option_value,
573 civicrm_option_group option_group
574WHERE
535a8e1e
CW
575 option_group.name = %1
576 AND option_group.id = option_value.option_group_id
6a488035
TO
577 AND option_value.label = %2";
578
579 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
580
581 while ($dao->fetch()) {
582 return $dao->id;
583 }
584 }
585
586 /**
587 * Delete the price set field.
588 *
589 * @param int $id Field Id
590 *
591 * @return boolean
592 *
593 * @access public
594 * @static
595 *
596 */
597 public static function deleteField($id) {
9da8dc8c 598 $field = new CRM_Price_DAO_PriceField();
6a488035
TO
599 $field->id = $id;
600
601 if ($field->find(TRUE)) {
602 // delete the options for this field
9da8dc8c 603 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
6a488035
TO
604
605 // reorder the weight before delete
606 $fieldValues = array('price_set_id' => $field->price_set_id);
607
9da8dc8c 608 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
6a488035
TO
609
610 // now delete the field
611 return $field->delete();
612 }
613
614 return NULL;
615 }
616
617 static function &htmlTypes() {
618 static $htmlTypes = NULL;
619 if (!$htmlTypes) {
620 $htmlTypes = array(
621 'Text' => ts('Text / Numeric Quantity'),
622 'Select' => ts('Select'),
623 'Radio' => ts('Radio'),
624 'CheckBox' => ts('CheckBox'),
625 );
626 }
627 return $htmlTypes;
628 }
629
630 /**
631 * Validate the priceset
632 *
2a6da8d7 633 * @param int $priceSetId , array $fields
6a488035
TO
634 *
635 * retrun the error string
636 *
2a6da8d7
EM
637 * @param $fields
638 * @param $error
639 * @param bool $allowNoneSelection
640 *
6a488035
TO
641 * @access public
642 * @static
6a488035
TO
643 */
644
645 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
646 // check for at least one positive
647 // amount price field should be selected.
9da8dc8c 648 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
649 $priceField->price_set_id = $priceSetId;
650 $priceField->find();
651
652 $priceFields = array();
653
654 if ($allowNoneSelection) {
655 $noneSelectedPriceFields = array();
656 }
657
658 while ($priceField->fetch()) {
659 $key = "price_{$priceField->id}";
660
661 if ($allowNoneSelection) {
662 if (array_key_exists($key, $fields)) {
663 if ($fields[$key] == 0 && !$priceField->is_required) {
664 $noneSelectedPriceFields[] = $priceField->id;
665 }
666 }
667 }
668
a7488080 669 if (!empty($fields[$key])) {
6a488035
TO
670 $priceFields[$priceField->id] = $fields[$key];
671 }
672 }
673
674 if (!empty($priceFields)) {
675 // we should has to have positive amount.
676 $sql = "
677SELECT id, html_type
678FROM civicrm_price_field
679WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
680 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
681 $htmlTypes = array();
682 while ($fieldDAO->fetch()) {
683 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
684 }
685
686 $selectedAmounts = array();
687
688 foreach ($htmlTypes as $fieldId => $type) {
689 $options = array();
9da8dc8c 690 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
6a488035
TO
691
692 if (empty($options)) {
693 continue;
694 }
695
696 if ($type == 'Text') {
697 foreach ($options as $opId => $option) {
698 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
699 break;
700 }
701 }
702 elseif (is_array($fields["price_{$fieldId}"])) {
703 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
704 $selectedAmounts[$opId] = $options[$opId]['amount'];
705 }
706 }
707 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
708 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
709 }
710 }
711
712 list($componentName) = explode(':', $fields['_qf_default']);
713 // now we have all selected amount in hand.
714 $totalAmount = array_sum($selectedAmounts);
715 if ($totalAmount < 0) {
716 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
717 }
718 }
719 else {
720 if ($allowNoneSelection) {
721 if (empty($noneSelectedPriceFields)) {
722 $error['_qf_default'] = ts('Please select at least one option from price set.');
723 }
724 } else {
725 $error['_qf_default'] = ts('Please select at least one option from price set.');
726 }
727 }
728 }
dc428161 729
730 /**
9d1c9154 731 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
dc428161 732 *
9d1c9154 733 * @param array $opt
734 * @param string $valueFieldName amount
735 * @param string $displayOpt tax display setting option
dc428161 736 *
9d1c9154 737 * @return string $label tax label for custom field
dc428161 738 *
739 * @access public
740 * @static
741 *
742 */
5ebee375 743 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
9d1c9154 744 if ($displayOpt == 'Do_not_show') {
745 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
746 }
747 else if ($displayOpt == 'Inclusive') {
748 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
a13f764f 749 $label .= '<span class="crm-price-amount-label"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
9d1c9154 750 }
751 else {
752 $label = CRM_Utils_Money::format($opt[$valueFieldName]);
a13f764f 753 $label .= '<span class="crm-price-amount-label"> + '. CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
9d1c9154 754 }
dc428161 755
9d1c9154 756 return $label;
dc428161 757 }
6a488035
TO
758}
759