Untitled
<?php namespace App\Http\Livewire\Front\Performance\Publish\Research; use App\Http\Livewire\Front\Performance\Publish\Components\CardComponent; use App\Models\PostFacebookDailyMetric; use App\Services\Posts\GetPostDailyMetricsTableNamesFromDateRange; use Carbon\Carbon; use Illuminate\Database\Query\Builder; use Illuminate\Support\Facades\DB; class Total3SecViewsFromChannels extends CardComponent { public $name = 'Views on Channels you Manage'; public $description = ''; public $key = '3_sec_views_on_channels'; public $icon = 'clock'; public function mountStats(): void { $dailyMetrics = $this->dailyMetrics(); $this->data = $this->getCardData(); $data = $this->calculateData(collect($dailyMetrics)->values()->all()); dd($data); $this->stats = [ 'labels' => $this->getLastSixMonths(), 'data' => $data, 'total' => $this->numberFormatShort(last($dailyMetrics)), 'avg_description' => '', 'projection' => $this->currentMonthProjection($dailyMetrics), ]; } protected function dailyMetrics(): array { $startDate = $this->startDate()->addDay(); $endDate = $this->endDate()->addDay(); $tableNames = (new GetPostDailyMetricsTableNamesFromDateRange( startDate: $startDate, endDate: $endDate, ))->get(); return (new PostFacebookDailyMetric()) ->setConnection('big_query') ->newQuery() ->from(function ($builder) use ($tableNames, $startDate, $endDate) { foreach ($tableNames as $key => $tableName) { if ($key === 0) { $this->buildBuilder($builder, $tableName, $startDate, $endDate); } else { $builder->unionAll(function ($builder1) use ($tableName, $startDate, $endDate) { $this->buildBuilder($builder1, $tableName, $startDate, $endDate); }); } } }, 't1') ->select([ DB::raw('SUM(post_video_views) AS total'), DB::raw('FORMAT_DATE("%Y-%m", date) as date'), ]) ->groupBy('date') ->orderBy('date') ->withCasts(['date' => 'date', 'total' => 'integer']) ->get() ->mapWithKeys(fn(PostFacebookDailyMetric $dailyMetric) => [ $dailyMetric->date->format('Y-m') => $dailyMetric->total, ]) ->all(); } private function buildBuilder(Builder $builder, string $tableName, Carbon $startDate, Carbon $endDate): void { (new PostFacebookDailyMetric()) ->setTable($tableName) ->newQuery() ->setQuery($builder) ->from($tableName) ->whereBetween('date', [$startDate, $endDate]) ->whereHas('post', fn($builder) => $builder ->whereHas('channel', function ($query) { // $query->when(auth()->user()->isAdminOrOrganisationAdminOrHead($this->stage), // fn($query) => $query->whereIn('manager_id', $this->getUsersToFilter($this->stage)), // fn($query) => $query->where('manager_id', auth()->id()) // ); }) ); } protected function startDate(): Carbon { return Carbon::createFromFormat('Y-m-d', $this->filters['months'] . '-01')->subMonths(5)->startOfMonth(); } protected function endDate(): Carbon { return Carbon::createFromFormat('Y-m-d', $this->filters['months'] . '-01')->endOfMonth(); } }
Leave a Comment