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
{
45 function __construct() {
46 parent
::__construct();
50 * takes an associative array and creates a price set object
52 * @param array $params (reference) an assoc array of name/value pairs
54 * @return object CRM_Price_DAO_PriceSet object
58 static function create(&$params) {
59 if(empty($params['id']) && empty($params['name'])) {
60 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
62 $priceSetBAO = new CRM_Price_BAO_PriceSet();
63 $priceSetBAO->copyValues($params);
64 if (self
::eventPriceSetDomainID()) {
65 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
67 return $priceSetBAO->save();
71 * Takes a bunch of params that are needed to match certain criteria and
72 * retrieves the relevant objects. Typically the valid params are only
73 * contact_id. We'll tweak this function to be more full featured over a period
74 * of time. This is the inverse function of create. It also stores all the retrieved
75 * values in the default array
77 * @param array $params (reference ) an assoc array of name/value pairs
78 * @param array $defaults (reference ) an assoc array to hold the flattened values
80 * @return object CRM_Price_DAO_PriceSet object
84 static function retrieve(&$params, &$defaults) {
85 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
89 * update the is_active flag in the db
91 * @param int $id id of the database record
94 * @internal param bool $is_active value we want to set the is_active field
96 * @return Object DAO object on sucess, null otherwise
100 static function setIsActive($id, $isActive) {
101 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
105 * Calculate the default price set id
106 * assigned to the contribution/membership etc
108 * @param string $entity
110 * @return array $defaultPriceSet default price set
116 public static function getDefaultPriceSet($entity = 'contribution') {
118 $entityName = 'default_contribution_amount';
119 if ($entity == 'membership') {
120 $entityName = 'default_membership_type_amount';
124 SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label
125 FROM civicrm_price_set ps
126 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
127 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
128 WHERE ps.name = '{$entityName}'
131 $dao = CRM_Core_DAO
::executeQuery($sql);
132 $defaultPriceSet = array();
133 while ($dao->fetch()) {
134 $defaultPriceSet[$dao->priceFieldValueID
]['setID'] = $dao->setID
;
135 $defaultPriceSet[$dao->priceFieldValueID
]['priceFieldID'] = $dao->priceFieldID
;
136 $defaultPriceSet[$dao->priceFieldValueID
]['name'] = $dao->name
;
137 $defaultPriceSet[$dao->priceFieldValueID
]['label'] = $dao->label
;
138 $defaultPriceSet[$dao->priceFieldValueID
]['priceFieldValueID'] = $dao->priceFieldValueID
;
141 return $defaultPriceSet;
145 * Get the price set title.
147 * @param int $id id of price set
149 * @return string title
155 public static function getTitle($id) {
156 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
160 * Return a list of all forms which use this price set.
162 * @param int $id id of price set
163 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
167 public static function &getUsedBy($id, $simpleReturn = FALSE) {
168 $usedBy = $forms = $tables = array();
170 SELECT entity_table, entity_id
171 FROM civicrm_price_set_entity
172 WHERE price_set_id = %1";
173 $params = array(1 => array($id, 'Integer'));
174 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
176 while ($crmFormDAO->fetch()) {
177 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
178 $tables[] = $crmFormDAO->entity_table
;
180 // Return only tables
181 if ($simpleReturn == 'table') {
186 SELECT cli.entity_table, cli.entity_id
187 FROM civicrm_line_item cli
188 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
189 WHERE cpf.price_set_id = %1";
190 $params = array(1 => array($id, 'Integer'));
191 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
192 while ($crmFormDAO->fetch()) {
193 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
194 $tables[] = $crmFormDAO->entity_table
;
200 // Return only entity data
201 if ($simpleReturn == 'entity') {
204 foreach ($forms as $table => $entities) {
206 case 'civicrm_event':
207 $ids = implode(',', $entities);
208 $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
209 FROM civicrm_event ce
210 LEFT JOIN civicrm_option_value ON
211 ( ce.event_type_id = civicrm_option_value.value )
212 LEFT JOIN civicrm_option_group ON
213 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
215 civicrm_option_group.name = 'event_type' AND
218 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
219 while ($crmDAO->fetch()) {
220 if ($crmDAO->isTemplate
) {
221 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
222 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
223 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
226 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
227 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
228 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
229 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
230 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
235 case 'civicrm_contribution_page':
236 $ids = implode(',', $entities);
237 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
238 FROM civicrm_contribution_page cp, civicrm_financial_type ct
239 WHERE ct.id = cp.financial_type_id AND
242 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
243 while ($crmDAO->fetch()) {
244 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
245 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
246 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
247 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
251 case 'civicrm_contribution':
252 case 'civicrm_membership':
253 case 'civicrm_participant':
258 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
267 * Delete the price set
269 * @param int $id Price Set id
271 * @return boolean false if fields exist for this set, true if the
272 * set could be deleted
277 public static function deleteSet($id) {
278 // remove from all inactive forms
279 $usedBy = self
::getUsedBy($id);
280 if (isset($usedBy['civicrm_event'])) {
281 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
282 $eventDAO = new CRM_Event_DAO_Event();
283 $eventDAO->id
= $eventId;
285 while ($eventDAO->fetch()) {
286 self
::removeFrom('civicrm_event', $eventDAO->id
);
291 // delete price fields
292 $priceField = new CRM_Price_DAO_PriceField();
293 $priceField->price_set_id
= $id;
295 while ($priceField->fetch()) {
296 // delete options first
297 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
300 $set = new CRM_Price_DAO_PriceSet();
302 return $set->delete();
306 * Link the price set with the specified table and id
308 * @param string $entityTable
309 * @param integer $entityId
310 * @param integer $priceSetId
314 public static function addTo($entityTable, $entityId, $priceSetId) {
315 // verify that the price set exists
316 $dao = new CRM_Price_DAO_PriceSet();
317 $dao->id
= $priceSetId;
323 $dao = new CRM_Price_DAO_PriceSetEntity();
324 // find if this already exists
325 $dao->entity_id
= $entityId;
326 $dao->entity_table
= $entityTable;
329 // add or update price_set_id
330 $dao->price_set_id
= $priceSetId;
335 * Delete price set for the given entity and id
337 * @param string $entityTable
338 * @param integer $entityId
342 public static function removeFrom($entityTable, $entityId) {
343 $dao = new CRM_Price_DAO_PriceSetEntity();
344 $dao->entity_table
= $entityTable;
345 $dao->entity_id
= $entityId;
346 return $dao->delete();
350 * Find a price_set_id associatied with the given table, id and usedFor
351 * Used For value for events:1, contribution:2, membership:3
353 * @param string $entityTable
354 * @param int $entityId
355 * @param int $usedFor ( price set that extends/used for particular component )
357 * @param null $isQuickConfig
358 * @param null $setName
360 * @return integer|false price_set_id, or false if none found
362 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
363 if (!$entityTable ||
!$entityId) {
367 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
368 FROM civicrm_price_set ps
369 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
370 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
371 if ($isQuickConfig) {
372 $sql .= ' AND ps.is_quick_config = 0 ';
374 $params = array(1 => array($entityTable, 'String'),
375 2 => array($entityId, 'Integer'),
378 $sql .= " AND ps.extends LIKE '%%3%' ";
379 $params[3] = array($usedFor, 'Integer');
382 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
384 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
385 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
389 * Find a price_set_id associated with the given option value or field ID
391 * @param array $params (reference) an assoc array of name/value pairs
392 * array may contain either option id or
395 * @return integer|NULL price set id on success, null otherwise
399 public static function getSetId(&$params) {
402 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
403 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
404 $fieldValue->id
= $oid;
405 if ($fieldValue->find(TRUE)) {
406 $fid = $fieldValue->price_field_id
;
410 $fid = CRM_Utils_Array
::value('fid', $params);
414 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
421 * Return an associative array of all price sets
423 * @param bool $withInactive whether or not to include inactive entries
424 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
426 * @return array associative array of id => name
428 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
431 DISTINCT ( price_set_id ) as id, title
436 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
438 if (!$withInactive) {
439 $query .= ' AND civicrm_price_set.is_active = 1 ';
442 if (self
::eventPriceSetDomainID()) {
443 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
446 $priceSets = array();
448 if ($extendComponentName) {
449 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
453 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
456 $dao = CRM_Core_DAO
::executeQuery($query);
457 while ($dao->fetch()) {
458 $priceSets[$dao->id
] = $dao->title
;
464 * Get price set details
466 * An array containing price set details (including price fields) is returned
469 * @param bool $required
470 * @param bool $validOnly
472 * @internal param int $setId - price set id whose details are needed
474 * @return array $setTree - array consisting of field details
476 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
480 $priceFields = array(
489 'is_display_amounts',
498 if ($required == TRUE) {
499 $priceFields[] = 'is_required';
503 $select = 'SELECT ' . implode(',', $priceFields);
504 $from = ' FROM civicrm_price_field';
507 $params[1] = array($setID, 'Integer');
509 WHERE price_set_id = %1
514 $currentTime = date('YmdHis');
516 AND ( active_on IS NULL OR active_on <= {$currentTime} )
517 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
521 $orderBy = ' ORDER BY weight';
523 $sql = $select . $from . $where . $dateSelect . $orderBy;
525 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
527 $visibility = CRM_Core_PseudoConstant
::visibility('name');
528 while ($dao->fetch()) {
531 $setTree[$setID]['fields'][$fieldID] = array();
532 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
534 foreach ($priceFields as $field) {
535 if ($field == 'id' ||
is_null($dao->$field)) {
539 if ($field == 'visibility_id') {
540 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
542 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
544 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
547 // also get the pre and post help from this price set
549 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
550 FROM civicrm_price_set
552 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
554 $setTree[$setID]['extends'] = $dao->extends;
555 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
556 $setTree[$setID]['help_pre'] = $dao->help_pre
;
557 $setTree[$setID]['help_post'] = $dao->help_post
;
558 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
564 * Get the Price Field ID. We call this function when more than one being present would represent an error
565 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
566 * @param array $priceSet
568 * @throws CRM_Core_Exception
571 static function getOnlyPriceFieldID(array $priceSet) {
572 if(count($priceSet['fields']) > 1) {
573 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
575 return (int) implode('_', array_keys($priceSet['fields']));
579 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
580 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
581 * @param array $priceSet
583 * @throws CRM_Core_Exception
586 static function getOnlyPriceFieldValueID(array $priceSet) {
587 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
588 if(count($priceSet['fields'][$priceFieldID]['options']) > 1) {
589 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
591 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
596 * @param CRM_Core_Form $form
598 * @param string $entityTable
599 * @param bool $validOnly
600 * @param null $priceSetId
602 * @return bool|false|int|null
604 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
606 $priceSetId = self
::getFor($entityTable, $id);
609 //check if priceset is is_config
610 if (is_numeric($priceSetId)) {
611 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
612 $form->assign('quickConfig', 1);
617 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
618 $entityId = $entity = NULL;
620 switch ($entityTable) {
621 case 'civicrm_event':
622 $entity = 'participant';
623 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
624 $entityId = $form->_id
;
627 $entityId = $form->_participantId
;
631 case 'civicrm_contribution_page':
632 case 'civicrm_contribution':
633 $entity = 'contribution';
634 $entityId = $form->_id
;
638 if ($entityId && $entity) {
639 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
647 $form->_priceSetId
= $priceSetId;
648 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
649 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
650 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
652 //get the price set fields participant count.
653 if ($entityTable == 'civicrm_event') {
654 //get option count info.
655 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
656 if ($form->_priceSet
['optionsCountTotal']) {
657 $optionsCountDeails = array();
658 if (!empty($form->_priceSet
['fields'])) {
659 foreach ($form->_priceSet
['fields'] as $field) {
660 foreach ($field['options'] as $option) {
661 $count = CRM_Utils_Array
::value('count', $option, 0);
662 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
666 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
669 //get option max value info.
670 $optionsMaxValueTotal = 0;
671 $optionsMaxValueDetails = array();
673 if (!empty($form->_priceSet
['fields'])) {
674 foreach ($form->_priceSet
['fields'] as $field) {
675 foreach ($field['options'] as $option) {
676 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
677 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
678 $optionsMaxValueTotal +
= $maxVal;
683 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
684 if ($optionsMaxValueTotal) {
685 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
688 $form->set('priceSetId', $form->_priceSetId
);
689 $form->set('priceSet', $form->_priceSet
);
700 * @param string $component
702 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
704 $totalPrice = $totalTax = 0;
705 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
707 $autoRenew = array();
708 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
710 foreach ($fields as $id => $field) {
711 if (empty($params["price_{$id}"]) ||
712 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
714 // skip if nothing was submitted for this field
718 switch ($field['html_type']) {
720 $params["price_{$id}"] = array(key($field['options']) => $params["price_{$id}"]);
721 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
722 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
723 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
724 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
726 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
727 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
728 if (array_key_exists($params['financial_type_id'], $taxRates)) {
729 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
730 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
731 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
732 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
733 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
736 $totalPrice +
= $lineItem[key($field['options'])]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
740 //special case if user select -none-
741 if ($params["price_{$id}"] <= 0) {
744 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
745 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
746 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
747 $params['amount_priceset_level_radio'] = array();
748 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
749 if (isset($radioLevel)) {
750 $radioLevel = array_merge($radioLevel,
751 array_keys($params['amount_priceset_level_radio'])
755 $radioLevel = array_keys($params['amount_priceset_level_radio']);
757 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
758 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
759 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
760 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
761 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
762 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
765 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
768 // auto_renew exists and is empty in some workflows, which php treat as a 0
769 // and hence we explicitly check to see if auto_renew is numeric
770 isset($lineItem[$optionValueId]['auto_renew']) &&
771 is_numeric($lineItem[$optionValueId]['auto_renew'])
773 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
778 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
779 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
780 $optionLabel = $field['options'][$optionValueId]['label'];
781 $params['amount_priceset_level_select'] = array();
782 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
783 if (isset($selectLevel)) {
784 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
787 $selectLevel = array_keys($params['amount_priceset_level_select']);
789 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
790 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
791 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
792 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
794 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
797 isset($lineItem[$optionValueId]['auto_renew']) &&
798 is_numeric($lineItem[$optionValueId]['auto_renew'])
800 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
805 $params['amount_priceset_level_checkbox'] = $optionIds = array();
806 foreach ($params["price_{$id}"] as $optionId => $option) {
807 $optionIds[] = $optionId;
808 $optionLabel = $field['options'][$optionId]['label'];
809 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
810 if (isset($checkboxLevel)) {
811 $checkboxLevel = array_unique(array_merge(
813 array_keys($params['amount_priceset_level_checkbox'])
818 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
821 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
822 foreach ($optionIds as $optionId) {
823 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
824 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
825 $totalTax +
= $field['options'][$optionId]['tax_amount'];
827 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
830 isset($lineItem[$optionId]['auto_renew']) &&
831 is_numeric($lineItem[$optionId]['auto_renew'])
833 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
840 $amount_level = array();
841 $totalParticipant = 0;
842 if (is_array($lineItem)) {
843 foreach ($lineItem as $values) {
844 $totalParticipant +
= $values['participant_count'];
845 if ($values['html_type'] == 'Text') {
846 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
849 $amount_level[] = $values['label'];
853 $displayParticipantCount = '';
854 if ($totalParticipant > 0) {
855 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
857 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
858 $params['amount'] = $totalPrice;
859 $params['tax_amount'] = $totalTax;
861 foreach ($autoRenew as $dontCare => $eachAmount) {
863 unset($autoRenew[$dontCare]);
866 if (count($autoRenew) > 1 ) {
867 $params['autoRenew'] = $autoRenew;
873 * Function to build the price set form.
875 * @param CRM_Core_Form $form
880 static function buildPriceSet(&$form) {
881 $priceSetId = $form->get('priceSetId');
882 $userid = $form->getVar('_userID');
887 $validFieldsOnly = TRUE;
888 $className = CRM_Utils_System
::getClassName($form);
889 if (in_array($className, array(
890 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
891 $validFieldsOnly = FALSE;
894 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
895 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
896 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
897 $form->_quickConfig
= $quickConfig = 0;
898 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
902 $form->assign('quickConfig', $quickConfig);
903 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
904 $form->_quickConfig
= $quickConfig;
906 $form->assign('priceSet', $form->_priceSet
);
908 $component = 'contribution';
909 if ($className == 'CRM_Member_Form_Membership') {
910 $component = 'membership';
913 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
914 $feeBlock = &$form->_values
['fee'];
915 if (!empty($form->_useForMember
)) {
916 $component = 'membership';
920 $feeBlock = &$form->_priceSet
['fields'];
924 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
926 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
927 $adminFieldVisible = false;
928 if (CRM_Core_Permission
::check('administer CiviCRM')) {
929 $adminFieldVisible = true;
932 foreach ($feeBlock as $id => $field) {
933 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
934 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
937 $options = CRM_Utils_Array
::value('options', $field);
938 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
939 $checklifetime = self
::checkCurrentMembership($options, $userid);
940 if ($checklifetime) {
941 $form->assign('ispricelifetime', TRUE);
944 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
947 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
948 'price_' . $field['id'],
951 CRM_Utils_Array
::value('is_required', $field, FALSE),
960 * Function to check the current Membership
961 * having end date null.
963 static function checkCurrentMembership(&$options, $userid) {
964 if (!$userid ||
empty($options)) {
967 static $_contact_memberships = array();
968 $checklifetime = FALSE;
969 foreach ($options as $key => $value) {
970 if (!empty($value['membership_type_id'])) {
971 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
972 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
974 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
975 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
976 unset($options[$key]);
977 $checklifetime = TRUE;
981 if ($checklifetime) {
990 * Function to set daefult the price set fields.
995 * @return array $defaults
998 static function setDefaultPriceSet(&$form, &$defaults) {
999 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1003 foreach ($form->_priceSet
['fields'] as $key => $val) {
1004 foreach ($val['options'] as $keys => $values) {
1005 if ($values['is_default']) {
1006 if ($val['html_type'] == 'CheckBox') {
1007 $defaults["price_{$key}"][$keys] = 1;
1010 $defaults["price_{$key}"] = $keys;
1019 * Supports event create function by setting up required price sets, not tested but expect
1020 * it will work for contribution page
1021 * @param array $params as passed to api/bao create fn
1022 * @param CRM_Core_DAO $entity object for given entity
1023 * @param string $entityName name of entity - e.g event
1025 static function setPriceSets(&$params, $entity, $entityName) {
1026 if(empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1029 // CRM-14069 note that we may as well start by assuming more than one.
1030 // currently the form does not pass in as an array & will be skipped
1031 // test is passing in as an array but I feel the api should have a metadata that allows
1032 // transform of single to array - seems good for managing transitions - in which case all api
1033 // calls that set price_set_id will hit this
1034 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1035 // all separated values, strings, json half-separated values (in participant we hit this)
1036 // to be converted to json @ api layer
1037 $pse = new CRM_Price_DAO_PriceSetEntity();
1038 $pse->entity_table
= 'civicrm_' . $entityName;
1039 $pse->entity_id
= $entity->id
;
1040 while ($pse->fetch()) {
1041 if(!in_array($pse->price_set_id
, $params['price_set_id'])) {
1042 // note an even more aggressive form of this deletion currently happens in event form
1043 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1044 // on the participant record
1045 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1046 CRM_Core_BAO_Discount
::del($this->_id
,'civicrm_' . $entityName);
1050 foreach ($params['price_set_id'] as $priceSetID) {
1051 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1052 //@todo - how should we do this - copied from form
1053 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1054 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1055 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1060 * Get field ids of a price set
1062 * @param int $id Price Set id
1064 * @return array of the field ids
1069 public static function getFieldIds($id) {
1070 $priceField = new CRM_Price_DAO_PriceField();
1071 $priceField->price_set_id
= $id;
1072 $priceField->find();
1073 while ($priceField->fetch()) {
1074 $var[] = $priceField->id
;
1080 * This function is to make a copy of a price set, including
1083 * @param int $id the price set id to copy
1085 * @return the copy object
1089 static function copy($id) {
1090 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1092 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1094 'suffix' => array('title' => ' ' . $title,
1095 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1099 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1105 //copying all the blocks pertaining to the price set
1106 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1107 array('price_set_id' => $id),
1108 array('price_set_id' => $copy->id
)
1110 if (!empty($copyPriceField)) {
1111 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1113 //copy option group and values
1114 foreach ($price as $originalId => $copyId) {
1115 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1116 array('price_field_id' => $originalId),
1117 array('price_field_id' => $copyId)
1123 CRM_Utils_Hook
::copy('Set', $copy);
1128 * This function is to check price set permission
1130 * @param int $sid the price set id
1134 static function checkPermission($sid) {
1135 if ($sid && self
::eventPriceSetDomainID()) {
1136 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1137 if (CRM_Core_Config
::domainID() != $domain_id) {
1138 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
1145 * Get the sum of participant count
1146 * for all fields of given price set.
1148 * @param int $sid the price set id
1150 * @param bool $onlyActive
1152 * @return int|null|string
1156 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1164 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1167 static $pricesetFieldCount = array();
1168 if (!isset($pricesetFieldCount[$sid])) {
1170 SELECT sum(value.count) as totalCount
1171 FROM civicrm_price_field_value value
1172 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1173 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1177 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1178 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1181 return $pricesetFieldCount[$sid];
1189 public static function getMembershipCount($ids) {
1191 SELECT count( pfv.id ) AS count, pfv.id AS id
1192 FROM civicrm_price_field_value pfv
1193 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1194 WHERE pfv.id IN ( $ids )
1195 GROUP BY mt.member_of_contact_id";
1197 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1200 while ($crmDAO->fetch()) {
1201 $count[$crmDAO->id
] = $crmDAO->count
;
1208 * Function to check if auto renew option should be shown
1210 * @param int $priceSetId price set id
1212 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1214 public static function checkAutoRenewForPriceSet($priceSetId) {
1215 // auto-renew option should be visible if membership types associated with all the fields has
1216 // been set for auto-renew option
1217 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1219 // get the membership type auto renew option and check if required or optional
1220 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1221 FROM civicrm_price_field_value pfv
1222 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1223 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1224 WHERE pf.price_set_id = %1
1225 AND pf.is_active = 1
1226 AND pfv.is_active = 1';
1228 $params = array(1 => array($priceSetId, 'Integer'));
1230 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1231 $autoRenewOption = 2;
1232 $interval = $unit = array();
1233 while ($dao->fetch()) {
1234 if (!$dao->auto_renew
) {
1235 $autoRenewOption = 0;
1238 if ($dao->auto_renew
== 1) {
1239 $autoRenewOption = 1;
1242 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1243 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1246 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1247 return $autoRenewOption;
1255 * Function to retrieve auto renew frequency and interval
1257 * @param int $priceSetId price set id
1259 * @return array associate array of frequency interval and unit
1263 public static function getRecurDetails($priceSetId) {
1264 $query = 'SELECT mt.duration_interval, mt.duration_unit
1265 FROM civicrm_price_field_value pfv
1266 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1267 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1268 WHERE pf.price_set_id = %1 LIMIT 1';
1270 $params = array(1 => array($priceSetId, 'Integer'));
1271 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1273 return array($dao->duration_interval
, $dao->duration_unit
);
1279 static function eventPriceSetDomainID() {
1280 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1281 'event_price_set_domain_id',
1287 * update the is_quick_config flag in the db
1289 * @param int $id id of the database record
1290 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1292 * @return Object DAO object on sucess, null otherwise
1296 static function setIsQuickConfig($id, $isQuickConfig) {
1297 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1301 * Check if price set id provides option for
1302 * user to select both auto-renew and non-auto-renew memberships
1308 public static function checkMembershipPriceSet($id) {
1311 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1312 FROM civicrm_price_field_value pfv
1313 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1314 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1315 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1319 $params = array(1 => array($id, 'Integer'));
1320 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1322 $autoRenew = array();
1323 //FIXME: do a comprehensive check of whether
1324 //2 membership types can be selected
1325 //instead of comparing all of them
1326 while ($dao->fetch()) {
1327 //temp fix for #CRM-10370
1328 //if its NULL consider it '0' i.e. 'No auto-renew option'
1329 $daoAutoRenew = $dao->auto_renew
;
1330 if ($daoAutoRenew === NULL) {
1333 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1336 $autoRenew[] = $daoAutoRenew;
1342 * Copy priceSet when event/contibution page is copied
1344 * @params string $baoName BAO name
1345 * @params int $id old event/contribution page id
1346 * @params int $newId newly created event/contribution page id
1348 * @param string $baoName
1349 * @param integer $id
1350 * @param integer $newId
1352 static function copyPriceSet($baoName, $id, $newId) {
1353 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1355 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1356 if($isQuickConfig) {
1357 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1358 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1361 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1364 'entity_table' => $baoName,
1366 array('entity_id' => $newId)
1369 // copy event discount
1370 if ($baoName == 'civicrm_event') {
1371 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1372 foreach ($discount as $discountId => $setId) {
1374 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1376 CRM_Core_DAO
::copyGeneric(
1377 'CRM_Core_DAO_Discount',
1379 'id' => $discountId,
1382 'entity_id' => $newId,
1383 'price_set_id' => $copyPriceSet->id
,
1392 * Function to set tax_amount and tax_rate in LineItem
1396 static function setLineItem($field, $lineItem, $optionValueId) {
1397 if ($field['html_type'] == 'Text') {
1398 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1401 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1403 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1404 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1405 $lineItem[$optionValueId]['tax_rate'] = $taxRate;