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