3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Business object for managing price sets.
22 class CRM_Price_BAO_PriceSet
extends CRM_Price_DAO_PriceSet
{
25 * Static field for default price set details.
29 public static $_defaultPriceSet = NULL;
32 * Takes an associative array and creates a price set object.
34 * @param array $params
35 * (reference) an assoc array of name/value pairs.
37 * @return CRM_Price_DAO_PriceSet
39 public static function create(&$params) {
40 $hook = empty($params['id']) ?
'create' : 'edit';
41 CRM_Utils_Hook
::pre($hook, 'PriceSet', CRM_Utils_Array
::value('id', $params), $params);
43 if (empty($params['id']) && empty($params['name'])) {
44 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
47 $validatePriceSet = TRUE;
48 if (!empty($params['extends']) && is_array($params['extends'])) {
49 if (!array_key_exists(CRM_Core_Component
::getComponentID('CiviEvent'), $params['extends'])
50 ||
!array_key_exists(CRM_Core_Component
::getComponentID('CiviMember'), $params['extends'])
52 $validatePriceSet = FALSE;
54 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
57 $priceSetID = $params['id'] ??
NULL;
59 $priceSetBAO = new CRM_Price_BAO_PriceSet();
60 $priceSetBAO->copyValues($params);
61 if (self
::eventPriceSetDomainID()) {
62 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
66 CRM_Utils_Hook
::post($hook, 'PriceSet', $priceSetBAO->id
, $priceSetBAO);
67 unset(\Civi
::$statics['CRM_Core_PseudoConstant']);
72 * Fetch object based on array of properties.
74 * @param array $params
75 * (reference ) an assoc array of name/value pairs.
76 * @param array $defaults
77 * (reference ) an assoc array to hold the flattened values.
79 * @return CRM_Price_DAO_PriceSet
81 public static function retrieve(&$params, &$defaults) {
82 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
86 * Update the is_active flag in the db.
89 * Id of the database record.
93 * true if we found and updated the object, else false
95 public static function setIsActive($id, $isActive) {
96 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
100 * Calculate the default price set id
101 * assigned to the contribution/membership etc
103 * @param string $entity
109 public static function getDefaultPriceSet($entity = 'contribution') {
110 if (isset(\Civi
::$statics[__CLASS__
][$entity])) {
111 return \Civi
::$statics[__CLASS__
][$entity];
113 $priceSetName = ($entity === 'membership') ?
'default_membership_type_amount' : 'default_contribution_amount';
116 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
117 FROM civicrm_price_set ps
118 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
119 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
120 WHERE ps.name = '{$priceSetName}'
123 $dao = CRM_Core_DAO
::executeQuery($sql);
124 while ($dao->fetch()) {
125 \Civi
::$statics[__CLASS__
][$entity][$dao->priceFieldValueID
] = [
126 'setID' => $dao->setID
,
127 'priceFieldID' => $dao->priceFieldID
,
128 'name' => $dao->name
,
129 'label' => $dao->label
,
130 'priceFieldValueID' => $dao->priceFieldValueID
,
131 'membership_type_id' => $dao->membership_type_id
,
132 'amount' => $dao->amount
,
133 'financial_type_id' => $dao->financial_type_id
,
137 return \Civi
::$statics[__CLASS__
][$entity];
141 * Get the price set title.
150 public static function getTitle($id) {
151 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
155 * Return a list of all forms which use this price set.
159 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
163 public static function getUsedBy($id, $simpleReturn = FALSE) {
165 $forms = self
::getFormsUsingPriceSet($id);
166 $tables = array_keys($forms);
167 // @todo - this is really clumsy overloading the signature like this. Instead
168 // move towards having a function that does not call reformatUsedByFormsWithEntityData
169 // and call that when that data is not used.
170 if ($simpleReturn == 'table') {
173 // @todo - this is painfully slow in some cases.
176 SELECT cli.entity_table, cli.entity_id
177 FROM civicrm_line_item cli
178 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
179 WHERE cpf.price_set_id = %1";
180 $params = [1 => [$id, 'Integer']];
181 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
182 while ($crmFormDAO->fetch()) {
183 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
184 $tables[] = $crmFormDAO->entity_table
;
190 // @todo - this is really clumsy overloading the signature like this. See above.
191 if ($simpleReturn == 'entity') {
194 $usedBy = self
::reformatUsedByFormsWithEntityData($forms, $usedBy);
200 * Delete the price set, including the fields.
206 * false if fields exist for this set, true if the
207 * set could be deleted
210 public static function deleteSet($id) {
211 // delete price fields
212 $priceField = new CRM_Price_DAO_PriceField();
213 $priceField->price_set_id
= $id;
215 while ($priceField->fetch()) {
216 // delete options first
217 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
220 $set = new CRM_Price_DAO_PriceSet();
222 return $set->delete();
226 * Link the price set with the specified table and id.
228 * @param string $entityTable
229 * @param int $entityId
230 * @param int $priceSetId
234 public static function addTo($entityTable, $entityId, $priceSetId) {
235 // verify that the price set exists
236 $dao = new CRM_Price_DAO_PriceSet();
237 $dao->id
= $priceSetId;
243 $dao = new CRM_Price_DAO_PriceSetEntity();
244 // find if this already exists
245 $dao->entity_id
= $entityId;
246 $dao->entity_table
= $entityTable;
249 // add or update price_set_id
250 $dao->price_set_id
= $priceSetId;
255 * Delete price set for the given entity and id.
257 * @param string $entityTable
258 * @param int $entityId
262 public static function removeFrom($entityTable, $entityId) {
263 $dao = new CRM_Price_DAO_PriceSetEntity();
264 $dao->entity_table
= $entityTable;
265 $dao->entity_id
= $entityId;
266 return $dao->delete();
270 * Find a price_set_id associated with the given table, id and usedFor
271 * Used For value for events:1, contribution:2, membership:3
273 * @param string $entityTable
274 * @param int $entityId
275 * @param int $usedFor
276 * ( price set that extends/used for particular component ).
278 * @param null $isQuickConfig
279 * @param null $setName
282 * price_set_id, or false if none found
284 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
285 if (!$entityTable ||
!$entityId) {
289 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
290 FROM civicrm_price_set ps
291 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
292 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
293 if ($isQuickConfig) {
294 $sql .= ' AND ps.is_quick_config = 0 ';
297 1 => [$entityTable, 'String'],
298 2 => [$entityId, 'Integer'],
301 $sql .= " AND ps.extends LIKE '%%3%' ";
302 $params[3] = [$usedFor, 'Integer'];
305 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
307 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
308 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
312 * Find a price_set_id associated with the given option value or field ID.
314 * @param array $params
315 * (reference) an assoc array of name/value pairs.
316 * array may contain either option id or
320 * price set id on success, null otherwise
322 public static function getSetId(&$params) {
325 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
326 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
327 $fieldValue->id
= $oid;
328 if ($fieldValue->find(TRUE)) {
329 $fid = $fieldValue->price_field_id
;
333 $fid = $params['fid'] ??
NULL;
337 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
344 * Return an associative array of all price sets.
346 * @param bool $withInactive
347 * Whether or not to include inactive entries.
348 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
349 * @param string $column name of the column.
352 * associative array of id => name
354 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
357 DISTINCT ( price_set_id ) as id, s.{$column}
360 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
361 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
363 is_quick_config = 0 ";
365 if (!$withInactive) {
366 $query .= ' AND s.is_active = 1 ';
369 if (self
::eventPriceSetDomainID()) {
370 $query .= ' AND s.domain_id = ' . CRM_Core_Config
::domainID();
375 if ($extendComponentName) {
376 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
380 $query .= " AND s.extends LIKE '%$componentId%' ";
382 // Check permissioned financial types
383 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialType, CRM_Core_Action
::ADD
);
384 if ($financialType) {
385 $types = implode(',', array_keys($financialType));
386 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
389 // Do not display any price sets
392 $query .= " GROUP BY s.id";
393 $dao = CRM_Core_DAO
::executeQuery($query);
394 while ($dao->fetch()) {
395 $priceSets[$dao->id
] = $dao->$column;
401 * Get price set details.
403 * An array containing price set details (including price fields) is returned
407 * @param bool $required
408 * Appears to have no effect based on reading the code.
409 * @param bool $doNotIncludeExpiredFields
410 * Should only fields where today's date falls within the valid range be returned?
413 * Array consisting of field details
415 public static function getSetDetail($setID, $required = TRUE, $doNotIncludeExpiredFields = FALSE) {
428 'is_display_amounts',
437 if ($required == TRUE) {
438 $priceFields[] = 'is_required';
442 $select = 'SELECT ' . implode(',', $priceFields);
443 $from = ' FROM civicrm_price_field';
446 1 => [$setID, 'Integer'],
448 $currentTime = date('YmdHis');
450 WHERE price_set_id = %1
454 if ($doNotIncludeExpiredFields) {
456 AND ( active_on IS NULL OR active_on <= {$currentTime} )
457 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
461 $orderBy = ' ORDER BY weight';
463 $sql = $select . $from . $where . $dateSelect . $orderBy;
465 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
467 $isDefaultContributionPriceSet = FALSE;
468 if ('default_contribution_amount' == CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
469 $isDefaultContributionPriceSet = TRUE;
472 $visibility = CRM_Core_PseudoConstant
::visibility('name');
473 while ($dao->fetch()) {
476 $setTree[$setID]['fields'][$fieldID] = [];
477 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
479 foreach ($priceFields as $field) {
480 if ($field == 'id' ||
is_null($dao->$field)) {
484 if ($field == 'visibility_id') {
485 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
487 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
489 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
492 // also get the pre and post help from this price set
494 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
495 FROM civicrm_price_set
497 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
499 $setTree[$setID]['extends'] = $dao->extends;
500 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
501 $setTree[$setID]['help_pre'] = $dao->help_pre
;
502 $setTree[$setID]['help_post'] = $dao->help_post
;
503 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
504 $setTree[$setID]['min_amount'] = $dao->min_amount
;
510 * Get the Price Field ID.
512 * We call this function when more than one being present would represent an error
513 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
514 * @param array $priceSet
516 * @throws CRM_Core_Exception
519 public static function getOnlyPriceFieldID(array $priceSet) {
520 if (count($priceSet['fields']) > 1) {
521 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
523 return (int) implode('_', array_keys($priceSet['fields']));
527 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
528 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
529 * @param array $priceSet
531 * @throws CRM_Core_Exception
534 public static function getOnlyPriceFieldValueID(array $priceSet) {
535 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
536 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
537 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
539 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
543 * Initiate price set such that various non-BAO things are set on the form.
545 * This function is not really a BAO function so the location is misleading.
547 * @param CRM_Core_Form $form
549 * @param string $entityTable
550 * @param bool $doNotIncludeExpiredFields
551 * @param int $priceSetId
554 public static function initSet(&$form, $entityTable = 'civicrm_event', $doNotIncludeExpiredFields = FALSE, $priceSetId = NULL) {
556 //check if price set is is_config
557 if (is_numeric($priceSetId)) {
558 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
559 $form->assign('quickConfig', 1);
564 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
565 $entityId = $entity = NULL;
567 switch ($entityTable) {
568 case 'civicrm_event':
569 $entity = 'participant';
570 if (in_array(CRM_Utils_System
::getClassName($form), ['CRM_Event_Form_Participant', 'CRM_Event_Form_Task_Register'])) {
571 $entityId = $form->_id
;
574 $entityId = $form->_participantId
;
578 case 'civicrm_contribution_page':
579 case 'civicrm_contribution':
580 $entity = 'contribution';
581 $entityId = $form->_id
;
585 if ($entityId && $entity) {
586 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
594 $form->_priceSetId
= $priceSetId;
595 $priceSet = self
::getSetDetail($priceSetId, $required, $doNotIncludeExpiredFields);
596 $form->_priceSet
= $priceSet[$priceSetId] ??
NULL;
597 $form->_values
['fee'] = $form->_priceSet
['fields'] ??
NULL;
599 //get the price set fields participant count.
600 if ($entityTable == 'civicrm_event') {
601 //get option count info.
602 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
603 if ($form->_priceSet
['optionsCountTotal']) {
604 $optionsCountDetails = [];
605 if (!empty($form->_priceSet
['fields'])) {
606 foreach ($form->_priceSet
['fields'] as $field) {
607 foreach ($field['options'] as $option) {
608 $count = CRM_Utils_Array
::value('count', $option, 0);
609 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
613 $form->_priceSet
['optionsCountDetails'] = $optionsCountDetails;
616 //get option max value info.
617 $optionsMaxValueTotal = 0;
618 $optionsMaxValueDetails = [];
620 if (!empty($form->_priceSet
['fields'])) {
621 foreach ($form->_priceSet
['fields'] as $field) {
622 foreach ($field['options'] as $option) {
623 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
624 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
625 $optionsMaxValueTotal +
= $maxVal;
630 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
631 if ($optionsMaxValueTotal) {
632 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
635 $form->set('priceSetId', $form->_priceSetId
);
636 $form->set('priceSet', $form->_priceSet
);
641 * Get line item purchase information.
643 * This function takes the input parameters and interprets out of it what has been purchased.
646 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
647 * And, it would make sense to introduce caching into that function and call it from here rather than
648 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
649 * @param array $params
650 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
652 * Line item array to be altered.
653 * @param int $priceSetID
655 * @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
656 * don't specifically need it & find a better way where we do.
658 public static function processAmount($fields, &$params, &$lineItem, $priceSetID = NULL) {
660 $totalPrice = $totalTax = 0;
661 foreach ($fields as $id => $field) {
662 if (empty($params["price_{$id}"]) ||
663 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
665 // skip if nothing was submitted for this field
669 [$params, $lineItem] = self
::getLine($params, $lineItem, $priceSetID, $field, $id);
673 $totalParticipant = 0;
674 if (is_array($lineItem)) {
675 foreach ($lineItem as $values) {
676 $totalPrice +
= $values['line_total'] +
$values['tax_amount'];
677 $totalTax +
= $values['tax_amount'];
678 $totalParticipant +
= $values['participant_count'];
679 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
680 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
683 // However, because the quick config concept existed all sorts of logic was hung off it
684 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
685 // is always set at the functional level. In this case we are dealing with the default 'quick config'
686 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
687 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
690 // But, in the interests of being careful when capacity is low - avoiding the known default value
692 // Crucially a test has been added so a better solution can be implemented later with some comfort.
693 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
694 if ($values['label'] !== ts('Contribution Amount')) {
695 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
700 $displayParticipantCount = '';
701 if ($totalParticipant > 0) {
702 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
704 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
705 if (!empty($amount_level)) {
706 $params['amount_level'] = CRM_Utils_Array
::implodePadded($amount_level);
707 if (!empty($displayParticipantCount)) {
708 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
712 $params['amount'] = $totalPrice;
713 $params['tax_amount'] = $totalTax;
717 * Get the text to record for amount level.
719 * @param array $params
720 * Submitted parameters
721 * - priceSetId is required to be set in the calling function
722 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
723 * default one & this function asks that be set if it is the case).
726 * Text for civicrm_contribution.amount_level field.
728 public static function getAmountLevelText($params) {
729 $priceSetID = $params['priceSetId'];
730 $priceFieldSelection = self
::filterPriceFieldsFromParams($priceSetID, $params);
731 $priceFieldMetadata = self
::getCachedPriceSetDetail($priceSetID);
732 $displayParticipantCount = NULL;
735 foreach ($priceFieldMetadata['fields'] as $field) {
736 if (!empty($priceFieldSelection[$field['id']])) {
738 if ($field['is_enter_qty']) {
739 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
741 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
742 // ie. it represents the default price field for a contribution. Another approach would be not
743 // to give it a label if we don't want it to show.
744 if ($field['label'] !== ts('Contribution Amount')) {
745 $amount_level[] = $field['label'] . $qtyString;
749 return CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
753 * Get the fields relevant to the price field from the parameters.
755 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
757 * @param int $priceSetID
758 * @param array $params
761 * Price fields found in the params array
763 public static function filterPriceFieldsFromParams($priceSetID, $params) {
764 $priceSet = self
::getCachedPriceSetDetail($priceSetID);
766 foreach ($priceSet['fields'] as $field) {
767 if (!empty($params['price_' . $field['id']])) {
768 $return[$field['id']] = $params['price_' . $field['id']];
775 * Wrapper for getSetDetail with caching.
777 * We seem to be passing this array around in a painful way - presumably to avoid the hit
778 * of loading it - so lets make it callable with caching.
780 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
781 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
782 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
783 * think less about the price sets.
785 * @param int $priceSetID
789 public static function getCachedPriceSetDetail($priceSetID) {
790 $cacheKey = __CLASS__
. __FUNCTION__
. '_' . $priceSetID;
791 $cache = CRM_Utils_Cache
::singleton();
792 $values = $cache->get($cacheKey);
793 if (empty($values)) {
794 $data = self
::getSetDetail($priceSetID);
795 $values = $data[$priceSetID];
796 $cache->set($cacheKey, $values);
802 * Build the price set form.
804 * @param CRM_Core_Form $form
808 public static function buildPriceSet(&$form) {
809 $priceSetId = $form->get('priceSetId');
814 $validFieldsOnly = TRUE;
815 $className = CRM_Utils_System
::getClassName($form);
816 if (in_array($className, [
817 'CRM_Contribute_Form_Contribution',
818 'CRM_Member_Form_Membership',
820 $validFieldsOnly = FALSE;
823 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
824 $form->_priceSet
= $priceSet[$priceSetId] ??
NULL;
825 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
826 $form->_quickConfig
= $quickConfig = 0;
827 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
831 $form->assign('quickConfig', $quickConfig);
832 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
833 $form->_quickConfig
= $quickConfig;
836 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
837 if (!empty($form->_membershipTypeValues
) && is_array($form->_membershipTypeValues
)) {
838 $autoRenewMembershipTypes = [];
839 foreach ($form->_membershipTypeValues
as $membershipTypeValue) {
840 if ($membershipTypeValue['auto_renew']) {
841 $autoRenewMembershipTypes[] = $membershipTypeValue['id'];
844 foreach ($form->_priceSet
['fields'] as $field) {
845 if (array_key_exists('options', $field) && is_array($field['options'])) {
846 foreach ($field['options'] as $option) {
847 if (!empty($option['membership_type_id'])) {
848 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
849 $form->_priceSet
['auto_renew_membership_field'] = $field['id'];
850 // Only one field can offer auto_renew memberships, so break here.
858 $form->_priceSet
['id'] = $form->_priceSet
['id'] ??
$priceSetId;
859 $form->assign('priceSet', $form->_priceSet
);
861 $component = 'contribution';
862 if ($className == 'CRM_Member_Form_Membership') {
863 $component = 'membership';
866 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
867 $feeBlock = &$form->_values
['fee'];
868 if (!empty($form->_useForMember
)) {
869 $component = 'membership';
873 $feeBlock = &$form->_priceSet
['fields'];
876 // Call the buildAmount hook.
877 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
879 self
::addPriceFieldsToForm($form, $feeBlock, $validFieldsOnly, $className, $validPriceFieldIds);
883 * Check the current Membership having end date null.
885 * @param array $options
887 * Probably actually contact ID.
891 public static function checkCurrentMembership(&$options, $userid) {
892 if (!$userid ||
empty($options)) {
895 static $_contact_memberships = [];
896 $checkLifetime = FALSE;
897 foreach ($options as $key => $value) {
898 if (!empty($value['membership_type_id'])) {
899 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
900 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
902 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
903 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
904 unset($options[$key]);
905 $checkLifetime = TRUE;
909 if ($checkLifetime) {
918 * Set daefult the price set fields.
920 * @param CRM_Core_Form $form
925 public static function setDefaultPriceSet(&$form, &$defaults) {
926 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
930 foreach ($form->_priceSet
['fields'] as $val) {
931 foreach ($val['options'] as $keys => $values) {
932 // build price field index which is passed via URL
933 // url format will be appended by "&price_5=11"
934 $priceFieldName = 'price_' . $values['price_field_id'];
935 $priceFieldValue = self
::getPriceFieldValueFromURL($form, $priceFieldName);
936 if (!empty($priceFieldValue)) {
937 self
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
938 // break here to prevent overwriting of default due to 'is_default'
939 // option configuration. The value sent via URL get's higher priority.
942 elseif ($values['is_default']) {
943 self
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
951 * Get the value of price field if passed via url
953 * @param string $priceFieldName
954 * @param string $priceFieldValue
955 * @param string $priceFieldType
956 * @param array $defaults
960 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
961 if ($priceFieldType == 'CheckBox') {
962 $defaults[$priceFieldName][$priceFieldValue] = 1;
965 $defaults[$priceFieldName] = $priceFieldValue;
970 * Get the value of price field if passed via url
972 * @param CRM_Core_Form $form
973 * @param string $priceFieldName
975 * @return mixed $priceFieldValue
977 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
978 $priceFieldValue = CRM_Utils_Request
::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
979 if (!empty($priceFieldValue)) {
980 return $priceFieldValue;
985 * Supports event create function by setting up required price sets, not tested but expect
986 * it will work for contribution page
987 * @param array $params
988 * As passed to api/bao create fn.
989 * @param CRM_Core_DAO $entity
990 * Object for given entity.
991 * @param string $entityName
992 * Name of entity - e.g event.
994 public static function setPriceSets(&$params, $entity, $entityName) {
995 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
998 // CRM-14069 note that we may as well start by assuming more than one.
999 // currently the form does not pass in as an array & will be skipped
1000 // test is passing in as an array but I feel the api should have a metadata that allows
1001 // transform of single to array - seems good for managing transitions - in which case all api
1002 // calls that set price_set_id will hit this
1003 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1004 // all separated values, strings, json half-separated values (in participant we hit this)
1005 // to be converted to json @ api layer
1006 $pse = new CRM_Price_DAO_PriceSetEntity();
1007 $pse->entity_table
= 'civicrm_' . $entityName;
1008 $pse->entity_id
= $entity->id
;
1009 while ($pse->fetch()) {
1010 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1011 // note an even more aggressive form of this deletion currently happens in event form
1012 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1013 // on the participant record
1014 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1015 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1019 foreach ($params['price_set_id'] as $priceSetID) {
1020 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1021 //@todo - how should we do this - copied from form
1022 //if (!empty($params['price_field_id'])) {
1023 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1024 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1030 * Get field ids of a price set.
1036 * Array of the field ids
1039 public static function getFieldIds($id) {
1040 $priceField = new CRM_Price_DAO_PriceField();
1041 $priceField->price_set_id
= $id;
1042 $priceField->find();
1043 while ($priceField->fetch()) {
1044 $var[] = $priceField->id
;
1050 * Copy a price set, including all the fields
1053 * The price set id to copy.
1055 * @return CRM_Price_DAO_PriceSet
1057 public static function copy($id) {
1058 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1059 $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
1061 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
1062 $title = ts('[Copy id %1]', [1 => $maxId +
1]);
1065 'title' => trim($newTitle) . ' ' . $title,
1066 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId +
1),
1070 $copy = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1076 //copying all the blocks pertaining to the price set
1077 $copyPriceField = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1078 ['price_set_id' => $id],
1079 ['price_set_id' => $copy->id
]
1081 if (!empty($copyPriceField)) {
1082 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1084 //copy option group and values
1085 foreach ($price as $originalId => $copyId) {
1086 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1087 ['price_field_id' => $originalId],
1088 ['price_field_id' => $copyId]
1094 CRM_Utils_Hook
::copy('Set', $copy);
1095 unset(\Civi
::$statics['CRM_Core_PseudoConstant']);
1100 * check price set permission.
1106 * @throws \CRM_Core_Exception
1108 public static function checkPermission($sid) {
1109 if ($sid && self
::eventPriceSetDomainID()) {
1110 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1111 if (CRM_Core_Config
::domainID() != $domain_id) {
1112 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
1119 * Get the sum of participant count
1120 * for all fields of given price set.
1125 * @param bool $onlyActive
1127 * @return int|null|string
1129 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1137 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1140 static $pricesetFieldCount = [];
1141 if (!isset($pricesetFieldCount[$sid])) {
1143 SELECT sum(value.count) as totalCount
1144 FROM civicrm_price_field_value value
1145 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1146 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1150 $count = CRM_Core_DAO
::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
1151 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1154 return $pricesetFieldCount[$sid];
1158 * Return a count of priceFieldValueIDs that are memberships by organisation and membership type
1160 * @param string $priceFieldValueIDs
1161 * Comma separated string of priceFieldValue IDs
1164 * Returns an array of counts by membership organisation
1166 public static function getMembershipCount($priceFieldValueIDs) {
1168 SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
1169 FROM civicrm_price_field_value pfv
1170 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1171 WHERE pfv.id IN ( $priceFieldValueIDs )
1172 GROUP BY mt.member_of_contact_id ";
1174 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1177 while ($crmDAO->fetch()) {
1178 $count[$crmDAO->id
] = $crmDAO->count
;
1185 * Check if auto renew option should be shown.
1187 * The auto-renew option should be visible if membership types associated with all the fields has
1188 * been set for auto-renew option.
1190 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1192 * @param int $priceSetId
1196 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1198 public static function checkAutoRenewForPriceSet($priceSetId) {
1199 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1200 pf.html_type, pf.id as price_field_id
1201 FROM civicrm_price_field_value pfv
1202 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1203 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1204 WHERE pf.price_set_id = %1
1205 AND pf.is_active = 1
1206 AND pfv.is_active = 1
1207 ORDER BY price_field_id';
1209 $params = [1 => [$priceSetId, 'Integer']];
1211 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1213 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1214 //If price set field is already present with auto-renew option then, it will restrict for adding another price set field with auto-renew option.
1219 $autoRenewOption = 2;
1221 while ($dao->fetch()) {
1222 if (!$dao->auto_renew
) {
1223 // If any one can't be renewed none can.
1226 if ($dao->auto_renew
== 1) {
1227 $autoRenewOption = 1;
1230 if ($dao->html_type
== 'Checkbox' && !in_array($dao->duration_interval
. $dao->duration_unit
, $priceFields[$dao->price_field_id
])) {
1231 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1232 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1235 $priceFields[$dao->price_field_id
][] = $dao->duration_interval
. $dao->duration_unit
;
1236 foreach ($priceFields as $priceFieldID => $durations) {
1237 if ($priceFieldID != $dao->price_field_id
&& !in_array($dao->duration_interval
. $dao->duration_unit
, $durations)) {
1238 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1244 return $autoRenewOption;
1248 * Retrieve auto renew frequency and interval.
1250 * @param int $priceSetId
1254 * associate array of frequency interval and unit
1256 public static function getRecurDetails($priceSetId) {
1257 $query = 'SELECT mt.duration_interval, mt.duration_unit
1258 FROM civicrm_price_field_value pfv
1259 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1260 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1261 WHERE pf.price_set_id = %1 LIMIT 1';
1263 $params = [1 => [$priceSetId, 'Integer']];
1264 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1266 return [$dao->duration_interval
, $dao->duration_unit
];
1272 public static function eventPriceSetDomainID() {
1273 return Civi
::settings()->get('event_price_set_domain_id');
1277 * Update the is_quick_config flag in the db.
1280 * Id of the database record.
1281 * @param bool $isQuickConfig we want to set the is_quick_config field.
1282 * Value we want to set the is_quick_config field.
1285 * true if we found and updated the object, else false
1287 public static function setIsQuickConfig($id, $isQuickConfig) {
1288 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1292 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1298 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1299 $membershipTypes = self
::getMembershipTypesFromPriceSet($id);
1300 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1307 * Get an array of the membership types in a price set.
1312 * Membership types in the price set
1314 public static function getMembershipTypesFromPriceSet($id) {
1316 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1317 FROM civicrm_price_field_value pfv
1318 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1319 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1320 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1324 $params = [1 => [$id, 'Integer']];
1325 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1327 $membershipTypes = [
1330 'autorenew_required' => [],
1331 'autorenew_optional' => [],
1333 while ($dao->fetch()) {
1334 if (empty($dao->membership_type_id
)) {
1337 $membershipTypes['all'][] = $dao->membership_type_id
;
1338 if (!empty($dao->auto_renew
)) {
1339 $membershipTypes['autorenew'][] = $dao->membership_type_id
;
1340 if ($dao->auto_renew
== 2) {
1341 $membershipTypes['autorenew_required'][] = $dao->membership_type_id
;
1344 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id
;
1348 $membershipTypes['non_renew'][] = $dao->membership_type_id
;
1351 return $membershipTypes;
1355 * Copy priceSet when event/contibution page is copied
1357 * @param string $baoName
1360 * Old event/contribution page id.
1362 * Newly created event/contribution page id.
1364 public static function copyPriceSet($baoName, $id, $newId) {
1365 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1367 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1368 if ($isQuickConfig) {
1369 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1370 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1373 $copyPriceSet = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1376 'entity_table' => $baoName,
1378 ['entity_id' => $newId]
1381 // copy event discount
1382 if ($baoName == 'civicrm_event') {
1383 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1384 foreach ($discount as $discountId => $setId) {
1386 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1388 CRM_Core_DAO
::copyGeneric(
1389 'CRM_Core_DAO_Discount',
1391 'id' => $discountId,
1394 'entity_id' => $newId,
1395 'price_set_id' => $copyPriceSet->id
,
1404 * Function to set tax_amount and tax_rate in LineItem.
1406 * @param array $field
1407 * @param array $lineItem
1408 * @param int $optionValueId
1409 * @param float $totalTax
1413 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
1414 // Here we round - i.e. after multiplying by quantity
1415 if ($field['html_type'] == 'Text') {
1416 $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
1419 $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
1421 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1422 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1423 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1424 $totalTax +
= $taxAmount;
1429 * Get the first price set value IDs from a parameters array.
1431 * In practice this is really used when we only expect one to exist.
1433 * @param array $params
1436 * Array of the ids of the price set values.
1438 public static function parseFirstPriceSetValueIDFromParams($params) {
1439 $priceSetValueIDs = self
::parsePriceSetValueIDsFromParams($params);
1440 return reset($priceSetValueIDs);
1444 * Get the price set value IDs from a set of parameters
1446 * @param array $params
1449 * Array of the ids of the price set values.
1451 public static function parsePriceSetValueIDsFromParams($params) {
1452 $priceSetParams = self
::parsePriceSetArrayFromParams($params);
1453 $priceSetValueIDs = [];
1454 foreach ($priceSetParams as $priceSetParam) {
1455 foreach (array_keys($priceSetParam) as $priceValueID) {
1456 $priceSetValueIDs[] = $priceValueID;
1459 return $priceSetValueIDs;
1463 * Get the price set value IDs from a set of parameters
1465 * @param array $params
1468 * Array of price fields filtered from the params.
1470 public static function parsePriceSetArrayFromParams($params) {
1471 $priceSetParams = [];
1472 foreach ($params as $field => $value) {
1473 $parts = explode('_', $field);
1474 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
1475 $priceSetParams[$field] = $value;
1478 return $priceSetParams;
1482 * Get non-deductible amount from price options
1484 * @param int $priceSetId
1485 * @param array $lineItem
1488 * calculated non-deductible amount.
1490 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1491 $nonDeductibleAmount = 0;
1492 if (!empty($lineItem[$priceSetId])) {
1493 foreach ($lineItem[$priceSetId] as $options) {
1494 $nonDeductibleAmount +
= $options['non_deductible_amount'] * $options['qty'];
1498 return $nonDeductibleAmount;
1502 * Get an array of all forms using a given price set.
1507 * Pages using the price set, keyed by type. e.g
1509 * 'civicrm_contribution_page' => array(2,5,6),
1510 * 'civicrm_event' => array(5,6),
1511 * 'civicrm_event_template' => array(7),
1514 public static function getFormsUsingPriceSet($id) {
1517 SELECT entity_table, entity_id
1518 FROM civicrm_price_set_entity
1519 WHERE price_set_id = %1";
1520 $params = [1 => [$id, 'Integer']];
1521 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1523 while ($crmFormDAO->fetch()) {
1524 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
1530 * @param array $forms
1531 * Array of forms that use a price set keyed by entity. e.g
1533 * 'civicrm_contribution_page' => array(2,5,6),
1534 * 'civicrm_event' => array(5,6),
1535 * 'civicrm_event_template' => array(7),
1539 * Array of entities suppliemented with per entity information.
1541 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1543 * @throws \Exception
1545 protected static function reformatUsedByFormsWithEntityData($forms) {
1547 foreach ($forms as $table => $entities) {
1549 case 'civicrm_event':
1550 $ids = implode(',', $entities);
1551 $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
1552 FROM civicrm_event ce
1553 LEFT JOIN civicrm_option_value ON
1554 ( ce.event_type_id = civicrm_option_value.value )
1555 LEFT JOIN civicrm_option_group ON
1556 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1558 civicrm_option_group.name = 'event_type' AND
1561 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1562 while ($crmDAO->fetch()) {
1563 if ($crmDAO->isTemplate
) {
1564 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
1565 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1566 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1569 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1570 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1571 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1572 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1573 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1578 case 'civicrm_contribution_page':
1579 $ids = implode(',', $entities);
1580 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1581 FROM civicrm_contribution_page cp, civicrm_financial_type ct
1582 WHERE ct.id = cp.financial_type_id AND
1585 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1586 while ($crmDAO->fetch()) {
1587 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1588 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
1589 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1590 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1594 case 'civicrm_contribution':
1595 case 'civicrm_membership':
1596 case 'civicrm_participant':
1597 $usedBy[$table] = 1;
1601 throw new CRM_Core_Exception("$table is not supported in PriceSet::usedBy()");
1609 * Get the relevant line item.
1611 * Note this is part of code being cleaned up / refactored & may change.
1613 * @param array $params
1614 * @param array $lineItem
1615 * @param int $priceSetID
1616 * @param array $field
1621 public static function getLine(&$params, &$lineItem, $priceSetID, $field, $id): array {
1623 switch ($field['html_type']) {
1625 $firstOption = reset($field['options']);
1626 $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
1627 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
1628 $optionValueId = key($field['options']);
1630 if (CRM_Utils_Array
::value('name', $field['options'][$optionValueId]) === 'contribution_amount') {
1631 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
1632 if (array_key_exists($params['financial_type_id'], $taxRates)) {
1633 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
1634 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
1635 $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
1638 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1639 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1644 //special case if user select -none-
1645 if ($params["price_{$id}"] <= 0) {
1648 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1649 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
1651 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
1652 // This is notably the case with memberships and we need to put this amount
1653 // on the line item rather than the calculated amount.
1654 // This seems to only affect radio link items as that is the use case for the 'quick config'
1655 // set up (which allows a free form field).
1656 // @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
1657 // don't specifically need it & find a better way where we do.
1658 $amount_override = NULL;
1660 if ($priceSetID && count(self
::filterPriceFieldsFromParams($priceSetID, $params)) === 1) {
1661 $amount_override = CRM_Utils_Array
::value('total_amount', $params);
1663 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, $amount_override);
1664 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1665 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1666 if ($amount_override) {
1667 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
1673 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1674 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
1676 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
1677 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1678 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1684 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
1685 foreach ($params["price_{$id}"] as $optionId => $option) {
1686 if (!empty($field['options'][$optionId]['tax_rate'])) {
1687 $lineItem = self
::setLineItem($field, $lineItem, $optionId, $totalTax);
1692 return [$params, $lineItem];
1696 * Add the relevant price fields to the form.
1698 * @param \CRM_Core_Form $form
1699 * @param array $feeBlock
1700 * @param bool $validFieldsOnly
1701 * @param string $className
1702 * @param array $validPriceFieldIds
1704 protected static function addPriceFieldsToForm(CRM_Core_Form
$form, $feeBlock, bool $validFieldsOnly, string $className, array $validPriceFieldIds) {
1705 $hideAdminValues = !CRM_Core_Permission
::check('edit contributions');
1706 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
1707 $adminFieldVisible = CRM_Core_Permission
::check('administer CiviCRM');
1708 foreach ($feeBlock as $id => $field) {
1709 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
1710 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
1713 $options = $field['options'] ??
NULL;
1714 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
1715 $userid = $form->getVar('_membershipContactID');
1716 $checklifetime = self
::checkCurrentMembership($options, $userid);
1717 if ($checklifetime) {
1718 $form->assign('ispricelifetime', TRUE);
1722 $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
1724 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
1727 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
1728 foreach ($options as $key => $currentOption) {
1729 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField
::getVisibilityOptionID('admin')) {
1730 unset($options[$key]);
1734 if (!empty($options)) {
1735 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
1736 'price_' . $field['id'],
1739 CRM_Utils_Array
::value('is_required', $field, FALSE),