3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * Business object for managing price sets.
38 class CRM_Price_BAO_PriceSet
extends CRM_Price_DAO_PriceSet
{
41 * Static field for default price set details.
45 public static $_defaultPriceSet = NULL;
50 public function __construct() {
51 parent
::__construct();
55 * Takes an associative array and creates a price set object.
57 * @param array $params
58 * (reference) an assoc array of name/value pairs.
60 * @return CRM_Price_DAO_PriceSet
62 public static function create(&$params) {
63 if (empty($params['id']) && empty($params['name'])) {
64 $params['name'] = CRM_Utils_String
::munge($params['title'], '_', 242);
67 $validatePriceSet = TRUE;
68 if (!empty($params['extends']) && is_array($params['extends'])) {
69 if (!array_key_exists(CRM_Core_Component
::getComponentID('CiviEvent'), $params['extends'])
70 ||
!array_key_exists(CRM_Core_Component
::getComponentID('CiviMember'), $params['extends'])
72 $validatePriceSet = FALSE;
74 $params['extends'] = CRM_Utils_Array
::implodePadded($params['extends']);
77 $priceSetID = CRM_Utils_Array
::value('id', $params);
79 $priceSetBAO = new CRM_Price_BAO_PriceSet();
80 $priceSetBAO->copyValues($params);
81 if (self
::eventPriceSetDomainID()) {
82 $priceSetBAO->domain_id
= CRM_Core_Config
::domainID();
84 return $priceSetBAO->save();
88 * Fetch object based on array of properties.
90 * @param array $params
91 * (reference ) an assoc array of name/value pairs.
92 * @param array $defaults
93 * (reference ) an assoc array to hold the flattened values.
95 * @return CRM_Price_DAO_PriceSet
97 public static function retrieve(&$params, &$defaults) {
98 return CRM_Core_DAO
::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
102 * Update the is_active flag in the db.
105 * Id of the database record.
109 * true if we found and updated the object, else false
111 public static function setIsActive($id, $isActive) {
112 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
116 * Calculate the default price set id
117 * assigned to the contribution/membership etc
119 * @param string $entity
125 public static function getDefaultPriceSet($entity = 'contribution') {
126 if (!empty(self
::$_defaultPriceSet[$entity])) {
127 return self
::$_defaultPriceSet[$entity];
129 $entityName = 'default_contribution_amount';
130 if ($entity == 'membership') {
131 $entityName = 'default_membership_type_amount';
135 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
136 FROM civicrm_price_set ps
137 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
138 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
139 WHERE ps.name = '{$entityName}'
142 $dao = CRM_Core_DAO
::executeQuery($sql);
143 self
::$_defaultPriceSet[$entity] = [];
144 while ($dao->fetch()) {
145 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = [
146 'setID' => $dao->setID
,
147 'priceFieldID' => $dao->priceFieldID
,
148 'name' => $dao->name
,
149 'label' => $dao->label
,
150 'priceFieldValueID' => $dao->priceFieldValueID
,
151 'membership_type_id' => $dao->membership_type_id
,
152 'amount' => $dao->amount
,
153 'financial_type_id' => $dao->financial_type_id
,
157 return self
::$_defaultPriceSet[$entity];
161 * Get the price set title.
170 public static function getTitle($id) {
171 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
175 * Return a list of all forms which use this price set.
179 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
183 public static function getUsedBy($id, $simpleReturn = FALSE) {
185 $forms = self
::getFormsUsingPriceSet($id);
186 $tables = array_keys($forms);
187 // @todo - this is really clumsy overloading the signature like this. Instead
188 // move towards having a function that does not call reformatUsedByFormsWithEntityData
189 // and call that when that data is not used.
190 if ($simpleReturn == 'table') {
193 // @todo - this is painfully slow in some cases.
196 SELECT cli.entity_table, cli.entity_id
197 FROM civicrm_line_item cli
198 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
199 WHERE cpf.price_set_id = %1";
200 $params = [1 => [$id, 'Integer']];
201 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
202 while ($crmFormDAO->fetch()) {
203 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
204 $tables[] = $crmFormDAO->entity_table
;
210 // @todo - this is really clumsy overloading the signature like this. See above.
211 if ($simpleReturn == 'entity') {
214 $usedBy = self
::reformatUsedByFormsWithEntityData($forms, $usedBy);
220 * Delete the price set, including the fields.
226 * false if fields exist for this set, true if the
227 * set could be deleted
230 public static function deleteSet($id) {
231 // delete price fields
232 $priceField = new CRM_Price_DAO_PriceField();
233 $priceField->price_set_id
= $id;
235 while ($priceField->fetch()) {
236 // delete options first
237 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
240 $set = new CRM_Price_DAO_PriceSet();
242 return $set->delete();
246 * Link the price set with the specified table and id.
248 * @param string $entityTable
249 * @param int $entityId
250 * @param int $priceSetId
254 public static function addTo($entityTable, $entityId, $priceSetId) {
255 // verify that the price set exists
256 $dao = new CRM_Price_DAO_PriceSet();
257 $dao->id
= $priceSetId;
263 $dao = new CRM_Price_DAO_PriceSetEntity();
264 // find if this already exists
265 $dao->entity_id
= $entityId;
266 $dao->entity_table
= $entityTable;
269 // add or update price_set_id
270 $dao->price_set_id
= $priceSetId;
275 * Delete price set for the given entity and id.
277 * @param string $entityTable
278 * @param int $entityId
282 public static function removeFrom($entityTable, $entityId) {
283 $dao = new CRM_Price_DAO_PriceSetEntity();
284 $dao->entity_table
= $entityTable;
285 $dao->entity_id
= $entityId;
286 return $dao->delete();
290 * Find a price_set_id associated with the given table, id and usedFor
291 * Used For value for events:1, contribution:2, membership:3
293 * @param string $entityTable
294 * @param int $entityId
295 * @param int $usedFor
296 * ( price set that extends/used for particular component ).
298 * @param null $isQuickConfig
299 * @param null $setName
302 * price_set_id, or false if none found
304 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
305 if (!$entityTable ||
!$entityId) {
309 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
310 FROM civicrm_price_set ps
311 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
312 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
313 if ($isQuickConfig) {
314 $sql .= ' AND ps.is_quick_config = 0 ';
317 1 => [$entityTable, 'String'],
318 2 => [$entityId, 'Integer'],
321 $sql .= " AND ps.extends LIKE '%%3%' ";
322 $params[3] = [$usedFor, 'Integer'];
325 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
327 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
328 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
332 * Find a price_set_id associated with the given option value or field ID.
334 * @param array $params
335 * (reference) an assoc array of name/value pairs.
336 * array may contain either option id or
340 * price set id on success, null otherwise
342 public static function getSetId(&$params) {
345 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
346 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
347 $fieldValue->id
= $oid;
348 if ($fieldValue->find(TRUE)) {
349 $fid = $fieldValue->price_field_id
;
353 $fid = CRM_Utils_Array
::value('fid', $params);
357 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
364 * Return an associative array of all price sets.
366 * @param bool $withInactive
367 * Whether or not to include inactive entries.
368 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
369 * @param string $column name of the column.
372 * associative array of id => name
374 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
377 DISTINCT ( price_set_id ) as id, s.{$column}
380 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
381 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
383 is_quick_config = 0 ";
385 if (!$withInactive) {
386 $query .= ' AND s.is_active = 1 ';
389 if (self
::eventPriceSetDomainID()) {
390 $query .= ' AND s.domain_id = ' . CRM_Core_Config
::domainID();
395 if ($extendComponentName) {
396 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
400 $query .= " AND s.extends LIKE '%$componentId%' ";
402 // Check permissioned financial types
403 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialType, CRM_Core_Action
::ADD
);
404 if ($financialType) {
405 $types = implode(',', array_keys($financialType));
406 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
409 // Do not display any price sets
412 $query .= " GROUP BY s.id";
413 $dao = CRM_Core_DAO
::executeQuery($query);
414 while ($dao->fetch()) {
415 $priceSets[$dao->id
] = $dao->$column;
421 * Get price set details.
423 * An array containing price set details (including price fields) is returned
427 * @param bool $required
428 * Appears to have no effect based on reading the code.
429 * @param bool $validOnly
430 * Should only fields where today's date falls within the valid range be returned?
433 * Array consisting of field details
435 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
448 'is_display_amounts',
457 if ($required == TRUE) {
458 $priceFields[] = 'is_required';
462 $select = 'SELECT ' . implode(',', $priceFields);
463 $from = ' FROM civicrm_price_field';
466 1 => [$setID, 'Integer'],
468 $currentTime = date('YmdHis');
470 WHERE price_set_id = %1
472 AND ( active_on IS NULL OR active_on <= {$currentTime} )
477 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
481 $orderBy = ' ORDER BY weight';
483 $sql = $select . $from . $where . $dateSelect . $orderBy;
485 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
487 $isDefaultContributionPriceSet = FALSE;
488 if ('default_contribution_amount' == CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
489 $isDefaultContributionPriceSet = TRUE;
492 $visibility = CRM_Core_PseudoConstant
::visibility('name');
493 while ($dao->fetch()) {
496 $setTree[$setID]['fields'][$fieldID] = [];
497 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
499 foreach ($priceFields as $field) {
500 if ($field == 'id' ||
is_null($dao->$field)) {
504 if ($field == 'visibility_id') {
505 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
507 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
509 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
512 // also get the pre and post help from this price set
514 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
515 FROM civicrm_price_set
517 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
519 $setTree[$setID]['extends'] = $dao->extends;
520 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
521 $setTree[$setID]['help_pre'] = $dao->help_pre
;
522 $setTree[$setID]['help_post'] = $dao->help_post
;
523 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
524 $setTree[$setID]['min_amount'] = $dao->min_amount
;
530 * Get the Price Field ID.
532 * We call this function when more than one being present would represent an error
533 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
534 * @param array $priceSet
536 * @throws CRM_Core_Exception
539 public static function getOnlyPriceFieldID(array $priceSet) {
540 if (count($priceSet['fields']) > 1) {
541 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
543 return (int) implode('_', array_keys($priceSet['fields']));
547 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
548 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
549 * @param array $priceSet
551 * @throws CRM_Core_Exception
554 public static function getOnlyPriceFieldValueID(array $priceSet) {
555 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
556 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
557 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
559 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
563 * Initiate price set such that various non-BAO things are set on the form.
565 * This function is not really a BAO function so the location is misleading.
567 * @param CRM_Core_Form $form
570 * @param string $entityTable
571 * @param bool $validOnly
572 * @param int $priceSetId
575 * @return bool|false|int|null
577 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
579 $priceSetId = self
::getFor($entityTable, $id);
582 //check if price set is is_config
583 if (is_numeric($priceSetId)) {
584 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
585 $form->assign('quickConfig', 1);
590 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
591 $entityId = $entity = NULL;
593 switch ($entityTable) {
594 case 'civicrm_event':
595 $entity = 'participant';
596 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
597 $entityId = $form->_id
;
600 $entityId = $form->_participantId
;
604 case 'civicrm_contribution_page':
605 case 'civicrm_contribution':
606 $entity = 'contribution';
607 $entityId = $form->_id
;
611 if ($entityId && $entity) {
612 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
620 $form->_priceSetId
= $priceSetId;
621 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
622 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
623 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
625 //get the price set fields participant count.
626 if ($entityTable == 'civicrm_event') {
627 //get option count info.
628 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
629 if ($form->_priceSet
['optionsCountTotal']) {
630 $optionsCountDetails = [];
631 if (!empty($form->_priceSet
['fields'])) {
632 foreach ($form->_priceSet
['fields'] as $field) {
633 foreach ($field['options'] as $option) {
634 $count = CRM_Utils_Array
::value('count', $option, 0);
635 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
639 $form->_priceSet
['optionsCountDetails'] = $optionsCountDetails;
642 //get option max value info.
643 $optionsMaxValueTotal = 0;
644 $optionsMaxValueDetails = [];
646 if (!empty($form->_priceSet
['fields'])) {
647 foreach ($form->_priceSet
['fields'] as $field) {
648 foreach ($field['options'] as $option) {
649 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
650 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
651 $optionsMaxValueTotal +
= $maxVal;
656 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
657 if ($optionsMaxValueTotal) {
658 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
661 $form->set('priceSetId', $form->_priceSetId
);
662 $form->set('priceSet', $form->_priceSet
);
670 * Get line item purchase information.
672 * This function takes the input parameters and interprets out of it what has been purchased.
675 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
676 * And, it would make sense to introduce caching into that function and call it from here rather than
677 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
678 * @param array $params
679 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
681 * Line item array to be altered.
682 * @param string $component
683 * This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
684 * (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
685 * @param int $priceSetID
687 public static function processAmount($fields, &$params, &$lineItem, $component = '', $priceSetID = NULL) {
689 $totalPrice = $totalTax = 0;
690 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
691 // This is notably the case with memberships and we need to put this amount
692 // on the line item rather than the calculated amount.
693 // This seems to only affect radio link items as that is the use case for the 'quick config'
694 // set up (which allows a free form field).
695 $amount_override = NULL;
699 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
702 $priceFields = self
::filterPriceFieldsFromParams($priceSetID, $params);
703 if (count($priceFields) == 1) {
704 $amount_override = CRM_Utils_Array
::value('partial_payment_total', $params, CRM_Utils_Array
::value('total_amount', $params));
707 foreach ($fields as $id => $field) {
708 if (empty($params["price_{$id}"]) ||
709 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
711 // skip if nothing was submitted for this field
715 switch ($field['html_type']) {
717 $firstOption = reset($field['options']);
718 $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
719 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
720 $optionValueId = key($field['options']);
722 if (CRM_Utils_Array
::value('name', $field['options'][$optionValueId]) == 'contribution_amount') {
723 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
724 if (array_key_exists($params['financial_type_id'], $taxRates)) {
725 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
726 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
727 $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
730 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
731 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
733 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
737 //special case if user select -none-
738 if ($params["price_{$id}"] <= 0) {
741 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
742 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
744 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, $amount_override);
745 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
746 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
747 if ($amount_override) {
748 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
751 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
754 // auto_renew exists and is empty in some workflows, which php treat as a 0
755 // and hence we explicitly check to see if auto_renew is numeric
756 isset($lineItem[$optionValueId]['auto_renew']) &&
757 is_numeric($lineItem[$optionValueId]['auto_renew'])
759 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
764 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
765 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
767 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
768 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
769 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
771 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
774 isset($lineItem[$optionValueId]['auto_renew']) &&
775 is_numeric($lineItem[$optionValueId]['auto_renew'])
777 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
783 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
784 foreach ($params["price_{$id}"] as $optionId => $option) {
785 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
786 $lineItem = self
::setLineItem($field, $lineItem, $optionId, $totalTax);
788 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
791 isset($lineItem[$optionId]['auto_renew']) &&
792 is_numeric($lineItem[$optionId]['auto_renew'])
794 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
802 $totalParticipant = 0;
803 if (is_array($lineItem)) {
804 foreach ($lineItem as $values) {
805 $totalParticipant +
= $values['participant_count'];
806 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
807 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
810 // However, because the quick config concept existed all sorts of logic was hung off it
811 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
812 // is always set at the functional level. In this case we are dealing with the default 'quick config'
813 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
814 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
817 // But, in the interests of being careful when capacity is low - avoiding the known default value
819 // Crucially a test has been added so a better solution can be implemented later with some comfort.
820 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
821 if ($values['label'] != ts('Contribution Amount')) {
822 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
827 $displayParticipantCount = '';
828 if ($totalParticipant > 0) {
829 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
831 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
832 if (!empty($amount_level)) {
833 $params['amount_level'] = CRM_Utils_Array
::implodePadded($amount_level);
834 if (!empty($displayParticipantCount)) {
835 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
839 $params['amount'] = $totalPrice;
840 $params['tax_amount'] = $totalTax;
842 foreach ($autoRenew as $dontCare => $eachAmount) {
844 unset($autoRenew[$dontCare]);
847 if (count($autoRenew) > 1) {
848 $params['autoRenew'] = $autoRenew;
854 * Get the text to record for amount level.
856 * @param array $params
857 * Submitted parameters
858 * - priceSetId is required to be set in the calling function
859 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
860 * default one & this function asks that be set if it is the case).
863 * Text for civicrm_contribution.amount_level field.
865 public static function getAmountLevelText($params) {
866 $priceSetID = $params['priceSetId'];
867 $priceFieldSelection = self
::filterPriceFieldsFromParams($priceSetID, $params);
868 $priceFieldMetadata = self
::getCachedPriceSetDetail($priceSetID);
869 $displayParticipantCount = NULL;
872 foreach ($priceFieldMetadata['fields'] as $field) {
873 if (!empty($priceFieldSelection[$field['id']])) {
875 if ($field['is_enter_qty']) {
876 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
878 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
879 // ie. it represents the default price field for a contribution. Another approach would be not
880 // to give it a label if we don't want it to show.
881 if ($field['label'] != ts('Contribution Amount')) {
882 $amount_level[] = $field['label'] . $qtyString;
886 return CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
890 * Get the fields relevant to the price field from the parameters.
892 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
894 * @param int $priceSetID
895 * @param array $params
898 * Price fields found in the params array
900 public static function filterPriceFieldsFromParams($priceSetID, $params) {
901 $priceSet = self
::getCachedPriceSetDetail($priceSetID);
903 foreach ($priceSet['fields'] as $field) {
904 if (!empty($params['price_' . $field['id']])) {
905 $return[$field['id']] = $params['price_' . $field['id']];
912 * Wrapper for getSetDetail with caching.
914 * We seem to be passing this array around in a painful way - presumably to avoid the hit
915 * of loading it - so lets make it callable with caching.
917 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
918 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
919 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
920 * think less about the price sets.
922 * @param int $priceSetID
926 public static function getCachedPriceSetDetail($priceSetID) {
927 $cacheKey = __CLASS__
. __FUNCTION__
. '_' . $priceSetID;
928 $cache = CRM_Utils_Cache
::singleton();
929 $values = $cache->get($cacheKey);
930 if (empty($values)) {
931 $data = self
::getSetDetail($priceSetID);
932 $values = $data[$priceSetID];
933 $cache->set($cacheKey, $values);
939 * Build the price set form.
941 * @param CRM_Core_Form $form
945 public static function buildPriceSet(&$form) {
946 $priceSetId = $form->get('priceSetId');
951 $validFieldsOnly = TRUE;
952 $className = CRM_Utils_System
::getClassName($form);
953 if (in_array($className, [
954 'CRM_Contribute_Form_Contribution',
955 'CRM_Member_Form_Membership',
957 $validFieldsOnly = FALSE;
960 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
961 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
962 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
963 $form->_quickConfig
= $quickConfig = 0;
964 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
968 $form->assign('quickConfig', $quickConfig);
969 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
970 $form->_quickConfig
= $quickConfig;
973 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
974 if (!empty($form->_membershipTypeValues
) && is_array($form->_membershipTypeValues
)) {
975 $autoRenewMembershipTypes = [];
976 foreach ($form->_membershipTypeValues
as $membershiptTypeValue) {
977 if ($membershiptTypeValue['auto_renew']) {
978 $autoRenewMembershipTypes[] = $membershiptTypeValue['id'];
981 foreach ($form->_priceSet
['fields'] as $field) {
982 if (array_key_exists('options', $field) && is_array($field['options'])) {
983 foreach ($field['options'] as $option) {
984 if (!empty($option['membership_type_id'])) {
985 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
986 $form->_priceSet
['auto_renew_membership_field'] = $field['id'];
987 // Only one field can offer auto_renew memberships, so break here.
995 $form->assign('priceSet', $form->_priceSet
);
997 $component = 'contribution';
998 if ($className == 'CRM_Member_Form_Membership') {
999 $component = 'membership';
1002 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
1003 $feeBlock = &$form->_values
['fee'];
1004 if (!empty($form->_useForMember
)) {
1005 $component = 'membership';
1009 $feeBlock = &$form->_priceSet
['fields'];
1011 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1012 foreach ($feeBlock as $key => $value) {
1013 foreach ($value['options'] as $k => $options) {
1014 if (!CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($options['financial_type_id']))) {
1015 unset($feeBlock[$key]['options'][$k]);
1018 if (empty($feeBlock[$key]['options'])) {
1019 unset($feeBlock[$key]);
1024 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
1026 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
1027 $adminFieldVisible = FALSE;
1028 if (CRM_Core_Permission
::check('administer CiviCRM')) {
1029 $adminFieldVisible = TRUE;
1032 $hideAdminValues = TRUE;
1033 if (CRM_Core_Permission
::check('edit contributions')) {
1034 $hideAdminValues = FALSE;
1037 foreach ($feeBlock as $id => $field) {
1038 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
1039 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
1042 $options = CRM_Utils_Array
::value('options', $field);
1043 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
1044 $userid = $form->getVar('_membershipContactID');
1045 $checklifetime = self
::checkCurrentMembership($options, $userid);
1046 if ($checklifetime) {
1047 $form->assign('ispricelifetime', TRUE);
1051 $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
1053 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
1056 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
1057 foreach ($options as $key => $currentOption) {
1058 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField
::getVisibilityOptionID('admin')) {
1059 unset($options[$key]);
1063 if (!empty($options)) {
1064 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
1065 'price_' . $field['id'],
1068 CRM_Utils_Array
::value('is_required', $field, FALSE),
1078 * Check the current Membership having end date null.
1080 * @param array $options
1081 * @param int $userid
1082 * Probably actually contact ID.
1086 public static function checkCurrentMembership(&$options, $userid) {
1087 if (!$userid ||
empty($options)) {
1090 static $_contact_memberships = [];
1091 $checkLifetime = FALSE;
1092 foreach ($options as $key => $value) {
1093 if (!empty($value['membership_type_id'])) {
1094 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
1095 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
1097 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
1098 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
1099 unset($options[$key]);
1100 $checkLifetime = TRUE;
1104 if ($checkLifetime) {
1113 * Set daefult the price set fields.
1115 * @param CRM_Core_Form $form
1120 public static function setDefaultPriceSet(&$form, &$defaults) {
1121 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1125 foreach ($form->_priceSet
['fields'] as $val) {
1126 foreach ($val['options'] as $keys => $values) {
1127 // build price field index which is passed via URL
1128 // url format will be appended by "&price_5=11"
1129 $priceFieldName = 'price_' . $values['price_field_id'];
1130 $priceFieldValue = self
::getPriceFieldValueFromURL($form, $priceFieldName);
1131 if (!empty($priceFieldValue)) {
1132 self
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
1133 // break here to prevent overwriting of default due to 'is_default'
1134 // option configuration. The value sent via URL get's higher priority.
1137 elseif ($values['is_default']) {
1138 self
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
1146 * Get the value of price field if passed via url
1148 * @param string $priceFieldName
1149 * @param string $priceFieldValue
1150 * @param string $priceFieldType
1151 * @param array $defaults
1155 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
1156 if ($priceFieldType == 'CheckBox') {
1157 $defaults[$priceFieldName][$priceFieldValue] = 1;
1160 $defaults[$priceFieldName] = $priceFieldValue;
1165 * Get the value of price field if passed via url
1167 * @param CRM_Core_Form $form
1168 * @param string $priceFieldName
1170 * @return mixed $priceFieldValue
1172 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
1173 $priceFieldValue = CRM_Utils_Request
::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
1174 if (!empty($priceFieldValue)) {
1175 return $priceFieldValue;
1180 * Supports event create function by setting up required price sets, not tested but expect
1181 * it will work for contribution page
1182 * @param array $params
1183 * As passed to api/bao create fn.
1184 * @param CRM_Core_DAO $entity
1185 * Object for given entity.
1186 * @param string $entityName
1187 * Name of entity - e.g event.
1189 public static function setPriceSets(&$params, $entity, $entityName) {
1190 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1193 // CRM-14069 note that we may as well start by assuming more than one.
1194 // currently the form does not pass in as an array & will be skipped
1195 // test is passing in as an array but I feel the api should have a metadata that allows
1196 // transform of single to array - seems good for managing transitions - in which case all api
1197 // calls that set price_set_id will hit this
1198 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1199 // all separated values, strings, json half-separated values (in participant we hit this)
1200 // to be converted to json @ api layer
1201 $pse = new CRM_Price_DAO_PriceSetEntity();
1202 $pse->entity_table
= 'civicrm_' . $entityName;
1203 $pse->entity_id
= $entity->id
;
1204 while ($pse->fetch()) {
1205 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1206 // note an even more aggressive form of this deletion currently happens in event form
1207 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1208 // on the participant record
1209 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1210 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1214 foreach ($params['price_set_id'] as $priceSetID) {
1215 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1216 //@todo - how should we do this - copied from form
1217 //if (!empty($params['price_field_id'])) {
1218 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1219 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1225 * Get field ids of a price set.
1231 * Array of the field ids
1234 public static function getFieldIds($id) {
1235 $priceField = new CRM_Price_DAO_PriceField();
1236 $priceField->price_set_id
= $id;
1237 $priceField->find();
1238 while ($priceField->fetch()) {
1239 $var[] = $priceField->id
;
1245 * Copy a price set, including all the fields
1248 * The price set id to copy.
1250 * @return CRM_Price_DAO_PriceSet
1252 public static function copy($id) {
1253 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1254 $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
1256 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
1257 $title = ts('[Copy id %1]', [1 => $maxId +
1]);
1260 'title' => trim($newTitle) . ' ' . $title,
1261 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId +
1),
1265 $copy = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1271 //copying all the blocks pertaining to the price set
1272 $copyPriceField = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1273 ['price_set_id' => $id],
1274 ['price_set_id' => $copy->id
]
1276 if (!empty($copyPriceField)) {
1277 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1279 //copy option group and values
1280 foreach ($price as $originalId => $copyId) {
1281 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1282 ['price_field_id' => $originalId],
1283 ['price_field_id' => $copyId]
1289 CRM_Utils_Hook
::copy('Set', $copy);
1294 * check price set permission.
1301 public static function checkPermission($sid) {
1302 if ($sid && self
::eventPriceSetDomainID()) {
1303 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1304 if (CRM_Core_Config
::domainID() != $domain_id) {
1305 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1312 * Get the sum of participant count
1313 * for all fields of given price set.
1318 * @param bool $onlyActive
1320 * @return int|null|string
1322 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1330 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1333 static $pricesetFieldCount = [];
1334 if (!isset($pricesetFieldCount[$sid])) {
1336 SELECT sum(value.count) as totalCount
1337 FROM civicrm_price_field_value value
1338 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1339 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1343 $count = CRM_Core_DAO
::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
1344 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1347 return $pricesetFieldCount[$sid];
1355 public static function getMembershipCount($ids) {
1357 SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
1358 FROM civicrm_price_field_value pfv
1359 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1360 WHERE pfv.id IN ( $ids )
1361 GROUP BY mt.member_of_contact_id ";
1363 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1366 while ($crmDAO->fetch()) {
1367 $count[$crmDAO->id
] = $crmDAO->count
;
1374 * Check if auto renew option should be shown.
1376 * The auto-renew option should be visible if membership types associated with all the fields has
1377 * been set for auto-renew option.
1379 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1381 * @param int $priceSetId
1385 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1387 public static function checkAutoRenewForPriceSet($priceSetId) {
1388 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1389 pf.html_type, pf.id as price_field_id
1390 FROM civicrm_price_field_value pfv
1391 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1392 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1393 WHERE pf.price_set_id = %1
1394 AND pf.is_active = 1
1395 AND pfv.is_active = 1
1396 ORDER BY price_field_id';
1398 $params = [1 => [$priceSetId, 'Integer']];
1400 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1402 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1403 //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.
1408 $autoRenewOption = 2;
1410 while ($dao->fetch()) {
1411 if (!$dao->auto_renew
) {
1412 // If any one can't be renewed none can.
1415 if ($dao->auto_renew
== 1) {
1416 $autoRenewOption = 1;
1419 if ($dao->html_type
== 'Checkbox' && !in_array($dao->duration_interval
. $dao->duration_unit
, $priceFields[$dao->price_field_id
])) {
1420 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1421 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1424 $priceFields[$dao->price_field_id
][] = $dao->duration_interval
. $dao->duration_unit
;
1425 foreach ($priceFields as $priceFieldID => $durations) {
1426 if ($priceFieldID != $dao->price_field_id
&& !in_array($dao->duration_interval
. $dao->duration_unit
, $durations)) {
1427 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1433 return $autoRenewOption;
1437 * Retrieve auto renew frequency and interval.
1439 * @param int $priceSetId
1443 * associate array of frequency interval and unit
1445 public static function getRecurDetails($priceSetId) {
1446 $query = 'SELECT mt.duration_interval, mt.duration_unit
1447 FROM civicrm_price_field_value pfv
1448 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1449 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1450 WHERE pf.price_set_id = %1 LIMIT 1';
1452 $params = [1 => [$priceSetId, 'Integer']];
1453 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1455 return [$dao->duration_interval
, $dao->duration_unit
];
1461 public static function eventPriceSetDomainID() {
1462 return Civi
::settings()->get('event_price_set_domain_id');
1466 * Update the is_quick_config flag in the db.
1469 * Id of the database record.
1470 * @param bool $isQuickConfig we want to set the is_quick_config field.
1471 * Value we want to set the is_quick_config field.
1474 * true if we found and updated the object, else false
1476 public static function setIsQuickConfig($id, $isQuickConfig) {
1477 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1481 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1487 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1488 $membershipTypes = self
::getMembershipTypesFromPriceSet($id);
1489 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1496 * Get an array of the membership types in a price set.
1501 * Membership types in the price set
1503 public static function getMembershipTypesFromPriceSet($id) {
1505 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1506 FROM civicrm_price_field_value pfv
1507 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1508 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1509 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1513 $params = [1 => [$id, 'Integer']];
1514 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1516 $membershipTypes = [
1519 'autorenew_required' => [],
1520 'autorenew_optional' => [],
1522 while ($dao->fetch()) {
1523 if (empty($dao->membership_type_id
)) {
1526 $membershipTypes['all'][] = $dao->membership_type_id
;
1527 if (!empty($dao->auto_renew
)) {
1528 $membershipTypes['autorenew'][] = $dao->membership_type_id
;
1529 if ($dao->auto_renew
== 2) {
1530 $membershipTypes['autorenew_required'][] = $dao->membership_type_id
;
1533 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id
;
1537 $membershipTypes['non_renew'][] = $dao->membership_type_id
;
1540 return $membershipTypes;
1544 * Copy priceSet when event/contibution page is copied
1546 * @param string $baoName
1549 * Old event/contribution page id.
1551 * Newly created event/contribution page id.
1553 public static function copyPriceSet($baoName, $id, $newId) {
1554 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1556 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1557 if ($isQuickConfig) {
1558 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1559 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1562 $copyPriceSet = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1565 'entity_table' => $baoName,
1567 ['entity_id' => $newId]
1570 // copy event discount
1571 if ($baoName == 'civicrm_event') {
1572 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1573 foreach ($discount as $discountId => $setId) {
1575 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1577 CRM_Core_DAO
::copyGeneric(
1578 'CRM_Core_DAO_Discount',
1580 'id' => $discountId,
1583 'entity_id' => $newId,
1584 'price_set_id' => $copyPriceSet->id
,
1593 * Function to set tax_amount and tax_rate in LineItem.
1595 * @param array $field
1596 * @param array $lineItem
1597 * @param int $optionValueId
1598 * @param float $totalTax
1602 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
1603 // Here we round - i.e. after multiplying by quantity
1604 if ($field['html_type'] == 'Text') {
1605 $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
1608 $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
1610 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1611 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1612 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1613 $totalTax +
= $taxAmount;
1618 * Get the first price set value IDs from a parameters array.
1620 * In practice this is really used when we only expect one to exist.
1622 * @param array $params
1625 * Array of the ids of the price set values.
1627 public static function parseFirstPriceSetValueIDFromParams($params) {
1628 $priceSetValueIDs = self
::parsePriceSetValueIDsFromParams($params);
1629 return reset($priceSetValueIDs);
1633 * Get the price set value IDs from a set of parameters
1635 * @param array $params
1638 * Array of the ids of the price set values.
1640 public static function parsePriceSetValueIDsFromParams($params) {
1641 $priceSetParams = self
::parsePriceSetArrayFromParams($params);
1642 $priceSetValueIDs = [];
1643 foreach ($priceSetParams as $priceSetParam) {
1644 foreach (array_keys($priceSetParam) as $priceValueID) {
1645 $priceSetValueIDs[] = $priceValueID;
1648 return $priceSetValueIDs;
1652 * Get the price set value IDs from a set of parameters
1654 * @param array $params
1657 * Array of price fields filtered from the params.
1659 public static function parsePriceSetArrayFromParams($params) {
1660 $priceSetParams = [];
1661 foreach ($params as $field => $value) {
1662 $parts = explode('_', $field);
1663 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
1664 $priceSetParams[$field] = $value;
1667 return $priceSetParams;
1671 * Get non-deductible amount from price options
1673 * @param int $priceSetId
1674 * @param array $lineItem
1677 * calculated non-deductible amount.
1679 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1680 $nonDeductibleAmount = 0;
1681 if (!empty($lineItem[$priceSetId])) {
1682 foreach ($lineItem[$priceSetId] as $options) {
1683 $nonDeductibleAmount +
= $options['non_deductible_amount'] * $options['qty'];
1687 return $nonDeductibleAmount;
1691 * Get an array of all forms using a given price set.
1696 * Pages using the price set, keyed by type. e.g
1698 * 'civicrm_contribution_page' => array(2,5,6),
1699 * 'civicrm_event' => array(5,6),
1700 * 'civicrm_event_template' => array(7),
1703 public static function getFormsUsingPriceSet($id) {
1706 SELECT entity_table, entity_id
1707 FROM civicrm_price_set_entity
1708 WHERE price_set_id = %1";
1709 $params = [1 => [$id, 'Integer']];
1710 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1712 while ($crmFormDAO->fetch()) {
1713 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
1719 * @param array $forms
1720 * Array of forms that use a price set keyed by entity. e.g
1722 * 'civicrm_contribution_page' => array(2,5,6),
1723 * 'civicrm_event' => array(5,6),
1724 * 'civicrm_event_template' => array(7),
1728 * Array of entities suppliemented with per entity information.
1730 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1732 * @throws \Exception
1734 protected static function reformatUsedByFormsWithEntityData($forms) {
1736 foreach ($forms as $table => $entities) {
1738 case 'civicrm_event':
1739 $ids = implode(',', $entities);
1740 $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
1741 FROM civicrm_event ce
1742 LEFT JOIN civicrm_option_value ON
1743 ( ce.event_type_id = civicrm_option_value.value )
1744 LEFT JOIN civicrm_option_group ON
1745 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1747 civicrm_option_group.name = 'event_type' AND
1750 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1751 while ($crmDAO->fetch()) {
1752 if ($crmDAO->isTemplate
) {
1753 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
1754 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1755 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1758 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1759 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1760 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1761 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1762 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1767 case 'civicrm_contribution_page':
1768 $ids = implode(',', $entities);
1769 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1770 FROM civicrm_contribution_page cp, civicrm_financial_type ct
1771 WHERE ct.id = cp.financial_type_id AND
1774 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1775 while ($crmDAO->fetch()) {
1776 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1777 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
1778 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1779 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1783 case 'civicrm_contribution':
1784 case 'civicrm_membership':
1785 case 'civicrm_participant':
1786 $usedBy[$table] = 1;
1790 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");