Added ts() for VAT (exempt).
[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 * @internal param array $ids the array that holds all the db ids
54 *
55 * @return object CRM_Price_BAO_PriceField object
56 * @access public
57 * @static
58 */
59 static function &add(&$params) {
60 $priceFieldBAO = new CRM_Price_BAO_PriceField();
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 *
79 * @return object CRM_Price_DAO_PriceField object
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
99 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
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 {
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 * 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 *
178 * @return object CRM_Price_DAO_PriceField object
179 * @access public
180 * @static
181 */
182 static function retrieve(&$params, &$defaults) {
183 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
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) {
198 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
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) {
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 object $qf form object (reference)
220 * @param string $elementName name of the custom field
221 * @param $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 $feezeOptions
228 *
229 * @return null
230 * @internal param bool $search true if used for search else false
231 * @access public
232 * @static
233 */
234 public static function addQuickFormElement(&$qf,
235 $elementName,
236 $fieldId,
237 $inactiveNeeded,
238 $useRequired = TRUE,
239 $label = NULL,
240 $fieldOptions = NULL,
241 $feezeOptions = array()
242 ) {
243
244 $field = new CRM_Price_DAO_PriceField();
245 $field->id = $fieldId;
246 if (!$field->find(TRUE)) {
247 /* FIXME: failure! */
248 return NULL;
249 }
250
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)) {
267 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
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)) {
280 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
281 }
282
283 //use value field.
284 $valueFieldName = 'amount';
285 $seperator = '|';
286 $displayOpt = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
287 $displayOpt = CRM_Utils_Array::value('tax_display_settings', $displayOpt);
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 ($taxAmount && $displayOpt) {
295 $qf->assign('displayOpt', $displayOpt);
296 }
297 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName] + $taxAmount, $count, $max_value));
298
299 $extra = array();
300 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
301 foreach($fieldOptions as &$fieldOption) {
302 if ($fieldOption['name'] == 'other_amount') {
303 $fieldOption['label'] = $fieldOption['label'] . ' ' . $currencySymbol;
304 }
305 }
306 $qf->assign('priceset', $elementName);
307 $extra = array('onclick' => 'useAmountOther();');
308 }
309
310 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
311 $useRequired = 0;
312 }
313 elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
314 $label = $fieldOptions[$optionKey]['label'];
315 }
316
317 $element = &$qf->add('text', $elementName, $label,
318 array_merge($extra,
319 array('price' => json_encode(array($optionKey, $priceVal)),
320 'size' => '4',
321 )
322 ),
323 $useRequired && $field->is_required
324 );
325 if ($is_pay_later) {
326 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
327 }
328
329 // CRM-6902
330 if (in_array($optionKey, $feezeOptions)) {
331 $element->freeze();
332 }
333
334 //CRM-10117
335 if (!empty($qf->_quickConfig)) {
336 $message = ts('Please enter a valid amount.');
337 $type = 'money';
338 }
339 else {
340 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
341 $type = 'positiveInteger';
342 }
343 // integers will have numeric rule applied to them.
344 $qf->addRule($elementName, $message, $type);
345 break;
346
347 case 'Radio':
348 $choice = array();
349
350 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
351 $qf->assign('contriPriceset', $elementName);
352 }
353
354 foreach ($customOption as $opId => $opt) {
355 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
356 if ($field->is_display_amounts) {
357 $opt['label'] = !empty($opt['label']) ? $opt['label'] : '';
358 if ($taxAmount) {
359 if ($displayOpt == 'Do_not_show') {
360 $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>';
361 }
362 else if ($displayOpt == 'Inclusive') {
363 $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>';
364 $opt['label'] .= '<span class="crm-price-amount-label"> (includes '.round($opt['tax_rate'],2).'% VAT - ' . CRM_Utils_Money::format($taxAmount) . ')</span>';
365 }
366 else {
367 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
368 $opt['label'] .= '<span class="crm-price-amount-label"> + '.round($opt['tax_rate'],2).'% VAT - ' . CRM_Utils_Money::format($taxAmount) . '</span>';
369 }
370 }
371 else {
372 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
373 if (isset($opt['tax_amount']) && $displayOpt != 'Do_not_show') {
374 $opt['label'] .= '<span class="crm-price-amount-label">'. ts(' VAT (exempt)') .'</span>';
375 }
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
403 if (in_array($opId, $feezeOptions)) {
404 $choice[$opId]->freeze();
405 }
406 }
407 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
408 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
409 array(
410 'onclick' => 'clearAmountOther();',
411 )
412 );
413 }
414
415 if (!$field->is_required) {
416 // add "none" option
417 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
418 $none = ts('Other Amount');
419 }
420 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
421 $none = ts('No thank you');
422 }
423 else {
424 $none = ts('- none -');
425 }
426
427 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
428 array('price' => json_encode(array($elementName, '0')))
429 );
430 }
431
432 $element = &$qf->addGroup($choice, $elementName, $label);
433
434 // make contribution field required for quick config when membership block is enabled
435 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
436 && !empty($qf->_membershipBlock) && !$field->is_required) {
437 $useRequired = $field->is_required = TRUE;
438 }
439
440 if ($useRequired && $field->is_required) {
441 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
442 }
443 break;
444
445 case 'Select':
446 $selectOption = $allowedOptions = $priceVal = array();
447
448 foreach ($customOption as $opt) {
449 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
450 $count = CRM_Utils_Array::value('count', $opt, '');
451 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
452
453 if ($field->is_display_amounts) {
454 $opt['label'] .= '&nbsp;-&nbsp;';
455 if ($taxAmount) {
456 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt);
457 }
458 else {
459 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
460 if (isset($opt['tax_amount']) && $displayOpt != 'Do_not_show') {
461 $opt['label'] .= '<span class="crm-price-amount-label">'. ts(' VAT (exempt)') .'</span>';
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'], $feezeOptions)) {
469 $allowedOptions[] = $opt['id'];
470 }
471 if ($is_pay_later) {
472 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
473 }
474 }
475 $element = &$qf->add('select', $elementName, $label,
476 array(
477 '' => ts('- select -')) + $selectOption,
478 $useRequired && $field->is_required,
479 array('price' => json_encode($priceVal))
480 );
481
482 // CRM-6902
483 $button = substr($qf->controller->getButtonName(), -4);
484 if (!empty($feezeOptions) && $button != 'skip') {
485 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
486 }
487 break;
488
489 case 'CheckBox':
490
491 $check = array();
492 foreach ($customOption as $opId => $opt) {
493 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
494 $count = CRM_Utils_Array::value('count', $opt, '');
495 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
496
497 if ($field->is_display_amounts) {
498 $opt['label'] .= '&nbsp;-&nbsp;';
499 if ($taxAmount) {
500 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt);
501 }
502 else {
503 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
504 if (isset($opt['tax_amount']) && $displayOpt != 'Do_not_show') {
505 $opt['label'] .= '<span class="crm-price-amount-label">'. ts(' VAT (exempt)') .'</span>';
506 }
507 }
508 }
509 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
510 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
511 array('price' => json_encode(array($opt['id'], $priceVal)),
512 'data-amount' => $opt[$valueFieldName],
513 'data-currency' => $currencyName,
514 )
515 );
516 if ($is_pay_later) {
517 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
518 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
519 }
520 // CRM-6902
521 if (in_array($opId, $feezeOptions)) {
522 $check[$opId]->freeze();
523 }
524 }
525 $element = &$qf->addGroup($check, $elementName, $label);
526 if ($useRequired && $field->is_required) {
527 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
528 }
529 break;
530 }
531 if (isset($qf->_online) && $qf->_online) {
532 $element->freeze();
533 }
534 }
535
536 /**
537 * Retrieve a list of options for the specified field
538 *
539 * @param int $fieldId price field ID
540 * @param bool $inactiveNeeded include inactive options
541 * @param bool $reset ignore stored values\
542 *
543 * @return array array of options
544 */
545 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
546 static $options = array();
547
548 if ($reset || empty($options[$fieldId])) {
549 $values = array();
550 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
551 $options[$fieldId] = $values;
552 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
553
554 // ToDo - Code for Hook Invoke
555
556 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
557 if (array_key_exists($priceFieldValues['financial_type_id'], $taxRates)) {
558 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
559 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
560 $options[$fieldId][$priceFieldId]['tax_amount'] = round($taxAmount['tax_amount'],2);
561 }
562 }
563 }
564
565 return $options[$fieldId];
566 }
567
568 public static function getOptionId($optionLabel, $fid) {
569 if (!$optionLabel || !$fid) {
570 return;
571 }
572
573 $optionGroupName = "civicrm_price_field.amount.{$fid}";
574
575 $query = "
576 SELECT
577 option_value.id as id
578 FROM
579 civicrm_option_value option_value,
580 civicrm_option_group option_group
581 WHERE
582 option_group.name = %1
583 AND option_group.id = option_value.option_group_id
584 AND option_value.label = %2";
585
586 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
587
588 while ($dao->fetch()) {
589 return $dao->id;
590 }
591 }
592
593 /**
594 * Delete the price set field.
595 *
596 * @param int $id Field Id
597 *
598 * @return boolean
599 *
600 * @access public
601 * @static
602 *
603 */
604 public static function deleteField($id) {
605 $field = new CRM_Price_DAO_PriceField();
606 $field->id = $id;
607
608 if ($field->find(TRUE)) {
609 // delete the options for this field
610 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
611
612 // reorder the weight before delete
613 $fieldValues = array('price_set_id' => $field->price_set_id);
614
615 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
616
617 // now delete the field
618 return $field->delete();
619 }
620
621 return NULL;
622 }
623
624 static function &htmlTypes() {
625 static $htmlTypes = NULL;
626 if (!$htmlTypes) {
627 $htmlTypes = array(
628 'Text' => ts('Text / Numeric Quantity'),
629 'Select' => ts('Select'),
630 'Radio' => ts('Radio'),
631 'CheckBox' => ts('CheckBox'),
632 );
633 }
634 return $htmlTypes;
635 }
636
637 /**
638 * Validate the priceset
639 *
640 * @param int $priceSetId , array $fields
641 *
642 * retrun the error string
643 *
644 * @param $fields
645 * @param $error
646 * @param bool $allowNoneSelection
647 *
648 * @access public
649 * @static
650 */
651
652 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
653 // check for at least one positive
654 // amount price field should be selected.
655 $priceField = new CRM_Price_DAO_PriceField();
656 $priceField->price_set_id = $priceSetId;
657 $priceField->find();
658
659 $priceFields = array();
660
661 if ($allowNoneSelection) {
662 $noneSelectedPriceFields = array();
663 }
664
665 while ($priceField->fetch()) {
666 $key = "price_{$priceField->id}";
667
668 if ($allowNoneSelection) {
669 if (array_key_exists($key, $fields)) {
670 if ($fields[$key] == 0 && !$priceField->is_required) {
671 $noneSelectedPriceFields[] = $priceField->id;
672 }
673 }
674 }
675
676 if (!empty($fields[$key])) {
677 $priceFields[$priceField->id] = $fields[$key];
678 }
679 }
680
681 if (!empty($priceFields)) {
682 // we should has to have positive amount.
683 $sql = "
684 SELECT id, html_type
685 FROM civicrm_price_field
686 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
687 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
688 $htmlTypes = array();
689 while ($fieldDAO->fetch()) {
690 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
691 }
692
693 $selectedAmounts = array();
694
695 foreach ($htmlTypes as $fieldId => $type) {
696 $options = array();
697 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
698
699 if (empty($options)) {
700 continue;
701 }
702
703 if ($type == 'Text') {
704 foreach ($options as $opId => $option) {
705 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
706 break;
707 }
708 }
709 elseif (is_array($fields["price_{$fieldId}"])) {
710 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
711 $selectedAmounts[$opId] = $options[$opId]['amount'];
712 }
713 }
714 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
715 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
716 }
717 }
718
719 list($componentName) = explode(':', $fields['_qf_default']);
720 // now we have all selected amount in hand.
721 $totalAmount = array_sum($selectedAmounts);
722 if ($totalAmount < 0) {
723 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
724 }
725 }
726 else {
727 if ($allowNoneSelection) {
728 if (empty($noneSelectedPriceFields)) {
729 $error['_qf_default'] = ts('Please select at least one option from price set.');
730 }
731 } else {
732 $error['_qf_default'] = ts('Please select at least one option from price set.');
733 }
734 }
735 }
736
737 /**
738 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
739 *
740 * @param array $opt
741 * @param string $valueFieldName amount
742 * @param string $displayOpt tax display setting option
743 *
744 * @return string $label tax label for custom field
745 *
746 * @access public
747 * @static
748 *
749 */
750 public static function getTaxLabel($opt, $valueFieldName, $displayOpt) {
751 if ($displayOpt == 'Do_not_show') {
752 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
753 }
754 else if ($displayOpt == 'Inclusive') {
755 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
756 $label .= '<span class="crm-price-amount-label"> (includes '.round($opt['tax_rate'],2).'% VAT - ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
757 }
758 else {
759 $label = CRM_Utils_Money::format($opt[$valueFieldName]);
760 $label .= '<span class="crm-price-amount-label"> + '.round($opt['tax_rate'],2).'% VAT - ' . CRM_Utils_Money::format($opt['tax_amount']) . '</span>';
761 }
762
763 return $label;
764 }
765 }
766