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