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