AutoStatisticsUserDailyTraffic.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Node;
  4. use App\Models\User;
  5. use App\Models\UserDailyDataFlow;
  6. use App\Models\UserDataFlowLog;
  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->statisticsByUser($user->id);
  17. // 统计每个节点产生的流量
  18. foreach(Node::query()->whereStatus(1)->orderBy('id')->get() as $node){
  19. $this->statisticsByUser($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 statisticsByUser($user_id, $node_id = 0): void {
  27. $query = UserDataFlowLog::query()
  28. ->whereUserId($user_id)
  29. ->whereBetween('log_time', [strtotime(date('Y-m-d')), 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. if($total){ // 有数据才记录
  37. $obj = new UserDailyDataFlow();
  38. $obj->user_id = $user_id;
  39. $obj->node_id = $node_id;
  40. $obj->u = $u;
  41. $obj->d = $d;
  42. $obj->total = $total;
  43. $obj->traffic = flowAutoShow($total);
  44. $obj->save();
  45. }
  46. }
  47. }