AutoStatisticsUserDailyTraffic.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 __construct() {
  13. parent::__construct();
  14. }
  15. public function handle() {
  16. $jobStartTime = microtime(true);
  17. $userList = User::query()->where('status', '>=', 0)->whereEnable(1)->get();
  18. foreach($userList as $user){
  19. // 统计一次所有节点的总和
  20. $this->statisticsByNode($user->id);
  21. // 统计每个节点产生的流量
  22. $nodeList = SsNode::query()->whereStatus(1)->orderBy('id')->get();
  23. foreach($nodeList as $node){
  24. $this->statisticsByNode($user->id, $node->id);
  25. }
  26. }
  27. $jobEndTime = microtime(true);
  28. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  29. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  30. }
  31. private function statisticsByNode($user_id, $node_id = 0) {
  32. $start_time = strtotime(date('Y-m-d 00:00:00', strtotime("-1 day")));
  33. $end_time = strtotime(date('Y-m-d 23:59:59', strtotime("-1 day")));
  34. $query = UserTrafficLog::query()->whereUserId($user_id)->whereBetween('log_time', [$start_time, $end_time]);
  35. if($node_id){
  36. $query->whereNodeId($node_id);
  37. }
  38. $u = $query->sum('u');
  39. $d = $query->sum('d');
  40. $total = $u + $d;
  41. $traffic = flowAutoShow($total);
  42. if($total){ // 有数据才记录
  43. $obj = new UserTrafficDaily();
  44. $obj->user_id = $user_id;
  45. $obj->node_id = $node_id;
  46. $obj->u = $u;
  47. $obj->d = $d;
  48. $obj->total = $total;
  49. $obj->traffic = $traffic;
  50. $obj->save();
  51. }
  52. }
  53. }