forked from civicrm/civicrm-core
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPriceSet.php
1781 lines (1636 loc) · 59.7 KB
/
PriceSet.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
/**
* Business object for managing price sets.
*
*/
class CRM_Price_BAO_PriceSet extends CRM_Price_DAO_PriceSet {
/**
* Static field for default price set details.
*
* @var array
*/
public static $_defaultPriceSet = NULL;
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Takes an associative array and creates a price set object.
*
* @param array $params
* (reference) an assoc array of name/value pairs.
*
* @return CRM_Price_DAO_PriceSet
*/
public static function create(&$params) {
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'PriceSet', CRM_Utils_Array::value('id', $params), $params);
if (empty($params['id']) && empty($params['name'])) {
$params['name'] = CRM_Utils_String::munge($params['title'], '_', 242);
}
$priceSetID = NULL;
$validatePriceSet = TRUE;
if (!empty($params['extends']) && is_array($params['extends'])) {
if (!array_key_exists(CRM_Core_Component::getComponentID('CiviEvent'), $params['extends'])
|| !array_key_exists(CRM_Core_Component::getComponentID('CiviMember'), $params['extends'])
) {
$validatePriceSet = FALSE;
}
$params['extends'] = CRM_Utils_Array::implodePadded($params['extends']);
}
else {
$priceSetID = $params['id'] ?? NULL;
}
$priceSetBAO = new CRM_Price_BAO_PriceSet();
$priceSetBAO->copyValues($params);
if (self::eventPriceSetDomainID()) {
$priceSetBAO->domain_id = CRM_Core_Config::domainID();
}
$priceSetBAO->save();
CRM_Utils_Hook::post($hook, 'PriceSet', $priceSetBAO->id, $priceSetBAO);
unset(\Civi::$statics['CRM_Core_PseudoConstant']);
return $priceSetBAO;
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Price_DAO_PriceSet
*/
public static function retrieve(&$params, &$defaults) {
return CRM_Core_DAO::commonRetrieve('CRM_Price_DAO_PriceSet', $params, $defaults);
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param $isActive
*
* @return bool
* true if we found and updated the object, else false
*/
public static function setIsActive($id, $isActive) {
return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_active', $isActive);
}
/**
* Calculate the default price set id
* assigned to the contribution/membership etc
*
* @param string $entity
*
* @return array
* default price set
*
*/
public static function getDefaultPriceSet($entity = 'contribution') {
if (isset(\Civi::$statics[__CLASS__][$entity])) {
return \Civi::$statics[__CLASS__][$entity];
}
$priceSetName = ($entity === 'membership') ? 'default_membership_type_amount' : 'default_contribution_amount';
$sql = "
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
FROM civicrm_price_set ps
LEFT JOIN civicrm_price_field pf ON pf.`price_set_id` = ps.id
LEFT JOIN civicrm_price_field_value pfv ON pfv.price_field_id = pf.id
WHERE ps.name = '{$priceSetName}'
";
$dao = CRM_Core_DAO::executeQuery($sql);
while ($dao->fetch()) {
\Civi::$statics[__CLASS__][$entity][$dao->priceFieldValueID] = [
'setID' => $dao->setID,
'priceFieldID' => $dao->priceFieldID,
'name' => $dao->name,
'label' => $dao->label,
'priceFieldValueID' => $dao->priceFieldValueID,
'membership_type_id' => $dao->membership_type_id,
'amount' => $dao->amount,
'financial_type_id' => $dao->financial_type_id,
];
}
return \Civi::$statics[__CLASS__][$entity];
}
/**
* Get the price set title.
*
* @param int $id
* Id of price set.
*
* @return string
* title
*
*/
public static function getTitle($id) {
return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $id, 'title');
}
/**
* Return a list of all forms which use this price set.
*
* @param int $id
* Id of price set.
* @param bool|string $simpleReturn - get raw data. Possible values: 'entity', 'table'
*
* @return array
*/
public static function getUsedBy($id, $simpleReturn = FALSE) {
$usedBy = [];
$forms = self::getFormsUsingPriceSet($id);
$tables = array_keys($forms);
// @todo - this is really clumsy overloading the signature like this. Instead
// move towards having a function that does not call reformatUsedByFormsWithEntityData
// and call that when that data is not used.
if ($simpleReturn == 'table') {
return $tables;
}
// @todo - this is painfully slow in some cases.
if (empty($forms)) {
$queryString = "
SELECT cli.entity_table, cli.entity_id
FROM civicrm_line_item cli
LEFT JOIN civicrm_price_field cpf ON cli.price_field_id = cpf.id
WHERE cpf.price_set_id = %1";
$params = [1 => [$id, 'Integer']];
$crmFormDAO = CRM_Core_DAO::executeQuery($queryString, $params);
while ($crmFormDAO->fetch()) {
$forms[$crmFormDAO->entity_table][] = $crmFormDAO->entity_id;
$tables[] = $crmFormDAO->entity_table;
}
if (empty($forms)) {
return $usedBy;
}
}
// @todo - this is really clumsy overloading the signature like this. See above.
if ($simpleReturn == 'entity') {
return $forms;
}
$usedBy = self::reformatUsedByFormsWithEntityData($forms, $usedBy);
return $usedBy;
}
/**
* Delete the price set, including the fields.
*
* @param int $id
* Price Set id.
*
* @return bool
* false if fields exist for this set, true if the
* set could be deleted
*
*/
public static function deleteSet($id) {
// delete price fields
$priceField = new CRM_Price_DAO_PriceField();
$priceField->price_set_id = $id;
$priceField->find();
while ($priceField->fetch()) {
// delete options first
CRM_Price_BAO_PriceField::deleteField($priceField->id);
}
$set = new CRM_Price_DAO_PriceSet();
$set->id = $id;
return $set->delete();
}
/**
* Link the price set with the specified table and id.
*
* @param string $entityTable
* @param int $entityId
* @param int $priceSetId
*
* @return bool
*/
public static function addTo($entityTable, $entityId, $priceSetId) {
// verify that the price set exists
$dao = new CRM_Price_DAO_PriceSet();
$dao->id = $priceSetId;
if (!$dao->find()) {
return FALSE;
}
unset($dao);
$dao = new CRM_Price_DAO_PriceSetEntity();
// find if this already exists
$dao->entity_id = $entityId;
$dao->entity_table = $entityTable;
$dao->find(TRUE);
// add or update price_set_id
$dao->price_set_id = $priceSetId;
return $dao->save();
}
/**
* Delete price set for the given entity and id.
*
* @param string $entityTable
* @param int $entityId
*
* @return mixed
*/
public static function removeFrom($entityTable, $entityId) {
$dao = new CRM_Price_DAO_PriceSetEntity();
$dao->entity_table = $entityTable;
$dao->entity_id = $entityId;
return $dao->delete();
}
/**
* Find a price_set_id associated with the given table, id and usedFor
* Used For value for events:1, contribution:2, membership:3
*
* @param string $entityTable
* @param int $entityId
* @param int $usedFor
* ( price set that extends/used for particular component ).
*
* @param null $isQuickConfig
* @param null $setName
*
* @return int|false
* price_set_id, or false if none found
*/
public static function getFor($entityTable, $entityId, $usedFor = NULL, $isQuickConfig = NULL, &$setName = NULL) {
if (!$entityTable || !$entityId) {
return FALSE;
}
$sql = 'SELECT ps.id as price_set_id, ps.name as price_set_name
FROM civicrm_price_set ps
INNER JOIN civicrm_price_set_entity pse ON ps.id = pse.price_set_id
WHERE pse.entity_table = %1 AND pse.entity_id = %2 ';
if ($isQuickConfig) {
$sql .= ' AND ps.is_quick_config = 0 ';
}
$params = [
1 => [$entityTable, 'String'],
2 => [$entityId, 'Integer'],
];
if ($usedFor) {
$sql .= " AND ps.extends LIKE '%%3%' ";
$params[3] = [$usedFor, 'Integer'];
}
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$dao->fetch();
$setName = (isset($dao->price_set_name)) ? $dao->price_set_name : FALSE;
return (isset($dao->price_set_id)) ? $dao->price_set_id : FALSE;
}
/**
* Find a price_set_id associated with the given option value or field ID.
*
* @param array $params
* (reference) an assoc array of name/value pairs.
* array may contain either option id or
* price field id
*
* @return int|null
* price set id on success, null otherwise
*/
public static function getSetId(&$params) {
$fid = NULL;
if ($oid = CRM_Utils_Array::value('oid', $params)) {
$fieldValue = new CRM_Price_DAO_PriceFieldValue();
$fieldValue->id = $oid;
if ($fieldValue->find(TRUE)) {
$fid = $fieldValue->price_field_id;
}
}
else {
$fid = $params['fid'] ?? NULL;
}
if (isset($fid)) {
return CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $fid, 'price_set_id');
}
return NULL;
}
/**
* Return an associative array of all price sets.
*
* @param bool $withInactive
* Whether or not to include inactive entries.
* @param bool|string $extendComponentName name of the component like 'CiviEvent','CiviContribute'
* @param string $column name of the column.
*
* @return array
* associative array of id => name
*/
public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE, $column = 'title') {
$query = "
SELECT
DISTINCT ( price_set_id ) as id, s.{$column}
FROM
civicrm_price_set s
INNER JOIN civicrm_price_field f ON f.price_set_id = s.id
INNER JOIN civicrm_price_field_value v ON v.price_field_id = f.id
WHERE
is_quick_config = 0 ";
if (!$withInactive) {
$query .= ' AND s.is_active = 1 ';
}
if (self::eventPriceSetDomainID()) {
$query .= ' AND s.domain_id = ' . CRM_Core_Config::domainID();
}
$priceSets = [];
if ($extendComponentName) {
$componentId = CRM_Core_Component::getComponentID($extendComponentName);
if (!$componentId) {
return $priceSets;
}
$query .= " AND s.extends LIKE '%$componentId%' ";
}
// Check permissioned financial types
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialType, CRM_Core_Action::ADD);
if ($financialType) {
$types = implode(',', array_keys($financialType));
$query .= ' AND s.financial_type_id IN (' . $types . ') AND v.financial_type_id IN (' . $types . ') ';
}
else {
// Do not display any price sets
$query .= " AND 0 ";
}
$query .= " GROUP BY s.id";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$priceSets[$dao->id] = $dao->$column;
}
return $priceSets;
}
/**
* Get price set details.
*
* An array containing price set details (including price fields) is returned
*
* @param int $setID
* Price Set ID.
* @param bool $required
* Appears to have no effect based on reading the code.
* @param bool $doNotIncludeExpiredFields
* Should only fields where today's date falls within the valid range be returned?
*
* @return array
* Array consisting of field details
*/
public static function getSetDetail($setID, $required = TRUE, $doNotIncludeExpiredFields = FALSE) {
// create a new tree
$setTree = [];
$priceFields = [
'id',
'name',
'label',
'html_type',
'is_enter_qty',
'help_pre',
'help_post',
'weight',
'is_display_amounts',
'options_per_line',
'is_active',
'active_on',
'expire_on',
'javascript',
'visibility_id',
'is_required',
];
if ($required == TRUE) {
$priceFields[] = 'is_required';
}
// create select
$select = 'SELECT ' . implode(',', $priceFields);
$from = ' FROM civicrm_price_field';
$params = [
1 => [$setID, 'Integer'],
];
$currentTime = date('YmdHis');
$where = "
WHERE price_set_id = %1
AND is_active = 1
AND ( active_on IS NULL OR active_on <= {$currentTime} )
";
$dateSelect = '';
if ($doNotIncludeExpiredFields) {
$dateSelect = "
AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
";
}
$orderBy = ' ORDER BY weight';
$sql = $select . $from . $where . $dateSelect . $orderBy;
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$isDefaultContributionPriceSet = FALSE;
if ('default_contribution_amount' == CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID)) {
$isDefaultContributionPriceSet = TRUE;
}
$visibility = CRM_Core_PseudoConstant::visibility('name');
while ($dao->fetch()) {
$fieldID = $dao->id;
$setTree[$setID]['fields'][$fieldID] = [];
$setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
foreach ($priceFields as $field) {
if ($field == 'id' || is_null($dao->$field)) {
continue;
}
if ($field == 'visibility_id') {
$setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
}
$setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
}
$setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE, FALSE, $isDefaultContributionPriceSet);
}
// also get the pre and post help from this price set
$sql = "
SELECT extends, financial_type_id, help_pre, help_post, is_quick_config, min_amount
FROM civicrm_price_set
WHERE id = %1";
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if ($dao->fetch()) {
$setTree[$setID]['extends'] = $dao->extends;
$setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
$setTree[$setID]['help_pre'] = $dao->help_pre;
$setTree[$setID]['help_post'] = $dao->help_post;
$setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
$setTree[$setID]['min_amount'] = $dao->min_amount;
}
return $setTree;
}
/**
* Get the Price Field ID.
*
* We call this function when more than one being present would represent an error
* starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
* @param array $priceSet
*
* @throws CRM_Core_Exception
* @return int
*/
public static function getOnlyPriceFieldID(array $priceSet) {
if (count($priceSet['fields']) > 1) {
throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
}
return (int) implode('_', array_keys($priceSet['fields']));
}
/**
* Get the Price Field Value ID. We call this function when more than one being present would represent an error
* current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
* @param array $priceSet
*
* @throws CRM_Core_Exception
* @return int
*/
public static function getOnlyPriceFieldValueID(array $priceSet) {
$priceFieldID = self::getOnlyPriceFieldID($priceSet);
if (count($priceSet['fields'][$priceFieldID]['options']) > 1) {
throw new CRM_Core_Exception(ts('expected only one price field to be in price set but multiple are present'));
}
return (int) implode('_', array_keys($priceSet['fields'][$priceFieldID]['options']));
}
/**
* Initiate price set such that various non-BAO things are set on the form.
*
* This function is not really a BAO function so the location is misleading.
*
* @param CRM_Core_Form $form
* Form entity id.
* @param string $entityTable
* @param bool $doNotIncludeExpiredFields
* @param int $priceSetId
* Price Set ID
*/
public static function initSet(&$form, $entityTable = 'civicrm_event', $doNotIncludeExpiredFields = FALSE, $priceSetId = NULL) {
//check if price set is is_config
if (is_numeric($priceSetId)) {
if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
$form->assign('quickConfig', 1);
}
}
// get price info
if ($priceSetId) {
if ($form->_action & CRM_Core_Action::UPDATE) {
$entityId = $entity = NULL;
switch ($entityTable) {
case 'civicrm_event':
$entity = 'participant';
if (in_array(CRM_Utils_System::getClassName($form), ['CRM_Event_Form_Participant', 'CRM_Event_Form_Task_Register'])) {
$entityId = $form->_id;
}
else {
$entityId = $form->_participantId;
}
break;
case 'civicrm_contribution_page':
case 'civicrm_contribution':
$entity = 'contribution';
$entityId = $form->_id;
break;
}
if ($entityId && $entity) {
$form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
}
$required = FALSE;
}
else {
$required = TRUE;
}
$form->_priceSetId = $priceSetId;
$priceSet = self::getSetDetail($priceSetId, $required, $doNotIncludeExpiredFields);
$form->_priceSet = $priceSet[$priceSetId] ?? NULL;
$form->_values['fee'] = $form->_priceSet['fields'] ?? NULL;
//get the price set fields participant count.
if ($entityTable == 'civicrm_event') {
//get option count info.
$form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
if ($form->_priceSet['optionsCountTotal']) {
$optionsCountDetails = [];
if (!empty($form->_priceSet['fields'])) {
foreach ($form->_priceSet['fields'] as $field) {
foreach ($field['options'] as $option) {
$count = CRM_Utils_Array::value('count', $option, 0);
$optionsCountDetails['fields'][$field['id']]['options'][$option['id']] = $count;
}
}
}
$form->_priceSet['optionsCountDetails'] = $optionsCountDetails;
}
//get option max value info.
$optionsMaxValueTotal = 0;
$optionsMaxValueDetails = [];
if (!empty($form->_priceSet['fields'])) {
foreach ($form->_priceSet['fields'] as $field) {
foreach ($field['options'] as $option) {
$maxVal = CRM_Utils_Array::value('max_value', $option, 0);
$optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
$optionsMaxValueTotal += $maxVal;
}
}
}
$form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
if ($optionsMaxValueTotal) {
$form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
}
}
$form->set('priceSetId', $form->_priceSetId);
$form->set('priceSet', $form->_priceSet);
}
}
/**
* Get line item purchase information.
*
* This function takes the input parameters and interprets out of it what has been purchased.
*
* @param $fields
* This is the output of the function CRM_Price_BAO_PriceSet::getSetDetail($priceSetID, FALSE, FALSE);
* And, it would make sense to introduce caching into that function and call it from here rather than
* require the $fields array which is passed from pillar to post around the form in order to pass it in here.
* @param array $params
* Params reflecting form input e.g with fields 'price_5' => 7, 'price_8' => array(7, 8)
* @param $lineItem
* Line item array to be altered.
* @param int $priceSetID
*
* @todo $priceSetID is a pseudoparam for permit override - we should stop passing it where we
* don't specifically need it & find a better way where we do.
*/
public static function processAmount($fields, &$params, &$lineItem, $priceSetID = NULL) {
// using price set
$totalPrice = $totalTax = 0;
foreach ($fields as $id => $field) {
if (empty($params["price_{$id}"]) ||
(empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
) {
// skip if nothing was submitted for this field
continue;
}
[$params, $lineItem] = self::getLine($params, $lineItem, $priceSetID, $field, $id);
}
$amount_level = [];
$totalParticipant = 0;
if (is_array($lineItem)) {
foreach ($lineItem as $values) {
$totalPrice += $values['line_total'] + $values['tax_amount'];
$totalTax += $values['tax_amount'];
$totalParticipant += $values['participant_count'];
// This is a bit nasty. The logic of 'quick config' was because price set configuration was
// (and still is) too difficult to replace the 'quick config' price set configuration on the contribution
// page.
//
// However, because the quick config concept existed all sorts of logic was hung off it
// and function behaviour sometimes depends on whether 'price set' is set - although actually it
// is always set at the functional level. In this case we are dealing with the default 'quick config'
// price set having a label of 'Contribution Amount' which could wind up creating a 'funny looking' label.
// The correct answer is probably for it to have an empty label in the DB - the label is never shown so it is a
// place holder.
//
// But, in the interests of being careful when capacity is low - avoiding the known default value
// will get us by.
// Crucially a test has been added so a better solution can be implemented later with some comfort.
// @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
if ($values['label'] !== ts('Contribution Amount')) {
$amount_level[] = $values['label'] . ' - ' . (float) $values['qty'];
}
}
}
$displayParticipantCount = '';
if ($totalParticipant > 0) {
$displayParticipantCount = ' Participant Count -' . $totalParticipant;
}
// @todo - stop setting amount level in this function & call the getAmountLevel function to retrieve it.
if (!empty($amount_level)) {
$params['amount_level'] = CRM_Utils_Array::implodePadded($amount_level);
if (!empty($displayParticipantCount)) {
$params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
}
}
$params['amount'] = $totalPrice;
$params['tax_amount'] = $totalTax;
}
/**
* Get the text to record for amount level.
*
* @param array $params
* Submitted parameters
* - priceSetId is required to be set in the calling function
* (we don't e-notice check it to enforce that - all payments DO have a price set - even if it is the
* default one & this function asks that be set if it is the case).
*
* @return string
* Text for civicrm_contribution.amount_level field.
*/
public static function getAmountLevelText($params) {
$priceSetID = $params['priceSetId'];
$priceFieldSelection = self::filterPriceFieldsFromParams($priceSetID, $params);
$priceFieldMetadata = self::getCachedPriceSetDetail($priceSetID);
$displayParticipantCount = NULL;
$amount_level = [];
foreach ($priceFieldMetadata['fields'] as $field) {
if (!empty($priceFieldSelection[$field['id']])) {
$qtyString = '';
if ($field['is_enter_qty']) {
$qtyString = ' - ' . (float) $params['price_' . $field['id']];
}
// We deliberately & specifically exclude contribution amount as it has a specific meaning.
// ie. it represents the default price field for a contribution. Another approach would be not
// to give it a label if we don't want it to show.
if ($field['label'] !== ts('Contribution Amount')) {
$amount_level[] = $field['label'] . $qtyString;
}
}
}
return CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
}
/**
* Get the fields relevant to the price field from the parameters.
*
* E.g we are looking for price_5 => 7 out of a big array of input parameters.
*
* @param int $priceSetID
* @param array $params
*
* @return array
* Price fields found in the params array
*/
public static function filterPriceFieldsFromParams($priceSetID, $params) {
$priceSet = self::getCachedPriceSetDetail($priceSetID);
$return = [];
foreach ($priceSet['fields'] as $field) {
if (!empty($params['price_' . $field['id']])) {
$return[$field['id']] = $params['price_' . $field['id']];
}
}
return $return;
}
/**
* Wrapper for getSetDetail with caching.
*
* We seem to be passing this array around in a painful way - presumably to avoid the hit
* of loading it - so lets make it callable with caching.
*
* Why not just add caching to the other function? We could do - it just seemed a bit unclear the best caching pattern
* & the function was already pretty fugly. Also, I feel like we need to migrate the interaction with price-sets into
* a more granular interaction - ie. retrieve specific data using specific functions on this class & have the form
* think less about the price sets.
*
* @param int $priceSetID
*
* @return array
*/
public static function getCachedPriceSetDetail($priceSetID) {
$cacheKey = __CLASS__ . __FUNCTION__ . '_' . $priceSetID;
$cache = CRM_Utils_Cache::singleton();
$values = $cache->get($cacheKey);
if (empty($values)) {
$data = self::getSetDetail($priceSetID);
$values = $data[$priceSetID];
$cache->set($cacheKey, $values);
}
return $values;
}
/**
* Build the price set form.
*
* @param CRM_Core_Form $form
*
* @return void
*/
public static function buildPriceSet(&$form) {
$priceSetId = $form->get('priceSetId');
if (!$priceSetId) {
return;
}
$validFieldsOnly = TRUE;
$className = CRM_Utils_System::getClassName($form);
if (in_array($className, [
'CRM_Contribute_Form_Contribution',
'CRM_Member_Form_Membership',
])) {
$validFieldsOnly = FALSE;
}
$priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
$form->_priceSet = $priceSet[$priceSetId] ?? NULL;
$validPriceFieldIds = array_keys($form->_priceSet['fields']);
$form->_quickConfig = $quickConfig = 0;
if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
$quickConfig = 1;
}
$form->assign('quickConfig', $quickConfig);
if ($className == 'CRM_Contribute_Form_Contribution_Main') {
$form->_quickConfig = $quickConfig;
}
// Mark which field should have the auto-renew checkbox, if any. CRM-18305
if (!empty($form->_membershipTypeValues) && is_array($form->_membershipTypeValues)) {
$autoRenewMembershipTypes = [];
foreach ($form->_membershipTypeValues as $membershipTypeValue) {
if ($membershipTypeValue['auto_renew']) {
$autoRenewMembershipTypes[] = $membershipTypeValue['id'];
}
}
foreach ($form->_priceSet['fields'] as $field) {
if (array_key_exists('options', $field) && is_array($field['options'])) {
foreach ($field['options'] as $option) {
if (!empty($option['membership_type_id'])) {
if (in_array($option['membership_type_id'], $autoRenewMembershipTypes)) {
$form->_priceSet['auto_renew_membership_field'] = $field['id'];
// Only one field can offer auto_renew memberships, so break here.
break;
}
}
}
}
}
}
$form->_priceSet['id'] = $form->_priceSet['id'] ?? $priceSetId;
$form->assign('priceSet', $form->_priceSet);
$component = 'contribution';
if ($className == 'CRM_Member_Form_Membership') {
$component = 'membership';
}
if ($className == 'CRM_Contribute_Form_Contribution_Main') {
$feeBlock = &$form->_values['fee'];
if (!empty($form->_useForMember)) {
$component = 'membership';
}
}
else {
$feeBlock = &$form->_priceSet['fields'];
}
// Call the buildAmount hook.
CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
self::addPriceFieldsToForm($form, $feeBlock, $validFieldsOnly, $className, $validPriceFieldIds);
}
/**
* Apply ACLs on Financial Type to the price options in a fee block.
*
* @param array $feeBlock
* Fee block: array of price fields.
*
* @deprecated not used in civi universe as at Oct 2020.
*
* @return void
*/
public static function applyACLFinancialTypeStatusToFeeBlock(&$feeBlock) {
CRM_Core_Error::deprecatedFunctionWarning('enacted in financialtypeacl extension');
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
foreach ($feeBlock as $key => $value) {
foreach ($value['options'] as $k => $options) {
if (!CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($options['financial_type_id']))) {
unset($feeBlock[$key]['options'][$k]);
}
}
if (empty($feeBlock[$key]['options'])) {
unset($feeBlock[$key]);
}
}
}
}
/**
* Check the current Membership having end date null.
*
* @param array $options
* @param int $userid
* Probably actually contact ID.
*
* @return bool
*/
public static function checkCurrentMembership(&$options, $userid) {
if (!$userid || empty($options)) {
return FALSE;
}
static $_contact_memberships = [];
$checkLifetime = FALSE;
foreach ($options as $key => $value) {
if (!empty($value['membership_type_id'])) {
if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
$_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
}
$currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
unset($options[$key]);
$checkLifetime = TRUE;
}
}
}
if ($checkLifetime) {
return TRUE;
}
else {
return FALSE;
}
}
/**
* Set daefult the price set fields.
*
* @param CRM_Core_Form $form
* @param $defaults
*
* @return array
*/
public static function setDefaultPriceSet(&$form, &$defaults) {
if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
return $defaults;
}
foreach ($form->_priceSet['fields'] as $val) {
foreach ($val['options'] as $keys => $values) {
// build price field index which is passed via URL
// url format will be appended by "&price_5=11"
$priceFieldName = 'price_' . $values['price_field_id'];
$priceFieldValue = self::getPriceFieldValueFromURL($form, $priceFieldName);
if (!empty($priceFieldValue)) {
self::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $defaults);
// break here to prevent overwriting of default due to 'is_default'
// option configuration. The value sent via URL get's higher priority.
break;
}
elseif ($values['is_default']) {
self::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $defaults);
}
}
}
return $defaults;
}
/**
* Get the value of price field if passed via url
*
* @param string $priceFieldName
* @param string $priceFieldValue
* @param string $priceFieldType
* @param array $defaults
*
* @return void
*/
public static function setDefaultPriceSetField($priceFieldName, $priceFieldValue, $priceFieldType, &$defaults) {
if ($priceFieldType == 'CheckBox') {
$defaults[$priceFieldName][$priceFieldValue] = 1;
}
else {
$defaults[$priceFieldName] = $priceFieldValue;
}
}