ctrlpanel/app/Console/Commands/ChargeCreditsCommand.php

102 lines
2.8 KiB
PHP
Raw Normal View History

2021-06-05 09:26:32 +00:00
<?php
namespace App\Console\Commands;
2021-06-25 21:42:53 +00:00
use App\Models\Product;
2021-06-05 09:26:32 +00:00
use App\Models\Server;
2021-06-25 21:42:53 +00:00
use App\Models\User;
2021-06-25 22:24:44 +00:00
use App\Notifications\ServersSuspendedNotification;
2021-06-05 09:26:32 +00:00
use Illuminate\Console\Command;
class ChargeCreditsCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'credits:charge';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Charge all users with active servers';
2021-06-25 22:24:44 +00:00
/**
* A list of users that have to be notified
*
2021-06-25 22:24:44 +00:00
* @var array
*/
protected $usersToNotify = [];
2021-06-05 09:26:32 +00:00
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return string
*/
public function handle()
{
2021-06-25 22:24:44 +00:00
Server::whereNull('suspended')->chunk(10, function ($servers) {
2021-06-12 12:24:50 +00:00
/** @var Server $server */
foreach ($servers as $server) {
2021-06-25 21:42:53 +00:00
/** @var Product $product */
$product = $server->product;
/** @var User $user */
2021-06-05 09:26:32 +00:00
$user = $server->user;
//charge credits / suspend server
2021-06-25 22:24:44 +00:00
if ($user->credits >= $product->getHourlyPrice()) {
2021-06-25 21:42:53 +00:00
$this->line("<fg=blue>{$user->name}</> Current credits: <fg=green>{$user->credits}</> Credits to be removed: <fg=red>{$product->getHourlyPrice()}</>");
$user->decrement('credits', $product->getHourlyPrice());
2021-06-05 09:26:32 +00:00
} else {
2021-06-25 22:24:44 +00:00
try {
//suspend server
2021-06-25 22:24:44 +00:00
$this->line("<fg=yellow>{$server->name}</> from user: <fg=blue>{$user->name}</> has been <fg=red>suspended!</>");
2021-06-26 14:57:03 +00:00
$server->suspend();
2021-06-25 22:24:44 +00:00
//add user to notify list
if (!in_array($user, $this->usersToNotify)) {
2021-06-25 22:24:44 +00:00
array_push($this->usersToNotify, $user);
}
} catch (\Exception $exception) {
$this->error($exception->getMessage());
}
2021-06-05 09:26:32 +00:00
}
}
});
2021-06-25 22:24:44 +00:00
return $this->notifyUsers();
}
/**
* @return bool
*/
public function notifyUsers()
{
if (!empty($this->usersToNotify)) {
2021-06-25 22:24:44 +00:00
/** @var User $user */
foreach ($this->usersToNotify as $user) {
$this->line("<fg=yellow>Notified user:</> <fg=blue>{$user->name}</>");
$user->notify(new ServersSuspendedNotification());
}
}
//reset array
$this->usersToNotify = [];
2021-06-25 22:24:44 +00:00
return true;
2021-06-05 09:26:32 +00:00
}
}