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;
34 public function __construct() {
35 parent
::__construct();
39 * Takes an associative array and creates a price set object.
41 * @param array $params
42 * (reference) an assoc array of name/value pairs.
44 * @return CRM_Price_DAO_PriceSet
46 public static function create(&$params) {
47 $hook = empty($params['id']) ?
'create' : 'edit';
48 CRM_Utils_Hook
::pre($hook, 'PriceSet', CRM_Utils_Array
::value('id', $params), $params);
50 if (empty($params['id']) && empty($params['name'])) {
51 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
54 $validatePriceSet = TRUE;
55 if (!empty($params['extends']) && is_array($params['extends'])) {
56 if (!array_key_exists(CRM_Core_Component
::getComponentID('CiviEvent'), $params['extends'])
57 ||
!array_key_exists(CRM_Core_Component
::getComponentID('CiviMember'), $params['extends'])
59 $validatePriceSet = FALSE;
61 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
64 $priceSetID = CRM_Utils_Array
::value('id', $params);
66 $priceSetBAO = new CRM_Price_BAO_PriceSet();
67 $priceSetBAO->copyValues($params);
68 if (self
::eventPriceSetDomainID()) {
69 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
73 CRM_Utils_Hook
::post($hook, 'PriceSet', $priceSetBAO->id
, $priceSetBAO);
78 * Fetch object based on array of properties.
80 * @param array $params
81 * (reference ) an assoc array of name/value pairs.
82 * @param array $defaults
83 * (reference ) an assoc array to hold the flattened values.
85 * @return CRM_Price_DAO_PriceSet
87 public static function retrieve(&$params, &$defaults) {
88 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
92 * Update the is_active flag in the db.
95 * Id of the database record.
99 * true if we found and updated the object, else false
101 public static function setIsActive($id, $isActive) {
102 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
106 * Calculate the default price set id
107 * assigned to the contribution/membership etc
109 * @param string $entity
115 public static function getDefaultPriceSet($entity = 'contribution') {
116 if (!empty(self
::$_defaultPriceSet[$entity])) {
117 return self
::$_defaultPriceSet[$entity];
119 $entityName = 'default_contribution_amount';
120 if ($entity == 'membership') {
121 $entityName = 'default_membership_type_amount';
125 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
126 FROM civicrm_price_set ps
127 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
128 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
129 WHERE ps.name = '{$entityName}'
132 $dao = CRM_Core_DAO
::executeQuery($sql);
133 self
::$_defaultPriceSet[$entity] = [];
134 while ($dao->fetch()) {
135 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = [
136 'setID' => $dao->setID
,
137 'priceFieldID' => $dao->priceFieldID
,
138 'name' => $dao->name
,
139 'label' => $dao->label
,
140 'priceFieldValueID' => $dao->priceFieldValueID
,
141 'membership_type_id' => $dao->membership_type_id
,
142 'amount' => $dao->amount
,
143 'financial_type_id' => $dao->financial_type_id
,
147 return self
::$_defaultPriceSet[$entity];
151 * Get the price set title.
160 public static function getTitle($id) {
161 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
165 * Return a list of all forms which use this price set.
169 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
173 public static function getUsedBy($id, $simpleReturn = FALSE) {
175 $forms = self
::getFormsUsingPriceSet($id);
176 $tables = array_keys($forms);
177 // @todo - this is really clumsy overloading the signature like this. Instead
178 // move towards having a function that does not call reformatUsedByFormsWithEntityData
179 // and call that when that data is not used.
180 if ($simpleReturn == 'table') {
183 // @todo - this is painfully slow in some cases.
186 SELECT cli.entity_table, cli.entity_id
187 FROM civicrm_line_item cli
188 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
189 WHERE cpf.price_set_id = %1";
190 $params = [1 => [$id, 'Integer']];
191 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
192 while ($crmFormDAO->fetch()) {
193 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
194 $tables[] = $crmFormDAO->entity_table
;
200 // @todo - this is really clumsy overloading the signature like this. See above.
201 if ($simpleReturn == 'entity') {
204 $usedBy = self
::reformatUsedByFormsWithEntityData($forms, $usedBy);
210 * Delete the price set, including the fields.
216 * false if fields exist for this set, true if the
217 * set could be deleted
220 public static function deleteSet($id) {
221 // delete price fields
222 $priceField = new CRM_Price_DAO_PriceField();
223 $priceField->price_set_id
= $id;
225 while ($priceField->fetch()) {
226 // delete options first
227 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
230 $set = new CRM_Price_DAO_PriceSet();
232 return $set->delete();
236 * Link the price set with the specified table and id.
238 * @param string $entityTable
239 * @param int $entityId
240 * @param int $priceSetId
244 public static function addTo($entityTable, $entityId, $priceSetId) {
245 // verify that the price set exists
246 $dao = new CRM_Price_DAO_PriceSet();
247 $dao->id
= $priceSetId;
253 $dao = new CRM_Price_DAO_PriceSetEntity();
254 // find if this already exists
255 $dao->entity_id
= $entityId;
256 $dao->entity_table
= $entityTable;
259 // add or update price_set_id
260 $dao->price_set_id
= $priceSetId;
265 * Delete price set for the given entity and id.
267 * @param string $entityTable
268 * @param int $entityId
272 public static function removeFrom($entityTable, $entityId) {
273 $dao = new CRM_Price_DAO_PriceSetEntity();
274 $dao->entity_table
= $entityTable;
275 $dao->entity_id
= $entityId;
276 return $dao->delete();
280 * Find a price_set_id associated with the given table, id and usedFor
281 * Used For value for events:1, contribution:2, membership:3
283 * @param string $entityTable
284 * @param int $entityId
285 * @param int $usedFor
286 * ( price set that extends/used for particular component ).
288 * @param null $isQuickConfig
289 * @param null $setName
292 * price_set_id, or false if none found
294 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
295 if (!$entityTable ||
!$entityId) {
299 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
300 FROM civicrm_price_set ps
301 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
302 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
303 if ($isQuickConfig) {
304 $sql .= ' AND ps.is_quick_config = 0 ';
307 1 => [$entityTable, 'String'],
308 2 => [$entityId, 'Integer'],
311 $sql .= " AND ps.extends LIKE '%%3%' ";
312 $params[3] = [$usedFor, 'Integer'];
315 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
317 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
318 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
322 * Find a price_set_id associated with the given option value or field ID.
324 * @param array $params
325 * (reference) an assoc array of name/value pairs.
326 * array may contain either option id or
330 * price set id on success, null otherwise
332 public static function getSetId(&$params) {
335 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
336 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
337 $fieldValue->id
= $oid;
338 if ($fieldValue->find(TRUE)) {
339 $fid = $fieldValue->price_field_id
;
343 $fid = CRM_Utils_Array
::value('fid', $params);
347 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
354 * Return an associative array of all price sets.
356 * @param bool $withInactive
357 * Whether or not to include inactive entries.
358 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
359 * @param string $column name of the column.
362 * associative array of id => name
364 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
367 DISTINCT ( price_set_id ) as id, s.{$column}
370 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
371 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
373 is_quick_config = 0 ";
375 if (!$withInactive) {
376 $query .= ' AND s.is_active = 1 ';
379 if (self
::eventPriceSetDomainID()) {
380 $query .= ' AND s.domain_id = ' . CRM_Core_Config
::domainID();
385 if ($extendComponentName) {
386 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
390 $query .= " AND s.extends LIKE '%$componentId%' ";
392 // Check permissioned financial types
393 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialType, CRM_Core_Action
::ADD
);
394 if ($financialType) {
395 $types = implode(',', array_keys($financialType));
396 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
399 // Do not display any price sets
402 $query .= " GROUP BY s.id";
403 $dao = CRM_Core_DAO
::executeQuery($query);
404 while ($dao->fetch()) {
405 $priceSets[$dao->id
] = $dao->$column;
411 * Get price set details.
413 * An array containing price set details (including price fields) is returned
417 * @param bool $required
418 * Appears to have no effect based on reading the code.
419 * @param bool $validOnly
420 * Should only fields where today's date falls within the valid range be returned?
423 * Array consisting of field details
425 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
438 'is_display_amounts',
447 if ($required == TRUE) {
448 $priceFields[] = 'is_required';
452 $select = 'SELECT ' . implode(',', $priceFields);
453 $from = ' FROM civicrm_price_field';
456 1 => [$setID, 'Integer'],
458 $currentTime = date('YmdHis');
460 WHERE price_set_id = %1
462 AND ( active_on IS NULL OR active_on <= {$currentTime} )
467 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
471 $orderBy = ' ORDER BY weight';
473 $sql = $select . $from . $where . $dateSelect . $orderBy;
475 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
477 $isDefaultContributionPriceSet = FALSE;
478 if ('default_contribution_amount' == CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
479 $isDefaultContributionPriceSet = TRUE;
482 $visibility = CRM_Core_PseudoConstant
::visibility('name');
483 while ($dao->fetch()) {
486 $setTree[$setID]['fields'][$fieldID] = [];
487 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
489 foreach ($priceFields as $field) {
490 if ($field == 'id' ||
is_null($dao->$field)) {
494 if ($field == 'visibility_id') {
495 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
497 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
499 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
502 // also get the pre and post help from this price set
504 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
505 FROM civicrm_price_set
507 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
509 $setTree[$setID]['extends'] = $dao->extends;
510 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
511 $setTree[$setID]['help_pre'] = $dao->help_pre
;
512 $setTree[$setID]['help_post'] = $dao->help_post
;
513 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
514 $setTree[$setID]['min_amount'] = $dao->min_amount
;
520 * Get the Price Field ID.
522 * We call this function when more than one being present would represent an error
523 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
524 * @param array $priceSet
526 * @throws CRM_Core_Exception
529 public static function getOnlyPriceFieldID(array $priceSet) {
530 if (count($priceSet['fields']) > 1) {
531 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
533 return (int) implode('_', array_keys($priceSet['fields']));
537 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
538 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
539 * @param array $priceSet
541 * @throws CRM_Core_Exception
544 public static function getOnlyPriceFieldValueID(array $priceSet) {
545 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
546 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
547 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
549 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
553 * Initiate price set such that various non-BAO things are set on the form.
555 * This function is not really a BAO function so the location is misleading.
557 * @param CRM_Core_Form $form
559 * @param string $entityTable
560 * @param bool $validOnly
561 * @param int $priceSetId
564 public static function initSet(&$form, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
566 //check if price set is is_config
567 if (is_numeric($priceSetId)) {
568 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
569 $form->assign('quickConfig', 1);
574 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
575 $entityId = $entity = NULL;
577 switch ($entityTable) {
578 case 'civicrm_event':
579 $entity = 'participant';
580 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
581 $entityId = $form->_id
;
584 $entityId = $form->_participantId
;
588 case 'civicrm_contribution_page':
589 case 'civicrm_contribution':
590 $entity = 'contribution';
591 $entityId = $form->_id
;
595 if ($entityId && $entity) {
596 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
604 $form->_priceSetId
= $priceSetId;
605 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
606 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
607 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
609 //get the price set fields participant count.
610 if ($entityTable == 'civicrm_event') {
611 //get option count info.
612 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
613 if ($form->_priceSet
['optionsCountTotal']) {
614 $optionsCountDetails = [];
615 if (!empty($form->_priceSet
['fields'])) {
616 foreach ($form->_priceSet
['fields'] as $field) {
617 foreach ($field['options'] as $option) {
618 $count = CRM_Utils_Array
::value('count', $option, 0);
619 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
623 $form->_priceSet
['optionsCountDetails'] = $optionsCountDetails;
626 //get option max value info.
627 $optionsMaxValueTotal = 0;
628 $optionsMaxValueDetails = [];
630 if (!empty($form->_priceSet
['fields'])) {
631 foreach ($form->_priceSet
['fields'] as $field) {
632 foreach ($field['options'] as $option) {
633 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
634 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
635 $optionsMaxValueTotal +
= $maxVal;
640 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
641 if ($optionsMaxValueTotal) {
642 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
645 $form->set('priceSetId', $form->_priceSetId
);
646 $form->set('priceSet', $form->_priceSet
);
651 * Get line item purchase information.
653 * This function takes the input parameters and interprets out of it what has been purchased.
656 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
657 * And, it would make sense to introduce caching into that function and call it from here rather than
658 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
659 * @param array $params
660 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
662 * Line item array to be altered.
663 * @param int $priceSetID
665 * @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
666 * don't specifically need it & find a better way where we do.
668 public static function processAmount($fields, &$params, &$lineItem, $priceSetID = NULL) {
670 $totalPrice = $totalTax = 0;
671 foreach ($fields as $id => $field) {
672 if (empty($params["price_{$id}"]) ||
673 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
675 // skip if nothing was submitted for this field
679 switch ($field['html_type']) {
681 $firstOption = reset($field['options']);
682 $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
683 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
684 $optionValueId = key($field['options']);
686 if (CRM_Utils_Array
::value('name', $field['options'][$optionValueId]) === 'contribution_amount') {
687 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
688 if (array_key_exists($params['financial_type_id'], $taxRates)) {
689 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
690 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
691 $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
694 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
695 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
697 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
701 //special case if user select -none-
702 if ($params["price_{$id}"] <= 0) {
705 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
706 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
708 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
709 // This is notably the case with memberships and we need to put this amount
710 // on the line item rather than the calculated amount.
711 // This seems to only affect radio link items as that is the use case for the 'quick config'
712 // set up (which allows a free form field).
713 // @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
714 // don't specifically need it & find a better way where we do.
715 $amount_override = NULL;
717 if ($priceSetID && count(self
::filterPriceFieldsFromParams($priceSetID, $params)) === 1) {
718 $amount_override = CRM_Utils_Array
::value('partial_payment_total', $params, CRM_Utils_Array
::value('total_amount', $params));
720 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, $amount_override);
721 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
722 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
723 if ($amount_override) {
724 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
727 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
731 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
732 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
734 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
735 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
736 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
738 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
743 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
744 foreach ($params["price_{$id}"] as $optionId => $option) {
745 if (!empty($field['options'][$optionId]['tax_rate'])) {
746 $lineItem = self
::setLineItem($field, $lineItem, $optionId, $totalTax);
748 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
755 $totalParticipant = 0;
756 if (is_array($lineItem)) {
757 foreach ($lineItem as $values) {
758 $totalParticipant +
= $values['participant_count'];
759 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
760 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
763 // However, because the quick config concept existed all sorts of logic was hung off it
764 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
765 // is always set at the functional level. In this case we are dealing with the default 'quick config'
766 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
767 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
770 // But, in the interests of being careful when capacity is low - avoiding the known default value
772 // Crucially a test has been added so a better solution can be implemented later with some comfort.
773 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
774 if ($values['label'] !== ts('Contribution Amount')) {
775 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
780 $displayParticipantCount = '';
781 if ($totalParticipant > 0) {
782 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
784 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
785 if (!empty($amount_level)) {
786 $params['amount_level'] = CRM_Utils_Array
::implodePadded($amount_level);
787 if (!empty($displayParticipantCount)) {
788 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
792 $params['amount'] = $totalPrice;
793 $params['tax_amount'] = $totalTax;
797 * Get the text to record for amount level.
799 * @param array $params
800 * Submitted parameters
801 * - priceSetId is required to be set in the calling function
802 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
803 * default one & this function asks that be set if it is the case).
806 * Text for civicrm_contribution.amount_level field.
808 public static function getAmountLevelText($params) {
809 $priceSetID = $params['priceSetId'];
810 $priceFieldSelection = self
::filterPriceFieldsFromParams($priceSetID, $params);
811 $priceFieldMetadata = self
::getCachedPriceSetDetail($priceSetID);
812 $displayParticipantCount = NULL;
815 foreach ($priceFieldMetadata['fields'] as $field) {
816 if (!empty($priceFieldSelection[$field['id']])) {
818 if ($field['is_enter_qty']) {
819 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
821 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
822 // ie. it represents the default price field for a contribution. Another approach would be not
823 // to give it a label if we don't want it to show.
824 if ($field['label'] !== ts('Contribution Amount')) {
825 $amount_level[] = $field['label'] . $qtyString;
829 return CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
833 * Get the fields relevant to the price field from the parameters.
835 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
837 * @param int $priceSetID
838 * @param array $params
841 * Price fields found in the params array
843 public static function filterPriceFieldsFromParams($priceSetID, $params) {
844 $priceSet = self
::getCachedPriceSetDetail($priceSetID);
846 foreach ($priceSet['fields'] as $field) {
847 if (!empty($params['price_' . $field['id']])) {
848 $return[$field['id']] = $params['price_' . $field['id']];
855 * Wrapper for getSetDetail with caching.
857 * We seem to be passing this array around in a painful way - presumably to avoid the hit
858 * of loading it - so lets make it callable with caching.
860 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
861 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
862 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
863 * think less about the price sets.
865 * @param int $priceSetID
869 public static function getCachedPriceSetDetail($priceSetID) {
870 $cacheKey = __CLASS__
. __FUNCTION__
. '_' . $priceSetID;
871 $cache = CRM_Utils_Cache
::singleton();
872 $values = $cache->get($cacheKey);
873 if (empty($values)) {
874 $data = self
::getSetDetail($priceSetID);
875 $values = $data[$priceSetID];
876 $cache->set($cacheKey, $values);
882 * Build the price set form.
884 * @param CRM_Core_Form $form
888 public static function buildPriceSet(&$form) {
889 $priceSetId = $form->get('priceSetId');
894 $validFieldsOnly = TRUE;
895 $className = CRM_Utils_System
::getClassName($form);
896 if (in_array($className, [
897 'CRM_Contribute_Form_Contribution',
898 'CRM_Member_Form_Membership',
900 $validFieldsOnly = FALSE;
903 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
904 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
905 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
906 $form->_quickConfig
= $quickConfig = 0;
907 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
911 $form->assign('quickConfig', $quickConfig);
912 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
913 $form->_quickConfig
= $quickConfig;
916 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
917 if (!empty($form->_membershipTypeValues
) && is_array($form->_membershipTypeValues
)) {
918 $autoRenewMembershipTypes = [];
919 foreach ($form->_membershipTypeValues
as $membershiptTypeValue) {
920 if ($membershiptTypeValue['auto_renew']) {
921 $autoRenewMembershipTypes[] = $membershiptTypeValue['id'];
924 foreach ($form->_priceSet
['fields'] as $field) {
925 if (array_key_exists('options', $field) && is_array($field['options'])) {
926 foreach ($field['options'] as $option) {
927 if (!empty($option['membership_type_id'])) {
928 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
929 $form->_priceSet
['auto_renew_membership_field'] = $field['id'];
930 // Only one field can offer auto_renew memberships, so break here.
938 $form->assign('priceSet', $form->_priceSet
);
940 $component = 'contribution';
941 if ($className == 'CRM_Member_Form_Membership') {
942 $component = 'membership';
945 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
946 $feeBlock = &$form->_values
['fee'];
947 if (!empty($form->_useForMember
)) {
948 $component = 'membership';
952 $feeBlock = &$form->_priceSet
['fields'];
955 self
::applyACLFinancialTypeStatusToFeeBlock($feeBlock);
956 // Call the buildAmount hook.
957 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
959 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
960 $adminFieldVisible = FALSE;
961 if (CRM_Core_Permission
::check('administer CiviCRM')) {
962 $adminFieldVisible = TRUE;
965 $hideAdminValues = TRUE;
966 if (CRM_Core_Permission
::check('edit contributions')) {
967 $hideAdminValues = FALSE;
970 foreach ($feeBlock as $id => $field) {
971 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
972 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
975 $options = CRM_Utils_Array
::value('options', $field);
976 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
977 $userid = $form->getVar('_membershipContactID');
978 $checklifetime = self
::checkCurrentMembership($options, $userid);
979 if ($checklifetime) {
980 $form->assign('ispricelifetime', TRUE);
984 $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
986 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
989 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
990 foreach ($options as $key => $currentOption) {
991 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField
::getVisibilityOptionID('admin')) {
992 unset($options[$key]);
996 if (!empty($options)) {
997 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
998 'price_' . $field['id'],
1001 CRM_Utils_Array
::value('is_required', $field, FALSE),
1011 * Apply ACLs on Financial Type to the price options in a fee block.
1013 * @param array $feeBlock
1014 * Fee block: array of price fields.
1018 public static function applyACLFinancialTypeStatusToFeeBlock(&$feeBlock) {
1019 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1020 foreach ($feeBlock as $key => $value) {
1021 foreach ($value['options'] as $k => $options) {
1022 if (!CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($options['financial_type_id']))) {
1023 unset($feeBlock[$key]['options'][$k]);
1026 if (empty($feeBlock[$key]['options'])) {
1027 unset($feeBlock[$key]);
1034 * Check the current Membership having end date null.
1036 * @param array $options
1037 * @param int $userid
1038 * Probably actually contact ID.
1042 public static function checkCurrentMembership(&$options, $userid) {
1043 if (!$userid ||
empty($options)) {
1046 static $_contact_memberships = [];
1047 $checkLifetime = FALSE;
1048 foreach ($options as $key => $value) {
1049 if (!empty($value['membership_type_id'])) {
1050 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
1051 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
1053 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
1054 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
1055 unset($options[$key]);
1056 $checkLifetime = TRUE;
1060 if ($checkLifetime) {
1069 * Set daefult the price set fields.
1071 * @param CRM_Core_Form $form
1076 public static function setDefaultPriceSet(&$form, &$defaults) {
1077 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1081 foreach ($form->_priceSet
['fields'] as $val) {
1082 foreach ($val['options'] as $keys => $values) {
1083 // build price field index which is passed via URL
1084 // url format will be appended by "&price_5=11"
1085 $priceFieldName = 'price_' . $values['price_field_id'];
1086 $priceFieldValue = self
::getPriceFieldValueFromURL($form, $priceFieldName);
1087 if (!empty($priceFieldValue)) {
1088 self
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
1089 // break here to prevent overwriting of default due to 'is_default'
1090 // option configuration. The value sent via URL get's higher priority.
1093 elseif ($values['is_default']) {
1094 self
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
1102 * Get the value of price field if passed via url
1104 * @param string $priceFieldName
1105 * @param string $priceFieldValue
1106 * @param string $priceFieldType
1107 * @param array $defaults
1111 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
1112 if ($priceFieldType == 'CheckBox') {
1113 $defaults[$priceFieldName][$priceFieldValue] = 1;
1116 $defaults[$priceFieldName] = $priceFieldValue;
1121 * Get the value of price field if passed via url
1123 * @param CRM_Core_Form $form
1124 * @param string $priceFieldName
1126 * @return mixed $priceFieldValue
1128 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
1129 $priceFieldValue = CRM_Utils_Request
::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
1130 if (!empty($priceFieldValue)) {
1131 return $priceFieldValue;
1136 * Supports event create function by setting up required price sets, not tested but expect
1137 * it will work for contribution page
1138 * @param array $params
1139 * As passed to api/bao create fn.
1140 * @param CRM_Core_DAO $entity
1141 * Object for given entity.
1142 * @param string $entityName
1143 * Name of entity - e.g event.
1145 public static function setPriceSets(&$params, $entity, $entityName) {
1146 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1149 // CRM-14069 note that we may as well start by assuming more than one.
1150 // currently the form does not pass in as an array & will be skipped
1151 // test is passing in as an array but I feel the api should have a metadata that allows
1152 // transform of single to array - seems good for managing transitions - in which case all api
1153 // calls that set price_set_id will hit this
1154 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1155 // all separated values, strings, json half-separated values (in participant we hit this)
1156 // to be converted to json @ api layer
1157 $pse = new CRM_Price_DAO_PriceSetEntity();
1158 $pse->entity_table
= 'civicrm_' . $entityName;
1159 $pse->entity_id
= $entity->id
;
1160 while ($pse->fetch()) {
1161 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1162 // note an even more aggressive form of this deletion currently happens in event form
1163 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1164 // on the participant record
1165 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1166 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1170 foreach ($params['price_set_id'] as $priceSetID) {
1171 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1172 //@todo - how should we do this - copied from form
1173 //if (!empty($params['price_field_id'])) {
1174 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1175 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1181 * Get field ids of a price set.
1187 * Array of the field ids
1190 public static function getFieldIds($id) {
1191 $priceField = new CRM_Price_DAO_PriceField();
1192 $priceField->price_set_id
= $id;
1193 $priceField->find();
1194 while ($priceField->fetch()) {
1195 $var[] = $priceField->id
;
1201 * Copy a price set, including all the fields
1204 * The price set id to copy.
1206 * @return CRM_Price_DAO_PriceSet
1208 public static function copy($id) {
1209 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1210 $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
1212 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
1213 $title = ts('[Copy id %1]', [1 => $maxId +
1]);
1216 'title' => trim($newTitle) . ' ' . $title,
1217 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId +
1),
1221 $copy = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1227 //copying all the blocks pertaining to the price set
1228 $copyPriceField = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1229 ['price_set_id' => $id],
1230 ['price_set_id' => $copy->id
]
1232 if (!empty($copyPriceField)) {
1233 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1235 //copy option group and values
1236 foreach ($price as $originalId => $copyId) {
1237 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1238 ['price_field_id' => $originalId],
1239 ['price_field_id' => $copyId]
1245 CRM_Utils_Hook
::copy('Set', $copy);
1250 * check price set permission.
1256 * @throws \CRM_Core_Exception
1258 public static function checkPermission($sid) {
1259 if ($sid && self
::eventPriceSetDomainID()) {
1260 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1261 if (CRM_Core_Config
::domainID() != $domain_id) {
1262 CRM_Core_Error
::statusBounce(ts('You do not have permission to access this page.'));
1269 * Get the sum of participant count
1270 * for all fields of given price set.
1275 * @param bool $onlyActive
1277 * @return int|null|string
1279 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1287 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1290 static $pricesetFieldCount = [];
1291 if (!isset($pricesetFieldCount[$sid])) {
1293 SELECT sum(value.count) as totalCount
1294 FROM civicrm_price_field_value value
1295 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1296 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1300 $count = CRM_Core_DAO
::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
1301 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1304 return $pricesetFieldCount[$sid];
1312 public static function getMembershipCount($ids) {
1314 SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
1315 FROM civicrm_price_field_value pfv
1316 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1317 WHERE pfv.id IN ( $ids )
1318 GROUP BY mt.member_of_contact_id ";
1320 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1323 while ($crmDAO->fetch()) {
1324 $count[$crmDAO->id
] = $crmDAO->count
;
1331 * Check if auto renew option should be shown.
1333 * The auto-renew option should be visible if membership types associated with all the fields has
1334 * been set for auto-renew option.
1336 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1338 * @param int $priceSetId
1342 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1344 public static function checkAutoRenewForPriceSet($priceSetId) {
1345 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1346 pf.html_type, pf.id as price_field_id
1347 FROM civicrm_price_field_value pfv
1348 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1349 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1350 WHERE pf.price_set_id = %1
1351 AND pf.is_active = 1
1352 AND pfv.is_active = 1
1353 ORDER BY price_field_id';
1355 $params = [1 => [$priceSetId, 'Integer']];
1357 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1359 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1360 //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.
1365 $autoRenewOption = 2;
1367 while ($dao->fetch()) {
1368 if (!$dao->auto_renew
) {
1369 // If any one can't be renewed none can.
1372 if ($dao->auto_renew
== 1) {
1373 $autoRenewOption = 1;
1376 if ($dao->html_type
== 'Checkbox' && !in_array($dao->duration_interval
. $dao->duration_unit
, $priceFields[$dao->price_field_id
])) {
1377 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1378 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1381 $priceFields[$dao->price_field_id
][] = $dao->duration_interval
. $dao->duration_unit
;
1382 foreach ($priceFields as $priceFieldID => $durations) {
1383 if ($priceFieldID != $dao->price_field_id
&& !in_array($dao->duration_interval
. $dao->duration_unit
, $durations)) {
1384 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1390 return $autoRenewOption;
1394 * Retrieve auto renew frequency and interval.
1396 * @param int $priceSetId
1400 * associate array of frequency interval and unit
1402 public static function getRecurDetails($priceSetId) {
1403 $query = 'SELECT mt.duration_interval, mt.duration_unit
1404 FROM civicrm_price_field_value pfv
1405 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1406 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1407 WHERE pf.price_set_id = %1 LIMIT 1';
1409 $params = [1 => [$priceSetId, 'Integer']];
1410 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1412 return [$dao->duration_interval
, $dao->duration_unit
];
1418 public static function eventPriceSetDomainID() {
1419 return Civi
::settings()->get('event_price_set_domain_id');
1423 * Update the is_quick_config flag in the db.
1426 * Id of the database record.
1427 * @param bool $isQuickConfig we want to set the is_quick_config field.
1428 * Value we want to set the is_quick_config field.
1431 * true if we found and updated the object, else false
1433 public static function setIsQuickConfig($id, $isQuickConfig) {
1434 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1438 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1444 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1445 $membershipTypes = self
::getMembershipTypesFromPriceSet($id);
1446 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1453 * Get an array of the membership types in a price set.
1458 * Membership types in the price set
1460 public static function getMembershipTypesFromPriceSet($id) {
1462 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1463 FROM civicrm_price_field_value pfv
1464 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1465 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1466 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1470 $params = [1 => [$id, 'Integer']];
1471 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1473 $membershipTypes = [
1476 'autorenew_required' => [],
1477 'autorenew_optional' => [],
1479 while ($dao->fetch()) {
1480 if (empty($dao->membership_type_id
)) {
1483 $membershipTypes['all'][] = $dao->membership_type_id
;
1484 if (!empty($dao->auto_renew
)) {
1485 $membershipTypes['autorenew'][] = $dao->membership_type_id
;
1486 if ($dao->auto_renew
== 2) {
1487 $membershipTypes['autorenew_required'][] = $dao->membership_type_id
;
1490 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id
;
1494 $membershipTypes['non_renew'][] = $dao->membership_type_id
;
1497 return $membershipTypes;
1501 * Copy priceSet when event/contibution page is copied
1503 * @param string $baoName
1506 * Old event/contribution page id.
1508 * Newly created event/contribution page id.
1510 public static function copyPriceSet($baoName, $id, $newId) {
1511 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1513 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1514 if ($isQuickConfig) {
1515 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1516 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1519 $copyPriceSet = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1522 'entity_table' => $baoName,
1524 ['entity_id' => $newId]
1527 // copy event discount
1528 if ($baoName == 'civicrm_event') {
1529 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1530 foreach ($discount as $discountId => $setId) {
1532 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1534 CRM_Core_DAO
::copyGeneric(
1535 'CRM_Core_DAO_Discount',
1537 'id' => $discountId,
1540 'entity_id' => $newId,
1541 'price_set_id' => $copyPriceSet->id
,
1550 * Function to set tax_amount and tax_rate in LineItem.
1552 * @param array $field
1553 * @param array $lineItem
1554 * @param int $optionValueId
1555 * @param float $totalTax
1559 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
1560 // Here we round - i.e. after multiplying by quantity
1561 if ($field['html_type'] == 'Text') {
1562 $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
1565 $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
1567 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1568 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1569 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1570 $totalTax +
= $taxAmount;
1575 * Get the first price set value IDs from a parameters array.
1577 * In practice this is really used when we only expect one to exist.
1579 * @param array $params
1582 * Array of the ids of the price set values.
1584 public static function parseFirstPriceSetValueIDFromParams($params) {
1585 $priceSetValueIDs = self
::parsePriceSetValueIDsFromParams($params);
1586 return reset($priceSetValueIDs);
1590 * Get the price set value IDs from a set of parameters
1592 * @param array $params
1595 * Array of the ids of the price set values.
1597 public static function parsePriceSetValueIDsFromParams($params) {
1598 $priceSetParams = self
::parsePriceSetArrayFromParams($params);
1599 $priceSetValueIDs = [];
1600 foreach ($priceSetParams as $priceSetParam) {
1601 foreach (array_keys($priceSetParam) as $priceValueID) {
1602 $priceSetValueIDs[] = $priceValueID;
1605 return $priceSetValueIDs;
1609 * Get the price set value IDs from a set of parameters
1611 * @param array $params
1614 * Array of price fields filtered from the params.
1616 public static function parsePriceSetArrayFromParams($params) {
1617 $priceSetParams = [];
1618 foreach ($params as $field => $value) {
1619 $parts = explode('_', $field);
1620 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
1621 $priceSetParams[$field] = $value;
1624 return $priceSetParams;
1628 * Get non-deductible amount from price options
1630 * @param int $priceSetId
1631 * @param array $lineItem
1634 * calculated non-deductible amount.
1636 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1637 $nonDeductibleAmount = 0;
1638 if (!empty($lineItem[$priceSetId])) {
1639 foreach ($lineItem[$priceSetId] as $options) {
1640 $nonDeductibleAmount +
= $options['non_deductible_amount'] * $options['qty'];
1644 return $nonDeductibleAmount;
1648 * Get an array of all forms using a given price set.
1653 * Pages using the price set, keyed by type. e.g
1655 * 'civicrm_contribution_page' => array(2,5,6),
1656 * 'civicrm_event' => array(5,6),
1657 * 'civicrm_event_template' => array(7),
1660 public static function getFormsUsingPriceSet($id) {
1663 SELECT entity_table, entity_id
1664 FROM civicrm_price_set_entity
1665 WHERE price_set_id = %1";
1666 $params = [1 => [$id, 'Integer']];
1667 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1669 while ($crmFormDAO->fetch()) {
1670 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
1676 * @param array $forms
1677 * Array of forms that use a price set keyed by entity. e.g
1679 * 'civicrm_contribution_page' => array(2,5,6),
1680 * 'civicrm_event' => array(5,6),
1681 * 'civicrm_event_template' => array(7),
1685 * Array of entities suppliemented with per entity information.
1687 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1689 * @throws \Exception
1691 protected static function reformatUsedByFormsWithEntityData($forms) {
1693 foreach ($forms as $table => $entities) {
1695 case 'civicrm_event':
1696 $ids = implode(',', $entities);
1697 $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
1698 FROM civicrm_event ce
1699 LEFT JOIN civicrm_option_value ON
1700 ( ce.event_type_id = civicrm_option_value.value )
1701 LEFT JOIN civicrm_option_group ON
1702 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1704 civicrm_option_group.name = 'event_type' AND
1707 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1708 while ($crmDAO->fetch()) {
1709 if ($crmDAO->isTemplate
) {
1710 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
1711 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1712 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1715 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1716 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1717 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1718 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1719 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1724 case 'civicrm_contribution_page':
1725 $ids = implode(',', $entities);
1726 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1727 FROM civicrm_contribution_page cp, civicrm_financial_type ct
1728 WHERE ct.id = cp.financial_type_id AND
1731 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1732 while ($crmDAO->fetch()) {
1733 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1734 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
1735 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1736 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1740 case 'civicrm_contribution':
1741 case 'civicrm_membership':
1742 case 'civicrm_participant':
1743 $usedBy[$table] = 1;
1747 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");