LevelCalculationTrait.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Longyi\RewardPoints\Services;
  3. use Webkul\Customer\Models\CustomerGroup;
  4. trait LevelCalculationTrait
  5. {
  6. /**
  7. * 根据成长值计算等级
  8. */
  9. protected function calculateLevel($growthValue)
  10. {
  11. $level = CustomerGroup::where('min_growth_value', '<=', $growthValue)
  12. ->orderBy('min_growth_value', 'desc')
  13. ->first();
  14. return $level && $level->growth_level_name
  15. ? $level->growth_level_name
  16. : 'V1';
  17. }
  18. /**
  19. * 根据等级名称获取对应的客户组ID
  20. */
  21. protected function getCustomerGroupIdByLevel($levelName)
  22. {
  23. // 根据等级名称查找
  24. $customerGroup = CustomerGroup::where('growth_level_name', $levelName)->first();
  25. if ($customerGroup) {
  26. return $customerGroup->id;
  27. }
  28. // 根据 code 查找
  29. $customerGroup = CustomerGroup::where('code', strtolower($levelName))->first();
  30. if ($customerGroup) {
  31. return $customerGroup->id;
  32. }
  33. // 返回默认组
  34. return optional(CustomerGroup::where('code', 'general')->first())->id;
  35. }
  36. /**
  37. * 获取配置值(带缓存)
  38. */
  39. protected function getSetting($code, $default = null)
  40. {
  41. $cacheKey = "growth_value_setting_{$code}";
  42. return cache()->remember($cacheKey, 3600, function () use ($code, $default) {
  43. $setting = \Longyi\RewardPoints\Models\RewardPointSetting::where('code', $code)->first();
  44. return $setting ? $setting->value : $default;
  45. });
  46. }
  47. }