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