Merge pull request #4752 from davecivicrm/CRM-15180
[civicrm-core.git] / CRM / Price / BAO / PriceField.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
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
44 /**
100fef9d 45 * Takes an associative array and creates a price field object
6a488035
TO
46 *
47 * the function extract all the params it needs to initialize the create a
48 * price field object. the params array could contain additional unused name/value
49 * pairs
50 *
c490a46a 51 * @param array $params (reference) an assoc array of name/value pairs
6a488035 52 *
c490a46a 53 * @return CRM_Price_BAO_PriceField object
6a488035
TO
54 * @access public
55 * @static
56 */
e0c1764e 57 static function add(&$params) {
9da8dc8c 58 $priceFieldBAO = new CRM_Price_BAO_PriceField();
6a488035
TO
59
60 $priceFieldBAO->copyValues($params);
61
62 if ($id = CRM_Utils_Array::value('id', $params)) {
63 $priceFieldBAO->id = $id;
64 }
65
66 $priceFieldBAO->save();
67 return $priceFieldBAO;
68 }
69
70 /**
100fef9d 71 * Takes an associative array and creates a price field object
6a488035
TO
72 *
73 * This function is invoked from within the web form layer and also from the api layer
74 *
75 * @param array $params (reference) an assoc array of name/value pairs
76 *
c490a46a 77 * @return CRM_Price_DAO_PriceField object
6a488035
TO
78 * @access public
79 * @static
80 */
81 static function create(&$params) {
291ebece 82 if(empty($params['id']) && empty($params['name'])) {
b10b974d 83 $params['name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 242));
291ebece 84 }
6a488035
TO
85 $transaction = new CRM_Core_Transaction();
86
87 $priceField = self::add($params);
88
89 if (is_a($priceField, 'CRM_Core_Error')) {
90 $transaction->rollback();
91 return $priceField;
92 }
93
e0c1764e 94 $optionsIds = array();
6a488035
TO
95 $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
96
97 if ($priceField->html_type == 'Text') {
98 $maxIndex = 1;
99
9da8dc8c 100 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
6a488035
TO
101 $fieldValue->price_field_id = $priceField->id;
102
103 // update previous field values( if any )
104 if ($fieldValue->find(TRUE)) {
105 $optionsIds['id'] = $fieldValue->id;
106 }
107 }
108 $defaultArray = array();
a4537ddd
EM
109 //html type would be empty in update scenario not sure what would happen ...
110 if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
6a488035
TO
111 $tempArray = array_keys($params['default_checkbox_option']);
112 foreach ($tempArray as $v) {
113 if ($params['option_amount'][$v]) {
114 $defaultArray[$v] = 1;
115 }
116 }
117 }
118 else {
a7488080 119 if (!empty($params['default_option'])) {
6a488035
TO
120 $defaultArray[$params['default_option']] = 1;
121 }
122 }
123
124 for ($index = 1; $index <= $maxIndex; $index++) {
125 if (array_key_exists('option_amount', $params) &&
126 array_key_exists($index, $params['option_amount']) &&
8cc574cf 127 (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) &&
6a488035
TO
128 !CRM_Utils_System::isNull($params['option_amount'][$index])
129 ) {
130 $options = array(
131 'price_field_id' => $priceField->id,
132 'label' => trim($params['option_label'][$index]),
133 'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64),
134 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])),
135 'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL),
136 'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL),
137 'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL),
138 'membership_type_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_type_id', $params), NULL),
139 'weight' => $params['option_weight'][$index],
140 'is_active' => 1,
141 'is_default' => CRM_Utils_Array::value($params['option_weight'][$index], $defaultArray) ? $defaultArray[$params['option_weight'][$index]] : 0,
142 'membership_num_terms' => NULL,
143 );
144
145 if ($options['membership_type_id']) {
146 $options['membership_num_terms'] = CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_num_terms', $params), 1);
147 }
148
149 if (CRM_Utils_Array::value( $index, CRM_Utils_Array::value('option_financial_type_id', $params))) {
150 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
a7488080 151 } elseif (!empty($params['financial_type_id'])) {
6a488035
TO
152 $options['financial_type_id'] = $params['financial_type_id'];
153 }
154
155 if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
156 if ($opId = CRM_Utils_Array::value($index, $opIds)) {
157 $optionsIds['id'] = $opId;
158 } else {
159 $optionsIds['id'] = NULL;
160 }
161 }
9da8dc8c 162 CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
6a488035
TO
163 }
164 }
165
166 $transaction->commit();
167 return $priceField;
168 }
169
170 /**
c490a46a 171 * Fetch object based on array of properties
6a488035
TO
172 *
173 * @param array $params (reference ) an assoc array of name/value pairs
174 * @param array $defaults (reference ) an assoc array to hold the flattened values
175 *
c490a46a 176 * @return CRM_Price_DAO_PriceField object
6a488035
TO
177 * @access public
178 * @static
179 */
180 static function retrieve(&$params, &$defaults) {
9da8dc8c 181 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
6a488035
TO
182 }
183
184 /**
100fef9d 185 * Update the is_active flag in the db
6a488035
TO
186 *
187 * @param int $id Id of the database record
188 * @param boolean $is_active Value we want to set the is_active field
189 *
190 * @return Object DAO object on sucess, null otherwise
191 *
192 * @access public
193 * @static
194 */
195 static function setIsActive($id, $is_active) {
9da8dc8c 196 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
6a488035
TO
197 }
198
199 /**
200 * Get the field title.
201 *
202 * @param int $id id of field.
203 *
204 * @return string name
205 *
206 * @access public
207 * @static
208 *
209 */
210 public static function getTitle($id) {
9da8dc8c 211 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
6a488035
TO
212 }
213
214 /**
215 * This function for building custom fields
216 *
f9a5ad43 217 * @param CRM_Core_Form $qf form object (reference)
77b97be7 218 * @param string $elementName name of the custom field
100fef9d 219 * @param int $fieldId
6a488035 220 * @param boolean $inactiveNeeded
77b97be7
EM
221 * @param boolean $useRequired true if required else false
222 * @param string $label label for custom field
223 *
224 * @param null $fieldOptions
1537c309 225 * @param array $freezeOptions
6a488035 226 *
77b97be7
EM
227 * @return null
228 * @internal param bool $search true if used for search else false
6a488035
TO
229 * @access public
230 * @static
231 */
232 public static function addQuickFormElement(&$qf,
233 $elementName,
234 $fieldId,
235 $inactiveNeeded,
535a8e1e
CW
236 $useRequired = TRUE,
237 $label = NULL,
6a488035 238 $fieldOptions = NULL,
1537c309 239 $freezeOptions = array()
6a488035
TO
240 ) {
241
9da8dc8c 242 $field = new CRM_Price_DAO_PriceField();
6a488035
TO
243 $field->id = $fieldId;
244 if (!$field->find(TRUE)) {
245 /* FIXME: failure! */
246 return NULL;
247 }
366fe2a3 248
6a488035
TO
249 $is_pay_later = 0;
250 if (isset($qf->_mode) && empty($qf->_mode)) {
251 $is_pay_later = 1;
252 }
253 elseif (isset($qf->_values)) {
254 $is_pay_later = CRM_Utils_Array::value( 'is_pay_later', $qf->_values);
255 }
256
257 $otherAmount = $qf->get('values');
258 $config = CRM_Core_Config::singleton();
259 $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency',$config->defaultCurrency,'symbol','name');
260 $qf->assign('currencySymbol', $currencySymbol);
261 // get currency name for price field and option attributes
262 $currencyName = $config->defaultCurrency;
263
264 if (!isset($label)) {
15831617 265 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
6a488035
TO
266 }
267
268 if ($field->name == 'contribution_amount') {
269 $qf->_contributionAmount = 1;
270 }
271
272 if (isset($qf->_online) && $qf->_online) {
273 $useRequired = FALSE;
274 }
275
276 $customOption = $fieldOptions;
277 if (!is_array($customOption)) {
9da8dc8c 278 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
6a488035
TO
279 }
280
281 //use value field.
282 $valueFieldName = 'amount';
283 $seperator = '|';
e0f7075f 284 $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
5ebee375 285 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
286 $displayOpt = CRM_Utils_Array::value('tax_display_settings', $invoiceSettings);
fff0f449 287 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
6a488035
TO
288 switch ($field->html_type) {
289 case 'Text':
290 $optionKey = key($customOption);
535a8e1e 291 $count = CRM_Utils_Array::value('count', $customOption[$optionKey], '');
6a488035 292 $max_value = CRM_Utils_Array::value('max_value', $customOption[$optionKey], '');
9d1c9154 293 $taxAmount = CRM_Utils_Array::value('tax_amount', $customOption[$optionKey]);
3bd20e3f 294 if (isset($taxAmount) && $displayOpt && $invoicing) {
dc428161 295 $qf->assign('displayOpt', $displayOpt);
5ebee375 296 $qf->assign('taxTerm', $taxTerm);
fff0f449 297 $qf->assign('invoicing', $invoicing);
dc428161 298 }
299 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName] + $taxAmount, $count, $max_value));
6a488035
TO
300
301 $extra = array();
15831617 302 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
6a488035
TO
303 foreach($fieldOptions as &$fieldOption) {
304 if ($fieldOption['name'] == 'other_amount') {
305 $fieldOption['label'] = $fieldOption['label'] . ' ' . $currencySymbol;
306 }
307 }
308 $qf->assign('priceset', $elementName);
309 $extra = array('onclick' => 'useAmountOther();');
6a488035
TO
310 }
311
15831617 312 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
6a488035 313 $useRequired = 0;
366fe2a3 314 }
a7488080 315 elseif (!empty($fieldOptions[$optionKey]['label'])) { //check for label.
6a488035
TO
316 $label = $fieldOptions[$optionKey]['label'];
317 }
318
319 $element = &$qf->add('text', $elementName, $label,
320 array_merge($extra,
321 array('price' => json_encode(array($optionKey, $priceVal)),
322 'size' => '4',
323 )
324 ),
325 $useRequired && $field->is_required
326 );
327 if ($is_pay_later) {
328 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
329 }
330
d2108f71 331 // CRM-6902 - Add "max" option for a price set field
1537c309 332 if (in_array($optionKey, $freezeOptions)) {
6a488035 333 $element->freeze();
4dd3f46d 334 // CRM-14696 - Styling for sold out Text input fields is handled in PriceSet.tpl
6a488035
TO
335 }
336
337 //CRM-10117
55c0b49a
RK
338 if (!empty($qf->_quickConfig)) {
339 $message = ts('Please enter a valid amount.');
340 $type = 'money';
341 }
342 else {
343 $message = ts('%1 must be a number (with or without decimal point).', array(1 => $label));
344 $type = 'numeric';
345 }
6a488035
TO
346 // integers will have numeric rule applied to them.
347 $qf->addRule($elementName, $message, $type);
348 break;
349
350 case 'Radio':
351 $choice = array();
352
15831617 353 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
6a488035
TO
354 $qf->assign('contriPriceset', $elementName);
355 }
356
357 foreach ($customOption as $opId => $opt) {
9d1c9154 358 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
6a488035 359 if ($field->is_display_amounts) {
e2d2aeab 360 $opt['label'] = !empty($opt['label']) ? $opt['label'] . '&nbsp;-&nbsp;' : '';
3bd20e3f 361 if (isset($taxAmount) && $invoicing) {
dc428161 362 if ($displayOpt == 'Do_not_show') {
e2d2aeab 363 $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 364 }
365 else if ($displayOpt == 'Inclusive') {
e2d2aeab
DG
366 $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>';
367 $opt['label'] .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
dc428161 368 }
369 else {
e2d2aeab
DG
370 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>' . '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span>';
371 $opt['label'] .= '<span class="crm-price-amount-tax"> + '. CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
dc428161 372 }
373 }
374 else {
e2d2aeab 375 $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 376 }
6a488035 377 }
535a8e1e 378 $count = CRM_Utils_Array::value('count', $opt, '');
6a488035 379 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
dc428161 380 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
6a488035
TO
381 $extra = array('price' => json_encode(array($elementName, $priceVal)),
382 'data-amount' => $opt[$valueFieldName],
383 'data-currency' => $currencyName,
384 );
15831617 385 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
6a488035 386 $extra += array('onclick' => 'clearAmountOther();');
366fe2a3 387 }
15831617 388 elseif (!empty($qf->_quickConfig) && $field->name == 'membership_amount') {
6a488035
TO
389 $extra += array(
390 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
391 'membership-type' => $opt['membership_type_id'],
366fe2a3 392 );
6a488035
TO
393 $qf->assign('membershipFieldID',$field->id);
394 }
366fe2a3 395
6a488035
TO
396 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
397
398 if ($is_pay_later) {
399 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
400 }
401
d2108f71 402 // CRM-6902 - Add "max" option for a price set field
1537c309 403 if (in_array($opId, $freezeOptions)) {
6a488035 404 $choice[$opId]->freeze();
d2108f71 405 // CRM-14696 - Improve display for sold out price set options
be6dcd4e 406 $choice[$opId]->setText('<span class="sold-out-option">' . $choice[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
6a488035
TO
407 }
408 }
15831617 409 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
6a488035 410 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
abcf506a
PN
411 array(
412 'onclick' => 'clearAmountOther();',
413 )
6a488035
TO
414 );
415 }
416
417 if (!$field->is_required) {
418 // add "none" option
a7488080 419 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
6a488035 420 $none = ts('Other Amount');
366fe2a3 421 }
8cc574cf 422 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
6a488035 423 $none = ts('No thank you');
366fe2a3 424 }
6a488035
TO
425 else {
426 $none = ts('- none -');
427 }
428
429 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
430 array('price' => json_encode(array($elementName, '0')))
431 );
432 }
433
434 $element = &$qf->addGroup($choice, $elementName, $label);
435
436 // make contribution field required for quick config when membership block is enabled
abcf506a 437 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
15831617 438 && !empty($qf->_membershipBlock) && !$field->is_required) {
6a488035
TO
439 $useRequired = $field->is_required = TRUE;
440 }
441
442 if ($useRequired && $field->is_required) {
443 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
444 }
445 break;
446
447 case 'Select':
448 $selectOption = $allowedOptions = $priceVal = array();
449
450 foreach ($customOption as $opt) {
9d1c9154 451 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
6a488035
TO
452 $count = CRM_Utils_Array::value('count', $opt, '');
453 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
6a488035
TO
454
455 if ($field->is_display_amounts) {
456 $opt['label'] .= '&nbsp;-&nbsp;';
3bd20e3f 457 if (isset($taxAmount) && $invoicing) {
e2d2aeab 458 $opt['label'] = $opt['label'] . self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
dc428161 459 }
460 else {
e2d2aeab 461 $opt['label'] = $opt['label'] . CRM_Utils_Money::format($opt[$valueFieldName]);
dc428161 462 }
6a488035 463 }
22fd90d4 464
6a488035 465 $selectOption[$opt['id']] = $opt['label'];
dc428161 466 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
d2108f71 467
1537c309 468 if (!in_array($opt['id'], $freezeOptions)) {
6a488035
TO
469 $allowedOptions[] = $opt['id'];
470 }
d2108f71 471 // CRM-14696 - Improve display for sold out price set options
76991db6 472 else {
be6dcd4e 473 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
d2108f71
J
474 }
475
476 $selectOption[$opt['id']] = $opt['label'];
477
6a488035
TO
478 if ($is_pay_later) {
479 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
480 }
481 }
d2108f71 482
6a488035
TO
483 $element = &$qf->add('select', $elementName, $label,
484 array(
485 '' => ts('- select -')) + $selectOption,
486 $useRequired && $field->is_required,
487 array('price' => json_encode($priceVal))
488 );
489
d2108f71 490 // CRM-6902 - Add "max" option for a price set field
6a488035 491 $button = substr($qf->controller->getButtonName(), -4);
1537c309 492 if (!empty($freezeOptions) && $button != 'skip') {
6a488035
TO
493 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
494 }
495 break;
496
497 case 'CheckBox':
498
499 $check = array();
500 foreach ($customOption as $opId => $opt) {
9d1c9154 501 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
535a8e1e 502 $count = CRM_Utils_Array::value('count', $opt, '');
6a488035 503 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
6a488035
TO
504
505 if ($field->is_display_amounts) {
e2d2aeab 506 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>&nbsp;-&nbsp;';
3bd20e3f 507 if (isset($taxAmount) && $invoicing) {
5ebee375 508 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
dc428161 509 }
510 else {
511 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
512 }
6a488035 513 }
dc428161 514 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
6a488035
TO
515 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
516 array('price' => json_encode(array($opt['id'], $priceVal)),
517 'data-amount' => $opt[$valueFieldName],
518 'data-currency' => $currencyName,
519 )
520 );
521 if ($is_pay_later) {
522 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
523 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
524 }
d2108f71 525 // CRM-6902 - Add "max" option for a price set field
1537c309 526 if (in_array($opId, $freezeOptions)) {
6a488035 527 $check[$opId]->freeze();
d2108f71 528 // CRM-14696 - Improve display for sold out price set options
be6dcd4e 529 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
6a488035
TO
530 }
531 }
532 $element = &$qf->addGroup($check, $elementName, $label);
533 if ($useRequired && $field->is_required) {
534 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
535 }
536 break;
537 }
538 if (isset($qf->_online) && $qf->_online) {
539 $element->freeze();
540 }
541 }
542
543 /**
544 * Retrieve a list of options for the specified field
545 *
546 * @param int $fieldId price field ID
547 * @param bool $inactiveNeeded include inactive options
548 * @param bool $reset ignore stored values\
549 *
550 * @return array array of options
551 */
552 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
553 static $options = array();
554
555 if ($reset || empty($options[$fieldId])) {
556 $values = array();
9da8dc8c 557 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
6a488035 558 $options[$fieldId] = $values;
dc428161 559 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
560
561 // ToDo - Code for Hook Invoke
562
563 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
17ab42dd 564 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates)) {
dc428161 565 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
9d1c9154 566 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
dc428161 567 $options[$fieldId][$priceFieldId]['tax_amount'] = round($taxAmount['tax_amount'],2);
568 }
569 }
6a488035
TO
570 }
571
572 return $options[$fieldId];
573 }
574
ffd93213
EM
575 /**
576 * @param $optionLabel
100fef9d 577 * @param int $fid
ffd93213
EM
578 *
579 * @return mixed
580 */
6a488035
TO
581 public static function getOptionId($optionLabel, $fid) {
582 if (!$optionLabel || !$fid) {
583 return;
584 }
585
586 $optionGroupName = "civicrm_price_field.amount.{$fid}";
587
588 $query = "
589SELECT
590 option_value.id as id
591FROM
592 civicrm_option_value option_value,
593 civicrm_option_group option_group
594WHERE
535a8e1e
CW
595 option_group.name = %1
596 AND option_group.id = option_value.option_group_id
6a488035
TO
597 AND option_value.label = %2";
598
599 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
600
601 while ($dao->fetch()) {
602 return $dao->id;
603 }
604 }
605
606 /**
607 * Delete the price set field.
608 *
609 * @param int $id Field Id
610 *
611 * @return boolean
612 *
613 * @access public
614 * @static
615 *
616 */
617 public static function deleteField($id) {
9da8dc8c 618 $field = new CRM_Price_DAO_PriceField();
6a488035
TO
619 $field->id = $id;
620
621 if ($field->find(TRUE)) {
622 // delete the options for this field
9da8dc8c 623 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
6a488035
TO
624
625 // reorder the weight before delete
626 $fieldValues = array('price_set_id' => $field->price_set_id);
627
9da8dc8c 628 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
6a488035
TO
629
630 // now delete the field
631 return $field->delete();
632 }
633
634 return NULL;
635 }
636
ffd93213
EM
637 /**
638 * @return array
639 */
6a488035
TO
640 static function &htmlTypes() {
641 static $htmlTypes = NULL;
642 if (!$htmlTypes) {
643 $htmlTypes = array(
644 'Text' => ts('Text / Numeric Quantity'),
645 'Select' => ts('Select'),
646 'Radio' => ts('Radio'),
647 'CheckBox' => ts('CheckBox'),
648 );
649 }
650 return $htmlTypes;
651 }
652
653 /**
654 * Validate the priceset
655 *
2a6da8d7 656 * @param int $priceSetId , array $fields
6a488035
TO
657 *
658 * retrun the error string
659 *
2a6da8d7
EM
660 * @param $fields
661 * @param $error
662 * @param bool $allowNoneSelection
663 *
6a488035
TO
664 * @access public
665 * @static
6a488035
TO
666 */
667
668 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
669 // check for at least one positive
670 // amount price field should be selected.
9da8dc8c 671 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
672 $priceField->price_set_id = $priceSetId;
673 $priceField->find();
674
675 $priceFields = array();
676
677 if ($allowNoneSelection) {
678 $noneSelectedPriceFields = array();
679 }
680
681 while ($priceField->fetch()) {
682 $key = "price_{$priceField->id}";
683
684 if ($allowNoneSelection) {
685 if (array_key_exists($key, $fields)) {
686 if ($fields[$key] == 0 && !$priceField->is_required) {
687 $noneSelectedPriceFields[] = $priceField->id;
688 }
689 }
690 }
691
a7488080 692 if (!empty($fields[$key])) {
6a488035
TO
693 $priceFields[$priceField->id] = $fields[$key];
694 }
695 }
696
697 if (!empty($priceFields)) {
698 // we should has to have positive amount.
699 $sql = "
700SELECT id, html_type
701FROM civicrm_price_field
702WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
703 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
704 $htmlTypes = array();
705 while ($fieldDAO->fetch()) {
706 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
707 }
708
709 $selectedAmounts = array();
710
711 foreach ($htmlTypes as $fieldId => $type) {
712 $options = array();
9da8dc8c 713 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
6a488035
TO
714
715 if (empty($options)) {
716 continue;
717 }
718
719 if ($type == 'Text') {
720 foreach ($options as $opId => $option) {
721 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
722 break;
723 }
724 }
725 elseif (is_array($fields["price_{$fieldId}"])) {
726 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
727 $selectedAmounts[$opId] = $options[$opId]['amount'];
728 }
729 }
730 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
731 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
732 }
733 }
734
735 list($componentName) = explode(':', $fields['_qf_default']);
736 // now we have all selected amount in hand.
737 $totalAmount = array_sum($selectedAmounts);
738 if ($totalAmount < 0) {
739 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
740 }
741 }
742 else {
743 if ($allowNoneSelection) {
744 if (empty($noneSelectedPriceFields)) {
745 $error['_qf_default'] = ts('Please select at least one option from price set.');
746 }
747 } else {
748 $error['_qf_default'] = ts('Please select at least one option from price set.');
749 }
750 }
751 }
dc428161 752
753 /**
9d1c9154 754 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
dc428161 755 *
9d1c9154 756 * @param array $opt
757 * @param string $valueFieldName amount
758 * @param string $displayOpt tax display setting option
dc428161 759 *
9d1c9154 760 * @return string $label tax label for custom field
dc428161 761 *
762 * @access public
763 * @static
764 *
765 */
5ebee375 766 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
9d1c9154 767 if ($displayOpt == 'Do_not_show') {
768 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
769 }
770 else if ($displayOpt == 'Inclusive') {
771 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
e2d2aeab 772 $label .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
9d1c9154 773 }
774 else {
775 $label = CRM_Utils_Money::format($opt[$valueFieldName]);
e2d2aeab 776 $label .= '<span class="crm-price-amount-tax"> + '. CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
9d1c9154 777 }
dc428161 778
9d1c9154 779 return $label;
dc428161 780 }
6a488035
TO
781}
782