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