AutoStatisticsUserDailyTraffic.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\SsNode;
  4. use App\Models\User;
  5. use App\Models\UserTrafficDaily;
  6. use App\Models\UserTrafficLog;
  7. use Illuminate\Console\Command;
  8. use Log;
  9. class AutoStatisticsUserDailyTraffic extends Command {
  10. protected $signature = 'autoStatisticsUserDailyTraffic';
  11. protected $description = '自动统计用户每日流量';
  12. public function handle(): void {
  13. $jobStartTime = microtime(true);
  14. foreach(User::query()->activeUser()->get() as $user){
  15. // 统计一次所有节点的总和
  16. $this->statisticsByNode($user->id);
  17. // 统计每个节点产生的流量
  18. foreach(SsNode::query()->whereStatus(1)->orderBy('id')->get() as $node){
  19. $this->statisticsByNode($user->id, $node->id);
  20. }
  21. }
  22. $jobEndTime = microtime(true);
  23. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  24. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  25. }
  26. private function statisticsByNode($user_id, $node_id = 0): void {
  27. $start_time = strtotime(date('Y-m-d 00:00:00', strtotime("-1 day")));
  28. $end_time = strtotime(date('Y-m-d 23:59:59', strtotime("-1 day")));
  29. $query = UserTrafficLog::query()->whereUserId($user_id)->whereBetween('log_time', [$start_time, $end_time]);
  30. if($node_id){
  31. $query->whereNodeId($node_id);
  32. }
  33. $u = $query->sum('u');
  34. $d = $query->sum('d');
  35. $total = $u + $d;
  36. $traffic = flowAutoShow($total);
  37. if($total){ // 有数据才记录
  38. $obj = new UserTrafficDaily();
  39. $obj->user_id = $user_id;
  40. $obj->node_id = $node_id;
  41. $obj->u = $u;
  42. $obj->d = $d;
  43. $obj->total = $total;
  44. $obj->traffic = $traffic;
  45. $obj->save();
  46. }
  47. }
  48. }