3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business object for managing price sets
40 class CRM_Price_BAO_PriceSet
extends CRM_Price_DAO_PriceSet
{
43 * Static field for default price set details
48 static $_defaultPriceSet = NULL;
53 public function __construct() {
54 parent
::__construct();
58 * Takes an associative array and creates a price set object
60 * @param array $params
61 * (reference) an assoc array of name/value pairs.
63 * @return CRM_Price_DAO_PriceSet
66 public static function create(&$params) {
67 if (empty($params['id']) && empty($params['name'])) {
68 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
70 if (!empty($params['extends']) && is_array($params['extends'])) {
71 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
73 $priceSetBAO = new CRM_Price_BAO_PriceSet();
74 $priceSetBAO->copyValues($params);
75 if (self
::eventPriceSetDomainID()) {
76 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
78 return $priceSetBAO->save();
82 * Fetch object based on array of properties
84 * @param array $params
85 * (reference ) an assoc array of name/value pairs.
86 * @param array $defaults
87 * (reference ) an assoc array to hold the flattened values.
89 * @return CRM_Price_DAO_PriceSet
92 public static function retrieve(&$params, &$defaults) {
93 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
97 * Update the is_active flag in the db
100 * Id of the database record.
103 * @internal param bool $is_active value we want to set the is_active field
106 * DAO object on sucess, null otherwise
109 public static function setIsActive($id, $isActive) {
110 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
114 * Calculate the default price set id
115 * assigned to the contribution/membership etc
117 * @param string $entity
124 public static function getDefaultPriceSet($entity = 'contribution') {
125 if (!empty(self
::$_defaultPriceSet[$entity])) {
126 return self
::$_defaultPriceSet[$entity];
128 $entityName = 'default_contribution_amount';
129 if ($entity == 'membership') {
130 $entityName = 'default_membership_type_amount';
134 SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label, pfv.membership_type_id, pfv.amount, pfv.financial_type_id
135 FROM civicrm_price_set ps
136 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
137 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
138 WHERE ps.name = '{$entityName}'
141 $dao = CRM_Core_DAO
::executeQuery($sql);
142 self
::$_defaultPriceSet[$entity] = array();
143 while ($dao->fetch()) {
144 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
145 'setID' => $dao->setID
,
146 'priceFieldID' => $dao->priceFieldID
,
147 'name' => $dao->name
,
148 'label' => $dao->label
,
149 'priceFieldValueID' => $dao->priceFieldValueID
,
150 'membership_type_id' => $dao->membership_type_id
,
151 'amount' => $dao->amount
,
152 'financial_type_id' => $dao->financial_type_id
,
156 return self
::$_defaultPriceSet[$entity];
160 * Get the price set title.
170 public static function getTitle($id) {
171 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
175 * Return a list of all forms which use this price set.
179 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
183 public static function &getUsedBy($id, $simpleReturn = FALSE) {
184 $usedBy = $forms = $tables = array();
186 SELECT entity_table, entity_id
187 FROM civicrm_price_set_entity
188 WHERE price_set_id = %1";
189 $params = array(1 => array($id, 'Integer'));
190 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
192 while ($crmFormDAO->fetch()) {
193 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
194 $tables[] = $crmFormDAO->entity_table
;
196 // Return only tables
197 if ($simpleReturn == 'table') {
202 SELECT cli.entity_table, cli.entity_id
203 FROM civicrm_line_item cli
204 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
205 WHERE cpf.price_set_id = %1";
206 $params = array(1 => array($id, 'Integer'));
207 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
208 while ($crmFormDAO->fetch()) {
209 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
210 $tables[] = $crmFormDAO->entity_table
;
216 // Return only entity data
217 if ($simpleReturn == 'entity') {
220 foreach ($forms as $table => $entities) {
222 case 'civicrm_event':
223 $ids = implode(',', $entities);
224 $queryString = "SELECT ce.id as id, ce.title as title, ce.is_public as isPublic, ce.start_date as startDate, ce.end_date as endDate, civicrm_option_value.label as eventType, ce.is_template as isTemplate, ce.template_title as templateTitle
225 FROM civicrm_event ce
226 LEFT JOIN civicrm_option_value ON
227 ( ce.event_type_id = civicrm_option_value.value )
228 LEFT JOIN civicrm_option_group ON
229 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
231 civicrm_option_group.name = 'event_type' AND
234 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
235 while ($crmDAO->fetch()) {
236 if ($crmDAO->isTemplate
) {
237 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
238 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
239 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
242 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
243 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
244 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
245 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
246 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
251 case 'civicrm_contribution_page':
252 $ids = implode(',', $entities);
253 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
254 FROM civicrm_contribution_page cp, civicrm_financial_type ct
255 WHERE ct.id = cp.financial_type_id AND
258 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
259 while ($crmDAO->fetch()) {
260 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
261 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
262 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
263 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
267 case 'civicrm_contribution':
268 case 'civicrm_membership':
269 case 'civicrm_participant':
274 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
283 * Delete the price set
289 * false if fields exist for this set, true if the
290 * set could be deleted
294 public static function deleteSet($id) {
295 // remove from all inactive forms
296 $usedBy = self
::getUsedBy($id);
297 if (isset($usedBy['civicrm_event'])) {
298 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
299 $eventDAO = new CRM_Event_DAO_Event();
300 $eventDAO->id
= $eventId;
302 while ($eventDAO->fetch()) {
303 self
::removeFrom('civicrm_event', $eventDAO->id
);
308 // delete price fields
309 $priceField = new CRM_Price_DAO_PriceField();
310 $priceField->price_set_id
= $id;
312 while ($priceField->fetch()) {
313 // delete options first
314 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
317 $set = new CRM_Price_DAO_PriceSet();
319 return $set->delete();
323 * Link the price set with the specified table and id
325 * @param string $entityTable
326 * @param int $entityId
327 * @param int $priceSetId
331 public static function addTo($entityTable, $entityId, $priceSetId) {
332 // verify that the price set exists
333 $dao = new CRM_Price_DAO_PriceSet();
334 $dao->id
= $priceSetId;
340 $dao = new CRM_Price_DAO_PriceSetEntity();
341 // find if this already exists
342 $dao->entity_id
= $entityId;
343 $dao->entity_table
= $entityTable;
346 // add or update price_set_id
347 $dao->price_set_id
= $priceSetId;
352 * Delete price set for the given entity and id
354 * @param string $entityTable
355 * @param int $entityId
359 public static function removeFrom($entityTable, $entityId) {
360 $dao = new CRM_Price_DAO_PriceSetEntity();
361 $dao->entity_table
= $entityTable;
362 $dao->entity_id
= $entityId;
363 return $dao->delete();
367 * Find a price_set_id associatied with the given table, id and usedFor
368 * Used For value for events:1, contribution:2, membership:3
370 * @param string $entityTable
371 * @param int $entityId
372 * @param int $usedFor
373 * ( price set that extends/used for particular component ).
375 * @param null $isQuickConfig
376 * @param null $setName
379 * price_set_id, or false if none found
381 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
382 if (!$entityTable ||
!$entityId) {
386 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
387 FROM civicrm_price_set ps
388 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
389 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
390 if ($isQuickConfig) {
391 $sql .= ' AND ps.is_quick_config = 0 ';
394 1 => array($entityTable, 'String'),
395 2 => array($entityId, 'Integer'),
398 $sql .= " AND ps.extends LIKE '%%3%' ";
399 $params[3] = array($usedFor, 'Integer');
402 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
404 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
405 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
409 * Find a price_set_id associated with the given option value or field ID
411 * @param array $params
412 * (reference) an assoc array of name/value pairs.
413 * array may contain either option id or
417 * price set id on success, null otherwise
420 public static function getSetId(&$params) {
423 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
424 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
425 $fieldValue->id
= $oid;
426 if ($fieldValue->find(TRUE)) {
427 $fid = $fieldValue->price_field_id
;
431 $fid = CRM_Utils_Array
::value('fid', $params);
435 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
442 * Return an associative array of all price sets
444 * @param bool $withInactive
445 * Whether or not to include inactive entries.
446 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
449 * associative array of id => name
451 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
454 DISTINCT ( price_set_id ) as id, title
459 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
461 if (!$withInactive) {
462 $query .= ' AND civicrm_price_set.is_active = 1 ';
465 if (self
::eventPriceSetDomainID()) {
466 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
469 $priceSets = array();
471 if ($extendComponentName) {
472 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
476 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
479 $dao = CRM_Core_DAO
::executeQuery($query);
480 while ($dao->fetch()) {
481 $priceSets[$dao->id
] = $dao->title
;
487 * Get price set details
489 * An array containing price set details (including price fields) is returned
492 * @param bool $required
493 * @param bool $validOnly
495 * @internal param int $setId - price set id whose details are needed
498 * array consisting of field details
500 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
504 $priceFields = array(
513 'is_display_amounts',
522 if ($required == TRUE) {
523 $priceFields[] = 'is_required';
527 $select = 'SELECT ' . implode(',', $priceFields);
528 $from = ' FROM civicrm_price_field';
531 $params[1] = array($setID, 'Integer');
533 WHERE price_set_id = %1
538 $currentTime = date('YmdHis');
540 AND ( active_on IS NULL OR active_on <= {$currentTime} )
541 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
545 $orderBy = ' ORDER BY weight';
547 $sql = $select . $from . $where . $dateSelect . $orderBy;
549 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
551 $visibility = CRM_Core_PseudoConstant
::visibility('name');
552 while ($dao->fetch()) {
555 $setTree[$setID]['fields'][$fieldID] = array();
556 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
558 foreach ($priceFields as $field) {
559 if ($field == 'id' ||
is_null($dao->$field)) {
563 if ($field == 'visibility_id') {
564 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
566 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
568 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
571 // also get the pre and post help from this price set
573 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
574 FROM civicrm_price_set
576 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
578 $setTree[$setID]['extends'] = $dao->extends;
579 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
580 $setTree[$setID]['help_pre'] = $dao->help_pre
;
581 $setTree[$setID]['help_post'] = $dao->help_post
;
582 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
588 * Get the Price Field ID. We call this function when more than one being present would represent an error
589 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
590 * @param array $priceSet
592 * @throws CRM_Core_Exception
595 public static function getOnlyPriceFieldID(array $priceSet) {
596 if (count($priceSet['fields']) > 1) {
597 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
599 return (int) implode('_', array_keys($priceSet['fields']));
603 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
604 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
605 * @param array $priceSet
607 * @throws CRM_Core_Exception
610 public static function getOnlyPriceFieldValueID(array $priceSet) {
611 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
612 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
613 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
615 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
620 * @param CRM_Core_Form $form
622 * @param string $entityTable
623 * @param bool $validOnly
624 * @param int $priceSetId
626 * @return bool|false|int|null
628 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
630 $priceSetId = self
::getFor($entityTable, $id);
633 //check if priceset is is_config
634 if (is_numeric($priceSetId)) {
635 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
636 $form->assign('quickConfig', 1);
641 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
642 $entityId = $entity = NULL;
644 switch ($entityTable) {
645 case 'civicrm_event':
646 $entity = 'participant';
647 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
648 $entityId = $form->_id
;
651 $entityId = $form->_participantId
;
655 case 'civicrm_contribution_page':
656 case 'civicrm_contribution':
657 $entity = 'contribution';
658 $entityId = $form->_id
;
662 if ($entityId && $entity) {
663 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
671 $form->_priceSetId
= $priceSetId;
672 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
673 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
674 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
676 //get the price set fields participant count.
677 if ($entityTable == 'civicrm_event') {
678 //get option count info.
679 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
680 if ($form->_priceSet
['optionsCountTotal']) {
681 $optionsCountDeails = array();
682 if (!empty($form->_priceSet
['fields'])) {
683 foreach ($form->_priceSet
['fields'] as $field) {
684 foreach ($field['options'] as $option) {
685 $count = CRM_Utils_Array
::value('count', $option, 0);
686 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
690 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
693 //get option max value info.
694 $optionsMaxValueTotal = 0;
695 $optionsMaxValueDetails = array();
697 if (!empty($form->_priceSet
['fields'])) {
698 foreach ($form->_priceSet
['fields'] as $field) {
699 foreach ($field['options'] as $option) {
700 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
701 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
702 $optionsMaxValueTotal +
= $maxVal;
707 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
708 if ($optionsMaxValueTotal) {
709 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
712 $form->set('priceSetId', $form->_priceSetId
);
713 $form->set('priceSet', $form->_priceSet
);
722 * @param array $params
724 * @param string $component
726 public static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
728 $totalPrice = $totalTax = 0;
729 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
731 $autoRenew = array();
732 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
734 foreach ($fields as $id => $field) {
735 if (empty($params["price_{$id}"]) ||
736 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
738 // skip if nothing was submitted for this field
742 switch ($field['html_type']) {
744 $firstOption = reset($field['options']);
745 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
746 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
747 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
748 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
749 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
751 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
752 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
753 if (array_key_exists($params['financial_type_id'], $taxRates)) {
754 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
755 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
756 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
757 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
758 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
761 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
765 //special case if user select -none-
766 if ($params["price_{$id}"] <= 0) {
769 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
770 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
771 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
772 $params['amount_priceset_level_radio'] = array();
773 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
774 if (isset($radioLevel)) {
775 $radioLevel = array_merge($radioLevel,
776 array_keys($params['amount_priceset_level_radio'])
780 $radioLevel = array_keys($params['amount_priceset_level_radio']);
782 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
783 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
784 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
785 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
786 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
787 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
790 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
793 // auto_renew exists and is empty in some workflows, which php treat as a 0
794 // and hence we explicitly check to see if auto_renew is numeric
795 isset($lineItem[$optionValueId]['auto_renew']) &&
796 is_numeric($lineItem[$optionValueId]['auto_renew'])
798 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
803 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
804 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
805 $optionLabel = $field['options'][$optionValueId]['label'];
806 $params['amount_priceset_level_select'] = array();
807 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
808 if (isset($selectLevel)) {
809 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
812 $selectLevel = array_keys($params['amount_priceset_level_select']);
814 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
815 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
816 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
817 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
819 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
822 isset($lineItem[$optionValueId]['auto_renew']) &&
823 is_numeric($lineItem[$optionValueId]['auto_renew'])
825 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
830 $params['amount_priceset_level_checkbox'] = $optionIds = array();
831 foreach ($params["price_{$id}"] as $optionId => $option) {
832 $optionIds[] = $optionId;
833 $optionLabel = $field['options'][$optionId]['label'];
834 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
835 if (isset($checkboxLevel)) {
836 $checkboxLevel = array_unique(array_merge(
838 array_keys($params['amount_priceset_level_checkbox'])
843 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
846 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
847 foreach ($optionIds as $optionId) {
848 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
849 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
850 $totalTax +
= $field['options'][$optionId]['tax_amount'];
852 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
855 isset($lineItem[$optionId]['auto_renew']) &&
856 is_numeric($lineItem[$optionId]['auto_renew'])
858 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
865 $amount_level = array();
866 $totalParticipant = 0;
867 if (is_array($lineItem)) {
868 foreach ($lineItem as $values) {
869 $totalParticipant +
= $values['participant_count'];
870 if ($values['html_type'] == 'Text') {
871 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
874 $amount_level[] = $values['label'];
878 $displayParticipantCount = '';
879 if ($totalParticipant > 0) {
880 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
882 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
883 $params['amount'] = $totalPrice;
884 $params['tax_amount'] = $totalTax;
886 foreach ($autoRenew as $dontCare => $eachAmount) {
888 unset($autoRenew[$dontCare]);
891 if (count($autoRenew) > 1) {
892 $params['autoRenew'] = $autoRenew;
898 * Build the price set form.
900 * @param CRM_Core_Form $form
904 public static function buildPriceSet(&$form) {
905 $priceSetId = $form->get('priceSetId');
910 $validFieldsOnly = TRUE;
911 $className = CRM_Utils_System
::getClassName($form);
912 if (in_array($className, array(
913 'CRM_Contribute_Form_Contribution',
914 'CRM_Member_Form_Membership'
916 $validFieldsOnly = FALSE;
919 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
920 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
921 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
922 $form->_quickConfig
= $quickConfig = 0;
923 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
927 $form->assign('quickConfig', $quickConfig);
928 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
929 $form->_quickConfig
= $quickConfig;
931 $form->assign('priceSet', $form->_priceSet
);
933 $component = 'contribution';
934 if ($className == 'CRM_Member_Form_Membership') {
935 $component = 'membership';
938 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
939 $feeBlock = &$form->_values
['fee'];
940 if (!empty($form->_useForMember
)) {
941 $component = 'membership';
945 $feeBlock = &$form->_priceSet
['fields'];
949 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
951 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
952 $adminFieldVisible = FALSE;
953 if (CRM_Core_Permission
::check('administer CiviCRM')) {
954 $adminFieldVisible = TRUE;
957 foreach ($feeBlock as $id => $field) {
958 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
959 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
962 $options = CRM_Utils_Array
::value('options', $field);
963 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
964 $userid = $form->getVar('_membershipContactID');
965 $checklifetime = self
::checkCurrentMembership($options, $userid);
966 if ($checklifetime) {
967 $form->assign('ispricelifetime', TRUE);
970 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
973 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
974 'price_' . $field['id'],
977 CRM_Utils_Array
::value('is_required', $field, FALSE),
986 * Check the current Membership
987 * having end date null.
989 public static function checkCurrentMembership(&$options, $userid) {
990 if (!$userid ||
empty($options)) {
993 static $_contact_memberships = array();
994 $checklifetime = FALSE;
995 foreach ($options as $key => $value) {
996 if (!empty($value['membership_type_id'])) {
997 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
998 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
1000 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
1001 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
1002 unset($options[$key]);
1003 $checklifetime = TRUE;
1007 if ($checklifetime) {
1016 * Set daefult the price set fields.
1018 * @param CRM_Core_Form $form
1023 public static function setDefaultPriceSet(&$form, &$defaults) {
1024 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1028 foreach ($form->_priceSet
['fields'] as $key => $val) {
1029 foreach ($val['options'] as $keys => $values) {
1030 if ($values['is_default']) {
1031 if ($val['html_type'] == 'CheckBox') {
1032 $defaults["price_{$key}"][$keys] = 1;
1035 $defaults["price_{$key}"] = $keys;
1044 * Supports event create function by setting up required price sets, not tested but expect
1045 * it will work for contribution page
1046 * @param array $params
1047 * As passed to api/bao create fn.
1048 * @param CRM_Core_DAO $entity
1049 * Object for given entity.
1050 * @param string $entityName
1051 * Name of entity - e.g event.
1053 public static function setPriceSets(&$params, $entity, $entityName) {
1054 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1057 // CRM-14069 note that we may as well start by assuming more than one.
1058 // currently the form does not pass in as an array & will be skipped
1059 // test is passing in as an array but I feel the api should have a metadata that allows
1060 // transform of single to array - seems good for managing transitions - in which case all api
1061 // calls that set price_set_id will hit this
1062 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1063 // all separated values, strings, json half-separated values (in participant we hit this)
1064 // to be converted to json @ api layer
1065 $pse = new CRM_Price_DAO_PriceSetEntity();
1066 $pse->entity_table
= 'civicrm_' . $entityName;
1067 $pse->entity_id
= $entity->id
;
1068 while ($pse->fetch()) {
1069 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1070 // note an even more aggressive form of this deletion currently happens in event form
1071 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1072 // on the participant record
1073 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1074 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1078 foreach ($params['price_set_id'] as $priceSetID) {
1079 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1080 //@todo - how should we do this - copied from form
1081 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1082 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1083 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1089 * Get field ids of a price set
1095 * Array of the field ids
1099 public static function getFieldIds($id) {
1100 $priceField = new CRM_Price_DAO_PriceField();
1101 $priceField->price_set_id
= $id;
1102 $priceField->find();
1103 while ($priceField->fetch()) {
1104 $var[] = $priceField->id
;
1110 * Copy a price set, including all the fields
1113 * The price set id to copy.
1115 * @return CRM_Price_DAO_PriceSet
1118 public static function copy($id) {
1119 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1121 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1124 'title' => ' ' . $title,
1125 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1129 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1135 //copying all the blocks pertaining to the price set
1136 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1137 array('price_set_id' => $id),
1138 array('price_set_id' => $copy->id
)
1140 if (!empty($copyPriceField)) {
1141 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1143 //copy option group and values
1144 foreach ($price as $originalId => $copyId) {
1145 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1146 array('price_field_id' => $originalId),
1147 array('price_field_id' => $copyId)
1153 CRM_Utils_Hook
::copy('Set', $copy);
1158 * check price set permission
1165 public static function checkPermission($sid) {
1166 if ($sid && self
::eventPriceSetDomainID()) {
1167 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1168 if (CRM_Core_Config
::domainID() != $domain_id) {
1169 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1176 * Get the sum of participant count
1177 * for all fields of given price set.
1182 * @param bool $onlyActive
1184 * @return int|null|string
1187 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1195 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1198 static $pricesetFieldCount = array();
1199 if (!isset($pricesetFieldCount[$sid])) {
1201 SELECT sum(value.count) as totalCount
1202 FROM civicrm_price_field_value value
1203 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1204 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1208 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1209 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1212 return $pricesetFieldCount[$sid];
1220 public static function getMembershipCount($ids) {
1222 SELECT count( pfv.id ) AS count, pfv.id AS id
1223 FROM civicrm_price_field_value pfv
1224 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1225 WHERE pfv.id IN ( $ids )
1226 GROUP BY mt.member_of_contact_id";
1228 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1231 while ($crmDAO->fetch()) {
1232 $count[$crmDAO->id
] = $crmDAO->count
;
1239 * Check if auto renew option should be shown
1241 * @param int $priceSetId
1245 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1247 public static function checkAutoRenewForPriceSet($priceSetId) {
1248 // auto-renew option should be visible if membership types associated with all the fields has
1249 // been set for auto-renew option
1250 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1252 // get the membership type auto renew option and check if required or optional
1253 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1254 FROM civicrm_price_field_value pfv
1255 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1256 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1257 WHERE pf.price_set_id = %1
1258 AND pf.is_active = 1
1259 AND pfv.is_active = 1';
1261 $params = array(1 => array($priceSetId, 'Integer'));
1263 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1264 $autoRenewOption = 2;
1265 $interval = $unit = array();
1266 while ($dao->fetch()) {
1267 if (!$dao->auto_renew
) {
1268 $autoRenewOption = 0;
1271 if ($dao->auto_renew
== 1) {
1272 $autoRenewOption = 1;
1275 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1276 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1279 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1280 return $autoRenewOption;
1288 * Retrieve auto renew frequency and interval
1290 * @param int $priceSetId
1294 * associate array of frequency interval and unit
1297 public static function getRecurDetails($priceSetId) {
1298 $query = 'SELECT mt.duration_interval, mt.duration_unit
1299 FROM civicrm_price_field_value pfv
1300 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1301 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1302 WHERE pf.price_set_id = %1 LIMIT 1';
1304 $params = array(1 => array($priceSetId, 'Integer'));
1305 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1307 return array($dao->duration_interval
, $dao->duration_unit
);
1313 public static function eventPriceSetDomainID() {
1314 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1315 'event_price_set_domain_id',
1321 * Update the is_quick_config flag in the db
1324 * Id of the database record.
1325 * @param bool $isQuickConfigValue we want to set the is_quick_config field.
1326 * Value we want to set the is_quick_config field.
1329 * DAO object on sucess, null otherwise
1332 public static function setIsQuickConfig($id, $isQuickConfig) {
1333 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1337 * Check if price set id provides option for
1338 * user to select both auto-renew and non-auto-renew memberships
1342 public static function checkMembershipPriceSet($id) {
1345 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1346 FROM civicrm_price_field_value pfv
1347 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1348 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1349 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1353 $params = array(1 => array($id, 'Integer'));
1354 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1356 $autoRenew = array();
1357 //FIXME: do a comprehensive check of whether
1358 //2 membership types can be selected
1359 //instead of comparing all of them
1360 while ($dao->fetch()) {
1361 //temp fix for #CRM-10370
1362 //if its NULL consider it '0' i.e. 'No auto-renew option'
1363 $daoAutoRenew = $dao->auto_renew
;
1364 if ($daoAutoRenew === NULL) {
1367 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1370 $autoRenew[] = $daoAutoRenew;
1376 * Copy priceSet when event/contibution page is copied
1378 * @param string $baoName
1381 * Old event/contribution page id.
1383 * Newly created event/contribution page id.
1385 public static function copyPriceSet($baoName, $id, $newId) {
1386 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1388 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1389 if ($isQuickConfig) {
1390 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1391 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1394 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1397 'entity_table' => $baoName,
1399 array('entity_id' => $newId)
1402 // copy event discount
1403 if ($baoName == 'civicrm_event') {
1404 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1405 foreach ($discount as $discountId => $setId) {
1407 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1409 CRM_Core_DAO
::copyGeneric(
1410 'CRM_Core_DAO_Discount',
1412 'id' => $discountId,
1415 'entity_id' => $newId,
1416 'price_set_id' => $copyPriceSet->id
,
1425 * Function to set tax_amount and tax_rate in LineItem
1427 public static function setLineItem($field, $lineItem, $optionValueId) {
1428 if ($field['html_type'] == 'Text') {
1429 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1432 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1434 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1435 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1436 $lineItem[$optionValueId]['tax_rate'] = $taxRate;