Grade.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\task\behavior\user;
  10. use think\Cache;
  11. use app\task\model\User as UserModel;
  12. use app\task\model\user\Grade as GradeModel;
  13. class Grade
  14. {
  15. /* @var GradeModel $model */
  16. private $model;
  17. /**
  18. * 执行函数
  19. * @param $model
  20. * @return bool
  21. * @throws \Exception
  22. */
  23. public function run($model)
  24. {
  25. if (!$model instanceof GradeModel) {
  26. return new GradeModel and false;
  27. }
  28. $this->model = $model;
  29. if (!$model::$wxapp_id) {
  30. return false;
  31. }
  32. $cacheKey = "__task_space__[user/Grade]__{$model::$wxapp_id}";
  33. if (!Cache::has($cacheKey)) {
  34. // 设置用户的会员等级
  35. $this->setUserGrade();
  36. Cache::set($cacheKey, time(), 60 * 10);
  37. }
  38. return true;
  39. }
  40. /**
  41. * 设置用户的会员等级
  42. * @return array|bool|false
  43. * @throws \Exception
  44. */
  45. private function setUserGrade()
  46. {
  47. // 用户模型
  48. $UserModel = new UserModel;
  49. // 获取所有等级
  50. $list = GradeModel::getUsableList(null, ['weight' => 'desc']);
  51. if ($list->isEmpty()) {
  52. return false;
  53. }
  54. // 遍历等级,根据升级条件 查询满足消费金额的用户列表,并且他的等级小于该等级
  55. $data = [];
  56. foreach ($list as $grade) {
  57. $userList = $UserModel->getUpgradeUserList($grade, array_keys($data));
  58. foreach ($userList as $user) {
  59. if (!isset($data[$user['user_id']])) {
  60. $data[$user['user_id']] = [
  61. 'user_id' => $user['user_id'],
  62. 'old_grade_id' => $user['grade_id'],
  63. 'new_grade_id' => $grade['grade_id'],
  64. ];
  65. }
  66. }
  67. }
  68. // 批量修改会员的等级
  69. return $UserModel->setBatchGrade($data);
  70. }
  71. }