Merge pull request #1625 from pradpnayak/CRM-13340
[civicrm-core.git] / CRM / Price / BAO / PriceField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 * takes an associative array and creates a price field object
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 *
51 * @param array $params (reference ) an assoc array of name/value pairs
52 * @param array $ids the array that holds all the db ids
53 *
54 * @return object CRM_Price_BAO_PriceField object
55 * @access public
56 * @static
57 */
58 static function &add(&$params) {
59 $priceFieldBAO = new CRM_Price_BAO_PriceField();
60
61 $priceFieldBAO->copyValues($params);
62
63 if ($id = CRM_Utils_Array::value('id', $params)) {
64 $priceFieldBAO->id = $id;
65 }
66
67 $priceFieldBAO->save();
68 return $priceFieldBAO;
69 }
70
71 /**
72 * takes an associative array and creates a price field object
73 *
74 * This function is invoked from within the web form layer and also from the api layer
75 *
76 * @param array $params (reference) an assoc array of name/value pairs
77 *
78 * @return object CRM_Price_DAO_PriceField object
79 * @access public
80 * @static
81 */
82 static function create(&$params) {
83 $transaction = new CRM_Core_Transaction();
84
85 $priceField = self::add($params);
86
87 if (is_a($priceField, 'CRM_Core_Error')) {
88 $transaction->rollback();
89 return $priceField;
90 }
91
92 $options = $optionsIds = array();
93 $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
94
95 if ($priceField->html_type == 'Text') {
96 $maxIndex = 1;
97
98 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
99 $fieldValue->price_field_id = $priceField->id;
100
101 // update previous field values( if any )
102 if ($fieldValue->find(TRUE)) {
103 $optionsIds['id'] = $fieldValue->id;
104 }
105 }
106 $defaultArray = array();
107 if ($params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
108 $tempArray = array_keys($params['default_checkbox_option']);
109 foreach ($tempArray as $v) {
110 if ($params['option_amount'][$v]) {
111 $defaultArray[$v] = 1;
112 }
113 }
114 }
115 else {
116 if (CRM_Utils_Array::value('default_option', $params)) {
117 $defaultArray[$params['default_option']] = 1;
118 }
119 }
120
121 for ($index = 1; $index <= $maxIndex; $index++) {
122 if (array_key_exists('option_amount', $params) &&
123 array_key_exists($index, $params['option_amount']) &&
124 (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) ||
125 CRM_Utils_Array::value('is_quick_config', $params)) &&
126 !CRM_Utils_System::isNull($params['option_amount'][$index])
127 ) {
128 $options = array(
129 'price_field_id' => $priceField->id,
130 'label' => trim($params['option_label'][$index]),
131 'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64),
132 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])),
133 'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL),
134 'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL),
135 'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL),
136 'membership_type_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_type_id', $params), NULL),
137 'weight' => $params['option_weight'][$index],
138 'is_active' => 1,
139 'is_default' => CRM_Utils_Array::value($params['option_weight'][$index], $defaultArray) ? $defaultArray[$params['option_weight'][$index]] : 0,
140 'membership_num_terms' => NULL,
141 );
142
143 if ($options['membership_type_id']) {
144 $options['membership_num_terms'] = CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_num_terms', $params), 1);
145 }
146
147 if (CRM_Utils_Array::value( $index, CRM_Utils_Array::value('option_financial_type_id', $params))) {
148 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
149 } elseif (CRM_Utils_Array::value( 'financial_type_id', $params )) {
150 $options['financial_type_id'] = $params['financial_type_id'];
151 }
152
153 if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
154 if ($opId = CRM_Utils_Array::value($index, $opIds)) {
155 $optionsIds['id'] = $opId;
156 } else {
157 $optionsIds['id'] = NULL;
158 }
159 }
160 CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
161 }
162 }
163
164 $transaction->commit();
165 return $priceField;
166 }
167
168 /**
169 * Takes a bunch of params that are needed to match certain criteria and
170 * retrieves the relevant objects. Typically the valid params are only
171 * contact_id. We'll tweak this function to be more full featured over a period
172 * of time. This is the inverse function of create. It also stores all the retrieved
173 * values in the default array
174 *
175 * @param array $params (reference ) an assoc array of name/value pairs
176 * @param array $defaults (reference ) an assoc array to hold the flattened values
177 *
178 * @return object CRM_Price_DAO_PriceField object
179 * @access public
180 * @static
181 */
182 static function retrieve(&$params, &$defaults) {
183 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceField', $params, $defaults);
184 }
185
186 /**
187 * update the is_active flag in the db
188 *
189 * @param int $id Id of the database record
190 * @param boolean $is_active Value we want to set the is_active field
191 *
192 * @return Object DAO object on sucess, null otherwise
193 *
194 * @access public
195 * @static
196 */
197 static function setIsActive($id, $is_active) {
198 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $id, 'is_active', $is_active);
199 }
200
201 /**
202 * Get the field title.
203 *
204 * @param int $id id of field.
205 *
206 * @return string name
207 *
208 * @access public
209 * @static
210 *
211 */
212 public static function getTitle($id) {
213 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $id, 'label');
214 }
215
216 /**
217 * This function for building custom fields
218 *
219 * @param object $qf form object (reference)
220 * @param string $elementName name of the custom field
221 * @param boolean $inactiveNeeded
222 * @param boolean $useRequired true if required else false
223 * @param boolean $search true if used for search else false
224 * @param string $label label for custom field
225 *
226 * @access public
227 * @static
228 */
229 public static function addQuickFormElement(&$qf,
230 $elementName,
231 $fieldId,
232 $inactiveNeeded,
233 $useRequired = TRUE,
234 $label = NULL,
235 $fieldOptions = NULL,
236 $feezeOptions = array()
237 ) {
238
239 $field = new CRM_Price_DAO_PriceField();
240 $field->id = $fieldId;
241 if (!$field->find(TRUE)) {
242 /* FIXME: failure! */
243 return NULL;
244 }
245
246 $is_pay_later = 0;
247 if (isset($qf->_mode) && empty($qf->_mode)) {
248 $is_pay_later = 1;
249 }
250 elseif (isset($qf->_values)) {
251 $is_pay_later = CRM_Utils_Array::value( 'is_pay_later', $qf->_values);
252 }
253
254 $otherAmount = $qf->get('values');
255 $config = CRM_Core_Config::singleton();
256 $currencySymbol = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_Currency',$config->defaultCurrency,'symbol','name');
257 $qf->assign('currencySymbol', $currencySymbol);
258 // get currency name for price field and option attributes
259 $currencyName = $config->defaultCurrency;
260
261 if (!isset($label)) {
262 $label = (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') ? ts('Additional Contribution') : $field->label;
263 }
264
265 if ($field->name == 'contribution_amount') {
266 $qf->_contributionAmount = 1;
267 }
268
269 if (isset($qf->_online) && $qf->_online) {
270 $useRequired = FALSE;
271 }
272
273 $customOption = $fieldOptions;
274 if (!is_array($customOption)) {
275 $customOption = CRM_Price_BAO_PriceField::getOptions($field->id, $inactiveNeeded);
276 }
277
278 //use value field.
279 $valueFieldName = 'amount';
280 $seperator = '|';
281 switch ($field->html_type) {
282 case 'Text':
283 $optionKey = key($customOption);
284 $count = CRM_Utils_Array::value('count', $customOption[$optionKey], '');
285 $max_value = CRM_Utils_Array::value('max_value', $customOption[$optionKey], '');
286 $priceVal = implode($seperator, array($customOption[$optionKey][$valueFieldName], $count, $max_value));
287
288 $extra = array();
289 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
290 foreach($fieldOptions as &$fieldOption) {
291 if ($fieldOption['name'] == 'other_amount') {
292 $fieldOption['label'] = $fieldOption['label'] . ' ' . $currencySymbol;
293 }
294 }
295 $qf->assign('priceset', $elementName);
296 $extra = array('onclick' => 'useAmountOther();');
297 }
298
299 // if seperate membership payment is used with quick config priceset then change the other amount label
300 if (!empty($qf->_membershipBlock) && !empty($qf->_quickConfig) && $field->name == 'other_amount' && empty($qf->_contributionAmount)) {
301 $label = ts('Additional Contribution');
302 $useRequired = 0;
303 }
304 elseif (CRM_Utils_Array::value('label', $fieldOptions[$optionKey])) { //check for label.
305 $label = $fieldOptions[$optionKey]['label'];
306 }
307
308 $element = &$qf->add('text', $elementName, $label,
309 array_merge($extra,
310 array('price' => json_encode(array($optionKey, $priceVal)),
311 'size' => '4',
312 )
313 ),
314 $useRequired && $field->is_required
315 );
316 if ($is_pay_later) {
317 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
318 }
319
320 // CRM-6902
321 if (in_array($optionKey, $feezeOptions)) {
322 $element->freeze();
323 }
324
325 //CRM-10117
326 if (!empty($qf->_quickConfig)) {
327 $message = ts('Please enter a valid amount.');
328 $type = 'money';
329 }
330 else {
331 $message = ts('%1 must be an integer (whole number).', array(1 => $label));
332 $type = 'positiveInteger';
333 }
334 // integers will have numeric rule applied to them.
335 $qf->addRule($elementName, $message, $type);
336 break;
337
338 case 'Radio':
339 $choice = array();
340
341 if (!empty($qf->_quickConfig) && !empty($qf->_contributionAmount)) {
342 $qf->assign('contriPriceset', $elementName);
343 }
344
345 foreach ($customOption as $opId => $opt) {
346 if ($field->is_display_amounts) {
347 $opt['label'] = CRM_Utils_Array::value('label', $opt) ? $opt['label'] : '';
348 $opt['label'] = '<span class="crm-price-amount-amount">' . CRM_Utils_Money::format($opt[$valueFieldName]) . '</span> <span class="crm-price-amount-label">' . $opt['label'] . '</span>';
349 }
350 $count = CRM_Utils_Array::value('count', $opt, '');
351 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
352 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
353 $extra = array('price' => json_encode(array($elementName, $priceVal)),
354 'data-amount' => $opt[$valueFieldName],
355 'data-currency' => $currencyName,
356 );
357 if (!empty($qf->_quickConfig) && $field->name == 'contribution_amount') {
358 $extra += array('onclick' => 'clearAmountOther();');
359 }
360 elseif (!empty($qf->_quickConfig) && $field->name == 'membership_amount') {
361 $extra += array(
362 'onclick' => "return showHideAutoRenew({$opt['membership_type_id']});",
363 'membership-type' => $opt['membership_type_id'],
364 );
365 $qf->assign('membershipFieldID',$field->id);
366 }
367
368 $choice[$opId] = $qf->createElement('radio', NULL, '', $opt['label'], $opt['id'], $extra);
369
370 if ($is_pay_later) {
371 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
372 }
373
374 // CRM-6902
375 if (in_array($opId, $feezeOptions)) {
376 $choice[$opId]->freeze();
377 }
378 }
379 if (!empty($qf->_membershipBlock) && $field->name == 'contribution_amount') {
380 $choice[] = $qf->createElement('radio', NULL, '', ts('No thank you'), '-1',
381 array(
382 'onclick' => 'clearAmountOther();',
383 )
384 );
385 }
386
387 if (!$field->is_required) {
388 // add "none" option
389 if (CRM_Utils_Array::value('is_allow_other_amount', $otherAmount) && $field->name == 'contribution_amount') {
390 $none = ts('Other Amount');
391 }
392 elseif (!empty($qf->_membershipBlock) && !CRM_Utils_Array::value('is_required', $qf->_membershipBlock) && $field->name == 'membership_amount') {
393 $none = ts('No thank you');
394 }
395 else {
396 $none = ts('- none -');
397 }
398
399 $choice[] = $qf->createElement('radio', NULL, '', $none, '0',
400 array('price' => json_encode(array($elementName, '0')))
401 );
402 }
403
404 $element = &$qf->addGroup($choice, $elementName, $label);
405
406 // make contribution field required for quick config when membership block is enabled
407 if (($field->name == 'membership_amount' || $field->name == 'contribution_amount')
408 && !empty($qf->_membershipBlock) && !$field->is_required) {
409 $useRequired = $field->is_required = TRUE;
410 }
411
412 if ($useRequired && $field->is_required) {
413 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
414 }
415 break;
416
417 case 'Select':
418 $selectOption = $allowedOptions = $priceVal = array();
419
420 foreach ($customOption as $opt) {
421 $count = CRM_Utils_Array::value('count', $opt, '');
422 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
423 $priceVal[$opt['id']] = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
424
425 if ($field->is_display_amounts) {
426 $opt['label'] .= '&nbsp;-&nbsp;';
427 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
428 }
429 $selectOption[$opt['id']] = $opt['label'];
430
431 if (!in_array($opt['id'], $feezeOptions)) {
432 $allowedOptions[] = $opt['id'];
433 }
434 if ($is_pay_later) {
435 $qf->add( 'text', 'txt-'.$elementName, $label, array( 'size' => '4'));
436 }
437 }
438 $element = &$qf->add('select', $elementName, $label,
439 array(
440 '' => ts('- select -')) + $selectOption,
441 $useRequired && $field->is_required,
442 array('price' => json_encode($priceVal))
443 );
444
445 // CRM-6902
446 $button = substr($qf->controller->getButtonName(), -4);
447 if (!empty($feezeOptions) && $button != 'skip') {
448 $qf->addRule($elementName, ts('Sorry, this option is currently sold out.'), 'regex', "/" . implode('|', $allowedOptions) . "/");
449 }
450 break;
451
452 case 'CheckBox':
453
454 $check = array();
455 foreach ($customOption as $opId => $opt) {
456 $count = CRM_Utils_Array::value('count', $opt, '');
457 $max_value = CRM_Utils_Array::value('max_value', $opt, '');
458 $priceVal = implode($seperator, array($opt[$valueFieldName], $count, $max_value));
459
460 if ($field->is_display_amounts) {
461 $opt['label'] .= '&nbsp;-&nbsp;';
462 $opt['label'] .= CRM_Utils_Money::format($opt[$valueFieldName]);
463 }
464 $check[$opId] = &$qf->createElement('checkbox', $opt['id'], NULL, $opt['label'],
465 array('price' => json_encode(array($opt['id'], $priceVal)),
466 'data-amount' => $opt[$valueFieldName],
467 'data-currency' => $currencyName,
468 )
469 );
470 if ($is_pay_later) {
471 $txtcheck[$opId] =& $qf->createElement( 'text', $opId, $opt['label'], array( 'size' => '4' ) );
472 $qf->addGroup($txtcheck, 'txt-'.$elementName, $label);
473 }
474 // CRM-6902
475 if (in_array($opId, $feezeOptions)) {
476 $check[$opId]->freeze();
477 }
478 }
479 $element = &$qf->addGroup($check, $elementName, $label);
480 if ($useRequired && $field->is_required) {
481 $qf->addRule($elementName, ts('%1 is a required field.', array(1 => $label)), 'required');
482 }
483 break;
484 }
485 if (isset($qf->_online) && $qf->_online) {
486 $element->freeze();
487 }
488 }
489
490 /**
491 * Retrieve a list of options for the specified field
492 *
493 * @param int $fieldId price field ID
494 * @param bool $inactiveNeeded include inactive options
495 * @param bool $reset ignore stored values\
496 *
497 * @return array array of options
498 */
499 public static function getOptions($fieldId, $inactiveNeeded = FALSE, $reset = FALSE) {
500 static $options = array();
501
502 if ($reset || empty($options[$fieldId])) {
503 $values = array();
504 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $values, 'weight', !$inactiveNeeded);
505 $options[$fieldId] = $values;
506 }
507
508 return $options[$fieldId];
509 }
510
511 public static function getOptionId($optionLabel, $fid) {
512 if (!$optionLabel || !$fid) {
513 return;
514 }
515
516 $optionGroupName = "civicrm_price_field.amount.{$fid}";
517
518 $query = "
519 SELECT
520 option_value.id as id
521 FROM
522 civicrm_option_value option_value,
523 civicrm_option_group option_group
524 WHERE
525 option_group.name = %1
526 AND option_group.id = option_value.option_group_id
527 AND option_value.label = %2";
528
529 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($optionGroupName, 'String'), 2 => array($optionLabel, 'String')));
530
531 while ($dao->fetch()) {
532 return $dao->id;
533 }
534 }
535
536 /**
537 * Delete the price set field.
538 *
539 * @param int $id Field Id
540 *
541 * @return boolean
542 *
543 * @access public
544 * @static
545 *
546 */
547 public static function deleteField($id) {
548 $field = new CRM_Price_DAO_PriceField();
549 $field->id = $id;
550
551 if ($field->find(TRUE)) {
552 // delete the options for this field
553 CRM_Price_BAO_PriceFieldValue::deleteValues($id);
554
555 // reorder the weight before delete
556 $fieldValues = array('price_set_id' => $field->price_set_id);
557
558 CRM_Utils_Weight::delWeight('CRM_Price_DAO_PriceField', $field->id, $fieldValues);
559
560 // now delete the field
561 return $field->delete();
562 }
563
564 return NULL;
565 }
566
567 static function &htmlTypes() {
568 static $htmlTypes = NULL;
569 if (!$htmlTypes) {
570 $htmlTypes = array(
571 'Text' => ts('Text / Numeric Quantity'),
572 'Select' => ts('Select'),
573 'Radio' => ts('Radio'),
574 'CheckBox' => ts('CheckBox'),
575 );
576 }
577 return $htmlTypes;
578 }
579
580 /**
581 * Validate the priceset
582 *
583 * @param int $priceSetId, array $fields
584 *
585 * retrun the error string
586 *
587 * @access public
588 * @static
589 *
590 */
591
592 public static function priceSetValidation($priceSetId, $fields, &$error, $allowNoneSelection = FALSE) {
593 // check for at least one positive
594 // amount price field should be selected.
595 $priceField = new CRM_Price_DAO_PriceField();
596 $priceField->price_set_id = $priceSetId;
597 $priceField->find();
598
599 $priceFields = array();
600
601 if ($allowNoneSelection) {
602 $noneSelectedPriceFields = array();
603 }
604
605 while ($priceField->fetch()) {
606 $key = "price_{$priceField->id}";
607
608 if ($allowNoneSelection) {
609 if (array_key_exists($key, $fields)) {
610 if ($fields[$key] == 0 && !$priceField->is_required) {
611 $noneSelectedPriceFields[] = $priceField->id;
612 }
613 }
614 }
615
616 if (CRM_Utils_Array::value($key, $fields)) {
617 $priceFields[$priceField->id] = $fields[$key];
618 }
619 }
620
621 if (!empty($priceFields)) {
622 // we should has to have positive amount.
623 $sql = "
624 SELECT id, html_type
625 FROM civicrm_price_field
626 WHERE id IN (" . implode(',', array_keys($priceFields)) . ')';
627 $fieldDAO = CRM_Core_DAO::executeQuery($sql);
628 $htmlTypes = array();
629 while ($fieldDAO->fetch()) {
630 $htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
631 }
632
633 $selectedAmounts = array();
634
635 foreach ($htmlTypes as $fieldId => $type) {
636 $options = array();
637 CRM_Price_BAO_PriceFieldValue::getValues($fieldId, $options);
638
639 if (empty($options)) {
640 continue;
641 }
642
643 if ($type == 'Text') {
644 foreach ($options as $opId => $option) {
645 $selectedAmounts[$opId] = $priceFields[$fieldId] * $option['amount'];
646 break;
647 }
648 }
649 elseif (is_array($fields["price_{$fieldId}"])) {
650 foreach (array_keys($fields["price_{$fieldId}"]) as $opId) {
651 $selectedAmounts[$opId] = $options[$opId]['amount'];
652 }
653 }
654 elseif (in_array($fields["price_{$fieldId}"], array_keys($options))) {
655 $selectedAmounts[$fields["price_{$fieldId}"]] = $options[$fields["price_{$fieldId}"]]['amount'];
656 }
657 }
658
659 list($componentName) = explode(':', $fields['_qf_default']);
660 // now we have all selected amount in hand.
661 $totalAmount = array_sum($selectedAmounts);
662 if ($totalAmount < 0) {
663 $error['_qf_default'] = ts('%1 amount can not be less than zero. Please select the options accordingly.', array(1 => $componentName));
664 }
665 }
666 else {
667 if ($allowNoneSelection) {
668 if (empty($noneSelectedPriceFields)) {
669 $error['_qf_default'] = ts('Please select at least one option from price set.');
670 }
671 } else {
672 $error['_qf_default'] = ts('Please select at least one option from price set.');
673 }
674 }
675 }
676 }
677