Merge pull request #22315 from braders/more-hardcoded-strings-2
[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 $qf->assign('currency', $config->defaultCurrency);
278 // get currency name for price field and option attributes
279 $currencyName = $config->defaultCurrency;
280
281 if (!isset($label)) {
282 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
283 }
284
285 if ($field->name === 'contribution_amount') {
286 $qf->_contributionAmount = 1;
287 }
288
289 if (isset($qf->_online) && $qf->_online) {
290 $useRequired = FALSE;
291 }
292
293 $customOption = $fieldOptions;
294 if (!is_array($customOption)) {
295 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
296 }
297
298 //use value field.
299 $valueFieldName = 'amount';
300 $separator = '|';
301 $taxTerm = Civi::settings()->get('tax_term');
302 $displayOpt = Civi::settings()->get('tax_display_settings');
303 $invoicing = Civi::settings()->get('invoicing');
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 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
391 }
392 else {
393 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span>';
394 }
395 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
396 }
397 $count = CRM_Utils_Array::value('count', $opt, '');
398 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
399 $priceVal = implode($separator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
400 if (isset($opt['visibility_id'])) {
401 $visibility_id = $opt['visibility_id'];
402 }
403 else {
404 $visibility_id = self::getVisibilityOptionID('public');
405 }
406 $extra = [
407 'price' => json_encode([$elementName, $priceVal]),
408 'data-amount' => $opt[$valueFieldName],
409 'data-currency' => $currencyName,
410 'data-price-field-values' => json_encode($customOption),
411 'visibility' => $visibility_id,
412 ];
413 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
414 $extra += ['onclick' => 'clearAmountOther();'];
415 }
416 if ($field->name == 'membership_amount') {
417 $extra += [
418 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
419 'membership-type' => $opt['membership_type_id'],
420 ];
421 $qf->assign('membershipFieldID', $field->id);
422 }
423
424 $choice[$opt['id']] = $opt['label'];
425 $choiceAttrs[$opt['id']] = $extra;
426 if ($is_pay_later) {
427 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
428 }
429 }
430 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
431 $choice['-1'] = ts('No thank you');
432 $choiceAttrs['-1'] = [
433 'price' => json_encode([$elementName, '0|0']),
434 'data-currency' => $currencyName,
435 'onclick' => 'clearAmountOther();',
436 ];
437 }
438
439 if (!$field->is_required) {
440 // add "none" option
441 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
442 $none = ts('Other Amount');
443 }
444 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
445 $none = ts('No thank you');
446 }
447 else {
448 $none = ts('- none -');
449 }
450
451 $choice['0'] = $none;
452 $choiceAttrs['0'] = ['price' => json_encode([$elementName, '0'])];
453 }
454
455 $element = &$qf->addRadio($elementName, $label, $choice, [], NULL, FALSE, $choiceAttrs);
456 foreach ($element->getElements() as $radioElement) {
457 // CRM-6902 - Add "max" option for a price set field
458 if (in_array($radioElement->getValue(), $freezeOptions)) {
459 self::freezeIfEnabled($radioElement, $customOption[$radioElement->getValue()]);
460 // CRM-14696 - Improve display for sold out price set options
461 $radioElement->setText('<span class="sold-out-option">' . $radioElement->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
462 }
463 }
464
465 // make contribution field required for quick config when membership block is enabled
466 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
467 && !empty($qf->_membershipBlock) && !$field->is_required
468 ) {
469 $useRequired = $field->is_required = TRUE;
470 }
471
472 if ($useRequired && $field->is_required) {
473 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
474 }
475 break;
476
477 case 'Select':
478 $selectOption = $allowedOptions = $priceVal = [];
479
480 foreach ($customOption as $opt) {
481 $taxAmount = $opt['tax_amount'] ?? NULL;
482 $count = CRM_Utils_Array::value('count', $opt, '');
483 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
484
485 if ($field->is_display_amounts) {
486 $opt['label'] .= '&nbsp;-&nbsp;';
487 if (isset($taxAmount) && $invoicing) {
488 $opt['label'] = $opt['label'] . self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
489 }
490 else {
491 $opt['label'] = $opt['label'] . CRM_Utils_Money::format($opt[$valueFieldName]);
492 }
493 }
494
495 $priceVal[$opt['id']] = implode($separator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
496
497 if (!in_array($opt['id'], $freezeOptions)) {
498 $allowedOptions[] = $opt['id'];
499 }
500 // CRM-14696 - Improve display for sold out price set options
501 else {
502 $opt['id'] = 'crm_disabled_opt-' . $opt['id'];
503 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
504 }
505
506 $selectOption[$opt['id']] = $opt['label'];
507
508 if ($is_pay_later) {
509 $qf->add('text', 'txt-' . $elementName, $label, ['size' => '4']);
510 }
511 }
512 if (isset($opt['visibility_id'])) {
513 $visibility_id = $opt['visibility_id'];
514 }
515 else {
516 $visibility_id = self::getVisibilityOptionID('public');
517 }
518 $element = &$qf->add('select', $elementName, $label, $selectOption, $useRequired && $field->is_required, [
519 'placeholder' => ts('- select %1 -', [1 => $label]),
520 'price' => json_encode($priceVal),
521 'class' => 'crm-select2',
522 'data-price-field-values' => json_encode($customOption),
523 ]);
524
525 // CRM-6902 - Add "max" option for a price set field
526 $button = substr($qf->controller->getButtonName(), -4);
527 if (!empty($freezeOptions) && $button != 'skip') {
528 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
529 }
530 break;
531
532 case 'CheckBox':
533
534 $check = [];
535 foreach ($customOption as $opId => $opt) {
536 $taxAmount = $opt['tax_amount'] ?? NULL;
537 $count = CRM_Utils_Array::value('count', $opt, '');
538 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
539
540 if ($field->is_display_amounts) {
541 $preHelpText = $postHelpText = '';
542 if (isset($opt['help_pre'])) {
543 $preHelpText = '<span class="crm-price-amount-help-pre description">' . $opt['help_pre'] . '</span>: ';
544 }
545 if (isset($opt['help_post'])) {
546 $postHelpText = ': <span class="crm-price-amount-help-post description">' . $opt['help_post'] . '</span>';
547 }
548 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>&nbsp;-&nbsp;';
549 if (isset($taxAmount) && $invoicing) {
550 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
551 }
552 else {
553 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
554 }
555 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
556 }
557 $priceVal = implode($separator, [$opt[$valueFieldName] + $taxAmount, $count, $max_value]);
558 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
559 [
560 'price' => json_encode([$opt['id'], $priceVal]),
561 'data-amount' => $opt[$valueFieldName],
562 'data-currency' => $currencyName,
563 'visibility' => $opt['visibility_id'],
564 ]
565 );
566 if ($is_pay_later) {
567 $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], ['size' => '4']);
568 $qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
569 }
570 // CRM-6902 - Add "max" option for a price set field
571 if (in_array($opId, $freezeOptions)) {
572 self::freezeIfEnabled($check[$opId], $customOption[$opId]);
573 // CRM-14696 - Improve display for sold out price set options
574 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
575 }
576 }
577 $element = &$qf->addGroup($check, $elementName, $label);
578 if ($useRequired && $field->is_required) {
579 $qf->addRule($elementName, ts('%1 is a required field.', [1 => $label]), 'required');
580 }
581 break;
582 }
583 if (isset($qf->_online) && $qf->_online) {
584 $element->freeze();
585 }
586 }
587
588 /**
589 * Retrieve a list of options for the specified field.
590 *
591 * @param int $fieldId
592 * Price field ID.
593 * @param bool $inactiveNeeded
594 * Include inactive options.
595 * @param bool $reset
596 * Discard stored values.
597 * @param bool $isDefaultContributionPriceSet
598 * Discard tax amount calculation for price set = default_contribution_amount.
599 *
600 * @return array
601 * array of options
602 */
603 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
604 if ($reset || !isset(Civi::$statics[__CLASS__]['priceOptions'])) {
605 Civi::$statics[__CLASS__]['priceOptions'] = [];
606 // This would happen if the function was only called to clear the cache.
607 if (empty($fieldId)) {
608 return [];
609 }
610 }
611
612 if (empty(Civi::$statics[__CLASS__]['priceOptions'][$fieldId])) {
613 $values = $options = [];
614 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
615 $options[$fieldId] = $values;
616 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
617
618 // ToDo - Code for Hook Invoke
619
620 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
621 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates) && !$isDefaultContributionPriceSet) {
622 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
623 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
624 $options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
625 }
626 }
627 Civi::$statics[__CLASS__]['priceOptions'][$fieldId] = $options[$fieldId];
628 }
629
630 return Civi::$statics[__CLASS__]['priceOptions'][$fieldId];
631 }
632
633 /**
634 * @param $optionLabel
635 * @param int $fid
636 *
637 * @return mixed
638 */
639 public static function getOptionId($optionLabel, $fid) {
640 if (!$optionLabel || !$fid) {
641 return;
642 }
643
644 $optionGroupName = "civicrm_price_field.amount.{$fid}";
645
646 $query = "
647 SELECT
648 option_value.id as id
649 FROM
650 civicrm_option_value option_value,
651 civicrm_option_group option_group
652 WHERE
653 option_group.name = %1
654 AND option_group.id = option_value.option_group_id
655 AND option_value.label = %2";
656
657 $dao = CRM_Core_DAO::executeQuery($query, [
658 1 => [$optionGroupName, 'String'],
659 2 => [$optionLabel, 'String'],
660 ]);
661
662 while ($dao->fetch()) {
663 return $dao->id;
664 }
665 }
666
667 /**
668 * Delete the price set field.
669 *
670 * @param int $id
671 * Field Id.
672 *
673 * @return bool
674 *
675 */
676 public static function deleteField($id) {
677 $field = new CRM_Price_DAO_PriceField();
678 $field->id = $id;
679
680 if ($field->find(TRUE)) {
681 // delete the options for this field
682 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
683
684 // reorder the weight before delete
685 $fieldValues = ['price_set_id' => $field->price_set_id];
686
687 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
688
689 // now delete the field
690 return $field->delete();
691 }
692
693 return NULL;
694 }
695
696 /**
697 * @return array
698 */
699 public static function &htmlTypes() {
700 static $htmlTypes = NULL;
701 if (!$htmlTypes) {
702 $htmlTypes = [
703 'Text' => ts('Text / Numeric Quantity'),
704 'Select' => ts('Select'),
705 'Radio' => ts('Radio'),
706 'CheckBox' => ts('CheckBox'),
707 ];
708 }
709 return $htmlTypes;
710 }
711
712 /**
713 * Validate the priceset.
714 *
715 * @param int $priceSetId
716 * , array $fields.
717 *
718 * retrun the error string
719 *
720 * @param $fields
721 * @param $error
722 * @param bool $allowNoneSelection
723 *
724 */
725 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
726 // check for at least one positive
727 // amount price field should be selected.
728 $priceField = new CRM_Price_DAO_PriceField();
729 $priceField->price_set_id = $priceSetId;
730 $priceField->find();
731
732 $priceFields = [];
733
734 if ($allowNoneSelection) {
735 $noneSelectedPriceFields = [];
736 }
737
738 while ($priceField->fetch()) {
739 $key = "price_{$priceField->id}";
740
741 if ($allowNoneSelection) {
742 if (array_key_exists($key, $fields)) {
743 if ($fields[$key] == 0 && !$priceField->is_required) {
744 $noneSelectedPriceFields[] = $priceField->id;
745 }
746 }
747 }
748
749 if (!empty($fields[$key])) {
750 $priceFields[$priceField->id] = $fields[$key];
751 }
752 }
753
754 if (!empty($priceFields)) {
755 // we should has to have positive amount.
756 $sql = "
757 SELECT id, html_type
758 FROM civicrm_price_field
759 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
760 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
761 $htmlTypes = [];
762 while ($fieldDAO->fetch()) {
763 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
764 }
765
766 $selectedAmounts = [];
767
768 foreach ($htmlTypes as $fieldId => $type) {
769 $options = [];
770 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
771
772 if (empty($options)) {
773 continue;
774 }
775
776 if ($type == 'Text') {
777 foreach ($options as $opId => $option) {
778 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
779 break;
780 }
781 }
782 elseif (is_array($fields["price_{$fieldId}"])) {
783 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
784 $selectedAmounts[$opId] = $options[$opId]['amount'];
785 }
786 }
787 elseif (array_key_exists($fields["price_{$fieldId}"], $options)) {
788 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
789 }
790 }
791
792 list($componentName) = explode(':', $fields['_qf_default']);
793 // now we have all selected amount in hand.
794 $totalAmount = array_sum($selectedAmounts);
795 // The form offers a field to enter the amount paid. This may differ from the amount that is due to complete the purchase
796 $totalPaymentAmountEnteredOnForm = CRM_Utils_Array::value('total_amount', $fields);
797 if ($totalAmount < 0) {
798 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', [1 => $componentName]);
799 }
800 elseif ($totalAmount > 0 &&
801 // if total amount is equal to all selected amount in hand
802 $totalPaymentAmountEnteredOnForm >= $totalAmount &&
803 (CRM_Utils_Array::value('contribution_status_id', $fields) == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Partially paid'))
804 ) {
805 $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');
806 }
807 }
808 else {
809 if ($allowNoneSelection) {
810 if (empty($noneSelectedPriceFields)) {
811 $error['_qf_default'] = ts('Please select at least one option from price set.');
812 }
813 }
814 else {
815 $error['_qf_default'] = ts('Please select at least one option from price set.');
816 }
817 }
818 }
819
820 /**
821 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
822 *
823 * @param array $opt
824 * @param string $valueFieldName
825 * Amount.
826 * @param string $displayOpt
827 * Tax display setting option.
828 *
829 * @param string $taxTerm
830 *
831 * @return string
832 * Tax label for custom field.
833 */
834 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
835 if ($displayOpt == 'Do_not_show') {
836 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
837 }
838 elseif ($displayOpt == 'Inclusive') {
839 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
840 $label .= '<span class="crm-price-amount-tax"> ' . ts('(includes %1 of %2)', [1 => $taxTerm, 2 => CRM_Utils_Money::format($opt['tax_amount'])]) . '</span>';
841 }
842 else {
843 $label = CRM_Utils_Money::format($opt[$valueFieldName]);
844 $label .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
845 }
846
847 return $label;
848 }
849
850 /**
851 * Given the name of a visibility option, returns its ID.
852 *
853 * @param string $visibilityName
854 *
855 * @return int
856 */
857 public static function getVisibilityOptionID($visibilityName) {
858
859 if (!isset(self::$visibilityOptionsKeys)) {
860 self::$visibilityOptionsKeys = CRM_Core_PseudoConstant::get('CRM_Price_BAO_PriceField', 'visibility_id', [
861 'labelColumn' => 'name',
862 'flip' => TRUE,
863 ]);
864 }
865
866 if (isset(self::$visibilityOptionsKeys[$visibilityName])) {
867 return self::$visibilityOptionsKeys[$visibilityName];
868 }
869
870 return 0;
871 }
872
873 }