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