Files
vedant-chavan/app/Console/Commands/StoreMonthlyPositions.php
vedant-chavan eff0228447 first commit
2024-06-12 20:29:05 +05:30

68 lines
1.7 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
use App\Models\MonthlyPosition;
use App\Models\LeaderboardMaster;
use Carbon\Carbon;
class StoreMonthlyPositions extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'positions:store-monthly';
/**
* The console command description.
*
* @var string
*/
protected $description = 'At the end of the month, the position of every user is stored';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$currentYear = now()->format('Y');
// $currentYear = 2023;
$currentMonth = now()->format('m');
// $currentMonth = 4;
$users = User::all();
foreach ($users as $user) {
$userId = $user->id;
$user_list = LeaderboardMaster::orderBy('total_score', 'desc')->get();
$position = null;
foreach ($user_list as $index => $user){
if($user->user_id == $userId){
$position = $index + 1;
break;
}
}
if (isset($position)) {
$monthDate = Carbon::createFromDate($currentYear, $currentMonth, 1)->format('Y-m');
MonthlyPosition::updateOrCreate([
'user_id' => $userId,
'month' => $monthDate,
], [
'position' => $position,
]);
}
}
$this->info('Users Position Stored Successfully!');
// return Command::SUCCESS;
}
}