UserNationalDay.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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 {
  19. __construct as private baseConfig;
  20. }
  21. private $uid;
  22. public $is_sign;
  23. public $sign_day;
  24. public $bonus;
  25. public function __construct(int $uid)
  26. {
  27. $this->baseConfig();
  28. $this->uid = $uid;
  29. $this->sign_day = $this->getUserSignDays();
  30. $this->is_sign = $this->judgeIsSign();
  31. }
  32. /**
  33. * 签到
  34. */
  35. public function sign()
  36. {
  37. if ($this->is_begin && !$this->is_sign) {
  38. $this->sign_day++;
  39. $this->bonus = $this->getSignBonusMoney($this->sign_day);
  40. $this->saveRedisSign();
  41. $this->saveSign();
  42. }
  43. }
  44. /**
  45. * 获取用户签到配置项
  46. */
  47. public function getSignConfigs()
  48. {
  49. return collect($this->sign_config)->map(function ($item) {
  50. $item['is_get'] = $item['day'] <= $this->sign_day;
  51. return $item;
  52. })->all();
  53. }
  54. /**
  55. * 判断今天用户是否签到
  56. * @return bool
  57. */
  58. private function judgeIsSign()
  59. {
  60. $result = Redis::sismember($this->redis_key, $this->uid);
  61. if (!$result) {
  62. $result = ActivityNationalDay::where('uid', $this->uid)->where('created_at', '>=', date('Y-m-d'))->exists();
  63. if ($result) {
  64. $this->saveRedisSign();
  65. }
  66. }
  67. return $result;
  68. }
  69. /**
  70. * 获取用户累计签到天数
  71. */
  72. private function getUserSignDays()
  73. {
  74. return ActivityNationalDay::where('uid', $this->uid)->count();
  75. }
  76. /**
  77. * redis签到
  78. */
  79. private function saveRedisSign()
  80. {
  81. Redis::sAdd($this->redis_key, $this->uid);
  82. Redis::expire($this->redis_key, SysConsts::ONE_DAY_SECONDS);
  83. }
  84. /**
  85. * 保存签到信息
  86. */
  87. private function saveSign()
  88. {
  89. try {
  90. DB::beginTransaction();
  91. $day = new ActivityNationalDay;
  92. $day->uid = $this->uid;
  93. $day->bonus = $this->bonus;
  94. $day->save();
  95. UserService::addBalance($this->uid, $this->bonus, 0, $this->bonus);
  96. DB::commit();
  97. } catch (Exception $e) {
  98. Log::error('national_day: ' . $e->getMessage());
  99. DB::rollback();
  100. }
  101. }
  102. }