3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business object for managing price sets
40 class CRM_Price_BAO_PriceSet
extends CRM_Price_DAO_PriceSet
{
43 * static field for default price set details
48 static $_defaultPriceSet = NULL;
53 function __construct() {
54 parent
::__construct();
58 * takes an associative array and creates a price set object
60 * @param array $params (reference) an assoc array of name/value pairs
62 * @return object CRM_Price_DAO_PriceSet object
66 static function create(&$params) {
67 if(empty($params['id']) && empty($params['name'])) {
68 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
70 $priceSetBAO = new CRM_Price_BAO_PriceSet();
71 $priceSetBAO->copyValues($params);
72 if (self
::eventPriceSetDomainID()) {
73 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
75 return $priceSetBAO->save();
79 * Takes a bunch of params that are needed to match certain criteria and
80 * retrieves the relevant objects. Typically the valid params are only
81 * contact_id. We'll tweak this function to be more full featured over a period
82 * of time. This is the inverse function of create. It also stores all the retrieved
83 * values in the default array
85 * @param array $params (reference ) an assoc array of name/value pairs
86 * @param array $defaults (reference ) an assoc array to hold the flattened values
88 * @return object CRM_Price_DAO_PriceSet object
92 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
99 * @param int $id id of the database record
102 * @internal param bool $is_active value we want to set the is_active field
104 * @return Object DAO object on sucess, null otherwise
108 static function setIsActive($id, $isActive) {
109 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
113 * Calculate the default price set id
114 * assigned to the contribution/membership etc
116 * @param string $entity
118 * @return array $defaultPriceSet default price set
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.
162 * @param int $id id of price set
164 * @return string 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.
177 * @param int $id id of price set
178 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
182 public static function &getUsedBy($id, $simpleReturn = FALSE) {
183 $usedBy = $forms = $tables = array();
185 SELECT entity_table, entity_id
186 FROM civicrm_price_set_entity
187 WHERE price_set_id = %1";
188 $params = array(1 => array($id, 'Integer'));
189 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
191 while ($crmFormDAO->fetch()) {
192 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
193 $tables[] = $crmFormDAO->entity_table
;
195 // Return only tables
196 if ($simpleReturn == 'table') {
201 SELECT cli.entity_table, cli.entity_id
202 FROM civicrm_line_item cli
203 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
204 WHERE cpf.price_set_id = %1";
205 $params = array(1 => array($id, 'Integer'));
206 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
207 while ($crmFormDAO->fetch()) {
208 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
209 $tables[] = $crmFormDAO->entity_table
;
215 // Return only entity data
216 if ($simpleReturn == 'entity') {
219 foreach ($forms as $table => $entities) {
221 case 'civicrm_event':
222 $ids = implode(',', $entities);
223 $queryString = "SELECT ce.id as id, ce.title as title, ce.is_public as isPublic, ce.start_date as startDate, ce.end_date as endDate, civicrm_option_value.label as eventType, ce.is_template as isTemplate, ce.template_title as templateTitle
224 FROM civicrm_event ce
225 LEFT JOIN civicrm_option_value ON
226 ( ce.event_type_id = civicrm_option_value.value )
227 LEFT JOIN civicrm_option_group ON
228 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
230 civicrm_option_group.name = 'event_type' AND
233 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
234 while ($crmDAO->fetch()) {
235 if ($crmDAO->isTemplate
) {
236 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
237 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
238 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
241 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
242 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
243 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
244 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
245 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
250 case 'civicrm_contribution_page':
251 $ids = implode(',', $entities);
252 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
253 FROM civicrm_contribution_page cp, civicrm_financial_type ct
254 WHERE ct.id = cp.financial_type_id AND
257 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
258 while ($crmDAO->fetch()) {
259 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
260 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
261 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
262 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
266 case 'civicrm_contribution':
267 case 'civicrm_membership':
268 case 'civicrm_participant':
273 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
282 * Delete the price set
284 * @param int $id Price Set id
286 * @return boolean false if fields exist for this set, true if the
287 * set could be deleted
292 public static function deleteSet($id) {
293 // remove from all inactive forms
294 $usedBy = self
::getUsedBy($id);
295 if (isset($usedBy['civicrm_event'])) {
296 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
297 $eventDAO = new CRM_Event_DAO_Event();
298 $eventDAO->id
= $eventId;
300 while ($eventDAO->fetch()) {
301 self
::removeFrom('civicrm_event', $eventDAO->id
);
306 // delete price fields
307 $priceField = new CRM_Price_DAO_PriceField();
308 $priceField->price_set_id
= $id;
310 while ($priceField->fetch()) {
311 // delete options first
312 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
315 $set = new CRM_Price_DAO_PriceSet();
317 return $set->delete();
321 * Link the price set with the specified table and id
323 * @param string $entityTable
324 * @param integer $entityId
325 * @param integer $priceSetId
329 public static function addTo($entityTable, $entityId, $priceSetId) {
330 // verify that the price set exists
331 $dao = new CRM_Price_DAO_PriceSet();
332 $dao->id
= $priceSetId;
338 $dao = new CRM_Price_DAO_PriceSetEntity();
339 // find if this already exists
340 $dao->entity_id
= $entityId;
341 $dao->entity_table
= $entityTable;
344 // add or update price_set_id
345 $dao->price_set_id
= $priceSetId;
350 * Delete price set for the given entity and id
352 * @param string $entityTable
353 * @param integer $entityId
357 public static function removeFrom($entityTable, $entityId) {
358 $dao = new CRM_Price_DAO_PriceSetEntity();
359 $dao->entity_table
= $entityTable;
360 $dao->entity_id
= $entityId;
361 return $dao->delete();
365 * Find a price_set_id associatied with the given table, id and usedFor
366 * Used For value for events:1, contribution:2, membership:3
368 * @param string $entityTable
369 * @param int $entityId
370 * @param int $usedFor ( price set that extends/used for particular component )
372 * @param null $isQuickConfig
373 * @param null $setName
375 * @return integer|false price_set_id, or false if none found
377 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
378 if (!$entityTable ||
!$entityId) {
382 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
383 FROM civicrm_price_set ps
384 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
385 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
386 if ($isQuickConfig) {
387 $sql .= ' AND ps.is_quick_config = 0 ';
389 $params = array(1 => array($entityTable, 'String'),
390 2 => array($entityId, 'Integer'),
393 $sql .= " AND ps.extends LIKE '%%3%' ";
394 $params[3] = array($usedFor, 'Integer');
397 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
399 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
400 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
404 * Find a price_set_id associated with the given option value or field ID
406 * @param array $params (reference) an assoc array of name/value pairs
407 * array may contain either option id or
410 * @return integer|NULL price set id on success, null otherwise
414 public static function getSetId(&$params) {
417 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
418 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
419 $fieldValue->id
= $oid;
420 if ($fieldValue->find(TRUE)) {
421 $fid = $fieldValue->price_field_id
;
425 $fid = CRM_Utils_Array
::value('fid', $params);
429 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
436 * Return an associative array of all price sets
438 * @param bool $withInactive whether or not to include inactive entries
439 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
441 * @return array associative array of id => name
443 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
446 DISTINCT ( price_set_id ) as id, title
451 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
453 if (!$withInactive) {
454 $query .= ' AND civicrm_price_set.is_active = 1 ';
457 if (self
::eventPriceSetDomainID()) {
458 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
461 $priceSets = array();
463 if ($extendComponentName) {
464 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
468 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
471 $dao = CRM_Core_DAO
::executeQuery($query);
472 while ($dao->fetch()) {
473 $priceSets[$dao->id
] = $dao->title
;
479 * Get price set details
481 * An array containing price set details (including price fields) is returned
484 * @param bool $required
485 * @param bool $validOnly
487 * @internal param int $setId - price set id whose details are needed
489 * @return array $setTree - array consisting of field details
491 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
495 $priceFields = array(
504 'is_display_amounts',
513 if ($required == TRUE) {
514 $priceFields[] = 'is_required';
518 $select = 'SELECT ' . implode(',', $priceFields);
519 $from = ' FROM civicrm_price_field';
522 $params[1] = array($setID, 'Integer');
524 WHERE price_set_id = %1
529 $currentTime = date('YmdHis');
531 AND ( active_on IS NULL OR active_on <= {$currentTime} )
532 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
536 $orderBy = ' ORDER BY weight';
538 $sql = $select . $from . $where . $dateSelect . $orderBy;
540 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
542 $visibility = CRM_Core_PseudoConstant
::visibility('name');
543 while ($dao->fetch()) {
546 $setTree[$setID]['fields'][$fieldID] = array();
547 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
549 foreach ($priceFields as $field) {
550 if ($field == 'id' ||
is_null($dao->$field)) {
554 if ($field == 'visibility_id') {
555 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
557 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
559 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
562 // also get the pre and post help from this price set
564 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
565 FROM civicrm_price_set
567 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
569 $setTree[$setID]['extends'] = $dao->extends;
570 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
571 $setTree[$setID]['help_pre'] = $dao->help_pre
;
572 $setTree[$setID]['help_post'] = $dao->help_post
;
573 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
579 * Get the Price Field ID. We call this function when more than one being present would represent an error
580 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
581 * @param array $priceSet
583 * @throws CRM_Core_Exception
586 static function getOnlyPriceFieldID(array $priceSet) {
587 if(count($priceSet['fields']) > 1) {
588 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
590 return (int) implode('_', array_keys($priceSet['fields']));
594 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
595 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
596 * @param array $priceSet
598 * @throws CRM_Core_Exception
601 static function getOnlyPriceFieldValueID(array $priceSet) {
602 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
603 if(count($priceSet['fields'][$priceFieldID]['options']) > 1) {
604 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
606 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
611 * @param CRM_Core_Form $form
613 * @param string $entityTable
614 * @param bool $validOnly
615 * @param null $priceSetId
617 * @return bool|false|int|null
619 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
621 $priceSetId = self
::getFor($entityTable, $id);
624 //check if priceset is is_config
625 if (is_numeric($priceSetId)) {
626 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
627 $form->assign('quickConfig', 1);
632 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
633 $entityId = $entity = NULL;
635 switch ($entityTable) {
636 case 'civicrm_event':
637 $entity = 'participant';
638 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
639 $entityId = $form->_id
;
642 $entityId = $form->_participantId
;
646 case 'civicrm_contribution_page':
647 case 'civicrm_contribution':
648 $entity = 'contribution';
649 $entityId = $form->_id
;
653 if ($entityId && $entity) {
654 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
662 $form->_priceSetId
= $priceSetId;
663 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
664 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
665 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
667 //get the price set fields participant count.
668 if ($entityTable == 'civicrm_event') {
669 //get option count info.
670 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
671 if ($form->_priceSet
['optionsCountTotal']) {
672 $optionsCountDeails = array();
673 if (!empty($form->_priceSet
['fields'])) {
674 foreach ($form->_priceSet
['fields'] as $field) {
675 foreach ($field['options'] as $option) {
676 $count = CRM_Utils_Array
::value('count', $option, 0);
677 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
681 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
684 //get option max value info.
685 $optionsMaxValueTotal = 0;
686 $optionsMaxValueDetails = array();
688 if (!empty($form->_priceSet
['fields'])) {
689 foreach ($form->_priceSet
['fields'] as $field) {
690 foreach ($field['options'] as $option) {
691 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
692 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
693 $optionsMaxValueTotal +
= $maxVal;
698 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
699 if ($optionsMaxValueTotal) {
700 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
703 $form->set('priceSetId', $form->_priceSetId
);
704 $form->set('priceSet', $form->_priceSet
);
715 * @param string $component
717 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
719 $totalPrice = $totalTax = 0;
720 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
722 $autoRenew = array();
723 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
725 foreach ($fields as $id => $field) {
726 if (empty($params["price_{$id}"]) ||
727 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
729 // skip if nothing was submitted for this field
733 switch ($field['html_type']) {
735 $firstOption = reset($field['options']);
736 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
737 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
738 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
739 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
740 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
742 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
743 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
744 if (array_key_exists($params['financial_type_id'], $taxRates)) {
745 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
746 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
747 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
748 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
749 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
752 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
756 //special case if user select -none-
757 if ($params["price_{$id}"] <= 0) {
760 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
761 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
762 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
763 $params['amount_priceset_level_radio'] = array();
764 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
765 if (isset($radioLevel)) {
766 $radioLevel = array_merge($radioLevel,
767 array_keys($params['amount_priceset_level_radio'])
771 $radioLevel = array_keys($params['amount_priceset_level_radio']);
773 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
774 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
775 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
776 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
777 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
778 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
781 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
784 // auto_renew exists and is empty in some workflows, which php treat as a 0
785 // and hence we explicitly check to see if auto_renew is numeric
786 isset($lineItem[$optionValueId]['auto_renew']) &&
787 is_numeric($lineItem[$optionValueId]['auto_renew'])
789 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
794 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
795 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
796 $optionLabel = $field['options'][$optionValueId]['label'];
797 $params['amount_priceset_level_select'] = array();
798 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
799 if (isset($selectLevel)) {
800 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
803 $selectLevel = array_keys($params['amount_priceset_level_select']);
805 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
806 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
807 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
808 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
810 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
813 isset($lineItem[$optionValueId]['auto_renew']) &&
814 is_numeric($lineItem[$optionValueId]['auto_renew'])
816 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
821 $params['amount_priceset_level_checkbox'] = $optionIds = array();
822 foreach ($params["price_{$id}"] as $optionId => $option) {
823 $optionIds[] = $optionId;
824 $optionLabel = $field['options'][$optionId]['label'];
825 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
826 if (isset($checkboxLevel)) {
827 $checkboxLevel = array_unique(array_merge(
829 array_keys($params['amount_priceset_level_checkbox'])
834 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
837 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
838 foreach ($optionIds as $optionId) {
839 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
840 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
841 $totalTax +
= $field['options'][$optionId]['tax_amount'];
843 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
846 isset($lineItem[$optionId]['auto_renew']) &&
847 is_numeric($lineItem[$optionId]['auto_renew'])
849 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
856 $amount_level = array();
857 $totalParticipant = 0;
858 if (is_array($lineItem)) {
859 foreach ($lineItem as $values) {
860 $totalParticipant +
= $values['participant_count'];
861 if ($values['html_type'] == 'Text') {
862 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
865 $amount_level[] = $values['label'];
869 $displayParticipantCount = '';
870 if ($totalParticipant > 0) {
871 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
873 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
874 $params['amount'] = $totalPrice;
875 $params['tax_amount'] = $totalTax;
877 foreach ($autoRenew as $dontCare => $eachAmount) {
879 unset($autoRenew[$dontCare]);
882 if (count($autoRenew) > 1 ) {
883 $params['autoRenew'] = $autoRenew;
889 * Function to build the price set form.
891 * @param CRM_Core_Form $form
896 static function buildPriceSet(&$form) {
897 $priceSetId = $form->get('priceSetId');
898 $userid = $form->getVar('_userID');
903 $validFieldsOnly = TRUE;
904 $className = CRM_Utils_System
::getClassName($form);
905 if (in_array($className, array(
906 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
907 $validFieldsOnly = FALSE;
910 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
911 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
912 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
913 $form->_quickConfig
= $quickConfig = 0;
914 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
918 $form->assign('quickConfig', $quickConfig);
919 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
920 $form->_quickConfig
= $quickConfig;
922 $form->assign('priceSet', $form->_priceSet
);
924 $component = 'contribution';
925 if ($className == 'CRM_Member_Form_Membership') {
926 $component = 'membership';
929 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
930 $feeBlock = &$form->_values
['fee'];
931 if (!empty($form->_useForMember
)) {
932 $component = 'membership';
936 $feeBlock = &$form->_priceSet
['fields'];
940 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
942 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
943 $adminFieldVisible = false;
944 if (CRM_Core_Permission
::check('administer CiviCRM')) {
945 $adminFieldVisible = true;
948 foreach ($feeBlock as $id => $field) {
949 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
950 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
953 $options = CRM_Utils_Array
::value('options', $field);
954 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
955 $checklifetime = self
::checkCurrentMembership($options, $userid);
956 if ($checklifetime) {
957 $form->assign('ispricelifetime', TRUE);
960 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
963 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
964 'price_' . $field['id'],
967 CRM_Utils_Array
::value('is_required', $field, FALSE),
976 * Function to check the current Membership
977 * having end date null.
979 static function checkCurrentMembership(&$options, $userid) {
980 if (!$userid ||
empty($options)) {
983 static $_contact_memberships = array();
984 $checklifetime = FALSE;
985 foreach ($options as $key => $value) {
986 if (!empty($value['membership_type_id'])) {
987 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
988 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
990 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
991 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
992 unset($options[$key]);
993 $checklifetime = TRUE;
997 if ($checklifetime) {
1006 * Function to set daefult the price set fields.
1011 * @return array $defaults
1014 static function setDefaultPriceSet(&$form, &$defaults) {
1015 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1019 foreach ($form->_priceSet
['fields'] as $key => $val) {
1020 foreach ($val['options'] as $keys => $values) {
1021 if ($values['is_default']) {
1022 if ($val['html_type'] == 'CheckBox') {
1023 $defaults["price_{$key}"][$keys] = 1;
1026 $defaults["price_{$key}"] = $keys;
1035 * Supports event create function by setting up required price sets, not tested but expect
1036 * it will work for contribution page
1037 * @param array $params as passed to api/bao create fn
1038 * @param CRM_Core_DAO $entity object for given entity
1039 * @param string $entityName name of entity - e.g event
1041 static function setPriceSets(&$params, $entity, $entityName) {
1042 if(empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1045 // CRM-14069 note that we may as well start by assuming more than one.
1046 // currently the form does not pass in as an array & will be skipped
1047 // test is passing in as an array but I feel the api should have a metadata that allows
1048 // transform of single to array - seems good for managing transitions - in which case all api
1049 // calls that set price_set_id will hit this
1050 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1051 // all separated values, strings, json half-separated values (in participant we hit this)
1052 // to be converted to json @ api layer
1053 $pse = new CRM_Price_DAO_PriceSetEntity();
1054 $pse->entity_table
= 'civicrm_' . $entityName;
1055 $pse->entity_id
= $entity->id
;
1056 while ($pse->fetch()) {
1057 if(!in_array($pse->price_set_id
, $params['price_set_id'])) {
1058 // note an even more aggressive form of this deletion currently happens in event form
1059 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1060 // on the participant record
1061 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1062 CRM_Core_BAO_Discount
::del($entity->id
,'civicrm_' . $entityName);
1066 foreach ($params['price_set_id'] as $priceSetID) {
1067 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1068 //@todo - how should we do this - copied from form
1069 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1070 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1071 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1076 * Get field ids of a price set
1078 * @param int $id Price Set id
1080 * @return array of the field ids
1085 public static function getFieldIds($id) {
1086 $priceField = new CRM_Price_DAO_PriceField();
1087 $priceField->price_set_id
= $id;
1088 $priceField->find();
1089 while ($priceField->fetch()) {
1090 $var[] = $priceField->id
;
1096 * This function is to make a copy of a price set, including
1099 * @param int $id the price set id to copy
1101 * @return the copy object
1105 static function copy($id) {
1106 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1108 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1110 'suffix' => array('title' => ' ' . $title,
1111 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1115 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1121 //copying all the blocks pertaining to the price set
1122 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1123 array('price_set_id' => $id),
1124 array('price_set_id' => $copy->id
)
1126 if (!empty($copyPriceField)) {
1127 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1129 //copy option group and values
1130 foreach ($price as $originalId => $copyId) {
1131 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1132 array('price_field_id' => $originalId),
1133 array('price_field_id' => $copyId)
1139 CRM_Utils_Hook
::copy('Set', $copy);
1144 * This function is to check price set permission
1146 * @param int $sid the price set id
1150 static function checkPermission($sid) {
1151 if ($sid && self
::eventPriceSetDomainID()) {
1152 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1153 if (CRM_Core_Config
::domainID() != $domain_id) {
1154 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1161 * Get the sum of participant count
1162 * for all fields of given price set.
1164 * @param int $sid the price set id
1166 * @param bool $onlyActive
1168 * @return int|null|string
1172 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1180 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1183 static $pricesetFieldCount = array();
1184 if (!isset($pricesetFieldCount[$sid])) {
1186 SELECT sum(value.count) as totalCount
1187 FROM civicrm_price_field_value value
1188 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1189 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1193 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1194 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1197 return $pricesetFieldCount[$sid];
1205 public static function getMembershipCount($ids) {
1207 SELECT count( pfv.id ) AS count, pfv.id AS id
1208 FROM civicrm_price_field_value pfv
1209 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1210 WHERE pfv.id IN ( $ids )
1211 GROUP BY mt.member_of_contact_id";
1213 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1216 while ($crmDAO->fetch()) {
1217 $count[$crmDAO->id
] = $crmDAO->count
;
1224 * Function to check if auto renew option should be shown
1226 * @param int $priceSetId price set id
1228 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1230 public static function checkAutoRenewForPriceSet($priceSetId) {
1231 // auto-renew option should be visible if membership types associated with all the fields has
1232 // been set for auto-renew option
1233 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1235 // get the membership type auto renew option and check if required or optional
1236 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1237 FROM civicrm_price_field_value pfv
1238 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1239 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1240 WHERE pf.price_set_id = %1
1241 AND pf.is_active = 1
1242 AND pfv.is_active = 1';
1244 $params = array(1 => array($priceSetId, 'Integer'));
1246 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1247 $autoRenewOption = 2;
1248 $interval = $unit = array();
1249 while ($dao->fetch()) {
1250 if (!$dao->auto_renew
) {
1251 $autoRenewOption = 0;
1254 if ($dao->auto_renew
== 1) {
1255 $autoRenewOption = 1;
1258 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1259 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1262 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1263 return $autoRenewOption;
1271 * Function to retrieve auto renew frequency and interval
1273 * @param int $priceSetId price set id
1275 * @return array associate array of frequency interval and unit
1279 public static function getRecurDetails($priceSetId) {
1280 $query = 'SELECT mt.duration_interval, mt.duration_unit
1281 FROM civicrm_price_field_value pfv
1282 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1283 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1284 WHERE pf.price_set_id = %1 LIMIT 1';
1286 $params = array(1 => array($priceSetId, 'Integer'));
1287 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1289 return array($dao->duration_interval
, $dao->duration_unit
);
1295 static function eventPriceSetDomainID() {
1296 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1297 'event_price_set_domain_id',
1303 * update the is_quick_config flag in the db
1305 * @param int $id id of the database record
1306 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1308 * @return Object DAO object on sucess, null otherwise
1312 static function setIsQuickConfig($id, $isQuickConfig) {
1313 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1317 * Check if price set id provides option for
1318 * user to select both auto-renew and non-auto-renew memberships
1324 public static function checkMembershipPriceSet($id) {
1327 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1328 FROM civicrm_price_field_value pfv
1329 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1330 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1331 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1335 $params = array(1 => array($id, 'Integer'));
1336 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1338 $autoRenew = array();
1339 //FIXME: do a comprehensive check of whether
1340 //2 membership types can be selected
1341 //instead of comparing all of them
1342 while ($dao->fetch()) {
1343 //temp fix for #CRM-10370
1344 //if its NULL consider it '0' i.e. 'No auto-renew option'
1345 $daoAutoRenew = $dao->auto_renew
;
1346 if ($daoAutoRenew === NULL) {
1349 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1352 $autoRenew[] = $daoAutoRenew;
1358 * Copy priceSet when event/contibution page is copied
1360 * @params string $baoName BAO name
1361 * @params int $id old event/contribution page id
1362 * @params int $newId newly created event/contribution page id
1364 * @param string $baoName
1365 * @param integer $id
1366 * @param integer $newId
1368 static function copyPriceSet($baoName, $id, $newId) {
1369 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1371 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1372 if($isQuickConfig) {
1373 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1374 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1377 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1380 'entity_table' => $baoName,
1382 array('entity_id' => $newId)
1385 // copy event discount
1386 if ($baoName == 'civicrm_event') {
1387 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1388 foreach ($discount as $discountId => $setId) {
1390 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1392 CRM_Core_DAO
::copyGeneric(
1393 'CRM_Core_DAO_Discount',
1395 'id' => $discountId,
1398 'entity_id' => $newId,
1399 'price_set_id' => $copyPriceSet->id
,
1408 * Function to set tax_amount and tax_rate in LineItem
1412 static function setLineItem($field, $lineItem, $optionValueId) {
1413 if ($field['html_type'] == 'Text') {
1414 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1417 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1419 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1420 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1421 $lineItem[$optionValueId]['tax_rate'] = $taxRate;