AutoResetUserTraffic.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use Illuminate\Console\Command;
  5. use App\Http\Models\Order;
  6. use App\Http\Models\User;
  7. use Log;
  8. class AutoResetUserTraffic extends Command
  9. {
  10. protected $signature = 'autoResetUserTraffic';
  11. protected $description = '自动重置用户可用流量';
  12. protected static $systemConfig;
  13. public function __construct()
  14. {
  15. parent::__construct();
  16. self::$systemConfig = Helpers::systemConfig();
  17. }
  18. public function handle()
  19. {
  20. $jobStartTime = microtime(true);
  21. // 重置用户流量
  22. if (self::$systemConfig['reset_traffic']) {
  23. $this->resetUserTraffic();
  24. }
  25. $jobEndTime = microtime(true);
  26. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  27. Log::info('执行定时任务【' . $this->description . '】,耗时' . $jobUsedTime . '秒');
  28. }
  29. // 重置用户流量
  30. private function resetUserTraffic()
  31. {
  32. $userList = User::query()->where('status', '>=', 0)->where('expire_time', '>=', date('Y-m-d'))->get();
  33. if (!$userList->isEmpty()) {
  34. foreach ($userList as $user) {
  35. if (!$user->traffic_reset_day) {
  36. continue;
  37. }
  38. // 取出用户最后购买的有效套餐
  39. $order = Order::query()
  40. ->with(['user', 'goods'])
  41. ->whereHas('goods', function ($q) {
  42. $q->where('type', 2);
  43. })
  44. ->where('user_id', $user->id)
  45. ->where('is_expire', 0)
  46. ->orderBy('oid', 'desc')
  47. ->first();
  48. if (!$order) {
  49. continue;
  50. }
  51. $month = abs(date('m'));
  52. $today = abs(date('d'));
  53. if ($order->user->traffic_reset_day == $today) {
  54. // 跳过本月,防止异常重置
  55. if ($month == date('m', strtotime($order->expire_at))) {
  56. continue;
  57. } elseif ($month == date('m', strtotime($order->created_at))) {
  58. continue;
  59. }
  60. User::query()->where('id', $user->id)->update(['u' => 0, 'd' => 0]);
  61. }
  62. }
  63. }
  64. }
  65. }