StatisticsDayTrend.php 2.4 KB
<?php

namespace App\Console\Commands\Bside\Statistics;

use App\Models\Bside\Statistics\TrafficTrends;
use App\Models\CustomerVisit\CustomerVisit;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Throwable;

class StatisticsDayTrend extends Command
{
    public $error = 0;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'statistics_day_trend';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计当天流量趋势数据';

    /**
     * @return void
     * @throws GuzzleException
     * @throws Throwable
     */
    public function handle()
    {
        $date          = getPreviousDaysDate();
        $trafficTrends = new TrafficTrends();
        $lists         = $trafficTrends->getDaysLists($date);
        if (!empty($lists)) {
            $date = array_diff($date, $lists->pluck('day')->all());
        }
        if (!empty($date)) {
            foreach ($date as $value) {
                echo $this->statistics_day_trend($value);
            }
        }
        echo $this->statistics_day_trend();
    }

    /**
     * 统计当天流量趋势数据PV|IP数量
     * @return int|mixed
     * @throws GuzzleException|Throwable
     */
    protected function statistics_day_trend($date = null)
    {
        DB::beginTransaction();
        $date = $date ?? date('Y-m-d');
        // 获取当天的IP|PV数量
        $customerVisit = new CustomerVisit();
        $ip_count      = $customerVisit->getDayIPCount($date);
        $pv_count      = $customerVisit->getDayPVCount($date);
        // 统计数据并插入到数据库
        $trafficTrends = new TrafficTrends();
        $isRes         = $trafficTrends->getDay($date);
        if ($isRes) {
            $trafficTrends = $isRes;
        }
        $trafficTrends->day   = $date;
        $trafficTrends->pvnum = $pv_count;
        $trafficTrends->ipnum = $ip_count;
        $res                  = $trafficTrends->save();
        if ($res) {
            DB::commit();
            $this->info($date . ' - 统计当天流量趋势数据PV|IP数量成功');
        } else {
            DB::rollBack();
            $this->error++;
            $this->info($date . ' - 统计当天流量趋势数据PV|IP数量失败');
        }
        return $this->error;
    }
}