3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Member_BAO_MembershipType
extends CRM_Member_DAO_MembershipType
{
20 * Static holder for the default Membership Type.
23 public static $_defaultMembershipType = NULL;
25 public static $_membershipTypeInfo = [];
30 public function __construct() {
31 parent
::__construct();
35 * Fetch object based on array of properties.
37 * @param array $params
38 * (reference ) an assoc array of name/value pairs.
39 * @param array $defaults
40 * (reference ) an assoc array to hold the flattened values.
42 * @return CRM_Member_BAO_MembershipType
44 public static function retrieve(&$params, &$defaults) {
45 $membershipType = new CRM_Member_DAO_MembershipType();
46 $membershipType->copyValues($params);
47 if ($membershipType->find(TRUE)) {
48 CRM_Core_DAO
::storeValues($membershipType, $defaults);
49 return $membershipType;
55 * Update the is_active flag in the db.
58 * Id of the database record.
59 * @param bool $is_active
60 * Value we want to set the is_active field.
63 * true if we found and updated the object, else false
65 public static function setIsActive($id, $is_active) {
66 return CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_MembershipType', $id, 'is_active', $is_active);
70 * Add the membership types.
72 * @param array $params
73 * Reference array contains the values submitted by the form.
75 * Array contains the id (deprecated).
77 * @return \CRM_Member_DAO_MembershipType
78 * @throws \CiviCRM_API3_Exception
80 public static function add(&$params, $ids = []) {
81 // DEPRECATED Check if membershipType ID was passed in via $ids
82 if (empty($params['id'])) {
83 if (isset($ids['membershipType'])) {
84 Civi
::log()->warning('Deprecated: Passing membershipType by $ids array in CRM_Member_BAO_MembershipType::add');
86 $params['id'] = $ids['membershipType'] ??
NULL;
89 $hook = empty($params['id']) ?
'create' : 'edit';
90 CRM_Utils_Hook
::pre($hook, 'MembershipType', CRM_Utils_Array
::value('id', $params), $params);
92 $membershipTypeId = $params['id'] ??
NULL;
94 if (!$membershipTypeId) {
95 if (!isset($params['is_active'])) {
97 $params['is_active'] = FALSE;
99 if (!isset($params['domain_id'])) {
100 $params['domain_id'] = CRM_Core_Config
::domainID();
104 // $previousID is the old organization id for membership type i.e 'member_of_contact_id'. This is used when an organization is changed.
106 if ($membershipTypeId) {
107 $previousID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $membershipTypeId, 'member_of_contact_id');
110 // action is taken depending upon the mode
111 $membershipType = new CRM_Member_DAO_MembershipType();
112 $membershipType->copyValues($params);
113 $membershipType->save();
115 if ($membershipTypeId) {
116 // on update we may need to retrieve some details for the price field function - otherwise we get e-notices on attempts to retrieve
117 // name etc - the presence of previous id tells us this is an update
118 $params = array_merge(civicrm_api3('membership_type', 'getsingle', ['id' => $membershipType->id
]), $params);
120 self
::createMembershipPriceField($params, $previousID, $membershipType->id
);
121 // update all price field value for quick config when membership type is set CRM-11718
122 if ($membershipTypeId) {
123 self
::updateAllPriceFieldValue($membershipTypeId, $params);
126 CRM_Utils_Hook
::post($hook, 'MembershipType', $membershipType->id
, $membershipType);
129 return $membershipType;
133 * Flush anywhere that membership types might be cached.
135 * @throws \CiviCRM_API3_Exception
137 public static function flush() {
138 CRM_Member_PseudoConstant
::membershipType(NULL, TRUE);
139 civicrm_api3('membership', 'getfields', ['cache_clear' => 1, 'fieldname' => 'membership_type_id']);
140 civicrm_api3('profile', 'getfields', ['action' => 'submit', 'cache_clear' => 1]);
141 Civi
::cache('metadata')->clear();
145 * Delete membership Types.
147 * @param int $membershipTypeId
149 * @throws CRM_Core_Exception
152 public static function del($membershipTypeId) {
153 // Check dependencies.
157 'Membership' => 'membership_type_id',
158 'MembershipBlock' => 'membership_type_default',
161 foreach ($dependency as $name => $field) {
162 $baoString = 'CRM_Member_BAO_' . $name;
163 $dao = new $baoString();
164 $dao->$field = $membershipTypeId;
165 /** @noinspection PhpUndefinedMethodInspection */
166 if ($dao->find(TRUE)) {
173 $message = ts('This membership type cannot be deleted due to following reason(s):');
174 if (in_array('Membership', $status)) {
175 $findMembersURL = CRM_Utils_System
::url('civicrm/member/search', 'reset=1');
176 $deleteURL = CRM_Utils_System
::url('civicrm/contact/search/advanced', 'reset=1');
177 $message .= '<br/>' . ts('%3. There are some contacts who have this membership type assigned to them. Search for contacts with this membership type from <a href=\'%1\'>Find Members</a>. If you are still getting this message after deleting these memberships, there may be contacts in the Trash (deleted) with this membership type. Try using <a href="%2">Advanced Search</a> and checking "Search in Trash".', [
178 1 => $findMembersURL,
185 if (in_array('MembershipBlock', $status)) {
186 $deleteURL = CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1');
187 $message .= ts('%2. This Membership Type is used in an <a href=\'%1\'>Online Contribution page</a>. Uncheck this membership type in the Memberships tab.', [
191 throw new CRM_Core_Exception($message);
194 CRM_Utils_Weight
::delWeight('CRM_Member_DAO_MembershipType', $membershipTypeId);
195 //delete from membership Type table
196 $membershipType = new CRM_Member_DAO_MembershipType();
197 $membershipType->id
= $membershipTypeId;
199 //fix for membership type delete api
201 if ($membershipType->find(TRUE)) {
202 return $membershipType->delete();
209 * Convert membership type's 'start day' & 'rollover day' to human readable formats.
211 * @param array $membershipType
212 * An array of membershipType-details.
214 public static function convertDayFormat(&$membershipType) {
216 'fixed_period_start_day',
217 'fixed_period_rollover_day',
219 foreach ($membershipType as $id => $details) {
220 foreach ($periodDays as $pDay) {
221 if (!empty($details[$pDay])) {
222 if ($details[$pDay] > 31) {
223 $month = substr($details[$pDay], 0, strlen($details[$pDay]) - 2);
224 $day = substr($details[$pDay], -2);
239 $membershipType[$id][$pDay] = $monthMap[$month] . ' ' . $day;
242 $membershipType[$id][$pDay] = $details[$pDay];
250 * Get membership Types.
252 * @deprecated use getAllMembershipTypes.
254 * @param bool $public
258 public static function getMembershipTypes($public = TRUE) {
259 $membershipTypes = [];
260 $membershipType = new CRM_Member_DAO_MembershipType();
261 $membershipType->is_active
= 1;
263 $membershipType->visibility
= 'Public';
265 $membershipType->orderBy(' weight');
266 $membershipType->find();
267 while ($membershipType->fetch()) {
268 $membershipTypes[$membershipType->id
] = $membershipType->name
;
270 return $membershipTypes;
274 * Get membership Type Details.
276 * @deprecated use getMembershipType.
278 * @param int $membershipTypeId
282 public static function getMembershipTypeDetails($membershipTypeId) {
283 $membershipTypeDetails = [];
285 $membershipType = new CRM_Member_DAO_MembershipType();
286 $membershipType->is_active
= 1;
287 $membershipType->id
= $membershipTypeId;
288 if ($membershipType->find(TRUE)) {
289 CRM_Core_DAO
::storeValues($membershipType, $membershipTypeDetails);
290 return $membershipTypeDetails;
298 * Calculate start date and end date for new membership.
300 * @param int $membershipTypeId
301 * Membership type id.
302 * @param string $joinDate
303 * Member since ( in mysql date format ).
304 * @param string $startDate
305 * Start date ( in mysql date format ).
306 * @param null $endDate
307 * @param int $numRenewTerms
308 * How many membership terms are being added to end date (default is 1).
311 * associated array with start date, end date and join date for the membership
313 public static function getDatesForMembershipType($membershipTypeId, $joinDate = NULL, $startDate = NULL, $endDate = NULL, $numRenewTerms = 1) {
314 $membershipTypeDetails = self
::getMembershipTypeDetails($membershipTypeId);
316 // Convert all dates to 'Y-m-d' format.
322 if (!empty($
$dateParam)) {
323 $
$dateParam = CRM_Utils_Date
::processDate($
$dateParam, NULL, FALSE, 'Y-m-d');
327 $joinDate = date('Y-m-d');
329 $actualStartDate = $joinDate;
331 $actualStartDate = $startDate;
334 $fixed_period_rollover = FALSE;
335 if (CRM_Utils_Array
::value('period_type', $membershipTypeDetails) == 'rolling') {
337 $startDate = $joinDate;
339 $actualStartDate = $startDate;
341 elseif (CRM_Utils_Array
::value('period_type', $membershipTypeDetails) == 'fixed') {
342 // calculate start date
343 // if !$startDate then use $joinDate
344 $toDay = explode('-', (empty($startDate) ?
$joinDate : $startDate));
349 if ($membershipTypeDetails['duration_unit'] == 'year') {
351 //get start fixed day
352 $startMonth = substr($membershipTypeDetails['fixed_period_start_day'], 0,
353 strlen($membershipTypeDetails['fixed_period_start_day']) - 2
355 $startDay = substr($membershipTypeDetails['fixed_period_start_day'], -2);
357 if (date('Y-m-d', mktime(0, 0, 0, $startMonth, $startDay, $year)) <= date('Y-m-d', mktime(0, 0, 0, $month, $day, $year))) {
358 $actualStartDate = date('Y-m-d', mktime(0, 0, 0, $startMonth, $startDay, $year));
361 $actualStartDate = date('Y-m-d', mktime(0, 0, 0, $startMonth, $startDay, $year - 1));
364 $fixed_period_rollover = self
::isDuringFixedAnnualRolloverPeriod($joinDate, $membershipTypeDetails, $year, $actualStartDate);
367 $startDate = $actualStartDate;
370 elseif ($membershipTypeDetails['duration_unit'] == 'month') {
371 // Check if we are on or after rollover day of the month - CRM-10585
372 // If so, set fixed_period_rollover TRUE so we increment end_date month below.
373 $dateParts = explode('-', $actualStartDate);
374 if ($dateParts[2] >= $membershipTypeDetails['fixed_period_rollover_day']) {
375 $fixed_period_rollover = TRUE;
378 // Start date is always first day of actualStartDate month
380 $actualStartDate = $startDate = $year . '-' . $month . '-01';
385 // Calculate end date if it is not passed by user.
387 //end date calculation
388 $date = explode('-', $actualStartDate);
393 switch ($membershipTypeDetails['duration_unit']) {
395 $year = $year +
($numRenewTerms * $membershipTypeDetails['duration_interval']);
396 //extend membership date by duration interval.
397 if ($fixed_period_rollover) {
403 $month = $month +
($numRenewTerms * $membershipTypeDetails['duration_interval']);
404 //duration interval is month
405 if ($fixed_period_rollover) {
412 $day = $day +
($numRenewTerms * $membershipTypeDetails['duration_interval']);
414 if ($fixed_period_rollover) {
415 //Fix Me: Currently we don't allow rollover if
416 //duration interval is day
421 if ($membershipTypeDetails['duration_unit'] == 'lifetime') {
425 $endDate = date('Y-m-d', mktime(0, 0, 0, $month, $day - 1, $year));
430 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
431 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
432 'join_date' => CRM_Utils_Date
::customFormat($joinDate, '%Y%m%d'),
435 return $membershipDates;
439 * Does this membership start between the rollover date and the start of the next period.
440 * (in which case they will get an extra membership period)
441 * ie if annual memberships run June - May & the rollover is in May memberships between
442 * May and June will return TRUE and between June and May will return FALSE
444 * @param string $startDate start date of current membership period
445 * @param array $membershipTypeDetails
447 * @param string $actualStartDate
448 * @return bool is this in the window where the membership gets an extra part-period added
450 public static function isDuringFixedAnnualRolloverPeriod($startDate, $membershipTypeDetails, $year, $actualStartDate) {
452 $rolloverMonth = substr($membershipTypeDetails['fixed_period_rollover_day'], 0,
453 strlen($membershipTypeDetails['fixed_period_rollover_day']) - 2
455 $rolloverDay = substr($membershipTypeDetails['fixed_period_rollover_day'], -2);
457 $calculatedRolloverDate = date('Y-m-d', mktime(0, 0, 0, $rolloverMonth, $rolloverDay, $year));
459 //CRM-7825 -membership date rules are :
460 //1. Membership should not be start in future.
461 //2. rollover window should be subset of membership window.
463 //get the fixed end date here.
464 $dateParts = explode('-', $actualStartDate);
465 $endDateOfFirstYearMembershipPeriod = date('Y-m-d', mktime(0, 0, 0,
471 //we know the month and day of the rollover date but not the year (we're just
472 //using the start date year at the moment. So if it's after the end
473 // of the first year of membership then it's the next period & we'll adjust back a year. If it's
474 // before the start_date then it's too early & we'll adjust forward.
475 if ($endDateOfFirstYearMembershipPeriod < $calculatedRolloverDate) {
476 $calculatedRolloverDate = date('Y-m-d', mktime(0, 0, 0, $rolloverMonth, $rolloverDay, $year - 1));
478 if ($calculatedRolloverDate < $actualStartDate) {
479 $calculatedRolloverDate = date('Y-m-d', mktime(0, 0, 0, $rolloverMonth, $rolloverDay, $year +
1));
482 if ($calculatedRolloverDate <= $startDate) {
489 * Calculate start date and end date for membership updates.
491 * Note that this function is called by the api for any membership update although it was
492 * originally written for renewal (which feels a bit fragile but hey....).
494 * @param int $membershipId
495 * @param $changeToday
496 * If provided, specify an alternative date to use as "today" for renewal
497 * @param int $membershipTypeID
498 * If provided, overrides the membership type of the $membershipID membership.
499 * @param int $numRenewTerms
500 * How many membership terms are being added to end date (default is 1).
502 * CRM-7297 Membership Upsell - Added $membershipTypeID param to facilitate calculations of dates when membership type changes
505 * array fo the start date, end date and join date of the membership
507 public static function getRenewalDatesForMembershipType($membershipId, $changeToday = NULL, $membershipTypeID = NULL, $numRenewTerms = 1) {
508 $params = ['id' => $membershipId];
509 $membershipDetails = CRM_Member_BAO_Membership
::getValues($params, $values);
510 $membershipDetails = $membershipDetails[$membershipId];
511 $statusID = $membershipDetails->status_id
;
512 $membershipDates = [];
513 if (!empty($membershipDetails->join_date
)) {
514 $membershipDates['join_date'] = CRM_Utils_Date
::customFormat($membershipDetails->join_date
, '%Y%m%d');
517 $oldPeriodType = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
518 CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id'), 'period_type');
520 // CRM-7297 Membership Upsell
521 if (is_null($membershipTypeID)) {
522 $membershipTypeDetails = self
::getMembershipTypeDetails($membershipDetails->membership_type_id
);
525 $membershipTypeDetails = self
::getMembershipTypeDetails($membershipTypeID);
527 $statusDetails = CRM_Member_BAO_MembershipStatus
::getMembershipStatus($statusID);
529 if ($statusDetails['is_current_member'] == 1) {
530 $startDate = $membershipDetails->start_date
;
531 // CRM=7297 Membership Upsell: we need to handle null end_date in case we are switching
532 // from a lifetime to a different membership type
533 if (is_null($membershipDetails->end_date
)) {
534 $date = date('Y-m-d');
537 $date = $membershipDetails->end_date
;
539 $date = explode('-', $date);
540 // We have to add 1 day first in case it's the end of the month, then subtract afterwards
541 // eg. 2018-02-28 should renew to 2018-03-31, if we just added 1 month we'd get 2018-03-28
542 $logStartDate = date('Y-m-d', mktime(0, 0, 0,
544 (double) ($date[2] +
1),
548 $date = explode('-', $logStartDate);
553 switch ($membershipTypeDetails['duration_unit']) {
555 //need to check if the upsell is from rolling to fixed and adjust accordingly
556 if ($membershipTypeDetails['period_type'] == 'fixed' && $oldPeriodType == 'rolling') {
557 $month = substr($membershipTypeDetails['fixed_period_start_day'], 0, strlen($membershipTypeDetails['fixed_period_start_day']) - 2);
558 $day = substr($membershipTypeDetails['fixed_period_start_day'], -2);
562 $year = $year +
($numRenewTerms * $membershipTypeDetails['duration_interval']);
567 $month = $month +
($numRenewTerms * $membershipTypeDetails['duration_interval']);
571 $day = $day +
($numRenewTerms * $membershipTypeDetails['duration_interval']);
574 if ($membershipTypeDetails['duration_unit'] == 'lifetime') {
578 $endDate = date('Y-m-d', mktime(0, 0, 0,
584 $today = date('Y-m-d');
585 $membershipDates['today'] = CRM_Utils_Date
::customFormat($today, '%Y%m%d');
586 $membershipDates['start_date'] = CRM_Utils_Date
::customFormat($startDate, '%Y%m%d');
587 $membershipDates['end_date'] = CRM_Utils_Date
::customFormat($endDate, '%Y%m%d');
588 $membershipDates['log_start_date'] = CRM_Utils_Date
::customFormat($logStartDate, '%Y%m%d');
591 $today = date('Y-m-d');
593 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
595 // Calculate new start/end dates when join date is today
596 $renewalDates = self
::getDatesForMembershipType($membershipTypeDetails['id'],
597 $today, NULL, NULL, $numRenewTerms
599 $membershipDates['today'] = CRM_Utils_Date
::customFormat($today, '%Y%m%d');
600 $membershipDates['start_date'] = $renewalDates['start_date'];
601 $membershipDates['end_date'] = $renewalDates['end_date'];
602 $membershipDates['log_start_date'] = $renewalDates['start_date'];
603 // CRM-18503 - set join_date as today in case the membership type is fixed.
604 if ($membershipTypeDetails['period_type'] == 'fixed' && !isset($membershipDates['join_date'])) {
605 $membershipDates['join_date'] = $renewalDates['join_date'];
608 if (!isset($membershipDates['join_date'])) {
609 $membershipDates['join_date'] = $membershipDates['start_date'];
612 return $membershipDates;
616 * Retrieve all Membership Types with Member of Contact id.
618 * @param array $membershipTypes
619 * array of membership type ids
621 * array of the details of membership types with Member of Contact id
623 public static function getMemberOfContactByMemTypes($membershipTypes) {
624 $memTypeOrganizations = [];
625 if (empty($membershipTypes)) {
626 return $memTypeOrganizations;
629 $result = CRM_Core_DAO
::executeQuery("SELECT id, member_of_contact_id FROM civicrm_membership_type WHERE id IN (" . implode(',', $membershipTypes) . ")");
630 while ($result->fetch()) {
631 $memTypeOrganizations[$result->id
] = $result->member_of_contact_id
;
634 return $memTypeOrganizations;
638 * The function returns all the Organization for all membershipTypes .
640 * @param int $membershipTypeId
644 public static function getMembershipTypeOrganization($membershipTypeId = NULL) {
645 $allMembershipTypes = [];
647 $membershipType = new CRM_Member_DAO_MembershipType();
649 if (isset($membershipTypeId)) {
650 $membershipType->id
= $membershipTypeId;
652 $membershipType->find();
654 while ($membershipType->fetch()) {
655 $allMembershipTypes[$membershipType->id
] = $membershipType->member_of_contact_id
;
657 return $allMembershipTypes;
661 * Function to retrieve organization and associated membership
665 * arrays of organization and membership types
668 public static function getMembershipTypeInfo() {
669 if (!self
::$_membershipTypeInfo) {
672 $query = 'SELECT memType.id, memType.name, memType.member_of_contact_id, c.sort_name
673 FROM civicrm_membership_type memType INNER JOIN civicrm_contact c ON c.id = memType.member_of_contact_id
674 WHERE memType.is_active = 1 ';
675 $dao = CRM_Core_DAO
::executeQuery($query);
676 while ($dao->fetch()) {
677 $orgs[$dao->member_of_contact_id
] = $dao->sort_name
;
678 $types[$dao->member_of_contact_id
][$dao->id
] = $dao->name
;
681 self
::$_membershipTypeInfo = [$orgs, $types];
683 return self
::$_membershipTypeInfo;
687 * @param array $params
688 * @param int $previousID
689 * @param int $membershipTypeId
691 public static function createMembershipPriceField($params, $previousID, $membershipTypeId) {
693 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
695 if (!empty($params['member_of_contact_id'])) {
696 $fieldName = $params['member_of_contact_id'];
699 $fieldName = $previousID;
701 $fieldLabel = 'Membership Amount';
704 'price_set_id ' => $priceSetId,
705 'name' => $fieldName,
708 CRM_Price_BAO_PriceField
::retrieve($fieldParams, $results);
709 if (empty($results)) {
711 $fieldParams['label'] = $fieldLabel;
712 $fieldParams['name'] = $fieldName;
713 $fieldParams['price_set_id'] = $priceSetId;
714 $fieldParams['html_type'] = 'Radio';
715 $fieldParams['is_display_amounts'] = $fieldParams['is_required'] = 0;
716 $fieldParams['weight'] = $fieldParams['option_weight'][1] = 1;
717 $fieldParams['option_label'][1] = $params['name'];
718 $fieldParams['option_description'][1] = $params['description'] ??
NULL;
720 $fieldParams['membership_type_id'][1] = $membershipTypeId;
721 $fieldParams['option_amount'][1] = empty($params['minimum_fee']) ?
0 : $params['minimum_fee'];
722 $fieldParams['financial_type_id'] = $params['financial_type_id'] ??
NULL;
725 CRM_Member_Form_MembershipType
::checkPreviousPriceField($previousID, $priceSetId, $membershipTypeId, $optionsIds);
726 $fieldParams['option_id'] = $optionsIds['option_id'] ??
NULL;
728 CRM_Price_BAO_PriceField
::create($fieldParams);
731 $fieldID = $results['id'];
732 $fieldValueParams = [
733 'price_field_id' => $fieldID,
734 'membership_type_id' => $membershipTypeId,
737 CRM_Price_BAO_PriceFieldValue
::retrieve($fieldValueParams, $results);
738 if (!empty($results)) {
739 $results['label'] = $results['name'] = $params['name'];
740 $results['amount'] = empty($params['minimum_fee']) ?
0 : $params['minimum_fee'];
744 'price_field_id' => $fieldID,
745 'name' => $params['name'],
746 'label' => $params['name'],
747 'amount' => empty($params['minimum_fee']) ?
0 : $params['minimum_fee'],
748 'membership_type_id' => $membershipTypeId,
754 CRM_Member_Form_MembershipType
::checkPreviousPriceField($previousID, $priceSetId, $membershipTypeId, $optionsIds);
755 if (!empty($optionsIds['option_id'])) {
756 $results['id'] = current($optionsIds['option_id']);
759 $results['financial_type_id'] = $params['financial_type_id'] ??
NULL;
760 $results['description'] = $params['description'] ??
NULL;
761 CRM_Price_BAO_PriceFieldValue
::add($results);
766 * This function updates all price field value for quick config
767 * price set which has membership type
769 * @param int $membershipTypeId membership type id
771 * @param array $params
773 public static function updateAllPriceFieldValue($membershipTypeId, $params) {
776 'financial_type_id' => 'financial_type_id',
778 'minimum_fee' => 'amount',
779 'description' => 'description',
780 'visibility' => 'visibility_id',
782 $priceFieldValueBAO = new CRM_Price_BAO_PriceFieldValue();
783 $priceFieldValueBAO->membership_type_id
= $membershipTypeId;
784 $priceFieldValueBAO->find();
785 while ($priceFieldValueBAO->fetch()) {
787 'id' => $priceFieldValueBAO->id
,
788 'price_field_id' => $priceFieldValueBAO->price_field_id
,
790 //Get priceset details.
791 $fieldParams = ['fid' => $priceFieldValueBAO->price_field_id
];
792 $setID = CRM_Price_BAO_PriceSet
::getSetId($fieldParams);
793 $setParams = ['id' => $setID];
794 $setValues = CRM_Price_BAO_PriceSet
::retrieve($setParams, $defaults);
795 if (!empty($setValues->is_quick_config
) && $setValues->name
!= 'default_membership_type_amount') {
796 foreach ($fieldsToUpdate as $key => $value) {
797 if ($value == 'visibility_id' && !empty($params['visibility'])) {
798 $updateParams['visibility_id'] = CRM_Price_BAO_PriceField
::getVisibilityOptionID(strtolower($params['visibility']));
801 $updateParams[$value] = $params[$key] ??
NULL;
804 CRM_Price_BAO_PriceFieldValue
::add($updateParams);
810 * Cached wrapper for membership types.
812 * Since this is used from the batched script caching helps.
814 * Caching is by domain - if that hits any issues we should add a new function getDomainMembershipTypes
815 * or similar rather than 'just add another param'! but this is closer to earlier behaviour so 'should' be OK.
818 * List of membershipType details keyed by membershipTypeID
819 * @throws \CiviCRM_API3_Exception
821 public static function getAllMembershipTypes() {
822 $cacheString = __CLASS__
. __FUNCTION__
. CRM_Core_Config
::domainID();
823 if (!Civi
::cache('metadata')->has($cacheString)) {
824 $types = civicrm_api3('MembershipType', 'get', ['options' => ['limit' => 0, 'sort' => 'weight']])['values'];
825 $taxRates = CRM_Core_PseudoConstant
::getTaxRates();
826 $keys = ['description', 'relationship_type_id', 'relationship_direction', 'max_related', 'auto_renew'];
827 // In order to avoid down-stream e-notices we undo api v3 filtering of NULL values. This is covered
828 // in Unit tests & ideally we might switch to apiv4 but I would argue we should build caching
829 // of metadata entities like this directly into apiv4.
830 foreach ($types as $id => $type) {
831 foreach ($keys as $key) {
832 if (!isset($type[$key])) {
833 $types[$id][$key] = NULL;
836 if (isset($type['contribution_type_id'])) {
837 unset($types[$id]['contribution_type_id']);
839 $types[$id]['tax_rate'] = (float) ($taxRates[$type['financial_type_id']] ??
0.0);
841 if ($types[$id]['tax_rate'] !== 0.0) {
842 $multiplier +
= ($types[$id]['tax_rate'] / 100);
844 $types[$id]['minimum_fee_with_tax'] = (float) $types[$id]['minimum_fee'] * $multiplier;
846 Civi
::cache('metadata')->set($cacheString, $types);
848 return Civi
::cache('metadata')->get($cacheString);
852 * Get a specific membership type (leveraging the cache).
857 * @throws \CiviCRM_API3_Exception
859 public static function getMembershipType($id) {
860 return self
::getAllMembershipTypes()[$id];