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