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