3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 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] = array();
144 while ($dao->fetch()) {
145 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
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 = array(1 => array($id, 'Integer'));
201 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
202 while ($crmFormDAO->fetch()) {
203 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
204 $tables[] = $crmFormDAO->entity_table
;
210 // @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 => array($entityTable, 'String'),
318 2 => array($entityId, 'Integer'),
321 $sql .= " AND ps.extends LIKE '%%3%' ";
322 $params[3] = array($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();
393 $priceSets = array();
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) {
439 $priceFields = array(
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 => array($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] = array();
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']));
564 * Initiate price set such that various non-BAO things are set on the form.
566 * This function is not really a BAO function so the location is misleading.
568 * @param CRM_Core_Form $form
571 * @param string $entityTable
572 * @param bool $validOnly
573 * @param int $priceSetId
576 * @return bool|false|int|null
578 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
580 $priceSetId = self
::getFor($entityTable, $id);
583 //check if price set is is_config
584 if (is_numeric($priceSetId)) {
585 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
586 $form->assign('quickConfig', 1);
591 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
592 $entityId = $entity = NULL;
594 switch ($entityTable) {
595 case 'civicrm_event':
596 $entity = 'participant';
597 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
598 $entityId = $form->_id
;
601 $entityId = $form->_participantId
;
605 case 'civicrm_contribution_page':
606 case 'civicrm_contribution':
607 $entity = 'contribution';
608 $entityId = $form->_id
;
612 if ($entityId && $entity) {
613 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
621 $form->_priceSetId
= $priceSetId;
622 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
623 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
624 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
626 //get the price set fields participant count.
627 if ($entityTable == 'civicrm_event') {
628 //get option count info.
629 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
630 if ($form->_priceSet
['optionsCountTotal']) {
631 $optionsCountDetails = array();
632 if (!empty($form->_priceSet
['fields'])) {
633 foreach ($form->_priceSet
['fields'] as $field) {
634 foreach ($field['options'] as $option) {
635 $count = CRM_Utils_Array
::value('count', $option, 0);
636 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
640 $form->_priceSet
['optionsCountDetails'] = $optionsCountDetails;
643 //get option max value info.
644 $optionsMaxValueTotal = 0;
645 $optionsMaxValueDetails = array();
647 if (!empty($form->_priceSet
['fields'])) {
648 foreach ($form->_priceSet
['fields'] as $field) {
649 foreach ($field['options'] as $option) {
650 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
651 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
652 $optionsMaxValueTotal +
= $maxVal;
657 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
658 if ($optionsMaxValueTotal) {
659 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
662 $form->set('priceSetId', $form->_priceSetId
);
663 $form->set('priceSet', $form->_priceSet
);
671 * Get line item purchase information.
673 * This function takes the input parameters and interprets out of it what has been purchased.
676 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
677 * And, it would make sense to introduce caching into that function and call it from here rather than
678 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
679 * @param array $params
680 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
682 * Line item array to be altered.
683 * @param string $component
684 * This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
685 * (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
686 * @param int $priceSetID
688 public static function processAmount($fields, &$params, &$lineItem, $component = '', $priceSetID = NULL) {
690 $totalPrice = $totalTax = 0;
691 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
692 // This is notably the case with memberships and we need to put this amount
693 // on the line item rather than the calculated amount.
694 // This seems to only affect radio link items as that is the use case for the 'quick config'
695 // set up (which allows a free form field).
696 $amount_override = NULL;
699 $autoRenew = array();
700 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
703 $priceFields = self
::filterPriceFieldsFromParams($priceSetID, $params);
704 if (count($priceFields) == 1) {
705 $amount_override = CRM_Utils_Array
::value('partial_payment_total', $params, CRM_Utils_Array
::value('total_amount', $params));
708 foreach ($fields as $id => $field) {
709 if (empty($params["price_{$id}"]) ||
710 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
712 // skip if nothing was submitted for this field
716 switch ($field['html_type']) {
718 $firstOption = reset($field['options']);
719 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
720 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
721 $optionValueId = key($field['options']);
723 if (CRM_Utils_Array
::value('name', $field['options'][$optionValueId]) == 'contribution_amount') {
724 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
725 if (array_key_exists($params['financial_type_id'], $taxRates)) {
726 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
727 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
728 $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
731 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
732 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
734 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
738 //special case if user select -none-
739 if ($params["price_{$id}"] <= 0) {
742 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
743 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
745 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, $amount_override);
746 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
747 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
748 if ($amount_override) {
749 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
752 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
755 // auto_renew exists and is empty in some workflows, which php treat as a 0
756 // and hence we explicitly check to see if auto_renew is numeric
757 isset($lineItem[$optionValueId]['auto_renew']) &&
758 is_numeric($lineItem[$optionValueId]['auto_renew'])
760 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
765 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
766 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
768 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
769 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
770 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
772 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
775 isset($lineItem[$optionValueId]['auto_renew']) &&
776 is_numeric($lineItem[$optionValueId]['auto_renew'])
778 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
784 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
785 foreach ($params["price_{$id}"] as $optionId => $option) {
786 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
787 $lineItem = self
::setLineItem($field, $lineItem, $optionId, $totalTax);
789 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
792 isset($lineItem[$optionId]['auto_renew']) &&
793 is_numeric($lineItem[$optionId]['auto_renew'])
795 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
802 $amount_level = array();
803 $totalParticipant = 0;
804 if (is_array($lineItem)) {
805 foreach ($lineItem as $values) {
806 $totalParticipant +
= $values['participant_count'];
807 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
808 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
811 // However, because the quick config concept existed all sorts of logic was hung off it
812 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
813 // is always set at the functional level. In this case we are dealing with the default 'quick config'
814 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
815 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
818 // But, in the interests of being careful when capacity is low - avoiding the known default value
820 // Crucially a test has been added so a better solution can be implemented later with some comfort.
821 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
822 if ($values['label'] != ts('Contribution Amount')) {
823 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
828 $displayParticipantCount = '';
829 if ($totalParticipant > 0) {
830 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
832 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
833 if (!empty($amount_level)) {
834 $params['amount_level'] = CRM_Utils_Array
::implodePadded($amount_level);
835 if (!empty($displayParticipantCount)) {
836 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
840 $params['amount'] = $totalPrice;
841 $params['tax_amount'] = $totalTax;
843 foreach ($autoRenew as $dontCare => $eachAmount) {
845 unset($autoRenew[$dontCare]);
848 if (count($autoRenew) > 1) {
849 $params['autoRenew'] = $autoRenew;
855 * Get the text to record for amount level.
857 * @param array $params
858 * Submitted parameters
859 * - priceSetId is required to be set in the calling function
860 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
861 * default one & this function asks that be set if it is the case).
864 * Text for civicrm_contribution.amount_level field.
866 public static function getAmountLevelText($params) {
867 $priceSetID = $params['priceSetId'];
868 $priceFieldSelection = self
::filterPriceFieldsFromParams($priceSetID, $params);
869 $priceFieldMetadata = self
::getCachedPriceSetDetail($priceSetID);
870 $displayParticipantCount = NULL;
872 $amount_level = array();
873 foreach ($priceFieldMetadata['fields'] as $field) {
874 if (!empty($priceFieldSelection[$field['id']])) {
876 if ($field['is_enter_qty']) {
877 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
879 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
880 // ie. it represents the default price field for a contribution. Another approach would be not
881 // to give it a label if we don't want it to show.
882 if ($field['label'] != ts('Contribution Amount')) {
883 $amount_level[] = $field['label'] . $qtyString;
887 return CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
891 * Get the fields relevant to the price field from the parameters.
893 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
895 * @param int $priceSetID
896 * @param array $params
899 * Price fields found in the params array
901 public static function filterPriceFieldsFromParams($priceSetID, $params) {
902 $priceSet = self
::getCachedPriceSetDetail($priceSetID);
904 foreach ($priceSet['fields'] as $field) {
905 if (!empty($params['price_' . $field['id']])) {
906 $return[$field['id']] = $params['price_' . $field['id']];
913 * Wrapper for getSetDetail with caching.
915 * We seem to be passing this array around in a painful way - presumably to avoid the hit
916 * of loading it - so lets make it callable with caching.
918 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
919 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
920 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
921 * think less about the price sets.
923 * @param int $priceSetID
927 public static function getCachedPriceSetDetail($priceSetID) {
928 $cacheKey = __CLASS__
. __FUNCTION__
. '_' . $priceSetID;
929 $cache = CRM_Utils_Cache
::singleton();
930 $values = $cache->get($cacheKey);
931 if (empty($values)) {
932 $data = self
::getSetDetail($priceSetID);
933 $values = $data[$priceSetID];
934 $cache->set($cacheKey, $values);
940 * Build the price set form.
942 * @param CRM_Core_Form $form
946 public static function buildPriceSet(&$form) {
947 $priceSetId = $form->get('priceSetId');
952 $validFieldsOnly = TRUE;
953 $className = CRM_Utils_System
::getClassName($form);
954 if (in_array($className, array(
955 'CRM_Contribute_Form_Contribution',
956 'CRM_Member_Form_Membership',
958 $validFieldsOnly = FALSE;
961 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
962 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
963 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
964 $form->_quickConfig
= $quickConfig = 0;
965 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
969 $form->assign('quickConfig', $quickConfig);
970 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
971 $form->_quickConfig
= $quickConfig;
974 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
975 if (!empty($form->_membershipTypeValues
) && is_array($form->_membershipTypeValues
)) {
976 $autoRenewMembershipTypes = array();
977 foreach ($form->_membershipTypeValues
as $membershiptTypeValue) {
978 if ($membershiptTypeValue['auto_renew']) {
979 $autoRenewMembershipTypes[] = $membershiptTypeValue['id'];
982 foreach ($form->_priceSet
['fields'] as $field) {
983 if (array_key_exists('options', $field) && is_array($field['options'])) {
984 foreach ($field['options'] as $option) {
985 if (!empty($option['membership_type_id'])) {
986 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
987 $form->_priceSet
['auto_renew_membership_field'] = $field['id'];
988 // Only one field can offer auto_renew memberships, so break here.
996 $form->assign('priceSet', $form->_priceSet
);
998 $component = 'contribution';
999 if ($className == 'CRM_Member_Form_Membership') {
1000 $component = 'membership';
1003 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
1004 $feeBlock = &$form->_values
['fee'];
1005 if (!empty($form->_useForMember
)) {
1006 $component = 'membership';
1010 $feeBlock = &$form->_priceSet
['fields'];
1012 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1013 foreach ($feeBlock as $key => $value) {
1014 foreach ($value['options'] as $k => $options) {
1015 if (!CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($options['financial_type_id']))) {
1016 unset($feeBlock[$key]['options'][$k]);
1019 if (empty($feeBlock[$key]['options'])) {
1020 unset($feeBlock[$key]);
1025 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
1027 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
1028 $adminFieldVisible = FALSE;
1029 if (CRM_Core_Permission
::check('administer CiviCRM')) {
1030 $adminFieldVisible = TRUE;
1033 $hideAdminValues = TRUE;
1034 if (CRM_Core_Permission
::check('edit contributions')) {
1035 $hideAdminValues = FALSE;
1038 foreach ($feeBlock as $id => $field) {
1039 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
1040 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
1043 $options = CRM_Utils_Array
::value('options', $field);
1044 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
1045 $userid = $form->getVar('_membershipContactID');
1046 $checklifetime = self
::checkCurrentMembership($options, $userid);
1047 if ($checklifetime) {
1048 $form->assign('ispricelifetime', TRUE);
1052 $formClasses = array('CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership');
1054 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
1057 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
1058 foreach ($options as $key => $currentOption) {
1059 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField
::getVisibilityOptionID('admin')) {
1060 unset($options[$key]);
1064 if (!empty($options)) {
1065 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
1066 'price_' . $field['id'],
1069 CRM_Utils_Array
::value('is_required', $field, FALSE),
1079 * Check the current Membership having end date null.
1081 * @param array $options
1082 * @param int $userid
1083 * Probably actually contact ID.
1087 public static function checkCurrentMembership(&$options, $userid) {
1088 if (!$userid ||
empty($options)) {
1091 static $_contact_memberships = array();
1092 $checkLifetime = FALSE;
1093 foreach ($options as $key => $value) {
1094 if (!empty($value['membership_type_id'])) {
1095 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
1096 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
1098 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
1099 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
1100 unset($options[$key]);
1101 $checkLifetime = TRUE;
1105 if ($checkLifetime) {
1114 * Set daefult the price set fields.
1116 * @param CRM_Core_Form $form
1121 public static function setDefaultPriceSet(&$form, &$defaults) {
1122 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1126 foreach ($form->_priceSet
['fields'] as $val) {
1127 foreach ($val['options'] as $keys => $values) {
1128 // build price field index which is passed via URL
1129 // url format will be appended by "&price_5=11"
1130 $priceFieldName = 'price_' . $values['price_field_id'];
1131 $priceFieldValue = self
::getPriceFieldValueFromURL($form, $priceFieldName);
1132 if (!empty($priceFieldValue)) {
1133 self
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
1134 // break here to prevent overwriting of default due to 'is_default'
1135 // option configuration. The value sent via URL get's higher priority.
1138 elseif ($values['is_default']) {
1139 self
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
1147 * Get the value of price field if passed via url
1149 * @param string $priceFieldName
1150 * @param string $priceFieldValue
1151 * @param string $priceFieldType
1152 * @param array $defaults
1156 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
1157 if ($priceFieldType == 'CheckBox') {
1158 $defaults[$priceFieldName][$priceFieldValue] = 1;
1161 $defaults[$priceFieldName] = $priceFieldValue;
1166 * Get the value of price field if passed via url
1168 * @param CRM_Core_Form $form
1169 * @param string $priceFieldName
1171 * @return mixed $priceFieldValue
1173 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
1174 $priceFieldValue = CRM_Utils_Request
::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
1175 if (!empty($priceFieldValue)) {
1176 return $priceFieldValue;
1181 * Supports event create function by setting up required price sets, not tested but expect
1182 * it will work for contribution page
1183 * @param array $params
1184 * As passed to api/bao create fn.
1185 * @param CRM_Core_DAO $entity
1186 * Object for given entity.
1187 * @param string $entityName
1188 * Name of entity - e.g event.
1190 public static function setPriceSets(&$params, $entity, $entityName) {
1191 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1194 // CRM-14069 note that we may as well start by assuming more than one.
1195 // currently the form does not pass in as an array & will be skipped
1196 // test is passing in as an array but I feel the api should have a metadata that allows
1197 // transform of single to array - seems good for managing transitions - in which case all api
1198 // calls that set price_set_id will hit this
1199 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1200 // all separated values, strings, json half-separated values (in participant we hit this)
1201 // to be converted to json @ api layer
1202 $pse = new CRM_Price_DAO_PriceSetEntity();
1203 $pse->entity_table
= 'civicrm_' . $entityName;
1204 $pse->entity_id
= $entity->id
;
1205 while ($pse->fetch()) {
1206 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1207 // note an even more aggressive form of this deletion currently happens in event form
1208 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1209 // on the participant record
1210 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1211 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1215 foreach ($params['price_set_id'] as $priceSetID) {
1216 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1217 //@todo - how should we do this - copied from form
1218 //if (!empty($params['price_field_id'])) {
1219 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1220 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1226 * Get field ids of a price set.
1232 * Array of the field ids
1235 public static function getFieldIds($id) {
1236 $priceField = new CRM_Price_DAO_PriceField();
1237 $priceField->price_set_id
= $id;
1238 $priceField->find();
1239 while ($priceField->fetch()) {
1240 $var[] = $priceField->id
;
1246 * Copy a price set, including all the fields
1249 * The price set id to copy.
1251 * @return CRM_Price_DAO_PriceSet
1253 public static function copy($id) {
1254 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1255 $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $id));
1257 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
1258 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1261 'title' => trim($newTitle) . ' ' . $title,
1262 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId +
1),
1266 $copy = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1272 //copying all the blocks pertaining to the price set
1273 $copyPriceField = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1274 array('price_set_id' => $id),
1275 array('price_set_id' => $copy->id
)
1277 if (!empty($copyPriceField)) {
1278 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1280 //copy option group and values
1281 foreach ($price as $originalId => $copyId) {
1282 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1283 array('price_field_id' => $originalId),
1284 array('price_field_id' => $copyId)
1290 CRM_Utils_Hook
::copy('Set', $copy);
1295 * check price set permission.
1302 public static function checkPermission($sid) {
1303 if ($sid && self
::eventPriceSetDomainID()) {
1304 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1305 if (CRM_Core_Config
::domainID() != $domain_id) {
1306 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1313 * Get the sum of participant count
1314 * for all fields of given price set.
1319 * @param bool $onlyActive
1321 * @return int|null|string
1323 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1331 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1334 static $pricesetFieldCount = array();
1335 if (!isset($pricesetFieldCount[$sid])) {
1337 SELECT sum(value.count) as totalCount
1338 FROM civicrm_price_field_value value
1339 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1340 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1344 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1345 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1348 return $pricesetFieldCount[$sid];
1356 public static function getMembershipCount($ids) {
1358 SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
1359 FROM civicrm_price_field_value pfv
1360 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1361 WHERE pfv.id IN ( $ids )
1362 GROUP BY mt.member_of_contact_id ";
1364 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1367 while ($crmDAO->fetch()) {
1368 $count[$crmDAO->id
] = $crmDAO->count
;
1375 * Check if auto renew option should be shown.
1377 * The auto-renew option should be visible if membership types associated with all the fields has
1378 * been set for auto-renew option.
1380 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1382 * @param int $priceSetId
1386 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1388 public static function checkAutoRenewForPriceSet($priceSetId) {
1389 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1390 pf.html_type, pf.id as price_field_id
1391 FROM civicrm_price_field_value pfv
1392 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1393 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1394 WHERE pf.price_set_id = %1
1395 AND pf.is_active = 1
1396 AND pfv.is_active = 1
1397 ORDER BY price_field_id';
1399 $params = array(1 => array($priceSetId, 'Integer'));
1401 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1403 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1404 //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.
1409 $autoRenewOption = 2;
1410 $priceFields = array();
1411 while ($dao->fetch()) {
1412 if (!$dao->auto_renew
) {
1413 // If any one can't be renewed none can.
1416 if ($dao->auto_renew
== 1) {
1417 $autoRenewOption = 1;
1420 if ($dao->html_type
== 'Checkbox' && !in_array($dao->duration_interval
. $dao->duration_unit
, $priceFields[$dao->price_field_id
])) {
1421 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1422 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1425 $priceFields[$dao->price_field_id
][] = $dao->duration_interval
. $dao->duration_unit
;
1426 foreach ($priceFields as $priceFieldID => $durations) {
1427 if ($priceFieldID != $dao->price_field_id
&& !in_array($dao->duration_interval
. $dao->duration_unit
, $durations)) {
1428 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1434 return $autoRenewOption;
1438 * Retrieve auto renew frequency and interval.
1440 * @param int $priceSetId
1444 * associate array of frequency interval and unit
1446 public static function getRecurDetails($priceSetId) {
1447 $query = 'SELECT mt.duration_interval, mt.duration_unit
1448 FROM civicrm_price_field_value pfv
1449 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1450 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1451 WHERE pf.price_set_id = %1 LIMIT 1';
1453 $params = array(1 => array($priceSetId, 'Integer'));
1454 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1456 return array($dao->duration_interval
, $dao->duration_unit
);
1462 public static function eventPriceSetDomainID() {
1463 return Civi
::settings()->get('event_price_set_domain_id');
1467 * Update the is_quick_config flag in the db.
1470 * Id of the database record.
1471 * @param bool $isQuickConfig we want to set the is_quick_config field.
1472 * Value we want to set the is_quick_config field.
1475 * true if we found and updated the object, else false
1477 public static function setIsQuickConfig($id, $isQuickConfig) {
1478 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1482 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1488 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1489 $membershipTypes = self
::getMembershipTypesFromPriceSet($id);
1490 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1497 * Get an array of the membership types in a price set.
1502 * Membership types in the price set
1504 public static function getMembershipTypesFromPriceSet($id) {
1506 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1507 FROM civicrm_price_field_value pfv
1508 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1509 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1510 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1514 $params = array(1 => array($id, 'Integer'));
1515 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1517 $membershipTypes = array(
1519 'autorenew' => array(),
1520 'autorenew_required' => array(),
1521 'autorenew_optional' => array(),
1523 while ($dao->fetch()) {
1524 if (empty($dao->membership_type_id
)) {
1527 $membershipTypes['all'][] = $dao->membership_type_id
;
1528 if (!empty($dao->auto_renew
)) {
1529 $membershipTypes['autorenew'][] = $dao->membership_type_id
;
1530 if ($dao->auto_renew
== 2) {
1531 $membershipTypes['autorenew_required'][] = $dao->membership_type_id
;
1534 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id
;
1538 $membershipTypes['non_renew'][] = $dao->membership_type_id
;
1541 return $membershipTypes;
1545 * Copy priceSet when event/contibution page is copied
1547 * @param string $baoName
1550 * Old event/contribution page id.
1552 * Newly created event/contribution page id.
1554 public static function copyPriceSet($baoName, $id, $newId) {
1555 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1557 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1558 if ($isQuickConfig) {
1559 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1560 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1563 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1566 'entity_table' => $baoName,
1568 array('entity_id' => $newId)
1571 // copy event discount
1572 if ($baoName == 'civicrm_event') {
1573 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1574 foreach ($discount as $discountId => $setId) {
1576 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1578 CRM_Core_DAO
::copyGeneric(
1579 'CRM_Core_DAO_Discount',
1581 'id' => $discountId,
1584 'entity_id' => $newId,
1585 'price_set_id' => $copyPriceSet->id
,
1594 * Function to set tax_amount and tax_rate in LineItem.
1596 * @param array $field
1597 * @param array $lineItem
1598 * @param int $optionValueId
1599 * @param float $totalTax
1603 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
1604 // Here we round - i.e. after multiplying by quantity
1605 if ($field['html_type'] == 'Text') {
1606 $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
1609 $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
1611 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1612 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1613 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1614 $totalTax +
= $taxAmount;
1619 * Get the first price set value IDs from a parameters array.
1621 * In practice this is really used when we only expect one to exist.
1623 * @param array $params
1626 * Array of the ids of the price set values.
1628 public static function parseFirstPriceSetValueIDFromParams($params) {
1629 $priceSetValueIDs = self
::parsePriceSetValueIDsFromParams($params);
1630 return reset($priceSetValueIDs);
1634 * Get the price set value IDs from a set of parameters
1636 * @param array $params
1639 * Array of the ids of the price set values.
1641 public static function parsePriceSetValueIDsFromParams($params) {
1642 $priceSetParams = self
::parsePriceSetArrayFromParams($params);
1643 $priceSetValueIDs = array();
1644 foreach ($priceSetParams as $priceSetParam) {
1645 foreach (array_keys($priceSetParam) as $priceValueID) {
1646 $priceSetValueIDs[] = $priceValueID;
1649 return $priceSetValueIDs;
1653 * Get the price set value IDs from a set of parameters
1655 * @param array $params
1658 * Array of price fields filtered from the params.
1660 public static function parsePriceSetArrayFromParams($params) {
1661 $priceSetParams = array();
1662 foreach ($params as $field => $value) {
1663 $parts = explode('_', $field);
1664 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
1665 $priceSetParams[$field] = $value;
1668 return $priceSetParams;
1672 * Get non-deductible amount from price options
1674 * @param int $priceSetId
1675 * @param array $lineItem
1678 * calculated non-deductible amount.
1680 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1681 $nonDeductibleAmount = 0;
1682 if (!empty($lineItem[$priceSetId])) {
1683 foreach ($lineItem[$priceSetId] as $options) {
1684 $nonDeductibleAmount +
= $options['non_deductible_amount'] * $options['qty'];
1688 return $nonDeductibleAmount;
1692 * Get an array of all forms using a given price set.
1697 * Pages using the price set, keyed by type. e.g
1699 * 'civicrm_contribution_page' => array(2,5,6),
1700 * 'civicrm_event' => array(5,6),
1701 * 'civicrm_event_template' => array(7),
1704 public static function getFormsUsingPriceSet($id) {
1707 SELECT entity_table, entity_id
1708 FROM civicrm_price_set_entity
1709 WHERE price_set_id = %1";
1710 $params = array(1 => array($id, 'Integer'));
1711 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1713 while ($crmFormDAO->fetch()) {
1714 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
1720 * @param array $forms
1721 * Array of forms that use a price set keyed by entity. e.g
1723 * 'civicrm_contribution_page' => array(2,5,6),
1724 * 'civicrm_event' => array(5,6),
1725 * 'civicrm_event_template' => array(7),
1729 * Array of entities suppliemented with per entity information.
1731 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1733 * @throws \Exception
1735 protected static function reformatUsedByFormsWithEntityData($forms) {
1737 foreach ($forms as $table => $entities) {
1739 case 'civicrm_event':
1740 $ids = implode(',', $entities);
1741 $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
1742 FROM civicrm_event ce
1743 LEFT JOIN civicrm_option_value ON
1744 ( ce.event_type_id = civicrm_option_value.value )
1745 LEFT JOIN civicrm_option_group ON
1746 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1748 civicrm_option_group.name = 'event_type' AND
1751 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1752 while ($crmDAO->fetch()) {
1753 if ($crmDAO->isTemplate
) {
1754 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
1755 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1756 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1759 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1760 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1761 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1762 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1763 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1768 case 'civicrm_contribution_page':
1769 $ids = implode(',', $entities);
1770 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1771 FROM civicrm_contribution_page cp, civicrm_financial_type ct
1772 WHERE ct.id = cp.financial_type_id AND
1775 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1776 while ($crmDAO->fetch()) {
1777 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1778 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
1779 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1780 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1784 case 'civicrm_contribution':
1785 case 'civicrm_membership':
1786 case 'civicrm_participant':
1787 $usedBy[$table] = 1;
1791 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");