Improve accessibility for price fields of the type select by adding the field label...
[civicrm-core.git] / CRM / Price / BAO / PriceField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Business objects for managing price fields.
14 *
15 */
16 class CRM_Price_BAO_PriceField extends CRM_Price_DAO_PriceField {
17
18 protected $_options;
19
20 /**
21 * List of visibility option ID's, of the form name => ID
22 *
23 * @var array
24 */
25 private static $visibilityOptionsKeys;
26
27 /**
28 * Create or update a PriceField.
29 *
30 * @param array $params
31 * @return CRM_Price_DAO_PriceField
32 */
33 public static function add($params) {
34 return self::writeRecord($params);
35 }
36
37 /**
38 * Takes an associative array and creates a price field object.
39 *
40 * This function is invoked from within the web form layer and also from the api layer
41 *
42 * @param array $params
43 * (reference) an assoc array of name/value pairs.
44 *
45 * @return CRM_Price_DAO_PriceField
46 *
47 * @throws \CRM_Core_Exception
48 * @throws \CiviCRM_API3_Exception
49 */
50 public static function create(&$params) {
51 if (empty($params['id']) && empty($params['name'])) {
52 $params['name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 242));
53 }
54 $transaction = new CRM_Core_Transaction();
55
56 $priceField = self::add($params);
57
58 if (is_a($priceField, 'CRM_Core_Error')) {
59 $transaction->rollback();
60 return $priceField;
61 }
62
63 if (!empty($params['id']) && empty($priceField->html_type)) {
64 $priceField->html_type = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['id'], 'html_type');
65 }
66 $optionsIds = [];
67 $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
68 if ($priceField->html_type == 'Text') {
69 $maxIndex = 1;
70 $fieldOptions = civicrm_api3('price_field_value', 'get', [
71 'price_field_id' => $priceField->id,
72 'sequential' => 1,
73 ]);
74 foreach ($fieldOptions['values'] as $option) {
75 $optionsIds['id'] = $option['id'];
76 $params['option_id'] = [1 => $option['id']];
77 // CRM-19741 If we are dealing with price fields that are Text only set the field value label to match
78 if (!empty($params['id']) && $priceField->label != $option['label']) {
79 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
80 $fieldValue->label = $priceField->label;
81 $fieldValue->id = $option['id'];
82 $fieldValue->save();
83 }
84 }
85 }
86 $defaultArray = [];
87 //html type would be empty in update scenario not sure what would happen ...
88 if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
89 $tempArray = array_keys($params['default_checkbox_option']);
90 foreach ($tempArray as $v) {
91 if ($params['option_amount'][$v]) {
92 $defaultArray[$v] = 1;
93 }
94 }
95 }
96 else {
97 if (!empty($params['default_option'])) {
98 $defaultArray[$params['default_option']] = 1;
99 }
100 }
101
102 for ($index = 1; $index <= $maxIndex; $index++) {
103 if (array_key_exists('option_amount', $params) &&
104 array_key_exists($index, $params['option_amount']) &&
105 (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) &&
106 !CRM_Utils_System::isNull($params['option_amount'][$index])
107 ) {
108 $options = [
109 'price_field_id' => $priceField->id,
110 'label' => trim($params['option_label'][$index]),
111 'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64),
112 'amount' => trim($params['option_amount'][$index]),
113 'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL),
114 'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL),
115 'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL),
116 'membership_type_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_type_id', $params), NULL),
117 'weight' => $params['option_weight'][$index],
118 'is_active' => 1,
119 'is_default' => !empty($defaultArray[$params['option_weight'][$index]]) ? $defaultArray[$params['option_weight'][$index]] : 0,
120 'membership_num_terms' => NULL,
121 'non_deductible_amount' => $params['non_deductible_amount'] ?? NULL,
122 'visibility_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_visibility_id', $params), self::getVisibilityOptionID('public')),
123 ];
124
125 if ($options['membership_type_id']) {
126 $options['membership_num_terms'] = CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_num_terms', $params), 1);
127 $options['is_default'] = !empty($defaultArray[$params['membership_type_id'][$index]]) ? $defaultArray[$params['membership_type_id'][$index]] : 0;
128 }
129
130 if (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_financial_type_id', $params))) {
131 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
132 }
133 elseif (!empty($params['financial_type_id'])) {
134 $options['financial_type_id'] = $params['financial_type_id'];
135 }
136 if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
137 if ($opId = CRM_Utils_Array::value($index, $opIds)) {
138 $options['id'] = $opId;
139 }
140 else {
141 $options['id'] = NULL;
142 }
143 }
144 try {
145 CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
146 }
147 catch (Exception $e) {
148 $transaction->rollback();
149 throw new CRM_Core_Exception($e->getMessage());
150 }
151 }
152 elseif (!empty($optionsIds) && !empty($optionsIds['id'])) {
153 $optionsLoad = civicrm_api3('price_field_value', 'get', ['id' => $optionsIds['id']]);
154 $options = $optionsLoad['values'][$optionsIds['id']];
155 $options['is_active'] = CRM_Utils_Array::value('is_active', $params, 1);
156 try {
157 CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
158 }
159 catch (Exception $e) {
160 $transaction->rollback();
161 throw new CRM_Core_Exception($e->getMessage());
162 }
163 }
164 }
165
166 $transaction->commit();
167 return $priceField;
168 }
169
170 /**
171 * Fetch object based on array of properties.
172 *
173 * @param array $params
174 * (reference ) an assoc array of name/value pairs.
175 * @param array $defaults
176 * (reference ) an assoc array to hold the flattened values.
177 *
178 * @return CRM_Price_DAO_PriceField
179 */
180 public static function retrieve(&$params, &$defaults) {
181 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
182 }
183
184 /**
185 * Update the is_active flag in the db.
186 *
187 * @param int $id
188 * Id of the database record.
189 * @param bool $is_active
190 * Value we want to set the is_active field.
191 *
192 * @return bool
193 * true if we found and updated the object, else false
194 */
195 public static function setIsActive($id, $is_active) {
196 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
197 }
198
199 /**
200 * Freeze form if the event is full.
201 *
202 * @param $element
203 * @param $fieldOptions
204 *
205 * @return null
206 */
207 public static function freezeIfEnabled(&$element, $fieldOptions) {
208 if (!empty($fieldOptions['is_full'])) {
209 $element->freeze();
210 }
211 return NULL;
212 }
213
214 /**
215 * Get the field title.
216 *
217 * @param int $id
218 * Id of field.
219 *
220 * @return string
221 * name
222 *
223 */
224 public static function getTitle($id) {
225 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
226 }
227
228 /**
229 * This function for building custom fields.
230 *
231 * @param CRM_Core_Form $qf
232 * Form object (reference).
233 * @param string $elementName
234 * Name of the custom field.
235 * @param int $fieldId
236 * @param bool $inactiveNeeded
237 * @param bool $useRequired
238 * True if required else false.
239 * @param string $label
240 * Label for custom field.
241 *
242 * @param null $fieldOptions
243 * @param array $freezeOptions
244 *
245 * @return null
246 */
247 public static function addQuickFormElement(
248 &$qf,
249 $elementName,
250 $fieldId,
251 $inactiveNeeded,
252 $useRequired = TRUE,
253 $label = NULL,
254 $fieldOptions = NULL,
255 $freezeOptions = []
256 ) {
257
258 $field = new CRM_Price_DAO_PriceField();
259 $field->id = $fieldId;
260 if (!$field->find(TRUE)) {
261 /* FIXME: failure! */
262 return NULL;
263 }
264
265 $is_pay_later = 0;
266 if (isset($qf->_mode) && empty($qf->_mode)) {
267 $is_pay_later = 1;
268 }
269 elseif (isset($qf->_values)) {
270 $is_pay_later = $qf->_values['is_pay_later'] ?? NULL;
271 }
272
273 $otherAmount = $qf->get('values');
274 $config = CRM_Core_Config::singleton();
275 $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', $config->defaultCurrency, 'symbol', 'name');
276 $qf->assign('currencySymbol', $currencySymbol);
277 // get currency name for price field and option attributes
278 $currencyName = $config->defaultCurrency;
279
280 if (!isset($label)) {
281 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
282 }
283
284 if ($field->name == 'contribution_amount') {
285 $qf->_contributionAmount = 1;
286 }
287
288 if (isset($qf->_online) && $qf->_online) {
289 $useRequired = FALSE;
290 }
291
292 $customOption = $fieldOptions;
293 if (!is_array($customOption)) {
294 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
295 }
296
297 //use value field.
298 $valueFieldName = 'amount';
299 $separator = '|';
300 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
301 $taxTerm = Civi::settings()->get('tax_term');
302 $displayOpt = $invoiceSettings['tax_display_settings'] ?? NULL;
303 $invoicing = $invoiceSettings['invoicing'] ?? NULL;
304 switch ($field->html_type) {
305 case 'Text':
306 $optionKey = key($customOption);
307 $count = CRM_Utils_Array::value('count', $customOption[$optionKey], '');
308 $max_value = CRM_Utils_Array::value('max_value', $customOption[$optionKey], '');
309 $taxAmount = $customOption[$optionKey]['tax_amount'] ?? NULL;
310 if (isset($taxAmount) && $displayOpt && $invoicing) {
311 $qf->assign('displayOpt', $displayOpt);
312 $qf->assign('taxTerm', $taxTerm);
313 $qf->assign('invoicing', $invoicing);
314 }
315 $priceVal = implode($separator, [
316 $customOption[$optionKey][$valueFieldName] + $taxAmount,
317 $count,
318 $max_value,
319 ]);
320
321 $extra = [];
322 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
323 $useRequired = 0;
324 }
325 elseif (!empty($fieldOptions[$optionKey]['label'])) {
326 //check for label.
327 $label = $fieldOptions[$optionKey]['label'];
328 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount) && strtolower($fieldOptions[$optionKey]['name']) == 'other_amount') {
329 $label .= ' ' . $currencySymbol;
330 $qf->assign('priceset', $elementName);
331 $extra = [
332 'onclick' => 'useAmountOther();',
333 'autocomplete' => 'off',
334 ];
335 }
336 }
337
338 $element = &$qf->add('text', $elementName, $label,
339 array_merge($extra,
340 [
341 'price' => json_encode([$optionKey, $priceVal]),
342 'size' => '4',
343 ]
344 ),
345 $useRequired && $field->is_required
346 );
347 if ($is_pay_later) {
348 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
349 }
350
351 // CRM-6902 - Add "max" option for a price set field
352 if (in_array($optionKey, $freezeOptions)) {
353 self::freezeIfEnabled($element, $fieldOptions[$optionKey]);
354 // CRM-14696 - Improve display for sold out price set options
355 $element->setLabel($label . '&nbsp;<span class="sold-out-option">' . ts('Sold out') . '</span>');
356 }
357
358 //CRM-10117
359 if (!empty($qf->_quickConfig)) {
360 $message = ts('Please enter a valid amount.');
361 $type = 'money';
362 }
363 else {
364 $message = ts('%1 must be a number (with or without decimal point).', [1 => $label]);
365 $type = 'numeric';
366 }
367 // integers will have numeric rule applied to them.
368 $qf->addRule($elementName, $message, $type);
369 break;
370
371 case 'Radio':
372 $choice = [];
373
374 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
375 $qf->assign('contriPriceset', $elementName);
376 }
377
378 foreach ($customOption as $opId => $opt) {
379 $taxAmount = $opt['tax_amount'] ?? NULL;
380 if ($field->is_display_amounts) {
381 $opt['label'] = !empty($opt['label']) ? $opt['label'] . '<span class="crm-price-amount-label-separator">&nbsp;-&nbsp;</span>' : '';
382 $preHelpText = $postHelpText = '';
383 if (!empty($opt['help_pre'])) {
384 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span><span class="crm-price-amount-help-pre-separator">:&nbsp;</span>';
385 }
386 if (!empty($opt['help_post'])) {
387 $postHelpText = '<span class="crm-price-amount-help-post-separator">:&nbsp;</span><span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
388 }
389 if (isset($taxAmount) && $invoicing) {
390 if ($displayOpt == 'Do_not_show') {
391 $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>';
392 }
393 elseif ($displayOpt == 'Inclusive') {
394 $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>';
395 $opt['label'] .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
396 }
397 else {
398 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span>';
399 $opt['label'] .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
400 }
401 }
402 else {
403 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span>';
404 }
405 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
406 }
407 $count = CRM_Utils_Array::value('count', $opt, '');
408 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
409 $priceVal = implode($separator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
410 if (isset($opt['visibility_id'])) {
411 $visibility_id = $opt['visibility_id'];
412 }
413 else {
414 $visibility_id = self::getVisibilityOptionID('public');
415 }
416 $extra = [
417 'price' => json_encode([$elementName, $priceVal]),
418 'data-amount' => $opt[$valueFieldName],
419 'data-currency' => $currencyName,
420 'data-price-field-values' => json_encode($customOption),
421 'visibility' => $visibility_id,
422 ];
423 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
424 $extra += ['onclick' => 'clearAmountOther();'];
425 }
426 if ($field->name == 'membership_amount') {
427 $extra += [
428 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
429 'membership-type' => $opt['membership_type_id'],
430 ];
431 $qf->assign('membershipFieldID', $field->id);
432 }
433
434 $choice[$opt['id']] = $opt['label'];
435 $choiceAttrs[$opt['id']] = $extra;
436 if ($is_pay_later) {
437 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
438 }
439 }
440 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
441 $choice['-1'] = ts('No thank you');
442 $choiceAttrs['-1'] = [
443 'price' => json_encode([$elementName, '0|0']),
444 'data-currency' => $currencyName,
445 'onclick' => 'clearAmountOther();',
446 ];
447 }
448
449 if (!$field->is_required) {
450 // add "none" option
451 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
452 $none = ts('Other Amount');
453 }
454 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
455 $none = ts('No thank you');
456 }
457 else {
458 $none = ts('- none -');
459 }
460
461 $choice['0'] = $none;
462 $choiceAttrs['0'] = ['price' => json_encode([$elementName, '0'])];
463 }
464
465 $element = &$qf->addRadio($elementName, $label, $choice, [], NULL, FALSE, $choiceAttrs);
466 foreach ($element->getElements() as $radioElement) {
467 // CRM-6902 - Add "max" option for a price set field
468 if (in_array($radioElement->getValue(), $freezeOptions)) {
469 self::freezeIfEnabled($radioElement, $customOption[$radioElement->getValue()]);
470 // CRM-14696 - Improve display for sold out price set options
471 $radioElement->setText('<span class="sold-out-option">' . $radioElement->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
472 }
473 }
474
475 // make contribution field required for quick config when membership block is enabled
476 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
477 && !empty($qf->_membershipBlock) && !$field->is_required
478 ) {
479 $useRequired = $field->is_required = TRUE;
480 }
481
482 if ($useRequired && $field->is_required) {
483 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
484 }
485 break;
486
487 case 'Select':
488 $selectOption = $allowedOptions = $priceVal = [];
489
490 foreach ($customOption as $opt) {
491 $taxAmount = $opt['tax_amount'] ?? NULL;
492 $count = CRM_Utils_Array::value('count', $opt, '');
493 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
494
495 if ($field->is_display_amounts) {
496 $opt['label'] .= '&nbsp;-&nbsp;';
497 if (isset($taxAmount) && $invoicing) {
498 $opt['label'] = $opt['label'] . self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
499 }
500 else {
501 $opt['label'] = $opt['label'] . CRM_Utils_Money::format($opt[$valueFieldName]);
502 }
503 }
504
505 $priceVal[$opt['id']] = implode($separator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
506
507 if (!in_array($opt['id'], $freezeOptions)) {
508 $allowedOptions[] = $opt['id'];
509 }
510 // CRM-14696 - Improve display for sold out price set options
511 else {
512 $opt['id'] = 'crm_disabled_opt-' . $opt['id'];
513 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
514 }
515
516 $selectOption[$opt['id']] = $opt['label'];
517
518 if ($is_pay_later) {
519 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
520 }
521 }
522 if (isset($opt['visibility_id'])) {
523 $visibility_id = $opt['visibility_id'];
524 }
525 else {
526 $visibility_id = self::getVisibilityOptionID('public');
527 }
528 $element = &$qf->add('select', $elementName, $label, $selectOption, $useRequired && $field->is_required, [
529 'placeholder' => ts('- select %1 -', [1 => $label]),
530 'price' => json_encode($priceVal),
531 'class' => 'crm-select2',
532 'data-price-field-values' => json_encode($customOption),
533 ]);
534
535 // CRM-6902 - Add "max" option for a price set field
536 $button = substr($qf->controller->getButtonName(), -4);
537 if (!empty($freezeOptions) && $button != 'skip') {
538 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
539 }
540 break;
541
542 case 'CheckBox':
543
544 $check = [];
545 foreach ($customOption as $opId => $opt) {
546 $taxAmount = $opt['tax_amount'] ?? NULL;
547 $count = CRM_Utils_Array::value('count', $opt, '');
548 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
549
550 if ($field->is_display_amounts) {
551 $preHelpText = $postHelpText = '';
552 if (isset($opt['help_pre'])) {
553 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span>: ';
554 }
555 if (isset($opt['help_post'])) {
556 $postHelpText = ': <span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
557 }
558 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>&nbsp;-&nbsp;';
559 if (isset($taxAmount) && $invoicing) {
560 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
561 }
562 else {
563 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
564 }
565 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
566 }
567 $priceVal = implode($separator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
568 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
569 [
570 'price' => json_encode([$opt['id'], $priceVal]),
571 'data-amount' => $opt[$valueFieldName],
572 'data-currency' => $currencyName,
573 'visibility' => $opt['visibility_id'],
574 ]
575 );
576 if ($is_pay_later) {
577 $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], ['size' => '4']);
578 $qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
579 }
580 // CRM-6902 - Add "max" option for a price set field
581 if (in_array($opId, $freezeOptions)) {
582 self::freezeIfEnabled($check[$opId], $customOption[$opId]);
583 // CRM-14696 - Improve display for sold out price set options
584 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
585 }
586 }
587 $element = &$qf->addGroup($check, $elementName, $label);
588 if ($useRequired && $field->is_required) {
589 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
590 }
591 break;
592 }
593 if (isset($qf->_online) && $qf->_online) {
594 $element->freeze();
595 }
596 }
597
598 /**
599 * Retrieve a list of options for the specified field.
600 *
601 * @param int $fieldId
602 * Price field ID.
603 * @param bool $inactiveNeeded
604 * Include inactive options.
605 * @param bool $reset
606 * Discard stored values.
607 * @param bool $isDefaultContributionPriceSet
608 * Discard tax amount calculation for price set = default_contribution_amount.
609 *
610 * @return array
611 * array of options
612 */
613 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
614 if ($reset || !isset(Civi::$statics[__CLASS__]['priceOptions'])) {
615 Civi::$statics[__CLASS__]['priceOptions'] = [];
616 // This would happen if the function was only called to clear the cache.
617 if (empty($fieldId)) {
618 return [];
619 }
620 }
621
622 if (empty(Civi::$statics[__CLASS__]['priceOptions'][$fieldId])) {
623 $values = $options = [];
624 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
625 $options[$fieldId] = $values;
626 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
627
628 // ToDo - Code for Hook Invoke
629
630 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
631 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates) && !$isDefaultContributionPriceSet) {
632 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
633 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
634 $options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
635 }
636 }
637 Civi::$statics[__CLASS__]['priceOptions'][$fieldId] = $options[$fieldId];
638 }
639
640 return Civi::$statics[__CLASS__]['priceOptions'][$fieldId];
641 }
642
643 /**
644 * @param $optionLabel
645 * @param int $fid
646 *
647 * @return mixed
648 */
649 public static function getOptionId($optionLabel, $fid) {
650 if (!$optionLabel || !$fid) {
651 return;
652 }
653
654 $optionGroupName = "civicrm_price_field.amount.{$fid}";
655
656 $query = "
657 SELECT
658 option_value.id as id
659 FROM
660 civicrm_option_value option_value,
661 civicrm_option_group option_group
662 WHERE
663 option_group.name = %1
664 AND option_group.id = option_value.option_group_id
665 AND option_value.label = %2";
666
667 $dao = CRM_Core_DAO::executeQuery($query, [
668 1 => [$optionGroupName, 'String'],
669 2 => [$optionLabel, 'String'],
670 ]);
671
672 while ($dao->fetch()) {
673 return $dao->id;
674 }
675 }
676
677 /**
678 * Delete the price set field.
679 *
680 * @param int $id
681 * Field Id.
682 *
683 * @return bool
684 *
685 */
686 public static function deleteField($id) {
687 $field = new CRM_Price_DAO_PriceField();
688 $field->id = $id;
689
690 if ($field->find(TRUE)) {
691 // delete the options for this field
692 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
693
694 // reorder the weight before delete
695 $fieldValues = ['price_set_id' => $field->price_set_id];
696
697 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
698
699 // now delete the field
700 return $field->delete();
701 }
702
703 return NULL;
704 }
705
706 /**
707 * @return array
708 */
709 public static function &htmlTypes() {
710 static $htmlTypes = NULL;
711 if (!$htmlTypes) {
712 $htmlTypes = [
713 'Text' => ts('Text / Numeric Quantity'),
714 'Select' => ts('Select'),
715 'Radio' => ts('Radio'),
716 'CheckBox' => ts('CheckBox'),
717 ];
718 }
719 return $htmlTypes;
720 }
721
722 /**
723 * Validate the priceset.
724 *
725 * @param int $priceSetId
726 * , array $fields.
727 *
728 * retrun the error string
729 *
730 * @param $fields
731 * @param $error
732 * @param bool $allowNoneSelection
733 *
734 */
735 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
736 // check for at least one positive
737 // amount price field should be selected.
738 $priceField = new CRM_Price_DAO_PriceField();
739 $priceField->price_set_id = $priceSetId;
740 $priceField->find();
741
742 $priceFields = [];
743
744 if ($allowNoneSelection) {
745 $noneSelectedPriceFields = [];
746 }
747
748 while ($priceField->fetch()) {
749 $key = "price_{$priceField->id}";
750
751 if ($allowNoneSelection) {
752 if (array_key_exists($key, $fields)) {
753 if ($fields[$key] == 0 && !$priceField->is_required) {
754 $noneSelectedPriceFields[] = $priceField->id;
755 }
756 }
757 }
758
759 if (!empty($fields[$key])) {
760 $priceFields[$priceField->id] = $fields[$key];
761 }
762 }
763
764 if (!empty($priceFields)) {
765 // we should has to have positive amount.
766 $sql = "
767 SELECT id, html_type
768 FROM civicrm_price_field
769 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
770 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
771 $htmlTypes = [];
772 while ($fieldDAO->fetch()) {
773 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
774 }
775
776 $selectedAmounts = [];
777
778 foreach ($htmlTypes as $fieldId => $type) {
779 $options = [];
780 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
781
782 if (empty($options)) {
783 continue;
784 }
785
786 if ($type == 'Text') {
787 foreach ($options as $opId => $option) {
788 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
789 break;
790 }
791 }
792 elseif (is_array($fields["price_{$fieldId}"])) {
793 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
794 $selectedAmounts[$opId] = $options[$opId]['amount'];
795 }
796 }
797 elseif (array_key_exists($fields["price_{$fieldId}"], $options)) {
798 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
799 }
800 }
801
802 list($componentName) = explode(':', $fields['_qf_default']);
803 // now we have all selected amount in hand.
804 $totalAmount = array_sum($selectedAmounts);
805 // The form offers a field to enter the amount paid. This may differ from the amount that is due to complete the purchase
806 $totalPaymentAmountEnteredOnForm = CRM_Utils_Array::value('total_amount', $fields);
807 if ($totalAmount < 0) {
808 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', [1 => $componentName]);
809 }
810 elseif ($totalAmount > 0 &&
811 // if total amount is equal to all selected amount in hand
812 $totalPaymentAmountEnteredOnForm >= $totalAmount &&
813 (CRM_Utils_Array::value('contribution_status_id', $fields) == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Partially paid'))
814 ) {
815 $error['total_amount'] = ts('You have specified the status Partially Paid but have entered an amount that equals or exceeds the amount due. Please adjust the status of the payment or the amount');
816 }
817 }
818 else {
819 if ($allowNoneSelection) {
820 if (empty($noneSelectedPriceFields)) {
821 $error['_qf_default'] = ts('Please select at least one option from price set.');
822 }
823 }
824 else {
825 $error['_qf_default'] = ts('Please select at least one option from price set.');
826 }
827 }
828 }
829
830 /**
831 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
832 *
833 * @param array $opt
834 * @param string $valueFieldName
835 * Amount.
836 * @param string $displayOpt
837 * Tax display setting option.
838 *
839 * @param string $taxTerm
840 *
841 * @return string
842 * Tax label for custom field.
843 */
844 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
845 if ($displayOpt == 'Do_not_show') {
846 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
847 }
848 elseif ($displayOpt == 'Inclusive') {
849 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
850 $label .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
851 }
852 else {
853 $label = CRM_Utils_Money::format($opt[$valueFieldName]);
854 $label .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
855 }
856
857 return $label;
858 }
859
860 /**
861 * Given the name of a visibility option, returns its ID.
862 *
863 * @param string $visibilityName
864 *
865 * @return int
866 */
867 public static function getVisibilityOptionID($visibilityName) {
868
869 if (!isset(self::$visibilityOptionsKeys)) {
870 self::$visibilityOptionsKeys = CRM_Core_PseudoConstant::get('CRM_Price_BAO_PriceField', 'visibility_id', [
871 'labelColumn' => 'name',
872 'flip' => TRUE,
873 ]);
874 }
875
876 if (isset(self::$visibilityOptionsKeys[$visibilityName])) {
877 return self::$visibilityOptionsKeys[$visibilityName];
878 }
879
880 return 0;
881 }
882
883 }