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.
47 static $_defaultPriceSet = NULL;
52 public function __construct() {
53 parent
::__construct();
57 * Takes an associative array and creates a price set object.
59 * @param array $params
60 * (reference) an assoc array of name/value pairs.
62 * @return CRM_Price_DAO_PriceSet
64 public static function create(&$params) {
65 if (empty($params['id']) && empty($params['name'])) {
66 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
68 if (!empty($params['extends']) && is_array($params['extends'])) {
69 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
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 * Fetch object based on array of properties.
82 * @param array $params
83 * (reference ) an assoc array of name/value pairs.
84 * @param array $defaults
85 * (reference ) an assoc array to hold the flattened values.
87 * @return CRM_Price_DAO_PriceSet
89 public static function retrieve(&$params, &$defaults) {
90 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
94 * Update the is_active flag in the db.
97 * Id of the database record.
100 * @internal param bool $is_active value we want to set the is_active field
103 * DAO object on sucess, null otherwise
105 public static function setIsActive($id, $isActive) {
106 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
110 * Calculate the default price set id
111 * assigned to the contribution/membership etc
113 * @param string $entity
119 public static function getDefaultPriceSet($entity = 'contribution') {
120 if (!empty(self
::$_defaultPriceSet[$entity])) {
121 return self
::$_defaultPriceSet[$entity];
123 $entityName = 'default_contribution_amount';
124 if ($entity == 'membership') {
125 $entityName = 'default_membership_type_amount';
129 SELECT ps.id AS setID, pfv.price_field_id AS priceFieldID, pfv.id AS priceFieldValueID, pfv.name, pfv.label, pfv.membership_type_id, pfv.amount, pfv.financial_type_id
130 FROM civicrm_price_set ps
131 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
132 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
133 WHERE ps.name = '{$entityName}'
136 $dao = CRM_Core_DAO
::executeQuery($sql);
137 self
::$_defaultPriceSet[$entity] = array();
138 while ($dao->fetch()) {
139 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
140 'setID' => $dao->setID
,
141 'priceFieldID' => $dao->priceFieldID
,
142 'name' => $dao->name
,
143 'label' => $dao->label
,
144 'priceFieldValueID' => $dao->priceFieldValueID
,
145 'membership_type_id' => $dao->membership_type_id
,
146 'amount' => $dao->amount
,
147 'financial_type_id' => $dao->financial_type_id
,
151 return self
::$_defaultPriceSet[$entity];
155 * Get the price set title.
164 public static function getTitle($id) {
165 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
169 * Return a list of all forms which use this price set.
173 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
177 public static function &getUsedBy($id, $simpleReturn = FALSE) {
178 $usedBy = $forms = $tables = array();
180 SELECT entity_table, entity_id
181 FROM civicrm_price_set_entity
182 WHERE price_set_id = %1";
183 $params = array(1 => array($id, 'Integer'));
184 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
186 while ($crmFormDAO->fetch()) {
187 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
188 $tables[] = $crmFormDAO->entity_table
;
190 // Return only tables
191 if ($simpleReturn == 'table') {
196 SELECT cli.entity_table, cli.entity_id
197 FROM civicrm_line_item cli
198 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
199 WHERE cpf.price_set_id = %1";
200 $params = array(1 => array($id, 'Integer'));
201 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
202 while ($crmFormDAO->fetch()) {
203 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
204 $tables[] = $crmFormDAO->entity_table
;
210 // Return only entity data
211 if ($simpleReturn == 'entity') {
214 foreach ($forms as $table => $entities) {
216 case 'civicrm_event':
217 $ids = implode(',', $entities);
218 $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
219 FROM civicrm_event ce
220 LEFT JOIN civicrm_option_value ON
221 ( ce.event_type_id = civicrm_option_value.value )
222 LEFT JOIN civicrm_option_group ON
223 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
225 civicrm_option_group.name = 'event_type' AND
228 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
229 while ($crmDAO->fetch()) {
230 if ($crmDAO->isTemplate
) {
231 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
232 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
233 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
236 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
237 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
238 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
239 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
240 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
245 case 'civicrm_contribution_page':
246 $ids = implode(',', $entities);
247 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
248 FROM civicrm_contribution_page cp, civicrm_financial_type ct
249 WHERE ct.id = cp.financial_type_id AND
252 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
253 while ($crmDAO->fetch()) {
254 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
255 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
256 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
257 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
261 case 'civicrm_contribution':
262 case 'civicrm_membership':
263 case 'civicrm_participant':
268 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");
277 * Delete the price set.
283 * false if fields exist for this set, true if the
284 * set could be deleted
287 public static function deleteSet($id) {
288 // remove from all inactive forms
289 $usedBy = self
::getUsedBy($id);
290 if (isset($usedBy['civicrm_event'])) {
291 foreach ($usedBy['civicrm_event'] as $eventId => $unused) {
292 $eventDAO = new CRM_Event_DAO_Event();
293 $eventDAO->id
= $eventId;
295 while ($eventDAO->fetch()) {
296 self
::removeFrom('civicrm_event', $eventDAO->id
);
301 // delete price fields
302 $priceField = new CRM_Price_DAO_PriceField();
303 $priceField->price_set_id
= $id;
305 while ($priceField->fetch()) {
306 // delete options first
307 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
310 $set = new CRM_Price_DAO_PriceSet();
312 return $set->delete();
316 * Link the price set with the specified table and id.
318 * @param string $entityTable
319 * @param int $entityId
320 * @param int $priceSetId
324 public static function addTo($entityTable, $entityId, $priceSetId) {
325 // verify that the price set exists
326 $dao = new CRM_Price_DAO_PriceSet();
327 $dao->id
= $priceSetId;
333 $dao = new CRM_Price_DAO_PriceSetEntity();
334 // find if this already exists
335 $dao->entity_id
= $entityId;
336 $dao->entity_table
= $entityTable;
339 // add or update price_set_id
340 $dao->price_set_id
= $priceSetId;
345 * Delete price set for the given entity and id.
347 * @param string $entityTable
348 * @param int $entityId
352 public static function removeFrom($entityTable, $entityId) {
353 $dao = new CRM_Price_DAO_PriceSetEntity();
354 $dao->entity_table
= $entityTable;
355 $dao->entity_id
= $entityId;
356 return $dao->delete();
360 * Find a price_set_id associatied with the given table, id and usedFor
361 * Used For value for events:1, contribution:2, membership:3
363 * @param string $entityTable
364 * @param int $entityId
365 * @param int $usedFor
366 * ( price set that extends/used for particular component ).
368 * @param null $isQuickConfig
369 * @param null $setName
372 * price_set_id, or false if none found
374 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
375 if (!$entityTable ||
!$entityId) {
379 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
380 FROM civicrm_price_set ps
381 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
382 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
383 if ($isQuickConfig) {
384 $sql .= ' AND ps.is_quick_config = 0 ';
387 1 => array($entityTable, 'String'),
388 2 => array($entityId, 'Integer'),
391 $sql .= " AND ps.extends LIKE '%%3%' ";
392 $params[3] = array($usedFor, 'Integer');
395 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
397 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
398 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
402 * Find a price_set_id associated with the given option value or field ID.
404 * @param array $params
405 * (reference) an assoc array of name/value pairs.
406 * array may contain either option id or
410 * price set id on success, null otherwise
412 public static function getSetId(&$params) {
415 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
416 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
417 $fieldValue->id
= $oid;
418 if ($fieldValue->find(TRUE)) {
419 $fid = $fieldValue->price_field_id
;
423 $fid = CRM_Utils_Array
::value('fid', $params);
427 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
434 * Return an associative array of all price sets.
436 * @param bool $withInactive
437 * Whether or not to include inactive entries.
438 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
441 * associative array of id => name
443 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
446 DISTINCT ( price_set_id ) as id, title
451 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
453 if (!$withInactive) {
454 $query .= ' AND civicrm_price_set.is_active = 1 ';
457 if (self
::eventPriceSetDomainID()) {
458 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config
::domainID();
461 $priceSets = array();
463 if ($extendComponentName) {
464 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
468 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
471 $dao = CRM_Core_DAO
::executeQuery($query);
472 while ($dao->fetch()) {
473 $priceSets[$dao->id
] = $dao->title
;
479 * Get price set details.
481 * An array containing price set details (including price fields) is returned
484 * @param bool $required
485 * @param bool $validOnly
488 * array consisting of field details
490 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
494 $priceFields = array(
503 'is_display_amounts',
512 if ($required == TRUE) {
513 $priceFields[] = 'is_required';
517 $select = 'SELECT ' . implode(',', $priceFields);
518 $from = ' FROM civicrm_price_field';
521 $params[1] = array($setID, 'Integer');
523 WHERE price_set_id = %1
528 $currentTime = date('YmdHis');
530 AND ( active_on IS NULL OR active_on <= {$currentTime} )
531 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
535 $orderBy = ' ORDER BY weight';
537 $sql = $select . $from . $where . $dateSelect . $orderBy;
539 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
541 $visibility = CRM_Core_PseudoConstant
::visibility('name');
542 while ($dao->fetch()) {
545 $setTree[$setID]['fields'][$fieldID] = array();
546 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
548 foreach ($priceFields as $field) {
549 if ($field == 'id' ||
is_null($dao->$field)) {
553 if ($field == 'visibility_id') {
554 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
556 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
558 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE);
561 // also get the pre and post help from this price set
563 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
564 FROM civicrm_price_set
566 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
568 $setTree[$setID]['extends'] = $dao->extends;
569 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
570 $setTree[$setID]['help_pre'] = $dao->help_pre
;
571 $setTree[$setID]['help_post'] = $dao->help_post
;
572 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
578 * Get the Price Field ID. We call this function when more than one being present would represent an error
579 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
580 * @param array $priceSet
582 * @throws CRM_Core_Exception
585 public static function getOnlyPriceFieldID(array $priceSet) {
586 if (count($priceSet['fields']) > 1) {
587 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
589 return (int) implode('_', array_keys($priceSet['fields']));
593 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
594 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
595 * @param array $priceSet
597 * @throws CRM_Core_Exception
600 public static function getOnlyPriceFieldValueID(array $priceSet) {
601 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
602 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
603 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
605 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
610 * @param CRM_Core_Form $form
612 * @param string $entityTable
613 * @param bool $validOnly
614 * @param int $priceSetId
616 * @return bool|false|int|null
618 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
620 $priceSetId = self
::getFor($entityTable, $id);
623 //check if priceset is is_config
624 if (is_numeric($priceSetId)) {
625 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
626 $form->assign('quickConfig', 1);
631 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
632 $entityId = $entity = NULL;
634 switch ($entityTable) {
635 case 'civicrm_event':
636 $entity = 'participant';
637 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
638 $entityId = $form->_id
;
641 $entityId = $form->_participantId
;
645 case 'civicrm_contribution_page':
646 case 'civicrm_contribution':
647 $entity = 'contribution';
648 $entityId = $form->_id
;
652 if ($entityId && $entity) {
653 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
661 $form->_priceSetId
= $priceSetId;
662 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
663 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
664 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
666 //get the price set fields participant count.
667 if ($entityTable == 'civicrm_event') {
668 //get option count info.
669 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
670 if ($form->_priceSet
['optionsCountTotal']) {
671 $optionsCountDeails = array();
672 if (!empty($form->_priceSet
['fields'])) {
673 foreach ($form->_priceSet
['fields'] as $field) {
674 foreach ($field['options'] as $option) {
675 $count = CRM_Utils_Array
::value('count', $option, 0);
676 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
680 $form->_priceSet
['optionsCountDetails'] = $optionsCountDeails;
683 //get option max value info.
684 $optionsMaxValueTotal = 0;
685 $optionsMaxValueDetails = array();
687 if (!empty($form->_priceSet
['fields'])) {
688 foreach ($form->_priceSet
['fields'] as $field) {
689 foreach ($field['options'] as $option) {
690 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
691 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
692 $optionsMaxValueTotal +
= $maxVal;
697 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
698 if ($optionsMaxValueTotal) {
699 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
702 $form->set('priceSetId', $form->_priceSetId
);
703 $form->set('priceSet', $form->_priceSet
);
712 * @param array $params
714 * @param string $component
716 public static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
718 $totalPrice = $totalTax = 0;
719 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
721 $autoRenew = array();
722 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
724 foreach ($fields as $id => $field) {
725 if (empty($params["price_{$id}"]) ||
726 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
728 // skip if nothing was submitted for this field
732 switch ($field['html_type']) {
734 $firstOption = reset($field['options']);
735 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
736 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
737 if (CRM_Utils_Array
::value('tax_rate', $field['options'][key($field['options'])])) {
738 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
739 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
741 if (CRM_Utils_Array
::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
742 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
743 if (array_key_exists($params['financial_type_id'], $taxRates)) {
744 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
745 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
746 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
747 $lineItem = self
::setLineItem($field, $lineItem, key($field['options']));
748 $totalTax +
= $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
751 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
755 //special case if user select -none-
756 if ($params["price_{$id}"] <= 0) {
759 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
760 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
761 $optionLabel = CRM_Utils_Array
::value('label', $field['options'][$optionValueId]);
762 $params['amount_priceset_level_radio'] = array();
763 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
764 if (isset($radioLevel)) {
765 $radioLevel = array_merge($radioLevel,
766 array_keys($params['amount_priceset_level_radio'])
770 $radioLevel = array_keys($params['amount_priceset_level_radio']);
772 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
773 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
774 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
775 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
776 if (CRM_Utils_Array
::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
777 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
780 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
783 // auto_renew exists and is empty in some workflows, which php treat as a 0
784 // and hence we explicitly check to see if auto_renew is numeric
785 isset($lineItem[$optionValueId]['auto_renew']) &&
786 is_numeric($lineItem[$optionValueId]['auto_renew'])
788 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
793 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
794 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
795 $optionLabel = $field['options'][$optionValueId]['label'];
796 $params['amount_priceset_level_select'] = array();
797 $params['amount_priceset_level_select'][CRM_Utils_Array
::key(1, $params["price_{$id}"])] = $optionLabel;
798 if (isset($selectLevel)) {
799 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
802 $selectLevel = array_keys($params['amount_priceset_level_select']);
804 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
805 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
806 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId);
807 $totalTax +
= $field['options'][$optionValueId]['tax_amount'];
809 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
812 isset($lineItem[$optionValueId]['auto_renew']) &&
813 is_numeric($lineItem[$optionValueId]['auto_renew'])
815 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
820 $params['amount_priceset_level_checkbox'] = $optionIds = array();
821 foreach ($params["price_{$id}"] as $optionId => $option) {
822 $optionIds[] = $optionId;
823 $optionLabel = $field['options'][$optionId]['label'];
824 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
825 if (isset($checkboxLevel)) {
826 $checkboxLevel = array_unique(array_merge(
828 array_keys($params['amount_priceset_level_checkbox'])
833 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
836 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
837 foreach ($optionIds as $optionId) {
838 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
839 $lineItem = self
::setLineItem($field, $lineItem, $optionId);
840 $totalTax +
= $field['options'][$optionId]['tax_amount'];
842 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
845 isset($lineItem[$optionId]['auto_renew']) &&
846 is_numeric($lineItem[$optionId]['auto_renew'])
848 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
855 $amount_level = array();
856 $totalParticipant = 0;
857 if (is_array($lineItem)) {
858 foreach ($lineItem as $values) {
859 $totalParticipant +
= $values['participant_count'];
860 if ($values['html_type'] == 'Text') {
861 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
864 $amount_level[] = $values['label'];
868 $displayParticipantCount = '';
869 if ($totalParticipant > 0) {
870 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
872 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
873 $params['amount'] = $totalPrice;
874 $params['tax_amount'] = $totalTax;
876 foreach ($autoRenew as $dontCare => $eachAmount) {
878 unset($autoRenew[$dontCare]);
881 if (count($autoRenew) > 1) {
882 $params['autoRenew'] = $autoRenew;
888 * Build the price set form.
890 * @param CRM_Core_Form $form
894 public static function buildPriceSet(&$form) {
895 $priceSetId = $form->get('priceSetId');
900 $validFieldsOnly = TRUE;
901 $className = CRM_Utils_System
::getClassName($form);
902 if (in_array($className, array(
903 'CRM_Contribute_Form_Contribution',
904 'CRM_Member_Form_Membership',
906 $validFieldsOnly = FALSE;
909 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
910 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
911 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
912 $form->_quickConfig
= $quickConfig = 0;
913 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
917 $form->assign('quickConfig', $quickConfig);
918 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
919 $form->_quickConfig
= $quickConfig;
921 $form->assign('priceSet', $form->_priceSet
);
923 $component = 'contribution';
924 if ($className == 'CRM_Member_Form_Membership') {
925 $component = 'membership';
928 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
929 $feeBlock = &$form->_values
['fee'];
930 if (!empty($form->_useForMember
)) {
931 $component = 'membership';
935 $feeBlock = &$form->_priceSet
['fields'];
939 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
941 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
942 $adminFieldVisible = FALSE;
943 if (CRM_Core_Permission
::check('administer CiviCRM')) {
944 $adminFieldVisible = TRUE;
947 foreach ($feeBlock as $id => $field) {
948 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
949 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
952 $options = CRM_Utils_Array
::value('options', $field);
953 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
954 $userid = $form->getVar('_membershipContactID');
955 $checklifetime = self
::checkCurrentMembership($options, $userid);
956 if ($checklifetime) {
957 $form->assign('ispricelifetime', TRUE);
960 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
963 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
964 'price_' . $field['id'],
967 CRM_Utils_Array
::value('is_required', $field, FALSE),
976 * Check the current Membership
977 * having end date null.
979 public static function checkCurrentMembership(&$options, $userid) {
980 if (!$userid ||
empty($options)) {
983 static $_contact_memberships = array();
984 $checklifetime = FALSE;
985 foreach ($options as $key => $value) {
986 if (!empty($value['membership_type_id'])) {
987 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
988 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
990 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
991 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
992 unset($options[$key]);
993 $checklifetime = TRUE;
997 if ($checklifetime) {
1006 * Set daefult the price set fields.
1008 * @param CRM_Core_Form $form
1013 public static function setDefaultPriceSet(&$form, &$defaults) {
1014 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1018 foreach ($form->_priceSet
['fields'] as $key => $val) {
1019 foreach ($val['options'] as $keys => $values) {
1020 if ($values['is_default']) {
1021 if ($val['html_type'] == 'CheckBox') {
1022 $defaults["price_{$key}"][$keys] = 1;
1025 $defaults["price_{$key}"] = $keys;
1034 * Supports event create function by setting up required price sets, not tested but expect
1035 * it will work for contribution page
1036 * @param array $params
1037 * As passed to api/bao create fn.
1038 * @param CRM_Core_DAO $entity
1039 * Object for given entity.
1040 * @param string $entityName
1041 * Name of entity - e.g event.
1043 public static function setPriceSets(&$params, $entity, $entityName) {
1044 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1047 // CRM-14069 note that we may as well start by assuming more than one.
1048 // currently the form does not pass in as an array & will be skipped
1049 // test is passing in as an array but I feel the api should have a metadata that allows
1050 // transform of single to array - seems good for managing transitions - in which case all api
1051 // calls that set price_set_id will hit this
1052 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1053 // all separated values, strings, json half-separated values (in participant we hit this)
1054 // to be converted to json @ api layer
1055 $pse = new CRM_Price_DAO_PriceSetEntity();
1056 $pse->entity_table
= 'civicrm_' . $entityName;
1057 $pse->entity_id
= $entity->id
;
1058 while ($pse->fetch()) {
1059 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1060 // note an even more aggressive form of this deletion currently happens in event form
1061 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1062 // on the participant record
1063 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1064 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1068 foreach ($params['price_set_id'] as $priceSetID) {
1069 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1070 //@todo - how should we do this - copied from form
1071 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1072 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1073 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1079 * Get field ids of a price set.
1085 * Array of the field ids
1088 public static function getFieldIds($id) {
1089 $priceField = new CRM_Price_DAO_PriceField();
1090 $priceField->price_set_id
= $id;
1091 $priceField->find();
1092 while ($priceField->fetch()) {
1093 $var[] = $priceField->id
;
1099 * Copy a price set, including all the fields
1102 * The price set id to copy.
1104 * @return CRM_Price_DAO_PriceSet
1106 public 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));
1112 'title' => ' ' . $title,
1113 'name' => '__Copy_id_' . ($maxId +
1) . '_',
1117 $copy = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1123 //copying all the blocks pertaining to the price set
1124 $copyPriceField = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1125 array('price_set_id' => $id),
1126 array('price_set_id' => $copy->id
)
1128 if (!empty($copyPriceField)) {
1129 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1131 //copy option group and values
1132 foreach ($price as $originalId => $copyId) {
1133 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1134 array('price_field_id' => $originalId),
1135 array('price_field_id' => $copyId)
1141 CRM_Utils_Hook
::copy('Set', $copy);
1146 * check price set permission.
1153 public static function checkPermission($sid) {
1154 if ($sid && self
::eventPriceSetDomainID()) {
1155 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1156 if (CRM_Core_Config
::domainID() != $domain_id) {
1157 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1164 * Get the sum of participant count
1165 * for all fields of given price set.
1170 * @param bool $onlyActive
1172 * @return int|null|string
1174 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1182 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1185 static $pricesetFieldCount = array();
1186 if (!isset($pricesetFieldCount[$sid])) {
1188 SELECT sum(value.count) as totalCount
1189 FROM civicrm_price_field_value value
1190 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1191 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1195 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1196 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1199 return $pricesetFieldCount[$sid];
1207 public static function getMembershipCount($ids) {
1209 SELECT count( pfv.id ) AS count, pfv.id AS id
1210 FROM civicrm_price_field_value pfv
1211 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1212 WHERE pfv.id IN ( $ids )
1213 GROUP BY mt.member_of_contact_id";
1215 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1218 while ($crmDAO->fetch()) {
1219 $count[$crmDAO->id
] = $crmDAO->count
;
1226 * Check if auto renew option should be shown.
1228 * @param int $priceSetId
1232 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1234 public static function checkAutoRenewForPriceSet($priceSetId) {
1235 // auto-renew option should be visible if membership types associated with all the fields has
1236 // been set for auto-renew option
1237 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1239 // get the membership type auto renew option and check if required or optional
1240 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1241 FROM civicrm_price_field_value pfv
1242 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1243 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1244 WHERE pf.price_set_id = %1
1245 AND pf.is_active = 1
1246 AND pfv.is_active = 1';
1248 $params = array(1 => array($priceSetId, 'Integer'));
1250 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1251 $autoRenewOption = 2;
1252 $interval = $unit = array();
1253 while ($dao->fetch()) {
1254 if (!$dao->auto_renew
) {
1255 $autoRenewOption = 0;
1258 if ($dao->auto_renew
== 1) {
1259 $autoRenewOption = 1;
1262 $interval[$dao->duration_interval
] = $dao->duration_interval
;
1263 $unit[$dao->duration_unit
] = $dao->duration_unit
;
1266 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1267 return $autoRenewOption;
1275 * Retrieve auto renew frequency and interval.
1277 * @param int $priceSetId
1281 * associate array of frequency interval and unit
1283 public static function getRecurDetails($priceSetId) {
1284 $query = 'SELECT mt.duration_interval, mt.duration_unit
1285 FROM civicrm_price_field_value pfv
1286 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1287 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1288 WHERE pf.price_set_id = %1 LIMIT 1';
1290 $params = array(1 => array($priceSetId, 'Integer'));
1291 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1293 return array($dao->duration_interval
, $dao->duration_unit
);
1299 public static function eventPriceSetDomainID() {
1300 return CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MULTISITE_PREFERENCES_NAME
,
1301 'event_price_set_domain_id',
1307 * Update the is_quick_config flag in the db.
1310 * Id of the database record.
1311 * @param bool $isQuickConfig we want to set the is_quick_config field.
1312 * Value we want to set the is_quick_config field.
1315 * DAO object on sucess, null otherwise
1317 public static function setIsQuickConfig($id, $isQuickConfig) {
1318 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1322 * Check if price set id provides option for
1323 * user to select both auto-renew and non-auto-renew memberships
1326 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 * @param string $baoName
1364 * Old event/contribution page id.
1366 * Newly created event/contribution page id.
1368 public static function copyPriceSet($baoName, $id, $newId) {
1369 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1371 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1372 if ($isQuickConfig) {
1373 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1374 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1377 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1380 'entity_table' => $baoName,
1382 array('entity_id' => $newId)
1385 // copy event discount
1386 if ($baoName == 'civicrm_event') {
1387 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1388 foreach ($discount as $discountId => $setId) {
1390 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1392 CRM_Core_DAO
::copyGeneric(
1393 'CRM_Core_DAO_Discount',
1395 'id' => $discountId,
1398 'entity_id' => $newId,
1399 'price_set_id' => $copyPriceSet->id
,
1408 * Function to set tax_amount and tax_rate in LineItem.
1410 * @param array $field
1411 * @param array $lineItem
1412 * @param int $optionValueId
1416 public static function setLineItem($field, $lineItem, $optionValueId) {
1417 if ($field['html_type'] == 'Text') {
1418 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1421 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1423 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1424 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1425 $lineItem[$optionValueId]['tax_rate'] = $taxRate;