作者 李美松

新增网站流量统计 - 2

<?php
namespace App\Console\Commands\Bside\Statistics;
use App\Models\Bside\Statistics\TrafficStatistics;
use App\Models\CustomerVisit\CustomerVisit;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Throwable;
class Logic
{
/**
* @param int $type 统计类型
* @return array
*/
public function getMonths(int $type = TrafficStatistics::TYPE_SOURCE)
{
$date = getPreviousMonthsDate();
$TrafficStatistics = new TrafficStatistics();
$lists = $TrafficStatistics->getMonthsLists($type, $date);
if (!empty($lists)) {
$dd = [];
$lists->map(function ($item) use (&$dd) {
$dd[] = $item->year . '-' . str_pad($item->month, 2, '0', STR_PAD_LEFT);
});
$date = array_diff($date, $dd);
}
return $date;
}
/**
* @param array $column 统计数据
* @param int $type 统计类型
* @param string|null $date 日期 格式:Y-m
* @param string $message
* @return array
* @throws Throwable
*/
public function save(array $column, int $type = TrafficStatistics::TYPE_SOURCE, string $date = null, $message = '统计当月访问来源数据')
{
DB::beginTransaction();
// 获取当天的IP|PV数量
$customerVisit = new CustomerVisit();
$ip_count = $customerVisit->getMonthIPCount($date);
$pv_count = $customerVisit->getMonthPVCount($date);
$column['pvnum'] = $pv_count;
$column['ipnum'] = $ip_count;
$date = $date ?? date('Y-m');
// 统计数据并插入到数据库
$dd = explode('-', $date);
$year = $dd[0];
$month = $dd[1];
$column['year'] = $year;
$column['month'] = $month;
$trafficStatistics = new TrafficStatistics();
$isRes = $trafficStatistics->getMonth($type, $year, $month);
if ($isRes) {
$trafficStatistics = $isRes;
}
foreach ($column as $key => $value) {
$trafficStatistics->$key = $value;
}
$res = $trafficStatistics->save();
if ($res) {
DB::commit();
$meg = "{$date} - {$message}成功!";
} else {
DB::rollBack();
$meg = "{$date} - {$message}失败!";
}
return ['status' => $res, 'msg' => $meg];
}
}
... ...
<?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;
}
}
... ...
<?php
namespace App\Console\Commands\Bside\Statistics;
use App\Models\Bside\Statistics\TrafficStatistics;
use App\Models\CustomerVisit\CustomerVisit;
use Illuminate\Console\Command;
use Throwable;
class StatisticsDistribution extends Command
{
public $error = 0;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'statistics_distribution';
/**
* The console command description.
*
* @var string
*/
protected $description = '统计当月地域分布数据';
public $logic;
public function __construct()
{
parent::__construct();
$this->logic = new Logic();
}
/**
* 定时执行
* @return void
* @throws Throwable
*/
public function handle()
{
$date = $this->logic->getMonths(TrafficStatistics::TYPE_DISTRIBUTION);
if (!empty($date)) {
foreach ($date as $value) {
echo $this->statistics_distribution($value);
}
}
echo $this->statistics_distribution();
}
/**
* 统计当天流量趋势数据PV|IP数量
* @param string|null $date
* @return int|mixed
* @throws Throwable
*/
protected function statistics_distribution(string $date = null)
{
$customerVisit = new CustomerVisit();
$type = TrafficStatistics::TYPE_DISTRIBUTION;
$top = json_encode($customerVisit->getCountryCount($date) ?? []);
$res = $this->logic->save(compact('top', 'type'), $type, $date, '统计当月地域分布数据');
if (!$res['status']) {
$this->info($res['msg']);
$this->error++;
}
$this->info($res['msg']);
return $this->error;
}
}
... ...
<?php
namespace App\Console\Commands\Bside\Statistics;
use App\Models\Bside\Statistics\TrafficStatistics;
use App\Models\CustomerVisit\CustomerVisit;
use Illuminate\Console\Command;
use Throwable;
class StatisticsPage extends Command
{
public $error = 0;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'statistics_page';
/**
* The console command description.
*
* @var string
*/
protected $description = '统计当月受访页面数据';
public $logic;
public function __construct()
{
parent::__construct();
$this->logic = new Logic();
}
/**
* 定时执行
* @return void
*/
public function handle()
{
$date = $this->logic->getMonths(TrafficStatistics::TYPE_PAGE);
if (!empty($date)) {
foreach ($date as $value) {
echo $this->statistics_page($value);
}
}
echo $this->statistics_page();
}
/**
* 统计当月受访页面数据
* @param null $date
* @return int|mixed
* @throws Throwable
*/
protected function statistics_page($date = null)
{
$customerVisit = new CustomerVisit();
$top = json_encode($customerVisit->getPageCount($date) ?? []);
$type = TrafficStatistics::TYPE_PAGE;
$res = $this->logic->save(compact('top', 'type'), $type, $date, '统计当月受访页面数据');
if (!$res['status']) {
$this->info($res['msg']);
$this->error++;
}
$this->info($res['msg']);
return $this->error;
}
}
... ...
<?php
namespace App\Console\Commands\Bside\Statistics;
use App\Models\Bside\Statistics\TrafficStatistics;
use App\Models\CustomerVisit\CustomerVisit;
use Illuminate\Console\Command;
use Throwable;
class StatisticsSource extends Command
{
public $error = 0;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'statistics_source';
/**
* The console command description.
*
* @var string
*/
protected $description = '统计当月访问来源数据';
public $logic;
public function __construct()
{
parent::__construct();
$this->logic = new Logic();
}
/**
* @return void
* @throws Throwable
*/
public function handle()
{
$date = $this->logic->getMonths();
if (!empty($date)) {
foreach ($date as $value) {
echo $this->statistics_source($value);
}
}
echo $this->statistics_source();
}
/**
* 统计当天流量趋势数据
* @param string|null $date
* @return int|mixed
* @throws Throwable
*/
protected function statistics_source(string $date = null)
{
// 获取当天的IP|PV数量
$customerVisit = new CustomerVisit();
$top = json_encode($customerVisit->getUrlCount($date) ?? []);
$type = TrafficStatistics::TYPE_SOURCE;
$res = $this->logic->save(compact('top', 'type'), $type, $date);
if (!$res['status']) {
$this->info($res['msg']);
$this->error++;
}
$this->info($res['msg']);
return $this->error;
}
}
... ...
<?php
namespace App\Console\Commands\Bside\Statistics;
use App\Models\Bside\Statistics\TrafficStatistics;
use App\Models\CustomerVisit\CustomerVisit;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Throwable;
class StatisticsTerminal extends Command
{
public $error = 0;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'statistics_terminal';
/**
* The console command description.
*
* @var string
*/
protected $description = '统计当月访问终端数据';
public $logic;
public function __construct()
{
parent::__construct();
$this->logic = new Logic();
}
/**
* @return void
* @throws Throwable
*/
public function handle()
{
$date = $this->logic->getMonths(TrafficStatistics::TYPE_TERMINAL);
if (!empty($date)) {
foreach ($date as $value) {
echo $this->statistics_terminal($value);
}
}
echo $this->statistics_terminal();
}
/**
* 统计当月访问终端数据
* @param string|null $date
* @return int|mixed
* @throws Throwable
*/
protected function statistics_terminal(string $date = null)
{
$customerVisit = new CustomerVisit();
$pcnum = $customerVisit->getTerminalPcCount($date);
$mbnum = $customerVisit->getTerminalMobileCount($date);
$top = json_encode($customerVisit->getCountryCount($date) ?? []);
$type = TrafficStatistics::TYPE_TERMINAL;
$res = $this->logic->save(compact('top', 'type', 'pcnum', 'mbnum'), $type, $date, '统计当月访问终端数据');
if (!$res['status']) {
$this->info($res['msg']);
$this->error++;
}
$this->info($res['msg']);
return $this->error;
}
}
... ...
... ... @@ -3,12 +3,14 @@
namespace App\Console\Commands\Bside\Statistics;
use App\Models\Bside\Statistics\TrafficStatistics;
use App\Models\CustomerVisit\CustomerVisit;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Throwable;
class StatisticsTrend extends Command
{
public $error = 0;
/**
* The name and signature of the console command.
*
... ... @@ -21,44 +23,52 @@ class StatisticsTrend extends Command
*
* @var string
*/
protected $description = '统计当天流量趋势数据PV|IP数量';
protected $description = '统计当月流量趋势数据';
public $logic;
public function __construct()
{
parent::__construct();
$this->logic = new Logic();
}
/**
* @name :(定时执行)handle
* @author :lyh
* @method :post
* @time :2023/5/12 14:48
* 定时执行
* @return void
* @throws GuzzleException|Throwable
*/
public function handle()
{
$date = $this->logic->getMonths(TrafficStatistics::TYPE_TREND);
if (!empty($date)) {
foreach ($date as $value) {
echo $this->statistics_trend($value);
}
}
echo $this->statistics_trend();
}
/**
* 统计当天流量趋势数据PV|IP数量
* 统计当天流量趋势数据
* @param string|null $date
* @return int|mixed
* @throws GuzzleException|Throwable
*/
protected function statistics_trend()
protected function statistics_trend(string $date = null)
{
$customerVisit = new CustomerVisit();
$date = date('Y-m-d');
$ip_count = $customerVisit->getDayIPCount();
$pv_count = $customerVisit->getDayPVCount();
$trafficStatistics = new TrafficStatistics();
$trafficStatistics->type = TrafficStatistics::TYPE_TREND;
$trafficStatistics->
$data = [
'date' => $date,
'ip_count' => $ip_count,
'pv_count' => $pv_count,
];
// $res = $customerVisit->insert($data);
if ($res) {
$this->info('统计当天流量趋势数据PV|IP数量成功');
} else {
$domain = request()->getHttpHost(); //'www.wowstainless.com';
$sta_date = !is_null($date) ? $date . "-01" : date('Y-m-01');
$inquiry = getInquiryInformation($domain, $sta_date);
$innum = $inquiry['count'] ?? 0;
$top = json_encode($inquiry['lists'] ?? []);
$type = TrafficStatistics::TYPE_TREND;
$res = $this->logic->save(compact('top', 'type', 'innum'), $type, $date, '统计当月流量趋势数据');
if (!$res['status']) {
$this->info($res['msg']);
$this->error++;
$this->info('统计当天流量趋势数据PV|IP数量失败');
}
$this->info($res['msg']);
return $this->error;
}
}
... ...
<?php
namespace App\Console\Commands\Bside\Domain;
namespace App\Console\Commands\Domain;
use App\Exceptions\AsideGlobalException;
use App\Exceptions\BsideGlobalException;
use App\Http\Logic\Aside\Domain\DomainInfoLogic;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
class DomainTime extends Command
... ... @@ -39,7 +40,7 @@ class DomainTime extends Command
* 更新域名|证书到期时间
* @return int|mixed|void
* @throws AsideGlobalException
* @throws BsideGlobalException
* @throws BsideGlobalException|GuzzleException
*/
protected function update_domain_time()
{
... ...
... ... @@ -27,7 +27,23 @@ class Kernel extends ConsoleKernel
$schedule->command('web_traffic 1')->everyThirtyMinutes(); // 引流 1-3个月的项目,半小时一次
$schedule->command('web_traffic 2')->cron('*/18 * * * *'); // 引流 4-8个月的项目,18分钟一次
$schedule->command('web_traffic 3')->cron('*/12 * * * *'); // 引流 大于9个月的项目,12分钟一次
// $schedule->command('domain_time')->dailyAt('01:00')->withoutOverlapping(1); // 更新域名|证书结束时间,每天凌晨1点执行一次
// 更新域名|证书结束时间,每天凌晨1点执行一次
// $schedule->command('domain_time')->dailyAt('01:00')->withoutOverlapping(1);
// B站 - 网站数据统计
// 获取当前月份最后一天
$lastDay = date('Y-m-t');
// 统计当月访问来源数据,每月最后一天23:59点执行一次
$schedule->command('statistics_source')->monthlyOn($lastDay, '23:59')->withoutOverlapping(1);
// 统计当月地域分布数据,每月最后一天23:59点执行一次
$schedule->command('statistics_distribution')->monthlyOn($lastDay, '23:59')->withoutOverlapping(1);
// 统计当月受访页面数据,每月最后一天23:59点执行一次
$schedule->command('statistics_page')->monthlyOn($lastDay, '23:59')->withoutOverlapping(1);
// 统计当月访问终端数据,每月最后一天23:59点执行一次
$schedule->command('statistics_terminal')->monthlyOn($lastDay, '23:59')->withoutOverlapping(1);
// 统计当月流量趋势数据,每月最后一天23:59点执行一次
$schedule->command('statistics_trend')->monthlyOn($lastDay, '23:59')->withoutOverlapping(1);
// 统计当天流量趋势数据,每天23:59点执行一次
$schedule->command('statistics_day_trend')->dailyAt('23:59')->withoutOverlapping(1);
}
/**
... ...
<?php
use App\Utils\LogUtils;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Carbon;
define('HTTP_OPENAI_URL','http://openai.waimaoq.com/');
define('HTTP_OPENAI_URL', 'http://openai.waimaoq.com/');
/**
* 生成路由标识
* @param $string
... ... @@ -28,7 +30,8 @@ if (!function_exists('generateRoute')) {
* @author zbj
* @date 2023/4/27
*/
function errorLog($title, $params, Throwable $exception){
function errorLog($title, $params, Throwable $exception)
{
$exceptionMessage = "错误CODE:" . $exception->getCode() .
"-----错误message:" . $exception->getMessage() .
'------错误文件:' . $exception->getFile() .
... ... @@ -37,15 +40,15 @@ function errorLog($title, $params, Throwable $exception){
LogUtils::error($title, $params, $exceptionMessage);
}
if(!function_exists('http_post')){
if (!function_exists('http_post')) {
/**
* 发送http post请求
* @param type $url
* @param type $post_data
*/
function http_post($url, $post_data,$header = [])
function http_post($url, $post_data, $header = [])
{
if(empty($header)){
if (empty($header)) {
$header = array(
"Accept: application/json",
"Content-Type:application/json;charset=utf-8",
... ... @@ -64,22 +67,22 @@ if(!function_exists('http_post')){
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
if (curl_errno($ch)) {
\Illuminate\Support\Facades\Log::write(print_r(curl_errno($ch),1),'debug---1');
\Illuminate\Support\Facades\Log::write(print_r(curl_errno($ch), 1), 'debug---1');
}
curl_close($ch);
return json_decode($res, true);
}
}
if(!function_exists('http_get')){
if (!function_exists('http_get')) {
/**
* 发送http get请求
* @param type $url
* @return type
*/
function http_get($url,$header = [])
function http_get($url, $header = [])
{
if(empty($header)){
if (empty($header)) {
$header[] = "content-type: application/json;
charset = UTF-8";
}
... ... @@ -98,7 +101,7 @@ if(!function_exists('http_get')){
}
if(!function_exists('_get_child')){
if (!function_exists('_get_child')) {
/**
* 菜单权限->得到子级数组
* @param int
... ... @@ -110,7 +113,7 @@ if(!function_exists('_get_child')){
foreach ($arr as $k => $v) {
$v = (array)$v;
if ($v['pid'] == $my_id) {
$v['sub'] = _get_child($v['id'],$arr);
$v['sub'] = _get_child($v['id'], $arr);
$new_arr[] = $v;
}
}
... ... @@ -119,7 +122,6 @@ if(!function_exists('_get_child')){
}
if (!function_exists('checkDomain')) {
/**
* 检查并补全域名协议
... ... @@ -130,12 +132,12 @@ if (!function_exists('checkDomain')) {
function checkDomain($value)
{
$urlParts = parse_url(strtolower($value));
if(empty($urlParts['host'])){
if (empty($urlParts['host'])) {
$urlParts = parse_url('https://' . $value);
}
$host = $urlParts['host'] ?? '';
$host = $urlParts['host'] ?? '';
$scheme = $urlParts['scheme'] ?? 'https';
if(!in_array($scheme, ['http', 'https'])){
if (!in_array($scheme, ['http', 'https'])) {
return false;
}
if (preg_match('/^(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6}$/', $host)) {
... ... @@ -147,7 +149,6 @@ if (!function_exists('checkDomain')) {
}
/**
* 把返回的数据集转换成Tree
* @param $list array 数据列表
... ... @@ -158,20 +159,21 @@ if (!function_exists('checkDomain')) {
* @param bool $empty_child 当子数据不存在,是否要返回空子数据
* @return array
*/
function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0,$empty_child=true) {
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0, $empty_child = true)
{
// 如果是数字,则是root
if(is_numeric($pk)){
$root = $pk;
$pk = 'id';
if (is_numeric($pk)) {
$root = $pk;
$pk = 'id';
}
// 创建Tree
$tree = array();
if(is_array($list)) {
if (is_array($list)) {
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
if($empty_child){
$list[$key][$child] = [];
if ($empty_child) {
$list[$key][$child] = [];
}
$refer[$data[$pk]] =& $list[$key];
}
... ... @@ -180,9 +182,9 @@ function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0,$em
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[] =& $list[$key];
}else{
} else {
if (isset($refer[$parentId])) {
$refer[$parentId][$child][] = & $list[$key];
$refer[$parentId][$child][] = &$list[$key];
}
}
}
... ... @@ -198,14 +200,15 @@ function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0,$em
* @author:dc
* @time 2022/1/11 10:13
*/
function tree_to_list($tree, $child='_child'){
$lists = [];
foreach ($tree as $item){
$c = $item[$child]??[];
function tree_to_list($tree, $child = '_child')
{
$lists = [];
foreach ($tree as $item) {
$c = $item[$child] ?? [];
unset($item[$child]);
$lists[] = $item;
if ($c){
$lists = array_merge($lists,tree_to_list($c, $child));
if ($c) {
$lists = array_merge($lists, tree_to_list($c, $child));
}
}
return $lists;
... ... @@ -233,10 +236,10 @@ if (!function_exists('object_to_array')) {
*/
function object_to_array($data)
{
if(is_object($data)){
if (is_object($data)) {
$data = (array)$data;
}else{
foreach ($data as $k => $v){
} else {
foreach ($data as $k => $v) {
$data[$k] = object_to_array($v);
}
}
... ... @@ -244,3 +247,76 @@ if (!function_exists('object_to_array')) {
}
}
if (!function_exists('getPreviousDaysDate')) {
/**
* 获取当前指定前几天日期,默认获取前三天日期
* @param int $day
* @return array
*/
function getPreviousDaysDate(int $day = 3)
{
$days = [];
while ($day > 0) {
$days[] = date("Y-m-d", strtotime("-{$day} days"));
$day -= 1;
}
return $days;
}
}
if (!function_exists('getPreviousMonthsDate')) {
/**
* 获取当前指定前几天日期,默认获取前三天日期
* @param int $month
* @return array
*/
function getPreviousMonthsDate(int $month = 3)
{
$months = [];
while ($month > 0) {
$months[] = date("Y-m", strtotime("-{$month} months"));
$month -= 1;
}
return $months;
}
}
if (!function_exists('getInquiryInformation')) {
/**
* 获取第三方询盘信息
* @return array|string
* @throws GuzzleException
*/
function getInquiryInformation($domain, $sta_date)
{
$token = md5($domain . date("Y-m-d"));
$source = '1,3';
$url = "https://form.globalso.com/api/external-interface/country_con/15243d63ed5a5738?domain={$domain}&token={$token}&source={$source}&sta_date={$sta_date}";
$client = new Client(['verify' => false]);
$http = $client->get($url);
$data = [];
if ($http->getStatusCode() != 200) {
return $data;
}
$content = $http->getBody()->getContents();
$json = json_decode($content, true);
if ($json['status'] != 200) {
return $content;
}
$data['count'] = $json['data']['count'];
$data['lists'] = $json['data']['data'];
return $data;
}
}
if (!function_exists('stringUnderlineLowercase')) {
/**
* 正则 - 名字转为小写并将空格转为下划线
* @param $name
* @return string
*/
function stringUnderlineLowercase($name)
{
return trim(strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', $name)));
}
}
... ...
... ... @@ -3,9 +3,8 @@
namespace App\Http\Controllers\Bside;
use App\Models\CustomerVisit\CustomerVisit;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use App\Http\Logic\Bside\Statistics\StatisticsLogic;
use App\Models\Bside\Statistics\TrafficStatistics;
use Illuminate\Http\JsonResponse;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
... ... @@ -17,136 +16,80 @@ use Psr\Container\NotFoundExceptionInterface;
*/
class StatisticsController extends BaseController
{
private $customerVisit;
public $statisticsLogic;
public $trafficStatistics;
public function __construct()
{
$this->customerVisit = new CustomerVisit();
$this->statisticsLogic = new StatisticsLogic();
$this->trafficStatistics = new TrafficStatistics();
}
/**
* 访问来源
* @return JsonResponse
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function source()
{
$pv_count = $this->customerVisit->getMonthPVCount();
$ip_count = $this->customerVisit->getMonthIPCount();
$lists = $this->customerVisit->getUrlCount();
return $this->success(compact('pv_count', 'ip_count', 'lists'));
$type = $this->trafficStatistics::TYPE_SOURCE;
$response = $this->statisticsLogic->getStatisticsData($type);
return $this->success($response);
}
/**
* 地域分布
* @return JsonResponse
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function distribution()
{
$pv_count = $this->customerVisit->getMonthPVCount();
$ip_count = $this->customerVisit->getMonthIPCount();
$lists = $this->customerVisit->getCountryCount();
return $this->success(compact('pv_count', 'ip_count', 'lists'));
$type = $this->trafficStatistics::TYPE_DISTRIBUTION;
$response = $this->statisticsLogic->getStatisticsData($type);
return $this->success($response);
}
/**
* 受访页面
* @return JsonResponse
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function page()
{
$pv_count = $this->customerVisit->getMonthPVCount();
$ip_count = $this->customerVisit->getMonthIPCount();
$lists = $this->customerVisit->getPageCount();
return $this->success(compact('pv_count', 'ip_count', 'lists'));
$type = $this->trafficStatistics::TYPE_PAGE;
$response = $this->statisticsLogic->getStatisticsData($type);
return $this->success($response);
}
/**
* 访问终端
* @return JsonResponse
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function terminal()
{
$pv_count = $this->customerVisit->getMonthPVCount();
$ip_count = $this->customerVisit->getMonthIPCount();
$pc_count = $this->customerVisit->getTerminalPcCount();
$mobile_count = $this->customerVisit->getTerminalMobileCount();
$lists = $this->customerVisit->getCountryCount();
return $this->success(compact('pv_count', 'ip_count', 'pc_count', 'mobile_count', 'lists'));
$type = $this->trafficStatistics::TYPE_TERMINAL;
$response = $this->statisticsLogic->getStatisticsData($type);
return $this->success($response);
}
/**
* 流量趋势
* @return JsonResponse
* @throws ContainerExceptionInterface
* @throws GuzzleException
* @throws NotFoundExceptionInterface
*/
public function trend()
{
// dd($this->customerVisit->getDayIPCount());
$pv_count = $this->customerVisit->getMonthPVCount();
$ip_count = $this->customerVisit->getMonthIPCount();
$inquiry = $this->getCache('inquiry_information');
$inquiry_count = $inquiry['count'] ?? 0;
$lists = $inquiry['lists'] ?? [];
return $this->success(compact('pv_count', 'ip_count', 'inquiry_count', 'lists'));
}
/**
* 获取缓存
* @param string $key 缓存键名
* @param float|int $time 缓存时间,默认2小时
* @return mixed
* @throws ContainerExceptionInterface
* @throws GuzzleException
* @throws NotFoundExceptionInterface
*/
public function getCache(string $key, $time = 60 * 60 * 2)
{
$domain = request()->getHttpHost(); //'www.wowstainless.com';
$sta_date = date('Y-m-01');
$key = $key . '_' . $this->stringUnderlineLowercase($domain) . '_' . str_replace('-', '_', $sta_date);
$value = cache()->get($key);
if (!$value) {
$value = $this->getInquiryInformation($domain, $sta_date);
cache()->put($key, $value, $time);
}
return $value;
$type = $this->trafficStatistics::TYPE_TREND;
$response = $this->statisticsLogic->getStatisticsData($type);
return $this->success($response);
}
/**
* 正则 - 名字转为小写并将空格转为下划线
* @param $name
* @return string
*/
public function stringUnderlineLowercase($name)
{
return trim(strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', $name)));
}
/**
* 获取第三方询盘信息
* @return array|string
* @throws GuzzleException
*/
public function getInquiryInformation($domain, $sta_date)
{
$token = md5($domain . date("Y-m-d"));
$source = '1,3';
$url = "https://form.globalso.com/api/external-interface/country_con/15243d63ed5a5738?domain={$domain}&token={$token}&source={$source}&sta_date={$sta_date}";
$client = new Client(['verify' => false]);
$http = $client->get($url);
$data = [];
if ($http->getStatusCode() != 200) {
return $data;
}
$content = $http->getBody()->getContents();
$json = json_decode($content, true);
if ($json['status'] != 200) {
return $content;
}
$data['count'] = $json['data']['count'];
$data['lists'] = $json['data']['data'];
return $data;
}
}
... ...
<?php
namespace App\Http\Logic\Bside\Statistics;
use App\Http\Logic\Bside\BaseLogic;
use App\Models\Bside\Statistics\TrafficStatistics;
use App\Models\CustomerVisit\CustomerVisit;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Contracts\Cache\Repository;
use Illuminate\Support\Facades\DB;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Throwable;
class StatisticsLogic extends BaseLogic
{
public $trafficStatistics;
private $customerVisit;
public $date;
public $time = 60 * 60 * 2;
public function __construct()
{
parent::__construct();
$this->customerVisit = new CustomerVisit();
$this->trafficStatistics = new TrafficStatistics();
try {
$this->date = request()->get('date') ?? null;
// 判断传入日期是否大于当月
if ($this->checkIsGreaterMonth($this->date)) {
$this->date = null;
}
// 判断传入日期是否是当月
if ($this->checkIsMonth($this->date)) {
$this->date = null;
}
} catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
$this->date = null;
}
}
/**
* @param $type
* @return array|Repository|mixed
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface|Throwable
*/
public function getStatisticsData($type)
{
$function = debug_backtrace()[1]['function'];
// 判断是否查询当月数据
if (!is_null($this->date)) {
// 获取缓存名
$key = $this->cacheName($type, $this->date);
$response = cache()->get($key);
if (empty($response)) {
$dd = explode('-', $this->date);
$year = $dd[0] ?? null;
$month = str_pad($dd[1], 2, '0', STR_PAD_LEFT) ?? null;
// 获取当前数据是否存在
$data = $this->trafficStatistics->getData($type, $year, $month);
if (is_null($data)) {
$response = $this->$function();
// 存在则直接返回
$response_data = array_filter($response);
if ($response_data) {
// 不存在则请求接口获取数据并保存
$this->create($response_data);
}
} else {
$response = $data->toArray();
}
// 缓存数据
cache()->put($key, $response, $this->time);
}
} else {
$response = $this->$function();
}
return $response;
}
/**
* @param $response
* @return bool
* @throws Throwable
*/
public function create($response)
{
DB::beginTransaction();
$keys = array_flip($this->trafficStatistics::KEY_VALUE);
foreach ($response as $k => $v) {
if (is_array($v)) {
$v = json_encode($v);
}
$field = $keys[$k];
$this->trafficStatistics->$field = $v;
}
$isRes = $this->trafficStatistics->save();
if (!$isRes) {
DB::rollBack();
return false;
}
DB::commit();
return true;
}
/**
* 访问来源
* @return array
*/
public function source()
{
$response = $this->getPvIp();
$response['lists'] = $this->customerVisit->getUrlCount();
return $response;
}
public function getPvIp()
{
$response['pv_count'] = $this->customerVisit->getMonthPVCount();
$response['ip_count'] = $this->customerVisit->getMonthIPCount();
return $response;
}
/**
* 地域分布
* @return array
*/
public function distribution()
{
$response = $this->getPvIp();
$response['lists'] = $this->customerVisit->getCountryCount();
return $response;
}
/**
* 流量趋势
* @return array
* @throws ContainerExceptionInterface
* @throws GuzzleException
* @throws NotFoundExceptionInterface
*/
public function trend()
{
$response = $this->getPvIp();
$inquiry = $this->getCache('inquiry_information', $this->date);
$response['in_count'] = $inquiry['count'] ?? 0;
$response['lists'] = $inquiry['lists'] ?? [];
return $response;
}
/**
* 访问终端
* @return array
*/
public function terminal()
{
$response = $this->getPvIp();
$response['pc_count'] = $this->customerVisit->getTerminalPcCount();
$response['mobile_count'] = $this->customerVisit->getTerminalMobileCount();
$response['lists'] = $this->customerVisit->getCountryCount();
return $response;
}
/**
* 受访页面
* @return array
*/
public function page()
{
$response = $this->getPvIp();
$response['lists'] = $this->customerVisit->getPageCount();
return $response;
}
/**
* 获取缓存
* @param string $key 缓存键名
* @param string|null $date 日期 格式:Y-m
* @param float|int $time 缓存时间,默认2小时
* @return mixed
* @throws ContainerExceptionInterface
* @throws GuzzleException
* @throws NotFoundExceptionInterface
*/
public function getCache(string $key, string $date = null, $time = 60 * 60 * 2)
{
$domain = request()->getHttpHost(); //'www.wowstainless.com';
$sta_date = !is_null($date) ? $date . '-01' : date('Y-m-01');
$key = $key . '_' . stringUnderlineLowercase($domain) . '_' . str_replace('-', '_', $sta_date);
$value = cache()->get($key);
if (!$value) {
$value = getInquiryInformation($domain, $sta_date);
cache()->put($key, $value, $time);
}
return $value;
}
/**
* @param int $type
* @param string|null $date 日期 格式:Y-m-d
* @return string
*/
public function cacheName(int $type = TrafficStatistics::TYPE_SOURCE, string $date = null)
{
return 'statistics_' . $type . '_' . str_replace('-', '_', $date);
}
/**
* 判断传入日期是否是当日
* @param $date
* @return bool
*/
public function checkIsDay($date)
{
// 传入日期的时间戳
$timestamp = strtotime($date);
// 当日的日期格式,如:2021-10-13
$today = date('Y-m-d');
// 传入日期的日期格式,如:2021-10-12
$date = date('Y-m-d', $timestamp);
// 判断传入日期是否是当日
return $date == $today;
}
/**
* 判断传入日期是否大于当日
* @param $date
* @return bool
*/
public function checkIsGreaterDay($date)
{
// 传入日期的时间戳
$timestamp = strtotime($date);
// 当前日期的时间戳
$now = strtotime(date('Y-m-d'));
// 判断传入日期是否大于当前日期
return $timestamp > $now;
}
/**
* 判断传入日期是否大于当月
* @param $date
* @return bool
*/
public function checkIsGreaterMonth($date)
{
// 传入日期的时间戳
$timestamp = strtotime($date);
// 当前月份的时间戳
$nowMonth = strtotime(date('Y-m'));
// 判断传入日期是否大于当前月份
return $timestamp > $nowMonth;
}
/**
* 判断传入日期是否是当月
* @param $date
* @return bool
*/
public function checkIsMonth($date)
{
// 获取当前时间戳
$now = time();
// 获取当月的起始时间戳和结束时间戳
$firstDay = strtotime(date('Y-m-01', $now));
$lastDay = strtotime(date('Y-m-t', $now));
// 传入日期的时间戳
$timestamp = strtotime($date);
// 判断传入日期是否在当月范围内
return $timestamp >= $firstDay && $timestamp <= $lastDay;
}
}
... ...
... ... @@ -6,10 +6,37 @@ use App\Models\Base;
/**
* Class DomainInfo
*
* @package App\Models\Aside\Domain
* @Author YiYuan-LIn
* @Date: 2019/5/16
* @Date : 2019/5/16
* 域名信息模型
* @property int $id
* @property string|null $domain 域名
* @property string $belong_to 域名归属 1 - 公司 2 - 客户
* @property string $status 域名状态 0 - 正常 1 - 关闭
* @property string|null $domain_start_time 域名开始时间
* @property string|null $domain_end_time 域名结束时间
* @property string|null $certificate_start_time 证书开始时间
* @property string|null $certificate_end_time 证书结束时间
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property int|null $deleted 软删除 0 - 正常 1 - 软删除
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo query()
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereBelongTo($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereCertificateEndTime($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereCertificateStartTime($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereDeleted($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereDomain($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereDomainEndTime($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereDomainStartTime($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereStatus($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfo whereUpdatedAt($value)
* @mixin \Eloquent
*/
class DomainInfo extends Base
{
... ...
... ... @@ -4,6 +4,36 @@ namespace App\Models\Aside\Domain;
use Illuminate\Database\Eloquent\Model;
/**
* App\Models\Aside\Domain\DomainInfoLog
*
* @property int $id
* @property int|null $user_id 操作用户
* @property string|null $action 用户操作 - 增删改查
* @property string|null $original 初始数据
* @property string|null $revised 修改后的数据
* @property string|null $ip 用户IP
* @property string|null $url
* @property string|null $method 请求类型
* @property string|null $remarks 备注
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog query()
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereAction($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereIp($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereMethod($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereOriginal($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereRemarks($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereRevised($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereUrl($value)
* @method static \Illuminate\Database\Eloquent\Builder|DomainInfoLog whereUserId($value)
* @mixin \Eloquent
*/
class DomainInfoLog extends Model
{
protected $table = 'gl_domain_info_log';
... ...
... ... @@ -3,9 +3,50 @@
namespace App\Models\Bside\Statistics;
use App\Models\Base;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
/**
* 流量统计
* App\Models\Bside\Statistics\TrafficStatistics
*
* @property int $id
* @property int|null $type 类型:
* 1 - 访问来源
* 2 - 地域分布
* 3 - 受访页面
* 4 - 访问终端
* 5 - 流量趋势
* @property int|null $year 年
* @property int|null $month 月
* @property string|null $top 访问来源|国家|页面TOP15 - 百分比 - json格式
* @property int|null $innum 询盘量
* @property float|null $conversion 询盘转化率
* @property int|null $pvnum 浏览量
* @property int|null $ipnum 访客量
* @property int|null $pcnum PC端访问量
* @property int|null $mbnum 移动端访问量
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static Builder|TrafficStatistics newModelQuery()
* @method static Builder|TrafficStatistics newQuery()
* @method static Builder|TrafficStatistics query()
* @method static Builder|TrafficStatistics whereConversion($value)
* @method static Builder|TrafficStatistics whereCreatedAt($value)
* @method static Builder|TrafficStatistics whereId($value)
* @method static Builder|TrafficStatistics whereInnum($value)
* @method static Builder|TrafficStatistics whereIpnum($value)
* @method static Builder|TrafficStatistics whereMbnum($value)
* @method static Builder|TrafficStatistics whereMonth($value)
* @method static Builder|TrafficStatistics wherePageview($value)
* @method static Builder|TrafficStatistics wherePcnum($value)
* @method static Builder|TrafficStatistics wherePvnum($value)
* @method static Builder|TrafficStatistics whereTop($value)
* @method static Builder|TrafficStatistics whereType($value)
* @method static Builder|TrafficStatistics whereUpdatedAt($value)
* @method static Builder|TrafficStatistics whereUserSessions($value)
* @method static Builder|TrafficStatistics whereYear($value)
* @mixin \Eloquent
*/
class TrafficStatistics extends Base
{
... ... @@ -21,4 +62,121 @@ class TrafficStatistics extends Base
const TYPE_TERMINAL = 4;
/** @var int 流量趋势 */
const TYPE_TREND = 5;
/** @var string[] 类型对应字段 */
const FIELDS = [
self::TYPE_SOURCE => ['pvnum', 'ipnum', 'top'],
self::TYPE_DISTRIBUTION => ['pvnum', 'ipnum', 'top'],
self::TYPE_PAGE => ['pvnum', 'ipnum', 'top'],
self::TYPE_TERMINAL => ['pvnum', 'ipnum', 'top', 'pcnum', 'mbnum'],
self::TYPE_TREND => ['pvnum', 'ipnum', 'top', 'innum'],
];
/** @var string[] 数据库字段对应返回字段 */
const KEY_VALUE = [
'pvnum' => 'pv_count',
'ipnum' => 'ip_count',
'pcnum' => 'pc_count',
'mbnum' => 'mobile_count',
'innum' => 'in_count',
'top' => 'lists'
];
/**
* 根据类型获取字段
* @param int $type
* @return string[]
*/
public function selectFields(int $type = self::TYPE_SOURCE)
{
return self::FIELDS[$type] ?? [];
}
/**
* 根据类型获取月份列表数据
* @param int $type
* @param $date
* @return TrafficStatistics[]|Builder[]|Collection
*/
public function getMonthsLists(int $type = self::TYPE_SOURCE, $date = null)
{
$query = $this->query()->where('type', $type);
if ($date != null) {
if (is_array($date)) {
$years = $months = [];
foreach ($date as $value) {
$dd = explode('-', $value);
$year = $dd[0];
$month = $dd[1];
if (!in_array($year, $years)) {
$years[] = $year;
}
if (!in_array($month, $months)) {
$months[] = $month;
}
}
$query->whereIn('year', $years)
->whereIn('month', $months);
} else {
$dd = explode('-', $date);
$year = $dd[0];
$month = $dd[1];
$query->where('year', $year)
->where('month', $month);
}
} else {
$query->where('year', date('Y'))
->where('month', date('m'));
}
return $query->get();
}
/**
* 根据类型获取单条月份数据
* @param int $type
* @param $year
* @param $month
* @return TrafficStatistics|Builder|Model|object|null
*/
public function getMonth(int $type = self::TYPE_SOURCE, $year = null, $month = null)
{
$year = $year ?? date('Y');
$month = $month ?? date('m');
return $this->query()->where('type', $type)
->where('year', $year)
->where('month', $month)
->first();
}
/**
* 根据类型获取数据
* @param int $type
* @param null $year
* @param null $month
* @return TrafficStatistics|Builder|Model|object|null
*/
public function getData(int $type = self::TYPE_SOURCE, $year = null, $month = null)
{
$key_value = self::KEY_VALUE;
$field_arr = [];
foreach ($this->selectFields($type) as $field) {
$field_arr[] = "{$field} as {$key_value[$field]}";
}
$query = $this->query();
if ($field_arr) {
$query->selectRaw(implode(',', $field_arr));
}
return $query->where('type', $type)
->where('year', $year)
->where('month', $month)
->first();
}
/**
* 格式化数据
* @param $value
* @return mixed
*/
public function getListsAttribute($value)
{
return json_decode($value);
}
}
... ...
... ... @@ -3,11 +3,62 @@
namespace App\Models\Bside\Statistics;
use App\Models\Base;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
/**
* 流量统计
* App\Models\Bside\Statistics\TrafficTrends
*
* @property int $id
* @property string|null $day 统计当天日期
* @property int|null $pvnum 当天的访问次数PV
* @property int|null $ipnum 当天的独立访问IP数量
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static Builder|TrafficTrends newModelQuery()
* @method static Builder|TrafficTrends newQuery()
* @method static Builder|TrafficTrends query()
* @method static Builder|TrafficTrends whereCreatedAt($value)
* @method static Builder|TrafficTrends whereDay($value)
* @method static Builder|TrafficTrends whereId($value)
* @method static Builder|TrafficTrends whereIpnum($value)
* @method static Builder|TrafficTrends wherePvnum($value)
* @method static Builder|TrafficTrends whereUpdatedAt($value)
* @mixin \Eloquent
*/
class TrafficTrends extends Base
{
protected $table = 'gl_traffic_trends';
/**
* * 根据时间获取数据
* @param array|string $date
* @return TrafficTrends[]|Builder[]|Collection
*/
public function getDaysLists($date = null)
{
$query = $this->query();
if ($date != null) {
if (is_array($date)) {
$query->whereIn('day', $date);
} else {
$query->where('day', $date);
}
} else {
$query->whereYear('day', '=', date("Y"))
->whereMonth('day', '=', date("m"))
->whereDay('day', '=', date("d"));
}
return $query->get();
}
/**
* @param string|null $date
* @return TrafficTrends|Builder|Model|object|null
*/
public function getDay(string $date = null)
{
return $this->query()->where('day', $date ?? date('Y-m-d'))->first();
}
}
... ...
... ... @@ -3,9 +3,43 @@
namespace App\Models\CustomerVisit;
use App\Models\Base;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
/**
* App\Models\CustomerVisit\CustomerVisit
*
* @property int $id ID
* @property string $url 客户访问URL
* @property string $referrer_url 访问来源
* @property int $device_port 设备端口 1:PC端,2:移动端
* @property string $country 国家
* @property string $city 地区
* @property string $ip 访问ip
* @property int $depth 访问深度
* @property string $domain 域名
* @property \Illuminate\Support\Carbon $created_at 访问时间
* @property \Illuminate\Support\Carbon $updated_at 更新时间
* @property string $updated_date 统计日期
* @method static \Database\Factories\CustomerVisit\CustomerVisitFactory factory(...$parameters)
* @method static Builder|CustomerVisit newModelQuery()
* @method static Builder|CustomerVisit newQuery()
* @method static Builder|CustomerVisit query()
* @method static Builder|CustomerVisit whereCity($value)
* @method static Builder|CustomerVisit whereCountry($value)
* @method static Builder|CustomerVisit whereCreatedAt($value)
* @method static Builder|CustomerVisit whereDepth($value)
* @method static Builder|CustomerVisit whereDevicePort($value)
* @method static Builder|CustomerVisit whereDomain($value)
* @method static Builder|CustomerVisit whereId($value)
* @method static Builder|CustomerVisit whereIp($value)
* @method static Builder|CustomerVisit whereReferrerUrl($value)
* @method static Builder|CustomerVisit whereUpdatedAt($value)
* @method static Builder|CustomerVisit whereUpdatedDate($value)
* @method static Builder|CustomerVisit whereUrl($value)
* @mixin \Eloquent
*/
class CustomerVisit extends Base
{
use HasFactory;
... ... @@ -19,51 +53,102 @@ class CustomerVisit extends Base
/** @var int 移动端 */
const TERMINAL_MOBILE = 2;
public function queryField($field, $action = 'count', $whereDay = false)
/**
* @param string $field 统计字段
* @param string $action 统计方法 count|sum
* @param bool $isDay 是否按天查询
* @param string|null $date 日期 格式:Y-m-d
* @return int
*/
public function queryField(string $field, string $action = 'count', bool $isDay = false, string $date = null)
{
$query = $this->query()
->selectRaw("{$action}({$field}) as count")
->whereYear('updated_date', '=', date("Y"))
->whereMonth('updated_date', '=', date("m"));
if ($whereDay) {
$query->whereDay('updated_date', '=', date("d"));
$query = $this->query()->selectRaw("{$action}({$field}) as count");
if ($date) {
$dd = explode('-', $date);
$year = $dd[0] ?? null;
$month = $dd[1] ?? null;
$day = $dd[2] ?? null;
if (!is_null($year)) {
$query->whereYear('updated_date', '=', $year);
}
if (!is_null($month)) {
$query->whereMonth('updated_date', '=', $month);
}
if (!is_null($day)) {
$query->whereDay('updated_date', '=', $day);
}
} else {
$query->whereYear('updated_date', '=', date("Y"))
->whereMonth('updated_date', '=', date("m"));
if ($isDay) {
$query->whereDay('updated_date', '=', date("d"));
}
}
return (int)$query->value('count') ?? 0;
}
public function queryTerminal($field, $action = self::TERMINAL_PC)
/**
* @param string $field 统计字段
* @param int $action 终端类型
* @param string|null $date 日期 格式:Y-m
* @return int
*/
public function queryTerminal(string $field, string $date = null, int $action = self::TERMINAL_PC)
{
return (int)$this->query()
->selectRaw("count(*) as count")
->where($field, '=', $action)
->whereYear('updated_date', '=', date("Y"))
->whereMonth('updated_date', '=', date("m"))
->value('count') ?? 0;
$query = $this->query()
->selectRaw("count(*) as count")
->where($field, '=', $action);
$this->extracted($date, $query);
return (int)$query->value('count') ?? 0;
}
public function getRankingData($field, $limit = self::LIMIT)
/**
* @param string $field 查询字段
* @param string|null $date 日期 格式:Y-m-d
* @param int $limit 查询条数
* @return Builder[]|Collection|\Illuminate\Support\Collection
*/
public function getRankingData(string $field, string $date = null, int $limit = self::LIMIT)
{
return $this->query()
->selectRaw('count(*) as count, ' . $field . ' as request')
->whereYear('updated_date', '=', date("Y"))
->whereMonth('updated_date', '=', date("m"))
->groupBy($field)
->orderBy('count', 'desc')
->limit($limit)
->get();
$query = $this->query()
->selectRaw('count(*) as count, ' . $field . ' as request');
$this->extracted($date, $query);
return $query->groupBy($field)
->orderBy('count', 'desc')
->limit($limit)
->get();
}
public function getSum($field)
/**
* 获取相加总数
* @param string $field
* @param string|null $date 日期 格式:Y-m-d
* @return int
*/
public function getSum(string $field, string $date = null)
{
return $this->queryField($field, 'sum');
return $this->queryField($field, 'sum', false, $date);
}
public function getCount($field)
/**
* 获取总数
* @param string $field
* @param string|null $date 日期 格式:Y-m-d
* @return int
*/
public function getCount(string $field, string $date = null)
{
return $this->queryField($field);
return $this->queryField($field, 'count', false, $date);
}
/**
* 获取列表和总数
* @param Collection $data
* @param int $limit
* @return array
*/
public function returnLists(Collection $data, int $limit = self::LIMIT)
{
$lists = $data->toArray();
... ... @@ -74,85 +159,117 @@ class CustomerVisit extends Base
/**
* 查询当月流量的浏览量
* @param string|null $data 日期 格式:Y-m-d
* @return int
*/
public function getMonthPVCount()
public function getMonthPVCount(string $data = null)
{
return $this->getSum('depth');
return $this->getSum('depth', $data);
}
/**
* 查询当月流量的访客量
* @param string|null $data 日期 格式:Y-m-d
* @return int
*/
public function getMonthIPCount()
public function getMonthIPCount(string $data = null)
{
return $this->getCount('ip');
return $this->getCount('ip', $data);
}
/**
* 查询当月TOP15访问来源
* @param int $limit
* @param string|null $date 日期 格式:Y-m-d
* @param int $limit 查询条数
* @return array
*/
public function getUrlCount(int $limit = self::LIMIT)
public function getUrlCount(string $date = null, int $limit = self::LIMIT)
{
return $this->getRankingData('referrer_url', $limit);
return $this->getRankingData('referrer_url', $date, $limit);
}
/**
* 查询当月TOP15访问国家来源
* @param string|null $date 日期 格式:Y-m
* @param int $limit
* @return array
*/
public function getCountryCount(int $limit = self::LIMIT)
public function getCountryCount(string $date = null, int $limit = self::LIMIT)
{
return $this->getRankingData('country', $limit);
return $this->getRankingData('country', $date, $limit);
}
/**
* 查询当月TOP15受访页面
* @param string|null $date 日期 格式:Y-m
* @param int $limit
* @return array
*/
public function getPageCount(int $limit = self::LIMIT)
public function getPageCount(string $date = null, int $limit = self::LIMIT)
{
return $this->getRankingData('url', $limit);
return $this->getRankingData('url', $date, $limit);
}
/**
* 查询当月TOP15访问终端
* @param string|null $date 日期 格式:Y-m-d
* @return int
*/
public function getTerminalPcCount()
public function getTerminalPcCount(string $date = null)
{
return $this->queryTerminal('device_port');
return $this->queryTerminal('device_port', $date);
}
/**
* 查询当月TOP15访问终端
* @param string|null $date 日期 格式:Y-m-d
* @return int
*/
public function getTerminalMobileCount()
public function getTerminalMobileCount(string $date = null)
{
return $this->queryTerminal('device_port', self::TERMINAL_MOBILE);
return $this->queryTerminal('device_port', $date, self::TERMINAL_MOBILE);
}
/**
* 查询当日流量的浏览量
* @param string|null $date 日期 格式:Y-m-d
* @return int
*/
public function getDayPVCount()
public function getDayPVCount(string $date = null)
{
return $this->queryField('depth', 'sum', true);
return $this->queryField('depth', 'sum', true, $date);
}
/**
* 查询当日流量的访客量
* @param string|null $date 日期 格式:Y-m-d
* @return int
*/
public function getDayIPCount()
public function getDayIPCount(string $date = null)
{
return $this->queryField('ip', 'count', true);
return $this->queryField('ip', 'count', true, $date);
}
/**
* @param $date
* @param $query
* @return void
*/
public function extracted($date, $query)
{
if (!is_null($date)) {
$dd = explode('-', $date);
$year = $dd[0] ?? null;
$month = $dd[1] ?? null;
if (!is_null($year)) {
$query->whereYear('updated_date', '=', $year);
}
if (!is_null($month)) {
$query->whereMonth('updated_date', '=', $month);
}
} else {
$query->whereYear('updated_date', '=', date("Y"))
->whereMonth('updated_date', '=', date("m"));
}
}
}
... ...
... ... @@ -4,6 +4,36 @@ namespace App\Models\Devops;
use App\Models\Base;
/**
* App\Models\Devops\ServerInformation
*
* @property int $id
* @property string $type 服务器类型
* @property string|null $ip 服务器ip
* @property string|null $title 服务器标题
* @property string $belong_to 服务器归属 1 - 公司 2 - 客户
* @property string|null $sshpass SSH 密码
* @property int|null $ports SSH 端口
* @property string|null $other 其他信息 json格式
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property int|null $deleted 软删除 0 - 正常 1 - 软删除
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation query()
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereBelongTo($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereDeleted($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereIp($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereOther($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation wherePorts($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereSshpass($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereTitle($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereType($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformation whereUpdatedAt($value)
* @mixin \Eloquent
*/
class ServerInformation extends Base
{
... ...
... ... @@ -4,6 +4,36 @@ namespace App\Models\Devops;
use App\Models\Base;
/**
* App\Models\Devops\ServerInformationLog
*
* @property int $id
* @property int|null $user_id 操作用户
* @property string|null $action 用户操作 - 增删改查
* @property string|null $original 初始数据
* @property string|null $revised 修改后的数据
* @property string|null $ip 用户IP
* @property string|null $url
* @property string|null $method 请求类型
* @property string|null $remarks 备注
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog query()
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereAction($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereIp($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereMethod($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereOriginal($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereRemarks($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereRevised($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereUrl($value)
* @method static \Illuminate\Database\Eloquent\Builder|ServerInformationLog whereUserId($value)
* @mixin \Eloquent
*/
class ServerInformationLog extends Base
{
protected $table = 'gl_server_information_log';
... ...