CRM-15932 - Additional QA fixes
[civicrm-core.git] / CRM / Price / BAO / PriceSet.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
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
CW
102 * @return Object
103 * DAO object on sucess, 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'
6a488035 439 *
a6c01b45
CW
440 * @return array
441 * associative array of id => name
6a488035
TO
442 */
443 public static function getAssoc($withInactive = FALSE, $extendComponentName = FALSE) {
444 $query = '
445 SELECT
446 DISTINCT ( price_set_id ) as id, title
447 FROM
448 civicrm_price_field,
449 civicrm_price_set
450 WHERE
451 civicrm_price_set.id = civicrm_price_field.price_set_id AND is_quick_config = 0 ';
452
453 if (!$withInactive) {
454 $query .= ' AND civicrm_price_set.is_active = 1 ';
455 }
456
457 if (self::eventPriceSetDomainID()) {
458 $query .= ' AND civicrm_price_set.domain_id = ' . CRM_Core_Config::domainID();
459 }
460
461 $priceSets = array();
462
463 if ($extendComponentName) {
464 $componentId = CRM_Core_Component::getComponentID($extendComponentName);
465 if (!$componentId) {
466 return $priceSets;
467 }
468 $query .= " AND civicrm_price_set.extends LIKE '%$componentId%' ";
469 }
470
471 $dao = CRM_Core_DAO::executeQuery($query);
472 while ($dao->fetch()) {
473 $priceSets[$dao->id] = $dao->title;
474 }
475 return $priceSets;
476 }
477
478 /**
fe482240 479 * Get price set details.
6a488035
TO
480 *
481 * An array containing price set details (including price fields) is returned
482 *
100fef9d 483 * @param int $setID
2a6da8d7
EM
484 * @param bool $required
485 * @param bool $validOnly
486 *
a6c01b45
CW
487 * @return array
488 * array consisting of field details
6a488035
TO
489 */
490 public static function getSetDetail($setID, $required = TRUE, $validOnly = FALSE) {
491 // create a new tree
492 $setTree = array();
6a488035
TO
493
494 $priceFields = array(
495 'id',
496 'name',
497 'label',
498 'html_type',
499 'is_enter_qty',
500 'help_pre',
501 'help_post',
502 'weight',
503 'is_display_amounts',
504 'options_per_line',
505 'is_active',
506 'active_on',
507 'expire_on',
508 'javascript',
509 'visibility_id',
510 'is_required',
511 );
512 if ($required == TRUE) {
513 $priceFields[] = 'is_required';
514 }
515
516 // create select
517 $select = 'SELECT ' . implode(',', $priceFields);
518 $from = ' FROM civicrm_price_field';
519
353ffa53 520 $params = array();
6a488035 521 $params[1] = array($setID, 'Integer');
353ffa53 522 $where = '
6a488035
TO
523WHERE price_set_id = %1
524AND is_active = 1
525';
526 $dateSelect = '';
527 if ($validOnly) {
528 $currentTime = date('YmdHis');
529 $dateSelect = "
530AND ( active_on IS NULL OR active_on <= {$currentTime} )
531AND ( expire_on IS NULL OR expire_on >= {$currentTime} )
532";
533 }
534
535 $orderBy = ' ORDER BY weight';
536
537 $sql = $select . $from . $where . $dateSelect . $orderBy;
538
539 $dao = CRM_Core_DAO::executeQuery($sql, $params);
540
541 $visibility = CRM_Core_PseudoConstant::visibility('name');
542 while ($dao->fetch()) {
543 $fieldID = $dao->id;
544
545 $setTree[$setID]['fields'][$fieldID] = array();
546 $setTree[$setID]['fields'][$fieldID]['id'] = $fieldID;
547
548 foreach ($priceFields as $field) {
549 if ($field == 'id' || is_null($dao->$field)) {
550 continue;
551 }
552
553 if ($field == 'visibility_id') {
554 $setTree[$setID]['fields'][$fieldID]['visibility'] = $visibility[$dao->$field];
555 }
556 $setTree[$setID]['fields'][$fieldID][$field] = $dao->$field;
557 }
9da8dc8c 558 $setTree[$setID]['fields'][$fieldID]['options'] = CRM_Price_BAO_PriceField::getOptions($fieldID, FALSE);
6a488035
TO
559 }
560
561 // also get the pre and post help from this price set
562 $sql = "
563SELECT extends, financial_type_id, help_pre, help_post, is_quick_config
564FROM civicrm_price_set
565WHERE id = %1";
566 $dao = CRM_Core_DAO::executeQuery($sql, $params);
567 if ($dao->fetch()) {
568 $setTree[$setID]['extends'] = $dao->extends;
157b21d8 569 $setTree[$setID]['financial_type_id'] = $dao->financial_type_id;
6a488035
TO
570 $setTree[$setID]['help_pre'] = $dao->help_pre;
571 $setTree[$setID]['help_post'] = $dao->help_post;
572 $setTree[$setID]['is_quick_config'] = $dao->is_quick_config;
573 }
574 return $setTree;
575 }
576
85020e43
EM
577 /**
578 * Get the Price Field ID. We call this function when more than one being present would represent an error
579 * starting format derived from current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
580 * @param array $priceSet
581 *
582 * @throws CRM_Core_Exception
583 * @return int
584 */
00be9182 585 public static function getOnlyPriceFieldID(array $priceSet) {
22e263ad 586 if (count($priceSet['fields']) > 1) {
85020e43
EM
587 throw new CRM_Core_Exception(ts('expected only one price field to be in priceset but multiple are present'));
588 }
589 return (int) implode('_', array_keys($priceSet['fields']));
590 }
591
592 /**
593 * Get the Price Field Value ID. We call this function when more than one being present would represent an error
594 * current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId))
595 * @param array $priceSet
596 *
597 * @throws CRM_Core_Exception
598 * @return int
599 */
00be9182 600 public static function getOnlyPriceFieldValueID(array $priceSet) {
85020e43 601 $priceFieldID = self::getOnlyPriceFieldID($priceSet);
22e263ad 602 if (count($priceSet['fields'][$priceFieldID]['options']) > 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'][$priceFieldID]['options']));
606 }
607
608
ffd93213 609 /**
e0c1764e 610 * @param CRM_Core_Form $form
100fef9d 611 * @param int $id
ffd93213
EM
612 * @param string $entityTable
613 * @param bool $validOnly
100fef9d 614 * @param int $priceSetId
ffd93213
EM
615 *
616 * @return bool|false|int|null
617 */
00be9182 618 public static function initSet(&$form, $id, $entityTable = 'civicrm_event', $validOnly = FALSE, $priceSetId = NULL) {
6a488035
TO
619 if (!$priceSetId) {
620 $priceSetId = self::getFor($entityTable, $id);
621 }
622
623 //check if priceset is is_config
624 if (is_numeric($priceSetId)) {
9da8dc8c 625 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config') && $form->getVar('_name') != 'Participant') {
6a488035
TO
626 $form->assign('quickConfig', 1);
627 }
628 }
629 // get price info
630 if ($priceSetId) {
631 if ($form->_action & CRM_Core_Action::UPDATE) {
632 $entityId = $entity = NULL;
633
634 switch ($entityTable) {
635 case 'civicrm_event':
636 $entity = 'participant';
637 if (CRM_Utils_System::getClassName($form) == 'CRM_Event_Form_Participant') {
638 $entityId = $form->_id;
639 }
640 else {
641 $entityId = $form->_participantId;
642 }
643 break;
644
645 case 'civicrm_contribution_page':
646 case 'civicrm_contribution':
647 $entity = 'contribution';
648 $entityId = $form->_id;
649 break;
650 }
651
652 if ($entityId && $entity) {
653 $form->_values['line_items'] = CRM_Price_BAO_LineItem::getLineItems($entityId, $entity);
654 }
655 $required = FALSE;
656 }
657 else {
658 $required = TRUE;
659 }
660
661 $form->_priceSetId = $priceSetId;
662 $priceSet = self::getSetDetail($priceSetId, $required, $validOnly);
663 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
664 $form->_values['fee'] = CRM_Utils_Array::value('fields', $form->_priceSet);
665
666 //get the price set fields participant count.
667 if ($entityTable == 'civicrm_event') {
668 //get option count info.
669 $form->_priceSet['optionsCountTotal'] = self::getPricesetCount($priceSetId);
670 if ($form->_priceSet['optionsCountTotal']) {
671 $optionsCountDeails = array();
672 if (!empty($form->_priceSet['fields'])) {
673 foreach ($form->_priceSet['fields'] as $field) {
674 foreach ($field['options'] as $option) {
675 $count = CRM_Utils_Array::value('count', $option, 0);
676 $optionsCountDeails['fields'][$field['id']]['options'][$option['id']] = $count;
677 }
678 }
679 }
680 $form->_priceSet['optionsCountDetails'] = $optionsCountDeails;
681 }
682
683 //get option max value info.
684 $optionsMaxValueTotal = 0;
685 $optionsMaxValueDetails = array();
686
687 if (!empty($form->_priceSet['fields'])) {
688 foreach ($form->_priceSet['fields'] as $field) {
689 foreach ($field['options'] as $option) {
690 $maxVal = CRM_Utils_Array::value('max_value', $option, 0);
691 $optionsMaxValueDetails['fields'][$field['id']]['options'][$option['id']] = $maxVal;
692 $optionsMaxValueTotal += $maxVal;
693 }
694 }
695 }
696
697 $form->_priceSet['optionsMaxValueTotal'] = $optionsMaxValueTotal;
698 if ($optionsMaxValueTotal) {
699 $form->_priceSet['optionsMaxValueDetails'] = $optionsMaxValueDetails;
700 }
701 }
702 $form->set('priceSetId', $form->_priceSetId);
703 $form->set('priceSet', $form->_priceSet);
704
705 return $priceSetId;
706 }
707 return FALSE;
708 }
709
ffd93213
EM
710 /**
711 * @param $fields
c490a46a 712 * @param array $params
ffd93213
EM
713 * @param $lineItem
714 * @param string $component
715 */
00be9182 716 public static function processAmount(&$fields, &$params, &$lineItem, $component = '') {
6a488035 717 // using price set
dc428161 718 $totalPrice = $totalTax = 0;
6a488035
TO
719 $radioLevel = $checkboxLevel = $selectLevel = $textLevel = array();
720 if ($component) {
721 $autoRenew = array();
722 $autoRenew[0] = $autoRenew[1] = $autoRenew[2] = 0;
723 }
724 foreach ($fields as $id => $field) {
a7488080 725 if (empty($params["price_{$id}"]) ||
6a488035
TO
726 (empty($params["price_{$id}"]) && $params["price_{$id}"] == NULL)
727 ) {
728 // skip if nothing was submitted for this field
729 continue;
730 }
731
732 switch ($field['html_type']) {
733 case 'Text':
be45c8b4
EM
734 $firstOption = reset($field['options']);
735 $params["price_{$id}"] = array($firstOption['id'] => $params["price_{$id}"]);
6a488035 736 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dc428161 737 if (CRM_Utils_Array::value('tax_rate', $field['options'][key($field['options'])])) {
738 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
739 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
740 }
049db839 741 if (CRM_Utils_Array::value('name', $field['options'][key($field['options'])]) == 'contribution_amount') {
742 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
743 if (array_key_exists($params['financial_type_id'], $taxRates)) {
744 $field['options'][key($field['options'])]['tax_rate'] = $taxRates[$params['financial_type_id']];
745 $taxAmount = CRM_Contribute_BAO_Contribution_Utils::calculateTaxAmount($field['options'][key($field['options'])]['amount'], $field['options'][key($field['options'])]['tax_rate']);
cce6ec9f 746 $field['options'][key($field['options'])]['tax_amount'] = round($taxAmount['tax_amount'], 2);
049db839 747 $lineItem = self::setLineItem($field, $lineItem, key($field['options']));
748 $totalTax += $field['options'][key($field['options'])]['tax_amount'] * $lineItem[key($field['options'])]['qty'];
749 }
750 }
3b5db8ce 751 $totalPrice += $lineItem[$firstOption['id']]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[key($field['options'])]);
6a488035
TO
752 break;
753
754 case 'Radio':
755 //special case if user select -none-
756 if ($params["price_{$id}"] <= 0) {
757 continue;
758 }
759 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
760 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
761 $optionLabel = CRM_Utils_Array::value('label', $field['options'][$optionValueId]);
762 $params['amount_priceset_level_radio'] = array();
763 $params['amount_priceset_level_radio'][$optionValueId] = $optionLabel;
764 if (isset($radioLevel)) {
765 $radioLevel = array_merge($radioLevel,
766 array_keys($params['amount_priceset_level_radio'])
767 );
768 }
769 else {
770 $radioLevel = array_keys($params['amount_priceset_level_radio']);
771 }
772 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dc428161 773 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
774 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
775 $totalTax += $field['options'][$optionValueId]['tax_amount'];
c40e1ff4 776 if (CRM_Utils_Array::value('field_title', $lineItem[$optionValueId]) == 'Membership Amount') {
777 $lineItem[$optionValueId]['line_total'] = $lineItem[$optionValueId]['unit_price'] = CRM_Utils_Rule::cleanMoney($lineItem[$optionValueId]['line_total'] - $lineItem[$optionValueId]['tax_amount']);
778 }
dc428161 779 }
c40e1ff4 780 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
cde484fd
DL
781 if (
782 $component &&
a6c4ca20 783 // auto_renew exists and is empty in some workflows, which php treat as a 0
28156120 784 // and hence we explicitly check to see if auto_renew is numeric
cde484fd
DL
785 isset($lineItem[$optionValueId]['auto_renew']) &&
786 is_numeric($lineItem[$optionValueId]['auto_renew'])
787 ) {
6a488035
TO
788 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
789 }
790 break;
791
792 case 'Select':
793 $params["price_{$id}"] = array($params["price_{$id}"] => 1);
794 $optionValueId = CRM_Utils_Array::key(1, $params["price_{$id}"]);
795 $optionLabel = $field['options'][$optionValueId]['label'];
796 $params['amount_priceset_level_select'] = array();
797 $params['amount_priceset_level_select'][CRM_Utils_Array::key(1, $params["price_{$id}"])] = $optionLabel;
798 if (isset($selectLevel)) {
799 $selectLevel = array_merge($selectLevel, array_keys($params['amount_priceset_level_select']));
800 }
801 else {
802 $selectLevel = array_keys($params['amount_priceset_level_select']);
803 }
804 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
dc428161 805 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionValueId])) {
806 $lineItem = self::setLineItem($field, $lineItem, $optionValueId);
807 $totalTax += $field['options'][$optionValueId]['tax_amount'];
808 }
c40e1ff4 809 $totalPrice += $lineItem[$optionValueId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionValueId]);
cde484fd
DL
810 if (
811 $component &&
812 isset($lineItem[$optionValueId]['auto_renew']) &&
813 is_numeric($lineItem[$optionValueId]['auto_renew'])
814 ) {
6a488035
TO
815 $autoRenew[$lineItem[$optionValueId]['auto_renew']] += $lineItem[$optionValueId]['line_total'];
816 }
817 break;
818
819 case 'CheckBox':
820 $params['amount_priceset_level_checkbox'] = $optionIds = array();
821 foreach ($params["price_{$id}"] as $optionId => $option) {
822 $optionIds[] = $optionId;
823 $optionLabel = $field['options'][$optionId]['label'];
824 $params['amount_priceset_level_checkbox']["{$field['options'][$optionId]['id']}"] = $optionLabel;
825 if (isset($checkboxLevel)) {
826 $checkboxLevel = array_unique(array_merge(
353ffa53
TO
827 $checkboxLevel,
828 array_keys($params['amount_priceset_level_checkbox'])
6a488035
TO
829 )
830 );
831 }
832 else {
833 $checkboxLevel = array_keys($params['amount_priceset_level_checkbox']);
834 }
835 }
836 CRM_Price_BAO_LineItem::format($id, $params, $field, $lineItem);
837 foreach ($optionIds as $optionId) {
dc428161 838 if (CRM_Utils_Array::value('tax_rate', $field['options'][$optionId])) {
839 $lineItem = self::setLineItem($field, $lineItem, $optionId);
840 $totalTax += $field['options'][$optionId]['tax_amount'];
841 }
c40e1ff4 842 $totalPrice += $lineItem[$optionId]['line_total'] + CRM_Utils_Array::value('tax_amount', $lineItem[$optionId]);
cde484fd
DL
843 if (
844 $component &&
845 isset($lineItem[$optionId]['auto_renew']) &&
846 is_numeric($lineItem[$optionId]['auto_renew'])
847 ) {
6a488035
TO
848 $autoRenew[$lineItem[$optionId]['auto_renew']] += $lineItem[$optionId]['line_total'];
849 }
850 }
851 break;
852 }
853 }
854
855 $amount_level = array();
856 $totalParticipant = 0;
857 if (is_array($lineItem)) {
858 foreach ($lineItem as $values) {
859 $totalParticipant += $values['participant_count'];
860 if ($values['html_type'] == 'Text') {
861 $amount_level[] = $values['label'] . ' - ' . $values['qty'];
862 continue;
863 }
864 $amount_level[] = $values['label'];
865 }
866 }
867
868 $displayParticipantCount = '';
869 if ($totalParticipant > 0) {
870 $displayParticipantCount = ' Participant Count -' . $totalParticipant;
871 }
872 $params['amount_level'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $amount_level) . $displayParticipantCount . CRM_Core_DAO::VALUE_SEPARATOR;
873 $params['amount'] = $totalPrice;
dc428161 874 $params['tax_amount'] = $totalTax;
6a488035
TO
875 if ($component) {
876 foreach ($autoRenew as $dontCare => $eachAmount) {
877 if (!$eachAmount) {
cde484fd 878 unset($autoRenew[$dontCare]);
6a488035
TO
879 }
880 }
481a74f4 881 if (count($autoRenew) > 1) {
6a488035
TO
882 $params['autoRenew'] = $autoRenew;
883 }
884 }
885 }
886
887 /**
100fef9d 888 * Build the price set form.
6a488035 889 *
e0c1764e 890 * @param CRM_Core_Form $form
dd244018 891 *
355ba699 892 * @return void
6a488035 893 */
00be9182 894 public static function buildPriceSet(&$form) {
6a488035 895 $priceSetId = $form->get('priceSetId');
6a488035
TO
896 if (!$priceSetId) {
897 return;
898 }
899
900 $validFieldsOnly = TRUE;
901 $className = CRM_Utils_System::getClassName($form);
902 if (in_array($className, array(
353ffa53 903 'CRM_Contribute_Form_Contribution',
acb1052e 904 'CRM_Member_Form_Membership',
353ffa53 905 ))) {
6a488035
TO
906 $validFieldsOnly = FALSE;
907 }
908
353ffa53
TO
909 $priceSet = self::getSetDetail($priceSetId, TRUE, $validFieldsOnly);
910 $form->_priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
883e4763 911 $validPriceFieldIds = array_keys($form->_priceSet['fields']);
6a488035 912 $form->_quickConfig = $quickConfig = 0;
9da8dc8c 913 if (CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
6a488035
TO
914 $quickConfig = 1;
915 }
916
917 $form->assign('quickConfig', $quickConfig);
918 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
919 $form->_quickConfig = $quickConfig;
920 }
921 $form->assign('priceSet', $form->_priceSet);
922
923 $component = 'contribution';
924 if ($className == 'CRM_Member_Form_Membership') {
925 $component = 'membership';
926 }
927
928 if ($className == 'CRM_Contribute_Form_Contribution_Main') {
929 $feeBlock = &$form->_values['fee'];
930 if (!empty($form->_useForMember)) {
931 $component = 'membership';
932 }
933 }
934 else {
935 $feeBlock = &$form->_priceSet['fields'];
936 }
937
938 // call the hook.
939 CRM_Utils_Hook::buildAmount($component, $form, $feeBlock);
940
c7b3d063 941 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
ba1dcfda 942 $adminFieldVisible = FALSE;
c7b3d063 943 if (CRM_Core_Permission::check('administer CiviCRM')) {
ba1dcfda 944 $adminFieldVisible = TRUE;
c7b3d063 945 }
77b97be7 946
883e4763 947 foreach ($feeBlock as $id => $field) {
6a488035 948 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
ba1dcfda 949 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
6a488035
TO
950 !$validFieldsOnly
951 ) {
952 $options = CRM_Utils_Array::value('options', $field);
953 if ($className == 'CRM_Contribute_Form_Contribution_Main' && $component = 'membership') {
cc509891 954 $userid = $form->getVar('_membershipContactID');
6a488035
TO
955 $checklifetime = self::checkCurrentMembership($options, $userid);
956 if ($checklifetime) {
957 $form->assign('ispricelifetime', TRUE);
958 }
959 }
883e4763 960 if (!is_array($options) || !in_array($id, $validPriceFieldIds)) {
6a488035
TO
961 continue;
962 }
9da8dc8c 963 CRM_Price_BAO_PriceField::addQuickFormElement($form,
6a488035
TO
964 'price_' . $field['id'],
965 $field['id'],
966 FALSE,
967 CRM_Utils_Array::value('is_required', $field, FALSE),
968 NULL,
969 $options
970 );
971 }
972 }
973 }
974
975 /**
100fef9d 976 * Check the current Membership
6a488035
TO
977 * having end date null.
978 */
00be9182 979 public static function checkCurrentMembership(&$options, $userid) {
6a488035
TO
980 if (!$userid || empty($options)) {
981 return;
982 }
983 static $_contact_memberships = array();
984 $checklifetime = FALSE;
985 foreach ($options as $key => $value) {
a7488080 986 if (!empty($value['membership_type_id'])) {
6a488035
TO
987 if (!isset($_contact_memberships[$userid][$value['membership_type_id']])) {
988 $_contact_memberships[$userid][$value['membership_type_id']] = CRM_Member_BAO_Membership::getContactMembership($userid, $value['membership_type_id'], FALSE);
989 }
990 $currentMembership = $_contact_memberships[$userid][$value['membership_type_id']];
8cc574cf 991 if (!empty($currentMembership) && empty($currentMembership['end_date'])) {
6a488035
TO
992 unset($options[$key]);
993 $checklifetime = TRUE;
994 }
995 }
996 }
997 if ($checklifetime) {
998 return TRUE;
999 }
1000 else {
1001 return FALSE;
1002 }
1003 }
1004
1005 /**
100fef9d 1006 * Set daefult the price set fields.
6a488035 1007 *
c490a46a 1008 * @param CRM_Core_Form $form
fd31fa4c
EM
1009 * @param $defaults
1010 *
a6c01b45 1011 * @return array
6a488035 1012 */
00be9182 1013 public static function setDefaultPriceSet(&$form, &$defaults) {
6a488035
TO
1014 if (!isset($form->_priceSet) || empty($form->_priceSet['fields'])) {
1015 return $defaults;
1016 }
1017
1018 foreach ($form->_priceSet['fields'] as $key => $val) {
1019 foreach ($val['options'] as $keys => $values) {
1020 if ($values['is_default']) {
1021 if ($val['html_type'] == 'CheckBox') {
1022 $defaults["price_{$key}"][$keys] = 1;
1023 }
1024 else {
1025 $defaults["price_{$key}"] = $keys;
1026 }
1027 }
1028 }
1029 }
1030 return $defaults;
1031 }
1032
b2cdd843
EM
1033 /**
1034 * Supports event create function by setting up required price sets, not tested but expect
1035 * it will work for contribution page
414c1420
TO
1036 * @param array $params
1037 * As passed to api/bao create fn.
1038 * @param CRM_Core_DAO $entity
1039 * Object for given entity.
1040 * @param string $entityName
1041 * Name of entity - e.g event.
b2cdd843 1042 */
00be9182 1043 public static function setPriceSets(&$params, $entity, $entityName) {
22e263ad 1044 if (empty($params['price_set_id']) || !is_array($params['price_set_id'])) {
b2cdd843
EM
1045 return;
1046 }
1047 // CRM-14069 note that we may as well start by assuming more than one.
1048 // currently the form does not pass in as an array & will be skipped
1049 // test is passing in as an array but I feel the api should have a metadata that allows
1050 // transform of single to array - seems good for managing transitions - in which case all api
1051 // calls that set price_set_id will hit this
1052 // e.g in getfields 'price_set_id' => array('blah', 'bao_type' => 'array') - causing
1053 // all separated values, strings, json half-separated values (in participant we hit this)
1054 // to be converted to json @ api layer
1055 $pse = new CRM_Price_DAO_PriceSetEntity();
1056 $pse->entity_table = 'civicrm_' . $entityName;
1057 $pse->entity_id = $entity->id;
1058 while ($pse->fetch()) {
22e263ad 1059 if (!in_array($pse->price_set_id, $params['price_set_id'])) {
b2cdd843
EM
1060 // note an even more aggressive form of this deletion currently happens in event form
1061 // past price sets discounts are made inaccessible by this as the discount_id is set to NULL
1062 // on the participant record
1063 if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_' . $entityName, $entity->id)) {
ba1dcfda 1064 CRM_Core_BAO_Discount::del($entity->id, 'civicrm_' . $entityName);
b2cdd843
EM
1065 }
1066 }
1067 }
1068 foreach ($params['price_set_id'] as $priceSetID) {
1069 CRM_Price_BAO_PriceSet::addTo('civicrm_' . $entityName, $entity->id, $priceSetID);
1070 //@todo - how should we do this - copied from form
1071 //if (CRM_Utils_Array::value('price_field_id', $params)) {
1072 // $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
1073 // CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
1074 //}
1075 }
1076 }
353ffa53 1077
6a488035 1078 /**
fe482240 1079 * Get field ids of a price set.
6a488035 1080 *
414c1420
TO
1081 * @param int $id
1082 * Price Set id.
6a488035 1083 *
a6c01b45 1084 * @return array
16b10e64 1085 * Array of the field ids
6a488035 1086 *
6a488035
TO
1087 */
1088 public static function getFieldIds($id) {
9da8dc8c 1089 $priceField = new CRM_Price_DAO_PriceField();
6a488035
TO
1090 $priceField->price_set_id = $id;
1091 $priceField->find();
1092 while ($priceField->fetch()) {
1093 $var[] = $priceField->id;
1094 }
1095 return $var;
1096 }
1097
1098 /**
72b3a70c 1099 * Copy a price set, including all the fields
6a488035 1100 *
414c1420
TO
1101 * @param int $id
1102 * The price set id to copy.
6a488035 1103 *
72b3a70c 1104 * @return CRM_Price_DAO_PriceSet
6a488035 1105 */
00be9182 1106 public static function copy($id) {
6a488035
TO
1107 $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
1108
1109 $title = ts('[Copy id %1]', array(1 => $maxId + 1));
1110 $fieldsFix = array(
ba1dcfda 1111 'suffix' => array(
353ffa53
TO
1112 'title' => ' ' . $title,
1113 'name' => '__Copy_id_' . ($maxId + 1) . '_',
6a488035
TO
1114 ),
1115 );
1116
9da8dc8c 1117 $copy = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSet',
353ffa53
TO
1118 array('id' => $id),
1119 NULL,
1120 $fieldsFix
6a488035
TO
1121 );
1122
1123 //copying all the blocks pertaining to the price set
9da8dc8c 1124 $copyPriceField = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceField',
353ffa53
TO
1125 array('price_set_id' => $id),
1126 array('price_set_id' => $copy->id)
6a488035
TO
1127 );
1128 if (!empty($copyPriceField)) {
1129 $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
1130
1131 //copy option group and values
1132 foreach ($price as $originalId => $copyId) {
9da8dc8c 1133 CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceFieldValue',
6a488035
TO
1134 array('price_field_id' => $originalId),
1135 array('price_field_id' => $copyId)
1136 );
1137 }
1138 }
1139 $copy->save();
1140
1141 CRM_Utils_Hook::copy('Set', $copy);
1142 return $copy;
1143 }
1144
1145 /**
fe482240 1146 * check price set permission.
6a488035 1147 *
414c1420
TO
1148 * @param int $sid
1149 * The price set id.
77b97be7
EM
1150 *
1151 * @return bool
6a488035 1152 */
00be9182 1153 public static function checkPermission($sid) {
44c8822b 1154 if ($sid && self::eventPriceSetDomainID()) {
9da8dc8c 1155 $domain_id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $sid, 'domain_id', 'id');
6a488035 1156 if (CRM_Core_Config::domainID() != $domain_id) {
0499b0ad 1157 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
6a488035
TO
1158 }
1159 }
1160 return TRUE;
1161 }
1162
1163 /**
1164 * Get the sum of participant count
1165 * for all fields of given price set.
1166 *
414c1420
TO
1167 * @param int $sid
1168 * The price set id.
6a488035 1169 *
77b97be7
EM
1170 * @param bool $onlyActive
1171 *
1172 * @return int|null|string
6a488035
TO
1173 */
1174 public static function getPricesetCount($sid, $onlyActive = TRUE) {
1175 $count = 0;
1176 if (!$sid) {
1177 return $count;
1178 }
1179
1180 $where = NULL;
1181 if ($onlyActive) {
1182 $where = 'AND value.is_active = 1 AND field.is_active = 1';
1183 }
1184
1185 static $pricesetFieldCount = array();
1186 if (!isset($pricesetFieldCount[$sid])) {
1187 $sql = "
1188 SELECT sum(value.count) as totalCount
1189 FROM civicrm_price_field_value value
1190INNER JOIN civicrm_price_field field ON ( field.id = value.price_field_id )
1191INNER JOIN civicrm_price_set pset ON ( pset.id = field.price_set_id )
1192 WHERE pset.id = %1
1193 $where";
1194
1195 $count = CRM_Core_DAO::singleValueQuery($sql, array(1 => array($sid, 'Positive')));
1196 $pricesetFieldCount[$sid] = ($count) ? $count : 0;
1197 }
1198
1199 return $pricesetFieldCount[$sid];
1200 }
1201
ffd93213
EM
1202 /**
1203 * @param $ids
1204 *
1205 * @return array
1206 */
6a488035
TO
1207 public static function getMembershipCount($ids) {
1208 $queryString = "
1209SELECT count( pfv.id ) AS count, pfv.id AS id
1210FROM civicrm_price_field_value pfv
1211INNER JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1212WHERE pfv.id IN ( $ids )
1213GROUP BY mt.member_of_contact_id";
1214
1215 $crmDAO = CRM_Core_DAO::executeQuery($queryString);
1216 $count = array();
1217
1218 while ($crmDAO->fetch()) {
1219 $count[$crmDAO->id] = $crmDAO->count;
1220 }
1221
1222 return $count;
1223 }
1224
1225 /**
fe482240 1226 * Check if auto renew option should be shown.
6a488035 1227 *
414c1420
TO
1228 * @param int $priceSetId
1229 * Price set id.
6a488035 1230 *
a6c01b45
CW
1231 * @return int
1232 * $autoRenewOption ( 0:hide, 1:optional 2:required )
6a488035
TO
1233 */
1234 public static function checkAutoRenewForPriceSet($priceSetId) {
1235 // auto-renew option should be visible if membership types associated with all the fields has
1236 // been set for auto-renew option
1237 // Auto renew checkbox should be frozen if for all the membership type auto renew is required
1238
1239 // get the membership type auto renew option and check if required or optional
1240 $query = 'SELECT mt.auto_renew, mt.duration_interval, mt.duration_unit
1241 FROM civicrm_price_field_value pfv
1242 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1243 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1244 WHERE pf.price_set_id = %1
1245 AND pf.is_active = 1
1246 AND pfv.is_active = 1';
1247
1248 $params = array(1 => array($priceSetId, 'Integer'));
1249
353ffa53 1250 $dao = CRM_Core_DAO::executeQuery($query, $params);
6a488035 1251 $autoRenewOption = 2;
353ffa53 1252 $interval = $unit = array();
6a488035
TO
1253 while ($dao->fetch()) {
1254 if (!$dao->auto_renew) {
1255 $autoRenewOption = 0;
1256 break;
1257 }
1258 if ($dao->auto_renew == 1) {
1259 $autoRenewOption = 1;
1260 }
1261
1262 $interval[$dao->duration_interval] = $dao->duration_interval;
1263 $unit[$dao->duration_unit] = $dao->duration_unit;
1264 }
1265
1266 if (count($interval) == 1 && count($unit) == 1 && $autoRenewOption > 0) {
1267 return $autoRenewOption;
1268 }
1269 else {
1270 return 0;
1271 }
1272 }
1273
1274 /**
fe482240 1275 * Retrieve auto renew frequency and interval.
6a488035 1276 *
414c1420
TO
1277 * @param int $priceSetId
1278 * Price set id.
6a488035 1279 *
a6c01b45
CW
1280 * @return array
1281 * associate array of frequency interval and unit
6a488035
TO
1282 */
1283 public static function getRecurDetails($priceSetId) {
1284 $query = 'SELECT mt.duration_interval, mt.duration_unit
1285 FROM civicrm_price_field_value pfv
1286 INNER JOIN civicrm_membership_type mt ON pfv.membership_type_id = mt.id
1287 INNER JOIN civicrm_price_field pf ON pfv.price_field_id = pf.id
1288 WHERE pf.price_set_id = %1 LIMIT 1';
1289
1290 $params = array(1 => array($priceSetId, 'Integer'));
1291 $dao = CRM_Core_DAO::executeQuery($query, $params);
1292 $dao->fetch();
1293 return array($dao->duration_interval, $dao->duration_unit);
1294 }
1295
ffd93213
EM
1296 /**
1297 * @return object
1298 */
00be9182 1299 public static function eventPriceSetDomainID() {
6a488035
TO
1300 return CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MULTISITE_PREFERENCES_NAME,
1301 'event_price_set_domain_id',
1302 NULL, FALSE
1303 );
1304 }
1305
1306 /**
fe482240 1307 * Update the is_quick_config flag in the db.
6a488035 1308 *
414c1420
TO
1309 * @param int $id
1310 * Id of the database record.
acb1052e 1311 * @param bool $isQuickConfig we want to set the is_quick_config field.
414c1420 1312 * Value we want to set the is_quick_config field.
6a488035 1313 *
a6c01b45
CW
1314 * @return Object
1315 * DAO object on sucess, null otherwise
6a488035 1316 */
00be9182 1317 public static function setIsQuickConfig($id, $isQuickConfig) {
9da8dc8c 1318 return CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $id, 'is_quick_config', $isQuickConfig);
6a488035
TO
1319 }
1320
1321 /**
cde484fd 1322 * Check if price set id provides option for
6a488035
TO
1323 * user to select both auto-renew and non-auto-renew memberships
1324 *
6a488035
TO
1325 */
1326 public static function checkMembershipPriceSet($id) {
acb1052e
WA
1327 $query
1328 = "SELECT pfv.id, pfv.price_field_id, pfv.name, pfv.membership_type_id, pf.html_type, mt.auto_renew
6a488035
TO
1329FROM civicrm_price_field_value pfv
1330LEFT JOIN civicrm_price_field pf ON pf.id = pfv.price_field_id
1331LEFT JOIN civicrm_price_set ps ON ps.id = pf.price_set_id
1332LEFT JOIN civicrm_membership_type mt ON mt.id = pfv.membership_type_id
1333WHERE ps.id = %1
1334";
1335
1336 $params = array(1 => array($id, 'Integer'));
1337 $dao = CRM_Core_DAO::executeQuery($query, $params);
1338
1339 $autoRenew = array();
1340 //FIXME: do a comprehensive check of whether
1341 //2 membership types can be selected
1342 //instead of comparing all of them
1343 while ($dao->fetch()) {
cde484fd 1344 //temp fix for #CRM-10370
6a488035
TO
1345 //if its NULL consider it '0' i.e. 'No auto-renew option'
1346 $daoAutoRenew = $dao->auto_renew;
1347 if ($daoAutoRenew === NULL) {
1348 $daoAutoRenew = 0;
1349 }
1350 if (!empty($autoRenew) && !in_array($daoAutoRenew, $autoRenew)) {
ba1dcfda 1351 return TRUE;
6a488035
TO
1352 }
1353 $autoRenew[] = $daoAutoRenew;
1354 }
ba1dcfda 1355 return FALSE;
6a488035
TO
1356 }
1357
e0c1764e 1358 /**
c6914066
PN
1359 * Copy priceSet when event/contibution page is copied
1360 *
414c1420
TO
1361 * @param string $baoName
1362 * BAO name.
1363 * @param int $id
1364 * Old event/contribution page id.
1365 * @param int $newId
1366 * Newly created event/contribution page id.
c6914066 1367 */
00be9182 1368 public static function copyPriceSet($baoName, $id, $newId) {
9da8dc8c 1369 $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
c6914066 1370 if ($priceSetId) {
9da8dc8c 1371 $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
22e263ad 1372 if ($isQuickConfig) {
37326fa1 1373 $copyPriceSet = CRM_Price_BAO_PriceSet::copy($priceSetId);
9da8dc8c 1374 CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
44c8822b 1375 }
c6914066 1376 else {
9da8dc8c 1377 $copyPriceSet = &CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity',
c6914066
PN
1378 array(
1379 'entity_id' => $id,
1380 'entity_table' => $baoName,
1381 ),
1382 array('entity_id' => $newId)
1383 );
1384 }
1385 // copy event discount
1386 if ($baoName == 'civicrm_event') {
1387 $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
1388 foreach ($discount as $discountId => $setId) {
1389
9da8dc8c 1390 $copyPriceSet = &CRM_Price_BAO_PriceSet::copy($setId);
44c8822b 1391
28156120 1392 CRM_Core_DAO::copyGeneric(
c6914066
PN
1393 'CRM_Core_DAO_Discount',
1394 array(
1395 'id' => $discountId,
1396 ),
1397 array(
1398 'entity_id' => $newId,
1399 'price_set_id' => $copyPriceSet->id,
1400 )
1401 );
1402 }
1403 }
1404 }
1405 }
dc428161 1406
d424ffde 1407 /**
fe482240 1408 * Function to set tax_amount and tax_rate in LineItem.
d424ffde
CW
1409 *
1410 * @param array $field
1411 * @param array $lineItem
1412 * @param int $optionValueId
1413 *
1414 * @return array
dc428161 1415 */
00be9182 1416 public static function setLineItem($field, $lineItem, $optionValueId) {
dc428161 1417 if ($field['html_type'] == 'Text') {
1418 $taxAmount = $field['options'][$optionValueId]['tax_amount'] * $lineItem[$optionValueId]['qty'];
1419 }
1420 else {
1421 $taxAmount = $field['options'][$optionValueId]['tax_amount'];
1422 }
1423 $taxRate = $field['options'][$optionValueId]['tax_rate'];
dc428161 1424 $lineItem[$optionValueId]['tax_amount'] = $taxAmount;
1425 $lineItem[$optionValueId]['tax_rate'] = $taxRate;
1426
1427 return $lineItem;
1428 }
96025800 1429
6a488035 1430}