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 * Retrieve DB object and copy to defaults array.
74 * @param array $params
75 * Array of criteria values.
76 * @param array $defaults
77 * Array to be populated with found values.
80 * The DAO object, if found.
84 public static function retrieve($params, &$defaults) {
85 return self
::commonRetrieve(self
::class, $params, $defaults);
89 * Update the is_active flag in the db.
92 * Id of the database record.
96 * true if we found and updated the object, else false
98 public static function setIsActive($id, $isActive) {
99 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
103 * Calculate the default price set id
104 * assigned to the contribution/membership etc
106 * @param string $entity
112 public static function getDefaultPriceSet($entity = 'contribution') {
113 if (isset(\Civi
::$statics[__CLASS__
][$entity])) {
114 return \Civi
::$statics[__CLASS__
][$entity];
116 $priceSetName = ($entity === 'membership') ?
'default_membership_type_amount' : 'default_contribution_amount';
119 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
120 FROM civicrm_price_set ps
121 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
122 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
123 WHERE ps.name = '{$priceSetName}'
126 $dao = CRM_Core_DAO
::executeQuery($sql);
127 while ($dao->fetch()) {
128 \Civi
::$statics[__CLASS__
][$entity][$dao->priceFieldValueID
] = [
129 'setID' => $dao->setID
,
130 'priceFieldID' => $dao->priceFieldID
,
131 'name' => $dao->name
,
132 'label' => $dao->label
,
133 'priceFieldValueID' => $dao->priceFieldValueID
,
134 'membership_type_id' => $dao->membership_type_id
,
135 'amount' => $dao->amount
,
136 'financial_type_id' => $dao->financial_type_id
,
140 return \Civi
::$statics[__CLASS__
][$entity];
144 * Get the price set title.
153 public static function getTitle($id) {
154 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
158 * Return a list of all forms which use this price set.
162 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
166 public static function getUsedBy($id, $simpleReturn = FALSE) {
168 $forms = self
::getFormsUsingPriceSet($id);
169 $tables = array_keys($forms);
170 // @todo - this is really clumsy overloading the signature like this. Instead
171 // move towards having a function that does not call reformatUsedByFormsWithEntityData
172 // and call that when that data is not used.
173 if ($simpleReturn == 'table') {
176 // @todo - this is painfully slow in some cases.
179 SELECT cli.entity_table, cli.entity_id
180 FROM civicrm_line_item cli
181 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
182 WHERE cpf.price_set_id = %1";
183 $params = [1 => [$id, 'Integer']];
184 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
185 while ($crmFormDAO->fetch()) {
186 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
187 $tables[] = $crmFormDAO->entity_table
;
193 // @todo - this is really clumsy overloading the signature like this. See above.
194 if ($simpleReturn == 'entity') {
197 $usedBy = self
::reformatUsedByFormsWithEntityData($forms, $usedBy);
203 * Delete the price set, including the fields.
209 * false if fields exist for this set, true if the
210 * set could be deleted
213 public static function deleteSet($id) {
214 // delete price fields
215 $priceField = new CRM_Price_DAO_PriceField();
216 $priceField->price_set_id
= $id;
218 while ($priceField->fetch()) {
219 // delete options first
220 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
223 $set = new CRM_Price_DAO_PriceSet();
225 return $set->delete();
229 * Link the price set with the specified table and id.
231 * @param string $entityTable
232 * @param int $entityId
233 * @param int $priceSetId
237 public static function addTo($entityTable, $entityId, $priceSetId) {
238 // verify that the price set exists
239 $dao = new CRM_Price_DAO_PriceSet();
240 $dao->id
= $priceSetId;
246 $dao = new CRM_Price_DAO_PriceSetEntity();
247 // find if this already exists
248 $dao->entity_id
= $entityId;
249 $dao->entity_table
= $entityTable;
252 // add or update price_set_id
253 $dao->price_set_id
= $priceSetId;
258 * Delete price set for the given entity and id.
260 * @param string $entityTable
261 * @param int $entityId
265 public static function removeFrom($entityTable, $entityId) {
266 $dao = new CRM_Price_DAO_PriceSetEntity();
267 $dao->entity_table
= $entityTable;
268 $dao->entity_id
= $entityId;
269 return $dao->delete();
273 * Find a price_set_id associated with the given table, id and usedFor
274 * Used For value for events:1, contribution:2, membership:3
276 * @param string $entityTable
277 * @param int $entityId
278 * @param int $usedFor
279 * ( price set that extends/used for particular component ).
281 * @param null $isQuickConfig
282 * @param null $setName
285 * price_set_id, or false if none found
287 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
288 if (!$entityTable ||
!$entityId) {
292 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
293 FROM civicrm_price_set ps
294 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
295 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
296 if ($isQuickConfig) {
297 $sql .= ' AND ps.is_quick_config = 0 ';
300 1 => [$entityTable, 'String'],
301 2 => [$entityId, 'Integer'],
304 $sql .= " AND ps.extends LIKE '%%3%' ";
305 $params[3] = [$usedFor, 'Integer'];
308 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
310 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
311 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
315 * Find a price_set_id associated with the given option value or field ID.
317 * @param array $params
318 * (reference) an assoc array of name/value pairs.
319 * array may contain either option id or
323 * price set id on success, null otherwise
325 public static function getSetId(&$params) {
328 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
329 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
330 $fieldValue->id
= $oid;
331 if ($fieldValue->find(TRUE)) {
332 $fid = $fieldValue->price_field_id
;
336 $fid = $params['fid'] ??
NULL;
340 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
347 * Return an associative array of all price sets.
349 * @param bool $withInactive
350 * Whether or not to include inactive entries.
351 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
352 * @param string $column name of the column.
355 * associative array of id => name
357 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
360 DISTINCT ( price_set_id ) as id, s.{$column}
363 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
364 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
366 is_quick_config = 0 ";
368 if (!$withInactive) {
369 $query .= ' AND s.is_active = 1 ';
372 if (self
::eventPriceSetDomainID()) {
373 $query .= ' AND s.domain_id = ' . CRM_Core_Config
::domainID();
378 if ($extendComponentName) {
379 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
383 $query .= " AND s.extends LIKE '%$componentId%' ";
385 // Check permissioned financial types
386 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialType, CRM_Core_Action
::ADD
);
387 if ($financialType) {
388 $types = implode(',', array_keys($financialType));
389 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
392 // Do not display any price sets
395 $query .= " GROUP BY s.id";
396 $dao = CRM_Core_DAO
::executeQuery($query);
397 while ($dao->fetch()) {
398 $priceSets[$dao->id
] = $dao->$column;
404 * Get price set details.
406 * An array containing price set details (including price fields) is returned
410 * @param bool $required
411 * Appears to have no effect based on reading the code.
412 * @param bool $doNotIncludeExpiredFields
413 * Should only fields where today's date falls within the valid range be returned?
416 * Array consisting of field details
418 public static function getSetDetail($setID, $required = TRUE, $doNotIncludeExpiredFields = FALSE) {
431 'is_display_amounts',
440 if ($required == TRUE) {
441 $priceFields[] = 'is_required';
445 $select = 'SELECT ' . implode(',', $priceFields);
446 $from = ' FROM civicrm_price_field';
449 1 => [$setID, 'Integer'],
451 $currentTime = date('YmdHis');
453 WHERE price_set_id = %1
457 if ($doNotIncludeExpiredFields) {
459 AND ( active_on IS NULL OR active_on <= {$currentTime} )
460 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
464 $orderBy = ' ORDER BY weight';
466 $sql = $select . $from . $where . $dateSelect . $orderBy;
468 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
470 $isDefaultContributionPriceSet = FALSE;
471 if ('default_contribution_amount' == CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
472 $isDefaultContributionPriceSet = TRUE;
475 $visibility = CRM_Core_PseudoConstant
::visibility('name');
476 while ($dao->fetch()) {
479 $setTree[$setID]['fields'][$fieldID] = [];
480 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
482 foreach ($priceFields as $field) {
483 if ($field == 'id' ||
is_null($dao->$field)) {
487 if ($field == 'visibility_id') {
488 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
490 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
492 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
495 // also get the pre and post help from this price set
497 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
498 FROM civicrm_price_set
500 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
502 $setTree[$setID]['extends'] = $dao->extends;
503 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
504 $setTree[$setID]['help_pre'] = $dao->help_pre
;
505 $setTree[$setID]['help_post'] = $dao->help_post
;
506 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
507 $setTree[$setID]['min_amount'] = $dao->min_amount
;
513 * Get the Price Field ID.
515 * We call this function when more than one being present would represent an error
516 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
517 * @param array $priceSet
519 * @throws CRM_Core_Exception
522 public static function getOnlyPriceFieldID(array $priceSet) {
523 if (count($priceSet['fields']) > 1) {
524 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
526 return (int) implode('_', array_keys($priceSet['fields']));
530 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
531 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
532 * @param array $priceSet
534 * @throws CRM_Core_Exception
537 public static function getOnlyPriceFieldValueID(array $priceSet) {
538 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
539 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
540 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
542 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
546 * Initiate price set such that various non-BAO things are set on the form.
548 * This function is not really a BAO function so the location is misleading.
550 * @param CRM_Core_Form $form
552 * @param string $entityTable
553 * @param bool $doNotIncludeExpiredFields
554 * @param int $priceSetId
557 public static function initSet(&$form, $entityTable = 'civicrm_event', $doNotIncludeExpiredFields = FALSE, $priceSetId = NULL) {
559 //check if price set is is_config
560 if (is_numeric($priceSetId)) {
561 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
562 $form->assign('quickConfig', 1);
567 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
568 $entityId = $entity = NULL;
570 switch ($entityTable) {
571 case 'civicrm_event':
572 $entity = 'participant';
573 if (in_array(CRM_Utils_System
::getClassName($form), ['CRM_Event_Form_Participant', 'CRM_Event_Form_Task_Register'])) {
574 $entityId = $form->_id
;
577 $entityId = $form->_participantId
;
581 case 'civicrm_contribution_page':
582 case 'civicrm_contribution':
583 $entity = 'contribution';
584 $entityId = $form->_id
;
588 if ($entityId && $entity) {
589 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
597 $form->_priceSetId
= $priceSetId;
598 $priceSet = self
::getSetDetail($priceSetId, $required, $doNotIncludeExpiredFields);
599 $form->_priceSet
= $priceSet[$priceSetId] ??
NULL;
600 $form->_values
['fee'] = $form->_priceSet
['fields'] ??
NULL;
602 //get the price set fields participant count.
603 if ($entityTable == 'civicrm_event') {
604 //get option count info.
605 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
606 if ($form->_priceSet
['optionsCountTotal']) {
607 $optionsCountDetails = [];
608 if (!empty($form->_priceSet
['fields'])) {
609 foreach ($form->_priceSet
['fields'] as $field) {
610 foreach ($field['options'] as $option) {
611 $count = CRM_Utils_Array
::value('count', $option, 0);
612 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
616 $form->_priceSet
['optionsCountDetails'] = $optionsCountDetails;
619 //get option max value info.
620 $optionsMaxValueTotal = 0;
621 $optionsMaxValueDetails = [];
623 if (!empty($form->_priceSet
['fields'])) {
624 foreach ($form->_priceSet
['fields'] as $field) {
625 foreach ($field['options'] as $option) {
626 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
627 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
628 $optionsMaxValueTotal +
= $maxVal;
633 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
634 if ($optionsMaxValueTotal) {
635 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
638 $form->set('priceSetId', $form->_priceSetId
);
639 $form->set('priceSet', $form->_priceSet
);
644 * Get line item purchase information.
646 * This function takes the input parameters and interprets out of it what has been purchased.
649 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
650 * And, it would make sense to introduce caching into that function and call it from here rather than
651 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
652 * @param array $params
653 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
655 * Line item array to be altered.
656 * @param int $priceSetID
658 * @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
659 * don't specifically need it & find a better way where we do.
661 public static function processAmount($fields, &$params, &$lineItem, $priceSetID = NULL) {
663 $totalPrice = $totalTax = 0;
664 foreach ($fields as $id => $field) {
665 if (empty($params["price_{$id}"]) ||
666 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
668 // skip if nothing was submitted for this field
672 [$params, $lineItem] = self
::getLine($params, $lineItem, $priceSetID, $field, $id);
676 $totalParticipant = 0;
677 if (is_array($lineItem)) {
678 foreach ($lineItem as $values) {
679 $totalPrice +
= $values['line_total'] +
$values['tax_amount'];
680 $totalTax +
= $values['tax_amount'];
681 $totalParticipant +
= $values['participant_count'];
682 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
683 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
686 // However, because the quick config concept existed all sorts of logic was hung off it
687 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
688 // is always set at the functional level. In this case we are dealing with the default 'quick config'
689 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
690 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
693 // But, in the interests of being careful when capacity is low - avoiding the known default value
695 // Crucially a test has been added so a better solution can be implemented later with some comfort.
696 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
697 if ($values['label'] !== ts('Contribution Amount')) {
698 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
703 $displayParticipantCount = '';
704 if ($totalParticipant > 0) {
705 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
707 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
708 if (!empty($amount_level)) {
709 $params['amount_level'] = CRM_Utils_Array
::implodePadded($amount_level);
710 if (!empty($displayParticipantCount)) {
711 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
715 $params['amount'] = $totalPrice;
716 $params['tax_amount'] = $totalTax;
720 * Get the text to record for amount level.
722 * @param array $params
723 * Submitted parameters
724 * - priceSetId is required to be set in the calling function
725 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
726 * default one & this function asks that be set if it is the case).
729 * Text for civicrm_contribution.amount_level field.
731 public static function getAmountLevelText($params) {
732 $priceSetID = $params['priceSetId'];
733 $priceFieldSelection = self
::filterPriceFieldsFromParams($priceSetID, $params);
734 $priceFieldMetadata = self
::getCachedPriceSetDetail($priceSetID);
735 $displayParticipantCount = NULL;
738 foreach ($priceFieldMetadata['fields'] as $field) {
739 if (!empty($priceFieldSelection[$field['id']])) {
741 if ($field['is_enter_qty']) {
742 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
744 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
745 // ie. it represents the default price field for a contribution. Another approach would be not
746 // to give it a label if we don't want it to show.
747 if ($field['label'] !== ts('Contribution Amount')) {
748 $amount_level[] = $field['label'] . $qtyString;
752 return CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
756 * Get the fields relevant to the price field from the parameters.
758 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
760 * @param int $priceSetID
761 * @param array $params
764 * Price fields found in the params array
766 public static function filterPriceFieldsFromParams($priceSetID, $params) {
767 $priceSet = self
::getCachedPriceSetDetail($priceSetID);
769 foreach ($priceSet['fields'] as $field) {
770 if (!empty($params['price_' . $field['id']])) {
771 $return[$field['id']] = $params['price_' . $field['id']];
778 * Wrapper for getSetDetail with caching.
780 * We seem to be passing this array around in a painful way - presumably to avoid the hit
781 * of loading it - so lets make it callable with caching.
783 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
784 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
785 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
786 * think less about the price sets.
788 * @param int $priceSetID
792 public static function getCachedPriceSetDetail($priceSetID) {
793 $cacheKey = __CLASS__
. __FUNCTION__
. '_' . $priceSetID;
794 $cache = CRM_Utils_Cache
::singleton();
795 $values = $cache->get($cacheKey);
796 if (empty($values)) {
797 $data = self
::getSetDetail($priceSetID);
798 $values = $data[$priceSetID];
799 $cache->set($cacheKey, $values);
805 * Build the price set form.
807 * @param CRM_Core_Form $form
811 public static function buildPriceSet(&$form) {
812 $priceSetId = $form->get('priceSetId');
817 $validFieldsOnly = TRUE;
818 $className = CRM_Utils_System
::getClassName($form);
819 if (in_array($className, [
820 'CRM_Contribute_Form_Contribution',
821 'CRM_Member_Form_Membership',
823 $validFieldsOnly = FALSE;
826 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
827 $form->_priceSet
= $priceSet[$priceSetId] ??
NULL;
828 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
829 $form->_quickConfig
= $quickConfig = 0;
830 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
834 $form->assign('quickConfig', $quickConfig);
835 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
836 $form->_quickConfig
= $quickConfig;
839 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
840 if (!empty($form->_membershipTypeValues
) && is_array($form->_membershipTypeValues
)) {
841 $autoRenewMembershipTypes = [];
842 foreach ($form->_membershipTypeValues
as $membershipTypeValue) {
843 if ($membershipTypeValue['auto_renew']) {
844 $autoRenewMembershipTypes[] = $membershipTypeValue['id'];
847 foreach ($form->_priceSet
['fields'] as $field) {
848 if (array_key_exists('options', $field) && is_array($field['options'])) {
849 foreach ($field['options'] as $option) {
850 if (!empty($option['membership_type_id'])) {
851 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
852 $form->_priceSet
['auto_renew_membership_field'] = $field['id'];
853 // Only one field can offer auto_renew memberships, so break here.
861 $form->_priceSet
['id'] = $form->_priceSet
['id'] ??
$priceSetId;
862 $form->assign('priceSet', $form->_priceSet
);
864 $component = 'contribution';
865 if ($className == 'CRM_Member_Form_Membership') {
866 $component = 'membership';
869 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
870 $feeBlock = &$form->_values
['fee'];
871 if (!empty($form->_useForMember
)) {
872 $component = 'membership';
876 $feeBlock = &$form->_priceSet
['fields'];
879 // Call the buildAmount hook.
880 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
882 self
::addPriceFieldsToForm($form, $feeBlock, $validFieldsOnly, $className, $validPriceFieldIds);
886 * Check the current Membership having end date null.
888 * @param array $options
890 * Probably actually contact ID.
894 public static function checkCurrentMembership(&$options, $userid) {
895 if (!$userid ||
empty($options)) {
898 static $_contact_memberships = [];
899 $checkLifetime = FALSE;
900 foreach ($options as $key => $value) {
901 if (!empty($value['membership_type_id'])) {
902 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
903 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
905 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
906 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
907 unset($options[$key]);
908 $checkLifetime = TRUE;
912 if ($checkLifetime) {
921 * Set daefult the price set fields.
923 * @param CRM_Core_Form $form
928 public static function setDefaultPriceSet(&$form, &$defaults) {
929 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
933 foreach ($form->_priceSet
['fields'] as $val) {
934 foreach ($val['options'] as $keys => $values) {
935 // build price field index which is passed via URL
936 // url format will be appended by "&price_5=11"
937 $priceFieldName = 'price_' . $values['price_field_id'];
938 $priceFieldValue = self
::getPriceFieldValueFromURL($form, $priceFieldName);
939 if (!empty($priceFieldValue)) {
940 self
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
941 // break here to prevent overwriting of default due to 'is_default'
942 // option configuration. The value sent via URL get's higher priority.
945 elseif ($values['is_default']) {
946 self
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
954 * Get the value of price field if passed via url
956 * @param string $priceFieldName
957 * @param string $priceFieldValue
958 * @param string $priceFieldType
959 * @param array $defaults
963 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
964 if ($priceFieldType == 'CheckBox') {
965 $defaults[$priceFieldName][$priceFieldValue] = 1;
968 $defaults[$priceFieldName] = $priceFieldValue;
973 * Get the value of price field if passed via url
975 * @param CRM_Core_Form $form
976 * @param string $priceFieldName
978 * @return mixed $priceFieldValue
980 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
981 $priceFieldValue = CRM_Utils_Request
::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
982 if (!empty($priceFieldValue)) {
983 return $priceFieldValue;
988 * Supports event create function by setting up required price sets, not tested but expect
989 * it will work for contribution page
990 * @param array $params
991 * As passed to api/bao create fn.
992 * @param CRM_Core_DAO $entity
993 * Object for given entity.
994 * @param string $entityName
995 * Name of entity - e.g event.
997 public static function setPriceSets(&$params, $entity, $entityName) {
998 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1001 // CRM-14069 note that we may as well start by assuming more than one.
1002 // currently the form does not pass in as an array & will be skipped
1003 // test is passing in as an array but I feel the api should have a metadata that allows
1004 // transform of single to array - seems good for managing transitions - in which case all api
1005 // calls that set price_set_id will hit this
1006 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1007 // all separated values, strings, json half-separated values (in participant we hit this)
1008 // to be converted to json @ api layer
1009 $pse = new CRM_Price_DAO_PriceSetEntity();
1010 $pse->entity_table
= 'civicrm_' . $entityName;
1011 $pse->entity_id
= $entity->id
;
1012 while ($pse->fetch()) {
1013 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1014 // note an even more aggressive form of this deletion currently happens in event form
1015 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1016 // on the participant record
1017 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1018 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1022 foreach ($params['price_set_id'] as $priceSetID) {
1023 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1024 //@todo - how should we do this - copied from form
1025 //if (!empty($params['price_field_id'])) {
1026 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1027 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1033 * Get field ids of a price set.
1039 * Array of the field ids
1042 public static function getFieldIds($id) {
1043 $priceField = new CRM_Price_DAO_PriceField();
1044 $priceField->price_set_id
= $id;
1045 $priceField->find();
1046 while ($priceField->fetch()) {
1047 $var[] = $priceField->id
;
1053 * Copy a price set, including all the fields
1056 * The price set id to copy.
1058 * @return CRM_Price_DAO_PriceSet
1060 public static function copy($id) {
1061 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1062 $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
1064 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
1065 $title = ts('[Copy id %1]', [1 => $maxId +
1]);
1068 'title' => trim($newTitle) . ' ' . $title,
1069 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId +
1),
1073 $copy = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1079 //copying all the blocks pertaining to the price set
1080 $copyPriceField = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1081 ['price_set_id' => $id],
1082 ['price_set_id' => $copy->id
]
1084 if (!empty($copyPriceField)) {
1085 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1087 //copy option group and values
1088 foreach ($price as $originalId => $copyId) {
1089 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1090 ['price_field_id' => $originalId],
1091 ['price_field_id' => $copyId]
1097 CRM_Utils_Hook
::copy('Set', $copy);
1098 unset(\Civi
::$statics['CRM_Core_PseudoConstant']);
1103 * check price set permission.
1109 * @throws \CRM_Core_Exception
1111 public static function checkPermission($sid) {
1112 if ($sid && self
::eventPriceSetDomainID()) {
1113 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1114 if (CRM_Core_Config
::domainID() != $domain_id) {
1115 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
1122 * Get the sum of participant count
1123 * for all fields of given price set.
1128 * @param bool $onlyActive
1130 * @return int|null|string
1132 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1140 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1143 static $pricesetFieldCount = [];
1144 if (!isset($pricesetFieldCount[$sid])) {
1146 SELECT sum(value.count) as totalCount
1147 FROM civicrm_price_field_value value
1148 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1149 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1153 $count = CRM_Core_DAO
::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
1154 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1157 return $pricesetFieldCount[$sid];
1161 * Return a count of priceFieldValueIDs that are memberships by organisation and membership type
1163 * @param string $priceFieldValueIDs
1164 * Comma separated string of priceFieldValue IDs
1167 * Returns an array of counts by membership organisation
1169 public static function getMembershipCount($priceFieldValueIDs) {
1171 SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
1172 FROM civicrm_price_field_value pfv
1173 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1174 WHERE pfv.id IN ( $priceFieldValueIDs )
1175 GROUP BY mt.member_of_contact_id ";
1177 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1180 while ($crmDAO->fetch()) {
1181 $count[$crmDAO->id
] = $crmDAO->count
;
1188 * Check if auto renew option should be shown.
1190 * The auto-renew option should be visible if membership types associated with all the fields has
1191 * been set for auto-renew option.
1193 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1195 * @param int $priceSetId
1199 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1201 public static function checkAutoRenewForPriceSet($priceSetId) {
1202 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1203 pf.html_type, pf.id as price_field_id
1204 FROM civicrm_price_field_value pfv
1205 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1206 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1207 WHERE pf.price_set_id = %1
1208 AND pf.is_active = 1
1209 AND pfv.is_active = 1
1210 ORDER BY price_field_id';
1212 $params = [1 => [$priceSetId, 'Integer']];
1214 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1216 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1217 //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.
1222 $autoRenewOption = 2;
1224 while ($dao->fetch()) {
1225 if (!$dao->auto_renew
) {
1226 // If any one can't be renewed none can.
1229 if ($dao->auto_renew
== 1) {
1230 $autoRenewOption = 1;
1233 if ($dao->html_type
== 'Checkbox' && !in_array($dao->duration_interval
. $dao->duration_unit
, $priceFields[$dao->price_field_id
])) {
1234 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1235 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1238 $priceFields[$dao->price_field_id
][] = $dao->duration_interval
. $dao->duration_unit
;
1239 foreach ($priceFields as $priceFieldID => $durations) {
1240 if ($priceFieldID != $dao->price_field_id
&& !in_array($dao->duration_interval
. $dao->duration_unit
, $durations)) {
1241 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1247 return $autoRenewOption;
1251 * Retrieve auto renew frequency and interval.
1253 * @param int $priceSetId
1257 * associate array of frequency interval and unit
1259 public static function getRecurDetails($priceSetId) {
1260 $query = 'SELECT mt.duration_interval, mt.duration_unit
1261 FROM civicrm_price_field_value pfv
1262 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1263 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1264 WHERE pf.price_set_id = %1 LIMIT 1';
1266 $params = [1 => [$priceSetId, 'Integer']];
1267 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1269 return [$dao->duration_interval
, $dao->duration_unit
];
1275 public static function eventPriceSetDomainID() {
1276 return Civi
::settings()->get('event_price_set_domain_id');
1280 * Update the is_quick_config flag in the db.
1283 * Id of the database record.
1284 * @param bool $isQuickConfig we want to set the is_quick_config field.
1285 * Value we want to set the is_quick_config field.
1288 * true if we found and updated the object, else false
1290 public static function setIsQuickConfig($id, $isQuickConfig) {
1291 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1295 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1301 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1302 $membershipTypes = self
::getMembershipTypesFromPriceSet($id);
1303 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1310 * Get an array of the membership types in a price set.
1315 * Membership types in the price set
1317 public static function getMembershipTypesFromPriceSet($id) {
1319 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1320 FROM civicrm_price_field_value pfv
1321 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1322 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1323 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1327 $params = [1 => [$id, 'Integer']];
1328 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1330 $membershipTypes = [
1333 'autorenew_required' => [],
1334 'autorenew_optional' => [],
1336 while ($dao->fetch()) {
1337 if (empty($dao->membership_type_id
)) {
1340 $membershipTypes['all'][] = $dao->membership_type_id
;
1341 if (!empty($dao->auto_renew
)) {
1342 $membershipTypes['autorenew'][] = $dao->membership_type_id
;
1343 if ($dao->auto_renew
== 2) {
1344 $membershipTypes['autorenew_required'][] = $dao->membership_type_id
;
1347 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id
;
1351 $membershipTypes['non_renew'][] = $dao->membership_type_id
;
1354 return $membershipTypes;
1358 * Copy priceSet when event/contibution page is copied
1360 * @param string $baoName
1363 * Old event/contribution page id.
1365 * Newly created event/contribution page id.
1367 public static function copyPriceSet($baoName, $id, $newId) {
1368 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1370 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1371 if ($isQuickConfig) {
1372 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1373 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1376 $copyPriceSet = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1379 'entity_table' => $baoName,
1381 ['entity_id' => $newId]
1384 // copy event discount
1385 if ($baoName == 'civicrm_event') {
1386 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1387 foreach ($discount as $discountId => $setId) {
1389 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1391 CRM_Core_DAO
::copyGeneric(
1392 'CRM_Core_DAO_Discount',
1394 'id' => $discountId,
1397 'entity_id' => $newId,
1398 'price_set_id' => $copyPriceSet->id
,
1407 * Function to set tax_amount and tax_rate in LineItem.
1409 * @param array $field
1410 * @param array $lineItem
1411 * @param int $optionValueId
1412 * @param float $totalTax
1416 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
1417 // Here we round - i.e. after multiplying by quantity
1418 if ($field['html_type'] == 'Text') {
1419 $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
1422 $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
1424 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1425 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1426 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1427 $totalTax +
= $taxAmount;
1432 * Get the first price set value IDs from a parameters array.
1434 * In practice this is really used when we only expect one to exist.
1436 * @param array $params
1439 * Array of the ids of the price set values.
1441 public static function parseFirstPriceSetValueIDFromParams($params) {
1442 $priceSetValueIDs = self
::parsePriceSetValueIDsFromParams($params);
1443 return reset($priceSetValueIDs);
1447 * Get the price set value IDs from a set of parameters
1449 * @param array $params
1452 * Array of the ids of the price set values.
1454 public static function parsePriceSetValueIDsFromParams($params) {
1455 $priceSetParams = self
::parsePriceSetArrayFromParams($params);
1456 $priceSetValueIDs = [];
1457 foreach ($priceSetParams as $priceSetParam) {
1458 foreach (array_keys($priceSetParam) as $priceValueID) {
1459 $priceSetValueIDs[] = $priceValueID;
1462 return $priceSetValueIDs;
1466 * Get the price set value IDs from a set of parameters
1468 * @param array $params
1471 * Array of price fields filtered from the params.
1473 public static function parsePriceSetArrayFromParams($params) {
1474 $priceSetParams = [];
1475 foreach ($params as $field => $value) {
1476 $parts = explode('_', $field);
1477 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
1478 $priceSetParams[$field] = $value;
1481 return $priceSetParams;
1485 * Get non-deductible amount from price options
1487 * @param int $priceSetId
1488 * @param array $lineItem
1491 * calculated non-deductible amount.
1493 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1494 $nonDeductibleAmount = 0;
1495 if (!empty($lineItem[$priceSetId])) {
1496 foreach ($lineItem[$priceSetId] as $options) {
1497 $nonDeductibleAmount +
= $options['non_deductible_amount'] * $options['qty'];
1501 return $nonDeductibleAmount;
1505 * Get an array of all forms using a given price set.
1510 * Pages using the price set, keyed by type. e.g
1512 * 'civicrm_contribution_page' => array(2,5,6),
1513 * 'civicrm_event' => array(5,6),
1514 * 'civicrm_event_template' => array(7),
1517 public static function getFormsUsingPriceSet($id) {
1520 SELECT entity_table, entity_id
1521 FROM civicrm_price_set_entity
1522 WHERE price_set_id = %1";
1523 $params = [1 => [$id, 'Integer']];
1524 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1526 while ($crmFormDAO->fetch()) {
1527 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
1533 * @param array $forms
1534 * Array of forms that use a price set keyed by entity. e.g
1536 * 'civicrm_contribution_page' => array(2,5,6),
1537 * 'civicrm_event' => array(5,6),
1538 * 'civicrm_event_template' => array(7),
1542 * Array of entities suppliemented with per entity information.
1544 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1546 * @throws \Exception
1548 protected static function reformatUsedByFormsWithEntityData($forms) {
1550 foreach ($forms as $table => $entities) {
1552 case 'civicrm_event':
1553 $ids = implode(',', $entities);
1554 $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
1555 FROM civicrm_event ce
1556 LEFT JOIN civicrm_option_value ON
1557 ( ce.event_type_id = civicrm_option_value.value )
1558 LEFT JOIN civicrm_option_group ON
1559 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1561 civicrm_option_group.name = 'event_type' AND
1564 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1565 while ($crmDAO->fetch()) {
1566 if ($crmDAO->isTemplate
) {
1567 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
1568 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1569 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1572 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1573 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1574 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1575 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1576 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1581 case 'civicrm_contribution_page':
1582 $ids = implode(',', $entities);
1583 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1584 FROM civicrm_contribution_page cp, civicrm_financial_type ct
1585 WHERE ct.id = cp.financial_type_id AND
1588 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1589 while ($crmDAO->fetch()) {
1590 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1591 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
1592 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1593 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1597 case 'civicrm_contribution':
1598 case 'civicrm_membership':
1599 case 'civicrm_participant':
1600 $usedBy[$table] = 1;
1604 throw new CRM_Core_Exception("$table is not supported in PriceSet::usedBy()");
1612 * Get the relevant line item.
1614 * Note this is part of code being cleaned up / refactored & may change.
1616 * @param array $params
1617 * @param array $lineItem
1618 * @param int $priceSetID
1619 * @param array $field
1624 public static function getLine(&$params, &$lineItem, $priceSetID, $field, $id): array {
1626 switch ($field['html_type']) {
1628 $firstOption = reset($field['options']);
1629 $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
1630 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
1631 $optionValueId = key($field['options']);
1633 if (CRM_Utils_Array
::value('name', $field['options'][$optionValueId]) === 'contribution_amount') {
1634 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
1635 if (array_key_exists($params['financial_type_id'], $taxRates)) {
1636 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
1637 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
1638 $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
1641 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1642 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1647 //special case if user select -none-
1648 if ($params["price_{$id}"] <= 0) {
1651 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1652 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
1654 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
1655 // This is notably the case with memberships and we need to put this amount
1656 // on the line item rather than the calculated amount.
1657 // This seems to only affect radio link items as that is the use case for the 'quick config'
1658 // set up (which allows a free form field).
1659 // @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
1660 // don't specifically need it & find a better way where we do.
1661 $amount_override = NULL;
1663 if ($priceSetID && count(self
::filterPriceFieldsFromParams($priceSetID, $params)) === 1) {
1664 $amount_override = CRM_Utils_Array
::value('total_amount', $params);
1666 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, $amount_override);
1667 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1668 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1669 if ($amount_override) {
1670 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
1676 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1677 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
1679 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
1680 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1681 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1687 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem);
1688 foreach ($params["price_{$id}"] as $optionId => $option) {
1689 if (!empty($field['options'][$optionId]['tax_rate'])) {
1690 $lineItem = self
::setLineItem($field, $lineItem, $optionId, $totalTax);
1695 return [$params, $lineItem];
1699 * Add the relevant price fields to the form.
1701 * @param \CRM_Core_Form $form
1702 * @param array $feeBlock
1703 * @param bool $validFieldsOnly
1704 * @param string $className
1705 * @param array $validPriceFieldIds
1707 protected static function addPriceFieldsToForm(CRM_Core_Form
$form, $feeBlock, bool $validFieldsOnly, string $className, array $validPriceFieldIds) {
1708 $hideAdminValues = !CRM_Core_Permission
::check('edit contributions');
1709 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
1710 $adminFieldVisible = CRM_Core_Permission
::check('administer CiviCRM');
1711 foreach ($feeBlock as $id => $field) {
1712 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
1713 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
1716 $options = $field['options'] ??
NULL;
1717 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
1718 $userid = $form->getVar('_membershipContactID');
1719 $checklifetime = self
::checkCurrentMembership($options, $userid);
1720 if ($checklifetime) {
1721 $form->assign('ispricelifetime', TRUE);
1725 $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
1727 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
1730 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
1731 foreach ($options as $key => $currentOption) {
1732 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField
::getVisibilityOptionID('admin')) {
1733 unset($options[$key]);
1737 if (!empty($options)) {
1738 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
1739 'price_' . $field['id'],
1742 CRM_Utils_Array
::value('is_required', $field, FALSE),