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
{
44 * static field for default price set details
49 static $_defaultPriceSet = NULL;
54 function __construct() {
55 parent
::__construct();
59 * takes an associative array and creates a price set object
61 * @param array $params (reference) an assoc array of name/value pairs
63 * @return object CRM_Price_DAO_PriceSet object
67 static function create(&$params) {
68 if(empty($params['id']) && empty($params['name'])) {
69 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
71 $priceSetBAO = new CRM_Price_BAO_PriceSet();
72 $priceSetBAO->copyValues($params);
73 if (self
::eventPriceSetDomainID()) {
74 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
76 return $priceSetBAO->save();
80 * Takes a bunch of params that are needed to match certain criteria and
81 * retrieves the relevant objects. Typically the valid params are only
82 * contact_id. We'll tweak this function to be more full featured over a period
83 * of time. This is the inverse function of create. It also stores all the retrieved
84 * values in the default array
86 * @param array $params (reference ) an assoc array of name/value pairs
87 * @param array $defaults (reference ) an assoc array to hold the flattened values
89 * @return object CRM_Price_DAO_PriceSet object
93 static function retrieve(&$params, &$defaults) {
94 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
98 * update the is_active flag in the db
100 * @param int $id id of the database record
103 * @internal param bool $is_active value we want to set the is_active field
105 * @return Object DAO object on sucess, null otherwise
109 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
119 * @return array $defaultPriceSet default price set
125 public static function getDefaultPriceSet($entity = 'contribution') {
126 if (!empty(self
::$_defaultPriceSet[$entity])) {
127 return self
::$_defaultPriceSet[$entity];
129 $entityName = 'default_contribution_amount';
130 if ($entity == 'membership') {
131 $entityName = 'default_membership_type_amount';
135 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
136 FROM civicrm_price_set ps
137 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
138 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
139 WHERE ps.name = '{$entityName}'
142 $dao = CRM_Core_DAO
::executeQuery($sql);
143 self
::$_defaultPriceSet[$entity] = array();
144 while ($dao->fetch()) {
145 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
146 'setID' => $dao->setID
,
147 'priceFieldID' => $dao->priceFieldID
,
148 'name' => $dao->name
,
149 'label' => $dao->label
,
150 'priceFieldValueID' => $dao->priceFieldValueID
,
151 'membership_type_id' => $dao->membership_type_id
,
152 'amount' => $dao->amount
,
153 'financial_type_id' => $dao->financial_type_id
,
157 return self
::$_defaultPriceSet[$entity];
161 * Get the price set title.
163 * @param int $id id of price set
165 * @return string title
171 public static function getTitle($id) {
172 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
176 * Return a list of all forms which use this price set.
178 * @param int $id id of 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
285 * @param int $id Price Set id
287 * @return boolean false if fields exist for this set, true if the
288 * set could be deleted
293 public static function deleteSet($id) {
294 // remove from all inactive forms
295 $usedBy = self
::getUsedBy($id);
296 if (isset($usedBy['civicrm_event'])) {
297 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
298 $eventDAO = new CRM_Event_DAO_Event();
299 $eventDAO->id
= $eventId;
301 while ($eventDAO->fetch()) {
302 self
::removeFrom('civicrm_event', $eventDAO->id
);
307 // delete price fields
308 $priceField = new CRM_Price_DAO_PriceField();
309 $priceField->price_set_id
= $id;
311 while ($priceField->fetch()) {
312 // delete options first
313 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
316 $set = new CRM_Price_DAO_PriceSet();
318 return $set->delete();
322 * Link the price set with the specified table and id
324 * @param string $entityTable
325 * @param integer $entityId
326 * @param integer $priceSetId
330 public static function addTo($entityTable, $entityId, $priceSetId) {
331 // verify that the price set exists
332 $dao = new CRM_Price_DAO_PriceSet();
333 $dao->id
= $priceSetId;
339 $dao = new CRM_Price_DAO_PriceSetEntity();
340 // find if this already exists
341 $dao->entity_id
= $entityId;
342 $dao->entity_table
= $entityTable;
345 // add or update price_set_id
346 $dao->price_set_id
= $priceSetId;
351 * Delete price set for the given entity and id
353 * @param string $entityTable
354 * @param integer $entityId
358 public static function removeFrom($entityTable, $entityId) {
359 $dao = new CRM_Price_DAO_PriceSetEntity();
360 $dao->entity_table
= $entityTable;
361 $dao->entity_id
= $entityId;
362 return $dao->delete();
366 * Find a price_set_id associatied with the given table, id and usedFor
367 * Used For value for events:1, contribution:2, membership:3
369 * @param string $entityTable
370 * @param int $entityId
371 * @param int $usedFor ( price set that extends/used for particular component )
373 * @param null $isQuickConfig
374 * @param null $setName
376 * @return integer|false price_set_id, or false if none found
378 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
379 if (!$entityTable ||
!$entityId) {
383 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
384 FROM civicrm_price_set ps
385 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
386 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
387 if ($isQuickConfig) {
388 $sql .= ' AND ps.is_quick_config = 0 ';
390 $params = array(1 => array($entityTable, 'String'),
391 2 => array($entityId, 'Integer'),
394 $sql .= " AND ps.extends LIKE '%%3%' ";
395 $params[3] = array($usedFor, 'Integer');
398 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
400 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
401 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
405 * Find a price_set_id associated with the given option value or field ID
407 * @param array $params (reference) an assoc array of name/value pairs
408 * array may contain either option id or
411 * @return integer|NULL price set id on success, null otherwise
415 public static function getSetId(&$params) {
418 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
419 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
420 $fieldValue->id
= $oid;
421 if ($fieldValue->find(TRUE)) {
422 $fid = $fieldValue->price_field_id
;
426 $fid = CRM_Utils_Array
::value('fid', $params);
430 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
437 * Return an associative array of all price sets
439 * @param bool $withInactive whether or not to include inactive entries
440 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
442 * @return array associative array of id => name
444 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
447 DISTINCT ( price_set_id ) as id, title
452 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
454 if (!$withInactive) {
455 $query .= ' AND civicrm_price_set.is_active = 1 ';
458 if (self
::eventPriceSetDomainID()) {
459 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
462 $priceSets = array();
464 if ($extendComponentName) {
465 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
469 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
472 $dao = CRM_Core_DAO
::executeQuery($query);
473 while ($dao->fetch()) {
474 $priceSets[$dao->id
] = $dao->title
;
480 * Get price set details
482 * An array containing price set details (including price fields) is returned
485 * @param bool $required
486 * @param bool $validOnly
488 * @internal param int $setId - price set id whose details are needed
490 * @return array $setTree - array consisting of field details
492 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
496 $priceFields = array(
505 'is_display_amounts',
514 if ($required == TRUE) {
515 $priceFields[] = 'is_required';
519 $select = 'SELECT ' . implode(',', $priceFields);
520 $from = ' FROM civicrm_price_field';
523 $params[1] = array($setID, 'Integer');
525 WHERE price_set_id = %1
530 $currentTime = date('YmdHis');
532 AND ( active_on IS NULL OR active_on <= {$currentTime} )
533 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
537 $orderBy = ' ORDER BY weight';
539 $sql = $select . $from . $where . $dateSelect . $orderBy;
541 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
543 $visibility = CRM_Core_PseudoConstant
::visibility('name');
544 while ($dao->fetch()) {
547 $setTree[$setID]['fields'][$fieldID] = array();
548 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
550 foreach ($priceFields as $field) {
551 if ($field == 'id' ||
is_null($dao->$field)) {
555 if ($field == 'visibility_id') {
556 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
558 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
560 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
563 // also get the pre and post help from this price set
565 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
566 FROM civicrm_price_set
568 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
570 $setTree[$setID]['extends'] = $dao->extends;
571 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
572 $setTree[$setID]['help_pre'] = $dao->help_pre
;
573 $setTree[$setID]['help_post'] = $dao->help_post
;
574 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
580 * Get the Price Field ID. We call this function when more than one being present would represent an error
581 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
582 * @param array $priceSet
584 * @throws CRM_Core_Exception
587 static function getOnlyPriceFieldID(array $priceSet) {
588 if(count($priceSet['fields']) > 1) {
589 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
591 return (int) implode('_', array_keys($priceSet['fields']));
595 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
596 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
597 * @param array $priceSet
599 * @throws CRM_Core_Exception
602 static function getOnlyPriceFieldValueID(array $priceSet) {
603 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
604 if(count($priceSet['fields'][$priceFieldID]['options']) > 1) {
605 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
607 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
612 * @param CRM_Core_Form $form
614 * @param string $entityTable
615 * @param bool $validOnly
616 * @param null $priceSetId
618 * @return bool|false|int|null
620 static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
622 $priceSetId = self
::getFor($entityTable, $id);
625 //check if priceset is is_config
626 if (is_numeric($priceSetId)) {
627 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
628 $form->assign('quickConfig', 1);
633 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
634 $entityId = $entity = NULL;
636 switch ($entityTable) {
637 case 'civicrm_event':
638 $entity = 'participant';
639 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
640 $entityId = $form->_id
;
643 $entityId = $form->_participantId
;
647 case 'civicrm_contribution_page':
648 case 'civicrm_contribution':
649 $entity = 'contribution';
650 $entityId = $form->_id
;
654 if ($entityId && $entity) {
655 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
663 $form->_priceSetId
= $priceSetId;
664 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
665 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
666 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
668 //get the price set fields participant count.
669 if ($entityTable == 'civicrm_event') {
670 //get option count info.
671 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
672 if ($form->_priceSet
['optionsCountTotal']) {
673 $optionsCountDeails = array();
674 if (!empty($form->_priceSet
['fields'])) {
675 foreach ($form->_priceSet
['fields'] as $field) {
676 foreach ($field['options'] as $option) {
677 $count = CRM_Utils_Array
::value('count', $option, 0);
678 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
682 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
685 //get option max value info.
686 $optionsMaxValueTotal = 0;
687 $optionsMaxValueDetails = array();
689 if (!empty($form->_priceSet
['fields'])) {
690 foreach ($form->_priceSet
['fields'] as $field) {
691 foreach ($field['options'] as $option) {
692 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
693 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
694 $optionsMaxValueTotal +
= $maxVal;
699 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
700 if ($optionsMaxValueTotal) {
701 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
704 $form->set('priceSetId', $form->_priceSetId
);
705 $form->set('priceSet', $form->_priceSet
);
716 * @param string $component
718 static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
720 $totalPrice = $totalTax = 0;
721 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
723 $autoRenew = array();
724 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
726 foreach ($fields as $id => $field) {
727 if (empty($params["price_{$id}"]) ||
728 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
730 // skip if nothing was submitted for this field
734 switch ($field['html_type']) {
736 $firstOption = reset($field['options']);
737 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
738 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
739 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
740 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
741 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
743 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
744 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
745 if (array_key_exists($params['financial_type_id'], $taxRates)) {
746 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
747 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
748 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
749 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
750 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
753 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
757 //special case if user select -none-
758 if ($params["price_{$id}"] <= 0) {
761 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
762 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
763 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
764 $params['amount_priceset_level_radio'] = array();
765 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
766 if (isset($radioLevel)) {
767 $radioLevel = array_merge($radioLevel,
768 array_keys($params['amount_priceset_level_radio'])
772 $radioLevel = array_keys($params['amount_priceset_level_radio']);
774 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
775 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
776 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
777 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
778 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
779 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
782 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
785 // auto_renew exists and is empty in some workflows, which php treat as a 0
786 // and hence we explicitly check to see if auto_renew is numeric
787 isset($lineItem[$optionValueId]['auto_renew']) &&
788 is_numeric($lineItem[$optionValueId]['auto_renew'])
790 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
795 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
796 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
797 $optionLabel = $field['options'][$optionValueId]['label'];
798 $params['amount_priceset_level_select'] = array();
799 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
800 if (isset($selectLevel)) {
801 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
804 $selectLevel = array_keys($params['amount_priceset_level_select']);
806 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
807 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
808 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
809 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
811 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
814 isset($lineItem[$optionValueId]['auto_renew']) &&
815 is_numeric($lineItem[$optionValueId]['auto_renew'])
817 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
822 $params['amount_priceset_level_checkbox'] = $optionIds = array();
823 foreach ($params["price_{$id}"] as $optionId => $option) {
824 $optionIds[] = $optionId;
825 $optionLabel = $field['options'][$optionId]['label'];
826 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
827 if (isset($checkboxLevel)) {
828 $checkboxLevel = array_unique(array_merge(
830 array_keys($params['amount_priceset_level_checkbox'])
835 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
838 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
839 foreach ($optionIds as $optionId) {
840 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
841 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
842 $totalTax +
= $field['options'][$optionId]['tax_amount'];
844 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
847 isset($lineItem[$optionId]['auto_renew']) &&
848 is_numeric($lineItem[$optionId]['auto_renew'])
850 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
857 $amount_level = array();
858 $totalParticipant = 0;
859 if (is_array($lineItem)) {
860 foreach ($lineItem as $values) {
861 $totalParticipant +
= $values['participant_count'];
862 if ($values['html_type'] == 'Text') {
863 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
866 $amount_level[] = $values['label'];
870 $displayParticipantCount = '';
871 if ($totalParticipant > 0) {
872 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
874 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
875 $params['amount'] = $totalPrice;
876 $params['tax_amount'] = $totalTax;
878 foreach ($autoRenew as $dontCare => $eachAmount) {
880 unset($autoRenew[$dontCare]);
883 if (count($autoRenew) > 1 ) {
884 $params['autoRenew'] = $autoRenew;
890 * Function to build the price set form.
892 * @param CRM_Core_Form $form
897 static function buildPriceSet(&$form) {
898 $priceSetId = $form->get('priceSetId');
899 $userid = $form->getVar('_userID');
904 $validFieldsOnly = TRUE;
905 $className = CRM_Utils_System
::getClassName($form);
906 if (in_array($className, array(
907 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
908 $validFieldsOnly = FALSE;
911 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
912 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
913 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
914 $form->_quickConfig
= $quickConfig = 0;
915 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
919 $form->assign('quickConfig', $quickConfig);
920 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
921 $form->_quickConfig
= $quickConfig;
923 $form->assign('priceSet', $form->_priceSet
);
925 $component = 'contribution';
926 if ($className == 'CRM_Member_Form_Membership') {
927 $component = 'membership';
930 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
931 $feeBlock = &$form->_values
['fee'];
932 if (!empty($form->_useForMember
)) {
933 $component = 'membership';
937 $feeBlock = &$form->_priceSet
['fields'];
941 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
943 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
944 $adminFieldVisible = false;
945 if (CRM_Core_Permission
::check('administer CiviCRM')) {
946 $adminFieldVisible = true;
949 foreach ($feeBlock as $id => $field) {
950 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
951 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
954 $options = CRM_Utils_Array
::value('options', $field);
955 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
956 $checklifetime = self
::checkCurrentMembership($options, $userid);
957 if ($checklifetime) {
958 $form->assign('ispricelifetime', TRUE);
961 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
964 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
965 'price_' . $field['id'],
968 CRM_Utils_Array
::value('is_required', $field, FALSE),
977 * Function to check the current Membership
978 * having end date null.
980 static function checkCurrentMembership(&$options, $userid) {
981 if (!$userid ||
empty($options)) {
984 static $_contact_memberships = array();
985 $checklifetime = FALSE;
986 foreach ($options as $key => $value) {
987 if (!empty($value['membership_type_id'])) {
988 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
989 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
991 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
992 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
993 unset($options[$key]);
994 $checklifetime = TRUE;
998 if ($checklifetime) {
1007 * Function to set daefult the price set fields.
1012 * @return array $defaults
1015 static function setDefaultPriceSet(&$form, &$defaults) {
1016 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1020 foreach ($form->_priceSet
['fields'] as $key => $val) {
1021 foreach ($val['options'] as $keys => $values) {
1022 if ($values['is_default']) {
1023 if ($val['html_type'] == 'CheckBox') {
1024 $defaults["price_{$key}"][$keys] = 1;
1027 $defaults["price_{$key}"] = $keys;
1036 * Supports event create function by setting up required price sets, not tested but expect
1037 * it will work for contribution page
1038 * @param array $params as passed to api/bao create fn
1039 * @param CRM_Core_DAO $entity object for given entity
1040 * @param string $entityName name of entity - e.g event
1042 static function setPriceSets(&$params, $entity, $entityName) {
1043 if(empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1046 // CRM-14069 note that we may as well start by assuming more than one.
1047 // currently the form does not pass in as an array & will be skipped
1048 // test is passing in as an array but I feel the api should have a metadata that allows
1049 // transform of single to array - seems good for managing transitions - in which case all api
1050 // calls that set price_set_id will hit this
1051 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1052 // all separated values, strings, json half-separated values (in participant we hit this)
1053 // to be converted to json @ api layer
1054 $pse = new CRM_Price_DAO_PriceSetEntity();
1055 $pse->entity_table
= 'civicrm_' . $entityName;
1056 $pse->entity_id
= $entity->id
;
1057 while ($pse->fetch()) {
1058 if(!in_array($pse->price_set_id
, $params['price_set_id'])) {
1059 // note an even more aggressive form of this deletion currently happens in event form
1060 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1061 // on the participant record
1062 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1063 CRM_Core_BAO_Discount
::del($this->_id
,'civicrm_' . $entityName);
1067 foreach ($params['price_set_id'] as $priceSetID) {
1068 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1069 //@todo - how should we do this - copied from form
1070 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1071 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1072 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1077 * Get field ids of a price set
1079 * @param int $id Price Set id
1081 * @return array of the field ids
1086 public static function getFieldIds($id) {
1087 $priceField = new CRM_Price_DAO_PriceField();
1088 $priceField->price_set_id
= $id;
1089 $priceField->find();
1090 while ($priceField->fetch()) {
1091 $var[] = $priceField->id
;
1097 * This function is to make a copy of a price set, including
1100 * @param int $id the price set id to copy
1102 * @return the copy object
1106 static function copy($id) {
1107 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1109 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1111 'suffix' => array('title' => ' ' . $title,
1112 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1116 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1122 //copying all the blocks pertaining to the price set
1123 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1124 array('price_set_id' => $id),
1125 array('price_set_id' => $copy->id
)
1127 if (!empty($copyPriceField)) {
1128 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1130 //copy option group and values
1131 foreach ($price as $originalId => $copyId) {
1132 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1133 array('price_field_id' => $originalId),
1134 array('price_field_id' => $copyId)
1140 CRM_Utils_Hook
::copy('Set', $copy);
1145 * This function is to check price set permission
1147 * @param int $sid the price set id
1151 static function checkPermission($sid) {
1152 if ($sid && self
::eventPriceSetDomainID()) {
1153 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1154 if (CRM_Core_Config
::domainID() != $domain_id) {
1155 CRM_Core_Error
::fatal(ts('You do not have permission to access this page'));
1162 * Get the sum of participant count
1163 * for all fields of given price set.
1165 * @param int $sid the price set id
1167 * @param bool $onlyActive
1169 * @return int|null|string
1173 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1181 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1184 static $pricesetFieldCount = array();
1185 if (!isset($pricesetFieldCount[$sid])) {
1187 SELECT sum(value.count) as totalCount
1188 FROM civicrm_price_field_value value
1189 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1190 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1194 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1195 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1198 return $pricesetFieldCount[$sid];
1206 public static function getMembershipCount($ids) {
1208 SELECT count( pfv.id ) AS count, pfv.id AS id
1209 FROM civicrm_price_field_value pfv
1210 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1211 WHERE pfv.id IN ( $ids )
1212 GROUP BY mt.member_of_contact_id";
1214 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1217 while ($crmDAO->fetch()) {
1218 $count[$crmDAO->id
] = $crmDAO->count
;
1225 * Function to check if auto renew option should be shown
1227 * @param int $priceSetId price set id
1229 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1231 public static function checkAutoRenewForPriceSet($priceSetId) {
1232 // auto-renew option should be visible if membership types associated with all the fields has
1233 // been set for auto-renew option
1234 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1236 // get the membership type auto renew option and check if required or optional
1237 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1238 FROM civicrm_price_field_value pfv
1239 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1240 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1241 WHERE pf.price_set_id = %1
1242 AND pf.is_active = 1
1243 AND pfv.is_active = 1';
1245 $params = array(1 => array($priceSetId, 'Integer'));
1247 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1248 $autoRenewOption = 2;
1249 $interval = $unit = array();
1250 while ($dao->fetch()) {
1251 if (!$dao->auto_renew
) {
1252 $autoRenewOption = 0;
1255 if ($dao->auto_renew
== 1) {
1256 $autoRenewOption = 1;
1259 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1260 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1263 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1264 return $autoRenewOption;
1272 * Function to retrieve auto renew frequency and interval
1274 * @param int $priceSetId price set id
1276 * @return array associate array of frequency interval and unit
1280 public static function getRecurDetails($priceSetId) {
1281 $query = 'SELECT mt.duration_interval, mt.duration_unit
1282 FROM civicrm_price_field_value pfv
1283 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1284 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1285 WHERE pf.price_set_id = %1 LIMIT 1';
1287 $params = array(1 => array($priceSetId, 'Integer'));
1288 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1290 return array($dao->duration_interval
, $dao->duration_unit
);
1296 static function eventPriceSetDomainID() {
1297 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1298 'event_price_set_domain_id',
1304 * update the is_quick_config flag in the db
1306 * @param int $id id of the database record
1307 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1309 * @return Object DAO object on sucess, null otherwise
1313 static function setIsQuickConfig($id, $isQuickConfig) {
1314 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1318 * Check if price set id provides option for
1319 * user to select both auto-renew and non-auto-renew memberships
1325 public static function checkMembershipPriceSet($id) {
1328 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1329 FROM civicrm_price_field_value pfv
1330 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1331 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1332 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1336 $params = array(1 => array($id, 'Integer'));
1337 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1339 $autoRenew = array();
1340 //FIXME: do a comprehensive check of whether
1341 //2 membership types can be selected
1342 //instead of comparing all of them
1343 while ($dao->fetch()) {
1344 //temp fix for #CRM-10370
1345 //if its NULL consider it '0' i.e. 'No auto-renew option'
1346 $daoAutoRenew = $dao->auto_renew
;
1347 if ($daoAutoRenew === NULL) {
1350 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1353 $autoRenew[] = $daoAutoRenew;
1359 * Copy priceSet when event/contibution page is copied
1361 * @params string $baoName BAO name
1362 * @params int $id old event/contribution page id
1363 * @params int $newId newly created event/contribution page id
1365 * @param string $baoName
1366 * @param integer $id
1367 * @param integer $newId
1369 static function copyPriceSet($baoName, $id, $newId) {
1370 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1372 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1373 if($isQuickConfig) {
1374 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1375 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1378 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1381 'entity_table' => $baoName,
1383 array('entity_id' => $newId)
1386 // copy event discount
1387 if ($baoName == 'civicrm_event') {
1388 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1389 foreach ($discount as $discountId => $setId) {
1391 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1393 CRM_Core_DAO
::copyGeneric(
1394 'CRM_Core_DAO_Discount',
1396 'id' => $discountId,
1399 'entity_id' => $newId,
1400 'price_set_id' => $copyPriceSet->id
,
1409 * Function to set tax_amount and tax_rate in LineItem
1413 static function setLineItem($field, $lineItem, $optionValueId) {
1414 if ($field['html_type'] == 'Text') {
1415 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1418 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1420 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1421 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1422 $lineItem[$optionValueId]['tax_rate'] = $taxRate;