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 (reference) an assoc array of name/value pairs
62 * @return CRM_Price_DAO_PriceSet object
65 public static function create(&$params) {
66 if(empty($params['id']) && empty($params['name'])) {
67 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
69 if (!empty($params['extends']) && is_array($params['extends'])) {
70 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
72 $priceSetBAO = new CRM_Price_BAO_PriceSet();
73 $priceSetBAO->copyValues($params);
74 if (self
::eventPriceSetDomainID()) {
75 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
77 return $priceSetBAO->save();
81 * Fetch object based on array of properties
83 * @param array $params (reference ) an assoc array of name/value pairs
84 * @param array $defaults (reference ) an assoc array to hold the flattened values
86 * @return CRM_Price_DAO_PriceSet object
89 public static function retrieve(&$params, &$defaults) {
90 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
94 * Update the is_active flag in the db
96 * @param int $id id of the database record
99 * @internal param bool $is_active value we want to set the is_active field
101 * @return Object DAO object on sucess, null otherwise
104 public 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
119 public static function getDefaultPriceSet($entity = 'contribution') {
120 if (!empty(self
::$_defaultPriceSet[$entity])) {
121 return self
::$_defaultPriceSet[$entity];
123 $entityName = 'default_contribution_amount';
124 if ($entity == 'membership') {
125 $entityName = 'default_membership_type_amount';
129 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
130 FROM civicrm_price_set ps
131 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
132 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
133 WHERE ps.name = '{$entityName}'
136 $dao = CRM_Core_DAO
::executeQuery($sql);
137 self
::$_defaultPriceSet[$entity] = array();
138 while ($dao->fetch()) {
139 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
140 'setID' => $dao->setID
,
141 'priceFieldID' => $dao->priceFieldID
,
142 'name' => $dao->name
,
143 'label' => $dao->label
,
144 'priceFieldValueID' => $dao->priceFieldValueID
,
145 'membership_type_id' => $dao->membership_type_id
,
146 'amount' => $dao->amount
,
147 'financial_type_id' => $dao->financial_type_id
,
151 return self
::$_defaultPriceSet[$entity];
155 * Get the price set title.
157 * @param int $id id of price set
159 * @return string title
164 public static function getTitle($id) {
165 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
169 * Return a list of all forms which use this price set.
171 * @param int $id id of price set
172 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
176 public static function &getUsedBy($id, $simpleReturn = FALSE) {
177 $usedBy = $forms = $tables = array();
179 SELECT entity_table, entity_id
180 FROM civicrm_price_set_entity
181 WHERE price_set_id = %1";
182 $params = array(1 => array($id, 'Integer'));
183 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
185 while ($crmFormDAO->fetch()) {
186 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
187 $tables[] = $crmFormDAO->entity_table
;
189 // Return only tables
190 if ($simpleReturn == 'table') {
195 SELECT cli.entity_table, cli.entity_id
196 FROM civicrm_line_item cli
197 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
198 WHERE cpf.price_set_id = %1";
199 $params = array(1 => array($id, 'Integer'));
200 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
201 while ($crmFormDAO->fetch()) {
202 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
203 $tables[] = $crmFormDAO->entity_table
;
209 // Return only entity data
210 if ($simpleReturn == 'entity') {
213 foreach ($forms as $table => $entities) {
215 case 'civicrm_event':
216 $ids = implode(',', $entities);
217 $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
218 FROM civicrm_event ce
219 LEFT JOIN civicrm_option_value ON
220 ( ce.event_type_id = civicrm_option_value.value )
221 LEFT JOIN civicrm_option_group ON
222 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
224 civicrm_option_group.name = 'event_type' AND
227 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
228 while ($crmDAO->fetch()) {
229 if ($crmDAO->isTemplate
) {
230 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
231 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
232 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
235 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
236 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
237 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
238 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
239 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
244 case 'civicrm_contribution_page':
245 $ids = implode(',', $entities);
246 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
247 FROM civicrm_contribution_page cp, civicrm_financial_type ct
248 WHERE ct.id = cp.financial_type_id AND
251 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
252 while ($crmDAO->fetch()) {
253 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
254 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
255 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
256 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
260 case 'civicrm_contribution':
261 case 'civicrm_membership':
262 case 'civicrm_participant':
267 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
276 * Delete the price set
278 * @param int $id Price Set id
280 * @return boolean false if fields exist for this set, true if the
281 * set could be deleted
285 public static function deleteSet($id) {
286 // remove from all inactive forms
287 $usedBy = self
::getUsedBy($id);
288 if (isset($usedBy['civicrm_event'])) {
289 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
290 $eventDAO = new CRM_Event_DAO_Event();
291 $eventDAO->id
= $eventId;
293 while ($eventDAO->fetch()) {
294 self
::removeFrom('civicrm_event', $eventDAO->id
);
299 // delete price fields
300 $priceField = new CRM_Price_DAO_PriceField();
301 $priceField->price_set_id
= $id;
303 while ($priceField->fetch()) {
304 // delete options first
305 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
308 $set = new CRM_Price_DAO_PriceSet();
310 return $set->delete();
314 * Link the price set with the specified table and id
316 * @param string $entityTable
317 * @param integer $entityId
318 * @param integer $priceSetId
322 public static function addTo($entityTable, $entityId, $priceSetId) {
323 // verify that the price set exists
324 $dao = new CRM_Price_DAO_PriceSet();
325 $dao->id
= $priceSetId;
331 $dao = new CRM_Price_DAO_PriceSetEntity();
332 // find if this already exists
333 $dao->entity_id
= $entityId;
334 $dao->entity_table
= $entityTable;
337 // add or update price_set_id
338 $dao->price_set_id
= $priceSetId;
343 * Delete price set for the given entity and id
345 * @param string $entityTable
346 * @param integer $entityId
350 public static function removeFrom($entityTable, $entityId) {
351 $dao = new CRM_Price_DAO_PriceSetEntity();
352 $dao->entity_table
= $entityTable;
353 $dao->entity_id
= $entityId;
354 return $dao->delete();
358 * Find a price_set_id associatied with the given table, id and usedFor
359 * Used For value for events:1, contribution:2, membership:3
361 * @param string $entityTable
362 * @param int $entityId
363 * @param int $usedFor ( price set that extends/used for particular component )
365 * @param null $isQuickConfig
366 * @param null $setName
368 * @return integer|false price_set_id, or false if none found
370 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
371 if (!$entityTable ||
!$entityId) {
375 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
376 FROM civicrm_price_set ps
377 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
378 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
379 if ($isQuickConfig) {
380 $sql .= ' AND ps.is_quick_config = 0 ';
382 $params = array(1 => array($entityTable, 'String'),
383 2 => array($entityId, 'Integer'),
386 $sql .= " AND ps.extends LIKE '%%3%' ";
387 $params[3] = array($usedFor, 'Integer');
390 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
392 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
393 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
397 * Find a price_set_id associated with the given option value or field ID
399 * @param array $params (reference) an assoc array of name/value pairs
400 * array may contain either option id or
403 * @return integer|NULL price set id on success, null otherwise
406 public static function getSetId(&$params) {
409 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
410 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
411 $fieldValue->id
= $oid;
412 if ($fieldValue->find(TRUE)) {
413 $fid = $fieldValue->price_field_id
;
417 $fid = CRM_Utils_Array
::value('fid', $params);
421 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
428 * Return an associative array of all price sets
430 * @param bool $withInactive whether or not to include inactive entries
431 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
433 * @return array associative array of id => name
435 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
438 DISTINCT ( price_set_id ) as id, title
443 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
445 if (!$withInactive) {
446 $query .= ' AND civicrm_price_set.is_active = 1 ';
449 if (self
::eventPriceSetDomainID()) {
450 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
453 $priceSets = array();
455 if ($extendComponentName) {
456 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
460 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
463 $dao = CRM_Core_DAO
::executeQuery($query);
464 while ($dao->fetch()) {
465 $priceSets[$dao->id
] = $dao->title
;
471 * Get price set details
473 * An array containing price set details (including price fields) is returned
476 * @param bool $required
477 * @param bool $validOnly
479 * @internal param int $setId - price set id whose details are needed
481 * @return array $setTree - array consisting of field details
483 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
487 $priceFields = array(
496 'is_display_amounts',
505 if ($required == TRUE) {
506 $priceFields[] = 'is_required';
510 $select = 'SELECT ' . implode(',', $priceFields);
511 $from = ' FROM civicrm_price_field';
514 $params[1] = array($setID, 'Integer');
516 WHERE price_set_id = %1
521 $currentTime = date('YmdHis');
523 AND ( active_on IS NULL OR active_on <= {$currentTime} )
524 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
528 $orderBy = ' ORDER BY weight';
530 $sql = $select . $from . $where . $dateSelect . $orderBy;
532 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
534 $visibility = CRM_Core_PseudoConstant
::visibility('name');
535 while ($dao->fetch()) {
538 $setTree[$setID]['fields'][$fieldID] = array();
539 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
541 foreach ($priceFields as $field) {
542 if ($field == 'id' ||
is_null($dao->$field)) {
546 if ($field == 'visibility_id') {
547 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
549 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
551 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
554 // also get the pre and post help from this price set
556 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
557 FROM civicrm_price_set
559 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
561 $setTree[$setID]['extends'] = $dao->extends;
562 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
563 $setTree[$setID]['help_pre'] = $dao->help_pre
;
564 $setTree[$setID]['help_post'] = $dao->help_post
;
565 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
571 * Get the Price Field ID. We call this function when more than one being present would represent an error
572 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
573 * @param array $priceSet
575 * @throws CRM_Core_Exception
578 public static function getOnlyPriceFieldID(array $priceSet) {
579 if(count($priceSet['fields']) > 1) {
580 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
582 return (int) implode('_', array_keys($priceSet['fields']));
586 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
587 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
588 * @param array $priceSet
590 * @throws CRM_Core_Exception
593 public static function getOnlyPriceFieldValueID(array $priceSet) {
594 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
595 if(count($priceSet['fields'][$priceFieldID]['options']) > 1) {
596 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
598 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
603 * @param CRM_Core_Form $form
605 * @param string $entityTable
606 * @param bool $validOnly
607 * @param int $priceSetId
609 * @return bool|false|int|null
611 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
613 $priceSetId = self
::getFor($entityTable, $id);
616 //check if priceset is is_config
617 if (is_numeric($priceSetId)) {
618 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
619 $form->assign('quickConfig', 1);
624 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
625 $entityId = $entity = NULL;
627 switch ($entityTable) {
628 case 'civicrm_event':
629 $entity = 'participant';
630 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
631 $entityId = $form->_id
;
634 $entityId = $form->_participantId
;
638 case 'civicrm_contribution_page':
639 case 'civicrm_contribution':
640 $entity = 'contribution';
641 $entityId = $form->_id
;
645 if ($entityId && $entity) {
646 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
654 $form->_priceSetId
= $priceSetId;
655 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
656 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
657 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
659 //get the price set fields participant count.
660 if ($entityTable == 'civicrm_event') {
661 //get option count info.
662 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
663 if ($form->_priceSet
['optionsCountTotal']) {
664 $optionsCountDeails = array();
665 if (!empty($form->_priceSet
['fields'])) {
666 foreach ($form->_priceSet
['fields'] as $field) {
667 foreach ($field['options'] as $option) {
668 $count = CRM_Utils_Array
::value('count', $option, 0);
669 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
673 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
676 //get option max value info.
677 $optionsMaxValueTotal = 0;
678 $optionsMaxValueDetails = array();
680 if (!empty($form->_priceSet
['fields'])) {
681 foreach ($form->_priceSet
['fields'] as $field) {
682 foreach ($field['options'] as $option) {
683 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
684 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
685 $optionsMaxValueTotal +
= $maxVal;
690 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
691 if ($optionsMaxValueTotal) {
692 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
695 $form->set('priceSetId', $form->_priceSetId
);
696 $form->set('priceSet', $form->_priceSet
);
705 * @param array $params
707 * @param string $component
709 public static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
711 $totalPrice = $totalTax = 0;
712 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
714 $autoRenew = array();
715 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
717 foreach ($fields as $id => $field) {
718 if (empty($params["price_{$id}"]) ||
719 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
721 // skip if nothing was submitted for this field
725 switch ($field['html_type']) {
727 $firstOption = reset($field['options']);
728 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
729 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
730 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
731 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
732 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
734 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
735 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
736 if (array_key_exists($params['financial_type_id'], $taxRates)) {
737 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
738 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
739 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
740 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
741 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
744 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
748 //special case if user select -none-
749 if ($params["price_{$id}"] <= 0) {
752 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
753 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
754 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
755 $params['amount_priceset_level_radio'] = array();
756 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
757 if (isset($radioLevel)) {
758 $radioLevel = array_merge($radioLevel,
759 array_keys($params['amount_priceset_level_radio'])
763 $radioLevel = array_keys($params['amount_priceset_level_radio']);
765 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
766 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
767 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
768 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
769 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
770 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
773 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
776 // auto_renew exists and is empty in some workflows, which php treat as a 0
777 // and hence we explicitly check to see if auto_renew is numeric
778 isset($lineItem[$optionValueId]['auto_renew']) &&
779 is_numeric($lineItem[$optionValueId]['auto_renew'])
781 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
786 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
787 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
788 $optionLabel = $field['options'][$optionValueId]['label'];
789 $params['amount_priceset_level_select'] = array();
790 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
791 if (isset($selectLevel)) {
792 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
795 $selectLevel = array_keys($params['amount_priceset_level_select']);
797 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
798 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
799 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
800 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
802 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
805 isset($lineItem[$optionValueId]['auto_renew']) &&
806 is_numeric($lineItem[$optionValueId]['auto_renew'])
808 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
813 $params['amount_priceset_level_checkbox'] = $optionIds = array();
814 foreach ($params["price_{$id}"] as $optionId => $option) {
815 $optionIds[] = $optionId;
816 $optionLabel = $field['options'][$optionId]['label'];
817 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
818 if (isset($checkboxLevel)) {
819 $checkboxLevel = array_unique(array_merge(
821 array_keys($params['amount_priceset_level_checkbox'])
826 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
829 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
830 foreach ($optionIds as $optionId) {
831 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
832 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
833 $totalTax +
= $field['options'][$optionId]['tax_amount'];
835 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
838 isset($lineItem[$optionId]['auto_renew']) &&
839 is_numeric($lineItem[$optionId]['auto_renew'])
841 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
848 $amount_level = array();
849 $totalParticipant = 0;
850 if (is_array($lineItem)) {
851 foreach ($lineItem as $values) {
852 $totalParticipant +
= $values['participant_count'];
853 if ($values['html_type'] == 'Text') {
854 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
857 $amount_level[] = $values['label'];
861 $displayParticipantCount = '';
862 if ($totalParticipant > 0) {
863 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
865 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
866 $params['amount'] = $totalPrice;
867 $params['tax_amount'] = $totalTax;
869 foreach ($autoRenew as $dontCare => $eachAmount) {
871 unset($autoRenew[$dontCare]);
874 if (count($autoRenew) > 1 ) {
875 $params['autoRenew'] = $autoRenew;
881 * Build the price set form.
883 * @param CRM_Core_Form $form
887 public static function buildPriceSet(&$form) {
888 $priceSetId = $form->get('priceSetId');
893 $validFieldsOnly = TRUE;
894 $className = CRM_Utils_System
::getClassName($form);
895 if (in_array($className, array(
896 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
897 $validFieldsOnly = FALSE;
900 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
901 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
902 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
903 $form->_quickConfig
= $quickConfig = 0;
904 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
908 $form->assign('quickConfig', $quickConfig);
909 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
910 $form->_quickConfig
= $quickConfig;
912 $form->assign('priceSet', $form->_priceSet
);
914 $component = 'contribution';
915 if ($className == 'CRM_Member_Form_Membership') {
916 $component = 'membership';
919 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
920 $feeBlock = &$form->_values
['fee'];
921 if (!empty($form->_useForMember
)) {
922 $component = 'membership';
926 $feeBlock = &$form->_priceSet
['fields'];
930 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
932 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
933 $adminFieldVisible = false;
934 if (CRM_Core_Permission
::check('administer CiviCRM')) {
935 $adminFieldVisible = true;
938 foreach ($feeBlock as $id => $field) {
939 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
940 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
943 $options = CRM_Utils_Array
::value('options', $field);
944 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
945 $userid = $form->getVar('_membershipContactID');
946 $checklifetime = self
::checkCurrentMembership($options, $userid);
947 if ($checklifetime) {
948 $form->assign('ispricelifetime', TRUE);
951 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
954 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
955 'price_' . $field['id'],
958 CRM_Utils_Array
::value('is_required', $field, FALSE),
967 * Check the current Membership
968 * having end date null.
970 public static function checkCurrentMembership(&$options, $userid) {
971 if (!$userid ||
empty($options)) {
974 static $_contact_memberships = array();
975 $checklifetime = FALSE;
976 foreach ($options as $key => $value) {
977 if (!empty($value['membership_type_id'])) {
978 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
979 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
981 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
982 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
983 unset($options[$key]);
984 $checklifetime = TRUE;
988 if ($checklifetime) {
997 * Set daefult the price set fields.
999 * @param CRM_Core_Form $form
1002 * @return array $defaults
1004 public static function setDefaultPriceSet(&$form, &$defaults) {
1005 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1009 foreach ($form->_priceSet
['fields'] as $key => $val) {
1010 foreach ($val['options'] as $keys => $values) {
1011 if ($values['is_default']) {
1012 if ($val['html_type'] == 'CheckBox') {
1013 $defaults["price_{$key}"][$keys] = 1;
1016 $defaults["price_{$key}"] = $keys;
1025 * Supports event create function by setting up required price sets, not tested but expect
1026 * it will work for contribution page
1027 * @param array $params as passed to api/bao create fn
1028 * @param CRM_Core_DAO $entity object for given entity
1029 * @param string $entityName name of entity - e.g event
1031 public static function setPriceSets(&$params, $entity, $entityName) {
1032 if(empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1035 // CRM-14069 note that we may as well start by assuming more than one.
1036 // currently the form does not pass in as an array & will be skipped
1037 // test is passing in as an array but I feel the api should have a metadata that allows
1038 // transform of single to array - seems good for managing transitions - in which case all api
1039 // calls that set price_set_id will hit this
1040 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1041 // all separated values, strings, json half-separated values (in participant we hit this)
1042 // to be converted to json @ api layer
1043 $pse = new CRM_Price_DAO_PriceSetEntity();
1044 $pse->entity_table
= 'civicrm_' . $entityName;
1045 $pse->entity_id
= $entity->id
;
1046 while ($pse->fetch()) {
1047 if(!in_array($pse->price_set_id
, $params['price_set_id'])) {
1048 // note an even more aggressive form of this deletion currently happens in event form
1049 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1050 // on the participant record
1051 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1052 CRM_Core_BAO_Discount
::del($entity->id
,'civicrm_' . $entityName);
1056 foreach ($params['price_set_id'] as $priceSetID) {
1057 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1058 //@todo - how should we do this - copied from form
1059 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1060 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1061 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1066 * Get field ids of a price set
1068 * @param int $id Price Set id
1070 * @return array of the field ids
1074 public static function getFieldIds($id) {
1075 $priceField = new CRM_Price_DAO_PriceField();
1076 $priceField->price_set_id
= $id;
1077 $priceField->find();
1078 while ($priceField->fetch()) {
1079 $var[] = $priceField->id
;
1085 * This function is to make a copy of a price set, including
1088 * @param int $id the price set id to copy
1090 * @return the copy object
1093 public static function copy($id) {
1094 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1096 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1098 'suffix' => array('title' => ' ' . $title,
1099 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1103 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1109 //copying all the blocks pertaining to the price set
1110 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1111 array('price_set_id' => $id),
1112 array('price_set_id' => $copy->id
)
1114 if (!empty($copyPriceField)) {
1115 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1117 //copy option group and values
1118 foreach ($price as $originalId => $copyId) {
1119 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1120 array('price_field_id' => $originalId),
1121 array('price_field_id' => $copyId)
1127 CRM_Utils_Hook
::copy('Set', $copy);
1132 * This function is to check price set permission
1134 * @param int $sid the price set id
1138 public static function checkPermission($sid) {
1139 if ($sid && self
::eventPriceSetDomainID()) {
1140 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1141 if (CRM_Core_Config
::domainID() != $domain_id) {
1142 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1149 * Get the sum of participant count
1150 * for all fields of given price set.
1152 * @param int $sid the price set id
1154 * @param bool $onlyActive
1156 * @return int|null|string
1159 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1167 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1170 static $pricesetFieldCount = array();
1171 if (!isset($pricesetFieldCount[$sid])) {
1173 SELECT sum(value.count) as totalCount
1174 FROM civicrm_price_field_value value
1175 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1176 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1180 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1181 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1184 return $pricesetFieldCount[$sid];
1192 public static function getMembershipCount($ids) {
1194 SELECT count( pfv.id ) AS count, pfv.id AS id
1195 FROM civicrm_price_field_value pfv
1196 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1197 WHERE pfv.id IN ( $ids )
1198 GROUP BY mt.member_of_contact_id";
1200 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1203 while ($crmDAO->fetch()) {
1204 $count[$crmDAO->id
] = $crmDAO->count
;
1211 * Check if auto renew option should be shown
1213 * @param int $priceSetId price set id
1215 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1217 public static function checkAutoRenewForPriceSet($priceSetId) {
1218 // auto-renew option should be visible if membership types associated with all the fields has
1219 // been set for auto-renew option
1220 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1222 // get the membership type auto renew option and check if required or optional
1223 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1224 FROM civicrm_price_field_value pfv
1225 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1226 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1227 WHERE pf.price_set_id = %1
1228 AND pf.is_active = 1
1229 AND pfv.is_active = 1';
1231 $params = array(1 => array($priceSetId, 'Integer'));
1233 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1234 $autoRenewOption = 2;
1235 $interval = $unit = array();
1236 while ($dao->fetch()) {
1237 if (!$dao->auto_renew
) {
1238 $autoRenewOption = 0;
1241 if ($dao->auto_renew
== 1) {
1242 $autoRenewOption = 1;
1245 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1246 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1249 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1250 return $autoRenewOption;
1258 * Retrieve auto renew frequency and interval
1260 * @param int $priceSetId price set id
1262 * @return array associate array of frequency interval and unit
1265 public static function getRecurDetails($priceSetId) {
1266 $query = 'SELECT mt.duration_interval, mt.duration_unit
1267 FROM civicrm_price_field_value pfv
1268 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1269 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1270 WHERE pf.price_set_id = %1 LIMIT 1';
1272 $params = array(1 => array($priceSetId, 'Integer'));
1273 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1275 return array($dao->duration_interval
, $dao->duration_unit
);
1281 public static function eventPriceSetDomainID() {
1282 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1283 'event_price_set_domain_id',
1289 * Update the is_quick_config flag in the db
1291 * @param int $id id of the database record
1292 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1294 * @return Object DAO object on sucess, null otherwise
1297 public static function setIsQuickConfig($id, $isQuickConfig) {
1298 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1302 * Check if price set id provides option for
1303 * 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 * @param string $baoName BAO name
1345 * @param int $id old event/contribution page id
1346 * @param int $newId newly created event/contribution page id
1348 public static function copyPriceSet($baoName, $id, $newId) {
1349 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1351 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1352 if($isQuickConfig) {
1353 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1354 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1357 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1360 'entity_table' => $baoName,
1362 array('entity_id' => $newId)
1365 // copy event discount
1366 if ($baoName == 'civicrm_event') {
1367 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1368 foreach ($discount as $discountId => $setId) {
1370 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1372 CRM_Core_DAO
::copyGeneric(
1373 'CRM_Core_DAO_Discount',
1375 'id' => $discountId,
1378 'entity_id' => $newId,
1379 'price_set_id' => $copyPriceSet->id
,
1388 * Function to set tax_amount and tax_rate in LineItem
1392 public static function setLineItem($field, $lineItem, $optionValueId) {
1393 if ($field['html_type'] == 'Text') {
1394 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1397 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1399 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1400 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1401 $lineItem[$optionValueId]['tax_rate'] = $taxRate;