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