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