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