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