Merge pull request #22420 from eileenmcnaughton/case
[civicrm-core.git] / CRM / Price / BAO / PriceSet.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * Business object for managing price sets.
20 *
21 */
22 class CRM_Price_BAO_PriceSet extends CRM_Price_DAO_PriceSet {
23
24 /**
25 * Static field for default price set details.
26 *
27 * @var array
28 */
29 public static $_defaultPriceSet = NULL;
30
31 /**
32 * Takes an associative array and creates a price set object.
33 *
34 * @param array $params
35 * (reference) an assoc array of name/value pairs.
36 *
37 * @return CRM_Price_DAO_PriceSet
38 */
39 public static function create(&$params) {
40 $hook = empty($params['id']) ? 'create' : 'edit';
41 CRM_Utils_Hook::pre($hook, 'PriceSet', CRM_Utils_Array::value('id', $params), $params);
42
43 if (empty($params['id']) && empty($params['name'])) {
44 $params['name'] = CRM_Utils_String::munge($params['title'], '_', 242);
45 }
46 $priceSetID = NULL;
47 $validatePriceSet = TRUE;
48 if (!empty($params['extends']) && is_array($params['extends'])) {
49 if (!array_key_exists(CRM_Core_Component::getComponentID('CiviEvent'), $params['extends'])
50 || !array_key_exists(CRM_Core_Component::getComponentID('CiviMember'), $params['extends'])
51 ) {
52 $validatePriceSet = FALSE;
53 }
54 $params['extends'] = CRM_Utils_Array::implodePadded($params['extends']);
55 }
56 else {
57 $priceSetID = $params['id'] ?? NULL;
58 }
59 $priceSetBAO = new CRM_Price_BAO_PriceSet();
60 $priceSetBAO->copyValues($params);
61 if (self::eventPriceSetDomainID()) {
62 $priceSetBAO->domain_id = CRM_Core_Config::domainID();
63 }
64 $priceSetBAO->save();
65
66 CRM_Utils_Hook::post($hook, 'PriceSet', $priceSetBAO->id, $priceSetBAO);
67 unset(\Civi::$statics['CRM_Core_PseudoConstant']);
68 return $priceSetBAO;
69 }
70
71 /**
72 * Fetch object based on array of properties.
73 *
74 * @param array $params
75 * (reference ) an assoc array of name/value pairs.
76 * @param array $defaults
77 * (reference ) an assoc array to hold the flattened values.
78 *
79 * @return CRM_Price_DAO_PriceSet
80 */
81 public static function retrieve(&$params, &$defaults) {
82 return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
83 }
84
85 /**
86 * Update the is_active flag in the db.
87 *
88 * @param int $id
89 * Id of the database record.
90 * @param $isActive
91 *
92 * @return bool
93 * true if we found and updated the object, else false
94 */
95 public static function setIsActive($id, $isActive) {
96 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
97 }
98
99 /**
100 * Calculate the default price set id
101 * assigned to the contribution/membership etc
102 *
103 * @param string $entity
104 *
105 * @return array
106 * default price set
107 *
108 */
109 public static function getDefaultPriceSet($entity = 'contribution') {
110 if (isset(\Civi::$statics[__CLASS__][$entity])) {
111 return \Civi::$statics[__CLASS__][$entity];
112 }
113 $priceSetName = ($entity === 'membership') ? 'default_membership_type_amount' : 'default_contribution_amount';
114
115 $sql = "
116 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
117 FROM civicrm_price_set ps
118 LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
119 LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
120 WHERE ps.name = '{$priceSetName}'
121 ";
122
123 $dao = CRM_Core_DAO::executeQuery($sql);
124 while ($dao->fetch()) {
125 \Civi::$statics[__CLASS__][$entity][$dao->priceFieldValueID] = [
126 'setID' => $dao->setID,
127 'priceFieldID' => $dao->priceFieldID,
128 'name' => $dao->name,
129 'label' => $dao->label,
130 'priceFieldValueID' => $dao->priceFieldValueID,
131 'membership_type_id' => $dao->membership_type_id,
132 'amount' => $dao->amount,
133 'financial_type_id' => $dao->financial_type_id,
134 ];
135 }
136
137 return \Civi::$statics[__CLASS__][$entity];
138 }
139
140 /**
141 * Get the price set title.
142 *
143 * @param int $id
144 * Id of price set.
145 *
146 * @return string
147 * title
148 *
149 */
150 public static function getTitle($id) {
151 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
152 }
153
154 /**
155 * Return a list of all forms which use this price set.
156 *
157 * @param int $id
158 * Id of price set.
159 * @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
160 *
161 * @return array
162 */
163 public static function getUsedBy($id, $simpleReturn = FALSE) {
164 $usedBy = [];
165 $forms = self::getFormsUsingPriceSet($id);
166 $tables = array_keys($forms);
167 // @todo - this is really clumsy overloading the signature like this. Instead
168 // move towards having a function that does not call reformatUsedByFormsWithEntityData
169 // and call that when that data is not used.
170 if ($simpleReturn == 'table') {
171 return $tables;
172 }
173 // @todo - this is painfully slow in some cases.
174 if (empty($forms)) {
175 $queryString = "
176 SELECT cli.entity_table, cli.entity_id
177 FROM civicrm_line_item cli
178 LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
179 WHERE cpf.price_set_id = %1";
180 $params = [1 => [$id, 'Integer']];
181 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
182 while ($crmFormDAO->fetch()) {
183 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
184 $tables[] = $crmFormDAO->entity_table;
185 }
186 if (empty($forms)) {
187 return $usedBy;
188 }
189 }
190 // @todo - this is really clumsy overloading the signature like this. See above.
191 if ($simpleReturn == 'entity') {
192 return $forms;
193 }
194 $usedBy = self::reformatUsedByFormsWithEntityData($forms, $usedBy);
195
196 return $usedBy;
197 }
198
199 /**
200 * Delete the price set, including the fields.
201 *
202 * @param int $id
203 * Price Set id.
204 *
205 * @return bool
206 * false if fields exist for this set, true if the
207 * set could be deleted
208 *
209 */
210 public static function deleteSet($id) {
211 // delete price fields
212 $priceField = new CRM_Price_DAO_PriceField();
213 $priceField->price_set_id = $id;
214 $priceField->find();
215 while ($priceField->fetch()) {
216 // delete options first
217 CRM_Price_BAO_PriceField::deleteField($priceField->id);
218 }
219
220 $set = new CRM_Price_DAO_PriceSet();
221 $set->id = $id;
222 return $set->delete();
223 }
224
225 /**
226 * Link the price set with the specified table and id.
227 *
228 * @param string $entityTable
229 * @param int $entityId
230 * @param int $priceSetId
231 *
232 * @return bool
233 */
234 public static function addTo($entityTable, $entityId, $priceSetId) {
235 // verify that the price set exists
236 $dao = new CRM_Price_DAO_PriceSet();
237 $dao->id = $priceSetId;
238 if (!$dao->find()) {
239 return FALSE;
240 }
241 unset($dao);
242
243 $dao = new CRM_Price_DAO_PriceSetEntity();
244 // find if this already exists
245 $dao->entity_id = $entityId;
246 $dao->entity_table = $entityTable;
247 $dao->find(TRUE);
248
249 // add or update price_set_id
250 $dao->price_set_id = $priceSetId;
251 return $dao->save();
252 }
253
254 /**
255 * Delete price set for the given entity and id.
256 *
257 * @param string $entityTable
258 * @param int $entityId
259 *
260 * @return mixed
261 */
262 public static function removeFrom($entityTable, $entityId) {
263 $dao = new CRM_Price_DAO_PriceSetEntity();
264 $dao->entity_table = $entityTable;
265 $dao->entity_id = $entityId;
266 return $dao->delete();
267 }
268
269 /**
270 * Find a price_set_id associated with the given table, id and usedFor
271 * Used For value for events:1, contribution:2, membership:3
272 *
273 * @param string $entityTable
274 * @param int $entityId
275 * @param int $usedFor
276 * ( price set that extends/used for particular component ).
277 *
278 * @param null $isQuickConfig
279 * @param null $setName
280 *
281 * @return int|false
282 * price_set_id, or false if none found
283 */
284 public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
285 if (!$entityTable || !$entityId) {
286 return FALSE;
287 }
288
289 $sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
290 FROM civicrm_price_set ps
291 INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
292 WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
293 if ($isQuickConfig) {
294 $sql .= ' AND ps.is_quick_config = 0 ';
295 }
296 $params = [
297 1 => [$entityTable, 'String'],
298 2 => [$entityId, 'Integer'],
299 ];
300 if ($usedFor) {
301 $sql .= " AND ps.extends LIKE '%%3%' ";
302 $params[3] = [$usedFor, 'Integer'];
303 }
304
305 $dao = CRM_Core_DAO::executeQuery($sql, $params);
306 $dao->fetch();
307 $setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
308 return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
309 }
310
311 /**
312 * Find a price_set_id associated with the given option value or field ID.
313 *
314 * @param array $params
315 * (reference) an assoc array of name/value pairs.
316 * array may contain either option id or
317 * price field id
318 *
319 * @return int|null
320 * price set id on success, null otherwise
321 */
322 public static function getSetId(&$params) {
323 $fid = NULL;
324
325 if ($oid = CRM_Utils_Array::value('oid', $params)) {
326 $fieldValue = new CRM_Price_DAO_PriceFieldValue();
327 $fieldValue->id = $oid;
328 if ($fieldValue->find(TRUE)) {
329 $fid = $fieldValue->price_field_id;
330 }
331 }
332 else {
333 $fid = $params['fid'] ?? NULL;
334 }
335
336 if (isset($fid)) {
337 return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
338 }
339
340 return NULL;
341 }
342
343 /**
344 * Return an associative array of all price sets.
345 *
346 * @param bool $withInactive
347 * Whether or not to include inactive entries.
348 * @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
349 * @param string $column name of the column.
350 *
351 * @return array
352 * associative array of id => name
353 */
354 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
355 $query = "
356 SELECT
357 DISTINCT ( price_set_id ) as id, s.{$column}
358 FROM
359 civicrm_price_set s
360 INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
361 INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
362 WHERE
363 is_quick_config = 0 ";
364
365 if (!$withInactive) {
366 $query .= ' AND s.is_active = 1 ';
367 }
368
369 if (self::eventPriceSetDomainID()) {
370 $query .= ' AND s.domain_id = ' . CRM_Core_Config::domainID();
371 }
372
373 $priceSets = [];
374
375 if ($extendComponentName) {
376 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
377 if (!$componentId) {
378 return $priceSets;
379 }
380 $query .= " AND s.extends LIKE '%$componentId%' ";
381 }
382 // Check permissioned financial types
383 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialType, CRM_Core_Action::ADD);
384 if ($financialType) {
385 $types = implode(',', array_keys($financialType));
386 $query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
387 }
388 else {
389 // Do not display any price sets
390 $query .= " AND 0 ";
391 }
392 $query .= " GROUP BY s.id";
393 $dao = CRM_Core_DAO::executeQuery($query);
394 while ($dao->fetch()) {
395 $priceSets[$dao->id] = $dao->$column;
396 }
397 return $priceSets;
398 }
399
400 /**
401 * Get price set details.
402 *
403 * An array containing price set details (including price fields) is returned
404 *
405 * @param int $setID
406 * Price Set ID.
407 * @param bool $required
408 * Appears to have no effect based on reading the code.
409 * @param bool $doNotIncludeExpiredFields
410 * Should only fields where today's date falls within the valid range be returned?
411 *
412 * @return array
413 * Array consisting of field details
414 */
415 public static function getSetDetail($setID, $required = TRUE, $doNotIncludeExpiredFields = FALSE) {
416 // create a new tree
417 $setTree = [];
418
419 $priceFields = [
420 'id',
421 'name',
422 'label',
423 'html_type',
424 'is_enter_qty',
425 'help_pre',
426 'help_post',
427 'weight',
428 'is_display_amounts',
429 'options_per_line',
430 'is_active',
431 'active_on',
432 'expire_on',
433 'javascript',
434 'visibility_id',
435 'is_required',
436 ];
437 if ($required == TRUE) {
438 $priceFields[] = 'is_required';
439 }
440
441 // create select
442 $select = 'SELECT ' . implode(',', $priceFields);
443 $from = ' FROM civicrm_price_field';
444
445 $params = [
446 1 => [$setID, 'Integer'],
447 ];
448 $currentTime = date('YmdHis');
449 $where = "
450 WHERE price_set_id = %1
451 AND is_active = 1
452 ";
453 $dateSelect = '';
454 if ($doNotIncludeExpiredFields) {
455 $dateSelect = "
456 AND ( active_on IS NULL OR active_on <= {$currentTime} )
457 AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
458 ";
459 }
460
461 $orderBy = ' ORDER BY weight';
462
463 $sql = $select . $from . $where . $dateSelect . $orderBy;
464
465 $dao = CRM_Core_DAO::executeQuery($sql, $params);
466
467 $isDefaultContributionPriceSet = FALSE;
468 if ('default_contribution_amount' == CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
469 $isDefaultContributionPriceSet = TRUE;
470 }
471
472 $visibility = CRM_Core_PseudoConstant::visibility('name');
473 while ($dao->fetch()) {
474 $fieldID = $dao->id;
475
476 $setTree[$setID]['fields'][$fieldID] = [];
477 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
478
479 foreach ($priceFields as $field) {
480 if ($field == 'id' || is_null($dao->$field)) {
481 continue;
482 }
483
484 if ($field == 'visibility_id') {
485 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
486 }
487 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
488 }
489 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
490 }
491
492 // also get the pre and post help from this price set
493 $sql = "
494 SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
495 FROM civicrm_price_set
496 WHERE id = %1";
497 $dao = CRM_Core_DAO::executeQuery($sql, $params);
498 if ($dao->fetch()) {
499 $setTree[$setID]['extends'] = $dao->extends;
500 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
501 $setTree[$setID]['help_pre'] = $dao->help_pre;
502 $setTree[$setID]['help_post'] = $dao->help_post;
503 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
504 $setTree[$setID]['min_amount'] = $dao->min_amount;
505 }
506 return $setTree;
507 }
508
509 /**
510 * Get the Price Field ID.
511 *
512 * We call this function when more than one being present would represent an error
513 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
514 * @param array $priceSet
515 *
516 * @throws CRM_Core_Exception
517 * @return int
518 */
519 public static function getOnlyPriceFieldID(array $priceSet) {
520 if (count($priceSet['fields']) > 1) {
521 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
522 }
523 return (int) implode('_', array_keys($priceSet['fields']));
524 }
525
526 /**
527 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
528 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
529 * @param array $priceSet
530 *
531 * @throws CRM_Core_Exception
532 * @return int
533 */
534 public static function getOnlyPriceFieldValueID(array $priceSet) {
535 $priceFieldID = self::getOnlyPriceFieldID($priceSet);
536 if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
537 throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
538 }
539 return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
540 }
541
542 /**
543 * Initiate price set such that various non-BAO things are set on the form.
544 *
545 * This function is not really a BAO function so the location is misleading.
546 *
547 * @param CRM_Core_Form $form
548 * Form entity id.
549 * @param string $entityTable
550 * @param bool $doNotIncludeExpiredFields
551 * @param int $priceSetId
552 * Price Set ID
553 */
554 public static function initSet(&$form, $entityTable = 'civicrm_event', $doNotIncludeExpiredFields = FALSE, $priceSetId = NULL) {
555
556 //check if price set is is_config
557 if (is_numeric($priceSetId)) {
558 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
559 $form->assign('quickConfig', 1);
560 }
561 }
562 // get price info
563 if ($priceSetId) {
564 if ($form->_action & CRM_Core_Action::UPDATE) {
565 $entityId = $entity = NULL;
566
567 switch ($entityTable) {
568 case 'civicrm_event':
569 $entity = 'participant';
570 if (in_array(CRM_Utils_System::getClassName($form), ['CRM_Event_Form_Participant', 'CRM_Event_Form_Task_Register'])) {
571 $entityId = $form->_id;
572 }
573 else {
574 $entityId = $form->_participantId;
575 }
576 break;
577
578 case 'civicrm_contribution_page':
579 case 'civicrm_contribution':
580 $entity = 'contribution';
581 $entityId = $form->_id;
582 break;
583 }
584
585 if ($entityId && $entity) {
586 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
587 }
588 $required = FALSE;
589 }
590 else {
591 $required = TRUE;
592 }
593
594 $form->_priceSetId = $priceSetId;
595 $priceSet = self::getSetDetail($priceSetId, $required, $doNotIncludeExpiredFields);
596 $form->_priceSet = $priceSet[$priceSetId] ?? NULL;
597 $form->_values['fee'] = $form->_priceSet['fields'] ?? NULL;
598
599 //get the price set fields participant count.
600 if ($entityTable == 'civicrm_event') {
601 //get option count info.
602 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
603 if ($form->_priceSet['optionsCountTotal']) {
604 $optionsCountDetails = [];
605 if (!empty($form->_priceSet['fields'])) {
606 foreach ($form->_priceSet['fields'] as $field) {
607 foreach ($field['options'] as $option) {
608 $count = CRM_Utils_Array::value('count', $option, 0);
609 $optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
610 }
611 }
612 }
613 $form->_priceSet['optionsCountDetails'] = $optionsCountDetails;
614 }
615
616 //get option max value info.
617 $optionsMaxValueTotal = 0;
618 $optionsMaxValueDetails = [];
619
620 if (!empty($form->_priceSet['fields'])) {
621 foreach ($form->_priceSet['fields'] as $field) {
622 foreach ($field['options'] as $option) {
623 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
624 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
625 $optionsMaxValueTotal += $maxVal;
626 }
627 }
628 }
629
630 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
631 if ($optionsMaxValueTotal) {
632 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
633 }
634 }
635 $form->set('priceSetId', $form->_priceSetId);
636 $form->set('priceSet', $form->_priceSet);
637 }
638 }
639
640 /**
641 * Get line item purchase information.
642 *
643 * This function takes the input parameters and interprets out of it what has been purchased.
644 *
645 * @param $fields
646 * This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
647 * And, it would make sense to introduce caching into that function and call it from here rather than
648 * require the $fields array which is passed from pillar to post around the form in order to pass it in here.
649 * @param array $params
650 * Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
651 * @param $lineItem
652 * Line item array to be altered.
653 * @param int $priceSetID
654 *
655 * @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
656 * don't specifically need it & find a better way where we do.
657 */
658 public static function processAmount($fields, &$params, &$lineItem, $priceSetID = NULL) {
659 // using price set
660 $totalPrice = $totalTax = 0;
661 foreach ($fields as $id => $field) {
662 if (empty($params["price_{$id}"]) ||
663 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
664 ) {
665 // skip if nothing was submitted for this field
666 continue;
667 }
668
669 [$params, $lineItem] = self::getLine($params, $lineItem, $priceSetID, $field, $id);
670 }
671
672 $amount_level = [];
673 $totalParticipant = 0;
674 if (is_array($lineItem)) {
675 foreach ($lineItem as $values) {
676 $totalPrice += $values['line_total'] + $values['tax_amount'];
677 $totalTax += $values['tax_amount'];
678 $totalParticipant += $values['participant_count'];
679 // This is a bit nasty. The logic of 'quick config' was because price set configuration was
680 // (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
681 // page.
682 //
683 // However, because the quick config concept existed all sorts of logic was hung off it
684 // and function behaviour sometimes depends on whether 'price set' is set - although actually it
685 // is always set at the functional level. In this case we are dealing with the default 'quick config'
686 // price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
687 // The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
688 // place holder.
689 //
690 // But, in the interests of being careful when capacity is low - avoiding the known default value
691 // will get us by.
692 // Crucially a test has been added so a better solution can be implemented later with some comfort.
693 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
694 if ($values['label'] !== ts('Contribution Amount')) {
695 $amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
696 }
697 }
698 }
699
700 $displayParticipantCount = '';
701 if ($totalParticipant > 0) {
702 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
703 }
704 // @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
705 if (!empty($amount_level)) {
706 $params['amount_level'] = CRM_Utils_Array::implodePadded($amount_level);
707 if (!empty($displayParticipantCount)) {
708 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
709 }
710 }
711
712 $params['amount'] = $totalPrice;
713 $params['tax_amount'] = $totalTax;
714 }
715
716 /**
717 * Get the text to record for amount level.
718 *
719 * @param array $params
720 * Submitted parameters
721 * - priceSetId is required to be set in the calling function
722 * (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
723 * default one & this function asks that be set if it is the case).
724 *
725 * @return string
726 * Text for civicrm_contribution.amount_level field.
727 */
728 public static function getAmountLevelText($params) {
729 $priceSetID = $params['priceSetId'];
730 $priceFieldSelection = self::filterPriceFieldsFromParams($priceSetID, $params);
731 $priceFieldMetadata = self::getCachedPriceSetDetail($priceSetID);
732 $displayParticipantCount = NULL;
733
734 $amount_level = [];
735 foreach ($priceFieldMetadata['fields'] as $field) {
736 if (!empty($priceFieldSelection[$field['id']])) {
737 $qtyString = '';
738 if ($field['is_enter_qty']) {
739 $qtyString = ' - ' . (float) $params['price_' . $field['id']];
740 }
741 // We deliberately & specifically exclude contribution amount as it has a specific meaning.
742 // ie. it represents the default price field for a contribution. Another approach would be not
743 // to give it a label if we don't want it to show.
744 if ($field['label'] !== ts('Contribution Amount')) {
745 $amount_level[] = $field['label'] . $qtyString;
746 }
747 }
748 }
749 return CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
750 }
751
752 /**
753 * Get the fields relevant to the price field from the parameters.
754 *
755 * E.g we are looking for price_5 => 7 out of a big array of input parameters.
756 *
757 * @param int $priceSetID
758 * @param array $params
759 *
760 * @return array
761 * Price fields found in the params array
762 */
763 public static function filterPriceFieldsFromParams($priceSetID, $params) {
764 $priceSet = self::getCachedPriceSetDetail($priceSetID);
765 $return = [];
766 foreach ($priceSet['fields'] as $field) {
767 if (!empty($params['price_' . $field['id']])) {
768 $return[$field['id']] = $params['price_' . $field['id']];
769 }
770 }
771 return $return;
772 }
773
774 /**
775 * Wrapper for getSetDetail with caching.
776 *
777 * We seem to be passing this array around in a painful way - presumably to avoid the hit
778 * of loading it - so lets make it callable with caching.
779 *
780 * Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
781 * & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
782 * a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
783 * think less about the price sets.
784 *
785 * @param int $priceSetID
786 *
787 * @return array
788 */
789 public static function getCachedPriceSetDetail($priceSetID) {
790 $cacheKey = __CLASS__ . __FUNCTION__ . '_' . $priceSetID;
791 $cache = CRM_Utils_Cache::singleton();
792 $values = $cache->get($cacheKey);
793 if (empty($values)) {
794 $data = self::getSetDetail($priceSetID);
795 $values = $data[$priceSetID];
796 $cache->set($cacheKey, $values);
797 }
798 return $values;
799 }
800
801 /**
802 * Build the price set form.
803 *
804 * @param CRM_Core_Form $form
805 *
806 * @return void
807 */
808 public static function buildPriceSet(&$form) {
809 $priceSetId = $form->get('priceSetId');
810 if (!$priceSetId) {
811 return;
812 }
813
814 $validFieldsOnly = TRUE;
815 $className = CRM_Utils_System::getClassName($form);
816 if (in_array($className, [
817 'CRM_Contribute_Form_Contribution',
818 'CRM_Member_Form_Membership',
819 ])) {
820 $validFieldsOnly = FALSE;
821 }
822
823 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
824 $form->_priceSet = $priceSet[$priceSetId] ?? NULL;
825 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
826 $form->_quickConfig = $quickConfig = 0;
827 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
828 $quickConfig = 1;
829 }
830
831 $form->assign('quickConfig', $quickConfig);
832 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
833 $form->_quickConfig = $quickConfig;
834 }
835
836 // Mark which field should have the auto-renew checkbox, if any. CRM-18305
837 if (!empty($form->_membershipTypeValues) && is_array($form->_membershipTypeValues)) {
838 $autoRenewMembershipTypes = [];
839 foreach ($form->_membershipTypeValues as $membershipTypeValue) {
840 if ($membershipTypeValue['auto_renew']) {
841 $autoRenewMembershipTypes[] = $membershipTypeValue['id'];
842 }
843 }
844 foreach ($form->_priceSet['fields'] as $field) {
845 if (array_key_exists('options', $field) && is_array($field['options'])) {
846 foreach ($field['options'] as $option) {
847 if (!empty($option['membership_type_id'])) {
848 if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
849 $form->_priceSet['auto_renew_membership_field'] = $field['id'];
850 // Only one field can offer auto_renew memberships, so break here.
851 break;
852 }
853 }
854 }
855 }
856 }
857 }
858 $form->_priceSet['id'] = $form->_priceSet['id'] ?? $priceSetId;
859 $form->assign('priceSet', $form->_priceSet);
860
861 $component = 'contribution';
862 if ($className == 'CRM_Member_Form_Membership') {
863 $component = 'membership';
864 }
865
866 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
867 $feeBlock = &$form->_values['fee'];
868 if (!empty($form->_useForMember)) {
869 $component = 'membership';
870 }
871 }
872 else {
873 $feeBlock = &$form->_priceSet['fields'];
874 }
875
876 // Call the buildAmount hook.
877 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
878
879 self::addPriceFieldsToForm($form, $feeBlock, $validFieldsOnly, $className, $validPriceFieldIds);
880 }
881
882 /**
883 * Check the current Membership having end date null.
884 *
885 * @param array $options
886 * @param int $userid
887 * Probably actually contact ID.
888 *
889 * @return bool
890 */
891 public static function checkCurrentMembership(&$options, $userid) {
892 if (!$userid || empty($options)) {
893 return FALSE;
894 }
895 static $_contact_memberships = [];
896 $checkLifetime = FALSE;
897 foreach ($options as $key => $value) {
898 if (!empty($value['membership_type_id'])) {
899 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
900 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
901 }
902 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
903 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
904 unset($options[$key]);
905 $checkLifetime = TRUE;
906 }
907 }
908 }
909 if ($checkLifetime) {
910 return TRUE;
911 }
912 else {
913 return FALSE;
914 }
915 }
916
917 /**
918 * Set daefult the price set fields.
919 *
920 * @param CRM_Core_Form $form
921 * @param $defaults
922 *
923 * @return array
924 */
925 public static function setDefaultPriceSet(&$form, &$defaults) {
926 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
927 return $defaults;
928 }
929
930 foreach ($form->_priceSet['fields'] as $val) {
931 foreach ($val['options'] as $keys => $values) {
932 // build price field index which is passed via URL
933 // url format will be appended by "&price_5=11"
934 $priceFieldName = 'price_' . $values['price_field_id'];
935 $priceFieldValue = self::getPriceFieldValueFromURL($form, $priceFieldName);
936 if (!empty($priceFieldValue)) {
937 self::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
938 // break here to prevent overwriting of default due to 'is_default'
939 // option configuration. The value sent via URL get's higher priority.
940 break;
941 }
942 elseif ($values['is_default']) {
943 self::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
944 }
945 }
946 }
947 return $defaults;
948 }
949
950 /**
951 * Get the value of price field if passed via url
952 *
953 * @param string $priceFieldName
954 * @param string $priceFieldValue
955 * @param string $priceFieldType
956 * @param array $defaults
957 *
958 * @return void
959 */
960 public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
961 if ($priceFieldType == 'CheckBox') {
962 $defaults[$priceFieldName][$priceFieldValue] = 1;
963 }
964 else {
965 $defaults[$priceFieldName] = $priceFieldValue;
966 }
967 }
968
969 /**
970 * Get the value of price field if passed via url
971 *
972 * @param CRM_Core_Form $form
973 * @param string $priceFieldName
974 *
975 * @return mixed $priceFieldValue
976 */
977 public static function getPriceFieldValueFromURL(&$form, $priceFieldName) {
978 $priceFieldValue = CRM_Utils_Request::retrieve($priceFieldName, 'String', $form, FALSE, NULL, 'GET');
979 if (!empty($priceFieldValue)) {
980 return $priceFieldValue;
981 }
982 }
983
984 /**
985 * Supports event create function by setting up required price sets, not tested but expect
986 * it will work for contribution page
987 * @param array $params
988 * As passed to api/bao create fn.
989 * @param CRM_Core_DAO $entity
990 * Object for given entity.
991 * @param string $entityName
992 * Name of entity - e.g event.
993 */
994 public static function setPriceSets(&$params, $entity, $entityName) {
995 if (empty($params['price_set_id']) || !is_array($params['price_set_id'])) {
996 return;
997 }
998 // CRM-14069 note that we may as well start by assuming more than one.
999 // currently the form does not pass in as an array & will be skipped
1000 // test is passing in as an array but I feel the api should have a metadata that allows
1001 // transform of single to array - seems good for managing transitions - in which case all api
1002 // calls that set price_set_id will hit this
1003 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1004 // all separated values, strings, json half-separated values (in participant we hit this)
1005 // to be converted to json @ api layer
1006 $pse = new CRM_Price_DAO_PriceSetEntity();
1007 $pse->entity_table = 'civicrm_' . $entityName;
1008 $pse->entity_id = $entity->id;
1009 while ($pse->fetch()) {
1010 if (!in_array($pse->price_set_id, $params['price_set_id'])) {
1011 // note an even more aggressive form of this deletion currently happens in event form
1012 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1013 // on the participant record
1014 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_' . $entityName, $entity->id)) {
1015 CRM_Core_BAO_Discount::del($entity->id, 'civicrm_' . $entityName);
1016 }
1017 }
1018 }
1019 foreach ($params['price_set_id'] as $priceSetID) {
1020 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $entityName, $entity->id, $priceSetID);
1021 //@todo - how should we do this - copied from form
1022 //if (!empty($params['price_field_id'])) {
1023 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1024 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1025 //}
1026 }
1027 }
1028
1029 /**
1030 * Get field ids of a price set.
1031 *
1032 * @param int $id
1033 * Price Set id.
1034 *
1035 * @return array
1036 * Array of the field ids
1037 *
1038 */
1039 public static function getFieldIds($id) {
1040 $priceField = new CRM_Price_DAO_PriceField();
1041 $priceField->price_set_id = $id;
1042 $priceField->find();
1043 while ($priceField->fetch()) {
1044 $var[] = $priceField->id;
1045 }
1046 return $var;
1047 }
1048
1049 /**
1050 * Copy a price set, including all the fields
1051 *
1052 * @param int $id
1053 * The price set id to copy.
1054 *
1055 * @return CRM_Price_DAO_PriceSet
1056 */
1057 public static function copy($id) {
1058 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1059 $priceSet = civicrm_api3('PriceSet', 'getsingle', ['id' => $id]);
1060
1061 $newTitle = preg_replace('/\[Copy id \d+\]$/', "", $priceSet['title']);
1062 $title = ts('[Copy id %1]', [1 => $maxId + 1]);
1063 $fieldsFix = [
1064 'replace' => [
1065 'title' => trim($newTitle) . ' ' . $title,
1066 'name' => substr($priceSet['name'], 0, 20) . 'price_set_' . ($maxId + 1),
1067 ],
1068 ];
1069
1070 $copy = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
1071 ['id' => $id],
1072 NULL,
1073 $fieldsFix
1074 );
1075
1076 //copying all the blocks pertaining to the price set
1077 $copyPriceField = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
1078 ['price_set_id' => $id],
1079 ['price_set_id' => $copy->id]
1080 );
1081 if (!empty($copyPriceField)) {
1082 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1083
1084 //copy option group and values
1085 foreach ($price as $originalId => $copyId) {
1086 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
1087 ['price_field_id' => $originalId],
1088 ['price_field_id' => $copyId]
1089 );
1090 }
1091 }
1092 $copy->save();
1093
1094 CRM_Utils_Hook::copy('Set', $copy);
1095 unset(\Civi::$statics['CRM_Core_PseudoConstant']);
1096 return $copy;
1097 }
1098
1099 /**
1100 * check price set permission.
1101 *
1102 * @param int $sid
1103 * The price set id.
1104 *
1105 * @return bool
1106 * @throws \CRM_Core_Exception
1107 */
1108 public static function checkPermission($sid) {
1109 if ($sid && self::eventPriceSetDomainID()) {
1110 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
1111 if (CRM_Core_Config::domainID() != $domain_id) {
1112 CRM_Core_Error::statusBounce(ts('You do not have permission to access this page.'));
1113 }
1114 }
1115 return TRUE;
1116 }
1117
1118 /**
1119 * Get the sum of participant count
1120 * for all fields of given price set.
1121 *
1122 * @param int $sid
1123 * The price set id.
1124 *
1125 * @param bool $onlyActive
1126 *
1127 * @return int|null|string
1128 */
1129 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1130 $count = 0;
1131 if (!$sid) {
1132 return $count;
1133 }
1134
1135 $where = NULL;
1136 if ($onlyActive) {
1137 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1138 }
1139
1140 static $pricesetFieldCount = [];
1141 if (!isset($pricesetFieldCount[$sid])) {
1142 $sql = "
1143 SELECT sum(value.count) as totalCount
1144 FROM civicrm_price_field_value value
1145 INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1146 INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1147 WHERE pset.id = %1
1148 $where";
1149
1150 $count = CRM_Core_DAO::singleValueQuery($sql, [1 => [$sid, 'Positive']]);
1151 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1152 }
1153
1154 return $pricesetFieldCount[$sid];
1155 }
1156
1157 /**
1158 * Return a count of priceFieldValueIDs that are memberships by organisation and membership type
1159 *
1160 * @param string $priceFieldValueIDs
1161 * Comma separated string of priceFieldValue IDs
1162 *
1163 * @return array
1164 * Returns an array of counts by membership organisation
1165 */
1166 public static function getMembershipCount($priceFieldValueIDs) {
1167 $queryString = "
1168 SELECT count( pfv.id ) AS count, mt.member_of_contact_id AS id
1169 FROM civicrm_price_field_value pfv
1170 INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1171 WHERE pfv.id IN ( $priceFieldValueIDs )
1172 GROUP BY mt.member_of_contact_id ";
1173
1174 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1175 $count = [];
1176
1177 while ($crmDAO->fetch()) {
1178 $count[$crmDAO->id] = $crmDAO->count;
1179 }
1180
1181 return $count;
1182 }
1183
1184 /**
1185 * Check if auto renew option should be shown.
1186 *
1187 * The auto-renew option should be visible if membership types associated with all the fields has
1188 * been set for auto-renew option.
1189 *
1190 * Auto renew checkbox should be frozen if for all the membership type auto renew is required
1191 *
1192 * @param int $priceSetId
1193 * Price set id.
1194 *
1195 * @return int
1196 * $autoRenewOption ( 0:hide, 1:optional 2:required )
1197 */
1198 public static function checkAutoRenewForPriceSet($priceSetId) {
1199 $query = 'SELECT DISTINCT mt.auto_renew, mt.duration_interval, mt.duration_unit,
1200 pf.html_type, pf.id as price_field_id
1201 FROM civicrm_price_field_value pfv
1202 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1203 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1204 WHERE pf.price_set_id = %1
1205 AND pf.is_active = 1
1206 AND pfv.is_active = 1
1207 ORDER BY price_field_id';
1208
1209 $params = [1 => [$priceSetId, 'Integer']];
1210
1211 $dao = CRM_Core_DAO::executeQuery($query, $params);
1212
1213 //CRM-18050: Check count of price set fields which has been set with auto-renew option.
1214 //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.
1215 if ($dao->N == 0) {
1216 return 0;
1217 }
1218
1219 $autoRenewOption = 2;
1220 $priceFields = [];
1221 while ($dao->fetch()) {
1222 if (!$dao->auto_renew) {
1223 // If any one can't be renewed none can.
1224 return 0;
1225 }
1226 if ($dao->auto_renew == 1) {
1227 $autoRenewOption = 1;
1228 }
1229
1230 if ($dao->html_type == 'Checkbox' && !in_array($dao->duration_interval . $dao->duration_unit, $priceFields[$dao->price_field_id])) {
1231 // Checkbox fields cannot support auto-renew if they have more than one duration configuration
1232 // as more than one can be selected. Radio and select are either-or so they can have more than one duration.
1233 return 0;
1234 }
1235 $priceFields[$dao->price_field_id][] = $dao->duration_interval . $dao->duration_unit;
1236 foreach ($priceFields as $priceFieldID => $durations) {
1237 if ($priceFieldID != $dao->price_field_id && !in_array($dao->duration_interval . $dao->duration_unit, $durations)) {
1238 // Another price field has a duration configuration that differs so we can't offer auto-renew.
1239 return 0;
1240 }
1241 }
1242 }
1243
1244 return $autoRenewOption;
1245 }
1246
1247 /**
1248 * Retrieve auto renew frequency and interval.
1249 *
1250 * @param int $priceSetId
1251 * Price set id.
1252 *
1253 * @return array
1254 * associate array of frequency interval and unit
1255 */
1256 public static function getRecurDetails($priceSetId) {
1257 $query = 'SELECT mt.duration_interval, mt.duration_unit
1258 FROM civicrm_price_field_value pfv
1259 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1260 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1261 WHERE pf.price_set_id = %1 LIMIT 1';
1262
1263 $params = [1 => [$priceSetId, 'Integer']];
1264 $dao = CRM_Core_DAO::executeQuery($query, $params);
1265 $dao->fetch();
1266 return [$dao->duration_interval, $dao->duration_unit];
1267 }
1268
1269 /**
1270 * @return object
1271 */
1272 public static function eventPriceSetDomainID() {
1273 return Civi::settings()->get('event_price_set_domain_id');
1274 }
1275
1276 /**
1277 * Update the is_quick_config flag in the db.
1278 *
1279 * @param int $id
1280 * Id of the database record.
1281 * @param bool $isQuickConfig we want to set the is_quick_config field.
1282 * Value we want to set the is_quick_config field.
1283 *
1284 * @return bool
1285 * true if we found and updated the object, else false
1286 */
1287 public static function setIsQuickConfig($id, $isQuickConfig) {
1288 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
1289 }
1290
1291 /**
1292 * Check if price set id provides option for user to select both auto-renew and non-auto-renew memberships
1293 *
1294 * @param int $id
1295 *
1296 * @return bool
1297 */
1298 public static function isMembershipPriceSetContainsMixOfRenewNonRenew($id) {
1299 $membershipTypes = self::getMembershipTypesFromPriceSet($id);
1300 if (!empty($membershipTypes['autorenew']) && !empty($membershipTypes['non_renew'])) {
1301 return TRUE;
1302 }
1303 return FALSE;
1304 }
1305
1306 /**
1307 * Get an array of the membership types in a price set.
1308 *
1309 * @param int $id
1310 *
1311 * @return array(
1312 * Membership types in the price set
1313 */
1314 public static function getMembershipTypesFromPriceSet($id) {
1315 $query
1316 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
1317 FROM civicrm_price_field_value pfv
1318 LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1319 LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1320 LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1321 WHERE ps.id = %1
1322 ";
1323
1324 $params = [1 => [$id, 'Integer']];
1325 $dao = CRM_Core_DAO::executeQuery($query, $params);
1326
1327 $membershipTypes = [
1328 'all' => [],
1329 'autorenew' => [],
1330 'autorenew_required' => [],
1331 'autorenew_optional' => [],
1332 ];
1333 while ($dao->fetch()) {
1334 if (empty($dao->membership_type_id)) {
1335 continue;
1336 }
1337 $membershipTypes['all'][] = $dao->membership_type_id;
1338 if (!empty($dao->auto_renew)) {
1339 $membershipTypes['autorenew'][] = $dao->membership_type_id;
1340 if ($dao->auto_renew == 2) {
1341 $membershipTypes['autorenew_required'][] = $dao->membership_type_id;
1342 }
1343 else {
1344 $membershipTypes['autorenew_optional'][] = $dao->membership_type_id;
1345 }
1346 }
1347 else {
1348 $membershipTypes['non_renew'][] = $dao->membership_type_id;
1349 }
1350 }
1351 return $membershipTypes;
1352 }
1353
1354 /**
1355 * Copy priceSet when event/contibution page is copied
1356 *
1357 * @param string $baoName
1358 * BAO name.
1359 * @param int $id
1360 * Old event/contribution page id.
1361 * @param int $newId
1362 * Newly created event/contribution page id.
1363 */
1364 public static function copyPriceSet($baoName, $id, $newId) {
1365 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
1366 if ($priceSetId) {
1367 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
1368 if ($isQuickConfig) {
1369 $copyPriceSet = CRM_Price_BAO_PriceSet::copy($priceSetId);
1370 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
1371 }
1372 else {
1373 $copyPriceSet = CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
1374 [
1375 'entity_id' => $id,
1376 'entity_table' => $baoName,
1377 ],
1378 ['entity_id' => $newId]
1379 );
1380 }
1381 // copy event discount
1382 if ($baoName == 'civicrm_event') {
1383 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1384 foreach ($discount as $discountId => $setId) {
1385
1386 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
1387
1388 CRM_Core_DAO::copyGeneric(
1389 'CRM_Core_DAO_Discount',
1390 [
1391 'id' => $discountId,
1392 ],
1393 [
1394 'entity_id' => $newId,
1395 'price_set_id' => $copyPriceSet->id,
1396 ]
1397 );
1398 }
1399 }
1400 }
1401 }
1402
1403 /**
1404 * Function to set tax_amount and tax_rate in LineItem.
1405 *
1406 * @param array $field
1407 * @param array $lineItem
1408 * @param int $optionValueId
1409 * @param float $totalTax
1410 *
1411 * @return array
1412 */
1413 public static function setLineItem($field, $lineItem, $optionValueId, &$totalTax) {
1414 // Here we round - i.e. after multiplying by quantity
1415 if ($field['html_type'] == 'Text') {
1416 $taxAmount = round($field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'], 2);
1417 }
1418 else {
1419 $taxAmount = round($field['options'][$optionValueId]['tax_amount'], 2);
1420 }
1421 $taxRate = $field['options'][$optionValueId]['tax_rate'];
1422 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1423 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1424 $totalTax += $taxAmount;
1425 return $lineItem;
1426 }
1427
1428 /**
1429 * Get the first price set value IDs from a parameters array.
1430 *
1431 * In practice this is really used when we only expect one to exist.
1432 *
1433 * @param array $params
1434 *
1435 * @return array
1436 * Array of the ids of the price set values.
1437 */
1438 public static function parseFirstPriceSetValueIDFromParams($params) {
1439 $priceSetValueIDs = self::parsePriceSetValueIDsFromParams($params);
1440 return reset($priceSetValueIDs);
1441 }
1442
1443 /**
1444 * Get the price set value IDs from a set of parameters
1445 *
1446 * @param array $params
1447 *
1448 * @return array
1449 * Array of the ids of the price set values.
1450 */
1451 public static function parsePriceSetValueIDsFromParams($params) {
1452 $priceSetParams = self::parsePriceSetArrayFromParams($params);
1453 $priceSetValueIDs = [];
1454 foreach ($priceSetParams as $priceSetParam) {
1455 foreach (array_keys($priceSetParam) as $priceValueID) {
1456 $priceSetValueIDs[] = $priceValueID;
1457 }
1458 }
1459 return $priceSetValueIDs;
1460 }
1461
1462 /**
1463 * Get the price set value IDs from a set of parameters
1464 *
1465 * @param array $params
1466 *
1467 * @return array
1468 * Array of price fields filtered from the params.
1469 */
1470 public static function parsePriceSetArrayFromParams($params) {
1471 $priceSetParams = [];
1472 foreach ($params as $field => $value) {
1473 $parts = explode('_', $field);
1474 if (count($parts) == 2 && $parts[0] == 'price' && is_numeric($parts[1]) && is_array($value)) {
1475 $priceSetParams[$field] = $value;
1476 }
1477 }
1478 return $priceSetParams;
1479 }
1480
1481 /**
1482 * Get non-deductible amount from price options
1483 *
1484 * @param int $priceSetId
1485 * @param array $lineItem
1486 *
1487 * @return int
1488 * calculated non-deductible amount.
1489 */
1490 public static function getNonDeductibleAmountFromPriceSet($priceSetId, $lineItem) {
1491 $nonDeductibleAmount = 0;
1492 if (!empty($lineItem[$priceSetId])) {
1493 foreach ($lineItem[$priceSetId] as $options) {
1494 $nonDeductibleAmount += $options['non_deductible_amount'] * $options['qty'];
1495 }
1496 }
1497
1498 return $nonDeductibleAmount;
1499 }
1500
1501 /**
1502 * Get an array of all forms using a given price set.
1503 *
1504 * @param int $id
1505 *
1506 * @return array
1507 * Pages using the price set, keyed by type. e.g
1508 * array('
1509 * 'civicrm_contribution_page' => array(2,5,6),
1510 * 'civicrm_event' => array(5,6),
1511 * 'civicrm_event_template' => array(7),
1512 * )
1513 */
1514 public static function getFormsUsingPriceSet($id) {
1515 $forms = [];
1516 $queryString = "
1517 SELECT entity_table, entity_id
1518 FROM civicrm_price_set_entity
1519 WHERE price_set_id = %1";
1520 $params = [1 => [$id, 'Integer']];
1521 $crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
1522
1523 while ($crmFormDAO->fetch()) {
1524 $forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
1525 }
1526 return $forms;
1527 }
1528
1529 /**
1530 * @param array $forms
1531 * Array of forms that use a price set keyed by entity. e.g
1532 * array('
1533 * 'civicrm_contribution_page' => array(2,5,6),
1534 * 'civicrm_event' => array(5,6),
1535 * 'civicrm_event_template' => array(7),
1536 * )
1537 *
1538 * @return mixed
1539 * Array of entities suppliemented with per entity information.
1540 * e.g
1541 * array('civicrm_event' => array(7 => array('title' => 'x'...))
1542 *
1543 * @throws \Exception
1544 */
1545 protected static function reformatUsedByFormsWithEntityData($forms) {
1546 $usedBy = [];
1547 foreach ($forms as $table => $entities) {
1548 switch ($table) {
1549 case 'civicrm_event':
1550 $ids = implode(',', $entities);
1551 $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
1552 FROM civicrm_event ce
1553 LEFT JOIN civicrm_option_value ON
1554 ( ce.event_type_id = civicrm_option_value.value )
1555 LEFT JOIN civicrm_option_group ON
1556 ( civicrm_option_group.id = civicrm_option_value.option_group_id )
1557 WHERE
1558 civicrm_option_group.name = 'event_type' AND
1559 ce.id IN ($ids) AND
1560 ce.is_active = 1;";
1561 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1562 while ($crmDAO->fetch()) {
1563 if ($crmDAO->isTemplate) {
1564 $usedBy['civicrm_event_template'][$crmDAO->id]['title'] = $crmDAO->templateTitle;
1565 $usedBy['civicrm_event_template'][$crmDAO->id]['eventType'] = $crmDAO->eventType;
1566 $usedBy['civicrm_event_template'][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
1567 }
1568 else {
1569 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
1570 $usedBy[$table][$crmDAO->id]['eventType'] = $crmDAO->eventType;
1571 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
1572 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
1573 $usedBy[$table][$crmDAO->id]['isPublic'] = $crmDAO->isPublic;
1574 }
1575 }
1576 break;
1577
1578 case 'civicrm_contribution_page':
1579 $ids = implode(',', $entities);
1580 $queryString = "SELECT cp.id as id, cp.title as title, cp.start_date as startDate, cp.end_date as endDate,ct.name as type
1581 FROM civicrm_contribution_page cp, civicrm_financial_type ct
1582 WHERE ct.id = cp.financial_type_id AND
1583 cp.id IN ($ids) AND
1584 cp.is_active = 1;";
1585 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1586 while ($crmDAO->fetch()) {
1587 $usedBy[$table][$crmDAO->id]['title'] = $crmDAO->title;
1588 $usedBy[$table][$crmDAO->id]['type'] = $crmDAO->type;
1589 $usedBy[$table][$crmDAO->id]['startDate'] = $crmDAO->startDate;
1590 $usedBy[$table][$crmDAO->id]['endDate'] = $crmDAO->endDate;
1591 }
1592 break;
1593
1594 case 'civicrm_contribution':
1595 case 'civicrm_membership':
1596 case 'civicrm_participant':
1597 $usedBy[$table] = 1;
1598 break;
1599
1600 default:
1601 throw new CRM_Core_Exception("$table is not supported in PriceSet::usedBy()");
1602
1603 }
1604 }
1605 return $usedBy;
1606 }
1607
1608 /**
1609 * Get the relevant line item.
1610 *
1611 * Note this is part of code being cleaned up / refactored & may change.
1612 *
1613 * @param array $params
1614 * @param array $lineItem
1615 * @param int $priceSetID
1616 * @param array $field
1617 * @param int $id
1618 *
1619 * @return array
1620 */
1621 public static function getLine(&$params, &$lineItem, $priceSetID, $field, $id): array {
1622 $totalTax = 0;
1623 switch ($field['html_type']) {
1624 case 'Text':
1625 $firstOption = reset($field['options']);
1626 $params["price_{$id}"] = [$firstOption['id'] => $params["price_{$id}"]];
1627 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
1628 $optionValueId = key($field['options']);
1629
1630 if (CRM_Utils_Array::value('name', $field['options'][$optionValueId]) === 'contribution_amount') {
1631 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
1632 if (array_key_exists($params['financial_type_id'], $taxRates)) {
1633 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
1634 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][$optionValueId]['amount'], $field['options'][$optionValueId]['tax_rate']);
1635 $field['options'][$optionValueId]['tax_amount'] = round($taxAmount['tax_amount'], 2);
1636 }
1637 }
1638 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1639 $lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1640 }
1641 break;
1642
1643 case 'Radio':
1644 //special case if user select -none-
1645 if ($params["price_{$id}"] <= 0) {
1646 break;
1647 }
1648 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1649 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
1650
1651 // CRM-18701 Sometimes the amount in the price set is overridden by the amount on the form.
1652 // This is notably the case with memberships and we need to put this amount
1653 // on the line item rather than the calculated amount.
1654 // This seems to only affect radio link items as that is the use case for the 'quick config'
1655 // set up (which allows a free form field).
1656 // @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
1657 // don't specifically need it & find a better way where we do.
1658 $amount_override = NULL;
1659
1660 if ($priceSetID && count(self::filterPriceFieldsFromParams($priceSetID, $params)) === 1) {
1661 $amount_override = CRM_Utils_Array::value('total_amount', $params);
1662 }
1663 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem, $amount_override);
1664 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1665 $lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1666 if ($amount_override) {
1667 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
1668 }
1669 }
1670 break;
1671
1672 case 'Select':
1673 $params["price_{$id}"] = [$params["price_{$id}"] => 1];
1674 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
1675
1676 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
1677 if (!empty($field['options'][$optionValueId]['tax_rate'])) {
1678 $lineItem = self::setLineItem($field, $lineItem, $optionValueId, $totalTax);
1679 }
1680 break;
1681
1682 case 'CheckBox':
1683
1684 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
1685 foreach ($params["price_{$id}"] as $optionId => $option) {
1686 if (!empty($field['options'][$optionId]['tax_rate'])) {
1687 $lineItem = self::setLineItem($field, $lineItem, $optionId, $totalTax);
1688 }
1689 }
1690 break;
1691 }
1692 return [$params, $lineItem];
1693 }
1694
1695 /**
1696 * Add the relevant price fields to the form.
1697 *
1698 * @param \CRM_Core_Form $form
1699 * @param array $feeBlock
1700 * @param bool $validFieldsOnly
1701 * @param string $className
1702 * @param array $validPriceFieldIds
1703 */
1704 protected static function addPriceFieldsToForm(CRM_Core_Form $form, $feeBlock, bool $validFieldsOnly, string $className, array $validPriceFieldIds) {
1705 $hideAdminValues = !CRM_Core_Permission::check('edit contributions');
1706 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
1707 $adminFieldVisible = CRM_Core_Permission::check('administer CiviCRM');
1708 foreach ($feeBlock as $id => $field) {
1709 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
1710 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
1711 !$validFieldsOnly
1712 ) {
1713 $options = $field['options'] ?? NULL;
1714 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
1715 $userid = $form->getVar('_membershipContactID');
1716 $checklifetime = self::checkCurrentMembership($options, $userid);
1717 if ($checklifetime) {
1718 $form->assign('ispricelifetime', TRUE);
1719 }
1720 }
1721
1722 $formClasses = ['CRM_Contribute_Form_Contribution', 'CRM_Member_Form_Membership'];
1723
1724 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
1725 continue;
1726 }
1727 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
1728 foreach ($options as $key => $currentOption) {
1729 if ($currentOption['visibility_id'] == CRM_Price_BAO_PriceField::getVisibilityOptionID('admin')) {
1730 unset($options[$key]);
1731 }
1732 }
1733 }
1734 if (!empty($options)) {
1735 CRM_Price_BAO_PriceField::addQuickFormElement($form,
1736 'price_' . $field['id'],
1737 $field['id'],
1738 FALSE,
1739 CRM_Utils_Array::value('is_required', $field, FALSE),
1740 NULL,
1741 $options
1742 );
1743 }
1744 }
1745 }
1746 }
1747
1748 }