Merge pull request #9648 from MegaphoneJon/CRM-19608
[civicrm-core.git] / CRM / Price / BAO / PriceField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
31 * @copyright CiviCRM LLC (c) 2004-2017
32 * $Id$
33 *
34 */
35
36 /**
37 * Business objects for managing price fields.
38 *
39 */
40 class CRM_Price_BAO_PriceField extends CRM_Price_DAO_PriceField {
41
42 protected $_options;
43
44 /**
45 * List of visibility option ID's, of the form name => ID
46 *
47 * @var array
48 */
49 private static $visibilityOptionsKeys;
50
51 /**
52 * Takes an associative array and creates a price field object.
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 *
58 * @param array $params
59 * (reference) an assoc array of name/value pairs.
60 *
61 * @return CRM_Price_BAO_PriceField
62 */
63 public static function add(&$params) {
64 $priceFieldBAO = new CRM_Price_BAO_PriceField();
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 /**
77 * Takes an associative array and creates a price field object.
78 *
79 * This function is invoked from within the web form layer and also from the api layer
80 *
81 * @param array $params
82 * (reference) an assoc array of name/value pairs.
83 *
84 * @return CRM_Price_DAO_PriceField
85 * @throws \CRM_Core_Exception
86 */
87 public static function create(&$params) {
88 if (empty($params['id']) && empty($params['name'])) {
89 $params['name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 242));
90 }
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
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 }
103 $optionsIds = array();
104 $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
105 if ($priceField->html_type == 'Text') {
106 $maxIndex = 1;
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'];
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 }
120 }
121 }
122 $defaultArray = array();
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'])) {
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 {
133 if (!empty($params['default_option'])) {
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']) &&
141 (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) &&
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,
157 'non_deductible_amount' => CRM_Utils_Array::value('non_deductible_amount', $params),
158 'visibility_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_visibility_id', $params), self::getVisibilityOptionID('public')),
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);
163 $options['is_default'] = CRM_Utils_Array::value($params['membership_type_id'][$index], $defaultArray) ? $defaultArray[$params['membership_type_id'][$index]] : 0;
164 }
165
166 if (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_financial_type_id', $params))) {
167 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
168 }
169 elseif (!empty($params['financial_type_id'])) {
170 $options['financial_type_id'] = $params['financial_type_id'];
171 }
172 if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
173 if ($opId = CRM_Utils_Array::value($index, $opIds)) {
174 $optionsIds['id'] = $opId;
175 }
176 else {
177 $optionsIds['id'] = NULL;
178 }
179 }
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 }
188 elseif (!empty($optionsIds) && !empty($optionsIds['id'])) {
189 $optionsLoad = civicrm_api3('price_field_value', 'get', array('id' => $optionsIds['id']));
190 $options = $optionsLoad['values'][$optionsIds['id']];
191 $options['is_active'] = CRM_Utils_Array::value('is_active', $params, 1);
192 try {
193 CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
194 }
195 catch (Exception $e) {
196 $transaction->rollback();
197 throw new CRM_Core_Exception($e->getMessage());
198 }
199 }
200 }
201
202 $transaction->commit();
203 return $priceField;
204 }
205
206 /**
207 * Fetch object based on array of properties.
208 *
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.
213 *
214 * @return CRM_Price_DAO_PriceField
215 */
216 public static function retrieve(&$params, &$defaults) {
217 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
218 }
219
220 /**
221 * Update the is_active flag in the db.
222 *
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.
227 *
228 * @return Object
229 * DAO object on success, null otherwise.
230 */
231 public static function setIsActive($id, $is_active) {
232 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
233 }
234
235 /**
236 * Freeze form if the event is full.
237 *
238 * @param $element
239 * @param $fieldOptions
240 *
241 * @return null
242 */
243 public static function freezeIfEnabled(&$element, $fieldOptions) {
244 if (!empty($fieldOptions['is_full'])) {
245 $element->freeze();
246 }
247 return NULL;
248 }
249
250 /**
251 * Get the field title.
252 *
253 * @param int $id
254 * Id of field.
255 *
256 * @return string
257 * name
258 *
259 */
260 public static function getTitle($id) {
261 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
262 }
263
264 /**
265 * This function for building custom fields.
266 *
267 * @param CRM_Core_Form $qf
268 * Form object (reference).
269 * @param string $elementName
270 * Name of the custom field.
271 * @param int $fieldId
272 * @param bool $inactiveNeeded
273 * @param bool $useRequired
274 * True if required else false.
275 * @param string $label
276 * Label for custom field.
277 *
278 * @param null $fieldOptions
279 * @param array $freezeOptions
280 *
281 * @return null
282 */
283 public static function addQuickFormElement(
284 &$qf,
285 $elementName,
286 $fieldId,
287 $inactiveNeeded,
288 $useRequired = TRUE,
289 $label = NULL,
290 $fieldOptions = NULL,
291 $freezeOptions = array()
292 ) {
293
294 $field = new CRM_Price_DAO_PriceField();
295 $field->id = $fieldId;
296 if (!$field->find(TRUE)) {
297 /* FIXME: failure! */
298 return NULL;
299 }
300
301 $is_pay_later = 0;
302 if (isset($qf->_mode) && empty($qf->_mode)) {
303 $is_pay_later = 1;
304 }
305 elseif (isset($qf->_values)) {
306 $is_pay_later = CRM_Utils_Array::value('is_pay_later', $qf->_values);
307 }
308
309 $otherAmount = $qf->get('values');
310 $config = CRM_Core_Config::singleton();
311 $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency', $config->defaultCurrency, 'symbol', 'name');
312 $qf->assign('currencySymbol', $currencySymbol);
313 // get currency name for price field and option attributes
314 $currencyName = $config->defaultCurrency;
315
316 if (!isset($label)) {
317 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
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)) {
330 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
331 }
332
333 //use value field.
334 $valueFieldName = 'amount';
335 $seperator = '|';
336 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
337 $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
338 $displayOpt = CRM_Utils_Array::value('tax_display_settings', $invoiceSettings);
339 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
340 switch ($field->html_type) {
341 case 'Text':
342 $optionKey = key($customOption);
343 $count = CRM_Utils_Array::value('count', $customOption[$optionKey], '');
344 $max_value = CRM_Utils_Array::value('max_value', $customOption[$optionKey], '');
345 $taxAmount = CRM_Utils_Array::value('tax_amount', $customOption[$optionKey]);
346 if (isset($taxAmount) && $displayOpt && $invoicing) {
347 $qf->assign('displayOpt', $displayOpt);
348 $qf->assign('taxTerm', $taxTerm);
349 $qf->assign('invoicing', $invoicing);
350 }
351 $priceVal = implode($seperator, array(
352 $customOption[$optionKey][$valueFieldName] + $taxAmount,
353 $count,
354 $max_value,
355 ));
356
357 $extra = array();
358 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
359 $useRequired = 0;
360 }
361 elseif (!empty($fieldOptions[$optionKey]['label'])) {
362 //check for label.
363 $label = $fieldOptions[$optionKey]['label'];
364 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount) && strtolower($fieldOptions[$optionKey]['name']) == 'other_amount') {
365 $label .= ' ' . $currencySymbol;
366 $qf->assign('priceset', $elementName);
367 $extra = array('onclick' => 'useAmountOther();');
368 }
369 }
370
371 $element = &$qf->add('text', $elementName, $label,
372 array_merge($extra,
373 array(
374 'price' => json_encode(array($optionKey, $priceVal)),
375 'size' => '4',
376 )
377 ),
378 $useRequired && $field->is_required
379 );
380 if ($is_pay_later) {
381 $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
382 }
383
384 // CRM-6902 - Add "max" option for a price set field
385 if (in_array($optionKey, $freezeOptions)) {
386 self::freezeIfEnabled($element, $fieldOptions[$optionKey]);
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>');
389 }
390
391 //CRM-10117
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 }
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
407 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
408 $qf->assign('contriPriceset', $elementName);
409 }
410
411 foreach ($customOption as $opId => $opt) {
412 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
413 if ($field->is_display_amounts) {
414 $opt['label'] = !empty($opt['label']) ? $opt['label'] . '<span class="crm-price-amount-label-separator">&nbsp;-&nbsp;</span>' : '';
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 }
422 if (isset($taxAmount) && $invoicing) {
423 if ($displayOpt == 'Do_not_show') {
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>';
425 }
426 elseif ($displayOpt == 'Inclusive') {
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>';
429 }
430 else {
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>';
433 }
434 }
435 else {
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>';
437 }
438 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
439 }
440 $count = CRM_Utils_Array::value('count', $opt, '');
441 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
442 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
443 if (isset($opt['visibility_id'])) {
444 $visibility_id = $opt['visibility_id'];
445 }
446 else {
447 $visibility_id = self::getVisibilityOptionID('public');
448 }
449 $extra = array(
450 'price' => json_encode(array($elementName, $priceVal)),
451 'data-amount' => $opt[$valueFieldName],
452 'data-currency' => $currencyName,
453 'data-price-field-values' => json_encode($customOption),
454 'visibility' => $visibility_id,
455 );
456 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
457 $extra += array('onclick' => 'clearAmountOther();');
458 }
459 if ($field->name == 'membership_amount') {
460 $extra += array(
461 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
462 'membership-type' => $opt['membership_type_id'],
463 );
464 $qf->assign('membershipFieldID', $field->id);
465 }
466
467 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
468 if ($is_pay_later) {
469 $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
470 }
471
472 // CRM-6902 - Add "max" option for a price set field
473 if (in_array($opId, $freezeOptions)) {
474 self::freezeIfEnabled($choice[$opId], $customOption[$opId]);
475 // CRM-14696 - Improve display for sold out price set options
476 $choice[$opId]->setText('<span class="sold-out-option">' . $choice[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
477 }
478 }
479 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
480 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
481 array(
482 'price' => json_encode(array($elementName, '0|0')),
483 'data-currency' => $currencyName,
484 'onclick' => 'clearAmountOther();',
485 )
486 );
487 }
488
489 if (!$field->is_required) {
490 // add "none" option
491 if (!empty($otherAmount['is_allow_other_amount']) && $field->name == 'contribution_amount') {
492 $none = ts('Other Amount');
493 }
494 elseif (!empty($qf->_membershipBlock) && empty($qf->_membershipBlock['is_required']) && $field->name == 'membership_amount') {
495 $none = ts('No thank you');
496 }
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
509 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
510 && !empty($qf->_membershipBlock) && !$field->is_required
511 ) {
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) {
524 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
525 $count = CRM_Utils_Array::value('count', $opt, '');
526 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
527
528 if ($field->is_display_amounts) {
529 $opt['label'] .= '&nbsp;-&nbsp;';
530 if (isset($taxAmount) && $invoicing) {
531 $opt['label'] = $opt['label'] . self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
532 }
533 else {
534 $opt['label'] = $opt['label'] . CRM_Utils_Money::format($opt[$valueFieldName]);
535 }
536 }
537
538 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
539
540 if (!in_array($opt['id'], $freezeOptions)) {
541 $allowedOptions[] = $opt['id'];
542 }
543 // CRM-14696 - Improve display for sold out price set options
544 else {
545 $opt['id'] = 'crm_disabled_opt-' . $opt['id'];
546 $opt['label'] = $opt['label'] . ' (' . ts('Sold out') . ')';
547 }
548
549 $selectOption[$opt['id']] = $opt['label'];
550
551 if ($is_pay_later) {
552 $qf->add('text', 'txt-' . $elementName, $label, array('size' => '4'));
553 }
554 }
555 if (isset($opt['visibility_id'])) {
556 $visibility_id = $opt['visibility_id'];
557 }
558 else {
559 $visibility_id = self::getVisibilityOptionID('public');
560 }
561 $element = &$qf->add('select', $elementName, $label,
562 array(
563 '' => ts('- select -'),
564 ) + $selectOption,
565 $useRequired && $field->is_required,
566 array('price' => json_encode($priceVal), 'class' => 'crm-select2', 'data-price-field-values' => json_encode($customOption))
567 );
568
569 // CRM-6902 - Add "max" option for a price set field
570 $button = substr($qf->controller->getButtonName(), -4);
571 if (!empty($freezeOptions) && $button != 'skip') {
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) {
580 $taxAmount = CRM_Utils_Array::value('tax_amount', $opt);
581 $count = CRM_Utils_Array::value('count', $opt, '');
582 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
583
584 if ($field->is_display_amounts) {
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 }
592 $opt['label'] = '<span class="crm-price-amount-label">' . $opt['label'] . '</span>&nbsp;-&nbsp;';
593 if (isset($taxAmount) && $invoicing) {
594 $opt['label'] .= self::getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm);
595 }
596 else {
597 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
598 }
599 $opt['label'] = $preHelpText . $opt['label'] . $postHelpText;
600 }
601 $priceVal = implode($seperator, array($opt[$valueFieldName] + $taxAmount, $count, $max_value));
602 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
603 array(
604 'price' => json_encode(array($opt['id'], $priceVal)),
605 'data-amount' => $opt[$valueFieldName],
606 'data-currency' => $currencyName,
607 'visibility' => $opt['visibility_id'],
608 )
609 );
610 if ($is_pay_later) {
611 $txtcheck[$opId] =& $qf->createElement('text', $opId, $opt['label'], array('size' => '4'));
612 $qf->addGroup($txtcheck, 'txt-' . $elementName, $label);
613 }
614 // CRM-6902 - Add "max" option for a price set field
615 if (in_array($opId, $freezeOptions)) {
616 self::freezeIfEnabled($check[$opId], $customOption[$opId]);
617 // CRM-14696 - Improve display for sold out price set options
618 $check[$opId]->setText('<span class="sold-out-option">' . $check[$opId]->getText() . '&nbsp;(' . ts('Sold out') . ')</span>');
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 /**
633 * Retrieve a list of options for the specified field.
634 *
635 * @param int $fieldId
636 * Price field ID.
637 * @param bool $inactiveNeeded
638 * Include inactive options.
639 * @param bool $reset
640 * Discard stored values.
641 * @param bool $isDefaultContributionPriceSet
642 * Discard tax amount calculation for price set = default_contribution_amount.
643 *
644 * @return array
645 * array of options
646 */
647 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE, $isDefaultContributionPriceSet = FALSE) {
648 static $options = array();
649 if ($reset) {
650 $options = array();
651 // This would happen if the function was only called to clear the cache.
652 if (empty($fieldId)) {
653 return array();
654 }
655 }
656
657 if (empty($options[$fieldId])) {
658 $values = array();
659 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
660 $options[$fieldId] = $values;
661 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
662
663 // ToDo - Code for Hook Invoke
664
665 foreach ($options[$fieldId] as $priceFieldId => $priceFieldValues) {
666 if (isset($priceFieldValues['financial_type_id']) && array_key_exists($priceFieldValues['financial_type_id'], $taxRates) && !$isDefaultContributionPriceSet) {
667 $options[$fieldId][$priceFieldId]['tax_rate'] = $taxRates[$priceFieldValues['financial_type_id']];
668 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($priceFieldValues['amount'], $options[$fieldId][$priceFieldId]['tax_rate']);
669 $options[$fieldId][$priceFieldId]['tax_amount'] = $taxAmount['tax_amount'];
670 }
671 }
672 }
673
674 return $options[$fieldId];
675 }
676
677 /**
678 * @param $optionLabel
679 * @param int $fid
680 *
681 * @return mixed
682 */
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 = "
691 SELECT
692 option_value.id as id
693 FROM
694 civicrm_option_value option_value,
695 civicrm_option_group option_group
696 WHERE
697 option_group.name = %1
698 AND option_group.id = option_value.option_group_id
699 AND option_value.label = %2";
700
701 $dao = CRM_Core_DAO::executeQuery($query, array(
702 1 => array($optionGroupName, 'String'),
703 2 => array($optionLabel, 'String'),
704 ));
705
706 while ($dao->fetch()) {
707 return $dao->id;
708 }
709 }
710
711 /**
712 * Delete the price set field.
713 *
714 * @param int $id
715 * Field Id.
716 *
717 * @return bool
718 *
719 */
720 public static function deleteField($id) {
721 $field = new CRM_Price_DAO_PriceField();
722 $field->id = $id;
723
724 if ($field->find(TRUE)) {
725 // delete the options for this field
726 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
727
728 // reorder the weight before delete
729 $fieldValues = array('price_set_id' => $field->price_set_id);
730
731 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
732
733 // now delete the field
734 return $field->delete();
735 }
736
737 return NULL;
738 }
739
740 /**
741 * @return array
742 */
743 public static function &htmlTypes() {
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 /**
757 * Validate the priceset.
758 *
759 * @param int $priceSetId
760 * , array $fields.
761 *
762 * retrun the error string
763 *
764 * @param $fields
765 * @param $error
766 * @param bool $allowNoneSelection
767 *
768 */
769 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
770 // check for at least one positive
771 // amount price field should be selected.
772 $priceField = new CRM_Price_DAO_PriceField();
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
793 if (!empty($fields[$key])) {
794 $priceFields[$priceField->id] = $fields[$key];
795 }
796 }
797
798 if (!empty($priceFields)) {
799 // we should has to have positive amount.
800 $sql = "
801 SELECT id, html_type
802 FROM civicrm_price_field
803 WHERE 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();
814 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
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);
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));
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 }
844 elseif ($totalAmount > 0 &&
845 $totalPaymentAmountEnteredOnForm >= $totalAmount && // if total amount is equal to all selected amount in hand
846 (CRM_Utils_Array::value('contribution_status_id', $fields) == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Partially paid'))
847 ) {
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');
849 }
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 }
856 }
857 else {
858 $error['_qf_default'] = ts('Please select at least one option from price set.');
859 }
860 }
861 }
862
863 /**
864 * Generate the label for price fields based on tax display setting option on CiviContribute Component Settings page.
865 *
866 * @param array $opt
867 * @param string $valueFieldName
868 * Amount.
869 * @param string $displayOpt
870 * Tax display setting option.
871 *
872 * @param string $taxTerm
873 *
874 * @return string
875 * Tax label for custom field.
876 */
877 public static function getTaxLabel($opt, $valueFieldName, $displayOpt, $taxTerm) {
878 if ($displayOpt == 'Do_not_show') {
879 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
880 }
881 elseif ($displayOpt == 'Inclusive') {
882 $label = CRM_Utils_Money::format($opt[$valueFieldName] + $opt['tax_amount']);
883 $label .= '<span class="crm-price-amount-tax"> (includes ' . $taxTerm . ' of ' . CRM_Utils_Money::format($opt['tax_amount']) . ')</span>';
884 }
885 else {
886 $label = CRM_Utils_Money::format($opt[$valueFieldName]);
887 $label .= '<span class="crm-price-amount-tax"> + ' . CRM_Utils_Money::format($opt['tax_amount']) . ' ' . $taxTerm . '</span>';
888 }
889
890 return $label;
891 }
892
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
920 }