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