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