3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Business object for managing price sets
40 class CRM_Price_BAO_PriceSet
extends CRM_Price_DAO_PriceSet
{
43 * Static field for default price set details
48 static $_defaultPriceSet = NULL;
53 public function __construct() {
54 parent
::__construct();
58 * Takes an associative array and creates a price set object
60 * @param array $params (reference) an assoc array of name/value pairs
62 * @return CRM_Price_DAO_PriceSet object
65 public static function create(&$params) {
66 if(empty($params['id']) && empty($params['name'])) {
67 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
69 $priceSetBAO = new CRM_Price_BAO_PriceSet();
70 $priceSetBAO->copyValues($params);
71 if (self
::eventPriceSetDomainID()) {
72 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
74 return $priceSetBAO->save();
78 * Fetch object based on array of properties
80 * @param array $params (reference ) an assoc array of name/value pairs
81 * @param array $defaults (reference ) an assoc array to hold the flattened values
83 * @return CRM_Price_DAO_PriceSet object
86 public static function retrieve(&$params, &$defaults) {
87 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
91 * Update the is_active flag in the db
93 * @param int $id id of the database record
96 * @internal param bool $is_active value we want to set the is_active field
98 * @return Object DAO object on sucess, null otherwise
101 public static function setIsActive($id, $isActive) {
102 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
106 * Calculate the default price set id
107 * assigned to the contribution/membership etc
109 * @param string $entity
111 * @return array $defaultPriceSet default price set
116 public static function getDefaultPriceSet($entity = 'contribution') {
117 if (!empty(self
::$_defaultPriceSet[$entity])) {
118 return self
::$_defaultPriceSet[$entity];
120 $entityName = 'default_contribution_amount';
121 if ($entity == 'membership') {
122 $entityName = 'default_membership_type_amount';
126 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
127 FROM civicrm_price_set ps
128 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
129 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
130 WHERE ps.name = '{$entityName}'
133 $dao = CRM_Core_DAO
::executeQuery($sql);
134 self
::$_defaultPriceSet[$entity] = array();
135 while ($dao->fetch()) {
136 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
137 'setID' => $dao->setID
,
138 'priceFieldID' => $dao->priceFieldID
,
139 'name' => $dao->name
,
140 'label' => $dao->label
,
141 'priceFieldValueID' => $dao->priceFieldValueID
,
142 'membership_type_id' => $dao->membership_type_id
,
143 'amount' => $dao->amount
,
144 'financial_type_id' => $dao->financial_type_id
,
148 return self
::$_defaultPriceSet[$entity];
152 * Get the price set title.
154 * @param int $id id of price set
156 * @return string title
161 public static function getTitle($id) {
162 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
166 * Return a list of all forms which use this price set.
168 * @param int $id id of price set
169 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
173 public static function &getUsedBy($id, $simpleReturn = FALSE) {
174 $usedBy = $forms = $tables = array();
176 SELECT entity_table, entity_id
177 FROM civicrm_price_set_entity
178 WHERE price_set_id = %1";
179 $params = array(1 => array($id, 'Integer'));
180 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
182 while ($crmFormDAO->fetch()) {
183 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
184 $tables[] = $crmFormDAO->entity_table
;
186 // Return only tables
187 if ($simpleReturn == 'table') {
192 SELECT cli.entity_table, cli.entity_id
193 FROM civicrm_line_item cli
194 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
195 WHERE cpf.price_set_id = %1";
196 $params = array(1 => array($id, 'Integer'));
197 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
198 while ($crmFormDAO->fetch()) {
199 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
200 $tables[] = $crmFormDAO->entity_table
;
206 // Return only entity data
207 if ($simpleReturn == 'entity') {
210 foreach ($forms as $table => $entities) {
212 case 'civicrm_event':
213 $ids = implode(',', $entities);
214 $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
215 FROM civicrm_event ce
216 LEFT JOIN civicrm_option_value ON
217 ( ce.event_type_id = civicrm_option_value.value )
218 LEFT JOIN civicrm_option_group ON
219 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
221 civicrm_option_group.name = 'event_type' AND
224 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
225 while ($crmDAO->fetch()) {
226 if ($crmDAO->isTemplate
) {
227 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
228 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
229 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
232 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
233 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
234 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
235 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
236 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
241 case 'civicrm_contribution_page':
242 $ids = implode(',', $entities);
243 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
244 FROM civicrm_contribution_page cp, civicrm_financial_type ct
245 WHERE ct.id = cp.financial_type_id AND
248 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
249 while ($crmDAO->fetch()) {
250 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
251 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
252 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
253 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
257 case 'civicrm_contribution':
258 case 'civicrm_membership':
259 case 'civicrm_participant':
264 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
273 * Delete the price set
275 * @param int $id Price Set id
277 * @return boolean false if fields exist for this set, true if the
278 * set could be deleted
282 public static function deleteSet($id) {
283 // remove from all inactive forms
284 $usedBy = self
::getUsedBy($id);
285 if (isset($usedBy['civicrm_event'])) {
286 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
287 $eventDAO = new CRM_Event_DAO_Event();
288 $eventDAO->id
= $eventId;
290 while ($eventDAO->fetch()) {
291 self
::removeFrom('civicrm_event', $eventDAO->id
);
296 // delete price fields
297 $priceField = new CRM_Price_DAO_PriceField();
298 $priceField->price_set_id
= $id;
300 while ($priceField->fetch()) {
301 // delete options first
302 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
305 $set = new CRM_Price_DAO_PriceSet();
307 return $set->delete();
311 * Link the price set with the specified table and id
313 * @param string $entityTable
314 * @param integer $entityId
315 * @param integer $priceSetId
319 public static function addTo($entityTable, $entityId, $priceSetId) {
320 // verify that the price set exists
321 $dao = new CRM_Price_DAO_PriceSet();
322 $dao->id
= $priceSetId;
328 $dao = new CRM_Price_DAO_PriceSetEntity();
329 // find if this already exists
330 $dao->entity_id
= $entityId;
331 $dao->entity_table
= $entityTable;
334 // add or update price_set_id
335 $dao->price_set_id
= $priceSetId;
340 * Delete price set for the given entity and id
342 * @param string $entityTable
343 * @param integer $entityId
347 public static function removeFrom($entityTable, $entityId) {
348 $dao = new CRM_Price_DAO_PriceSetEntity();
349 $dao->entity_table
= $entityTable;
350 $dao->entity_id
= $entityId;
351 return $dao->delete();
355 * Find a price_set_id associatied with the given table, id and usedFor
356 * Used For value for events:1, contribution:2, membership:3
358 * @param string $entityTable
359 * @param int $entityId
360 * @param int $usedFor ( price set that extends/used for particular component )
362 * @param null $isQuickConfig
363 * @param null $setName
365 * @return integer|false price_set_id, or false if none found
367 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
368 if (!$entityTable ||
!$entityId) {
372 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
373 FROM civicrm_price_set ps
374 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
375 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
376 if ($isQuickConfig) {
377 $sql .= ' AND ps.is_quick_config = 0 ';
379 $params = array(1 => array($entityTable, 'String'),
380 2 => array($entityId, 'Integer'),
383 $sql .= " AND ps.extends LIKE '%%3%' ";
384 $params[3] = array($usedFor, 'Integer');
387 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
389 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
390 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
394 * Find a price_set_id associated with the given option value or field ID
396 * @param array $params (reference) an assoc array of name/value pairs
397 * array may contain either option id or
400 * @return integer|NULL price set id on success, null otherwise
403 public static function getSetId(&$params) {
406 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
407 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
408 $fieldValue->id
= $oid;
409 if ($fieldValue->find(TRUE)) {
410 $fid = $fieldValue->price_field_id
;
414 $fid = CRM_Utils_Array
::value('fid', $params);
418 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
425 * Return an associative array of all price sets
427 * @param bool $withInactive whether or not to include inactive entries
428 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
430 * @return array associative array of id => name
432 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
435 DISTINCT ( price_set_id ) as id, title
440 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
442 if (!$withInactive) {
443 $query .= ' AND civicrm_price_set.is_active = 1 ';
446 if (self
::eventPriceSetDomainID()) {
447 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
450 $priceSets = array();
452 if ($extendComponentName) {
453 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
457 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
460 $dao = CRM_Core_DAO
::executeQuery($query);
461 while ($dao->fetch()) {
462 $priceSets[$dao->id
] = $dao->title
;
468 * Get price set details
470 * An array containing price set details (including price fields) is returned
473 * @param bool $required
474 * @param bool $validOnly
476 * @internal param int $setId - price set id whose details are needed
478 * @return array $setTree - array consisting of field details
480 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
484 $priceFields = array(
493 'is_display_amounts',
502 if ($required == TRUE) {
503 $priceFields[] = 'is_required';
507 $select = 'SELECT ' . implode(',', $priceFields);
508 $from = ' FROM civicrm_price_field';
511 $params[1] = array($setID, 'Integer');
513 WHERE price_set_id = %1
518 $currentTime = date('YmdHis');
520 AND ( active_on IS NULL OR active_on <= {$currentTime} )
521 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
525 $orderBy = ' ORDER BY weight';
527 $sql = $select . $from . $where . $dateSelect . $orderBy;
529 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
531 $visibility = CRM_Core_PseudoConstant
::visibility('name');
532 while ($dao->fetch()) {
535 $setTree[$setID]['fields'][$fieldID] = array();
536 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
538 foreach ($priceFields as $field) {
539 if ($field == 'id' ||
is_null($dao->$field)) {
543 if ($field == 'visibility_id') {
544 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
546 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
548 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
551 // also get the pre and post help from this price set
553 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
554 FROM civicrm_price_set
556 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
558 $setTree[$setID]['extends'] = $dao->extends;
559 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
560 $setTree[$setID]['help_pre'] = $dao->help_pre
;
561 $setTree[$setID]['help_post'] = $dao->help_post
;
562 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
568 * Get the Price Field ID. We call this function when more than one being present would represent an error
569 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
570 * @param array $priceSet
572 * @throws CRM_Core_Exception
575 public static function getOnlyPriceFieldID(array $priceSet) {
576 if(count($priceSet['fields']) > 1) {
577 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
579 return (int) implode('_', array_keys($priceSet['fields']));
583 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
584 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
585 * @param array $priceSet
587 * @throws CRM_Core_Exception
590 public static function getOnlyPriceFieldValueID(array $priceSet) {
591 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
592 if(count($priceSet['fields'][$priceFieldID]['options']) > 1) {
593 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
595 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
600 * @param CRM_Core_Form $form
602 * @param string $entityTable
603 * @param bool $validOnly
604 * @param int $priceSetId
606 * @return bool|false|int|null
608 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
610 $priceSetId = self
::getFor($entityTable, $id);
613 //check if priceset is is_config
614 if (is_numeric($priceSetId)) {
615 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
616 $form->assign('quickConfig', 1);
621 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
622 $entityId = $entity = NULL;
624 switch ($entityTable) {
625 case 'civicrm_event':
626 $entity = 'participant';
627 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
628 $entityId = $form->_id
;
631 $entityId = $form->_participantId
;
635 case 'civicrm_contribution_page':
636 case 'civicrm_contribution':
637 $entity = 'contribution';
638 $entityId = $form->_id
;
642 if ($entityId && $entity) {
643 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
651 $form->_priceSetId
= $priceSetId;
652 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
653 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
654 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
656 //get the price set fields participant count.
657 if ($entityTable == 'civicrm_event') {
658 //get option count info.
659 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
660 if ($form->_priceSet
['optionsCountTotal']) {
661 $optionsCountDeails = array();
662 if (!empty($form->_priceSet
['fields'])) {
663 foreach ($form->_priceSet
['fields'] as $field) {
664 foreach ($field['options'] as $option) {
665 $count = CRM_Utils_Array
::value('count', $option, 0);
666 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
670 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
673 //get option max value info.
674 $optionsMaxValueTotal = 0;
675 $optionsMaxValueDetails = array();
677 if (!empty($form->_priceSet
['fields'])) {
678 foreach ($form->_priceSet
['fields'] as $field) {
679 foreach ($field['options'] as $option) {
680 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
681 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
682 $optionsMaxValueTotal +
= $maxVal;
687 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
688 if ($optionsMaxValueTotal) {
689 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
692 $form->set('priceSetId', $form->_priceSetId
);
693 $form->set('priceSet', $form->_priceSet
);
702 * @param array $params
704 * @param string $component
706 public static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
708 $totalPrice = $totalTax = 0;
709 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
711 $autoRenew = array();
712 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
714 foreach ($fields as $id => $field) {
715 if (empty($params["price_{$id}"]) ||
716 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
718 // skip if nothing was submitted for this field
722 switch ($field['html_type']) {
724 $firstOption = reset($field['options']);
725 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
726 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
727 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
728 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
729 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
731 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
732 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
733 if (array_key_exists($params['financial_type_id'], $taxRates)) {
734 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
735 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
736 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
737 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
738 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
741 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
745 //special case if user select -none-
746 if ($params["price_{$id}"] <= 0) {
749 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
750 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
751 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
752 $params['amount_priceset_level_radio'] = array();
753 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
754 if (isset($radioLevel)) {
755 $radioLevel = array_merge($radioLevel,
756 array_keys($params['amount_priceset_level_radio'])
760 $radioLevel = array_keys($params['amount_priceset_level_radio']);
762 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
763 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
764 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
765 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
766 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
767 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
770 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
773 // auto_renew exists and is empty in some workflows, which php treat as a 0
774 // and hence we explicitly check to see if auto_renew is numeric
775 isset($lineItem[$optionValueId]['auto_renew']) &&
776 is_numeric($lineItem[$optionValueId]['auto_renew'])
778 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
783 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
784 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
785 $optionLabel = $field['options'][$optionValueId]['label'];
786 $params['amount_priceset_level_select'] = array();
787 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
788 if (isset($selectLevel)) {
789 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
792 $selectLevel = array_keys($params['amount_priceset_level_select']);
794 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
795 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
796 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
797 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
799 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
802 isset($lineItem[$optionValueId]['auto_renew']) &&
803 is_numeric($lineItem[$optionValueId]['auto_renew'])
805 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
810 $params['amount_priceset_level_checkbox'] = $optionIds = array();
811 foreach ($params["price_{$id}"] as $optionId => $option) {
812 $optionIds[] = $optionId;
813 $optionLabel = $field['options'][$optionId]['label'];
814 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
815 if (isset($checkboxLevel)) {
816 $checkboxLevel = array_unique(array_merge(
818 array_keys($params['amount_priceset_level_checkbox'])
823 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
826 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
827 foreach ($optionIds as $optionId) {
828 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
829 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
830 $totalTax +
= $field['options'][$optionId]['tax_amount'];
832 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
835 isset($lineItem[$optionId]['auto_renew']) &&
836 is_numeric($lineItem[$optionId]['auto_renew'])
838 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
845 $amount_level = array();
846 $totalParticipant = 0;
847 if (is_array($lineItem)) {
848 foreach ($lineItem as $values) {
849 $totalParticipant +
= $values['participant_count'];
850 if ($values['html_type'] == 'Text') {
851 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
854 $amount_level[] = $values['label'];
858 $displayParticipantCount = '';
859 if ($totalParticipant > 0) {
860 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
862 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
863 $params['amount'] = $totalPrice;
864 $params['tax_amount'] = $totalTax;
866 foreach ($autoRenew as $dontCare => $eachAmount) {
868 unset($autoRenew[$dontCare]);
871 if (count($autoRenew) > 1 ) {
872 $params['autoRenew'] = $autoRenew;
878 * Build the price set form.
880 * @param CRM_Core_Form $form
884 public static function buildPriceSet(&$form) {
885 $priceSetId = $form->get('priceSetId');
890 $validFieldsOnly = TRUE;
891 $className = CRM_Utils_System
::getClassName($form);
892 if (in_array($className, array(
893 'CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'))) {
894 $validFieldsOnly = FALSE;
897 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
898 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
899 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
900 $form->_quickConfig
= $quickConfig = 0;
901 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
905 $form->assign('quickConfig', $quickConfig);
906 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
907 $form->_quickConfig
= $quickConfig;
909 $form->assign('priceSet', $form->_priceSet
);
911 $component = 'contribution';
912 if ($className == 'CRM_Member_Form_Membership') {
913 $component = 'membership';
916 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
917 $feeBlock = &$form->_values
['fee'];
918 if (!empty($form->_useForMember
)) {
919 $component = 'membership';
923 $feeBlock = &$form->_priceSet
['fields'];
927 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
929 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
930 $adminFieldVisible = false;
931 if (CRM_Core_Permission
::check('administer CiviCRM')) {
932 $adminFieldVisible = true;
935 foreach ($feeBlock as $id => $field) {
936 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
937 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == true) ||
940 $options = CRM_Utils_Array
::value('options', $field);
941 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
942 $userid = $form->getVar('_membershipContactID');
943 $checklifetime = self
::checkCurrentMembership($options, $userid);
944 if ($checklifetime) {
945 $form->assign('ispricelifetime', TRUE);
948 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
951 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
952 'price_' . $field['id'],
955 CRM_Utils_Array
::value('is_required', $field, FALSE),
964 * Check the current Membership
965 * having end date null.
967 public static function checkCurrentMembership(&$options, $userid) {
968 if (!$userid ||
empty($options)) {
971 static $_contact_memberships = array();
972 $checklifetime = FALSE;
973 foreach ($options as $key => $value) {
974 if (!empty($value['membership_type_id'])) {
975 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
976 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
978 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
979 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
980 unset($options[$key]);
981 $checklifetime = TRUE;
985 if ($checklifetime) {
994 * Set daefult the price set fields.
996 * @param CRM_Core_Form $form
999 * @return array $defaults
1001 public static function setDefaultPriceSet(&$form, &$defaults) {
1002 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1006 foreach ($form->_priceSet
['fields'] as $key => $val) {
1007 foreach ($val['options'] as $keys => $values) {
1008 if ($values['is_default']) {
1009 if ($val['html_type'] == 'CheckBox') {
1010 $defaults["price_{$key}"][$keys] = 1;
1013 $defaults["price_{$key}"] = $keys;
1022 * Supports event create function by setting up required price sets, not tested but expect
1023 * it will work for contribution page
1024 * @param array $params as passed to api/bao create fn
1025 * @param CRM_Core_DAO $entity object for given entity
1026 * @param string $entityName name of entity - e.g event
1028 public static function setPriceSets(&$params, $entity, $entityName) {
1029 if(empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1032 // CRM-14069 note that we may as well start by assuming more than one.
1033 // currently the form does not pass in as an array & will be skipped
1034 // test is passing in as an array but I feel the api should have a metadata that allows
1035 // transform of single to array - seems good for managing transitions - in which case all api
1036 // calls that set price_set_id will hit this
1037 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1038 // all separated values, strings, json half-separated values (in participant we hit this)
1039 // to be converted to json @ api layer
1040 $pse = new CRM_Price_DAO_PriceSetEntity();
1041 $pse->entity_table
= 'civicrm_' . $entityName;
1042 $pse->entity_id
= $entity->id
;
1043 while ($pse->fetch()) {
1044 if(!in_array($pse->price_set_id
, $params['price_set_id'])) {
1045 // note an even more aggressive form of this deletion currently happens in event form
1046 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1047 // on the participant record
1048 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1049 CRM_Core_BAO_Discount
::del($entity->id
,'civicrm_' . $entityName);
1053 foreach ($params['price_set_id'] as $priceSetID) {
1054 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1055 //@todo - how should we do this - copied from form
1056 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1057 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1058 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1063 * Get field ids of a price set
1065 * @param int $id Price Set id
1067 * @return array of the field ids
1071 public static function getFieldIds($id) {
1072 $priceField = new CRM_Price_DAO_PriceField();
1073 $priceField->price_set_id
= $id;
1074 $priceField->find();
1075 while ($priceField->fetch()) {
1076 $var[] = $priceField->id
;
1082 * This function is to make a copy of a price set, including
1085 * @param int $id the price set id to copy
1087 * @return the copy object
1090 public static function copy($id) {
1091 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1093 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1095 'suffix' => array('title' => ' ' . $title,
1096 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1100 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1106 //copying all the blocks pertaining to the price set
1107 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1108 array('price_set_id' => $id),
1109 array('price_set_id' => $copy->id
)
1111 if (!empty($copyPriceField)) {
1112 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1114 //copy option group and values
1115 foreach ($price as $originalId => $copyId) {
1116 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1117 array('price_field_id' => $originalId),
1118 array('price_field_id' => $copyId)
1124 CRM_Utils_Hook
::copy('Set', $copy);
1129 * This function is to check price set permission
1131 * @param int $sid the price set id
1135 public static function checkPermission($sid) {
1136 if ($sid && self
::eventPriceSetDomainID()) {
1137 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1138 if (CRM_Core_Config
::domainID() != $domain_id) {
1139 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1146 * Get the sum of participant count
1147 * for all fields of given price set.
1149 * @param int $sid the price set id
1151 * @param bool $onlyActive
1153 * @return int|null|string
1156 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1164 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1167 static $pricesetFieldCount = array();
1168 if (!isset($pricesetFieldCount[$sid])) {
1170 SELECT sum(value.count) as totalCount
1171 FROM civicrm_price_field_value value
1172 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1173 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1177 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1178 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1181 return $pricesetFieldCount[$sid];
1189 public static function getMembershipCount($ids) {
1191 SELECT count( pfv.id ) AS count, pfv.id AS id
1192 FROM civicrm_price_field_value pfv
1193 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1194 WHERE pfv.id IN ( $ids )
1195 GROUP BY mt.member_of_contact_id";
1197 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1200 while ($crmDAO->fetch()) {
1201 $count[$crmDAO->id
] = $crmDAO->count
;
1208 * Check if auto renew option should be shown
1210 * @param int $priceSetId price set id
1212 * @return int $autoRenewOption ( 0:hide, 1:optional 2:required )
1214 public static function checkAutoRenewForPriceSet($priceSetId) {
1215 // auto-renew option should be visible if membership types associated with all the fields has
1216 // been set for auto-renew option
1217 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1219 // get the membership type auto renew option and check if required or optional
1220 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1221 FROM civicrm_price_field_value pfv
1222 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1223 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1224 WHERE pf.price_set_id = %1
1225 AND pf.is_active = 1
1226 AND pfv.is_active = 1';
1228 $params = array(1 => array($priceSetId, 'Integer'));
1230 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1231 $autoRenewOption = 2;
1232 $interval = $unit = array();
1233 while ($dao->fetch()) {
1234 if (!$dao->auto_renew
) {
1235 $autoRenewOption = 0;
1238 if ($dao->auto_renew
== 1) {
1239 $autoRenewOption = 1;
1242 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1243 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1246 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1247 return $autoRenewOption;
1255 * Retrieve auto renew frequency and interval
1257 * @param int $priceSetId price set id
1259 * @return array associate array of frequency interval and unit
1262 public static function getRecurDetails($priceSetId) {
1263 $query = 'SELECT mt.duration_interval, mt.duration_unit
1264 FROM civicrm_price_field_value pfv
1265 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1266 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1267 WHERE pf.price_set_id = %1 LIMIT 1';
1269 $params = array(1 => array($priceSetId, 'Integer'));
1270 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1272 return array($dao->duration_interval
, $dao->duration_unit
);
1278 public static function eventPriceSetDomainID() {
1279 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1280 'event_price_set_domain_id',
1286 * Update the is_quick_config flag in the db
1288 * @param int $id id of the database record
1289 * @param boolean $isQuickConfig value we want to set the is_quick_config field
1291 * @return Object DAO object on sucess, null otherwise
1294 public static function setIsQuickConfig($id, $isQuickConfig) {
1295 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1299 * Check if price set id provides option for
1300 * user to select both auto-renew and non-auto-renew memberships
1305 public static function checkMembershipPriceSet($id) {
1308 SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1309 FROM civicrm_price_field_value pfv
1310 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1311 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1312 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1316 $params = array(1 => array($id, 'Integer'));
1317 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1319 $autoRenew = array();
1320 //FIXME: do a comprehensive check of whether
1321 //2 membership types can be selected
1322 //instead of comparing all of them
1323 while ($dao->fetch()) {
1324 //temp fix for #CRM-10370
1325 //if its NULL consider it '0' i.e. 'No auto-renew option'
1326 $daoAutoRenew = $dao->auto_renew
;
1327 if ($daoAutoRenew === NULL) {
1330 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
1333 $autoRenew[] = $daoAutoRenew;
1339 * Copy priceSet when event/contibution page is copied
1341 * @param string $baoName BAO name
1342 * @param int $id old event/contribution page id
1343 * @param int $newId newly created event/contribution page id
1345 public static function copyPriceSet($baoName, $id, $newId) {
1346 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1348 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1349 if($isQuickConfig) {
1350 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($priceSetId);
1351 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1354 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1357 'entity_table' => $baoName,
1359 array('entity_id' => $newId)
1362 // copy event discount
1363 if ($baoName == 'civicrm_event') {
1364 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1365 foreach ($discount as $discountId => $setId) {
1367 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1369 CRM_Core_DAO
::copyGeneric(
1370 'CRM_Core_DAO_Discount',
1372 'id' => $discountId,
1375 'entity_id' => $newId,
1376 'price_set_id' => $copyPriceSet->id
,
1385 * Function to set tax_amount and tax_rate in LineItem
1389 public static function setLineItem($field, $lineItem, $optionValueId) {
1390 if ($field['html_type'] == 'Text') {
1391 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1394 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1396 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1397 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1398 $lineItem[$optionValueId]['tax_rate'] = $taxRate;