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