3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 public function __construct() {
54 parent
::__construct();
58 * Takes an associative array and creates a price set object
60 * @param array $params
61 * (reference) an assoc array of name/value pairs.
63 * @return CRM_Price_DAO_PriceSet object
66 public static function create(&$params) {
67 if (empty($params['id']) && empty($params['name'])) {
68 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
70 if (!empty($params['extends']) && is_array($params['extends'])) {
71 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
73 $priceSetBAO = new CRM_Price_BAO_PriceSet();
74 $priceSetBAO->copyValues($params);
75 if (self
::eventPriceSetDomainID()) {
76 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
78 return $priceSetBAO->save();
82 * Fetch object based on array of properties
84 * @param array $params
85 * (reference ) an assoc array of name/value pairs.
86 * @param array $defaults
87 * (reference ) an assoc array to hold the flattened values.
89 * @return CRM_Price_DAO_PriceSet object
92 public static function retrieve(&$params, &$defaults) {
93 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
97 * Update the is_active flag in the db
100 * Id of the database record.
103 * @internal param bool $is_active value we want to set the is_active field
106 * DAO object on sucess, null otherwise
109 public static function setIsActive($id, $isActive) {
110 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
114 * Calculate the default price set id
115 * assigned to the contribution/membership etc
117 * @param string $entity
124 public static function getDefaultPriceSet($entity = 'contribution') {
125 if (!empty(self
::$_defaultPriceSet[$entity])) {
126 return self
::$_defaultPriceSet[$entity];
128 $entityName = 'default_contribution_amount';
129 if ($entity == 'membership') {
130 $entityName = 'default_membership_type_amount';
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}'
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
,
156 return self
::$_defaultPriceSet[$entity];
160 * Get the price set title.
170 public static function getTitle($id) {
171 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
175 * Return a list of all forms which use this price set.
179 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
183 public static function &getUsedBy($id, $simpleReturn = FALSE) {
184 $usedBy = $forms = $tables = array();
186 SELECT entity_table, entity_id
187 FROM civicrm_price_set_entity
188 WHERE price_set_id = %1";
189 $params = array(1 => array($id, 'Integer'));
190 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
192 while ($crmFormDAO->fetch()) {
193 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
194 $tables[] = $crmFormDAO->entity_table
;
196 // Return only tables
197 if ($simpleReturn == 'table') {
202 SELECT cli.entity_table, cli.entity_id
203 FROM civicrm_line_item cli
204 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
205 WHERE cpf.price_set_id = %1";
206 $params = array(1 => array($id, 'Integer'));
207 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
208 while ($crmFormDAO->fetch()) {
209 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
210 $tables[] = $crmFormDAO->entity_table
;
216 // Return only entity data
217 if ($simpleReturn == 'entity') {
220 foreach ($forms as $table => $entities) {
222 case 'civicrm_event':
223 $ids = implode(',', $entities);
224 $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
225 FROM civicrm_event ce
226 LEFT JOIN civicrm_option_value ON
227 ( ce.event_type_id = civicrm_option_value.value )
228 LEFT JOIN civicrm_option_group ON
229 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
231 civicrm_option_group.name = 'event_type' AND
234 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
235 while ($crmDAO->fetch()) {
236 if ($crmDAO->isTemplate
) {
237 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
238 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
239 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
242 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
243 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
244 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
245 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
246 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
251 case 'civicrm_contribution_page':
252 $ids = implode(',', $entities);
253 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
254 FROM civicrm_contribution_page cp, civicrm_financial_type ct
255 WHERE ct.id = cp.financial_type_id AND
258 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
259 while ($crmDAO->fetch()) {
260 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
261 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
262 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
263 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
267 case 'civicrm_contribution':
268 case 'civicrm_membership':
269 case 'civicrm_participant':
274 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
283 * Delete the price set
289 * false if fields exist for this set, true if the
290 * set could be deleted
294 public static function deleteSet($id) {
295 // remove from all inactive forms
296 $usedBy = self
::getUsedBy($id);
297 if (isset($usedBy['civicrm_event'])) {
298 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
299 $eventDAO = new CRM_Event_DAO_Event();
300 $eventDAO->id
= $eventId;
302 while ($eventDAO->fetch()) {
303 self
::removeFrom('civicrm_event', $eventDAO->id
);
308 // delete price fields
309 $priceField = new CRM_Price_DAO_PriceField();
310 $priceField->price_set_id
= $id;
312 while ($priceField->fetch()) {
313 // delete options first
314 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
317 $set = new CRM_Price_DAO_PriceSet();
319 return $set->delete();
323 * Link the price set with the specified table and id
325 * @param string $entityTable
326 * @param int $entityId
327 * @param int $priceSetId
331 public static function addTo($entityTable, $entityId, $priceSetId) {
332 // verify that the price set exists
333 $dao = new CRM_Price_DAO_PriceSet();
334 $dao->id
= $priceSetId;
340 $dao = new CRM_Price_DAO_PriceSetEntity();
341 // find if this already exists
342 $dao->entity_id
= $entityId;
343 $dao->entity_table
= $entityTable;
346 // add or update price_set_id
347 $dao->price_set_id
= $priceSetId;
352 * Delete price set for the given entity and id
354 * @param string $entityTable
355 * @param int $entityId
359 public static function removeFrom($entityTable, $entityId) {
360 $dao = new CRM_Price_DAO_PriceSetEntity();
361 $dao->entity_table
= $entityTable;
362 $dao->entity_id
= $entityId;
363 return $dao->delete();
367 * Find a price_set_id associatied with the given table, id and usedFor
368 * Used For value for events:1, contribution:2, membership:3
370 * @param string $entityTable
371 * @param int $entityId
372 * @param int $usedFor
373 * ( price set that extends/used for particular component ).
375 * @param null $isQuickConfig
376 * @param null $setName
378 * @return integer|false price_set_id, or false if none found
380 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
381 if (!$entityTable ||
!$entityId) {
385 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
386 FROM civicrm_price_set ps
387 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
388 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
389 if ($isQuickConfig) {
390 $sql .= ' AND ps.is_quick_config = 0 ';
393 1 => array($entityTable, 'String'),
394 2 => array($entityId, 'Integer'),
397 $sql .= " AND ps.extends LIKE '%%3%' ";
398 $params[3] = array($usedFor, 'Integer');
401 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
403 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
404 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
408 * Find a price_set_id associated with the given option value or field ID
410 * @param array $params
411 * (reference) an assoc array of name/value pairs.
412 * array may contain either option id or
415 * @return integer|NULL price set id on success, null otherwise
418 public static function getSetId(&$params) {
421 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
422 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
423 $fieldValue->id
= $oid;
424 if ($fieldValue->find(TRUE)) {
425 $fid = $fieldValue->price_field_id
;
429 $fid = CRM_Utils_Array
::value('fid', $params);
433 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
440 * Return an associative array of all price sets
442 * @param bool $withInactive
443 * Whether or not to include inactive entries.
444 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
447 * associative array of id => name
449 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
452 DISTINCT ( price_set_id ) as id, title
457 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
459 if (!$withInactive) {
460 $query .= ' AND civicrm_price_set.is_active = 1 ';
463 if (self
::eventPriceSetDomainID()) {
464 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
467 $priceSets = array();
469 if ($extendComponentName) {
470 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
474 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
477 $dao = CRM_Core_DAO
::executeQuery($query);
478 while ($dao->fetch()) {
479 $priceSets[$dao->id
] = $dao->title
;
485 * Get price set details
487 * An array containing price set details (including price fields) is returned
490 * @param bool $required
491 * @param bool $validOnly
493 * @internal param int $setId - price set id whose details are needed
496 * array consisting of field details
498 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
502 $priceFields = array(
511 'is_display_amounts',
520 if ($required == TRUE) {
521 $priceFields[] = 'is_required';
525 $select = 'SELECT ' . implode(',', $priceFields);
526 $from = ' FROM civicrm_price_field';
529 $params[1] = array($setID, 'Integer');
531 WHERE price_set_id = %1
536 $currentTime = date('YmdHis');
538 AND ( active_on IS NULL OR active_on <= {$currentTime} )
539 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
543 $orderBy = ' ORDER BY weight';
545 $sql = $select . $from . $where . $dateSelect . $orderBy;
547 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
549 $visibility = CRM_Core_PseudoConstant
::visibility('name');
550 while ($dao->fetch()) {
553 $setTree[$setID]['fields'][$fieldID] = array();
554 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
556 foreach ($priceFields as $field) {
557 if ($field == 'id' ||
is_null($dao->$field)) {
561 if ($field == 'visibility_id') {
562 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
564 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
566 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
569 // also get the pre and post help from this price set
571 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
572 FROM civicrm_price_set
574 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
576 $setTree[$setID]['extends'] = $dao->extends;
577 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
578 $setTree[$setID]['help_pre'] = $dao->help_pre
;
579 $setTree[$setID]['help_post'] = $dao->help_post
;
580 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
586 * Get the Price Field ID. We call this function when more than one being present would represent an error
587 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
588 * @param array $priceSet
590 * @throws CRM_Core_Exception
593 public static function getOnlyPriceFieldID(array $priceSet) {
594 if (count($priceSet['fields']) > 1) {
595 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
597 return (int) implode('_', array_keys($priceSet['fields']));
601 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
602 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
603 * @param array $priceSet
605 * @throws CRM_Core_Exception
608 public static function getOnlyPriceFieldValueID(array $priceSet) {
609 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
610 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
611 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
613 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
618 * @param CRM_Core_Form $form
620 * @param string $entityTable
621 * @param bool $validOnly
622 * @param int $priceSetId
624 * @return bool|false|int|null
626 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
628 $priceSetId = self
::getFor($entityTable, $id);
631 //check if priceset is is_config
632 if (is_numeric($priceSetId)) {
633 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
634 $form->assign('quickConfig', 1);
639 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
640 $entityId = $entity = NULL;
642 switch ($entityTable) {
643 case 'civicrm_event':
644 $entity = 'participant';
645 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
646 $entityId = $form->_id
;
649 $entityId = $form->_participantId
;
653 case 'civicrm_contribution_page':
654 case 'civicrm_contribution':
655 $entity = 'contribution';
656 $entityId = $form->_id
;
660 if ($entityId && $entity) {
661 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
669 $form->_priceSetId
= $priceSetId;
670 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
671 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
672 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
674 //get the price set fields participant count.
675 if ($entityTable == 'civicrm_event') {
676 //get option count info.
677 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
678 if ($form->_priceSet
['optionsCountTotal']) {
679 $optionsCountDeails = array();
680 if (!empty($form->_priceSet
['fields'])) {
681 foreach ($form->_priceSet
['fields'] as $field) {
682 foreach ($field['options'] as $option) {
683 $count = CRM_Utils_Array
::value('count', $option, 0);
684 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
688 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
691 //get option max value info.
692 $optionsMaxValueTotal = 0;
693 $optionsMaxValueDetails = array();
695 if (!empty($form->_priceSet
['fields'])) {
696 foreach ($form->_priceSet
['fields'] as $field) {
697 foreach ($field['options'] as $option) {
698 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
699 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
700 $optionsMaxValueTotal +
= $maxVal;
705 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
706 if ($optionsMaxValueTotal) {
707 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
710 $form->set('priceSetId', $form->_priceSetId
);
711 $form->set('priceSet', $form->_priceSet
);
720 * @param array $params
722 * @param string $component
724 public static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
726 $totalPrice = $totalTax = 0;
727 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
729 $autoRenew = array();
730 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
732 foreach ($fields as $id => $field) {
733 if (empty($params["price_{$id}"]) ||
734 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
736 // skip if nothing was submitted for this field
740 switch ($field['html_type']) {
742 $firstOption = reset($field['options']);
743 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
744 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
745 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
746 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
747 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
749 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
750 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
751 if (array_key_exists($params['financial_type_id'], $taxRates)) {
752 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
753 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
754 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
755 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
756 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
759 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
763 //special case if user select -none-
764 if ($params["price_{$id}"] <= 0) {
767 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
768 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
769 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
770 $params['amount_priceset_level_radio'] = array();
771 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
772 if (isset($radioLevel)) {
773 $radioLevel = array_merge($radioLevel,
774 array_keys($params['amount_priceset_level_radio'])
778 $radioLevel = array_keys($params['amount_priceset_level_radio']);
780 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
781 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
782 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
783 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
784 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
785 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
788 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
791 // auto_renew exists and is empty in some workflows, which php treat as a 0
792 // and hence we explicitly check to see if auto_renew is numeric
793 isset($lineItem[$optionValueId]['auto_renew']) &&
794 is_numeric($lineItem[$optionValueId]['auto_renew'])
796 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
801 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
802 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
803 $optionLabel = $field['options'][$optionValueId]['label'];
804 $params['amount_priceset_level_select'] = array();
805 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
806 if (isset($selectLevel)) {
807 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
810 $selectLevel = array_keys($params['amount_priceset_level_select']);
812 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
813 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
814 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
815 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
817 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
820 isset($lineItem[$optionValueId]['auto_renew']) &&
821 is_numeric($lineItem[$optionValueId]['auto_renew'])
823 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
828 $params['amount_priceset_level_checkbox'] = $optionIds = array();
829 foreach ($params["price_{$id}"] as $optionId => $option) {
830 $optionIds[] = $optionId;
831 $optionLabel = $field['options'][$optionId]['label'];
832 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
833 if (isset($checkboxLevel)) {
834 $checkboxLevel = array_unique(array_merge(
836 array_keys($params['amount_priceset_level_checkbox'])
841 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
844 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
845 foreach ($optionIds as $optionId) {
846 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
847 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
848 $totalTax +
= $field['options'][$optionId]['tax_amount'];
850 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
853 isset($lineItem[$optionId]['auto_renew']) &&
854 is_numeric($lineItem[$optionId]['auto_renew'])
856 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
863 $amount_level = array();
864 $totalParticipant = 0;
865 if (is_array($lineItem)) {
866 foreach ($lineItem as $values) {
867 $totalParticipant +
= $values['participant_count'];
868 if ($values['html_type'] == 'Text') {
869 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
872 $amount_level[] = $values['label'];
876 $displayParticipantCount = '';
877 if ($totalParticipant > 0) {
878 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
880 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
881 $params['amount'] = $totalPrice;
882 $params['tax_amount'] = $totalTax;
884 foreach ($autoRenew as $dontCare => $eachAmount) {
886 unset($autoRenew[$dontCare]);
889 if (count($autoRenew) > 1) {
890 $params['autoRenew'] = $autoRenew;
896 * Build the price set form.
898 * @param CRM_Core_Form $form
902 public static function buildPriceSet(&$form) {
903 $priceSetId = $form->get('priceSetId');
908 $validFieldsOnly = TRUE;
909 $className = CRM_Utils_System
::getClassName($form);
910 if (in_array($className, array(
911 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
912 $validFieldsOnly = FALSE;
915 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
916 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
917 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
918 $form->_quickConfig
= $quickConfig = 0;
919 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
923 $form->assign('quickConfig', $quickConfig);
924 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
925 $form->_quickConfig
= $quickConfig;
927 $form->assign('priceSet', $form->_priceSet
);
929 $component = 'contribution';
930 if ($className == 'CRM_Member_Form_Membership') {
931 $component = 'membership';
934 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
935 $feeBlock = &$form->_values
['fee'];
936 if (!empty($form->_useForMember
)) {
937 $component = 'membership';
941 $feeBlock = &$form->_priceSet
['fields'];
945 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
947 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
948 $adminFieldVisible = FALSE;
949 if (CRM_Core_Permission
::check('administer CiviCRM')) {
950 $adminFieldVisible = TRUE;
953 foreach ($feeBlock as $id => $field) {
954 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
955 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
958 $options = CRM_Utils_Array
::value('options', $field);
959 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
960 $userid = $form->getVar('_membershipContactID');
961 $checklifetime = self
::checkCurrentMembership($options, $userid);
962 if ($checklifetime) {
963 $form->assign('ispricelifetime', TRUE);
966 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
969 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
970 'price_' . $field['id'],
973 CRM_Utils_Array
::value('is_required', $field, FALSE),
982 * Check the current Membership
983 * having end date null.
985 public static function checkCurrentMembership(&$options, $userid) {
986 if (!$userid ||
empty($options)) {
989 static $_contact_memberships = array();
990 $checklifetime = FALSE;
991 foreach ($options as $key => $value) {
992 if (!empty($value['membership_type_id'])) {
993 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
994 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
996 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
997 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
998 unset($options[$key]);
999 $checklifetime = TRUE;
1003 if ($checklifetime) {
1012 * Set daefult the price set fields.
1014 * @param CRM_Core_Form $form
1019 public static function setDefaultPriceSet(&$form, &$defaults) {
1020 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1024 foreach ($form->_priceSet
['fields'] as $key => $val) {
1025 foreach ($val['options'] as $keys => $values) {
1026 if ($values['is_default']) {
1027 if ($val['html_type'] == 'CheckBox') {
1028 $defaults["price_{$key}"][$keys] = 1;
1031 $defaults["price_{$key}"] = $keys;
1040 * Supports event create function by setting up required price sets, not tested but expect
1041 * it will work for contribution page
1042 * @param array $params
1043 * As passed to api/bao create fn.
1044 * @param CRM_Core_DAO $entity
1045 * Object for given entity.
1046 * @param string $entityName
1047 * Name of entity - e.g event.
1049 public static function setPriceSets(&$params, $entity, $entityName) {
1050 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1053 // CRM-14069 note that we may as well start by assuming more than one.
1054 // currently the form does not pass in as an array & will be skipped
1055 // test is passing in as an array but I feel the api should have a metadata that allows
1056 // transform of single to array - seems good for managing transitions - in which case all api
1057 // calls that set price_set_id will hit this
1058 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1059 // all separated values, strings, json half-separated values (in participant we hit this)
1060 // to be converted to json @ api layer
1061 $pse = new CRM_Price_DAO_PriceSetEntity();
1062 $pse->entity_table
= 'civicrm_' . $entityName;
1063 $pse->entity_id
= $entity->id
;
1064 while ($pse->fetch()) {
1065 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1066 // note an even more aggressive form of this deletion currently happens in event form
1067 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1068 // on the participant record
1069 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1070 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1074 foreach ($params['price_set_id'] as $priceSetID) {
1075 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1076 //@todo - how should we do this - copied from form
1077 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1078 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1079 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1084 * Get field ids of a price set
1094 public static function getFieldIds($id) {
1095 $priceField = new CRM_Price_DAO_PriceField();
1096 $priceField->price_set_id
= $id;
1097 $priceField->find();
1098 while ($priceField->fetch()) {
1099 $var[] = $priceField->id
;
1105 * make a copy of a price set, including
1109 * The price set id to copy.
1111 * @return the copy object
1114 public static function copy($id) {
1115 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1117 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1120 'title' => ' ' . $title,
1121 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1125 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1131 //copying all the blocks pertaining to the price set
1132 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1133 array('price_set_id' => $id),
1134 array('price_set_id' => $copy->id
)
1136 if (!empty($copyPriceField)) {
1137 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1139 //copy option group and values
1140 foreach ($price as $originalId => $copyId) {
1141 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1142 array('price_field_id' => $originalId),
1143 array('price_field_id' => $copyId)
1149 CRM_Utils_Hook
::copy('Set', $copy);
1154 * check price set permission
1161 public static function checkPermission($sid) {
1162 if ($sid && self
::eventPriceSetDomainID()) {
1163 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1164 if (CRM_Core_Config
::domainID() != $domain_id) {
1165 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1172 * Get the sum of participant count
1173 * for all fields of given price set.
1178 * @param bool $onlyActive
1180 * @return int|null|string
1183 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1191 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1194 static $pricesetFieldCount = array();
1195 if (!isset($pricesetFieldCount[$sid])) {
1197 SELECT sum(value.count) as totalCount
1198 FROM civicrm_price_field_value value
1199 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1200 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1204 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1205 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1208 return $pricesetFieldCount[$sid];
1216 public static function getMembershipCount($ids) {
1218 SELECT count( pfv.id ) AS count, pfv.id AS id
1219 FROM civicrm_price_field_value pfv
1220 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1221 WHERE pfv.id IN ( $ids )
1222 GROUP BY mt.member_of_contact_id";
1224 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1227 while ($crmDAO->fetch()) {
1228 $count[$crmDAO->id
] = $crmDAO->count
;
1235 * Check if auto renew option should be shown
1237 * @param int $priceSetId
1241 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1243 public static function checkAutoRenewForPriceSet($priceSetId) {
1244 // auto-renew option should be visible if membership types associated with all the fields has
1245 // been set for auto-renew option
1246 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1248 // get the membership type auto renew option and check if required or optional
1249 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1250 FROM civicrm_price_field_value pfv
1251 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1252 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1253 WHERE pf.price_set_id = %1
1254 AND pf.is_active = 1
1255 AND pfv.is_active = 1';
1257 $params = array(1 => array($priceSetId, 'Integer'));
1259 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1260 $autoRenewOption = 2;
1261 $interval = $unit = array();
1262 while ($dao->fetch()) {
1263 if (!$dao->auto_renew
) {
1264 $autoRenewOption = 0;
1267 if ($dao->auto_renew
== 1) {
1268 $autoRenewOption = 1;
1271 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1272 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1275 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1276 return $autoRenewOption;
1284 * Retrieve auto renew frequency and interval
1286 * @param int $priceSetId
1290 * associate array of frequency interval and unit
1293 public static function getRecurDetails($priceSetId) {
1294 $query = 'SELECT mt.duration_interval, mt.duration_unit
1295 FROM civicrm_price_field_value pfv
1296 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1297 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1298 WHERE pf.price_set_id = %1 LIMIT 1';
1300 $params = array(1 => array($priceSetId, 'Integer'));
1301 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1303 return array($dao->duration_interval
, $dao->duration_unit
);
1309 public static function eventPriceSetDomainID() {
1310 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1311 'event_price_set_domain_id',
1317 * Update the is_quick_config flag in the db
1320 * Id of the database record.
1321 * @param bool $isQuickConfigValue we want to set the is_quick_config field.
1322 * Value we want to set the is_quick_config field.
1325 * DAO object on sucess, null otherwise
1328 public static function setIsQuickConfig($id, $isQuickConfig) {
1329 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1333 * Check if price set id provides option for
1334 * user to select both auto-renew and non-auto-renew memberships
1338 public static function checkMembershipPriceSet($id) {
1341 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1342 FROM civicrm_price_field_value pfv
1343 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1344 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1345 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1349 $params = array(1 => array($id, 'Integer'));
1350 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1352 $autoRenew = array();
1353 //FIXME: do a comprehensive check of whether
1354 //2 membership types can be selected
1355 //instead of comparing all of them
1356 while ($dao->fetch()) {
1357 //temp fix for #CRM-10370
1358 //if its NULL consider it '0' i.e. 'No auto-renew option'
1359 $daoAutoRenew = $dao->auto_renew
;
1360 if ($daoAutoRenew === NULL) {
1363 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1366 $autoRenew[] = $daoAutoRenew;
1372 * Copy priceSet when event/contibution page is copied
1374 * @param string $baoName
1377 * Old event/contribution page id.
1379 * Newly created event/contribution page id.
1381 public static function copyPriceSet($baoName, $id, $newId) {
1382 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1384 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1385 if ($isQuickConfig) {
1386 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1387 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1390 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1393 'entity_table' => $baoName,
1395 array('entity_id' => $newId)
1398 // copy event discount
1399 if ($baoName == 'civicrm_event') {
1400 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1401 foreach ($discount as $discountId => $setId) {
1403 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1405 CRM_Core_DAO
::copyGeneric(
1406 'CRM_Core_DAO_Discount',
1408 'id' => $discountId,
1411 'entity_id' => $newId,
1412 'price_set_id' => $copyPriceSet->id
,
1421 * Function to set tax_amount and tax_rate in LineItem
1423 public static function setLineItem($field, $lineItem, $optionValueId) {
1424 if ($field['html_type'] == 'Text') {
1425 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1428 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1430 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1431 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1432 $lineItem[$optionValueId]['tax_rate'] = $taxRate;