UserNationalDay.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace App\Modules\Activity\Services;
  3. use App\Consts\SysConsts;
  4. use App\Modules\Activity\Models\ActivityNationalDay;
  5. use App\Modules\User\Services\UserService;
  6. use Redis;
  7. use DB;
  8. use Exception;
  9. /**
  10. * 个人微信号——用户国庆活动
  11. * @property int $uid
  12. * @property int $sign_day 累计签到天数
  13. * @property bool $is_sign 今天是否已签到
  14. * @property int $bonus 今天签到获取奖金币
  15. */
  16. class UserNationalDay
  17. {
  18. use NationalDay { __construct as private baseConfig;}
  19. private $uid;
  20. public $is_sign;
  21. public $sign_day;
  22. public $bonus;
  23. public function __construct(int $uid)
  24. {
  25. $this->baseConfig();
  26. $this->uid = $uid;
  27. $this->sign_day = $this->getUserSignDays();
  28. $this->is_sign = $this->judgeIsSign();
  29. }
  30. /**
  31. * 签到
  32. */
  33. public function sign()
  34. {
  35. if (!$this->is_sign) {
  36. $this->sign_day++;
  37. $this->bonus = $this->getSignBonusMoney($this->sign_day);
  38. $this->saveRedisSign();
  39. $this->saveSign();
  40. }
  41. }
  42. /**
  43. * 获取用户签到配置项
  44. */
  45. public function getSignConfigs()
  46. {
  47. return collect($this->sign_config)->map(function ($item) {
  48. $item['is_get'] = $item['day'] <= $this->sign_day;
  49. return $item;
  50. })->all();
  51. }
  52. /**
  53. * 判断今天用户是否签到
  54. * @return bool
  55. */
  56. private function judgeIsSign()
  57. {
  58. $result = Redis::sismember($this->redis_key, $this->uid);
  59. if (!$result) {
  60. $result = ActivityNationalDay::where('uid', $this->uid)->where('created_at', '>=', date('Y-m-d'))->exists();
  61. if ($result) {
  62. $this->saveRedisSign();
  63. }
  64. }
  65. return $result;
  66. }
  67. /**
  68. * 获取用户累计签到天数
  69. */
  70. private function getUserSignDays()
  71. {
  72. return ActivityNationalDay::where('uid', $this->uid)->count();
  73. }
  74. /**
  75. * redis签到
  76. */
  77. private function saveRedisSign()
  78. {
  79. Redis::sAdd($this->redis_key, $this->uid);
  80. Redis::expire($this->redis_key, SysConsts::ONE_DAY_SECONDS);
  81. }
  82. /**
  83. * 保存签到信息
  84. */
  85. private function saveSign()
  86. {
  87. try {
  88. DB::beginTransaction();
  89. $day = new ActivityNationalDay;
  90. $day->uid = $this->uid;
  91. $day->bonus = $this->bonus;
  92. $day->save();
  93. UserService::addBalance($this->uid, $this->bonus, 0, $this->bonus);
  94. DB::commit();
  95. } catch (Exception $e) {
  96. Log::error('national_day: ' . $e->getMessage());
  97. DB::rollback();
  98. }
  99. }
  100. }