3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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.
108 * @internal param bool $is_active value we want to set the is_active field
111 * DAO object on success, null otherwise
113 public static function setIsActive($id, $isActive) {
114 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
118 * Calculate the default price set id
119 * assigned to the contribution/membership etc
121 * @param string $entity
127 public static function getDefaultPriceSet($entity = 'contribution') {
128 if (!empty(self
::$_defaultPriceSet[$entity])) {
129 return self
::$_defaultPriceSet[$entity];
131 $entityName = 'default_contribution_amount';
132 if ($entity == 'membership') {
133 $entityName = 'default_membership_type_amount';
137 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
138 FROM civicrm_price_set ps
139 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
140 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
141 WHERE ps.name = '{$entityName}'
144 $dao = CRM_Core_DAO
::executeQuery($sql);
145 self
::$_defaultPriceSet[$entity] = array();
146 while ($dao->fetch()) {
147 self
::$_defaultPriceSet[$entity][$dao->priceFieldValueID
] = array(
148 'setID' => $dao->setID
,
149 'priceFieldID' => $dao->priceFieldID
,
150 'name' => $dao->name
,
151 'label' => $dao->label
,
152 'priceFieldValueID' => $dao->priceFieldValueID
,
153 'membership_type_id' => $dao->membership_type_id
,
154 'amount' => $dao->amount
,
155 'financial_type_id' => $dao->financial_type_id
,
159 return self
::$_defaultPriceSet[$entity];
163 * Get the price set title.
172 public static function getTitle($id) {
173 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
177 * Return a list of all forms which use this price set.
181 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
185 public static function getUsedBy($id, $simpleReturn = FALSE) {
187 $forms = self
::getFormsUsingPriceSet($id);
188 $tables = array_keys($forms);
189 // @todo - this is really clumsy overloading the signature like this. Instead
190 // move towards having a function that does not call reformatUsedByFormsWithEntityData
191 // and call that when that data is not used.
192 if ($simpleReturn == 'table') {
195 // @todo - this is painfully slow in some cases.
198 SELECT cli.entity_table, cli.entity_id
199 FROM civicrm_line_item cli
200 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
201 WHERE cpf.price_set_id = %1";
202 $params = array(1 => array($id, 'Integer'));
203 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
204 while ($crmFormDAO->fetch()) {
205 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
206 $tables[] = $crmFormDAO->entity_table
;
212 // @todo - this is really clumsy overloading the signature like this. See above.
213 if ($simpleReturn == 'entity') {
216 $usedBy = self
::reformatUsedByFormsWithEntityData($forms, $usedBy);
222 * Delete the price set, including the fields.
228 * false if fields exist for this set, true if the
229 * set could be deleted
232 public static function deleteSet($id) {
233 // delete price fields
234 $priceField = new CRM_Price_DAO_PriceField();
235 $priceField->price_set_id
= $id;
237 while ($priceField->fetch()) {
238 // delete options first
239 CRM_Price_BAO_PriceField
::deleteField($priceField->id
);
242 $set = new CRM_Price_DAO_PriceSet();
244 return $set->delete();
248 * Link the price set with the specified table and id.
250 * @param string $entityTable
251 * @param int $entityId
252 * @param int $priceSetId
256 public static function addTo($entityTable, $entityId, $priceSetId) {
257 // verify that the price set exists
258 $dao = new CRM_Price_DAO_PriceSet();
259 $dao->id
= $priceSetId;
265 $dao = new CRM_Price_DAO_PriceSetEntity();
266 // find if this already exists
267 $dao->entity_id
= $entityId;
268 $dao->entity_table
= $entityTable;
271 // add or update price_set_id
272 $dao->price_set_id
= $priceSetId;
277 * Delete price set for the given entity and id.
279 * @param string $entityTable
280 * @param int $entityId
284 public static function removeFrom($entityTable, $entityId) {
285 $dao = new CRM_Price_DAO_PriceSetEntity();
286 $dao->entity_table
= $entityTable;
287 $dao->entity_id
= $entityId;
288 return $dao->delete();
292 * Find a price_set_id associated with the given table, id and usedFor
293 * Used For value for events:1, contribution:2, membership:3
295 * @param string $entityTable
296 * @param int $entityId
297 * @param int $usedFor
298 * ( price set that extends/used for particular component ).
300 * @param null $isQuickConfig
301 * @param null $setName
304 * price_set_id, or false if none found
306 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
307 if (!$entityTable ||
!$entityId) {
311 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
312 FROM civicrm_price_set ps
313 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
314 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
315 if ($isQuickConfig) {
316 $sql .= ' AND ps.is_quick_config = 0 ';
319 1 => array($entityTable, 'String'),
320 2 => array($entityId, 'Integer'),
323 $sql .= " AND ps.extends LIKE '%%3%' ";
324 $params[3] = array($usedFor, 'Integer');
327 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
329 $setName = (isset($dao->price_set_name
)) ?
$dao->price_set_name
: FALSE;
330 return (isset($dao->price_set_id
)) ?
$dao->price_set_id
: FALSE;
334 * Find a price_set_id associated with the given option value or field ID.
336 * @param array $params
337 * (reference) an assoc array of name/value pairs.
338 * array may contain either option id or
342 * price set id on success, null otherwise
344 public static function getSetId(&$params) {
347 if ($oid = CRM_Utils_Array
::value('oid', $params)) {
348 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
349 $fieldValue->id
= $oid;
350 if ($fieldValue->find(TRUE)) {
351 $fid = $fieldValue->price_field_id
;
355 $fid = CRM_Utils_Array
::value('fid', $params);
359 return CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
366 * Return an associative array of all price sets.
368 * @param bool $withInactive
369 * Whether or not to include inactive entries.
370 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
371 * @param string $column name of the column.
374 * associative array of id => name
376 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
379 DISTINCT ( price_set_id ) as id, s.{$column}
382 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
383 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
385 is_quick_config = 0 ";
387 if (!$withInactive) {
388 $query .= ' AND s.is_active = 1 ';
391 if (self
::eventPriceSetDomainID()) {
392 $query .= ' AND s.domain_id = ' . CRM_Core_Config
::domainID();
395 $priceSets = array();
397 if ($extendComponentName) {
398 $componentId = CRM_Core_Component
::getComponentID($extendComponentName);
402 $query .= " AND s.extends LIKE '%$componentId%' ";
404 // Check permissioned financial types
405 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialType, CRM_Core_Action
::ADD
);
406 if ($financialType) {
407 $types = implode(',', array_keys($financialType));
408 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
411 // Do not display any price sets
414 $query .= " GROUP BY s.id";
415 $dao = CRM_Core_DAO
::executeQuery($query);
416 while ($dao->fetch()) {
417 $priceSets[$dao->id
] = $dao->$column;
423 * Get price set details.
425 * An array containing price set details (including price fields) is returned
429 * @param bool $required
430 * Appears to have no effect based on reading the code.
431 * @param bool $validOnly
432 * Should only fields where today's date falls within the valid range be returned?
435 * Array consisting of field details
437 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
441 $priceFields = array(
450 'is_display_amounts',
459 if ($required == TRUE) {
460 $priceFields[] = 'is_required';
464 $select = 'SELECT ' . implode(',', $priceFields);
465 $from = ' FROM civicrm_price_field';
468 1 => array($setID, 'Integer'),
470 $currentTime = date('YmdHis');
472 WHERE price_set_id = %1
474 AND ( active_on IS NULL OR active_on <= {$currentTime} )
479 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
483 $orderBy = ' ORDER BY weight';
485 $sql = $select . $from . $where . $dateSelect . $orderBy;
487 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
489 $isDefaultContributionPriceSet = FALSE;
490 if ('default_contribution_amount' == CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
491 $isDefaultContributionPriceSet = TRUE;
494 $visibility = CRM_Core_PseudoConstant
::visibility('name');
495 while ($dao->fetch()) {
498 $setTree[$setID]['fields'][$fieldID] = array();
499 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
501 foreach ($priceFields as $field) {
502 if ($field == 'id' ||
is_null($dao->$field)) {
506 if ($field == 'visibility_id') {
507 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
509 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
511 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField
::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
514 // also get the pre and post help from this price set
516 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
517 FROM civicrm_price_set
519 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
521 $setTree[$setID]['extends'] = $dao->extends;
522 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id
;
523 $setTree[$setID]['help_pre'] = $dao->help_pre
;
524 $setTree[$setID]['help_post'] = $dao->help_post
;
525 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config
;
526 $setTree[$setID]['min_amount'] = $dao->min_amount
;
532 * Get the Price Field ID.
534 * We call this function when more than one being present would represent an error
535 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
536 * @param array $priceSet
538 * @throws CRM_Core_Exception
541 public static function getOnlyPriceFieldID(array $priceSet) {
542 if (count($priceSet['fields']) > 1) {
543 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
545 return (int) implode('_', array_keys($priceSet['fields']));
549 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
550 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
551 * @param array $priceSet
553 * @throws CRM_Core_Exception
556 public static function getOnlyPriceFieldValueID(array $priceSet) {
557 $priceFieldID = self
::getOnlyPriceFieldID($priceSet);
558 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
559 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
561 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
566 * Initiate price set such that various non-BAO things are set on the form.
568 * This function is not really a BAO function so the location is misleading.
570 * @param CRM_Core_Form $form
573 * @param string $entityTable
574 * @param bool $validOnly
575 * @param int $priceSetId
578 * @return bool|false|int|null
580 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
582 $priceSetId = self
::getFor($entityTable, $id);
585 //check if price set is is_config
586 if (is_numeric($priceSetId)) {
587 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
588 $form->assign('quickConfig', 1);
593 if ($form->_action
& CRM_Core_Action
::UPDATE
) {
594 $entityId = $entity = NULL;
596 switch ($entityTable) {
597 case 'civicrm_event':
598 $entity = 'participant';
599 if (CRM_Utils_System
::getClassName($form) == 'CRM_Event_Form_Participant') {
600 $entityId = $form->_id
;
603 $entityId = $form->_participantId
;
607 case 'civicrm_contribution_page':
608 case 'civicrm_contribution':
609 $entity = 'contribution';
610 $entityId = $form->_id
;
614 if ($entityId && $entity) {
615 $form->_values
['line_items'] = CRM_Price_BAO_LineItem
::getLineItems($entityId, $entity);
623 $form->_priceSetId
= $priceSetId;
624 $priceSet = self
::getSetDetail($priceSetId, $required, $validOnly);
625 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
626 $form->_values
['fee'] = CRM_Utils_Array
::value('fields', $form->_priceSet
);
628 //get the price set fields participant count.
629 if ($entityTable == 'civicrm_event') {
630 //get option count info.
631 $form->_priceSet
['optionsCountTotal'] = self
::getPricesetCount($priceSetId);
632 if ($form->_priceSet
['optionsCountTotal']) {
633 $optionsCountDetails = array();
634 if (!empty($form->_priceSet
['fields'])) {
635 foreach ($form->_priceSet
['fields'] as $field) {
636 foreach ($field['options'] as $option) {
637 $count = CRM_Utils_Array
::value('count', $option, 0);
638 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
642 $form->_priceSet
['optionsCountDetails'] = $optionsCountDetails;
645 //get option max value info.
646 $optionsMaxValueTotal = 0;
647 $optionsMaxValueDetails = array();
649 if (!empty($form->_priceSet
['fields'])) {
650 foreach ($form->_priceSet
['fields'] as $field) {
651 foreach ($field['options'] as $option) {
652 $maxVal = CRM_Utils_Array
::value('max_value', $option, 0);
653 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
654 $optionsMaxValueTotal +
= $maxVal;
659 $form->_priceSet
['optionsMaxValueTotal'] = $optionsMaxValueTotal;
660 if ($optionsMaxValueTotal) {
661 $form->_priceSet
['optionsMaxValueDetails'] = $optionsMaxValueDetails;
664 $form->set('priceSetId', $form->_priceSetId
);
665 $form->set('priceSet', $form->_priceSet
);
673 * Get line item purchase information.
675 * This function takes the input parameters and interprets out of it what has been purchased.
678 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
679 * And, it would make sense to introduce caching into that function and call it from here rather than
680 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
681 * @param array $params
682 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
684 * Line item array to be altered.
685 * @param string $component
686 * This parameter appears to only be relevant to determining whether memberships should be auto-renewed.
687 * (and is effectively a boolean for 'is_membership' which could be calculated from the line items.)
688 * @param int $priceSetID
690 public static function processAmount($fields, &$params, &$lineItem, $component = '', $priceSetID = NULL) {
692 $totalPrice = $totalTax = 0;
693 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
694 // This is notably the case with memberships and we need to put this amount
695 // on the line item rather than the calculated amount.
696 // This seems to only affect radio link items as that is the use case for the 'quick config'
697 // set up (which allows a free form field).
698 $amount_override = NULL;
701 $autoRenew = array();
702 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
705 $priceFields = self
::filterPriceFieldsFromParams($priceSetID, $params);
706 if (count($priceFields) == 1) {
707 $amount_override = CRM_Utils_Array
::value('partial_payment_total', $params, CRM_Utils_Array
::value('total_amount', $params));
710 foreach ($fields as $id => $field) {
711 if (empty($params["price_{$id}"]) ||
712 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
714 // skip if nothing was submitted for this field
718 switch ($field['html_type']) {
720 $firstOption = reset($field['options']);
721 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
722 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
723 $optionValueId = key($field['options']);
725 if (CRM_Utils_Array
::value('name', $field['options'][$optionValueId]) == 'contribution_amount') {
726 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
727 if (array_key_exists($params['financial_type_id'], $taxRates)) {
728 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
729 $taxAmount = CRM_Contribute_BAO_Contribution_Utils
::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
730 $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
733 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
734 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
736 $totalPrice +
= $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[key($field['options'])]);
740 //special case if user select -none-
741 if ($params["price_{$id}"] <= 0) {
744 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
745 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
747 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, $amount_override);
748 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
749 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
750 if ($amount_override) {
751 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule
::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
754 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
757 // auto_renew exists and is empty in some workflows, which php treat as a 0
758 // and hence we explicitly check to see if auto_renew is numeric
759 isset($lineItem[$optionValueId]['auto_renew']) &&
760 is_numeric($lineItem[$optionValueId]['auto_renew'])
762 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
767 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
768 $optionValueId = CRM_Utils_Array
::key(1, $params["price_{$id}"]);
770 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
771 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionValueId])) {
772 $lineItem = self
::setLineItem($field, $lineItem, $optionValueId, $totalTax);
774 $totalPrice +
= $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionValueId]);
777 isset($lineItem[$optionValueId]['auto_renew']) &&
778 is_numeric($lineItem[$optionValueId]['auto_renew'])
780 $autoRenew[$lineItem[$optionValueId]['auto_renew']] +
= $lineItem[$optionValueId]['line_total'];
786 CRM_Price_BAO_LineItem
::format($id, $params, $field, $lineItem, CRM_Utils_Array
::value('partial_payment_total', $params));
787 foreach ($params["price_{$id}"] as $optionId => $option) {
788 if (CRM_Utils_Array
::value('tax_rate', $field['options'][$optionId])) {
789 $lineItem = self
::setLineItem($field, $lineItem, $optionId, $totalTax);
791 $totalPrice +
= $lineItem[$optionId]['line_total'] + CRM_Utils_Array
::value('tax_amount', $lineItem[$optionId]);
794 isset($lineItem[$optionId]['auto_renew']) &&
795 is_numeric($lineItem[$optionId]['auto_renew'])
797 $autoRenew[$lineItem[$optionId]['auto_renew']] +
= $lineItem[$optionId]['line_total'];
804 $amount_level = array();
805 $totalParticipant = 0;
806 if (is_array($lineItem)) {
807 foreach ($lineItem as $values) {
808 $totalParticipant +
= $values['participant_count'];
809 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
810 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
813 // However, because the quick config concept existed all sorts of logic was hung off it
814 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
815 // is always set at the functional level. In this case we are dealing with the default 'quick config'
816 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
817 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
820 // But, in the interests of being careful when capacity is low - avoiding the known default value
822 // Crucially a test has been added so a better solution can be implemented later with some comfort.
823 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
824 if ($values['label'] != ts('Contribution Amount')) {
825 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
830 $displayParticipantCount = '';
831 if ($totalParticipant > 0) {
832 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
834 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
835 if (!empty($amount_level)) {
836 $params['amount_level'] = CRM_Utils_Array
::implodePadded($amount_level);
837 if (!empty($displayParticipantCount)) {
838 $params['amount_level'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
842 $params['amount'] = $totalPrice;
843 $params['tax_amount'] = $totalTax;
845 foreach ($autoRenew as $dontCare => $eachAmount) {
847 unset($autoRenew[$dontCare]);
850 if (count($autoRenew) > 1) {
851 $params['autoRenew'] = $autoRenew;
857 * Get the text to record for amount level.
859 * @param array $params
860 * Submitted parameters
861 * - priceSetId is required to be set in the calling function
862 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
863 * default one & this function asks that be set if it is the case).
866 * Text for civicrm_contribution.amount_level field.
868 public static function getAmountLevelText($params) {
869 $priceSetID = $params['priceSetId'];
870 $priceFieldSelection = self
::filterPriceFieldsFromParams($priceSetID, $params);
871 $priceFieldMetadata = self
::getCachedPriceSetDetail($priceSetID);
872 $displayParticipantCount = NULL;
874 $amount_level = array();
875 foreach ($priceFieldMetadata['fields'] as $field) {
876 if (!empty($priceFieldSelection[$field['id']])) {
878 if ($field['is_enter_qty']) {
879 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
881 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
882 // ie. it represents the default price field for a contribution. Another approach would be not
883 // to give it a label if we don't want it to show.
884 if ($field['label'] != ts('Contribution Amount')) {
885 $amount_level[] = $field['label'] . $qtyString;
889 return CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $amount_level) . $displayParticipantCount . CRM_Core_DAO
::VALUE_SEPARATOR
;
893 * Get the fields relevant to the price field from the parameters.
895 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
897 * @param int $priceSetID
898 * @param array $params
901 * Price fields found in the params array
903 public static function filterPriceFieldsFromParams($priceSetID, $params) {
904 $priceSet = self
::getCachedPriceSetDetail($priceSetID);
906 foreach ($priceSet['fields'] as $field) {
907 if (!empty($params['price_' . $field['id']])) {
908 $return[$field['id']] = $params['price_' . $field['id']];
915 * Wrapper for getSetDetail with caching.
917 * We seem to be passing this array around in a painful way - presumably to avoid the hit
918 * of loading it - so lets make it callable with caching.
920 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
921 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
922 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
923 * think less about the price sets.
925 * @param int $priceSetID
929 public static function getCachedPriceSetDetail($priceSetID) {
930 $cacheKey = __CLASS__
. __FUNCTION__
. '_' . $priceSetID;
931 $cache = CRM_Utils_Cache
::singleton();
932 $values = $cache->get($cacheKey);
933 if (empty($values)) {
934 $data = self
::getSetDetail($priceSetID);
935 $values = $data[$priceSetID];
936 $cache->set($cacheKey, $values);
942 * Build the price set form.
944 * @param CRM_Core_Form $form
948 public static function buildPriceSet(&$form) {
949 $priceSetId = $form->get('priceSetId');
954 $validFieldsOnly = TRUE;
955 $className = CRM_Utils_System
::getClassName($form);
956 if (in_array($className, array(
957 'CRM_Contribute_Form_Contribution',
958 'CRM_Member_Form_Membership',
960 $validFieldsOnly = FALSE;
963 $priceSet = self
::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
964 $form->_priceSet
= CRM_Utils_Array
::value($priceSetId, $priceSet);
965 $validPriceFieldIds = array_keys($form->_priceSet
['fields']);
966 $form->_quickConfig
= $quickConfig = 0;
967 if (CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
971 $form->assign('quickConfig', $quickConfig);
972 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
973 $form->_quickConfig
= $quickConfig;
976 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
977 if (!empty($form->_membershipTypeValues
) && is_array($form->_membershipTypeValues
)) {
978 $autoRenewMembershipTypes = array();
979 foreach ($form->_membershipTypeValues
as $membershiptTypeValue) {
980 if ($membershiptTypeValue['auto_renew']) {
981 $autoRenewMembershipTypes[] = $membershiptTypeValue['id'];
984 foreach ($form->_priceSet
['fields'] as $field) {
985 if (array_key_exists('options', $field) && is_array($field['options'])) {
986 foreach ($field['options'] as $option) {
987 if (!empty($option['membership_type_id'])) {
988 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
989 $form->_priceSet
['auto_renew_membership_field'] = $field['id'];
990 // Only one field can offer auto_renew memberships, so break here.
998 $form->assign('priceSet', $form->_priceSet
);
1000 $component = 'contribution';
1001 if ($className == 'CRM_Member_Form_Membership') {
1002 $component = 'membership';
1005 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
1006 $feeBlock = &$form->_values
['fee'];
1007 if (!empty($form->_useForMember
)) {
1008 $component = 'membership';
1012 $feeBlock = &$form->_priceSet
['fields'];
1014 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()) {
1015 foreach ($feeBlock as $key => $value) {
1016 foreach ($value['options'] as $k => $options) {
1017 if (!CRM_Core_Permission
::check('add contributions of type ' . CRM_Contribute_PseudoConstant
::financialType($options['financial_type_id']))) {
1018 unset($feeBlock[$key]['options'][$k]);
1021 if (empty($feeBlock[$key]['options'])) {
1022 unset($feeBlock[$key]);
1027 CRM_Utils_Hook
::buildAmount($component, $form, $feeBlock);
1029 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
1030 $adminFieldVisible = FALSE;
1031 if (CRM_Core_Permission
::check('administer CiviCRM')) {
1032 $adminFieldVisible = TRUE;
1035 $hideAdminValues = TRUE;
1036 if (CRM_Core_Permission
::check('edit contributions')) {
1037 $hideAdminValues = FALSE;
1040 foreach ($feeBlock as $id => $field) {
1041 if (CRM_Utils_Array
::value('visibility', $field) == 'public' ||
1042 (CRM_Utils_Array
::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
1045 $options = CRM_Utils_Array
::value('options', $field);
1046 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
1047 $userid = $form->getVar('_membershipContactID');
1048 $checklifetime = self
::checkCurrentMembership($options, $userid);
1049 if ($checklifetime) {
1050 $form->assign('ispricelifetime', TRUE);
1054 $formClasses = array('CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership');
1056 if (!is_array($options) ||
!in_array($id, $validPriceFieldIds)) {
1059 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
1060 foreach ($options as $key => $currentOption) {
1061 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField
::getVisibilityOptionID('admin')) {
1062 unset($options[$key]);
1066 if (!empty($options)) {
1067 CRM_Price_BAO_PriceField
::addQuickFormElement($form,
1068 'price_' . $field['id'],
1071 CRM_Utils_Array
::value('is_required', $field, FALSE),
1081 * Check the current Membership having end date null.
1083 * @param array $options
1084 * @param int $userid
1085 * Probably actually contact ID.
1089 public static function checkCurrentMembership(&$options, $userid) {
1090 if (!$userid ||
empty($options)) {
1093 static $_contact_memberships = array();
1094 $checkLifetime = FALSE;
1095 foreach ($options as $key => $value) {
1096 if (!empty($value['membership_type_id'])) {
1097 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
1098 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership
::getContactMembership($userid, $value['membership_type_id'], FALSE);
1100 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
1101 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
1102 unset($options[$key]);
1103 $checkLifetime = TRUE;
1107 if ($checkLifetime) {
1116 * Set daefult the price set fields.
1118 * @param CRM_Core_Form $form
1123 public static function setDefaultPriceSet(&$form, &$defaults) {
1124 if (!isset($form->_priceSet
) ||
empty($form->_priceSet
['fields'])) {
1128 foreach ($form->_priceSet
['fields'] as $val) {
1129 foreach ($val['options'] as $keys => $values) {
1130 // build price field index which is passed via URL
1131 // url format will be appended by "&price_5=11"
1132 $priceFieldName = 'price_' . $values['price_field_id'];
1133 $priceFieldValue = self
::getPriceFieldValueFromURL($form, $priceFieldName);
1134 if (!empty($priceFieldValue)) {
1135 self
::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
1136 // break here to prevent overwriting of default due to 'is_default'
1137 // option configuration. The value sent via URL get's higher priority.
1140 elseif ($values['is_default']) {
1141 self
::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
1149 * Get the value of price field if passed via url
1151 * @param string $priceFieldName
1152 * @param string $priceFieldValue
1153 * @param string $priceFieldType
1154 * @param array $defaults
1158 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
1159 if ($priceFieldType == 'CheckBox') {
1160 $defaults[$priceFieldName][$priceFieldValue] = 1;
1163 $defaults[$priceFieldName] = $priceFieldValue;
1168 * Get the value of price field if passed via url
1170 * @param CRM_Core_Form $form
1171 * @param string $priceFieldName
1173 * @return mixed $priceFieldValue
1175 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
1176 $priceFieldValue = CRM_Utils_Request
::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
1177 if (!empty($priceFieldValue)) {
1178 return $priceFieldValue;
1183 * Supports event create function by setting up required price sets, not tested but expect
1184 * it will work for contribution page
1185 * @param array $params
1186 * As passed to api/bao create fn.
1187 * @param CRM_Core_DAO $entity
1188 * Object for given entity.
1189 * @param string $entityName
1190 * Name of entity - e.g event.
1192 public static function setPriceSets(&$params, $entity, $entityName) {
1193 if (empty($params['price_set_id']) ||
!is_array($params['price_set_id'])) {
1196 // CRM-14069 note that we may as well start by assuming more than one.
1197 // currently the form does not pass in as an array & will be skipped
1198 // test is passing in as an array but I feel the api should have a metadata that allows
1199 // transform of single to array - seems good for managing transitions - in which case all api
1200 // calls that set price_set_id will hit this
1201 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1202 // all separated values, strings, json half-separated values (in participant we hit this)
1203 // to be converted to json @ api layer
1204 $pse = new CRM_Price_DAO_PriceSetEntity();
1205 $pse->entity_table
= 'civicrm_' . $entityName;
1206 $pse->entity_id
= $entity->id
;
1207 while ($pse->fetch()) {
1208 if (!in_array($pse->price_set_id
, $params['price_set_id'])) {
1209 // note an even more aggressive form of this deletion currently happens in event form
1210 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1211 // on the participant record
1212 if (CRM_Price_BAO_PriceSet
::removeFrom('civicrm_' . $entityName, $entity->id
)) {
1213 CRM_Core_BAO_Discount
::del($entity->id
, 'civicrm_' . $entityName);
1217 foreach ($params['price_set_id'] as $priceSetID) {
1218 CRM_Price_BAO_PriceSet
::addTo('civicrm_' . $entityName, $entity->id
, $priceSetID);
1219 //@todo - how should we do this - copied from form
1220 //if (!empty($params['price_field_id'])) {
1221 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1222 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1228 * Get field ids of a price set.
1234 * Array of the field ids
1237 public static function getFieldIds($id) {
1238 $priceField = new CRM_Price_DAO_PriceField();
1239 $priceField->price_set_id
= $id;
1240 $priceField->find();
1241 while ($priceField->fetch()) {
1242 $var[] = $priceField->id
;
1248 * Copy a price set, including all the fields
1251 * The price set id to copy.
1253 * @return CRM_Price_DAO_PriceSet
1255 public static function copy($id) {
1256 $maxId = CRM_Core_DAO
::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1257 $priceSet = civicrm_api3('PriceSet', 'getsingle', array('id' => $id));
1259 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
1260 $title = ts('[Copy id %1]', array(1 => $maxId +
1));
1263 'title' => trim($newTitle) . ' ' . $title,
1264 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId +
1),
1268 $copy = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSet',
1274 //copying all the blocks pertaining to the price set
1275 $copyPriceField = CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceField',
1276 array('price_set_id' => $id),
1277 array('price_set_id' => $copy->id
)
1279 if (!empty($copyPriceField)) {
1280 $price = array_combine(self
::getFieldIds($id), self
::getFieldIds($copy->id
));
1282 //copy option group and values
1283 foreach ($price as $originalId => $copyId) {
1284 CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1285 array('price_field_id' => $originalId),
1286 array('price_field_id' => $copyId)
1292 CRM_Utils_Hook
::copy('Set', $copy);
1297 * check price set permission.
1304 public static function checkPermission($sid) {
1305 if ($sid && self
::eventPriceSetDomainID()) {
1306 $domain_id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1307 if (CRM_Core_Config
::domainID() != $domain_id) {
1308 CRM_Core_Error
::fatal(ts('You do not have permission to access this page.'));
1315 * Get the sum of participant count
1316 * for all fields of given price set.
1321 * @param bool $onlyActive
1323 * @return int|null|string
1325 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1333 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1336 static $pricesetFieldCount = array();
1337 if (!isset($pricesetFieldCount[$sid])) {
1339 SELECT sum(value.count) as totalCount
1340 FROM civicrm_price_field_value value
1341 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1342 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1346 $count = CRM_Core_DAO
::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1347 $pricesetFieldCount[$sid] = ($count) ?
$count : 0;
1350 return $pricesetFieldCount[$sid];
1358 public static function getMembershipCount($ids) {
1360 SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
1361 FROM civicrm_price_field_value pfv
1362 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1363 WHERE pfv.id IN ( $ids )
1364 GROUP BY mt.member_of_contact_id ";
1366 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1369 while ($crmDAO->fetch()) {
1370 $count[$crmDAO->id
] = $crmDAO->count
;
1377 * Check if auto renew option should be shown.
1379 * The auto-renew option should be visible if membership types associated with all the fields has
1380 * been set for auto-renew option.
1382 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1384 * @param int $priceSetId
1388 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1390 public static function checkAutoRenewForPriceSet($priceSetId) {
1391 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1392 pf.html_type, pf.id as price_field_id
1393 FROM civicrm_price_field_value pfv
1394 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1395 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1396 WHERE pf.price_set_id = %1
1397 AND pf.is_active = 1
1398 AND pfv.is_active = 1
1399 ORDER BY price_field_id';
1401 $params = array(1 => array($priceSetId, 'Integer'));
1403 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1405 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1406 //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.
1411 $autoRenewOption = 2;
1412 $priceFields = array();
1413 while ($dao->fetch()) {
1414 if (!$dao->auto_renew
) {
1415 // If any one can't be renewed none can.
1418 if ($dao->auto_renew
== 1) {
1419 $autoRenewOption = 1;
1422 if ($dao->html_type
== 'Checkbox' && !in_array($dao->duration_interval
. $dao->duration_unit
, $priceFields[$dao->price_field_id
])) {
1423 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1424 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1427 $priceFields[$dao->price_field_id
][] = $dao->duration_interval
. $dao->duration_unit
;
1428 foreach ($priceFields as $priceFieldID => $durations) {
1429 if ($priceFieldID != $dao->price_field_id
&& !in_array($dao->duration_interval
. $dao->duration_unit
, $durations)) {
1430 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1436 return $autoRenewOption;
1440 * Retrieve auto renew frequency and interval.
1442 * @param int $priceSetId
1446 * associate array of frequency interval and unit
1448 public static function getRecurDetails($priceSetId) {
1449 $query = 'SELECT mt.duration_interval, mt.duration_unit
1450 FROM civicrm_price_field_value pfv
1451 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1452 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1453 WHERE pf.price_set_id = %1 LIMIT 1';
1455 $params = array(1 => array($priceSetId, 'Integer'));
1456 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1458 return array($dao->duration_interval
, $dao->duration_unit
);
1464 public static function eventPriceSetDomainID() {
1465 return Civi
::settings()->get('event_price_set_domain_id');
1469 * Update the is_quick_config flag in the db.
1472 * Id of the database record.
1473 * @param bool $isQuickConfig we want to set the is_quick_config field.
1474 * Value we want to set the is_quick_config field.
1477 * DAO object on success, null otherwise
1479 public static function setIsQuickConfig($id, $isQuickConfig) {
1480 return CRM_Core_DAO
::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1484 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1490 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1491 $membershipTypes = self
::getMembershipTypesFromPriceSet($id);
1492 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1499 * Get an array of the membership types in a price set.
1504 * Membership types in the price set
1506 public static function getMembershipTypesFromPriceSet($id) {
1508 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1509 FROM civicrm_price_field_value pfv
1510 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1511 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1512 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1516 $params = array(1 => array($id, 'Integer'));
1517 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1519 $membershipTypes = array(
1521 'autorenew' => array(),
1522 'autorenew_required' => array(),
1523 'autorenew_optional' => array(),
1525 while ($dao->fetch()) {
1526 if (empty($dao->membership_type_id
)) {
1529 $membershipTypes['all'][] = $dao->membership_type_id
;
1530 if (!empty($dao->auto_renew
)) {
1531 $membershipTypes['autorenew'][] = $dao->membership_type_id
;
1532 if ($dao->auto_renew
== 2) {
1533 $membershipTypes['autorenew_required'][] = $dao->membership_type_id
;
1536 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id
;
1540 $membershipTypes['non_renew'][] = $dao->membership_type_id
;
1543 return $membershipTypes;
1547 * Copy priceSet when event/contibution page is copied
1549 * @param string $baoName
1552 * Old event/contribution page id.
1554 * Newly created event/contribution page id.
1556 public static function copyPriceSet($baoName, $id, $newId) {
1557 $priceSetId = CRM_Price_BAO_PriceSet
::getFor($baoName, $id);
1559 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1560 if ($isQuickConfig) {
1561 $copyPriceSet = CRM_Price_BAO_PriceSet
::copy($priceSetId);
1562 CRM_Price_BAO_PriceSet
::addTo($baoName, $newId, $copyPriceSet->id
);
1565 $copyPriceSet = &CRM_Core_DAO
::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1568 'entity_table' => $baoName,
1570 array('entity_id' => $newId)
1573 // copy event discount
1574 if ($baoName == 'civicrm_event') {
1575 $discount = CRM_Core_BAO_Discount
::getOptionGroup($id, 'civicrm_event');
1576 foreach ($discount as $discountId => $setId) {
1578 $copyPriceSet = &CRM_Price_BAO_PriceSet
::copy($setId);
1580 CRM_Core_DAO
::copyGeneric(
1581 'CRM_Core_DAO_Discount',
1583 'id' => $discountId,
1586 'entity_id' => $newId,
1587 'price_set_id' => $copyPriceSet->id
,
1596 * Function to set tax_amount and tax_rate in LineItem.
1598 * @param array $field
1599 * @param array $lineItem
1600 * @param int $optionValueId
1601 * @param float $totalTax
1605 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
1606 // Here we round - i.e. after multiplying by quantity
1607 if ($field['html_type'] == 'Text') {
1608 $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
1611 $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
1613 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1614 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1615 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1616 $totalTax +
= $taxAmount;
1621 * Get the first price set value IDs from a parameters array.
1623 * In practice this is really used when we only expect one to exist.
1625 * @param array $params
1628 * Array of the ids of the price set values.
1630 public static function parseFirstPriceSetValueIDFromParams($params) {
1631 $priceSetValueIDs = self
::parsePriceSetValueIDsFromParams($params);
1632 return reset($priceSetValueIDs);
1636 * Get the price set value IDs from a set of parameters
1638 * @param array $params
1641 * Array of the ids of the price set values.
1643 public static function parsePriceSetValueIDsFromParams($params) {
1644 $priceSetParams = self
::parsePriceSetArrayFromParams($params);
1645 $priceSetValueIDs = array();
1646 foreach ($priceSetParams as $priceSetParam) {
1647 foreach (array_keys($priceSetParam) as $priceValueID) {
1648 $priceSetValueIDs[] = $priceValueID;
1651 return $priceSetValueIDs;
1655 * Get the price set value IDs from a set of parameters
1657 * @param array $params
1660 * Array of price fields filtered from the params.
1662 public static function parsePriceSetArrayFromParams($params) {
1663 $priceSetParams = array();
1664 foreach ($params as $field => $value) {
1665 $parts = explode('_', $field);
1666 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
1667 $priceSetParams[$field] = $value;
1670 return $priceSetParams;
1674 * Get non-deductible amount from price options
1676 * @param int $priceSetId
1677 * @param array $lineItem
1680 * calculated non-deductible amount.
1682 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1683 $nonDeductibleAmount = 0;
1684 if (!empty($lineItem[$priceSetId])) {
1685 foreach ($lineItem[$priceSetId] as $options) {
1686 $nonDeductibleAmount +
= $options['non_deductible_amount'] * $options['qty'];
1690 return $nonDeductibleAmount;
1694 * Get an array of all forms using a given price set.
1699 * Pages using the price set, keyed by type. e.g
1701 * 'civicrm_contribution_page' => array(2,5,6),
1702 * 'civicrm_event' => array(5,6),
1703 * 'civicrm_event_template' => array(7),
1706 public static function getFormsUsingPriceSet($id) {
1709 SELECT entity_table, entity_id
1710 FROM civicrm_price_set_entity
1711 WHERE price_set_id = %1";
1712 $params = array(1 => array($id, 'Integer'));
1713 $crmFormDAO = CRM_Core_DAO
::executeQuery($queryString, $params);
1715 while ($crmFormDAO->fetch()) {
1716 $forms[$crmFormDAO->entity_table
][] = $crmFormDAO->entity_id
;
1722 * @param array $forms
1723 * Array of forms that use a price set keyed by entity. e.g
1725 * 'civicrm_contribution_page' => array(2,5,6),
1726 * 'civicrm_event' => array(5,6),
1727 * 'civicrm_event_template' => array(7),
1731 * Array of entities suppliemented with per entity information.
1733 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1735 * @throws \Exception
1737 protected static function reformatUsedByFormsWithEntityData($forms) {
1739 foreach ($forms as $table => $entities) {
1741 case 'civicrm_event':
1742 $ids = implode(',', $entities);
1743 $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
1744 FROM civicrm_event ce
1745 LEFT JOIN civicrm_option_value ON
1746 ( ce.event_type_id = civicrm_option_value.value )
1747 LEFT JOIN civicrm_option_group ON
1748 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1750 civicrm_option_group.name = 'event_type' AND
1753 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1754 while ($crmDAO->fetch()) {
1755 if ($crmDAO->isTemplate
) {
1756 $usedBy['civicrm_event_template'][$crmDAO->id
]['title'] = $crmDAO->templateTitle
;
1757 $usedBy['civicrm_event_template'][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1758 $usedBy['civicrm_event_template'][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1761 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1762 $usedBy[$table][$crmDAO->id
]['eventType'] = $crmDAO->eventType
;
1763 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1764 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1765 $usedBy[$table][$crmDAO->id
]['isPublic'] = $crmDAO->isPublic
;
1770 case 'civicrm_contribution_page':
1771 $ids = implode(',', $entities);
1772 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1773 FROM civicrm_contribution_page cp, civicrm_financial_type ct
1774 WHERE ct.id = cp.financial_type_id AND
1777 $crmDAO = CRM_Core_DAO
::executeQuery($queryString);
1778 while ($crmDAO->fetch()) {
1779 $usedBy[$table][$crmDAO->id
]['title'] = $crmDAO->title
;
1780 $usedBy[$table][$crmDAO->id
]['type'] = $crmDAO->type
;
1781 $usedBy[$table][$crmDAO->id
]['startDate'] = $crmDAO->startDate
;
1782 $usedBy[$table][$crmDAO->id
]['endDate'] = $crmDAO->endDate
;
1786 case 'civicrm_contribution':
1787 case 'civicrm_membership':
1788 case 'civicrm_participant':
1789 $usedBy[$table] = 1;
1793 CRM_Core_Error
::fatal("$table is not supported in PriceSet::usedBy()");