Merge pull request #4560 from priyankakaran26/recurring-entity-improvements
[civicrm-core.git] / CRM / Price / BAO / PriceSet.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36 /**
37 * Business object for managing price sets
38 *
39 */
40 class CRM_Price_BAO_PriceSet extends CRM_Price_DAO_PriceSet {
41
42 /**
43 * static field for default price set details
44 *
45 * @var array
46 * @static
47 */
48 static $_defaultPriceSet = NULL;
49
50 /**
51 * class constructor
52 */
53 function __construct() {
54 parent::__construct();
55 }
56
57 /**
58 * takes an associative array and creates a price set object
59 *
60 * @param array $params (reference) an assoc array of name/value pairs
61 *
62 * @return object CRM_Price_DAO_PriceSet object
63 * @access public
64 * @static
65 */
66 static function create(&$params) {
67 if(empty($params['id']) && empty($params['name'])) {
68 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 242);
69 }
70 $priceSetBAO = new CRM_Price_BAO_PriceSet();
71 $priceSetBAO->copyValues($params);
72 if (self::eventPriceSetDomainID()) {
73 $priceSetBAO->domain_id = CRM_Core_Config::domainID();
74 }
75 return $priceSetBAO->save();
76 }
77
78 /**
79 * Takes a bunch of params that are needed to match certain criteria and
80 * retrieves the relevant objects. Typically the valid params are only
81 * contact_id. We'll tweak this function to be more full featured over a period
82 * of time. This is the inverse function of create. It also stores all the retrieved
83 * values in the default array
84 *
85 * @param array $params (reference ) an assoc array of name/value pairs
86 * @param array $defaults (reference ) an assoc array to hold the flattened values
87 *
88 * @return object CRM_Price_DAO_PriceSet object
89 * @access public
90 * @static
91 */
92 static function retrieve(&$params, &$defaults) {
93 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
94 }
95
96 /**
97 * update the is_active flag in the db
98 *
99 * @param int $id id of the database record
100 * @param $isActive
101 *
102 * @internal param bool $is_active value we want to set the is_active field
103 *
104 * @return Object DAO object on sucess, null otherwise
105 * @static
106 * @access public
107 */
108 static function setIsActive($id, $isActive) {
109 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
110 }
111
112 /**
113 * Calculate the default price set id
114 * assigned to the contribution/membership etc
115 *
116 * @param string $entity
117 *
118 * @return array $defaultPriceSet default price set
119 *
120 * @access public
121 * @static
122 *
123 */
124 public static function getDefaultPriceSet($entity = 'contribution') {
125 if (!empty(self::$_defaultPriceSet[$entity])) {
126 return self::$_defaultPriceSet[$entity];
127 }
128 $entityName = 'default_contribution_amount';
129 if ($entity == 'membership') {
130 $entityName = 'default_membership_type_amount';
131 }
132
133 $sql = "
134 SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label, pfv.membership_type_id, pfv.amount, pfv.financial_type_id
135 FROM civicrm_price_set ps
136 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
137 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
138 WHERE ps.name = '{$entityName}'
139 ";
140
141 $dao = CRM_Core_DAO::executeQuery($sql);
142 self::$_defaultPriceSet[$entity] = array();
143 while ($dao->fetch()) {
144 self::$_defaultPriceSet[$entity][$dao->priceFieldValueID] = array(
145 'setID' => $dao->setID,
146 'priceFieldID' => $dao->priceFieldID,
147 'name' => $dao->name,
148 'label' => $dao->label,
149 'priceFieldValueID' => $dao->priceFieldValueID,
150 'membership_type_id' => $dao->membership_type_id,
151 'amount' => $dao->amount,
152 'financial_type_id' => $dao->financial_type_id,
153 );
154 }
155
156 return self::$_defaultPriceSet[$entity];
157 }
158
159 /**
160 * Get the price set title.
161 *
162 * @param int $id id of price set
163 *
164 * @return string title
165 *
166 * @access public
167 * @static
168 *
169 */
170 public static function getTitle($id) {
171 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
172 }
173
174 /**
175 * Return a list of all forms which use this price set.
176 *
177 * @param int $id id of price set
178 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
179 *
180 * @return array
181 */
182 public static function &getUsedBy($id, $simpleReturn = FALSE) {
183 $usedBy = $forms = $tables = array();
184 $queryString = "
185 SELECT entity_table, entity_id
186 FROM civicrm_price_set_entity
187 WHERE price_set_id = %1";
188 $params = array(1 => array($id, 'Integer'));
189 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
190
191 while ($crmFormDAO->fetch()) {
192 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
193 $tables[] = $crmFormDAO->entity_table;
194 }
195 // Return only tables
196 if ($simpleReturn == 'table') {
197 return $tables;
198 }
199 if (empty($forms)) {
200 $queryString = "
201 SELECT cli.entity_table, cli.entity_id
202 FROM civicrm_line_item cli
203 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
204 WHERE cpf.price_set_id = %1";
205 $params = array(1 => array($id, 'Integer'));
206 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
207 while ($crmFormDAO->fetch()) {
208 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
209 $tables[] = $crmFormDAO->entity_table;
210 }
211 if (empty($forms)) {
212 return $usedBy;
213 }
214 }
215 // Return only entity data
216 if ($simpleReturn == 'entity') {
217 return $forms;
218 }
219 foreach ($forms as $table => $entities) {
220 switch ($table) {
221 case 'civicrm_event':
222 $ids = implode(',', $entities);
223 $queryString = "SELECT ce.id as id, ce.title as title, ce.is_public as isPublic, ce.start_date as startDate, ce.end_date as endDate, civicrm_option_value.label as eventType, ce.is_template as isTemplate, ce.template_title as templateTitle
224 FROM civicrm_event ce
225 LEFT JOIN civicrm_option_value ON
226 ( ce.event_type_id = civicrm_option_value.value )
227 LEFT JOIN civicrm_option_group ON
228 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
229 WHERE
230 civicrm_option_group.name = 'event_type' AND
231 ce.id IN ($ids) AND
232 ce.is_active = 1;";
233 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
234 while ($crmDAO->fetch()) {
235 if ($crmDAO->isTemplate) {
236 $usedBy['civicrm_event_template'][$crmDAO->id]['title'] = $crmDAO->templateTitle;
237 $usedBy['civicrm_event_template'][$crmDAO->id]['eventType'] = $crmDAO->eventType;
238 $usedBy['civicrm_event_template'][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
239 }
240 else {
241 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
242 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
243 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
244 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
245 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
246 }
247 }
248 break;
249
250 case 'civicrm_contribution_page':
251 $ids = implode(',', $entities);
252 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
253 FROM civicrm_contribution_page cp, civicrm_financial_type ct
254 WHERE ct.id = cp.financial_type_id AND
255 cp.id IN ($ids) AND
256 cp.is_active = 1;";
257 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
258 while ($crmDAO->fetch()) {
259 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
260 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
261 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
262 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
263 }
264 break;
265
266 case 'civicrm_contribution':
267 case 'civicrm_membership':
268 case 'civicrm_participant':
269 $usedBy[$table] = 1;
270 break;
271
272 default:
273 CRM_Core_Error::fatal("$table is not supported in PriceSet::usedBy()");
274 break;
275 }
276 }
277
278 return $usedBy;
279 }
280
281 /**
282 * Delete the price set
283 *
284 * @param int $id Price Set id
285 *
286 * @return boolean false if fields exist for this set, true if the
287 * set could be deleted
288 *
289 * @access public
290 * @static
291 */
292 public static function deleteSet($id) {
293 // remove from all inactive forms
294 $usedBy = self::getUsedBy($id);
295 if (isset($usedBy['civicrm_event'])) {
296 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
297 $eventDAO = new CRM_Event_DAO_Event();
298 $eventDAO->id = $eventId;
299 $eventDAO->find();
300 while ($eventDAO->fetch()) {
301 self::removeFrom('civicrm_event', $eventDAO->id);
302 }
303 }
304 }
305
306 // delete price fields
307 $priceField = new CRM_Price_DAO_PriceField();
308 $priceField->price_set_id = $id;
309 $priceField->find();
310 while ($priceField->fetch()) {
311 // delete options first
312 CRM_Price_BAO_PriceField::deleteField($priceField->id);
313 }
314
315 $set = new CRM_Price_DAO_PriceSet();
316 $set->id = $id;
317 return $set->delete();
318 }
319
320 /**
321 * Link the price set with the specified table and id
322 *
323 * @param string $entityTable
324 * @param integer $entityId
325 * @param integer $priceSetId
326 *
327 * @return bool
328 */
329 public static function addTo($entityTable, $entityId, $priceSetId) {
330 // verify that the price set exists
331 $dao = new CRM_Price_DAO_PriceSet();
332 $dao->id = $priceSetId;
333 if (!$dao->find()) {
334 return FALSE;
335 }
336 unset($dao);
337
338 $dao = new CRM_Price_DAO_PriceSetEntity();
339 // find if this already exists
340 $dao->entity_id = $entityId;
341 $dao->entity_table = $entityTable;
342 $dao->find(TRUE);
343
344 // add or update price_set_id
345 $dao->price_set_id = $priceSetId;
346 return $dao->save();
347 }
348
349 /**
350 * Delete price set for the given entity and id
351 *
352 * @param string $entityTable
353 * @param integer $entityId
354 *
355 * @return mixed
356 */
357 public static function removeFrom($entityTable, $entityId) {
358 $dao = new CRM_Price_DAO_PriceSetEntity();
359 $dao->entity_table = $entityTable;
360 $dao->entity_id = $entityId;
361 return $dao->delete();
362 }
363
364 /**
365 * Find a price_set_id associatied with the given table, id and usedFor
366 * Used For value for events:1, contribution:2, membership:3
367 *
368 * @param string $entityTable
369 * @param int $entityId
370 * @param int $usedFor ( price set that extends/used for particular component )
371 *
372 * @param null $isQuickConfig
373 * @param null $setName
374 *
375 * @return integer|false price_set_id, or false if none found
376 */
377 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
378 if (!$entityTable || !$entityId) {
379 return FALSE;
380 }
381
382 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
383 FROM civicrm_price_set ps
384 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
385 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
386 if ($isQuickConfig) {
387 $sql .= ' AND ps.is_quick_config = 0 ';
388 }
389 $params = array(1 => array($entityTable, 'String'),
390 2 => array($entityId, 'Integer'),
391 );
392 if ($usedFor) {
393 $sql .= " AND ps.extends LIKE '%%3%' ";
394 $params[3] = array($usedFor, 'Integer');
395 }
396
397 $dao = CRM_Core_DAO::executeQuery($sql, $params);
398 $dao->fetch();
399 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
400 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
401 }
402
403 /**
404 * Find a price_set_id associated with the given option value or field ID
405 *
406 * @param array $params (reference) an assoc array of name/value pairs
407 * array may contain either option id or
408 * price field id
409 *
410 * @return integer|NULL price set id on success, null otherwise
411 * @static
412 * @access public
413 */
414 public static function getSetId(&$params) {
415 $fid = NULL;
416
417 if ($oid = CRM_Utils_Array::value('oid', $params)) {
418 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
419 $fieldValue->id = $oid;
420 if ($fieldValue->find(TRUE)) {
421 $fid = $fieldValue->price_field_id;
422 }
423 }
424 else {
425 $fid = CRM_Utils_Array::value('fid', $params);
426 }
427
428 if (isset($fid)) {
429 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
430 }
431
432 return NULL;
433 }
434
435 /**
436 * Return an associative array of all price sets
437 *
438 * @param bool $withInactive whether or not to include inactive entries
439 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
440 *
441 * @return array associative array of id => name
442 */
443 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
444 $query = '
445 SELECT
446 DISTINCT ( price_set_id ) as id, title
447 FROM
448 civicrm_price_field,
449 civicrm_price_set
450 WHERE
451 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
452
453 if (!$withInactive) {
454 $query .= ' AND civicrm_price_set.is_active = 1 ';
455 }
456
457 if (self::eventPriceSetDomainID()) {
458 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config::domainID();
459 }
460
461 $priceSets = array();
462
463 if ($extendComponentName) {
464 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
465 if (!$componentId) {
466 return $priceSets;
467 }
468 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
469 }
470
471 $dao = CRM_Core_DAO::executeQuery($query);
472 while ($dao->fetch()) {
473 $priceSets[$dao->id] = $dao->title;
474 }
475 return $priceSets;
476 }
477
478 /**
479 * Get price set details
480 *
481 * An array containing price set details (including price fields) is returned
482 *
483 * @param $setID
484 * @param bool $required
485 * @param bool $validOnly
486 *
487 * @internal param int $setId - price set id whose details are needed
488 *
489 * @return array $setTree - array consisting of field details
490 */
491 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
492 // create a new tree
493 $setTree = array();
494
495 $priceFields = array(
496 'id',
497 'name',
498 'label',
499 'html_type',
500 'is_enter_qty',
501 'help_pre',
502 'help_post',
503 'weight',
504 'is_display_amounts',
505 'options_per_line',
506 'is_active',
507 'active_on',
508 'expire_on',
509 'javascript',
510 'visibility_id',
511 'is_required',
512 );
513 if ($required == TRUE) {
514 $priceFields[] = 'is_required';
515 }
516
517 // create select
518 $select = 'SELECT ' . implode(',', $priceFields);
519 $from = ' FROM civicrm_price_field';
520
521 $params = array();
522 $params[1] = array($setID, 'Integer');
523 $where = '
524 WHERE price_set_id = %1
525 AND is_active = 1
526 ';
527 $dateSelect = '';
528 if ($validOnly) {
529 $currentTime = date('YmdHis');
530 $dateSelect = "
531 AND ( active_on IS NULL OR active_on <= {$currentTime} )
532 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
533 ";
534 }
535
536 $orderBy = ' ORDER BY weight';
537
538 $sql = $select . $from . $where . $dateSelect . $orderBy;
539
540 $dao = CRM_Core_DAO::executeQuery($sql, $params);
541
542 $visibility = CRM_Core_PseudoConstant::visibility('name');
543 while ($dao->fetch()) {
544 $fieldID = $dao->id;
545
546 $setTree[$setID]['fields'][$fieldID] = array();
547 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
548
549 foreach ($priceFields as $field) {
550 if ($field == 'id' || is_null($dao->$field)) {
551 continue;
552 }
553
554 if ($field == 'visibility_id') {
555 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
556 }
557 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
558 }
559 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE);
560 }
561
562 // also get the pre and post help from this price set
563 $sql = "
564 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
565 FROM civicrm_price_set
566 WHERE id = %1";
567 $dao = CRM_Core_DAO::executeQuery($sql, $params);
568 if ($dao->fetch()) {
569 $setTree[$setID]['extends'] = $dao->extends;
570 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
571 $setTree[$setID]['help_pre'] = $dao->help_pre;
572 $setTree[$setID]['help_post'] = $dao->help_post;
573 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
574 }
575 return $setTree;
576 }
577
578 /**
579 * Get the Price Field ID. We call this function when more than one being present would represent an error
580 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
581 * @param array $priceSet
582 *
583 * @throws CRM_Core_Exception
584 * @return int
585 */
586 static function getOnlyPriceFieldID(array $priceSet) {
587 if(count($priceSet['fields']) > 1) {
588 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
589 }
590 return (int) implode('_', array_keys($priceSet['fields']));
591 }
592
593 /**
594 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
595 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
596 * @param array $priceSet
597 *
598 * @throws CRM_Core_Exception
599 * @return int
600 */
601 static function getOnlyPriceFieldValueID(array $priceSet) {
602 $priceFieldID = self::getOnlyPriceFieldID($priceSet);
603 if(count($priceSet['fields'][$priceFieldID]['options']) > 1) {
604 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
605 }
606 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
607 }
608
609
610 /**
611 * @param CRM_Core_Form $form
612 * @param $id
613 * @param string $entityTable
614 * @param bool $validOnly
615 * @param null $priceSetId
616 *
617 * @return bool|false|int|null
618 */
619 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
620 if (!$priceSetId) {
621 $priceSetId = self::getFor($entityTable, $id);
622 }
623
624 //check if priceset is is_config
625 if (is_numeric($priceSetId)) {
626 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
627 $form->assign('quickConfig', 1);
628 }
629 }
630 // get price info
631 if ($priceSetId) {
632 if ($form->_action & CRM_Core_Action::UPDATE) {
633 $entityId = $entity = NULL;
634
635 switch ($entityTable) {
636 case 'civicrm_event':
637 $entity = 'participant';
638 if (CRM_Utils_System::getClassName($form) == 'CRM_Event_Form_Participant') {
639 $entityId = $form->_id;
640 }
641 else {
642 $entityId = $form->_participantId;
643 }
644 break;
645
646 case 'civicrm_contribution_page':
647 case 'civicrm_contribution':
648 $entity = 'contribution';
649 $entityId = $form->_id;
650 break;
651 }
652
653 if ($entityId && $entity) {
654 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
655 }
656 $required = FALSE;
657 }
658 else {
659 $required = TRUE;
660 }
661
662 $form->_priceSetId = $priceSetId;
663 $priceSet = self::getSetDetail($priceSetId, $required, $validOnly);
664 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
665 $form->_values['fee'] = CRM_Utils_Array::value('fields', $form->_priceSet);
666
667 //get the price set fields participant count.
668 if ($entityTable == 'civicrm_event') {
669 //get option count info.
670 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
671 if ($form->_priceSet['optionsCountTotal']) {
672 $optionsCountDeails = array();
673 if (!empty($form->_priceSet['fields'])) {
674 foreach ($form->_priceSet['fields'] as $field) {
675 foreach ($field['options'] as $option) {
676 $count = CRM_Utils_Array::value('count', $option, 0);
677 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
678 }
679 }
680 }
681 $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
682 }
683
684 //get option max value info.
685 $optionsMaxValueTotal = 0;
686 $optionsMaxValueDetails = array();
687
688 if (!empty($form->_priceSet['fields'])) {
689 foreach ($form->_priceSet['fields'] as $field) {
690 foreach ($field['options'] as $option) {
691 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
692 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
693 $optionsMaxValueTotal += $maxVal;
694 }
695 }
696 }
697
698 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
699 if ($optionsMaxValueTotal) {
700 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
701 }
702 }
703 $form->set('priceSetId', $form->_priceSetId);
704 $form->set('priceSet', $form->_priceSet);
705
706 return $priceSetId;
707 }
708 return FALSE;
709 }
710
711 /**
712 * @param $fields
713 * @param $params
714 * @param $lineItem
715 * @param string $component
716 */
717 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
718 // using price set
719 $totalPrice = $totalTax = 0;
720 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
721 if ($component) {
722 $autoRenew = array();
723 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
724 }
725 foreach ($fields as $id => $field) {
726 if (empty($params["price_{$id}"]) ||
727 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
728 ) {
729 // skip if nothing was submitted for this field
730 continue;
731 }
732
733 switch ($field['html_type']) {
734 case 'Text':
735 $firstOption = reset($field['options']);
736 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
737 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
738 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
739 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
740 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
741 }
742 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
743 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
744 if (array_key_exists($params['financial_type_id'], $taxRates)) {
745 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
746 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
747 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
748 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
749 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
750 }
751 }
752 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
753 break;
754
755 case 'Radio':
756 //special case if user select -none-
757 if ($params["price_{$id}"] <= 0) {
758 continue;
759 }
760 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
761 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
762 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
763 $params['amount_priceset_level_radio'] = array();
764 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
765 if (isset($radioLevel)) {
766 $radioLevel = array_merge($radioLevel,
767 array_keys($params['amount_priceset_level_radio'])
768 );
769 }
770 else {
771 $radioLevel = array_keys($params['amount_priceset_level_radio']);
772 }
773 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
774 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
775 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
776 $totalTax += $field['options'][$optionValueId]['tax_amount'];
777 if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
778 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
779 }
780 }
781 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
782 if (
783 $component &&
784 // auto_renew exists and is empty in some workflows, which php treat as a 0
785 // and hence we explicitly check to see if auto_renew is numeric
786 isset($lineItem[$optionValueId]['auto_renew']) &&
787 is_numeric($lineItem[$optionValueId]['auto_renew'])
788 ) {
789 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
790 }
791 break;
792
793 case 'Select':
794 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
795 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
796 $optionLabel = $field['options'][$optionValueId]['label'];
797 $params['amount_priceset_level_select'] = array();
798 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
799 if (isset($selectLevel)) {
800 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
801 }
802 else {
803 $selectLevel = array_keys($params['amount_priceset_level_select']);
804 }
805 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
806 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
807 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
808 $totalTax += $field['options'][$optionValueId]['tax_amount'];
809 }
810 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
811 if (
812 $component &&
813 isset($lineItem[$optionValueId]['auto_renew']) &&
814 is_numeric($lineItem[$optionValueId]['auto_renew'])
815 ) {
816 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
817 }
818 break;
819
820 case 'CheckBox':
821 $params['amount_priceset_level_checkbox'] = $optionIds = array();
822 foreach ($params["price_{$id}"] as $optionId => $option) {
823 $optionIds[] = $optionId;
824 $optionLabel = $field['options'][$optionId]['label'];
825 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
826 if (isset($checkboxLevel)) {
827 $checkboxLevel = array_unique(array_merge(
828 $checkboxLevel,
829 array_keys($params['amount_priceset_level_checkbox'])
830 )
831 );
832 }
833 else {
834 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
835 }
836 }
837 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
838 foreach ($optionIds as $optionId) {
839 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
840 $lineItem = self::setLineItem($field, $lineItem, $optionId);
841 $totalTax += $field['options'][$optionId]['tax_amount'];
842 }
843 $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
844 if (
845 $component &&
846 isset($lineItem[$optionId]['auto_renew']) &&
847 is_numeric($lineItem[$optionId]['auto_renew'])
848 ) {
849 $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
850 }
851 }
852 break;
853 }
854 }
855
856 $amount_level = array();
857 $totalParticipant = 0;
858 if (is_array($lineItem)) {
859 foreach ($lineItem as $values) {
860 $totalParticipant += $values['participant_count'];
861 if ($values['html_type'] == 'Text') {
862 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
863 continue;
864 }
865 $amount_level[] = $values['label'];
866 }
867 }
868
869 $displayParticipantCount = '';
870 if ($totalParticipant > 0) {
871 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
872 }
873 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
874 $params['amount'] = $totalPrice;
875 $params['tax_amount'] = $totalTax;
876 if ($component) {
877 foreach ($autoRenew as $dontCare => $eachAmount) {
878 if (!$eachAmount) {
879 unset($autoRenew[$dontCare]);
880 }
881 }
882 if (count($autoRenew) > 1 ) {
883 $params['autoRenew'] = $autoRenew;
884 }
885 }
886 }
887
888 /**
889 * Function to build the price set form.
890 *
891 * @param CRM_Core_Form $form
892 *
893 * @return void
894 * @access public
895 */
896 static function buildPriceSet(&$form) {
897 $priceSetId = $form->get('priceSetId');
898 $userid = $form->getVar('_userID');
899 if (!$priceSetId) {
900 return;
901 }
902
903 $validFieldsOnly = TRUE;
904 $className = CRM_Utils_System::getClassName($form);
905 if (in_array($className, array(
906 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
907 $validFieldsOnly = FALSE;
908 }
909
910 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
911 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
912 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
913 $form->_quickConfig = $quickConfig = 0;
914 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
915 $quickConfig = 1;
916 }
917
918 $form->assign('quickConfig', $quickConfig);
919 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
920 $form->_quickConfig = $quickConfig;
921 }
922 $form->assign('priceSet', $form->_priceSet);
923
924 $component = 'contribution';
925 if ($className == 'CRM_Member_Form_Membership') {
926 $component = 'membership';
927 }
928
929 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
930 $feeBlock = &$form->_values['fee'];
931 if (!empty($form->_useForMember)) {
932 $component = 'membership';
933 }
934 }
935 else {
936 $feeBlock = &$form->_priceSet['fields'];
937 }
938
939 // call the hook.
940 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
941
942 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
943 $adminFieldVisible = false;
944 if (CRM_Core_Permission::check('administer CiviCRM')) {
945 $adminFieldVisible = true;
946 }
947
948 foreach ($feeBlock as $id => $field) {
949 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
950 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
951 !$validFieldsOnly
952 ) {
953 $options = CRM_Utils_Array::value('options', $field);
954 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
955 $checklifetime = self::checkCurrentMembership($options, $userid);
956 if ($checklifetime) {
957 $form->assign('ispricelifetime', TRUE);
958 }
959 }
960 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
961 continue;
962 }
963 CRM_Price_BAO_PriceField::addQuickFormElement($form,
964 'price_' . $field['id'],
965 $field['id'],
966 FALSE,
967 CRM_Utils_Array::value('is_required', $field, FALSE),
968 NULL,
969 $options
970 );
971 }
972 }
973 }
974
975 /**
976 * Function to check the current Membership
977 * having end date null.
978 */
979 static function checkCurrentMembership(&$options, $userid) {
980 if (!$userid || empty($options)) {
981 return;
982 }
983 static $_contact_memberships = array();
984 $checklifetime = FALSE;
985 foreach ($options as $key => $value) {
986 if (!empty($value['membership_type_id'])) {
987 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
988 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
989 }
990 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
991 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
992 unset($options[$key]);
993 $checklifetime = TRUE;
994 }
995 }
996 }
997 if ($checklifetime) {
998 return TRUE;
999 }
1000 else {
1001 return FALSE;
1002 }
1003 }
1004
1005 /**
1006 * Function to set daefult the price set fields.
1007 *
1008 * @param $form
1009 * @param $defaults
1010 *
1011 * @return array $defaults
1012 * @access public
1013 */
1014 static function setDefaultPriceSet(&$form, &$defaults) {
1015 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
1016 return $defaults;
1017 }
1018
1019 foreach ($form->_priceSet['fields'] as $key => $val) {
1020 foreach ($val['options'] as $keys => $values) {
1021 if ($values['is_default']) {
1022 if ($val['html_type'] == 'CheckBox') {
1023 $defaults["price_{$key}"][$keys] = 1;
1024 }
1025 else {
1026 $defaults["price_{$key}"] = $keys;
1027 }
1028 }
1029 }
1030 }
1031 return $defaults;
1032 }
1033
1034 /**
1035 * Supports event create function by setting up required price sets, not tested but expect
1036 * it will work for contribution page
1037 * @param array $params as passed to api/bao create fn
1038 * @param CRM_Core_DAO $entity object for given entity
1039 * @param string $entityName name of entity - e.g event
1040 */
1041 static function setPriceSets(&$params, $entity, $entityName) {
1042 if(empty($params['price_set_id']) || !is_array($params['price_set_id'])) {
1043 return;
1044 }
1045 // CRM-14069 note that we may as well start by assuming more than one.
1046 // currently the form does not pass in as an array & will be skipped
1047 // test is passing in as an array but I feel the api should have a metadata that allows
1048 // transform of single to array - seems good for managing transitions - in which case all api
1049 // calls that set price_set_id will hit this
1050 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1051 // all separated values, strings, json half-separated values (in participant we hit this)
1052 // to be converted to json @ api layer
1053 $pse = new CRM_Price_DAO_PriceSetEntity();
1054 $pse->entity_table = 'civicrm_' . $entityName;
1055 $pse->entity_id = $entity->id;
1056 while ($pse->fetch()) {
1057 if(!in_array($pse->price_set_id, $params['price_set_id'])) {
1058 // note an even more aggressive form of this deletion currently happens in event form
1059 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1060 // on the participant record
1061 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_' . $entityName, $entity->id)) {
1062 CRM_Core_BAO_Discount::del($entity->id,'civicrm_' . $entityName);
1063 }
1064 }
1065 }
1066 foreach ($params['price_set_id'] as $priceSetID) {
1067 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $entityName, $entity->id, $priceSetID);
1068 //@todo - how should we do this - copied from form
1069 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1070 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1071 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1072 //}
1073 }
1074 }
1075 /**
1076 * Get field ids of a price set
1077 *
1078 * @param int $id Price Set id
1079 *
1080 * @return array of the field ids
1081 *
1082 * @access public
1083 * @static
1084 */
1085 public static function getFieldIds($id) {
1086 $priceField = new CRM_Price_DAO_PriceField();
1087 $priceField->price_set_id = $id;
1088 $priceField->find();
1089 while ($priceField->fetch()) {
1090 $var[] = $priceField->id;
1091 }
1092 return $var;
1093 }
1094
1095 /**
1096 * This function is to make a copy of a price set, including
1097 * all the fields
1098 *
1099 * @param int $id the price set id to copy
1100 *
1101 * @return the copy object
1102 * @access public
1103 * @static
1104 */
1105 static function copy($id) {
1106 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1107
1108 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
1109 $fieldsFix = array(
1110 'suffix' => array('title' => ' ' . $title,
1111 'name' => '__Copy_id_' . ($maxId + 1) . '_',
1112 ),
1113 );
1114
1115 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
1116 array('id' => $id),
1117 NULL,
1118 $fieldsFix
1119 );
1120
1121 //copying all the blocks pertaining to the price set
1122 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
1123 array('price_set_id' => $id),
1124 array('price_set_id' => $copy->id)
1125 );
1126 if (!empty($copyPriceField)) {
1127 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1128
1129 //copy option group and values
1130 foreach ($price as $originalId => $copyId) {
1131 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1132 array('price_field_id' => $originalId),
1133 array('price_field_id' => $copyId)
1134 );
1135 }
1136 }
1137 $copy->save();
1138
1139 CRM_Utils_Hook::copy('Set', $copy);
1140 return $copy;
1141 }
1142
1143 /**
1144 * This function is to check price set permission
1145 *
1146 * @param int $sid the price set id
1147 *
1148 * @return bool
1149 */
1150 static function checkPermission($sid) {
1151 if ($sid && self::eventPriceSetDomainID()) {
1152 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1153 if (CRM_Core_Config::domainID() != $domain_id) {
1154 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
1155 }
1156 }
1157 return TRUE;
1158 }
1159
1160 /**
1161 * Get the sum of participant count
1162 * for all fields of given price set.
1163 *
1164 * @param int $sid the price set id
1165 *
1166 * @param bool $onlyActive
1167 *
1168 * @return int|null|string
1169 * @access public
1170 * @static
1171 */
1172 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1173 $count = 0;
1174 if (!$sid) {
1175 return $count;
1176 }
1177
1178 $where = NULL;
1179 if ($onlyActive) {
1180 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1181 }
1182
1183 static $pricesetFieldCount = array();
1184 if (!isset($pricesetFieldCount[$sid])) {
1185 $sql = "
1186 SELECT sum(value.count) as totalCount
1187 FROM civicrm_price_field_value value
1188 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1189 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1190 WHERE pset.id = %1
1191 $where";
1192
1193 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1194 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1195 }
1196
1197 return $pricesetFieldCount[$sid];
1198 }
1199
1200 /**
1201 * @param $ids
1202 *
1203 * @return array
1204 */
1205 public static function getMembershipCount($ids) {
1206 $queryString = "
1207 SELECT count( pfv.id ) AS count, pfv.id AS id
1208 FROM civicrm_price_field_value pfv
1209 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1210 WHERE pfv.id IN ( $ids )
1211 GROUP BY mt.member_of_contact_id";
1212
1213 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1214 $count = array();
1215
1216 while ($crmDAO->fetch()) {
1217 $count[$crmDAO->id] = $crmDAO->count;
1218 }
1219
1220 return $count;
1221 }
1222
1223 /**
1224 * Function to check if auto renew option should be shown
1225 *
1226 * @param int $priceSetId price set id
1227 *
1228 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1229 */
1230 public static function checkAutoRenewForPriceSet($priceSetId) {
1231 // auto-renew option should be visible if membership types associated with all the fields has
1232 // been set for auto-renew option
1233 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1234
1235 // get the membership type auto renew option and check if required or optional
1236 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1237 FROM civicrm_price_field_value pfv
1238 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1239 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1240 WHERE pf.price_set_id = %1
1241 AND pf.is_active = 1
1242 AND pfv.is_active = 1';
1243
1244 $params = array(1 => array($priceSetId, 'Integer'));
1245
1246 $dao = CRM_Core_DAO::executeQuery($query, $params);
1247 $autoRenewOption = 2;
1248 $interval = $unit = array();
1249 while ($dao->fetch()) {
1250 if (!$dao->auto_renew) {
1251 $autoRenewOption = 0;
1252 break;
1253 }
1254 if ($dao->auto_renew == 1) {
1255 $autoRenewOption = 1;
1256 }
1257
1258 $interval[$dao->duration_interval] = $dao->duration_interval;
1259 $unit[$dao->duration_unit] = $dao->duration_unit;
1260 }
1261
1262 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1263 return $autoRenewOption;
1264 }
1265 else {
1266 return 0;
1267 }
1268 }
1269
1270 /**
1271 * Function to retrieve auto renew frequency and interval
1272 *
1273 * @param int $priceSetId price set id
1274 *
1275 * @return array associate array of frequency interval and unit
1276 * @static
1277 * @access public
1278 */
1279 public static function getRecurDetails($priceSetId) {
1280 $query = 'SELECT mt.duration_interval, mt.duration_unit
1281 FROM civicrm_price_field_value pfv
1282 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1283 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1284 WHERE pf.price_set_id = %1 LIMIT 1';
1285
1286 $params = array(1 => array($priceSetId, 'Integer'));
1287 $dao = CRM_Core_DAO::executeQuery($query, $params);
1288 $dao->fetch();
1289 return array($dao->duration_interval, $dao->duration_unit);
1290 }
1291
1292 /**
1293 * @return object
1294 */
1295 static function eventPriceSetDomainID() {
1296 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1297 'event_price_set_domain_id',
1298 NULL, FALSE
1299 );
1300 }
1301
1302 /**
1303 * update the is_quick_config flag in the db
1304 *
1305 * @param int $id id of the database record
1306 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1307 *
1308 * @return Object DAO object on sucess, null otherwise
1309 * @static
1310 * @access public
1311 */
1312 static function setIsQuickConfig($id, $isQuickConfig) {
1313 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1314 }
1315
1316 /**
1317 * Check if price set id provides option for
1318 * user to select both auto-renew and non-auto-renew memberships
1319 *
1320 * @access public
1321 * @static
1322 *
1323 */
1324 public static function checkMembershipPriceSet($id) {
1325 $query =
1326 "
1327 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1328 FROM civicrm_price_field_value pfv
1329 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1330 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1331 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1332 WHERE ps.id = %1
1333 ";
1334
1335 $params = array(1 => array($id, 'Integer'));
1336 $dao = CRM_Core_DAO::executeQuery($query, $params);
1337
1338 $autoRenew = array();
1339 //FIXME: do a comprehensive check of whether
1340 //2 membership types can be selected
1341 //instead of comparing all of them
1342 while ($dao->fetch()) {
1343 //temp fix for #CRM-10370
1344 //if its NULL consider it '0' i.e. 'No auto-renew option'
1345 $daoAutoRenew = $dao->auto_renew;
1346 if ($daoAutoRenew === NULL) {
1347 $daoAutoRenew = 0;
1348 }
1349 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1350 return true;
1351 }
1352 $autoRenew[] = $daoAutoRenew;
1353 }
1354 return false;
1355 }
1356
1357 /**
1358 * Copy priceSet when event/contibution page is copied
1359 *
1360 * @params string $baoName BAO name
1361 * @params int $id old event/contribution page id
1362 * @params int $newId newly created event/contribution page id
1363 *
1364 * @param string $baoName
1365 * @param integer $id
1366 * @param integer $newId
1367 */
1368 static function copyPriceSet($baoName, $id, $newId) {
1369 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
1370 if ($priceSetId) {
1371 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1372 if($isQuickConfig) {
1373 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($priceSetId);
1374 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
1375 }
1376 else {
1377 $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1378 array(
1379 'entity_id' => $id,
1380 'entity_table' => $baoName,
1381 ),
1382 array('entity_id' => $newId)
1383 );
1384 }
1385 // copy event discount
1386 if ($baoName == 'civicrm_event') {
1387 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1388 foreach ($discount as $discountId => $setId) {
1389
1390 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
1391
1392 CRM_Core_DAO::copyGeneric(
1393 'CRM_Core_DAO_Discount',
1394 array(
1395 'id' => $discountId,
1396 ),
1397 array(
1398 'entity_id' => $newId,
1399 'price_set_id' => $copyPriceSet->id,
1400 )
1401 );
1402 }
1403 }
1404 }
1405 }
1406
1407 /*
1408 * Function to set tax_amount and tax_rate in LineItem
1409 *
1410 *
1411 */
1412 static function setLineItem($field, $lineItem, $optionValueId) {
1413 if ($field['html_type'] == 'Text') {
1414 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1415 }
1416 else {
1417 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1418 }
1419 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1420 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1421 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1422
1423 return $lineItem;
1424 }
1425 }
1426