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