ChargeCreditsCommand.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Product;
  4. use App\Models\Server;
  5. use App\Models\User;
  6. use App\Notifications\ServersSuspendedNotification;
  7. use Illuminate\Console\Command;
  8. class ChargeCreditsCommand extends Command
  9. {
  10. /**
  11. * The name and signature of the console command.
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'credits:charge';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = 'Charge all users with active servers';
  22. /**
  23. * A list of users that have to be notified
  24. * @var array
  25. */
  26. protected $usersToNotify = [];
  27. /**
  28. * Create a new command instance.
  29. *
  30. * @return void
  31. */
  32. public function __construct()
  33. {
  34. parent::__construct();
  35. }
  36. /**
  37. * Execute the console command.
  38. *
  39. * @return string
  40. */
  41. public function handle()
  42. {
  43. Server::whereNull('suspended')->chunk(10, function ($servers) {
  44. /** @var Server $server */
  45. foreach ($servers as $server) {
  46. /** @var Product $product */
  47. $product = $server->product;
  48. /** @var User $user */
  49. $user = $server->user;
  50. #charge credits / suspend server
  51. if ($user->credits >= $product->getHourlyPrice()) {
  52. $this->line("<fg=blue>{$user->name}</> Current credits: <fg=green>{$user->credits}</> Credits to be removed: <fg=red>{$product->getHourlyPrice()}</>");
  53. $user->decrement('credits', $product->getHourlyPrice());
  54. } else {
  55. try {
  56. #suspend server
  57. $this->line("<fg=yellow>{$server->name}</> from user: <fg=blue>{$user->name}</> has been <fg=red>suspended!</>");
  58. $server->suspend();
  59. #add user to notify list
  60. if (!in_array($user, $this->usersToNotify)) {
  61. array_push($this->usersToNotify, $user);
  62. }
  63. } catch (\Exception $exception) {
  64. $this->error($exception->getMessage());
  65. }
  66. }
  67. }
  68. });
  69. return $this->notifyUsers();
  70. }
  71. /**
  72. * @return bool
  73. */
  74. public function notifyUsers()
  75. {
  76. if (!empty($this->usersToNotify)) {
  77. /** @var User $user */
  78. foreach ($this->usersToNotify as $user) {
  79. $this->line("<fg=yellow>Notified user:</> <fg=blue>{$user->name}</>");
  80. $user->notify(new ServersSuspendedNotification());
  81. }
  82. }
  83. #reset array
  84. $this->usersToNotify = array();
  85. return true;
  86. }
  87. }