ChargeCreditsCommand.php 2.8 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. *
  25. * @var array
  26. */
  27. protected $usersToNotify = [];
  28. /**
  29. * Create a new command instance.
  30. *
  31. * @return void
  32. */
  33. public function __construct()
  34. {
  35. parent::__construct();
  36. }
  37. /**
  38. * Execute the console command.
  39. *
  40. * @return string
  41. */
  42. public function handle()
  43. {
  44. Server::whereNull('suspended')->chunk(10, function ($servers) {
  45. /** @var Server $server */
  46. foreach ($servers as $server) {
  47. /** @var Product $product */
  48. $product = $server->product;
  49. /** @var User $user */
  50. $user = $server->user;
  51. //charge credits / suspend server
  52. if ($user->credits >= $product->getHourlyPrice()) {
  53. $this->line("<fg=blue>{$user->name}</> Current credits: <fg=green>{$user->credits}</> Credits to be removed: <fg=red>{$product->getHourlyPrice()}</>");
  54. $user->decrement('credits', $product->getHourlyPrice());
  55. } else {
  56. try {
  57. //suspend server
  58. $this->line("<fg=yellow>{$server->name}</> from user: <fg=blue>{$user->name}</> has been <fg=red>suspended!</>");
  59. $server->suspend();
  60. //add user to notify list
  61. if (!in_array($user, $this->usersToNotify)) {
  62. array_push($this->usersToNotify, $user);
  63. }
  64. } catch (\Exception $exception) {
  65. $this->error($exception->getMessage());
  66. }
  67. }
  68. }
  69. });
  70. return $this->notifyUsers();
  71. }
  72. /**
  73. * @return bool
  74. */
  75. public function notifyUsers()
  76. {
  77. if (!empty($this->usersToNotify)) {
  78. /** @var User $user */
  79. foreach ($this->usersToNotify as $user) {
  80. $this->line("<fg=yellow>Notified user:</> <fg=blue>{$user->name}</>");
  81. $user->notify(new ServersSuspendedNotification());
  82. }
  83. }
  84. //reset array
  85. $this->usersToNotify = [];
  86. return true;
  87. }
  88. }