3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business object for managing price sets
40 class CRM_Price_BAO_PriceSet
extends CRM_Price_DAO_PriceSet
{
43 * Static field for default price set details
48 static $_defaultPriceSet = NULL;
53 function __construct() {
54 parent
::__construct();
58 * Takes an associative array and creates a price set object
60 * @param array $params (reference) an assoc array of name/value pairs
62 * @return CRM_Price_DAO_PriceSet object
66 static function create(&$params) {
67 if(empty($params['id']) && empty($params['name'])) {
68 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
70 $priceSetBAO = new CRM_Price_BAO_PriceSet();
71 $priceSetBAO->copyValues($params);
72 if (self
::eventPriceSetDomainID()) {
73 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
75 return $priceSetBAO->save();
79 * Fetch object based on array of properties
81 * @param array $params (reference ) an assoc array of name/value pairs
82 * @param array $defaults (reference ) an assoc array to hold the flattened values
84 * @return CRM_Price_DAO_PriceSet object
88 static function retrieve(&$params, &$defaults) {
89 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
93 * Update the is_active flag in the db
95 * @param int $id id of the database record
98 * @internal param bool $is_active value we want to set the is_active field
100 * @return Object DAO object on sucess, null otherwise
104 static function setIsActive($id, $isActive) {
105 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
109 * Calculate the default price set id
110 * assigned to the contribution/membership etc
112 * @param string $entity
114 * @return array $defaultPriceSet default price set
120 public static function getDefaultPriceSet($entity = 'contribution') {
121 if (!empty(self
::$_defaultPriceSet[$entity])) {
122 return self
::$_defaultPriceSet[$entity];
124 $entityName = 'default_contribution_amount';
125 if ($entity == 'membership') {
126 $entityName = 'default_membership_type_amount';
130 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
131 FROM civicrm_price_set ps
132 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
133 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
134 WHERE ps.name = '{$entityName}'
137 $dao = CRM_Core_DAO
::executeQuery($sql);
138 self
::$_defaultPriceSet[$entity] = array();
139 while ($dao->fetch()) {
140 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
141 'setID' => $dao->setID
,
142 'priceFieldID' => $dao->priceFieldID
,
143 'name' => $dao->name
,
144 'label' => $dao->label
,
145 'priceFieldValueID' => $dao->priceFieldValueID
,
146 'membership_type_id' => $dao->membership_type_id
,
147 'amount' => $dao->amount
,
148 'financial_type_id' => $dao->financial_type_id
,
152 return self
::$_defaultPriceSet[$entity];
156 * Get the price set title.
158 * @param int $id id of price set
160 * @return string title
166 public static function getTitle($id) {
167 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
171 * Return a list of all forms which use this price set.
173 * @param int $id id of price set
174 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
178 public static function &getUsedBy($id, $simpleReturn = FALSE) {
179 $usedBy = $forms = $tables = array();
181 SELECT entity_table, entity_id
182 FROM civicrm_price_set_entity
183 WHERE price_set_id = %1";
184 $params = array(1 => array($id, 'Integer'));
185 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
187 while ($crmFormDAO->fetch()) {
188 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
189 $tables[] = $crmFormDAO->entity_table
;
191 // Return only tables
192 if ($simpleReturn == 'table') {
197 SELECT cli.entity_table, cli.entity_id
198 FROM civicrm_line_item cli
199 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
200 WHERE cpf.price_set_id = %1";
201 $params = array(1 => array($id, 'Integer'));
202 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
203 while ($crmFormDAO->fetch()) {
204 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
205 $tables[] = $crmFormDAO->entity_table
;
211 // Return only entity data
212 if ($simpleReturn == 'entity') {
215 foreach ($forms as $table => $entities) {
217 case 'civicrm_event':
218 $ids = implode(',', $entities);
219 $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
220 FROM civicrm_event ce
221 LEFT JOIN civicrm_option_value ON
222 ( ce.event_type_id = civicrm_option_value.value )
223 LEFT JOIN civicrm_option_group ON
224 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
226 civicrm_option_group.name = 'event_type' AND
229 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
230 while ($crmDAO->fetch()) {
231 if ($crmDAO->isTemplate
) {
232 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
233 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
234 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
237 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
238 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
239 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
240 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
241 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
246 case 'civicrm_contribution_page':
247 $ids = implode(',', $entities);
248 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
249 FROM civicrm_contribution_page cp, civicrm_financial_type ct
250 WHERE ct.id = cp.financial_type_id AND
253 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
254 while ($crmDAO->fetch()) {
255 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
256 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
257 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
258 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
262 case 'civicrm_contribution':
263 case 'civicrm_membership':
264 case 'civicrm_participant':
269 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
278 * Delete the price set
280 * @param int $id Price Set id
282 * @return boolean false if fields exist for this set, true if the
283 * set could be deleted
288 public static function deleteSet($id) {
289 // remove from all inactive forms
290 $usedBy = self
::getUsedBy($id);
291 if (isset($usedBy['civicrm_event'])) {
292 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
293 $eventDAO = new CRM_Event_DAO_Event();
294 $eventDAO->id
= $eventId;
296 while ($eventDAO->fetch()) {
297 self
::removeFrom('civicrm_event', $eventDAO->id
);
302 // delete price fields
303 $priceField = new CRM_Price_DAO_PriceField();
304 $priceField->price_set_id
= $id;
306 while ($priceField->fetch()) {
307 // delete options first
308 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
311 $set = new CRM_Price_DAO_PriceSet();
313 return $set->delete();
317 * Link the price set with the specified table and id
319 * @param string $entityTable
320 * @param integer $entityId
321 * @param integer $priceSetId
325 public static function addTo($entityTable, $entityId, $priceSetId) {
326 // verify that the price set exists
327 $dao = new CRM_Price_DAO_PriceSet();
328 $dao->id
= $priceSetId;
334 $dao = new CRM_Price_DAO_PriceSetEntity();
335 // find if this already exists
336 $dao->entity_id
= $entityId;
337 $dao->entity_table
= $entityTable;
340 // add or update price_set_id
341 $dao->price_set_id
= $priceSetId;
346 * Delete price set for the given entity and id
348 * @param string $entityTable
349 * @param integer $entityId
353 public static function removeFrom($entityTable, $entityId) {
354 $dao = new CRM_Price_DAO_PriceSetEntity();
355 $dao->entity_table
= $entityTable;
356 $dao->entity_id
= $entityId;
357 return $dao->delete();
361 * Find a price_set_id associatied with the given table, id and usedFor
362 * Used For value for events:1, contribution:2, membership:3
364 * @param string $entityTable
365 * @param int $entityId
366 * @param int $usedFor ( price set that extends/used for particular component )
368 * @param null $isQuickConfig
369 * @param null $setName
371 * @return integer|false price_set_id, or false if none found
373 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
374 if (!$entityTable ||
!$entityId) {
378 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
379 FROM civicrm_price_set ps
380 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
381 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
382 if ($isQuickConfig) {
383 $sql .= ' AND ps.is_quick_config = 0 ';
385 $params = array(1 => array($entityTable, 'String'),
386 2 => array($entityId, 'Integer'),
389 $sql .= " AND ps.extends LIKE '%%3%' ";
390 $params[3] = array($usedFor, 'Integer');
393 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
395 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
396 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
400 * Find a price_set_id associated with the given option value or field ID
402 * @param array $params (reference) an assoc array of name/value pairs
403 * array may contain either option id or
406 * @return integer|NULL price set id on success, null otherwise
410 public static function getSetId(&$params) {
413 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
414 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
415 $fieldValue->id
= $oid;
416 if ($fieldValue->find(TRUE)) {
417 $fid = $fieldValue->price_field_id
;
421 $fid = CRM_Utils_Array
::value('fid', $params);
425 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
432 * Return an associative array of all price sets
434 * @param bool $withInactive whether or not to include inactive entries
435 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
437 * @return array associative array of id => name
439 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
442 DISTINCT ( price_set_id ) as id, title
447 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
449 if (!$withInactive) {
450 $query .= ' AND civicrm_price_set.is_active = 1 ';
453 if (self
::eventPriceSetDomainID()) {
454 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
457 $priceSets = array();
459 if ($extendComponentName) {
460 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
464 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
467 $dao = CRM_Core_DAO
::executeQuery($query);
468 while ($dao->fetch()) {
469 $priceSets[$dao->id
] = $dao->title
;
475 * Get price set details
477 * An array containing price set details (including price fields) is returned
480 * @param bool $required
481 * @param bool $validOnly
483 * @internal param int $setId - price set id whose details are needed
485 * @return array $setTree - array consisting of field details
487 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
491 $priceFields = array(
500 'is_display_amounts',
509 if ($required == TRUE) {
510 $priceFields[] = 'is_required';
514 $select = 'SELECT ' . implode(',', $priceFields);
515 $from = ' FROM civicrm_price_field';
518 $params[1] = array($setID, 'Integer');
520 WHERE price_set_id = %1
525 $currentTime = date('YmdHis');
527 AND ( active_on IS NULL OR active_on <= {$currentTime} )
528 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
532 $orderBy = ' ORDER BY weight';
534 $sql = $select . $from . $where . $dateSelect . $orderBy;
536 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
538 $visibility = CRM_Core_PseudoConstant
::visibility('name');
539 while ($dao->fetch()) {
542 $setTree[$setID]['fields'][$fieldID] = array();
543 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
545 foreach ($priceFields as $field) {
546 if ($field == 'id' ||
is_null($dao->$field)) {
550 if ($field == 'visibility_id') {
551 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
553 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
555 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
558 // also get the pre and post help from this price set
560 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
561 FROM civicrm_price_set
563 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
565 $setTree[$setID]['extends'] = $dao->extends;
566 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
567 $setTree[$setID]['help_pre'] = $dao->help_pre
;
568 $setTree[$setID]['help_post'] = $dao->help_post
;
569 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
575 * Get the Price Field ID. We call this function when more than one being present would represent an error
576 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
577 * @param array $priceSet
579 * @throws CRM_Core_Exception
582 static function getOnlyPriceFieldID(array $priceSet) {
583 if(count($priceSet['fields']) > 1) {
584 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
586 return (int) implode('_', array_keys($priceSet['fields']));
590 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
591 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
592 * @param array $priceSet
594 * @throws CRM_Core_Exception
597 static function getOnlyPriceFieldValueID(array $priceSet) {
598 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
599 if(count($priceSet['fields'][$priceFieldID]['options']) > 1) {
600 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
602 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
607 * @param CRM_Core_Form $form
609 * @param string $entityTable
610 * @param bool $validOnly
611 * @param int $priceSetId
613 * @return bool|false|int|null
615 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
617 $priceSetId = self
::getFor($entityTable, $id);
620 //check if priceset is is_config
621 if (is_numeric($priceSetId)) {
622 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
623 $form->assign('quickConfig', 1);
628 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
629 $entityId = $entity = NULL;
631 switch ($entityTable) {
632 case 'civicrm_event':
633 $entity = 'participant';
634 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
635 $entityId = $form->_id
;
638 $entityId = $form->_participantId
;
642 case 'civicrm_contribution_page':
643 case 'civicrm_contribution':
644 $entity = 'contribution';
645 $entityId = $form->_id
;
649 if ($entityId && $entity) {
650 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
658 $form->_priceSetId
= $priceSetId;
659 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
660 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
661 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
663 //get the price set fields participant count.
664 if ($entityTable == 'civicrm_event') {
665 //get option count info.
666 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
667 if ($form->_priceSet
['optionsCountTotal']) {
668 $optionsCountDeails = array();
669 if (!empty($form->_priceSet
['fields'])) {
670 foreach ($form->_priceSet
['fields'] as $field) {
671 foreach ($field['options'] as $option) {
672 $count = CRM_Utils_Array
::value('count', $option, 0);
673 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
677 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
680 //get option max value info.
681 $optionsMaxValueTotal = 0;
682 $optionsMaxValueDetails = array();
684 if (!empty($form->_priceSet
['fields'])) {
685 foreach ($form->_priceSet
['fields'] as $field) {
686 foreach ($field['options'] as $option) {
687 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
688 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
689 $optionsMaxValueTotal +
= $maxVal;
694 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
695 if ($optionsMaxValueTotal) {
696 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
699 $form->set('priceSetId', $form->_priceSetId
);
700 $form->set('priceSet', $form->_priceSet
);
709 * @param array $params
711 * @param string $component
713 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
715 $totalPrice = $totalTax = 0;
716 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
718 $autoRenew = array();
719 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
721 foreach ($fields as $id => $field) {
722 if (empty($params["price_{$id}"]) ||
723 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
725 // skip if nothing was submitted for this field
729 switch ($field['html_type']) {
731 $firstOption = reset($field['options']);
732 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
733 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
734 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
735 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
736 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
738 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
739 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
740 if (array_key_exists($params['financial_type_id'], $taxRates)) {
741 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
742 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
743 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
744 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
745 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
748 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
752 //special case if user select -none-
753 if ($params["price_{$id}"] <= 0) {
756 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
757 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
758 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
759 $params['amount_priceset_level_radio'] = array();
760 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
761 if (isset($radioLevel)) {
762 $radioLevel = array_merge($radioLevel,
763 array_keys($params['amount_priceset_level_radio'])
767 $radioLevel = array_keys($params['amount_priceset_level_radio']);
769 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
770 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
771 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
772 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
773 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
774 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
777 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
780 // auto_renew exists and is empty in some workflows, which php treat as a 0
781 // and hence we explicitly check to see if auto_renew is numeric
782 isset($lineItem[$optionValueId]['auto_renew']) &&
783 is_numeric($lineItem[$optionValueId]['auto_renew'])
785 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
790 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
791 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
792 $optionLabel = $field['options'][$optionValueId]['label'];
793 $params['amount_priceset_level_select'] = array();
794 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
795 if (isset($selectLevel)) {
796 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
799 $selectLevel = array_keys($params['amount_priceset_level_select']);
801 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
802 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
803 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
804 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
806 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
809 isset($lineItem[$optionValueId]['auto_renew']) &&
810 is_numeric($lineItem[$optionValueId]['auto_renew'])
812 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
817 $params['amount_priceset_level_checkbox'] = $optionIds = array();
818 foreach ($params["price_{$id}"] as $optionId => $option) {
819 $optionIds[] = $optionId;
820 $optionLabel = $field['options'][$optionId]['label'];
821 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
822 if (isset($checkboxLevel)) {
823 $checkboxLevel = array_unique(array_merge(
825 array_keys($params['amount_priceset_level_checkbox'])
830 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
833 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
834 foreach ($optionIds as $optionId) {
835 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
836 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
837 $totalTax +
= $field['options'][$optionId]['tax_amount'];
839 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
842 isset($lineItem[$optionId]['auto_renew']) &&
843 is_numeric($lineItem[$optionId]['auto_renew'])
845 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
852 $amount_level = array();
853 $totalParticipant = 0;
854 if (is_array($lineItem)) {
855 foreach ($lineItem as $values) {
856 $totalParticipant +
= $values['participant_count'];
857 if ($values['html_type'] == 'Text') {
858 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
861 $amount_level[] = $values['label'];
865 $displayParticipantCount = '';
866 if ($totalParticipant > 0) {
867 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
869 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
870 $params['amount'] = $totalPrice;
871 $params['tax_amount'] = $totalTax;
873 foreach ($autoRenew as $dontCare => $eachAmount) {
875 unset($autoRenew[$dontCare]);
878 if (count($autoRenew) > 1 ) {
879 $params['autoRenew'] = $autoRenew;
885 * Build the price set form.
887 * @param CRM_Core_Form $form
892 static function buildPriceSet(&$form) {
893 $priceSetId = $form->get('priceSetId');
898 $validFieldsOnly = TRUE;
899 $className = CRM_Utils_System
::getClassName($form);
900 if (in_array($className, array(
901 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
902 $validFieldsOnly = FALSE;
905 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
906 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
907 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
908 $form->_quickConfig
= $quickConfig = 0;
909 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
913 $form->assign('quickConfig', $quickConfig);
914 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
915 $form->_quickConfig
= $quickConfig;
917 $form->assign('priceSet', $form->_priceSet
);
919 $component = 'contribution';
920 if ($className == 'CRM_Member_Form_Membership') {
921 $component = 'membership';
924 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
925 $feeBlock = &$form->_values
['fee'];
926 if (!empty($form->_useForMember
)) {
927 $component = 'membership';
931 $feeBlock = &$form->_priceSet
['fields'];
935 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
937 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
938 $adminFieldVisible = false;
939 if (CRM_Core_Permission
::check('administer CiviCRM')) {
940 $adminFieldVisible = true;
943 foreach ($feeBlock as $id => $field) {
944 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
945 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
948 $options = CRM_Utils_Array
::value('options', $field);
949 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
950 $userid = $form->getVar('_membershipContactID');
951 $checklifetime = self
::checkCurrentMembership($options, $userid);
952 if ($checklifetime) {
953 $form->assign('ispricelifetime', TRUE);
956 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
959 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
960 'price_' . $field['id'],
963 CRM_Utils_Array
::value('is_required', $field, FALSE),
972 * Check the current Membership
973 * having end date null.
975 static function checkCurrentMembership(&$options, $userid) {
976 if (!$userid ||
empty($options)) {
979 static $_contact_memberships = array();
980 $checklifetime = FALSE;
981 foreach ($options as $key => $value) {
982 if (!empty($value['membership_type_id'])) {
983 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
984 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
986 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
987 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
988 unset($options[$key]);
989 $checklifetime = TRUE;
993 if ($checklifetime) {
1002 * Set daefult the price set fields.
1004 * @param CRM_Core_Form $form
1007 * @return array $defaults
1010 static function setDefaultPriceSet(&$form, &$defaults) {
1011 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1015 foreach ($form->_priceSet
['fields'] as $key => $val) {
1016 foreach ($val['options'] as $keys => $values) {
1017 if ($values['is_default']) {
1018 if ($val['html_type'] == 'CheckBox') {
1019 $defaults["price_{$key}"][$keys] = 1;
1022 $defaults["price_{$key}"] = $keys;
1031 * Supports event create function by setting up required price sets, not tested but expect
1032 * it will work for contribution page
1033 * @param array $params as passed to api/bao create fn
1034 * @param CRM_Core_DAO $entity object for given entity
1035 * @param string $entityName name of entity - e.g event
1037 static function setPriceSets(&$params, $entity, $entityName) {
1038 if(empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1041 // CRM-14069 note that we may as well start by assuming more than one.
1042 // currently the form does not pass in as an array & will be skipped
1043 // test is passing in as an array but I feel the api should have a metadata that allows
1044 // transform of single to array - seems good for managing transitions - in which case all api
1045 // calls that set price_set_id will hit this
1046 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1047 // all separated values, strings, json half-separated values (in participant we hit this)
1048 // to be converted to json @ api layer
1049 $pse = new CRM_Price_DAO_PriceSetEntity();
1050 $pse->entity_table
= 'civicrm_' . $entityName;
1051 $pse->entity_id
= $entity->id
;
1052 while ($pse->fetch()) {
1053 if(!in_array($pse->price_set_id
, $params['price_set_id'])) {
1054 // note an even more aggressive form of this deletion currently happens in event form
1055 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1056 // on the participant record
1057 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1058 CRM_Core_BAO_Discount
::del($entity->id
,'civicrm_' . $entityName);
1062 foreach ($params['price_set_id'] as $priceSetID) {
1063 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1064 //@todo - how should we do this - copied from form
1065 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1066 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1067 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1072 * Get field ids of a price set
1074 * @param int $id Price Set id
1076 * @return array of the field ids
1081 public static function getFieldIds($id) {
1082 $priceField = new CRM_Price_DAO_PriceField();
1083 $priceField->price_set_id
= $id;
1084 $priceField->find();
1085 while ($priceField->fetch()) {
1086 $var[] = $priceField->id
;
1092 * This function is to make a copy of a price set, including
1095 * @param int $id the price set id to copy
1097 * @return the copy object
1101 static function copy($id) {
1102 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1104 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1106 'suffix' => array('title' => ' ' . $title,
1107 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1111 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1117 //copying all the blocks pertaining to the price set
1118 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1119 array('price_set_id' => $id),
1120 array('price_set_id' => $copy->id
)
1122 if (!empty($copyPriceField)) {
1123 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1125 //copy option group and values
1126 foreach ($price as $originalId => $copyId) {
1127 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1128 array('price_field_id' => $originalId),
1129 array('price_field_id' => $copyId)
1135 CRM_Utils_Hook
::copy('Set', $copy);
1140 * This function is to check price set permission
1142 * @param int $sid the price set id
1146 static function checkPermission($sid) {
1147 if ($sid && self
::eventPriceSetDomainID()) {
1148 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1149 if (CRM_Core_Config
::domainID() != $domain_id) {
1150 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1157 * Get the sum of participant count
1158 * for all fields of given price set.
1160 * @param int $sid the price set id
1162 * @param bool $onlyActive
1164 * @return int|null|string
1168 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1176 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1179 static $pricesetFieldCount = array();
1180 if (!isset($pricesetFieldCount[$sid])) {
1182 SELECT sum(value.count) as totalCount
1183 FROM civicrm_price_field_value value
1184 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1185 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1189 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1190 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1193 return $pricesetFieldCount[$sid];
1201 public static function getMembershipCount($ids) {
1203 SELECT count( pfv.id ) AS count, pfv.id AS id
1204 FROM civicrm_price_field_value pfv
1205 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1206 WHERE pfv.id IN ( $ids )
1207 GROUP BY mt.member_of_contact_id";
1209 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1212 while ($crmDAO->fetch()) {
1213 $count[$crmDAO->id
] = $crmDAO->count
;
1220 * Check if auto renew option should be shown
1222 * @param int $priceSetId price set id
1224 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1226 public static function checkAutoRenewForPriceSet($priceSetId) {
1227 // auto-renew option should be visible if membership types associated with all the fields has
1228 // been set for auto-renew option
1229 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1231 // get the membership type auto renew option and check if required or optional
1232 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1233 FROM civicrm_price_field_value pfv
1234 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1235 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1236 WHERE pf.price_set_id = %1
1237 AND pf.is_active = 1
1238 AND pfv.is_active = 1';
1240 $params = array(1 => array($priceSetId, 'Integer'));
1242 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1243 $autoRenewOption = 2;
1244 $interval = $unit = array();
1245 while ($dao->fetch()) {
1246 if (!$dao->auto_renew
) {
1247 $autoRenewOption = 0;
1250 if ($dao->auto_renew
== 1) {
1251 $autoRenewOption = 1;
1254 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1255 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1258 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1259 return $autoRenewOption;
1267 * Retrieve auto renew frequency and interval
1269 * @param int $priceSetId price set id
1271 * @return array associate array of frequency interval and unit
1275 public static function getRecurDetails($priceSetId) {
1276 $query = 'SELECT mt.duration_interval, mt.duration_unit
1277 FROM civicrm_price_field_value pfv
1278 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1279 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1280 WHERE pf.price_set_id = %1 LIMIT 1';
1282 $params = array(1 => array($priceSetId, 'Integer'));
1283 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1285 return array($dao->duration_interval
, $dao->duration_unit
);
1291 static function eventPriceSetDomainID() {
1292 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1293 'event_price_set_domain_id',
1299 * Update the is_quick_config flag in the db
1301 * @param int $id id of the database record
1302 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1304 * @return Object DAO object on sucess, null otherwise
1308 static function setIsQuickConfig($id, $isQuickConfig) {
1309 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1313 * Check if price set id provides option for
1314 * user to select both auto-renew and non-auto-renew memberships
1320 public static function checkMembershipPriceSet($id) {
1323 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1324 FROM civicrm_price_field_value pfv
1325 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1326 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1327 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1331 $params = array(1 => array($id, 'Integer'));
1332 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1334 $autoRenew = array();
1335 //FIXME: do a comprehensive check of whether
1336 //2 membership types can be selected
1337 //instead of comparing all of them
1338 while ($dao->fetch()) {
1339 //temp fix for #CRM-10370
1340 //if its NULL consider it '0' i.e. 'No auto-renew option'
1341 $daoAutoRenew = $dao->auto_renew
;
1342 if ($daoAutoRenew === NULL) {
1345 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1348 $autoRenew[] = $daoAutoRenew;
1354 * Copy priceSet when event/contibution page is copied
1356 * @param string $baoName BAO name
1357 * @param int $id old event/contribution page id
1358 * @param int $newId newly created event/contribution page id
1360 static function copyPriceSet($baoName, $id, $newId) {
1361 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1363 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1364 if($isQuickConfig) {
1365 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1366 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1369 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1372 'entity_table' => $baoName,
1374 array('entity_id' => $newId)
1377 // copy event discount
1378 if ($baoName == 'civicrm_event') {
1379 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1380 foreach ($discount as $discountId => $setId) {
1382 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1384 CRM_Core_DAO
::copyGeneric(
1385 'CRM_Core_DAO_Discount',
1387 'id' => $discountId,
1390 'entity_id' => $newId,
1391 'price_set_id' => $copyPriceSet->id
,
1400 * Function to set tax_amount and tax_rate in LineItem
1404 static function setLineItem($field, $lineItem, $optionValueId) {
1405 if ($field['html_type'] == 'Text') {
1406 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1409 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1411 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1412 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1413 $lineItem[$optionValueId]['tax_rate'] = $taxRate;