Merge branch 'dev'

This commit is contained in:
Nabeel Shahzad
2018-04-23 11:45:22 -05:00
1320 changed files with 98470 additions and 86802 deletions
+1
View File
@@ -2,6 +2,7 @@
Options -Indexes Options -Indexes
RewriteEngine On RewriteEngine On
RewriteBase /
# Handle Authorization Header # Handle Authorization Header
RewriteCond %{HTTP:Authorization} ^(.*) RewriteCond %{HTTP:Authorization} ^(.*)
+1 -1
View File
@@ -15,7 +15,7 @@ services:
before_script: before_script:
- cp .travis/env.travis.php env.php - cp .travis/env.travis.php env.php
- composer install --no-interaction --verbose - composer install --dev --no-interaction --verbose
script: script:
- php artisan database:create --reset - php artisan database:create --reset
+27
View File
@@ -0,0 +1,27 @@
<code_scheme name="PHPVMS" version="173">
<option name="RIGHT_MARGIN" value="100" />
<PHPCodeStyleSettings>
<option name="ALIGN_KEY_VALUE_PAIRS" value="true" />
<option name="LOWER_CASE_BOOLEAN_CONST" value="true" />
<option name="LOWER_CASE_NULL_CONST" value="true" />
<option name="ALIGN_CLASS_CONSTANTS" value="true" />
<option name="FORCE_SHORT_DECLARATION_ARRAY_STYLE" value="true" />
</PHPCodeStyleSettings>
<XML>
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
</XML>
<codeStyleSettings language="JAVA">
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JSON">
<indentOptions>
<option name="INDENT_SIZE" value="4" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="PHP">
<option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
<option name="ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION" value="true" />
</codeStyleSettings>
</code_scheme>
+18 -1
View File
@@ -30,18 +30,23 @@ if [ "$TRAVIS" = "true" ]; then
make clean make clean
# Clean up the dependencies to only remove the dev packages
#rm -rf vendor
#composer install --no-interaction --no-dev
rm -rf env.php config.php rm -rf env.php config.php
find ./vendor -type d -name ".git" -print0 | xargs rm -rf find ./vendor -type d -name ".git" -print0 | xargs rm -rf
find . -type d -name "sass-cache" -print0 | xargs rm -rf find . -type d -name "sass-cache" -print0 | xargs rm -rf
# clear any app specific stuff that might have been loaded in # clear any app specific stuff that might have been loaded in
find storage/app/public -mindepth 1 -not -name '.gitignore' -print0 -exec rm -rf {} + find storage/app/public -mindepth 1 -not -name '.gitignore' -print0 -exec rm -rf {} +
find storage/app -mindepth 1 -not -name '.gitignore' -not -name public -print0 -exec rm -rf {} + find storage/app -mindepth 1 -not -name '.gitignore' -not -name public -not -name import -print0 -exec rm -rf {} +
# Remove any development files # Remove any development files
rm -rf .sass-cache rm -rf .sass-cache
rm -rf .idea phpvms.iml .travis .dpl rm -rf .idea phpvms.iml .travis .dpl
rm -rf .phpstorm.meta.php _ide_helper.php phpunit.xml Procfile rm -rf .phpstorm.meta.php _ide_helper.php phpunit.xml Procfile
rm -f phpstan.neon
# remove large sized files # remove large sized files
rm -rf .git rm -rf .git
@@ -63,5 +68,17 @@ if [ "$TRAVIS" = "true" ]; then
mv "/tmp/$TAR_NAME" "/tmp/$TAR_NAME.sha256" . mv "/tmp/$TAR_NAME" "/tmp/$TAR_NAME.sha256" .
artifacts upload --target-paths "/" $TAR_NAME $TRAVIS_BUILD_DIR/VERSION $TAR_NAME.sha256 artifacts upload --target-paths "/" $TAR_NAME $TRAVIS_BUILD_DIR/VERSION $TAR_NAME.sha256
# Upload the version for a tagged release. Move to a version file in different
# tags. Within phpVMS, we have an option of which version to track in the admin
if test "$TRAVIS_TAG"; then
echo "uploading release version file"
cp "$TRAVIS_BUILD_DIR/VERSION" release_version
artifacts upload --target-paths "/" release_version
else
echo "uploading ${TRAVIS_BRANCH}_version file"
cp $TRAVIS_BUILD_DIR/VERSION ${TRAVIS_BRANCH}_version
artifacts upload --target-paths "/" ${TRAVIS_BRANCH}_version
fi
curl -X POST --data "{\"content\": \"A new build is available at http://downloads.phpvms.net/$TAR_NAME ($VERSION)\"}" -H "Content-Type: application/json" $DISCORD_WEBHOOK_URL curl -X POST --data "{\"content\": \"A new build is available at http://downloads.phpvms.net/$TAR_NAME ($VERSION)\"}" -H "Content-Type: application/json" $DISCORD_WEBHOOK_URL
fi fi
+23
View File
@@ -1,3 +1,26 @@
## Alpha 3
!! Please do a complete reinstall, with a new database
- Finances! The finance portions have been implemented, you can [read about them here](http://docs.phpvms.net/concepts/finances)
- Awards! Added the award plugin system. [see docs](http://docs.phpvms.net/customizing/awards)
- Import/Export in admin panel for aircraft, airports, expenses, fares, flights and subfleets
- Changed theme system to using [laravel-theme](https://github.com/igaster/laravel-theme), there are changes to making theming much simpler with much more flexibility.
- Added cron task for background tasks
- Expanded on flight types to match IATA SIMM format
- Added subfleet `cost_block_hour`
- Fixed several security vulnerabilities (thanks magicflyer!)
- Fuel units changed to lbs/kgs [#193](https://github.com/nabeelio/phpvms/issues/193)
- Airports can be restricted to only hubs on registration/user profile
- Cleaned up a lot unused icons and files [#195](https://github.com/nabeelio/phpvms/issues/195)
- Rank restrictions for PIREPs are respected [#170](https://github.com/nabeelio/phpvms/issues/170)
- API: Added the ability to get/update/delete user bids [#172](https://github.com/nabeelio/phpvms/issues/172)
- API: Added `block_time` parameter for PIREP prefile/update/file calls
- API: Added `block_on_time` and `block_off_time` for PIREP prefile/update/file calls
- Artisan: Added a `phpvms:csv-import [table] [file]` to import from CSV
- Artisan: Added a `phpvms:yaml-export [tables]` to export tables to YAML files which can be re-imported using `phpvms:yaml-import`
- Numerous bug fixes
## Alpha 2 (2018-02-23, v7.0.0-alpha2) ## Alpha 2 (2018-02-23, v7.0.0-alpha2)
!! Please do a full reinstall, with recreating the database !! Please do a full reinstall, with recreating the database
+8 -5
View File
@@ -36,8 +36,7 @@ build:
# This is to build all the stylesheets, etc # This is to build all the stylesheets, etc
.PHONY: build-assets .PHONY: build-assets
build-assets: build-assets:
npm update yarn run dev
npm run dev
.PHONY: install .PHONY: install
install: build install: build
@@ -53,7 +52,7 @@ update: build
@echo "Done!" @echo "Done!"
.PHONY: reset .PHONY: reset
reset: clean reset: cleanapp/Models/Traits/JournalTrait.php
@php $(COMPOSER) dump-autoload @php $(COMPOSER) dump-autoload
@make reload-db @make reload-db
@@ -61,8 +60,8 @@ reset: clean
reload-db: reload-db:
@php artisan database:create --reset @php artisan database:create --reset
@php artisan migrate:fresh --seed @php artisan migrate:fresh --seed
@php artisan phpvms:import app/Database/seeds/sample.yml @php artisan phpvms:yaml-import app/Database/seeds/sample.yml
@php artisan phpvms:import app/Database/seeds/acars.yml @php artisan phpvms:yaml-import app/Database/seeds/acars.yml
#php artisan phpvms:navdata #php artisan phpvms:navdata
.PHONY: tests .PHONY: tests
@@ -73,6 +72,10 @@ test:
#php artisan database:create --reset #php artisan database:create --reset
vendor/bin/phpunit --debug --verbose vendor/bin/phpunit --debug --verbose
.PHONY:
phpstan:
vendor/bin/phpstan analyse -c phpstan.neon -v --level 2 app
.PHONY: replay-acars .PHONY: replay-acars
replay-acars: replay-acars:
#@php artisan phpvms:replay AAL10,AAL3113,BAW172,DAL988,FIN6,MSR986 --manual #@php artisan phpvms:replay AAL10,AAL3113,BAW172,DAL988,FIN6,MSR986 --manual
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Awards;
use App\Interfaces\Award;
/**
* Simple example of an awards class, where you can apply an award when a user
* has 100 flights. All award classes need to extend the AwardInterface
* @package App\Awards
*/
class PilotFlightAwards extends Award
{
/**
* Set the name of this award class to make it easier to see when
* assigning to a specific award
* @var string
*/
public $name = 'Pilot Flights';
/**
* The description to show under the parameters field, so the admin knows
* what the parameter actually controls. You can leave this blank if there
* isn't a parameter.
* @var string
*/
public $param_description = 'The number of flights at which to give this award';
/**
* If the user has over N flights, then we can give them this award. This method
* only needs to return a true or false of whether it should be awarded or not.
*
* If no parameter is passed in, just default it to 100. You should check if there
* is a parameter or not. You can call it whatever you want, since that would make
* sense with the $param_description.
* @param int|null $number_of_flights The parameters passed in from the UI
* @return bool
*/
public function check($number_of_flights = null): bool
{
if (!$number_of_flights) {
$number_of_flights = 100;
}
return $this->user->flights >= $number_of_flights;
}
}
+1 -2
View File
@@ -23,8 +23,7 @@ class LoadConfiguration extends \Illuminate\Foundation\Bootstrap\LoadConfigurati
* Load the configuration items from all of the files. * Load the configuration items from all of the files.
* *
* @param \Illuminate\Contracts\Foundation\Application $app * @param \Illuminate\Contracts\Foundation\Application $app
* @param \Illuminate\Contracts\Config\Repository $repository * @param \Illuminate\Contracts\Config\Repository $repository
* @return void
* @throws \Exception * @throws \Exception
*/ */
protected function loadConfigurationFiles(Application $app, RepositoryContract $repository) protected function loadConfigurationFiles(Application $app, RepositoryContract $repository)
-65
View File
@@ -1,65 +0,0 @@
<?php
namespace App\Console;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
class BaseCommand extends Command
{
/**
* Streaming file read
* @param $filename
* @return \Generator
*/
public function readFile($filename)
{
$fp = fopen($filename, 'rb');
while (($line = fgets($fp)) !== false) {
$line = rtrim($line, "\r\n");
if ($line[0] === ';') {
continue;
}
yield $line;
}
fclose($fp);
}
/**
* @param $cmd
* @param bool $return
* @return string
*/
public function runCommand($cmd, $return=false, $verbose=true)
{
if (\is_array($cmd)) {
$cmd = join(' ', $cmd);
}
if($verbose) {
$this->info('Running "' . $cmd . '"');
}
$val = '';
$process = new Process($cmd);
$process->run(function ($type, $buffer) use ($return, $val) {
if ($return) {
$val .= $buffer;
} else {
echo $buffer;
}
/*if (Process::ERR === $type) {
echo $buffer;
} else {
echo $buffer;
}*/
});
return $val;
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
namespace App\Console;
use Log;
use Symfony\Component\Process\Process;
/**
* Class BaseCommand
* @package App\Console
*/
abstract class Command extends \Illuminate\Console\Command
{
/**
* @return mixed
*/
abstract public function handle();
/**
* Splice the logger and replace the active handlers with
* the handlers from the "cron" stack in config/logging.php
*
* Close out any of the existing handlers so we don't leave
* file descriptors leaking around
*
* @param string $channel_name Channel name to grab the handlers from
*/
public function redirectLoggingToStdout($channel_name): void
{
$logger = app(\Illuminate\Log\Logger::class);
// Close the existing loggers
try {
$handlers = $logger->getHandlers();
foreach ($handlers as $handler) {
$handler->close();
}
} catch (\Exception $e) {
$this->error('Error closing handlers: '.$e->getMessage());
}
// Open the handlers for the channel name,
// and then set them to the main logger
try {
$logger->setHandlers(
Log::channel($channel_name)->getHandlers()
);
} catch (\Exception $e) {
$this->error('Couldn\'t splice the logger: '.$e->getMessage());
}
}
/**
* Streaming file reader
* @param $filename
* @return \Generator
*/
public function readFile($filename): ?\Generator
{
$fp = fopen($filename, 'rb');
while (($line = fgets($fp)) !== false) {
$line = rtrim($line, "\r\n");
if ($line[0] === ';') {
continue;
}
yield $line;
}
fclose($fp);
}
/**
* @param $cmd
* @param bool $return
* @return string
* @throws \Symfony\Component\Process\Exception\RuntimeException
* @throws \Symfony\Component\Process\Exception\LogicException
*/
public function runCommand($cmd, $return = false, $verbose = true): string
{
if (\is_array($cmd)) {
$cmd = join(' ', $cmd);
}
if ($verbose) {
$this->info('Running "'.$cmd.'"');
}
$val = '';
$process = new Process($cmd);
$process->run(function ($type, $buffer) use ($return, &$val) {
if ($return) {
$val .= $buffer;
} else {
echo $buffer;
}
});
return $val;
}
}
+46 -41
View File
@@ -2,12 +2,16 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Console\BaseCommand; use App\Console\Command;
use App\Facades\Utils; use App\Facades\Utils;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
class AcarsReplay extends BaseCommand /**
* Class AcarsReplay
* @package App\Console\Commands
*/
class AcarsReplay extends Command
{ {
protected $signature = 'phpvms:replay {files} {--manual} {--write-all} {--no-submit}'; protected $signature = 'phpvms:replay {files} {--manual} {--write-all} {--no-submit}';
protected $description = 'Replay an ACARS file'; protected $description = 'Replay an ACARS file';
@@ -35,7 +39,6 @@ class AcarsReplay extends BaseCommand
*/ */
protected $httpClient; protected $httpClient;
/** /**
* Return an instance of an HTTP client all ready to post * Return an instance of an HTTP client all ready to post
*/ */
@@ -45,46 +48,43 @@ class AcarsReplay extends BaseCommand
$this->httpClient = new Client([ $this->httpClient = new Client([
'base_uri' => config('app.url'), 'base_uri' => config('app.url'),
'headers' => [ 'headers' => [
'Authorization' => $this->apiKey, 'Authorization' => $this->apiKey,
] ]
]); ]);
} }
/*protected function getArguments()
{
return [
['--files', InputOption::VALUE_OPTIONAL]
];
}*/
/** /**
* Make a request to start a PIREP * Make a request to start a PIREP
* @param \stdClass $flight * @param \stdClass $flight
* @return string * @return string
* @throws \RuntimeException
*/ */
protected function startPirep($flight): string protected function startPirep($flight): string
{ {
# convert the planned flight time to be completely in minutes # convert the planned flight time to be completely in minutes
$pft = Utils::hoursToMinutes($flight->planned_hrsenroute, $pft = Utils::hoursToMinutes(
$flight->planned_minenroute); $flight->planned_hrsenroute,
$flight->planned_minenroute
);
$flight_number = substr($flight->callsign, 3); $flight_number = substr($flight->callsign, 3);
$response = $this->httpClient->post('/api/pireps/prefile', [ $response = $this->httpClient->post('/api/pireps/prefile', [
'json' => [ 'json' => [
'airline_id' => 1, 'airline_id' => 1,
'flight_number' => $flight_number, 'flight_number' => $flight_number,
'aircraft_id' => 1, 'aircraft_id' => 1,
'dpt_airport_id' => $flight->planned_depairport, 'dpt_airport_id' => $flight->planned_depairport,
'arr_airport_id' => $flight->planned_destairport, 'arr_airport_id' => $flight->planned_destairport,
'level' => $flight->planned_altitude, 'level' => $flight->planned_altitude,
'planned_flight_time' => $pft, 'planned_flight_time' => $pft,
'route' => $flight->planned_route, 'route' => $flight->planned_route,
] ]
]); ]);
$body = \json_decode($response->getBody()->getContents()); $body = \json_decode($response->getBody()->getContents());
return $body->id; return $body->id;
} }
@@ -92,14 +92,16 @@ class AcarsReplay extends BaseCommand
* Mark the PIREP as filed * Mark the PIREP as filed
* @param $pirep_id * @param $pirep_id
* @return mixed * @return mixed
* @throws \RuntimeException
*/ */
protected function filePirep($pirep_id) protected function filePirep($pirep_id)
{ {
$response = $this->httpClient->post('/api/pireps/'.$pirep_id.'/file', [ $response = $this->httpClient->post('/api/pireps/'.$pirep_id.'/file', [
'json'=> [] 'json' => []
]); ]);
$body = \json_decode($response->getBody()->getContents()); $body = \json_decode($response->getBody()->getContents());
return $body; return $body;
} }
@@ -107,18 +109,19 @@ class AcarsReplay extends BaseCommand
* @param $pirep_id * @param $pirep_id
* @param $data * @param $data
* @return array * @return array
* @throws \RuntimeException
*/ */
protected function postUpdate($pirep_id, $data) protected function postUpdate($pirep_id, $data)
{ {
$uri = '/api/pireps/' . $pirep_id . '/acars/position'; $uri = '/api/pireps/'.$pirep_id.'/acars/position';
$position = [ $position = [
'log' => '', 'log' => '',
'lat' => $data->latitude, 'lat' => $data->latitude,
'lon' => $data->longitude, 'lon' => $data->longitude,
'heading' => $data->heading, 'heading' => $data->heading,
'altitude' => $data->altitude, 'altitude' => $data->altitude,
'gs' => $data->groundspeed, 'gs' => $data->groundspeed,
'transponder' => $data->transponder, 'transponder' => $data->transponder,
]; ];
@@ -129,13 +132,14 @@ class AcarsReplay extends BaseCommand
]; ];
$this->info("Update: $data->callsign, $position[lat] x $position[lon] \t\t" $this->info("Update: $data->callsign, $position[lat] x $position[lon] \t\t"
. "hdg: $position[heading]\t\talt: $position[altitude]\t\tgs: $position[gs]"); ."hdg: $position[heading]\t\talt: $position[altitude]\t\tgs: $position[gs]");
$response = $this->httpClient->post($uri, [ $response = $this->httpClient->post($uri, [
'json' => $upd 'json' => $upd
]); ]);
$body = \json_decode($response->getBody()->getContents()); $body = \json_decode($response->getBody()->getContents());
return [ return [
$data->callsign, $data->callsign,
$position['lat'], $position['lat'],
@@ -149,22 +153,24 @@ class AcarsReplay extends BaseCommand
/** /**
* Parse this file and run the updates * Parse this file and run the updates
* @param array $files * @param array $files
* @throws \RuntimeException
*/ */
protected function updatesFromFile(array $files) protected function updatesFromFile(array $files)
{ {
/** /**
* @var $flights Collection * @var $flights Collection
*/ */
$flights = collect($files)->transform(function ($f) $flights = collect($files)->transform(function ($f) {
{ $file = storage_path('/replay/'.$f.'.json');
$file = storage_path('/replay/' . $f . '.json');
if (file_exists($file)) { if (file_exists($file)) {
$this->info('Loading ' . $file); $this->info('Loading '.$file);
$contents = file_get_contents($file); $contents = file_get_contents($file);
$contents = \json_decode($contents); $contents = \json_decode($contents);
return collect($contents->updates); return collect($contents->updates);
} else { } else {
$this->error($file . ' not found, skipping'); $this->error($file.' not found, skipping');
return false; return false;
} }
}) })
@@ -178,12 +184,11 @@ class AcarsReplay extends BaseCommand
/** /**
* File the initial pirep to get a "preflight" status * File the initial pirep to get a "preflight" status
*/ */
$flights->each(function ($updates, $idx) $flights->each(function ($updates, $idx) {
{
$update = $updates->first(); $update = $updates->first();
$pirep_id = $this->startPirep($update); $pirep_id = $this->startPirep($update);
$this->pirepList[$update->callsign] = $pirep_id; $this->pirepList[$update->callsign] = $pirep_id;
$this->info('Prefiled ' . $update->callsign . ', ID: ' . $pirep_id); $this->info('Prefiled '.$update->callsign.', ID: '.$pirep_id);
}); });
/** /**
@@ -202,14 +207,14 @@ class AcarsReplay extends BaseCommand
$this->postUpdate($pirep_id, $update); $this->postUpdate($pirep_id, $update);
# we're done and don't put the "no-submit" option # we're done and don't put the "no-submit" option
if($updates->count() === 0 && !$this->option('no-submit')) { if ($updates->count() === 0 && !$this->option('no-submit')) {
$this->filePirep($pirep_id); $this->filePirep($pirep_id);
} }
})->filter(function ($updates, $idx) { })->filter(function ($updates, $idx) {
return $updates->count() > 0; return $updates->count() > 0;
}); });
if(!$this->option('write-all')) { if (!$this->option('write-all')) {
if (!$this->option('manual')) { if (!$this->option('manual')) {
sleep($this->sleepTime); sleep($this->sleepTime);
} else { } else {
@@ -221,8 +226,8 @@ class AcarsReplay extends BaseCommand
/** /**
* Execute the console command. * Execute the console command.
*
* @return mixed * @return mixed
* @throws \RuntimeException
*/ */
public function handle() public function handle()
{ {
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Console\Commands;
use App\Console\Command;
use Artisan;
/**
* Class ComposerCommand
* @package App\Console\Commands
*/
class ComposerCommand extends Command
{
protected $signature = 'phpvms:composer {cmd}';
protected $description = 'Composer related tasks';
/**
* Run composer update related commands
*/
public function handle()
{
switch(trim($this->argument('cmd')))
{
case 'post-update':
$this->postUpdate();
break;
default:
$this->error('Command exists');
}
}
/**
* Any composer post update tasks
*/
protected function postUpdate(): void
{
if (config('app.env') === 'dev') {
if (class_exists(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class)) {
Artisan::call('ide-helper:generate');
Artisan::call('ide-helper:meta');
}
}
}
}
+26 -21
View File
@@ -2,15 +2,22 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Console\BaseCommand; use App\Console\Command;
use Log; use Log;
class CreateDatabase extends BaseCommand /**
* Class CreateDatabase
* @package App\Console\Commands
*/
class CreateDatabase extends Command
{ {
protected $signature = 'database:create {--reset} {--conn=?}'; protected $signature = 'database:create {--reset} {--conn=?}';
protected $description = 'Create a database'; protected $description = 'Create a database';
protected $os; protected $os;
/**
* CreateDatabase constructor.
*/
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
@@ -24,21 +31,22 @@ class CreateDatabase extends BaseCommand
*/ */
protected function create_mysql($dbkey) protected function create_mysql($dbkey)
{ {
$host = config($dbkey . 'host'); $host = config($dbkey.'host');
$port = config($dbkey . 'port'); $port = config($dbkey.'port');
$name = config($dbkey . 'database'); $name = config($dbkey.'database');
$user = config($dbkey . 'username'); $user = config($dbkey.'username');
$pass = config($dbkey . 'password'); $pass = config($dbkey.'password');
$dbSvc = new \App\Console\Services\Database(); $dbSvc = new \App\Console\Services\Database();
$dsn = $dbSvc->createDsn($host, $port); $dsn = $dbSvc->createDsn($host, $port);
Log::info('Connection string: ' . $dsn); Log::info('Connection string: '.$dsn);
try { try {
$conn = $dbSvc->createPDO($dsn, $user, $pass); $conn = $dbSvc->createPDO($dsn, $user, $pass);
} catch (\PDOException $e) { } catch (\PDOException $e) {
Log::error($e); Log::error($e);
return false; return false;
} }
@@ -59,6 +67,7 @@ class CreateDatabase extends BaseCommand
$conn->exec($sql); $conn->exec($sql);
} catch (\PDOException $e) { } catch (\PDOException $e) {
Log::error($e); Log::error($e);
return false; return false;
} }
} }
@@ -75,14 +84,14 @@ class CreateDatabase extends BaseCommand
} }
if ($this->option('reset') === true) { if ($this->option('reset') === true) {
$cmd = ['rm', '-rf', config($dbkey . 'database')]; $cmd = ['rm', '-rf', config($dbkey.'database')];
$this->runCommand($cmd); $this->runCommand($cmd);
} }
if (!file_exists(config($dbkey . 'database'))) { if (!file_exists(config($dbkey.'database'))) {
$cmd = [ $cmd = [
$exec, $exec,
config($dbkey . 'database'), config($dbkey.'database'),
'""', '""',
]; ];
@@ -108,21 +117,17 @@ class CreateDatabase extends BaseCommand
} }
}*/ }*/
$this->info('Using connection "' . config('database.default') . '"'); $this->info('Using connection "'.config('database.default').'"');
$conn = config('database.default'); $conn = config('database.default');
$dbkey = 'database.connections.' . $conn . '.'; $dbkey = 'database.connections.'.$conn.'.';
if (config($dbkey . 'driver') === 'mysql') { if (config($dbkey.'driver') === 'mysql') {
$this->create_mysql($dbkey); $this->create_mysql($dbkey);
} } elseif (config($dbkey.'driver') === 'sqlite') {
elseif (config($dbkey . 'driver') === 'sqlite') {
$this->create_sqlite($dbkey); $this->create_sqlite($dbkey);
} } // TODO: Eventually
elseif (config($dbkey.'driver') === 'postgres') {
// TODO: Eventually
elseif (config($dbkey . 'driver') === 'postgres') {
$this->create_postgres($dbkey); $this->create_postgres($dbkey);
} }
} }
+36 -12
View File
@@ -2,16 +2,22 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Console\BaseCommand; use App\Console\Command;
use App\Models\Acars; use App\Models\Acars;
use App\Models\Airline; use App\Models\Airline;
use App\Models\Pirep; use App\Models\Pirep;
use App\Models\User; use App\Models\User;
use App\Services\AwardService;
use Artisan;
use DB; use DB;
use PDO; use PDO;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
class DevCommands extends BaseCommand /**
* Class DevCommands
* @package App\Console\Commands
*/
class DevCommands extends Command
{ {
protected $signature = 'phpvms {cmd} {param?}'; protected $signature = 'phpvms {cmd} {param?}';
protected $description = 'Developer commands'; protected $description = 'Developer commands';
@@ -29,14 +35,15 @@ class DevCommands extends BaseCommand
} }
$commands = [ $commands = [
'clear-acars' => 'clearAcars', 'list-awards' => 'listAwardClasses',
'clear-users' => 'clearUsers', 'clear-acars' => 'clearAcars',
'clear-users' => 'clearUsers',
'compile-assets' => 'compileAssets', 'compile-assets' => 'compileAssets',
'db-attrs' => 'dbAttrs', 'db-attrs' => 'dbAttrs',
'xml-to-yaml' => 'xmlToYaml', 'xml-to-yaml' => 'xmlToYaml',
]; ];
if(!array_key_exists($command, $commands)) { if (!array_key_exists($command, $commands)) {
$this->error('Command not found!'); $this->error('Command not found!');
exit(); exit();
} }
@@ -44,12 +51,29 @@ class DevCommands extends BaseCommand
$this->{$commands[$command]}(); $this->{$commands[$command]}();
} }
/**
* List all award classes
*/
protected function listAwardClasses()
{
$awardSvc = app(AwardService::class);
$awards = $awardSvc->findAllAwardClasses();
$headers = ['Award Name', 'Class'];
$formatted_awards = [];
foreach ($awards as $award) {
$formatted_awards[] = [$award->name, \get_class($award)];
}
$this->table($headers, $formatted_awards);
}
/** /**
* Delete all the data from the ACARS and PIREP tables * Delete all the data from the ACARS and PIREP tables
*/ */
protected function clearAcars() protected function clearAcars()
{ {
if(config('database.default') === 'mysql') { if (config('database.default') === 'mysql') {
DB::statement('SET foreign_key_checks=0'); DB::statement('SET foreign_key_checks=0');
} }
@@ -103,7 +127,7 @@ class DevCommands extends BaseCommand
$server_version = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION); $server_version = $pdo->getAttribute(PDO::ATTR_SERVER_VERSION);
$emulate_prepares = version_compare($server_version, $emulate_prepares_below_version, '<'); $emulate_prepares = version_compare($server_version, $emulate_prepares_below_version, '<');
$this->info('Server Version: '. $server_version); $this->info('Server Version: '.$server_version);
$this->info('Emulate Prepares: '.$emulate_prepares); $this->info('Emulate Prepares: '.$emulate_prepares);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $emulate_prepares); $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $emulate_prepares);
@@ -115,7 +139,7 @@ class DevCommands extends BaseCommand
protected function xmlToYaml() protected function xmlToYaml()
{ {
$file = $this->argument('param'); $file = $this->argument('param');
$this->info('Reading '. $file); $this->info('Reading '.$file);
$xml_str = file_get_contents($file); $xml_str = file_get_contents($file);
$xml = new \SimpleXMLElement($xml_str); $xml = new \SimpleXMLElement($xml_str);
@@ -129,7 +153,7 @@ class DevCommands extends BaseCommand
foreach ($xml->database->table_data->row as $row) { foreach ($xml->database->table_data->row as $row) {
$yaml_row = []; $yaml_row = [];
foreach($row->field as $field) { foreach ($row->field as $field) {
$fname = (string) $field['name']; $fname = (string) $field['name'];
$fvalue = (string) $field; $fvalue = (string) $field;
@@ -144,6 +168,6 @@ class DevCommands extends BaseCommand
$file_name = $table_name.'.yml'; $file_name = $table_name.'.yml';
file_put_contents(storage_path($file_name), Yaml::dump($yaml, 4, 2)); file_put_contents(storage_path($file_name), Yaml::dump($yaml, 4, 2));
$this->info('Writing yaml to storage: '. $file_name); $this->info('Writing yaml to storage: '.$file_name);
} }
} }
+8 -8
View File
@@ -2,14 +2,14 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Console\BaseCommand; use App\Console\Command;
use Modules\Installer\Services\ConfigService; use Modules\Installer\Services\ConfigService;
/** /**
* Create a fresh development install * Create a fresh development install
* @package App\Console\Commands * @package App\Console\Commands
*/ */
class DevInstall extends BaseCommand class DevInstall extends Command
{ {
protected $signature = 'phpvms:dev-install {--reset-db}'; protected $signature = 'phpvms:dev-install {--reset-db}';
protected $description = 'Run a developer install and run the sample migration'; protected $description = 'Run a developer install and run the sample migration';
@@ -20,7 +20,7 @@ class DevInstall extends BaseCommand
*/ */
public function handle() public function handle()
{ {
if(!$this->option('reset-db')) { if (!$this->option('reset-db')) {
$this->rewriteConfigs(); $this->rewriteConfigs();
} }
@@ -69,26 +69,26 @@ class DevInstall extends BaseCommand
# Remove the old files # Remove the old files
$config_file = base_path('config.php'); $config_file = base_path('config.php');
if(file_exists($config_file)) { if (file_exists($config_file)) {
unlink($config_file); unlink($config_file);
} }
$env_file = base_path('env.php'); $env_file = base_path('env.php');
if(file_exists($env_file)) { if (file_exists($env_file)) {
unlink($env_file); unlink($env_file);
} }
$this->info('Removing the sqlite db'); $this->info('Removing the sqlite db');
$db_file = storage_path('db.sqlite'); $db_file = storage_path('db.sqlite');
if(file_exists($db_file)) { if (file_exists($db_file)) {
unlink($db_file); unlink($db_file);
} }
$this->info('Regenerating the config files'); $this->info('Regenerating the config files');
$cfgSvc->createConfigFiles([ $cfgSvc->createConfigFiles([
'APP_ENV' => 'dev', 'APP_ENV' => 'dev',
'SITE_NAME' => 'phpvms test', 'SITE_NAME' => 'phpvms test',
'DB_CONN' => 'sqlite', 'DB_CONN' => 'sqlite',
]); ]);
$this->info('Config files generated!'); $this->info('Config files generated!');
+59
View File
@@ -0,0 +1,59 @@
<?php
/**
*
*/
namespace App\Console\Commands;
use App\Console\Command;
use App\Services\ImportService;
/**
* Class ImportCsv
* @package App\Console\Commands
*/
class ImportCsv extends Command
{
protected $signature = 'phpvms:csv-import {type} {file}';
protected $description = 'Import from a CSV file';
private $importer;
/**
* Import constructor.
* @param ImportService $importer
*/
public function __construct(ImportService $importer)
{
parent::__construct();
$this->importer = $importer;
}
/**
* @return mixed|void
* @throws \Illuminate\Validation\ValidationException
*/
public function handle()
{
$type = $this->argument('type');
$file = $this->argument('file');
if (\in_array($type, ['flight', 'flights'])) {
$status = $this->importer->importFlights($file);
} elseif ($type === 'aircraft') {
$status = $this->importer->importAircraft($file);
} elseif (\in_array($type, ['airport', 'airports'])) {
$status = $this->importer->importAirports($file);
} elseif ($type === 'subfleet') {
$status = $this->importer->importSubfleets($file);
}
foreach($status['success'] as $line) {
$this->info($line);
}
foreach ($status['errors'] as $line) {
$this->error($line);
}
}
}
+6 -6
View File
@@ -2,9 +2,9 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Console\BaseCommand; use App\Console\Command;
class ImportFromClassic extends BaseCommand class ImportFromClassic extends Command
{ {
protected $signature = 'phpvms:importer {db_host} {db_name} {db_user} {db_pass?} {table_prefix=phpvms_}'; protected $signature = 'phpvms:importer {db_host} {db_name} {db_user} {db_pass?} {table_prefix=phpvms_}';
protected $description = 'Import from an older version of phpVMS'; protected $description = 'Import from an older version of phpVMS';
@@ -15,10 +15,10 @@ class ImportFromClassic extends BaseCommand
public function handle() public function handle()
{ {
$db_creds = [ $db_creds = [
'host' => $this->argument('db_host'), 'host' => $this->argument('db_host'),
'name' => $this->argument('db_name'), 'name' => $this->argument('db_name'),
'user' => $this->argument('db_user'), 'user' => $this->argument('db_user'),
'pass' => $this->argument('db_pass'), 'pass' => $this->argument('db_pass'),
'table_prefix' => $this->argument('table_prefix') 'table_prefix' => $this->argument('table_prefix')
]; ];
-77
View File
@@ -1,77 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Console\BaseCommand;
class Install extends BaseCommand
{
protected $signature = 'phpvms:install
{--update}
{--airline-name?}
{--airline-code?}';
protected $description = 'Install or update phpVMS';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$this->info('Installing phpVMS...');
$this->setupDatabase();
# Only run these if we're doing an initial install
if(!$this->option('update')) {
$this->writeLocalConfig();
$this->initialData();
}
}
/**
* Setup the database and run the migrations
* Only call the database creation if we're not
* explicitly trying to upgrade
*/
protected function setupDatabase()
{
if(!$this->option('update')) {
$this->call('database:create');
}
$this->info('Running database migrations...');
$this->call('migrate');
# TODO: Call initial seed data, for the groups and other supporting data
}
/**
* Write a local config file
*/
protected function writeLocalConfig()
{
}
/**
* Set an initial airline and admin user/password
*/
protected function initialData()
{
# TODO: Prompt for initial airline info
$airline_name = $this->option('airline-name');
if(!$airline_name) {
$airline_name = $this->ask('Enter your airline name');
}
$airline_code = $this->option('airline-code');
if(!$airline_code) {
$airline_code = $this->ask('Enter your airline code');
}
# TODO: Prompt for admin user/password
}
}
+34 -26
View File
@@ -2,15 +2,33 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Console\BaseCommand; use App\Console\Command;
use App\Models\Enums\NavaidType; use App\Models\Enums\NavaidType;
use App\Models\Navdata; use App\Models\Navdata;
class NavdataImport extends BaseCommand /**
* Class NavdataImport
* @package App\Console\Commands
*/
class NavdataImport extends Command
{ {
protected $signature = 'phpvms:navdata'; protected $signature = 'phpvms:navdata';
protected $description = ''; protected $description = '';
/**
* @return mixed|void
* @throws \League\Geotools\Exception\InvalidArgumentException
*/
public function handle()
{
$this->info('Emptying the current navdata...');
Navdata::query()->truncate();
$this->info('Looking for nav files...');
$this->read_wp_nav_aid();
$this->read_wp_nav_fix();
}
/** /**
* Read and parse in the navaid file * Read and parse in the navaid file
* @throws \League\Geotools\Exception\InvalidArgumentException * @throws \League\Geotools\Exception\InvalidArgumentException
@@ -49,6 +67,7 @@ class NavdataImport extends BaseCommand
$file_path = storage_path('/navdata/WPNAVAID.txt'); $file_path = storage_path('/navdata/WPNAVAID.txt');
if (!file_exists($file_path)) { if (!file_exists($file_path)) {
$this->error('WPNAVAID.txt not found in storage/navdata'); $this->error('WPNAVAID.txt not found in storage/navdata');
return false; return false;
} }
@@ -57,10 +76,9 @@ class NavdataImport extends BaseCommand
$imported = 0; $imported = 0;
foreach($generator as $line) { foreach ($generator as $line) {
$navaid = [ $navaid = [
'id' => trim(substr($line, 24, 4)), // ident column 'id' => trim(substr($line, 24, 4)), // ident column
'name' => trim(substr($line, 0, 24)), 'name' => trim(substr($line, 0, 24)),
'type' => trim(substr($line, 29, 4)), 'type' => trim(substr($line, 29, 4)),
'lat' => trim(substr($line, 33, 9)), 'lat' => trim(substr($line, 33, 9)),
@@ -70,8 +88,7 @@ class NavdataImport extends BaseCommand
]; ];
# Map to the Navaid enum # Map to the Navaid enum
switch($navaid['type']) switch ($navaid['type']) {
{
case 'ILS': case 'ILS':
$navaid['type'] = NavaidType::LOC; $navaid['type'] = NavaidType::LOC;
break; break;
@@ -104,12 +121,12 @@ class NavdataImport extends BaseCommand
], $navaid); ], $navaid);
$imported++; $imported++;
if($imported % 100 === 0) { if ($imported % 100 === 0) {
$this->info('Imported ' . $imported . ' entries...'); $this->info('Imported '.$imported.' entries...');
} }
} }
$this->info('Imported a total of ' . $imported . ' nav aids'); $this->info('Imported a total of '.$imported.' nav aids');
} }
/** /**
@@ -137,8 +154,9 @@ class NavdataImport extends BaseCommand
*/ */
$file_path = storage_path('/navdata/WPNAVFIX.txt'); $file_path = storage_path('/navdata/WPNAVFIX.txt');
if(!file_exists($file_path)) { if (!file_exists($file_path)) {
$this->error('WPNAVFIX.txt not found in storage/navdata'); $this->error('WPNAVFIX.txt not found in storage/navdata');
return false; return false;
} }
@@ -148,11 +166,11 @@ class NavdataImport extends BaseCommand
$imported = 0; $imported = 0;
foreach ($generator as $line) { foreach ($generator as $line) {
$navfix = [ $navfix = [
'id' => trim(substr($line, 0, 4)), // ident column 'id' => trim(substr($line, 0, 4)), // ident column
'name' => trim(substr($line, 24, 6)), 'name' => trim(substr($line, 24, 6)),
'type' => NavaidType::FIX, 'type' => NavaidType::FIX,
'lat' => trim(substr($line, 30, 10)), 'lat' => trim(substr($line, 30, 10)),
'lon' => trim(substr($line, 40, 11)), 'lon' => trim(substr($line, 40, 11)),
]; ];
switch ($navfix['type']) { switch ($navfix['type']) {
@@ -165,20 +183,10 @@ class NavdataImport extends BaseCommand
$imported++; $imported++;
if ($imported % 100 === 0) { if ($imported % 100 === 0) {
$this->info('Imported ' . $imported . ' entries...'); $this->info('Imported '.$imported.' entries...');
} }
} }
$this->info('Imported a total of ' . $imported . ' nav fixes'); $this->info('Imported a total of '.$imported.' nav fixes');
}
public function handle()
{
$this->info('Emptying the current navdata...');
Navdata::query()->truncate();
$this->info('Looking for nav files...');
$this->read_wp_nav_aid();
$this->read_wp_nav_fix();
} }
} }
+11 -8
View File
@@ -2,13 +2,16 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Console\BaseCommand; use App\Console\Command;
use GuzzleHttp\Client; use GuzzleHttp\Client;
class TestApi extends BaseCommand /**
* Class TestApi
* @package App\Console\Commands
*/
class TestApi extends Command
{ {
protected $signature = 'phpvms:test-api {apikey} {url}'; protected $signature = 'phpvms:test-api {apikey} {url}';
protected $httpClient; protected $httpClient;
/** /**
@@ -17,11 +20,11 @@ class TestApi extends BaseCommand
public function handle() public function handle()
{ {
$this->httpClient = new Client([ $this->httpClient = new Client([
'headers' => [ 'headers' => [
'Authorization' => $this->argument('apikey'), 'Authorization' => $this->argument('apikey'),
'Content-type' => 'application/json', 'Content-type' => 'application/json',
'X-API-Key' => $this->argument('apikey'), 'X-API-Key' => $this->argument('apikey'),
] ]
]); ]);
$result = $this->httpClient->get($this->argument('url')); $result = $this->httpClient->get($this->argument('url'));
+20 -17
View File
@@ -2,10 +2,14 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Console\BaseCommand; use App\Console\Command;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
class Version extends BaseCommand /**
* Class Version
* @package App\Console\Commands
*/
class Version extends Command
{ {
protected $signature = 'phpvms:version {--write} {--base-only}'; protected $signature = 'phpvms:version {--write} {--base-only}';
@@ -19,7 +23,6 @@ class Version extends BaseCommand
# prefix with the date in YYMMDD format # prefix with the date in YYMMDD format
$date = date('ymd'); $date = date('ymd');
$version = $date.'-'.$version; $version = $date.'-'.$version;
return $version; return $version;
@@ -34,24 +37,24 @@ class Version extends BaseCommand
$version_file = config_path('version.yml'); $version_file = config_path('version.yml');
$cfg = Yaml::parse(file_get_contents($version_file)); $cfg = Yaml::parse(file_get_contents($version_file));
if($this->option('write')) { # Get the current build id
$version = $this->createVersionNumber($cfg); $build_number = $this->createVersionNumber($cfg);
$cfg['build']['number'] = $version; $cfg['build']['number'] = $build_number;
$c = $cfg['current'];
$version = "v{$c['major']}.{$c['minor']}.{$c['patch']}-{$build_number}";
if ($this->option('write')) {
file_put_contents($version_file, Yaml::dump($cfg, 4, 2)); file_put_contents($version_file, Yaml::dump($cfg, 4, 2));
} }
# Only show the major.minor.patch version # Only show the major.minor.patch version
if($this->option('base-only')) { if ($this->option('base-only')) {
$version = 'v'.$cfg['current']['major'] . '.' $version = 'v'.$cfg['current']['major'].'.'
.$cfg['current']['minor'] . '.' .$cfg['current']['minor'].'.'
.$cfg['current']['patch']; .$cfg['current']['patch'];
print $version;
} else {
$this->call('version:show', [
'--format' => 'compact',
'--suppress-app-name' => true
]);
} }
print $version."\n";
} }
} }
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Console\Commands;
use App\Console\Command;
use App\Services\DatabaseService;
use DB;
use Symfony\Component\Yaml\Yaml;
/**
* Class YamlExport
* @package App\Console\Commands
*/
class YamlExport extends Command
{
protected $signature = 'phpvms:yaml-export {tables*}';
protected $description = 'YAML table export';
/**
* YamlExport constructor.
* @param DatabaseService $dbSvc
*/
public function __construct(DatabaseService $dbSvc)
{
parent::__construct();
}
/**
* Run dev related commands
*/
public function handle()
{
$tables = $this->argument('tables');
if (empty($tables)) {
$this->error('No tables specified');
exit();
}
$export_tables = [];
foreach ($tables as $table) {
$export_tables[$table] = [];
$rows = DB::table($table)->get();
foreach ($rows as $row) {
$export_tables[$table][] = (array) $row;
}
}
$yaml = Yaml::dump($export_tables, 4, 2);
print($yaml);
}
}
+18 -14
View File
@@ -2,16 +2,23 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Console\BaseCommand; use App\Console\Command;
use App\Services\DatabaseService; use App\Services\DatabaseService;
class YamlImport extends BaseCommand /**
* Class YamlImport
* @package App\Console\Commands
*/
class YamlImport extends Command
{ {
protected $signature = 'phpvms:import {files*}'; protected $signature = 'phpvms:yaml-import {files*}';
protected $description = 'Developer commands'; protected $description = 'Developer commands';
protected $dbSvc; protected $dbSvc;
/**
* YamlImport constructor.
* @param DatabaseService $dbSvc
*/
public function __construct(DatabaseService $dbSvc) public function __construct(DatabaseService $dbSvc)
{ {
parent::__construct(); parent::__construct();
@@ -20,31 +27,28 @@ class YamlImport extends BaseCommand
/** /**
* Run dev related commands * Run dev related commands
* @throws \Exception
*/ */
public function handle() public function handle()
{ {
$files = $this->argument('files'); $files = $this->argument('files');
if(empty($files)) { if (empty($files)) {
$this->error('No files to import specified!'); $this->error('No files to import specified!');
exit(); exit();
} }
$ignore_errors = true; $ignore_errors = true;
/*$ignore_errors = $this->option('ignore_errors');
if(!$ignore_errors) {
$ignore_errors = false;
}*/
foreach($files as $file) { foreach ($files as $file) {
if(!file_exists($file)) { if (!file_exists($file)) {
$this->error('File ' . $file .' doesn\'t exist'); $this->error('File '.$file.' doesn\'t exist');
exit; exit;
} }
$this->info('Importing ' . $file); $this->info('Importing '.$file);
$imported = $this->dbSvc->seed_from_yaml_file($file, $ignore_errors); $imported = $this->dbSvc->seed_from_yaml_file($file, $ignore_errors);
foreach($imported as $table => $count) { foreach ($imported as $table => $count) {
$this->info('Imported '.$count.' records from "'.$table.'"'); $this->info('Imported '.$count.' records from "'.$table.'"');
} }
} }
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Console\Cron;
use App\Console\Command;
use App\Events\CronMonthly;
/**
* This just calls the CronMonthly event, so all of the
* listeners, etc can just be called to run those tasks
* @package App\Console\Cron
*/
class Monthly extends Command
{
protected $signature = 'cron:monthly';
protected $description = 'Run the monthly cron tasks';
protected $schedule;
/**
*
*/
public function handle(): void
{
$this->redirectLoggingToStdout('cron');
event(new CronMonthly());
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Console\Cron;
use App\Console\Command;
use App\Events\CronNightly;
/**
* This just calls the CronNightly event, so all of the
* listeners, etc can just be called to run those tasks
* @package App\Console\Cron
*/
class Nightly extends Command
{
protected $signature = 'cron:nightly';
protected $description = 'Run the nightly cron tasks';
protected $schedule;
/**
*
*/
public function handle(): void
{
$this->redirectLoggingToStdout('cron');
event(new CronNightly());
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Console\Cron;
use App\Console\Command;
use App\Events\CronMonthly;
/**
* This just calls the CronWeekly event, so all of the
* listeners, etc can just be called to run those tasks
* @package App\Console\Cron
*/
class Weekly extends Command
{
protected $signature = 'cron:monthly';
protected $description = 'Run the monthly cron tasks';
protected $schedule;
/**
*
*/
public function handle(): void
{
$this->redirectLoggingToStdout('cron');
event(new CronMonthly());
}
}
+17 -16
View File
@@ -2,47 +2,48 @@
namespace App\Console; namespace App\Console;
use App\Console\Cron\Monthly;
use App\Console\Cron\Nightly;
use App\Console\Cron\Weekly;
use Illuminate\Console\Scheduling\Schedule; use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel; use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
/**
* Class Kernel
* @package App\Console
*/
class Kernel extends ConsoleKernel class Kernel extends ConsoleKernel
{ {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [ protected $commands = [
Commands\AcarsReplay::class, /*Commands\AcarsReplay::class,
Commands\CreateDatabase::class, Commands\CreateDatabase::class,
Commands\DevCommands::class, Commands\DevCommands::class,
Commands\YamlImport::class, Commands\YamlImport::class,
Commands\ImportFromClassic::class, Commands\ImportFromClassic::class,
Commands\Install::class,
Commands\NavdataImport::class, Commands\NavdataImport::class,
Commands\TestApi::class, Commands\TestApi::class,*/
]; ];
/** /**
* Define the application's command schedule. * Define the application's command schedule.
* * @param \Illuminate\Console\Scheduling\Schedule $schedule
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void * @return void
*/ */
protected function schedule(Schedule $schedule) protected function schedule(Schedule $schedule): void
{ {
// $schedule->command('inspire') $schedule->command(Nightly::class)->dailyAt('01:00');
// ->hourly(); $schedule->command(Weekly::class)->weeklyOn(0);
$schedule->command(Monthly::class)->monthlyOn(1);
} }
/** /**
* Register the Closure based commands for the application. * Register the Closure based commands for the application.
*
* @return void * @return void
*/ */
protected function commands() protected function commands(): void
{ {
require app_path('Routes/console.php'); require app_path('Routes/console.php');
$this->load(__DIR__ . '/Commands'); $this->load(__DIR__.'/Commands');
$this->load(__DIR__.'/Cron');
} }
} }
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Console;
use Monolog\Handler\StreamHandler;
/**
* Just a simple custom logger that dumps to the console
* @package App\Console
*/
class Logger
{
public function __invoke(array $config)
{
$logger = new \Monolog\Logger('console');
try {
$logger->pushHandler(new StreamHandler('php://stdout'));
} catch (\Exception $e) {
}
return $logger;
}
}
+5 -5
View File
@@ -2,7 +2,7 @@
namespace App\Console\Services; namespace App\Console\Services;
use Doctrine\DBAL\Driver\PDOException; use PDOException;
use PDO; use PDO;
/** /**
@@ -13,16 +13,16 @@ class Database
{ {
/** /**
* Create the base connection DSN, optionally include the DB name * Create the base connection DSN, optionally include the DB name
* @param $host * @param $host
* @param $port * @param $port
* @param null $name * @param null $name
* @return string * @return string
*/ */
public function createDsn($host, $port, $name=null) public function createDsn($host, $port, $name = null)
{ {
$conn = config('database.default'); $conn = config('database.default');
$dsn = "$conn:host=$host;port=$port"; $dsn = "$conn:host=$host;port=$port";
if(filled($name)) { if (filled($name)) {
$dsn .= ';dbname='.$name; $dsn .= ';dbname='.$name;
} }
+105 -111
View File
@@ -15,7 +15,7 @@ use App\Models\Rank;
use App\Models\Subfleet; use App\Models\Subfleet;
use App\Models\User; use App\Models\User;
use Carbon\Carbon; use Carbon\Carbon;
use Doctrine\DBAL\Driver\PDOException; use PDOException;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@@ -56,7 +56,7 @@ class Importer
*/ */
const BATCH_READ_ROWS = 300; const BATCH_READ_ROWS = 300;
const SUBFLEET_NAME = 'Imported Aircraft'; const SUBFLEET_NAME = 'Imported Aircraft';
/** /**
* Importer constructor. * Importer constructor.
@@ -69,11 +69,11 @@ class Importer
# The db credentials # The db credentials
$this->creds = array_merge([ $this->creds = array_merge([
'host' => '127.0.0.1', 'host' => '127.0.0.1',
'port' => 3306, 'port' => 3306,
'name' => '', 'name' => '',
'user' => '', 'user' => '',
'pass' => '', 'pass' => '',
'table_prefix' => 'phpvms_' 'table_prefix' => 'phpvms_'
], $db_creds); ], $db_creds);
} }
@@ -105,13 +105,13 @@ class Importer
*/ */
protected function reconnect() protected function reconnect()
{ {
$dsn = 'mysql:' . implode(';', [ $dsn = 'mysql:'.implode(';', [
'host=' . $this->creds['host'], 'host='.$this->creds['host'],
'port=' . $this->creds['port'], 'port='.$this->creds['port'],
'dbname=' . $this->creds['name'] 'dbname='.$this->creds['name']
]); ]);
$this->info('Connection string: ' . $dsn); $this->info('Connection string: '.$dsn);
try { try {
$this->conn = new PDO($dsn, $this->creds['user'], $this->creds['pass']); $this->conn = new PDO($dsn, $this->creds['user'], $this->creds['pass']);
@@ -127,14 +127,15 @@ class Importer
*/ */
protected function comment($message) protected function comment($message)
{ {
$this->log->writeln('<comment>' . $message . '</comment>'); $this->log->writeln('<comment>'.$message.'</comment>');
} }
/** /**
* @param $message * @param $message
*/ */
protected function error($message) { protected function error($message)
$this->log->writeln('<error>' . $message . '</error>'); {
$this->log->writeln('<error>'.$message.'</error>');
} }
/** /**
@@ -142,10 +143,9 @@ class Importer
*/ */
protected function info($message) protected function info($message)
{ {
if(\is_array($message)) { if (\is_array($message)) {
print_r($message); print_r($message);
} } else {
else {
$this->log->writeln('<info>'.$message.'</info>'); $this->log->writeln('<info>'.$message.'</info>');
} }
} }
@@ -157,7 +157,7 @@ class Importer
*/ */
protected function tableName($table) protected function tableName($table)
{ {
if($this->creds['table_prefix'] !== false) { if ($this->creds['table_prefix'] !== false) {
return $this->creds['table_prefix'].$table; return $this->creds['table_prefix'].$table;
} }
@@ -173,9 +173,10 @@ class Importer
{ {
try { try {
$model->save(); $model->save();
return true; return true;
} catch (QueryException $e) { } catch (QueryException $e) {
if($e->getCode() !== '23000') { if ($e->getCode() !== '23000') {
$this->error($e); $this->error($e);
} }
@@ -191,7 +192,7 @@ class Importer
*/ */
protected function addMapping($entity, $old_id, $new_id) protected function addMapping($entity, $old_id, $new_id)
{ {
if(!array_key_exists($entity, $this->mappedEntities)) { if (!array_key_exists($entity, $this->mappedEntities)) {
$this->mappedEntities[$entity] = []; $this->mappedEntities[$entity] = [];
} }
@@ -206,12 +207,12 @@ class Importer
*/ */
protected function getMapping($entity, $old_id) protected function getMapping($entity, $old_id)
{ {
if(!array_key_exists($entity, $this->mappedEntities)) { if (!array_key_exists($entity, $this->mappedEntities)) {
return 0; return 0;
} }
$entity = $this->mappedEntities[$entity]; $entity = $this->mappedEntities[$entity];
if(array_key_exists($old_id, $entity)) { if (array_key_exists($old_id, $entity)) {
return $entity[$old_id]; return $entity[$old_id];
} }
@@ -225,6 +226,7 @@ class Importer
protected function parseDate($date) protected function parseDate($date)
{ {
$carbon = Carbon::parse($date); $carbon = Carbon::parse($date);
return $carbon; return $carbon;
} }
@@ -235,9 +237,9 @@ class Importer
*/ */
protected function convertDuration($duration) protected function convertDuration($duration)
{ {
if(strpos($duration, '.') !== false) { if (strpos($duration, '.') !== false) {
$delim = '.'; $delim = '.';
} elseif(strpos($duration, ':')) { } elseif (strpos($duration, ':')) {
$delim = ':'; $delim = ':';
} else { } else {
# no delimiter, assume it's just a straight hour # no delimiter, assume it's just a straight hour
@@ -259,52 +261,52 @@ class Importer
{ {
$table = $this->tableName($table); $table = $this->tableName($table);
$sql = 'SELECT COUNT(*) FROM ' . $table; $sql = 'SELECT COUNT(*) FROM '.$table;
$rows = $this->conn->query($sql)->fetchColumn(); $rows = $this->conn->query($sql)->fetchColumn();
$this->info('Found '.$rows.' rows in '.$table); $this->info('Found '.$rows.' rows in '.$table);
return (int) $rows; return (int) $rows;
} }
/** /**
* Read all the rows in a table, but read them in a batched manner * Read all the rows in a table, but read them in a batched manner
* @param string $table The name of the table * @param string $table The name of the table
* @param null $read_rows Number of rows to read * @param null $read_rows Number of rows to read
* @return \Generator * @return \Generator
*/ */
protected function readRows($table, $read_rows=null) protected function readRows($table, $read_rows = null)
{ {
// Set the table prefix if it has been entered // Set the table prefix if it has been entered
$this->tableName($table); $this->tableName($table);
$offset = 0; $offset = 0;
if($read_rows === null) { if ($read_rows === null) {
$read_rows = self::BATCH_READ_ROWS; $read_rows = self::BATCH_READ_ROWS;
} }
$total_rows = $this->getTotalRows($table); $total_rows = $this->getTotalRows($table);
while($offset < $total_rows) while ($offset < $total_rows) {
{
$rows_to_read = $offset + $read_rows; $rows_to_read = $offset + $read_rows;
if($rows_to_read > $total_rows) { if ($rows_to_read > $total_rows) {
$rows_to_read = $total_rows; $rows_to_read = $total_rows;
} }
$this->info('Reading '.$offset.' to '.$rows_to_read.' of '.$total_rows); $this->info('Reading '.$offset.' to '.$rows_to_read.' of '.$total_rows);
$sql = 'SELECT * FROM ' . $this->tableName($table) $sql = 'SELECT * FROM '.$this->tableName($table)
. ' LIMIT ' . self::BATCH_READ_ROWS . ' OFFSET ' . $offset; .' LIMIT '.self::BATCH_READ_ROWS.' OFFSET '.$offset;
try { try {
foreach ($this->conn->query($sql) as $row) { foreach ($this->conn->query($sql) as $row) {
yield $row; yield $row;
} }
} catch(PDOException $e) { } catch (PDOException $e) {
// Without incrementing the offset, it should re-run the same query // Without incrementing the offset, it should re-run the same query
$this->error($e); $this->error($e);
if(strpos($e->getMessage(), 'server has gone away') !== false) { if (strpos($e->getMessage(), 'server has gone away') !== false) {
$this->reconnect(); $this->reconnect();
continue; continue;
} }
@@ -344,22 +346,21 @@ class Importer
$this->comment('--- RANK IMPORT ---'); $this->comment('--- RANK IMPORT ---');
$count = 0; $count = 0;
foreach ($this->readRows('ranks') as $row) foreach ($this->readRows('ranks') as $row) {
{
$rank = Rank::firstOrCreate( $rank = Rank::firstOrCreate(
['name' => $row->rank], ['name' => $row->rank],
['image_link' => $row->rankimage, 'hours'=>$row->minhours] ['image_url' => $row->rankimage, 'hours' => $row->minhours]
); );
$this->addMapping('ranks', $row->rankid, $rank->id); $this->addMapping('ranks', $row->rankid, $rank->id);
$this->addMapping('ranks', $row->rank, $rank->id); $this->addMapping('ranks', $row->rank, $rank->id);
if($rank->wasRecentlyCreated) { if ($rank->wasRecentlyCreated) {
++$count; ++$count;
} }
} }
$this->info('Imported ' . $count . ' ranks'); $this->info('Imported '.$count.' ranks');
} }
/** /**
@@ -371,8 +372,7 @@ class Importer
$this->comment('--- AIRLINE IMPORT ---'); $this->comment('--- AIRLINE IMPORT ---');
$count = 0; $count = 0;
foreach ($this->readRows('airlines') as $row) foreach ($this->readRows('airlines') as $row) {
{
$airline = Airline::firstOrCreate( $airline = Airline::firstOrCreate(
['icao' => $row->code], ['icao' => $row->code],
['iata' => $row->code, 'name' => $row->name, 'active' => $row->enabled] ['iata' => $row->code, 'name' => $row->name, 'active' => $row->enabled]
@@ -386,7 +386,7 @@ class Importer
} }
} }
$this->info('Imported '. $count.' airlines'); $this->info('Imported '.$count.' airlines');
} }
/** /**
@@ -401,23 +401,22 @@ class Importer
$this->info('Subfleet ID is '.$subfleet->id); $this->info('Subfleet ID is '.$subfleet->id);
$count = 0; $count = 0;
foreach($this->readRows('aircraft') as $row) foreach ($this->readRows('aircraft') as $row) {
{
$aircraft = Aircraft::firstOrCreate( $aircraft = Aircraft::firstOrCreate(
['name' => $row->fullname, 'registration' => $row->registration], ['name' => $row->fullname, 'registration' => $row->registration],
['icao' => $row->icao, ['icao' => $row->icao,
'subfleet_id' => $subfleet->id, 'subfleet_id' => $subfleet->id,
'active' => $row->enabled 'active' => $row->enabled
]); ]);
$this->addMapping('aircraft', $row->id, $aircraft->id); $this->addMapping('aircraft', $row->id, $aircraft->id);
if($aircraft->wasRecentlyCreated) { if ($aircraft->wasRecentlyCreated) {
++$count; ++$count;
} }
} }
$this->info('Imported ' . $count . ' aircraft'); $this->info('Imported '.$count.' aircraft');
} }
/** /**
@@ -428,16 +427,15 @@ class Importer
$this->comment('--- AIRPORT IMPORT ---'); $this->comment('--- AIRPORT IMPORT ---');
$count = 0; $count = 0;
foreach ($this->readRows('airports') as $row) foreach ($this->readRows('airports') as $row) {
{
$attrs = [ $attrs = [
'id' => trim($row->icao), 'id' => trim($row->icao),
'icao' => trim($row->icao), 'icao' => trim($row->icao),
'name' => $row->name, 'name' => $row->name,
'country' => $row->country, 'country' => $row->country,
'lat' => $row->lat, 'lat' => $row->lat,
'lon' => $row->lng, 'lon' => $row->lng,
'hub' => $row->hub, 'hub' => $row->hub,
]; ];
$airport = Airport::updateOrCreate( $airport = Airport::updateOrCreate(
@@ -445,12 +443,12 @@ class Importer
$attrs $attrs
); );
if($airport->wasRecentlyCreated) { if ($airport->wasRecentlyCreated) {
++$count; ++$count;
} }
} }
$this->info('Imported ' . $count . ' airports'); $this->info('Imported '.$count.' airports');
} }
/** /**
@@ -461,8 +459,7 @@ class Importer
$this->comment('--- FLIGHT SCHEDULE IMPORT ---'); $this->comment('--- FLIGHT SCHEDULE IMPORT ---');
$count = 0; $count = 0;
foreach ($this->readRows('schedules') as $row) foreach ($this->readRows('schedules') as $row) {
{
$airline_id = $this->getMapping('airlines', $row->code); $airline_id = $this->getMapping('airlines', $row->code);
$flight_num = trim($row->flightnum); $flight_num = trim($row->flightnum);
@@ -470,14 +467,14 @@ class Importer
$attrs = [ $attrs = [
'dpt_airport_id' => $row->depicao, 'dpt_airport_id' => $row->depicao,
'arr_airport_id' => $row->arricao, 'arr_airport_id' => $row->arricao,
'route' => $row->route ?: '', 'route' => $row->route ?: '',
'distance' => round($row->distance ?: 0, 2), 'distance' => round($row->distance ?: 0, 2),
'level' => $row->flightlevel ?: 0, 'level' => $row->flightlevel ?: 0,
'dpt_time' => $row->deptime ?: '', 'dpt_time' => $row->deptime ?: '',
'arr_time' => $row->arrtime ?: '', 'arr_time' => $row->arrtime ?: '',
'flight_time' => $this->convertDuration($row->flighttime) ?: '', 'flight_time' => $this->convertDuration($row->flighttime) ?: '',
'notes' => $row->notes ?: '', 'notes' => $row->notes ?: '',
'active' => $row->enabled ?: true, 'active' => $row->enabled ?: true,
]; ];
try { try {
@@ -493,12 +490,12 @@ class Importer
// TODO: deserialize route_details into ACARS table // TODO: deserialize route_details into ACARS table
if($flight->wasRecentlyCreated) { if ($flight->wasRecentlyCreated) {
++$count; ++$count;
} }
} }
$this->info('Imported ' . $count . ' flights'); $this->info('Imported '.$count.' flights');
} }
/** /**
@@ -509,8 +506,7 @@ class Importer
$this->comment('--- PIREP IMPORT ---'); $this->comment('--- PIREP IMPORT ---');
$count = 0; $count = 0;
foreach ($this->readRows('pireps') as $row) foreach ($this->readRows('pireps') as $row) {
{
$pirep_id = $row->pirepid; $pirep_id = $row->pirepid;
$user_id = $this->getMapping('users', $row->pilotid); $user_id = $this->getMapping('users', $row->pilotid);
$airline_id = $this->getMapping('airlines', $row->code); $airline_id = $this->getMapping('airlines', $row->code);
@@ -518,17 +514,17 @@ class Importer
$attrs = [ $attrs = [
#'id' => $pirep_id, #'id' => $pirep_id,
'user_id' => $user_id, 'user_id' => $user_id,
'airline_id' => $airline_id, 'airline_id' => $airline_id,
'aircraft_id' => $aircraft_id, 'aircraft_id' => $aircraft_id,
'flight_number' => $row->flightnum ?: '', 'flight_number' => $row->flightnum ?: '',
'dpt_airport_id' => $row->depicao, 'dpt_airport_id' => $row->depicao,
'arr_airport_id' => $row->arricao, 'arr_airport_id' => $row->arricao,
'block_fuel' => $row->fuelused, 'block_fuel' => $row->fuelused,
'route' => $row->route ?: '', 'route' => $row->route ?: '',
'source_name' => $row->source, 'source_name' => $row->source,
'created_at' => $this->parseDate($row->submitdate), 'created_at' => $this->parseDate($row->submitdate),
'updated_at' => $this->parseDate($row->modifieddate), 'updated_at' => $this->parseDate($row->modifieddate),
]; ];
# Set the distance # Set the distance
@@ -542,7 +538,7 @@ class Importer
$attrs['planned_flight_time'] = $duration; $attrs['planned_flight_time'] = $duration;
# Set how it was filed # Set how it was filed
if(strtoupper($row->source) === 'MANUAL') { if (strtoupper($row->source) === 'MANUAL') {
$attrs['source'] = PirepSource::MANUAL; $attrs['source'] = PirepSource::MANUAL;
} else { } else {
$attrs['source'] = PirepSource::ACARS; $attrs['source'] = PirepSource::ACARS;
@@ -550,16 +546,16 @@ class Importer
# Set the flight type # Set the flight type
$row->flighttype = strtoupper($row->flighttype); $row->flighttype = strtoupper($row->flighttype);
if($row->flighttype === 'P') { if ($row->flighttype === 'P') {
$attrs['flight_type'] = FlightType::PASSENGER; $attrs['flight_type'] = FlightType::SCHED_PAX;
} elseif($row->flighttype === 'C') { } elseif ($row->flighttype === 'C') {
$attrs['flight_type'] = FlightType::CARGO; $attrs['flight_type'] = FlightType::SCHED_CARGO;
} else { } else {
$attrs['flight_type'] = FlightType::CHARTER; $attrs['flight_type'] = FlightType::CHARTER_PAX_ONLY;
} }
# Set the flight level of the PIREP is set # Set the flight level of the PIREP is set
if(property_exists($row, 'flightlevel')) { if (property_exists($row, 'flightlevel')) {
$attrs['level'] = $row->flightlevel; $attrs['level'] = $row->flightlevel;
} else { } else {
$attrs['level'] = 0; $attrs['level'] = 0;
@@ -571,11 +567,11 @@ class Importer
); );
$source = strtoupper($row->source); $source = strtoupper($row->source);
if($source === 'SMARTCARS') { if ($source === 'SMARTCARS') {
# TODO: Parse smartcars log into the acars table # TODO: Parse smartcars log into the acars table
} elseif($source === 'KACARS') { } elseif ($source === 'KACARS') {
# TODO: Parse kACARS log into acars table # TODO: Parse kACARS log into acars table
} elseif($source === 'XACARS') { } elseif ($source === 'XACARS') {
# TODO: Parse XACARS log into acars table # TODO: Parse XACARS log into acars table
} }
@@ -587,7 +583,7 @@ class Importer
} }
} }
$this->info('Imported ' . $count . ' pireps'); $this->info('Imported '.$count.' pireps');
} }
protected function importUsers() protected function importUsers()
@@ -596,10 +592,9 @@ class Importer
$count = 0; $count = 0;
foreach ($this->readRows('pilots', 50) as $row) { foreach ($this->readRows('pilots', 50) as $row) {
# TODO: What to do about pilot ids # TODO: What to do about pilot ids
$name = $row->firstname . ' ' . $row->lastname; $name = $row->firstname.' '.$row->lastname;
$airline_id = $this->getMapping('airlines', $row->code); $airline_id = $this->getMapping('airlines', $row->code);
$rank_id = $this->getMapping('ranks', $row->rank); $rank_id = $this->getMapping('ranks', $row->rank);
@@ -608,17 +603,17 @@ class Importer
$new_password = Str::random(60); $new_password = Str::random(60);
$attrs = [ $attrs = [
'name' => $name, 'name' => $name,
'password' => Hash::make($new_password), 'password' => Hash::make($new_password),
'api_key' => Utils::generateApiKey(), 'api_key' => Utils::generateApiKey(),
'airline_id' => $airline_id, 'airline_id' => $airline_id,
'rank_id' => $rank_id, 'rank_id' => $rank_id,
'home_airport_id' => $row->hub, 'home_airport_id' => $row->hub,
'curr_airport_id' => $row->hub, 'curr_airport_id' => $row->hub,
'flights' => (int)$row->totalflights, 'flights' => (int) $row->totalflights,
'flight_time' => Utils::hoursToMinutes($row->totalhours), 'flight_time' => Utils::hoursToMinutes($row->totalhours),
'state' => $state, 'state' => $state,
'created_at' => $this->parseDate($row->joindate), 'created_at' => $this->parseDate($row->joindate),
]; ];
$user = User::updateOrCreate( $user = User::updateOrCreate(
@@ -633,7 +628,7 @@ class Importer
} }
} }
$this->info('Imported ' . $count . ' users'); $this->info('Imported '.$count.' users');
} }
/** /**
@@ -641,7 +636,6 @@ class Importer
*/ */
protected function findLastPireps() protected function findLastPireps()
{ {
} }
/** /**
@@ -665,9 +659,9 @@ class Importer
// Declare array of classic states // Declare array of classic states
$phpvms_classic_states = [ $phpvms_classic_states = [
'ACTIVE' => 0, 'ACTIVE' => 0,
'INACTIVE' => 1, 'INACTIVE' => 1,
'BANNED' => 2, 'BANNED' => 2,
'ON_LEAVE' => 3 'ON_LEAVE' => 3
]; ];
@@ -682,7 +676,7 @@ class Importer
} elseif ($state === $phpvms_classic_states['ON_LEAVE']) { } elseif ($state === $phpvms_classic_states['ON_LEAVE']) {
return UserState::ON_LEAVE; return UserState::ON_LEAVE;
} else { } else {
$this->error('Unknown status: '. $state); $this->error('Unknown status: '.$state);
} }
} }
} }
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Cron\Monthly;
use App\Events\CronMonthly;
use App\Interfaces\Listener;
use App\Models\Enums\ExpenseType;
use App\Services\Finance\RecurringFinanceService;
/**
* Go through and apply any finances that are daily
* @package App\Listeners\Cron\Nightly
*/
class ApplyExpenses extends Listener
{
private $financeSvc;
/**
* ApplyExpenses constructor.
* @param RecurringFinanceService $financeSvc
*/
public function __construct(RecurringFinanceService $financeSvc)
{
$this->financeSvc = $financeSvc;
}
/**
* Apply all of the expenses for a month
* @param CronMonthly $event
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Prettus\Validator\Exceptions\ValidatorException
*/
public function handle(CronMonthly $event): void
{
$this->financeSvc->processExpenses(ExpenseType::MONTHLY);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Cron\Nightly;
use App\Events\CronNightly;
use App\Interfaces\Listener;
use App\Models\Enums\ExpenseType;
use App\Services\Finance\RecurringFinanceService;
/**
* Go through and apply any finances that are daily
* @package App\Listeners\Cron\Nightly
*/
class ApplyExpenses extends Listener
{
private $financeSvc;
/**
* ApplyExpenses constructor.
* @param RecurringFinanceService $financeSvc
*/
public function __construct(RecurringFinanceService $financeSvc)
{
$this->financeSvc = $financeSvc;
}
/**
* Apply all of the expenses for a day
* @param CronNightly $event
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Prettus\Validator\Exceptions\ValidatorException
*/
public function handle(CronNightly $event): void
{
$this->financeSvc->processExpenses(ExpenseType::DAILY);
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Cron\Nightly;
use App\Events\CronNightly;
use App\Interfaces\Listener;
use App\Models\Enums\UserState;
use App\Models\User;
use App\Services\UserService;
use Carbon\Carbon;
/**
* Determine if any pilots should be set to ON LEAVE status
* @package App\Listeners\Cron\Nightly
*/
class PilotLeave extends Listener
{
private $userSvc;
/**
* PilotLeave constructor.
*/
public function __construct(UserService $userSvc)
{
$this->userSvc = $userSvc;
}
/**
* Set any users to being on leave after X days
* @param CronNightly $event
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
*/
public function handle(CronNightly $event): void
{
if(setting('pilots.auto_leave_days') === 0) {
return;
}
$date = Carbon::now()->subDay(setting('pilots.auto_leave_days'));
$users = User::where('status', UserState::ACTIVE)
->whereDate('updated_at', '<', $date);
foreach($users as $user) {
$this->userSvc->setStatusOnLeave($user);
}
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Cron\Nightly;
use App\Events\CronNightly;
use App\Interfaces\Listener;
use App\Models\Journal;
use App\Repositories\JournalRepository;
use Log;
/**
* This recalculates the balances on all of the journals
* @package App\Listeners\Cron
*/
class RecalculateBalances extends Listener
{
private $journalRepo;
/**
* Nightly constructor.
* @param JournalRepository $journalRepo
*/
public function __construct(JournalRepository $journalRepo)
{
$this->journalRepo = $journalRepo;
}
/**
* Recalculate all the balances for the different ledgers
* @param CronNightly $event
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
*/
public function handle(CronNightly $event): void
{
Log::info('Recalculating balances');
$journals = Journal::all();
foreach ($journals as $journal) {
$old_balance = $journal->balance;
$this->journalRepo->recalculateBalance($journal);
$journal->refresh();
Log::info('Adjusting balance on '.
$journal->morphed_type.':'.$journal->morphed_id
.' from '.$old_balance.' to '.$journal->balance);
}
Log::info('Done calculating balances');
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace App\Cron\Nightly;
use App\Events\CronNightly;
use App\Interfaces\Listener;
use App\Models\Enums\Days;
use App\Models\Flight;
use Carbon\Carbon;
/**
* Figure out what flights need to be active for today
* @package App\Cron\Nightly
*/
class SetActiveFlights extends Listener
{
/**
* @param CronNightly $event
*/
public function handle(CronNightly $event): void
{
$this->checkFlights();
}
/**
* Look through every single flight, check the start/end dates,
* as well of the days of week if this flight is active on this day
*
* TODO: Option to check the flight active/inactive against departure TZ
* TODO: Move to FlightService
*/
public function checkFlights(): void
{
$today = Carbon::now('UTC');
$flights = Flight::all();
/**
* @var Flight $flight
*/
foreach($flights as $flight) {
// dates aren't set, so just save if there were any changes above
// and move onto the next one
if ($flight->start_date === null || $flight->end_date === null) {
if ($flight->days > 0) {
$flight->active = Days::isToday($flight->days);
}
$flight->save();
continue;
}
// Check the day of week now first
// Start/end date is set, so make sure today is valid for it to be alive
// and then make sure if days of the week are specified, check that too
if ($today->gte($flight->start_date) && $today->lte($flight->end_date)) {
if ($flight->days > 0) {
$flight->active = Days::isToday($flight->days);
} else {
$flight->active = true;
}
} else {
$flight->active = false;
}
$flight->save();
}
}
}
+12 -12
View File
@@ -4,18 +4,18 @@ use Faker\Generator as Faker;
$factory->define(App\Models\Acars::class, function (Faker $faker) { $factory->define(App\Models\Acars::class, function (Faker $faker) {
return [ return [
'id' => null, 'id' => null,
'pirep_id' => null, 'pirep_id' => null,
'log' => $faker->text(100), 'log' => $faker->text(100),
'lat' => $faker->latitude, 'lat' => $faker->latitude,
'lon' => $faker->longitude, 'lon' => $faker->longitude,
'heading' => $faker->numberBetween(0, 359), 'heading' => $faker->numberBetween(0, 359),
'altitude' => $faker->numberBetween(20, 400), 'altitude' => $faker->numberBetween(20, 400),
'vs' => $faker->numberBetween(-5000, 5000), 'vs' => $faker->numberBetween(-5000, 5000),
'gs' => $faker->numberBetween(300, 500), 'gs' => $faker->numberBetween(300, 500),
'transponder' => $faker->numberBetween(200, 9999), 'transponder' => $faker->numberBetween(200, 9999),
'autopilot' => $faker->text(10), 'autopilot' => $faker->text(10),
'fuel_flow' => $faker->randomFloat(2, 100, 1000), 'fuel_flow' => $faker->randomFloat(2, 100, 1000),
'sim_time' => $faker->dateTime('now', 'UTC'), 'sim_time' => $faker->dateTime('now', 'UTC'),
]; ];
}); });
+12 -9
View File
@@ -4,20 +4,23 @@ use Faker\Generator as Faker;
$factory->define(App\Models\Aircraft::class, function (Faker $faker) { $factory->define(App\Models\Aircraft::class, function (Faker $faker) {
return [ return [
'id' => null, 'id' => null,
'subfleet_id' => function() { 'subfleet_id' => function () {
return factory(App\Models\Subfleet::class)->create()->id; return factory(App\Models\Subfleet::class)->create()->id;
}, },
'airport_id' => function () { 'airport_id' => function () {
return factory(App\Models\Airport::class)->create()->id; return factory(App\Models\Airport::class)->create()->id;
}, },
'icao' => $faker->unique()->text(5), 'iata' => $faker->unique()->text(5),
'name' => $faker->unique()->text(50), 'icao' => $faker->unique()->text(5),
'name' => $faker->text(50),
'registration' => $faker->unique()->text(10), 'registration' => $faker->unique()->text(10),
'hex_code' => \App\Support\ICAO::createHexCode(), 'hex_code' => \App\Support\ICAO::createHexCode(),
'active' => true, 'zfw' => $faker->randomFloat(2, 0, 50000),
'created_at' => $faker->dateTimeBetween('-1 week', 'now'), 'status' => \App\Models\Enums\AircraftStatus::ACTIVE,
'updated_at' => function (array $pirep) { 'state' => \App\Models\Enums\AircraftState::PARKED,
'created_at' => $faker->dateTimeBetween('-1 week', 'now'),
'updated_at' => function (array $pirep) {
return $pirep['created_at']; return $pirep['created_at'];
}, },
]; ];
+8 -5
View File
@@ -8,15 +8,18 @@ use Hashids\Hashids;
*/ */
$factory->define(App\Models\Airline::class, function (Faker $faker) { $factory->define(App\Models\Airline::class, function (Faker $faker) {
return [ return [
'id' => null, 'id' => null,
'icao' => function (array $apt) use ($faker) { 'icao' => function (array $apt) use ($faker) {
$hashids = new Hashids(microtime(), 5); $hashids = new Hashids(microtime(), 5);
$mt = str_replace('.', '', microtime(true)); $mt = str_replace('.', '', microtime(true));
return $hashids->encode($mt); return $hashids->encode($mt);
}, },
'iata' => function (array $apt) { return $apt['icao']; }, 'iata' => function (array $apt) {
'name' => $faker->sentence(3), return $apt['icao'];
},
'name' => $faker->sentence(3),
'country' => $faker->country, 'country' => $faker->country,
'active' => 1 'active' => 1
]; ];
}); });
+16 -12
View File
@@ -6,9 +6,8 @@ use Faker\Generator as Faker;
* Add any number of airports. Don't really care if they're real or not * Add any number of airports. Don't really care if they're real or not
*/ */
$factory->define(App\Models\Airport::class, function (Faker $faker) { $factory->define(App\Models\Airport::class, function (Faker $faker) {
return [ return [
'id' => function() { 'id' => function () {
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$string = ''; $string = '';
$max = strlen($characters) - 1; $max = strlen($characters) - 1;
@@ -18,15 +17,20 @@ $factory->define(App\Models\Airport::class, function (Faker $faker) {
return $string; return $string;
}, },
'icao' => function(array $apt) { return $apt['id']; }, 'icao' => function (array $apt) {
'iata' => function (array $apt) { return $apt['id']; }, return $apt['id'];
'name' => $faker->sentence(3), },
'country' => $faker->country, 'iata' => function (array $apt) {
'timezone' => $faker->timezone, return $apt['id'];
'lat' => $faker->latitude, },
'lon' => $faker->longitude, 'name' => $faker->sentence(3),
'fuel_100ll_cost' => $faker->randomFloat(2), 'country' => $faker->country,
'fuel_jeta_cost' => $faker->randomFloat(2), 'timezone' => $faker->timezone,
'fuel_mogas_cost' => $faker->randomFloat(2), 'lat' => $faker->latitude,
'lon' => $faker->longitude,
'ground_handling_cost' => $faker->randomFloat(2, 0, 500),
'fuel_100ll_cost' => $faker->randomFloat(2, 0, 100),
'fuel_jeta_cost' => $faker->randomFloat(2, 0, 100),
'fuel_mogas_cost' => $faker->randomFloat(2, 0, 100),
]; ];
}); });
+13
View File
@@ -0,0 +1,13 @@
<?php
use Faker\Generator as Faker;
$factory->define(App\Models\Award::class, function (Faker $faker) {
return [
'id' => null,
'name' => $faker->name,
'description' => $faker->text(10),
'ref_model' => null,
'ref_model_params' => null,
];
});
+18
View File
@@ -0,0 +1,18 @@
<?php
use App\Models\Enums\ExpenseType;
use Faker\Generator as Faker;
$factory->define(App\Models\Expense::class, function (Faker $faker) {
return [
'id' => null,
'airline_id' => null,
'name' => $faker->text(20),
'amount' => $faker->randomFloat(2, 100, 1000),
'type' => ExpenseType::FLIGHT,
'multiplier' => false,
'ref_model' => \App\Models\Expense::class,
'ref_model_id' => null,
'active' => true,
];
});
+7 -4
View File
@@ -4,10 +4,13 @@ use Faker\Generator as Faker;
$factory->define(App\Models\Fare::class, function (Faker $faker) { $factory->define(App\Models\Fare::class, function (Faker $faker) {
return [ return [
'id' => null, 'id' => null,
'code' => $faker->text(5), 'code' => $faker->unique()->text(50),
'name' => $faker->text(20), 'name' => $faker->text(50),
'price' => $faker->randomFloat(2, 100, 1000), 'price' => $faker->randomFloat(2, 100, 1000),
'cost' => function (array $fare) {
return round($fare['price'] / 2);
},
'capacity' => $faker->randomFloat(0, 20, 500), 'capacity' => $faker->randomFloat(0, 20, 500),
]; ];
}); });
+23 -20
View File
@@ -1,21 +1,20 @@
<?php <?php
/**
* Create flights
*/
use Faker\Generator as Faker; use Faker\Generator as Faker;
# Match the list available in tests/data/*.yml $factory->define(App\Models\Flight::class, function (Faker $faker) {
$airlinesAvailable = [1];
$factory->define(App\Models\Flight::class, function (Faker $faker) use ($airlinesAvailable) {
return [ return [
'id' => null, 'id' => null,
'airline_id' => function () { 'airline_id' => function () {
return factory(App\Models\Airline::class)->create()->id; return factory(App\Models\Airline::class)->create()->id;
}, },
'flight_number' => $faker->unique()->numberBetween(10, 1000000), 'flight_number' => $faker->unique()->numberBetween(10, 1000000),
'route_code' => $faker->randomElement(['', $faker->text(5)]), 'route_code' => $faker->randomElement(['', $faker->text(5)]),
'route_leg' => $faker->randomElement(['', $faker->text(5)]), 'route_leg' => $faker->randomElement(['', $faker->text(5)]),
'dpt_airport_id' => function() { 'dpt_airport_id' => function () {
return factory(App\Models\Airport::class)->create()->id; return factory(App\Models\Airport::class)->create()->id;
}, },
'arr_airport_id' => function () { 'arr_airport_id' => function () {
@@ -24,15 +23,19 @@ $factory->define(App\Models\Flight::class, function (Faker $faker) use ($airline
'alt_airport_id' => function () { 'alt_airport_id' => function () {
return factory(App\Models\Airport::class)->create()->id; return factory(App\Models\Airport::class)->create()->id;
}, },
'distance' => $faker->numberBetween(0, 3000), 'distance' => $faker->numberBetween(0, 3000),
'route' => null, 'route' => null,
'dpt_time' => $faker->time(), 'level' => 0,
'arr_time' => $faker->time(), 'dpt_time' => $faker->time(),
'flight_time' => $faker->numberBetween(60, 360), 'arr_time' => $faker->time(),
'has_bid' => false, 'flight_time' => $faker->numberBetween(60, 360),
'active' => true, 'has_bid' => false,
'created_at' => $faker->dateTimeBetween('-1 week', 'now'), 'active' => true,
'updated_at' => function (array $flight) { 'days' => 0,
'start_date' => null,
'end_date' => null,
'created_at' => $faker->dateTimeBetween('-1 week', 'now'),
'updated_at' => function (array $flight) {
return $flight['created_at']; return $flight['created_at'];
}, },
]; ];
@@ -0,0 +1,9 @@
<?php
use Faker\Generator as Faker;
$factory->define(App\Models\Journal::class, function (Faker $faker) {
return [
'currency' => 'USD',
];
});
@@ -0,0 +1,17 @@
<?php
use Faker\Generator as Faker;
$factory->define(App\Models\JournalTransactions::class, function (Faker $faker) {
return [
'transaction_group' => \Ramsey\Uuid\Uuid::uuid4()->toString(),
'journal_id' => function () {
return factory(App\Models\Journal::class)->create()->id;
},
'credit' => $faker->numberBetween(100, 10000),
'debit' => $faker->numberBetween(100, 10000),
'currency' => 'USD',
'memo' => $faker->sentence(6),
'post_date' => \Carbon\Carbon::now(),
];
});
+4 -4
View File
@@ -1,15 +1,15 @@
<?php <?php
use App\Models\Enums\NavaidType;
use Faker\Generator as Faker; use Faker\Generator as Faker;
use \App\Models\Enums\NavaidType;
$factory->define(App\Models\Navdata::class, function (Faker $faker) { $factory->define(App\Models\Navdata::class, function (Faker $faker) {
return [ return [
'id' => str_replace(' ', '', str_replace('.', '', $faker->unique()->text(5))), 'id' => str_replace(' ', '', str_replace('.', '', $faker->unique()->text(5))),
'name' => str_replace('.', '', $faker->unique()->word), 'name' => str_replace('.', '', $faker->unique()->word),
'type' => $faker->randomElement([NavaidType::VOR, NavaidType::NDB]), 'type' => $faker->randomElement([NavaidType::VOR, NavaidType::NDB]),
'lat' => $faker->latitude, 'lat' => $faker->latitude,
'lon' => $faker->longitude, 'lon' => $faker->longitude,
'freq' => $faker->randomFloat(2, 100, 1000), 'freq' => $faker->randomFloat(2, 100, 1000),
]; ];
}); });
+14
View File
@@ -0,0 +1,14 @@
<?php
use Faker\Generator as Faker;
$factory->define(App\Models\News::class, function (Faker $faker) {
return [
'id' => null,
'user_id' => function() {
return factory(App\Models\User::class)->create()->id;
},
'subject' => $faker->text(),
'body' => $faker->sentence,
];
});
+29 -25
View File
@@ -7,47 +7,51 @@ use Faker\Generator as Faker;
* Create a new PIREP * Create a new PIREP
*/ */
$factory->define(App\Models\Pirep::class, function (Faker $faker) { $factory->define(App\Models\Pirep::class, function (Faker $faker) {
return [ return [
'id' => null, 'id' => null,
'airline_id' => function () { 'airline_id' => function () {
return factory(App\Models\Airline::class)->create()->id; return factory(App\Models\Airline::class)->create()->id;
}, },
'user_id' => function () { 'user_id' => function () {
return factory(App\Models\User::class)->create()->id; return factory(App\Models\User::class)->create()->id;
}, },
'aircraft_id' => function () { 'aircraft_id' => function () {
return factory(App\Models\Aircraft::class)->create()->id; return factory(App\Models\Aircraft::class)->create()->id;
}, },
'flight_number' => function (array $pirep) { 'flight_number' => function (array $pirep) {
return factory(App\Models\Flight::class)->create([ return factory(App\Models\Flight::class)->create([
'airline_id' => $pirep['airline_id'] 'airline_id' => $pirep['airline_id']
])->flight_number; ])->flight_number;
}, },
'route_code' => null, 'route_code' => null,
'route_leg' => null, 'route_leg' => null,
'dpt_airport_id' => function () { 'dpt_airport_id' => function () {
return factory(App\Models\Airport::class)->create()->id; return factory(App\Models\Airport::class)->create()->id;
}, },
'arr_airport_id' => function () { 'arr_airport_id' => function () {
return factory(App\Models\Airport::class)->create()->id; return factory(App\Models\Airport::class)->create()->id;
}, },
'level' => $faker->numberBetween(20, 400), 'level' => $faker->numberBetween(20, 400),
'distance' => $faker->randomFloat(2, 0, 6000), 'distance' => $faker->randomFloat(2, 0, 6000),
'planned_distance' => $faker->randomFloat(2, 0, 6000), 'planned_distance' => $faker->randomFloat(2, 0, 6000),
'flight_time' => $faker->numberBetween(60, 360), 'flight_time' => $faker->numberBetween(60, 360),
'planned_flight_time' => $faker->numberBetween(60, 360), 'planned_flight_time' => $faker->numberBetween(60, 360),
'zfw' => $faker->randomFloat(2), 'zfw' => $faker->randomFloat(2),
'block_fuel' => $faker->randomFloat(2, 0, 30000), 'block_fuel' => $faker->randomFloat(2, 0, 30000),
'fuel_used' => $faker->randomFloat(2, 0, 30000), 'fuel_used' => $faker->randomFloat(2, 0, 30000),
'route' => $faker->text(200), 'block_on_time' => Carbon::now('UTC'),
'notes' => $faker->text(200), 'block_off_time' => function (array $pirep) {
'source' => $faker->randomElement([PirepSource::MANUAL, PirepSource::ACARS]), return $pirep['block_on_time']->subMinutes($pirep['flight_time']);
'source_name' => 'Test Factory', },
'state' => PirepState::PENDING, 'route' => $faker->text(200),
'status' => PirepStatus::SCHEDULED, 'notes' => $faker->text(200),
'created_at' => Carbon::now()->toDateTimeString(), 'source' => $faker->randomElement([PirepSource::MANUAL, PirepSource::ACARS]),
'updated_at' => function(array $pirep) { 'source_name' => 'Test Factory',
'state' => PirepState::PENDING,
'status' => PirepStatus::SCHEDULED,
'submitted_at' => Carbon::now('UTC')->toDateTimeString(),
'created_at' => Carbon::now('UTC')->toDateTimeString(),
'updated_at' => function (array $pirep) {
return $pirep['created_at']; return $pirep['created_at'];
}, },
]; ];
+8 -6
View File
@@ -11,11 +11,13 @@ use Faker\Generator as Faker;
*/ */
$factory->define(App\Models\Rank::class, function (Faker $faker) { $factory->define(App\Models\Rank::class, function (Faker $faker) {
return [ return [
'id' => null, 'id' => null,
'name' => $faker->unique()->text(50), 'name' => $faker->unique()->text(50),
'hours' => $faker->numberBetween(10, 50), 'hours' => $faker->numberBetween(10, 50),
'auto_approve_acars' => 0, 'acars_base_pay_rate' => $faker->numberBetween(10, 100),
'auto_approve_manual' => 0, 'manual_base_pay_rate' => $faker->numberBetween(10, 100),
'auto_promote' => 0, 'auto_approve_acars' => 0,
'auto_approve_manual' => 0,
'auto_promote' => 0,
]; ];
}); });
+5 -4
View File
@@ -4,11 +4,12 @@ use Faker\Generator as Faker;
$factory->define(App\Models\Subfleet::class, function (Faker $faker) { $factory->define(App\Models\Subfleet::class, function (Faker $faker) {
return [ return [
'id' => null, 'id' => null,
'airline_id' => function () { 'airline_id' => function () {
return factory(App\Models\Airline::class)->create()->id; return factory(App\Models\Airline::class)->create()->id;
}, },
'name' => $faker->unique()->text(50), 'name' => $faker->unique()->text(50),
'type' => $faker->unique()->text(7), 'type' => $faker->unique()->text(7),
'ground_handling_multiplier' => $faker->numberBetween(50, 200),
]; ];
}); });
+13 -14
View File
@@ -1,26 +1,25 @@
<?php <?php
use Faker\Generator as Faker;
use App\Models\Enums\UserState; use App\Models\Enums\UserState;
use Faker\Generator as Faker;
$factory->define(App\Models\User::class, function (Faker $faker) $factory->define(App\Models\User::class, function (Faker $faker) {
{
static $password; static $password;
return [ return [
'id' => null, 'id' => null,
'name' => $faker->name, 'name' => $faker->name,
'email' => $faker->safeEmail, 'email' => $faker->safeEmail,
'password' => $password ?: $password = Hash::make('secret'), 'password' => $password ?: $password = Hash::make('secret'),
'api_key' => $faker->sha1, 'api_key' => $faker->sha1,
'airline_id' => function () { 'airline_id' => function () {
return factory(App\Models\Airline::class)->create()->id; return factory(App\Models\Airline::class)->create()->id;
}, },
'rank_id' => 1, 'rank_id' => 1,
'flights' => $faker->numberBetween(0, 1000), 'flights' => $faker->numberBetween(0, 1000),
'flight_time' => $faker->numberBetween(0, 10000), 'flight_time' => $faker->numberBetween(0, 10000),
'transfer_time' => $faker->numberBetween(0, 10000), 'transfer_time' => $faker->numberBetween(0, 10000),
'state' => UserState::ACTIVE, 'state' => UserState::ACTIVE,
'remember_token' => $faker->unique()->text(5), 'remember_token' => $faker->unique()->text(5),
]; ];
}); });
@@ -1,6 +1,6 @@
<?php <?php
use App\Models\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class CreateSettingsTable extends Migration class CreateSettingsTable extends Migration
@@ -22,7 +22,7 @@ class CreateSettingsTable extends Migration
$table->string('default')->nullable(); $table->string('default')->nullable();
$table->string('group')->nullable(); $table->string('group')->nullable();
$table->string('type')->nullable(); $table->string('type')->nullable();
$table->string('options')->nullable(); $table->text('options')->nullable();
$table->string('description')->nullable(); $table->string('description')->nullable();
$table->primary('id'); $table->primary('id');
@@ -35,73 +35,91 @@ class CreateSettingsTable extends Migration
*/ */
$this->addSetting('general.start_date', [ $this->addSetting('general.start_date', [
'name' => 'Start Date', 'name' => 'Start Date',
'group' => 'general', 'group' => 'general',
'value' => '', 'value' => '',
'type' => 'date', 'type' => 'date',
'description' => 'The date your VA started', 'description' => 'The date your VA started',
]); ]);
$this->addSetting('general.admin_email', [ $this->addSetting('general.admin_email', [
'name' => 'Admin Email', 'name' => 'Admin Email',
'group' => 'general', 'group' => 'general',
'value' => '', 'value' => '',
'type' => 'text', 'type' => 'text',
'description' => 'Email where notices, etc are sent', 'description' => 'Email where notices, etc are sent',
]); ]);
$this->addSetting('general.currency', [ /*$this->addSetting('general.currency', [
'name' => 'Currency to Use', 'name' => 'Currency to Use',
'group' => 'general', 'group' => 'general',
'value' => 'dollar', 'value' => 'USD',
'type' => 'select', 'type' => 'select',
'options' => 'dollar,euro,gbp,yen,jpy,rupee,ruble', 'options' => 'USD,EUR,GBP,JPY,RUB',
'description' => 'Currency to show in the interface', 'description' => 'Currency to use. NOTE: If you change this, then current amounts won\'t be converted',
]);*/
$this->addSetting('units.distance', [
'name' => 'Distance Units',
'group' => 'units',
'value' => 'nmi',
'type' => 'select',
'options' => 'km=kilometers,mi=miles,nmi=nautical miles',
'description' => 'The distance unit for display',
]); ]);
$this->addSetting('general.distance_unit', [ $this->addSetting('units.weight', [
'name' => 'Distance Units', 'name' => 'Weight Units',
'group' => 'general', 'group' => 'units',
'value' => 'NM', 'value' => 'lbs',
'type' => 'select', 'type' => 'select',
'options' => 'km,mi,NM', 'options' => 'lbs,kg',
'description' => 'The distance unit to show', 'description' => 'The weight unit for display',
]); ]);
$this->addSetting('general.weight_unit', [ $this->addSetting('units.speed', [
'name' => 'Weight Units', 'name' => 'Speed Units',
'group' => 'general', 'group' => 'units',
'value' => 'lbs', 'value' => 'knot',
'type' => 'select', 'type' => 'select',
'options' => 'lbs,kg', 'options' => 'km/h,knot',
'description' => 'The weight unit', 'description' => 'The speed unit for display',
]); ]);
$this->addSetting('general.speed_unit', [ $this->addSetting('units.altitude', [
'name' => 'Speed Units', 'name' => 'Altitude Units',
'group' => 'general', 'group' => 'units',
'value' => 'knot', 'value' => 'ft',
'type' => 'select', 'type' => 'select',
'options' => 'km/h,knot', 'options' => 'ft=feet,m=meters',
'description' => 'The speed unit', 'description' => 'The altitude unit for display',
]); ]);
$this->addSetting('general.altitude_unit', [ $this->addSetting('units.fuel', [
'name' => 'Altitude Units', 'name' => 'Fuel Units',
'group' => 'general', 'group' => 'units',
'value' => 'ft', 'value' => 'lbs',
'type' => 'select', 'type' => 'select',
'options' => 'ft,m', 'options' => 'lbs,kg',
'description' => 'The altitude units', 'description' => 'The units for fuel for display',
]); ]);
$this->addSetting('general.fuel_unit', [ $this->addSetting('units.volume', [
'name' => 'Fuel Units', 'name' => 'Volume Units',
'group' => 'general', 'group' => 'units',
'value' => 'lbs', 'value' => 'gallons',
'type' => 'select', 'type' => 'select',
'options' => 'lbs,kg', 'options' => 'gallons,l=liters',
'description' => 'The units for fuel', 'description' => 'The units for fuel for display',
]);
$this->addSetting('units.temperature', [
'name' => 'Temperature Units',
'group' => 'units',
'value' => 'F',
'type' => 'select',
'options' => 'F=Fahrenheit,C=Celsius',
'description' => 'The units for temperature',
]); ]);
/** /**
@@ -109,30 +127,38 @@ class CreateSettingsTable extends Migration
*/ */
$this->addSetting('bids.disable_flight_on_bid', [ $this->addSetting('bids.disable_flight_on_bid', [
'name' => 'Disable flight on bid', 'name' => 'Disable flight on bid',
'group' => 'bids', 'group' => 'bids',
'value' => true, 'value' => true,
'type' => 'boolean', 'type' => 'boolean',
'description' => 'When a flight is bid on, no one else can bid on it', 'description' => 'When a flight is bid on, no one else can bid on it',
]); ]);
$this->addSetting('bids.allow_multiple_bids', [ $this->addSetting('bids.allow_multiple_bids', [
'name' => 'Allow multiple bids', 'name' => 'Allow multiple bids',
'group' => 'bids', 'group' => 'bids',
'value' => true, 'value' => true,
'type' => 'boolean', 'type' => 'boolean',
'description' => 'Whether or not someone can bid on multiple flights', 'description' => 'Whether or not someone can bid on multiple flights',
]); ]);
$this->addSetting('bids.expire_time', [
'name' => 'Expire Time',
'group' => 'bids',
'value' => 48,
'type' => 'int',
'description' => 'Number of hours to expire bids after',
]);
/** /**
* PIREPS * PIREPS
*/ */
$this->addSetting('pireps.duplicate_check_time', [ $this->addSetting('pireps.duplicate_check_time', [
'name' => 'PIREP duplicate time check', 'name' => 'PIREP duplicate time check',
'group' => 'pireps', 'group' => 'pireps',
'value' => 10, 'value' => 10,
'type' => 'int', 'type' => 'int',
'description' => 'The time in minutes to check for a duplicate PIREP', 'description' => 'The time in minutes to check for a duplicate PIREP',
]); ]);
@@ -145,64 +171,80 @@ class CreateSettingsTable extends Migration
]);*/ ]);*/
$this->addSetting('pireps.restrict_aircraft_to_rank', [ $this->addSetting('pireps.restrict_aircraft_to_rank', [
'name' => 'Restrict Aircraft to Ranks', 'name' => 'Restrict Aircraft to Ranks',
'group' => 'pireps', 'group' => 'pireps',
'value' => true, 'value' => true,
'type' => 'boolean', 'type' => 'boolean',
'description' => 'Aircraft that can be flown are restricted to a user\'s rank', 'description' => 'Aircraft that can be flown are restricted to a user\'s rank',
]); ]);
$this->addSetting('pireps.only_aircraft_at_dep_airport', [ $this->addSetting('pireps.only_aircraft_at_dpt_airport', [
'name' => 'Restrict Aircraft At Departure', 'name' => 'Restrict Aircraft At Departure',
'group' => 'pireps', 'group' => 'pireps',
'value' => false, 'value' => false,
'type' => 'boolean', 'type' => 'boolean',
'description' => 'Only allow aircraft that are at the departure airport', 'description' => 'Only allow aircraft that are at the departure airport',
]); ]);
$this->addSetting('pireps.remove_bid_on_accept', [
'name' => 'Remove bid on accept',
'group' => 'pireps',
'value' => false,
'type' => 'boolean',
'description' => 'When a PIREP is accepted, remove the bid, if it exists',
]);
/** /**
* PILOTS * PILOTS
*/ */
$this->addSetting('pilots.id_length', [ $this->addSetting('pilots.id_length', [
'name' => 'Pilot ID Length', 'name' => 'Pilot ID Length',
'group' => 'pilots', 'group' => 'pilots',
'value' => 4, 'value' => 4,
'default' => 4, 'default' => 4,
'type' => 'int', 'type' => 'int',
'description' => 'The length of a pilot\'s ID', 'description' => 'The length of a pilot\'s ID',
]); ]);
$this->addSetting('pilot.auto_accept', [ $this->addSetting('pilots.auto_accept', [
'name' => 'Auto Accept New Pilot', 'name' => 'Auto Accept New Pilot',
'group' => 'pilots', 'group' => 'pilots',
'value' => true, 'value' => true,
'type' => 'boolean', 'type' => 'boolean',
'description' => 'Automatically accept a pilot when they register', 'description' => 'Automatically accept a pilot when they register',
]); ]);
$this->addSetting('pilots.home_hubs_only', [
'name' => 'Hubs as home airport',
'group' => 'pilots',
'value' => false,
'type' => 'boolean',
'description' => 'Pilots can only select hubs as their home airport',
]);
$this->addSetting('pilots.only_flights_from_current', [ $this->addSetting('pilots.only_flights_from_current', [
'name' => 'Flights from Current', 'name' => 'Flights from Current',
'group' => 'pilots', 'group' => 'pilots',
'value' => false, 'value' => false,
'type' => 'boolean', 'type' => 'boolean',
'description' => 'Only show/allow flights from their current location', 'description' => 'Only show/allow flights from their current location',
]); ]);
$this->addSetting('pilot.auto_leave_days', [ $this->addSetting('pilots.auto_leave_days', [
'name' => 'Pilot to ON LEAVE days', 'name' => 'Pilot to ON LEAVE days',
'group' => 'pilots', 'group' => 'pilots',
'value' => 30, 'value' => 30,
'default' => 30, 'default' => 30,
'type' => 'int', 'type' => 'int',
'description' => 'Automatically set a pilot to ON LEAVE status after N days of no activity', 'description' => 'Automatically set a pilot to ON LEAVE status after N days of no activity',
]); ]);
$this->addSetting('pilots.hide_inactive', [ $this->addSetting('pilots.hide_inactive', [
'name' => 'Hide Inactive Pilots', 'name' => 'Hide Inactive Pilots',
'group' => 'pilots', 'group' => 'pilots',
'value' => true, 'value' => true,
'type' => 'boolean', 'type' => 'boolean',
'description' => 'Don\'t show inactive pilots in the public view', 'description' => 'Don\'t show inactive pilots in the public view',
]); ]);
} }
@@ -1,6 +1,6 @@
<?php <?php
use App\Models\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -28,7 +28,7 @@ class CreateUsersTable extends Migration
$table->unsignedBigInteger('flights')->default(0); $table->unsignedBigInteger('flights')->default(0);
$table->unsignedBigInteger('flight_time')->nullable()->default(0); $table->unsignedBigInteger('flight_time')->nullable()->default(0);
$table->unsignedBigInteger('transfer_time')->nullable()->default(0); $table->unsignedBigInteger('transfer_time')->nullable()->default(0);
$table->decimal('balance')->nullable(); $table->string('avatar')->nullable();
$table->string('timezone', 64)->nullable(); $table->string('timezone', 64)->nullable();
$table->unsignedTinyInteger('status')->nullable()->default(0); $table->unsignedTinyInteger('status')->nullable()->default(0);
$table->unsignedTinyInteger('state')->nullable()->default(0); $table->unsignedTinyInteger('state')->nullable()->default(0);
@@ -1,6 +1,6 @@
<?php <?php
use App\Models\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class RolesPermissionsTables extends Migration class RolesPermissionsTables extends Migration
@@ -70,18 +70,17 @@ class RolesPermissionsTables extends Migration
# create a default user/role # create a default user/role
$roles = [ $roles = [
[ [
'id' => 1, 'id' => 1,
'name' => 'admin', 'name' => 'admin',
'display_name' => 'Administrators', 'display_name' => 'Administrators',
], ],
[ [
'id' => 2, 'id' => 2,
'name' => 'user', 'name' => 'user',
'display_name' => 'Pilot' 'display_name' => 'Pilot'
], ],
]; ];
$this->addData('roles', $roles); $this->addData('roles', $roles);
} }
@@ -1,6 +1,6 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -1,6 +1,6 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -1,11 +1,10 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class CreateAirlinesTable extends Migration class CreateAirlinesTable extends Migration
{ {
/** /**
* Run the migrations. * Run the migrations.
* *
@@ -1,7 +1,8 @@
<?php <?php
use App\Interfaces\Migration;
use App\Models\Enums\AircraftState; use App\Models\Enums\AircraftState;
use Illuminate\Database\Migrations\Migration; use App\Models\Enums\AircraftStatus;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class CreateAircraftsTable extends Migration class CreateAircraftsTable extends Migration
@@ -12,6 +13,7 @@ class CreateAircraftsTable extends Migration
$table->increments('id'); $table->increments('id');
$table->unsignedInteger('subfleet_id'); $table->unsignedInteger('subfleet_id');
$table->string('icao', 4)->nullable(); $table->string('icao', 4)->nullable();
$table->string('iata', 4)->nullable();
$table->string('airport_id', 5)->nullable(); $table->string('airport_id', 5)->nullable();
$table->timestamp('landing_time')->nullable(); $table->timestamp('landing_time')->nullable();
$table->string('name', 50); $table->string('name', 50);
@@ -19,14 +21,13 @@ class CreateAircraftsTable extends Migration
$table->string('hex_code', 10)->nullable(); $table->string('hex_code', 10)->nullable();
$table->unsignedDecimal('zfw')->nullable()->default(0); $table->unsignedDecimal('zfw')->nullable()->default(0);
$table->unsignedBigInteger('flight_time')->nullable()->default(0); $table->unsignedBigInteger('flight_time')->nullable()->default(0);
$table->boolean('active')->default(true); $table->char('status', 1)->default(AircraftStatus::ACTIVE);
$table->unsignedTinyInteger('state')->default(AircraftState::PARKED); $table->unsignedTinyInteger('state')->default(AircraftState::PARKED);
$table->timestamps(); $table->timestamps();
$table->unique('registration'); $table->unique('registration');
$table->index('airport_id'); $table->index('airport_id');
}); });
} }
public function down() public function down()
@@ -1,11 +1,10 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class CreateFaresTable extends Migration class CreateFaresTable extends Migration
{ {
/** /**
* Run the migrations. * Run the migrations.
* *
@@ -15,7 +14,7 @@ class CreateFaresTable extends Migration
{ {
Schema::create('fares', function (Blueprint $table) { Schema::create('fares', function (Blueprint $table) {
$table->increments('id'); $table->increments('id');
$table->string('code', 50); $table->string('code', 50)->unique();
$table->string('name', 50); $table->string('name', 50);
$table->unsignedDecimal('price')->nullable()->default(0.00); $table->unsignedDecimal('price')->nullable()->default(0.00);
$table->unsignedDecimal('cost')->nullable()->default(0.00); $table->unsignedDecimal('cost')->nullable()->default(0.00);
@@ -1,6 +1,6 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class CreateAirportsTable extends Migration class CreateAirportsTable extends Migration
@@ -16,6 +16,7 @@ class CreateAirportsTable extends Migration
$table->string('country', 64)->nullable(); $table->string('country', 64)->nullable();
$table->string('timezone', 64)->nullable(); $table->string('timezone', 64)->nullable();
$table->boolean('hub')->default(false); $table->boolean('hub')->default(false);
$table->unsignedDecimal('ground_handling_cost')->nullable()->default(0);
$table->unsignedDecimal('fuel_100ll_cost')->nullable()->default(0); $table->unsignedDecimal('fuel_100ll_cost')->nullable()->default(0);
$table->unsignedDecimal('fuel_jeta_cost')->nullable()->default(0); $table->unsignedDecimal('fuel_jeta_cost')->nullable()->default(0);
$table->unsignedDecimal('fuel_mogas_cost')->nullable()->default(0); $table->unsignedDecimal('fuel_mogas_cost')->nullable()->default(0);
@@ -1,12 +1,11 @@
<?php <?php
use App\Interfaces\Migration;
use App\Models\Enums\FlightType; use App\Models\Enums\FlightType;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class CreateFlightTables extends Migration class CreateFlightTables extends Migration
{ {
/** /**
* Run the migrations. * Run the migrations.
* *
@@ -15,9 +14,9 @@ class CreateFlightTables extends Migration
public function up() public function up()
{ {
Schema::create('flights', function (Blueprint $table) { Schema::create('flights', function (Blueprint $table) {
$table->string('id', \App\Models\Flight::ID_MAX_LENGTH); $table->string('id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->unsignedInteger('airline_id'); $table->unsignedInteger('airline_id');
$table->string('flight_number', 10); $table->unsignedInteger('flight_number');
$table->string('route_code', 5)->nullable(); $table->string('route_code', 5)->nullable();
$table->string('route_leg', 5)->nullable(); $table->string('route_leg', 5)->nullable();
$table->string('dpt_airport_id', 5); $table->string('dpt_airport_id', 5);
@@ -28,9 +27,13 @@ class CreateFlightTables extends Migration
$table->unsignedInteger('level')->nullable()->default(0); $table->unsignedInteger('level')->nullable()->default(0);
$table->unsignedDecimal('distance')->nullable()->default(0.0); $table->unsignedDecimal('distance')->nullable()->default(0.0);
$table->unsignedInteger('flight_time')->nullable(); $table->unsignedInteger('flight_time')->nullable();
$table->tinyInteger('flight_type')->default(FlightType::PASSENGER); $table->char('flight_type', 1)->default(FlightType::SCHED_PAX);
$table->text('route')->nullable(); $table->text('route')->nullable();
$table->text('notes')->nullable(); $table->text('notes')->nullable();
$table->boolean('scheduled')->default(false)->nullable();
$table->unsignedTinyInteger('days')->nullable();
$table->date('start_date')->nullable();
$table->date('end_date')->nullable();
$table->boolean('has_bid')->default(false); $table->boolean('has_bid')->default(false);
$table->boolean('active')->default(true); $table->boolean('active')->default(true);
$table->timestamps(); $table->timestamps();
@@ -43,7 +46,7 @@ class CreateFlightTables extends Migration
}); });
Schema::create('flight_fare', function (Blueprint $table) { Schema::create('flight_fare', function (Blueprint $table) {
$table->string('flight_id', \App\Models\Flight::ID_MAX_LENGTH); $table->string('flight_id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->unsignedInteger('fare_id'); $table->unsignedInteger('fare_id');
$table->string('price', 10)->nullable(); $table->string('price', 10)->nullable();
$table->string('cost', 10)->nullable(); $table->string('cost', 10)->nullable();
@@ -53,15 +56,36 @@ class CreateFlightTables extends Migration
$table->primary(['flight_id', 'fare_id']); $table->primary(['flight_id', 'fare_id']);
}); });
/**
* Hold a master list of fields
*/
Schema::create('flight_fields', function (Blueprint $table) { Schema::create('flight_fields', function (Blueprint $table) {
$table->increments('id'); $table->increments('id');
$table->string('flight_id', \App\Models\Flight::ID_MAX_LENGTH); $table->string('name', 50);
$table->string('slug', 50)->nullable();
});
/**
* The values for the actual fields
*/
Schema::create('flight_field_values', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('flight_id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->string('name', 50); $table->string('name', 50);
$table->text('value'); $table->text('value');
$table->timestamps(); $table->timestamps();
$table->index('flight_id'); $table->index('flight_id');
}); });
Schema::create('flight_subfleet', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('subfleet_id');
$table->string('flight_id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->index(['subfleet_id', 'flight_id']);
$table->index(['flight_id', 'subfleet_id']);
});
} }
/** /**
@@ -73,6 +97,7 @@ class CreateFlightTables extends Migration
{ {
Schema::drop('flight_fields'); Schema::drop('flight_fields');
Schema::drop('flight_fare'); Schema::drop('flight_fare');
Schema::drop('flight_subfleet');
Schema::drop('flights'); Schema::drop('flights');
} }
} }
@@ -1,11 +1,10 @@
<?php <?php
use App\Models\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class CreateRanksTable extends Migration class CreateRanksTable extends Migration
{ {
/** /**
* Run the migrations. * Run the migrations.
* *
@@ -16,8 +15,10 @@ class CreateRanksTable extends Migration
Schema::create('ranks', function (Blueprint $table) { Schema::create('ranks', function (Blueprint $table) {
$table->increments('id'); $table->increments('id');
$table->string('name', 50); $table->string('name', 50);
$table->string('image_link')->nullable(); $table->string('image_url')->nullable();
$table->unsignedInteger('hours')->default(0); $table->unsignedInteger('hours')->default(0);
$table->unsignedDecimal('acars_base_pay_rate')->nullable()->default(0);
$table->unsignedDecimal('manual_base_pay_rate')->nullable()->default(0);
$table->boolean('auto_approve_acars')->nullable()->default(false); $table->boolean('auto_approve_acars')->nullable()->default(false);
$table->boolean('auto_approve_manual')->nullable()->default(false); $table->boolean('auto_approve_manual')->nullable()->default(false);
$table->boolean('auto_promote')->nullable()->default(true); $table->boolean('auto_promote')->nullable()->default(true);
@@ -31,9 +32,11 @@ class CreateRanksTable extends Migration
*/ */
$ranks = [ $ranks = [
[ [
'id' => 1, 'id' => 1,
'name' => 'New Pilot', 'name' => 'New Pilot',
'hours' => 0, 'hours' => 0,
'acars_base_pay_rate' => 50,
'manual_base_pay_rate' => 25,
] ]
]; ];
@@ -1,63 +1,47 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
/**
* Class CreateSubfleetTables
*/
class CreateSubfleetTables extends Migration class CreateSubfleetTables extends Migration
{ {
/**
* Run the migrations.
*
* @return void
*/
public function up() public function up()
{ {
Schema::create('subfleets', function (Blueprint $table) { Schema::create('subfleets', function (Blueprint $table) {
$table->increments('id'); $table->increments('id');
$table->unsignedInteger('airline_id')->nullable(); $table->unsignedInteger('airline_id')->nullable();
$table->string('type', 50)->unique();
$table->string('name', 50); $table->string('name', 50);
$table->string('type', 50); $table->unsignedDecimal('cost_block_hour')->default(0)->nullable();
$table->unsignedDecimal('cost_delay_minute')->default(0)->nullable();
$table->unsignedTinyInteger('fuel_type')->nullable(); $table->unsignedTinyInteger('fuel_type')->nullable();
$table->unsignedDecimal('ground_handling_multiplier')->nullable()->default(100);
$table->unsignedDecimal('cargo_capacity')->nullable(); $table->unsignedDecimal('cargo_capacity')->nullable();
$table->unsignedDecimal('fuel_capacity')->nullable(); $table->unsignedDecimal('fuel_capacity')->nullable();
$table->unsignedDecimal('gross_weight')->nullable(); $table->unsignedDecimal('gross_weight')->nullable();
$table->timestamps(); $table->timestamps();
}); });
Schema::create('subfleet_expenses', function(Blueprint $table) {
$table->unsignedBigInteger('subfleet_id');
$table->string('name', 50);
$table->unsignedDecimal('cost');
$table->primary(['subfleet_id', 'name']);
});
Schema::create('subfleet_fare', function (Blueprint $table) { Schema::create('subfleet_fare', function (Blueprint $table) {
$table->unsignedInteger('subfleet_id'); $table->unsignedInteger('subfleet_id');
$table->unsignedInteger('fare_id'); $table->unsignedInteger('fare_id');
$table->unsignedDecimal('price')->nullable(); $table->string('price')->nullable();
$table->unsignedDecimal('cost')->nullable(); $table->string('cost')->nullable();
$table->unsignedInteger('capacity')->nullable(); $table->string('capacity')->nullable();
$table->timestamps(); $table->timestamps();
$table->primary(['subfleet_id', 'fare_id']); $table->primary(['subfleet_id', 'fare_id']);
$table->index(['fare_id', 'subfleet_id']); $table->index(['fare_id', 'subfleet_id']);
}); });
Schema::create('subfleet_flight', function(Blueprint $table) { Schema::create('subfleet_rank', function (Blueprint $table) {
$table->unsignedInteger('subfleet_id');
$table->string('flight_id', 12);
$table->primary(['subfleet_id', 'flight_id']);
$table->index(['flight_id', 'subfleet_id']);
});
Schema::create('subfleet_rank', function(Blueprint $table) {
$table->unsignedInteger('rank_id'); $table->unsignedInteger('rank_id');
$table->unsignedInteger('subfleet_id'); $table->unsignedInteger('subfleet_id');
$table->unsignedDecimal('acars_pay')->nullable(); $table->string('acars_pay')->nullable();
$table->unsignedDecimal('manual_pay')->nullable(); $table->string('manual_pay')->nullable();
$table->primary(['rank_id', 'subfleet_id']); $table->primary(['rank_id', 'subfleet_id']);
$table->index(['subfleet_id', 'rank_id']); $table->index(['subfleet_id', 'rank_id']);
@@ -72,9 +56,7 @@ class CreateSubfleetTables extends Migration
public function down() public function down()
{ {
Schema::dropIfExists('subfleets'); Schema::dropIfExists('subfleets');
Schema::dropIfExists('subfleet_expenses');
Schema::dropIfExists('subfleet_fare'); Schema::dropIfExists('subfleet_fare');
Schema::dropIfExists('subfleet_flight');
Schema::dropIfExists('subfleet_rank'); Schema::dropIfExists('subfleet_rank');
} }
} }
@@ -1,14 +1,13 @@
<?php <?php
use App\Interfaces\Migration;
use App\Models\Enums\FlightType; use App\Models\Enums\FlightType;
use App\Models\Enums\PirepState; use App\Models\Enums\PirepState;
use App\Models\Enums\PirepStatus; use App\Models\Enums\PirepStatus;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class CreatePirepTables extends Migration class CreatePirepTables extends Migration
{ {
/** /**
* Run the migrations. * Run the migrations.
* *
@@ -17,19 +16,20 @@ class CreatePirepTables extends Migration
public function up() public function up()
{ {
Schema::create('pireps', function (Blueprint $table) { Schema::create('pireps', function (Blueprint $table) {
$table->string('id', \App\Models\Pirep::ID_MAX_LENGTH); $table->string('id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->unsignedInteger('user_id'); $table->unsignedInteger('user_id');
$table->unsignedInteger('airline_id'); $table->unsignedInteger('airline_id');
$table->unsignedInteger('aircraft_id')->nullable(); $table->unsignedInteger('aircraft_id')->nullable();
$table->string('flight_id', \App\Models\Flight::ID_MAX_LENGTH)->nullable();
$table->string('flight_number', 10)->nullable(); $table->string('flight_number', 10)->nullable();
$table->string('route_code', 5)->nullable(); $table->string('route_code', 5)->nullable();
$table->string('route_leg', 5)->nullable(); $table->string('route_leg', 5)->nullable();
$table->char('flight_type', 1)->default(FlightType::SCHED_PAX);
$table->string('dpt_airport_id', 5); $table->string('dpt_airport_id', 5);
$table->string('arr_airport_id', 5); $table->string('arr_airport_id', 5);
$table->unsignedInteger('level')->nullable(); $table->unsignedInteger('level')->nullable();
$table->unsignedDecimal('distance')->nullable(); $table->unsignedDecimal('distance')->nullable();
$table->unsignedDecimal('planned_distance')->nullable(); $table->unsignedDecimal('planned_distance')->nullable();
$table->unsignedInteger('block_time')->nullable();
$table->unsignedInteger('flight_time')->nullable(); $table->unsignedInteger('flight_time')->nullable();
$table->unsignedInteger('planned_flight_time')->nullable(); $table->unsignedInteger('planned_flight_time')->nullable();
$table->unsignedDecimal('zfw')->nullable(); $table->unsignedDecimal('zfw')->nullable();
@@ -39,53 +39,40 @@ class CreatePirepTables extends Migration
$table->text('route')->nullable(); $table->text('route')->nullable();
$table->text('notes')->nullable(); $table->text('notes')->nullable();
$table->unsignedTinyInteger('source')->nullable()->default(0); $table->unsignedTinyInteger('source')->nullable()->default(0);
$table->string('source_name', 25)->nullable(); $table->string('source_name', 50)->nullable();
$table->tinyInteger('flight_type')->default(FlightType::PASSENGER);
$table->tinyInteger('state')->default(PirepState::PENDING); $table->tinyInteger('state')->default(PirepState::PENDING);
$table->tinyInteger('status')->default(PirepStatus::SCHEDULED); $table->char('status', 3)->default(PirepStatus::SCHEDULED);
$table->dateTime('submitted_at')->nullable();
$table->dateTime('block_off_time')->nullable();
$table->dateTime('block_on_time')->nullable();
$table->timestamps(); $table->timestamps();
$table->primary('id'); $table->primary('id');
$table->index('user_id'); $table->index('user_id');
$table->index('flight_id'); $table->index('flight_number');
$table->index('dpt_airport_id'); $table->index('dpt_airport_id');
$table->index('arr_airport_id'); $table->index('arr_airport_id');
}); });
Schema::create('pirep_comments', function (Blueprint $table) { Schema::create('pirep_comments', function (Blueprint $table) {
$table->bigIncrements('id'); $table->bigIncrements('id');
$table->string('pirep_id', \App\Models\Pirep::ID_MAX_LENGTH); $table->string('pirep_id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->unsignedInteger('user_id'); $table->unsignedInteger('user_id');
$table->text('comment'); $table->text('comment');
$table->timestamps(); $table->timestamps();
}); });
/*
* Financial tables/fields
*/
Schema::create('pirep_expenses', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('pirep_id', \App\Models\Pirep::ID_MAX_LENGTH);
$table->string('name');
$table->double('value')->nullable();
$table->index('pirep_id');
});
Schema::create('pirep_fares', function (Blueprint $table) { Schema::create('pirep_fares', function (Blueprint $table) {
$table->bigIncrements('id'); $table->bigIncrements('id');
$table->string('pirep_id', \App\Models\Pirep::ID_MAX_LENGTH); $table->string('pirep_id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->unsignedBigInteger('fare_id'); $table->unsignedInteger('fare_id');
$table->unsignedInteger('count')->nullable(); $table->unsignedInteger('count')->nullable()->default(0);
$table->index('pirep_id'); $table->index('pirep_id');
}); });
/*
* Additional PIREP data
*/
Schema::create('pirep_fields', function (Blueprint $table) { Schema::create('pirep_fields', function (Blueprint $table) {
$table->bigIncrements('id'); $table->increments('id');
$table->string('name', 50); $table->string('name', 50);
$table->string('slug', 50)->nullable(); $table->string('slug', 50)->nullable();
$table->boolean('required')->nullable()->default(false); $table->boolean('required')->nullable()->default(false);
@@ -93,8 +80,9 @@ class CreatePirepTables extends Migration
Schema::create('pirep_field_values', function (Blueprint $table) { Schema::create('pirep_field_values', function (Blueprint $table) {
$table->bigIncrements('id'); $table->bigIncrements('id');
$table->string('pirep_id', \App\Models\Pirep::ID_MAX_LENGTH); $table->string('pirep_id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->string('name', 50); $table->string('name', 50);
$table->string('slug', 50)->nullable();
$table->string('value')->nullable(); $table->string('value')->nullable();
$table->string('source')->nullable(); $table->string('source')->nullable();
$table->timestamps(); $table->timestamps();
@@ -112,7 +100,6 @@ class CreatePirepTables extends Migration
{ {
Schema::dropIfExists('pireps'); Schema::dropIfExists('pireps');
Schema::dropIfExists('pirep_comments'); Schema::dropIfExists('pirep_comments');
Schema::dropIfExists('pirep_expenses');
Schema::dropIfExists('pirep_fares'); Schema::dropIfExists('pirep_fares');
Schema::dropIfExists('pirep_fields'); Schema::dropIfExists('pirep_fields');
Schema::dropIfExists('pirep_field_values'); Schema::dropIfExists('pirep_field_values');
@@ -1,6 +1,6 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -13,10 +13,10 @@ class CreateBidsTable extends Migration
*/ */
public function up() public function up()
{ {
Schema::create('user_bids', function (Blueprint $table) { Schema::create('bids', function (Blueprint $table) {
$table->increments('id'); $table->increments('id');
$table->unsignedInteger('user_id'); $table->unsignedInteger('user_id');
$table->string('flight_id', \App\Models\Flight::ID_MAX_LENGTH); $table->string('flight_id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->timestamps(); $table->timestamps();
$table->index('user_id'); $table->index('user_id');
@@ -31,6 +31,6 @@ class CreateBidsTable extends Migration
*/ */
public function down() public function down()
{ {
Schema::dropIfExists('user_bids'); Schema::dropIfExists('bids');
} }
} }
@@ -1,6 +1,6 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -1,6 +1,6 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -1,6 +1,6 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -1,6 +1,6 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -15,7 +15,7 @@ class CreateAcarsTables extends Migration
{ {
Schema::create('acars', function (Blueprint $table) { Schema::create('acars', function (Blueprint $table) {
$table->string('id', 12); $table->string('id', 12);
$table->string('pirep_id', \App\Models\Pirep::ID_MAX_LENGTH); $table->string('pirep_id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->unsignedTinyInteger('type'); $table->unsignedTinyInteger('type');
$table->unsignedInteger('nav_type')->nullable(); $table->unsignedInteger('nav_type')->nullable();
$table->unsignedInteger('order')->default(0); $table->unsignedInteger('order')->default(0);
@@ -1,6 +1,6 @@
<?php <?php
use App\Models\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
class CreateStatsTable extends Migration class CreateStatsTable extends Migration
@@ -22,7 +22,6 @@ class CreateStatsTable extends Migration
$table->primary('id'); $table->primary('id');
$table->timestamps(); $table->timestamps();
}); });
/*$this->addCounterGroups([ /*$this->addCounterGroups([
'flights' => 1, 'flights' => 1,
]); ]);
@@ -1,6 +1,6 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -0,0 +1,53 @@
<?php
use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAwardsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('awards', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description')->nullable();
$table->text('image_url')->nullable();
# ref fields are expenses tied to some model object
# EG, the airports has an internal expense for gate costs
$table->string('ref_model')->nullable();
$table->text('ref_model_params')->nullable();
#$table->string('ref_model_id', 36)->nullable();
$table->timestamps();
$table->index(['ref_model']);
});
Schema::create('user_awards', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('award_id');
$table->timestamps();
$table->index(['user_id', 'award_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('awards');
Schema::dropIfExists('user_awards');
}
}
@@ -0,0 +1,37 @@
<?php
use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateExpensesTable extends Migration
{
public function up()
{
Schema::create('expenses', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('airline_id')->nullable();
$table->string('name');
$table->unsignedInteger('amount');
$table->char('type');
$table->boolean('charge_to_user')->nullable()->default(false);
$table->boolean('multiplier')->nullable()->default(0);
$table->boolean('active')->nullable()->default(true);
# ref fields are expenses tied to some model object
# EG, the airports has an internal expense for gate costs
$table->string('ref_model')->nullable();
$table->string('ref_model_id', 36)->nullable();
$table->timestamps();
$table->index(['ref_model', 'ref_model_id']);
});
}
public function down()
{
Schema::dropIfExists('expenses');
}
}
@@ -0,0 +1,46 @@
<?php
use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateJournalTransactionsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('journal_transactions', function (Blueprint $table) {
$table->char('id', 36)->unique();
$table->string('transaction_group')->nullable();
$table->integer('journal_id');
$table->unsignedBigInteger('credit')->nullable();
$table->unsignedBigInteger('debit')->nullable();
$table->char('currency', 5);
$table->text('memo')->nullable();
$table->string('tags')->nullable();
$table->string('ref_model', 50)->nullable();
$table->string('ref_model_id', 36)->nullable();
$table->timestamps();
$table->date('post_date');
$table->primary('id');
$table->index('journal_id');
$table->index('transaction_group');
$table->index(['ref_model', 'ref_model_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('journal_transactions');
}
}
@@ -0,0 +1,36 @@
<?php
use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateJournalsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('journals', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('ledger_id')->nullable();
$table->unsignedTinyInteger('type')->default(0);
$table->bigInteger('balance')->default(0);
$table->string('currency', 5);
$table->nullableMorphs('morphed');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('journals');
}
}
@@ -0,0 +1,33 @@
<?php
use App\Interfaces\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLedgersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ledgers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->enum('type', ['asset', 'liability', 'equity', 'income', 'expense']);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('ledgers');
}
}
@@ -0,0 +1,41 @@
<?php
use App\Interfaces\Migration;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
class CreateFilesTable extends Migration
{
/**
* Create the files table. Acts as a morphable
* @return void
*/
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->string('id', \App\Interfaces\Model::ID_MAX_LENGTH);
$table->string('name');
$table->string('description')->nullable();
$table->string('disk')->nullable();
$table->string('path');
$table->boolean('public')->default(true);
$table->unsignedInteger('download_count')->default(0);
$table->string('ref_model', 50)->nullable();
$table->string('ref_model_id', 36)->nullable();
$table->timestamps();
$table->primary('id');
$table->index(['ref_model', 'ref_model_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('files');
}
}
+6 -5
View File
@@ -9,24 +9,25 @@ class DatabaseSeeder extends Seeder
* @var array * @var array
*/ */
public static $seed_mapper = [ public static $seed_mapper = [
'local' => 'dev', 'local' => 'dev',
'qa' => 'dev', 'qa' => 'dev',
'staging' => 'dev', 'staging' => 'dev',
]; ];
/** /**
* Run the database seeds. * Run the database seeds.
* @throws Exception
*/ */
public function run() public function run()
{ {
$env = App::environment(); $env = App::environment();
if(array_key_exists($env, self::$seed_mapper)) { if (array_key_exists($env, self::$seed_mapper)) {
$env = self::$seed_mapper[$env]; $env = self::$seed_mapper[$env];
} }
$path = database_path('seeds/'.$env.'.yml'); $path = database_path('seeds/'.$env.'.yml');
if(!file_exists($path)) { if (!file_exists($path)) {
$path = database_path('seeds/prod.yml'); $path = database_path('seeds/prod.yml');
} }
+351 -72
View File
@@ -75,18 +75,34 @@ ranks:
- id: 2 - id: 2
name: Junior First Officer name: Junior First Officer
hours: 10 hours: 10
acars_base_pay_rate: 100
manual_base_pay_rate: 90
- id: 3 - id: 3
name: First Officer name: First Officer
hours: 15 hours: 15
acars_base_pay_rate: 250
manual_base_pay_rate: 200
auto_approve_acars: 1 auto_approve_acars: 1
auto_approve_manual: 1 auto_approve_manual: 1
- id: 4 - id: 4
name: Senior Captain name: Senior Captain
hours: 20 hours: 20
acars_base_pay_rate: 500
manual_base_pay_rate: 400
auto_approve_acars: 1 auto_approve_acars: 1
auto_approve_manual: 1 auto_approve_manual: 1
auto_promote: 0 auto_promote: 0
awards:
- id: 1
name: Pilot 50 flights
description: When a pilot has 50 flights, give this award
image_url:
ref_model: App\Awards\PilotFlightAwards
ref_model_params: 50
created_at: now
updated_at: now
news: news:
- id: 1 - id: 1
user_id: 1 user_id: 1
@@ -115,6 +131,7 @@ airports:
lat: 30.1945278 lat: 30.1945278
lon: -97.6698889 lon: -97.6698889
hub: 1 hub: 1
ground_handling_cost: 100
- id: KJFK - id: KJFK
iata: JFK iata: JFK
icao: KJFK icao: KJFK
@@ -125,51 +142,7 @@ airports:
lat: 40.6399257 lat: 40.6399257
lon: -73.7786950 lon: -73.7786950
hub: 1 hub: 1
- id: KBWI ground_handling_cost: 250
iata: BWI
icao: KBWI
name: Baltimore/Washington International Thurgood Marshall Airport
location: Baltimore, MD
country: United States
timezone: America/New_York
lat: 39.1754
lon: -76.6683
- id: KIAH
iata: IAH
icao: KIAH
name: George Bush Intercontinental Houston Airport
location: Houston, TX
country: United States
timezone: America/Chicago
lat: 29.9844
lon: -95.3414
- id: KORD
iata: ORD
icao: KORD
name: Chicago O'Hare International Airport
location: Chicago, IL
country: United States
timezone: America/Chicago
lat: 41.9786
lon: -87.9048
- id: KDFW
iata: DFW
icao: KDFW
name: Dallas Fort Worth International Airport
location: Dallas, TX
country: United States
timezone: America/Chicago
lat: 32.8968
lon: -97.038
- id: EFHK
iata: HEL
icao: EFHK
name: Helsinki Vantaa Airport
location: Helsinki
country: Finland
timezone: Europe/Helsinki
lat: 60.3172
lon: 24.9633
- id: EGLL - id: EGLL
iata: LHR iata: LHR
icao: EGLL icao: EGLL
@@ -178,6 +151,7 @@ airports:
timezone: Europe/London timezone: Europe/London
lat: 51.4775 lat: 51.4775
lon: -0.4614 lon: -0.4614
ground_handling_cost: 500
- id: LGRP - id: LGRP
iata: RHO iata: RHO
icao: LGRP icao: LGRP
@@ -187,20 +161,87 @@ airports:
timezone: Europe/Athens timezone: Europe/Athens
lat: 36.4054 lat: 36.4054
lon: 28.0862 lon: 28.0862
ground_handling_cost: 50
# #
aircraft: aircraft:
- id: 1 - id: 1
subfleet_id: 1 subfleet_id: 1
name: Boeing 747-400 airport_id: KJFK
name: Boeing 747-438
registration: 001Z registration: 001Z
status: A
- id: 2 - id: 2
subfleet_id: 2 subfleet_id: 2
airport_id: LGRP
name: Boeing 777-200 name: Boeing 777-200
registration: C202 registration: C202
status: A
- id: 3 - id: 3
subfleet_id: 1 subfleet_id: 1
airport_id: KAUS
name: Boeing 747-412 name: Boeing 747-412
registration: S2333 registration: S2333
status: A
- id: 4
subfleet_id: 1
airport_id: KAUS
name: Boeing 747-436 RETIRED
registration:
status: R
expenses:
- name: Per-Flight (no muliplier)
amount: 100
type: F
active: 1
ref_model: App\Models\Expense
- name: Per-Flight (multiplier)
amount: 100
type: F
multiplier: 1
active: 1
ref_model: App\Models\Expense
- name: Per-Flight (multiplier, on airline)
airline_id: 1
amount: 200
type: F
multiplier: 1
active: 1
ref_model: App\Models\Expense
- name: A daily fee
amount: 800
type: D
active: 1
ref_model: App\Models\Expense
- name: A monthly fee
amount: 5000
type: M
active: 1
ref_model: App\Models\Expense
- name: Catering
amount: 1000
type: F
active: 1
ref_model: App\Models\Subfleet
ref_model_id: 1
created_at: now
updated_at: now
- name: Catering Staff
amount: 1000
type: D
active: 1
ref_model: App\Models\Subfleet
ref_model_id: 1
created_at: now
updated_at: now
- name: Maintenance
amount: 1000
type: D
active: 1
ref_model: App\Models\Aircraft
ref_model_id: 1
created_at: now
updated_at: now
fares: fares:
- id: 1 - id: 1
@@ -222,12 +263,22 @@ fares:
subfleets: subfleets:
- id: 1 - id: 1
airline_id: 1 airline_id: 1
name: 747-400 Winglets name: 747-43X RB211-524G
type: 744W type: 744-3X-RB211
cost_block_hour: 1000
ground_handling_multiplier: 200
- id: 2 - id: 2
airline_id: 1 airline_id: 1
name: 777-200 LR name: 777-222ER GE90-76B
type: 772-LR type: 772-22ER-GE90-76B
cost_block_hour: 500
ground_handling_multiplier: 150
- id: 3
airline_id: 1
name: 777-367 ER GE90-115B
type: 772-36ER-GE90-115B
cost_block_hour: 100
ground_handling_multiplier: 150
# add a few mods to aircraft and fares # add a few mods to aircraft and fares
subfleet_fare: subfleet_fare:
@@ -239,11 +290,11 @@ subfleet_fare:
capacity: 400 capacity: 400
- subfleet_id: 1 - subfleet_id: 1
fare_id: 2 fare_id: 2
capacity: 20 price: 120%
- subfleet_id: 1 - subfleet_id: 1
fare_id: 3 fare_id: 3
price: 1000 price: 1000
capacity: 10 capacity: 110%
# Fare classes on the 777 # Fare classes on the 777
- subfleet_id: 2 - subfleet_id: 2
@@ -252,10 +303,6 @@ subfleet_fare:
fare_id: 3 fare_id: 3
capacity: 10 capacity: 10
subfleet_flight:
- subfleet_id: 1
flight_id: flightid_1
subfleet_rank: subfleet_rank:
- rank_id: 1 - rank_id: 1
subfleet_id: 1 subfleet_id: 1
@@ -271,6 +318,8 @@ flights:
level: 360 level: 360
dpt_time: 6PM CST dpt_time: 6PM CST
arr_time: 11PM EST arr_time: 11PM EST
flight_time: 240
flight_type: J
created_at: NOW created_at: NOW
updated_at: NOW updated_at: NOW
- id: flightid_2 - id: flightid_2
@@ -281,6 +330,8 @@ flights:
arr_airport_id: LGRP arr_airport_id: LGRP
dpt_time: 9AM CST dpt_time: 9AM CST
arr_time: 1030AM CST arr_time: 1030AM CST
flight_time: 30
flight_type: J
route: PITZZ4 MNURE WLEEE4 route: PITZZ4 MNURE WLEEE4
created_at: NOW created_at: NOW
updated_at: NOW updated_at: NOW
@@ -289,8 +340,10 @@ flights:
flight_number: 6028 flight_number: 6028
route_code: A route_code: A
route_leg: 1 route_leg: 1
dpt_airport_id: KIAH dpt_airport_id: EGLL
arr_airport_id: KAUS arr_airport_id: KJFK
flight_time: 480
flight_type: J
dpt_time: 9AM CST dpt_time: 9AM CST
arr_time: 1030AM CST arr_time: 1030AM CST
route: PITZZ4 MNURE WLEEE4 route: PITZZ4 MNURE WLEEE4
@@ -298,6 +351,12 @@ flights:
updated_at: NOW updated_at: NOW
flight_fields: flight_fields:
- name: Departure Gate
slug: departure_gate
- name: Arrival Gate
slug: arrival_gate
flight_field_values:
- id: 1 - id: 1
flight_id: flightid_1 flight_id: flightid_1
name: cost index name: cost index
@@ -307,7 +366,11 @@ flight_fields:
name: cost index name: cost index
value: 100 value: 100
user_bids: flight_subfleet:
- subfleet_id: 1
flight_id: flightid_1
bids:
- id: 100 - id: 100
user_id: 1 user_id: 1
flight_id: flightid_1 flight_id: flightid_1
@@ -319,48 +382,78 @@ pireps:
- id: pirepid_1 - id: pirepid_1
user_id: 1 user_id: 1
airline_id: 1 airline_id: 1
flight_id: flightid_1
flight_number: 100 flight_number: 100
aircraft_id: 1 aircraft_id: 1
dpt_airport_id: KAUS dpt_airport_id: KAUS
arr_airport_id: KJFK arr_airport_id: KJFK
block_off_time: 2018-04-04T12:42:36+00:00
block_on_time: 2018-04-04T16:42:36+00:00
flight_time: 180 # 6 hours flight_time: 180 # 6 hours
state: 1 state: 1 # accepted
status: 0
source: 1
flight_type: J
route: KAUS SID TNV J87 IAH J2 LCH J22 MEI J239 ATL J52 AJFEB J14 BYJAC Q60 JAXSN J14 COLIN J61 HUBBS J55 SIE STAR KJFK route: KAUS SID TNV J87 IAH J2 LCH J22 MEI J239 ATL J52 AJFEB J14 BYJAC Q60 JAXSN J14 COLIN J61 HUBBS J55 SIE STAR KJFK
notes: just a pilot report notes: just a pilot report
created_at: NOW submitted_at: 2018-04-04T16:50:36+00:00
updated_at: NOW created_at: 2018-04-04T16:50:36+00:00
updated_at: 2018-04-04T17:00:36+00:00
- id: pirepid_2 - id: pirepid_2
user_id: 1 user_id: 1
airline_id: 1 airline_id: 1
flight_id: flightid_2 flight_number: 2023
flight_number: 101 aircraft_id: 2
aircraft_id: 1
dpt_airport_id: LGRP dpt_airport_id: LGRP
arr_airport_id: LGRP arr_airport_id: LGRP
flight_time: 180 # 6 hours flight_time: 180 # 6 hours
state: 1 state: 1
flight_type: J
route: PLMMR2 SPA Q22 BEARI FAK PHLBO3 route: PLMMR2 SPA Q22 BEARI FAK PHLBO3
notes: just a pilot report notes: just a pilot report
source: 1 source: 1 # pending
source_name: sample source_name: sample
submitted_at: NOW
created_at: NOW created_at: NOW
updated_at: NOW updated_at: NOW
- id: pirepid_3 - id: pirepid_3
user_id: 1 user_id: 1
airline_id: 1 airline_id: 1
flight_id: flightid_2 flight_number: 300
flight_number: 101 aircraft_id: 3
aircraft_id: 1
dpt_airport_id: KJFK dpt_airport_id: KJFK
arr_airport_id: KAUS arr_airport_id: KAUS
flight_time: 180 # 6 hours flight_time: 180 # 6 hours
state: 1 state: 1 # pending
source: 0 # manual
flight_type: J
route: PLMMR2 SPA Q22 BEARI FAK PHLBO3 route: PLMMR2 SPA Q22 BEARI FAK PHLBO3
notes: just a pilot report notes: just a pilot report
submitted_at: NOW
created_at: NOW created_at: NOW
updated_at: NOW updated_at: NOW
pirep_fares:
- id: 1
pirep_id: pirepid_1
fare_id: 1
count: 300
- id: 2
pirep_id: pirepid_1
fare_id: 2
count: 25
- id: 3
pirep_id: pirepid_1
fare_id: 3
count: 10
- id: 4
pirep_id: pirepid_2
fare_id: 1
count: 200
- id: 5
pirep_id: pirepid_2
fare_id: 3
count: 15
pirep_fields: pirep_fields:
- id: 1 - id: 1
name: departure gate name: departure gate
@@ -375,7 +468,14 @@ pirep_field_values:
- id: 1 - id: 1
pirep_id: pirepid_1 pirep_id: pirepid_1
name: arrival gate name: arrival gate
value: B14 slug: arrival_gate
value: 10
source: manual
- id: 2
pirep_id: pirepid_1
name: departure gate
slug: departure_gate
value: B32
source: manual source: manual
pirep_comments: pirep_comments:
@@ -391,3 +491,182 @@ pirep_comments:
comment: Another comment comment: Another comment
created_at: now created_at: now
updated_at: now updated_at: now
journals:
-
id: 1
ledger_id: null
type: 0
balance: 7870000
currency: USD
morphed_type: App\Models\Airline
morphed_id: 1
created_at: '2018-03-06 12:33:45'
updated_at: '2018-03-06 12:34:15'
-
id: 2
ledger_id: null
type: 1
balance: 15000
currency: USD
morphed_type: App\Models\User
morphed_id: 1
created_at: '2018-03-06 12:33:45'
updated_at: '2018-03-06 12:34:15'
journal_transactions:
-
id: 2cbb5990-c70c-40a8-8381-05b6402a96b4
transaction_group: 'Pilot Pay'
journal_id: 2
credit: 15000
debit: null
currency: USD
memo: 'Pilot Payment @ 50'
tags: "pilot_pay"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: '2018-03-06 12:34:15'
updated_at: '2018-03-06 12:34:15'
post_date: '2018-03-06 12:34:15'
-
id: 3471fb16-0afd-4815-8b0c-f92771274063
transaction_group: 'Expense: Per-Flight (no muliplier)'
journal_id: 1
credit: null
debit: 10000
currency: USD
memo: 'Expense: Per-Flight (no muliplier)'
tags: "expense"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: '2018-03-06 12:34:15'
updated_at: '2018-03-06 12:34:15'
post_date: '2018-03-06 12:34:15'
-
id: 37f21468-ebad-4850-8557-db310ca45eb4
transaction_group: Fares
journal_id: 1
credit: 6000000
debit: 0
currency: USD
memo: 'Fares Y300; price: 200, cost: 0'
tags: "fare"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: '2018-03-06 12:34:15'
updated_at: '2018-03-06 12:34:15'
post_date: '2018-03-06 12:34:15'
-
id: 3e933972-07ef-4bb2-b1e1-90ef7e8871c6
transaction_group: 'Expense: Per-Flight (multiplier, on airline)'
journal_id: 1
credit: null
debit: 20000
currency: USD
memo: 'Expense: Per-Flight (multiplier, on airline)'
tags: "expense"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: '2018-03-06 12:34:15'
updated_at: '2018-03-06 12:34:15'
post_date: '2018-03-06 12:34:15'
-
id: 522d8032-4ca0-4d6d-b7af-613be4bf281c
transaction_group: 'Expense: Per-Flight (multiplier)'
journal_id: 1
credit: null
debit: 10000
currency: USD
memo: 'Expense: Per-Flight (multiplier)'
tags: "expense"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: '2018-03-06 12:34:15'
updated_at: '2018-03-06 12:34:15'
post_date: '2018-03-06 12:34:15'
-
id: a9bca611-c251-4fde-9f28-206d4debeb01
transaction_group: 'Subfleet: Catering (747-43X RB211-524G)'
journal_id: 1
credit: null
debit: 100000
currency: USD
memo: 'Subfleet Expense: Catering (747-43X RB211-524G)'
tags: "subfleet"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: '2018-03-06 12:34:15'
updated_at: '2018-03-06 12:34:15'
post_date: '2018-03-06 12:34:15'
-
id: c3ff6a6d-03d0-4744-8678-e27329462dcb
transaction_group: Fares
journal_id: 1
credit: 1000000
debit: 0
currency: USD
memo: 'Fares F10; price: 1000, cost: 0'
tags: "fare"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: '2018-03-06 12:34:15'
updated_at: '2018-03-06 12:34:15'
post_date: '2018-03-06 12:34:15'
-
id: c4e05ec1-530f-4897-92e8-787bdec8a0a1
transaction_group: 'Pilot Pay'
journal_id: 1
credit: null
debit: 15000
currency: USD
memo: 'Pilot Payment @ 50'
tags: "pilot_pay"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: now
updated_at: now
post_date: now
-
id: ed516367-eeb9-4a09-bfb7-531ec4be2f93
transaction_group: Fares
journal_id: 1
credit: 1100000
debit: 0
currency: USD
memo: 'Fares B10; price: 1100, cost: 0'
tags: "fare"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: now
updated_at: now
post_date: now
-
id: f3f8585e-894c-4491-b19b-d07b6ad20208
transaction_group: 'Ground Handling'
journal_id: 1
credit: null
debit: 75000
currency: USD
memo: 'Ground Handling'
tags: "ground_handling"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: now
updated_at: now
post_date: now
-
id: 1bd1616c-eaa4-4ab9-b5c1-441004ceef14
transaction_group: 'Subfleet 744-3X-RB211'
journal_id: 1
credit: null
debit: 300000
currency: USD
memo: 'Subfleet 744-3X-RB211: Block Time Cost'
tags: "subfleet"
ref_model: App\Models\Pirep
ref_model_id: pirepid_1
created_at: now
updated_at: now
post_date: now
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Events;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* This event is dispatched when the monthly cron is run
* It happens after all of the default nightly tasks
* @package App\Events
*/
class CronMonthly
{
use Dispatchable, SerializesModels;
/**
* CronMonthly constructor.
*/
public function __construct()
{
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Events;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* This event is dispatched when the daily cron is run
* It happens after all of the default nightly tasks
* @package App\Events
*/
class CronNightly
{
use Dispatchable, SerializesModels;
/**
* CronNightly constructor.
*/
public function __construct()
{
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Events;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* This event is dispatched when the weekly cron is run
* It happens after all of the default nightly tasks
* @package App\Events
*/
class CronWeekly
{
use Dispatchable, SerializesModels;
/**
* CronWeekly constructor.
*/
public function __construct()
{
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Events;
use App\Models\Pirep;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* This event is dispatched when the expenses for a flight report
* are collected. Your listeners should return a list of Expense
* models. Don't call save on the model!
*
* Example return:
*
* [
* new Expense([
* 'airline_id': '', # < optional field
* 'name': '',
* 'amount': [DECIMAL],
* 'type': int from ExpenseType enum class
* ]),
* ]
*
* The event caller will check the 'type' to make sure that it
* will filter out expenses that only apply to the current process
*
* The event will have a copy of the PIREP model, if it's applicable
*
* @package App\Events
*/
class Expenses
{
use Dispatchable, SerializesModels;
public $pirep;
/**
* @param Pirep|null $pirep
*/
public function __construct(Pirep $pirep = null)
{
$this->pirep = $pirep;
}
}
+7 -2
View File
@@ -7,6 +7,10 @@ use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
/**
* Class PirepAccepted
* @package App\Events
*/
class PirepAccepted class PirepAccepted
{ {
use Dispatchable, InteractsWithSockets, SerializesModels; use Dispatchable, InteractsWithSockets, SerializesModels;
@@ -14,10 +18,11 @@ class PirepAccepted
public $pirep; public $pirep;
/** /**
* Create a new event instance. * PirepAccepted constructor.
* @param Pirep $pirep
*/ */
public function __construct(Pirep $pirep) public function __construct(Pirep $pirep)
{ {
// $this->pirep = $pirep;
} }
} }
-1
View File
@@ -10,7 +10,6 @@ use Illuminate\Queue\SerializesModels;
class PirepFiled class PirepFiled
{ {
use Dispatchable, InteractsWithSockets, SerializesModels; use Dispatchable, InteractsWithSockets, SerializesModels;
public $pirep; public $pirep;
public function __construct(Pirep $pirep) public function __construct(Pirep $pirep)
+8
View File
@@ -7,12 +7,20 @@ use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
/**
* Class PirepRejected
* @package App\Events
*/
class PirepRejected class PirepRejected
{ {
use Dispatchable, InteractsWithSockets, SerializesModels; use Dispatchable, InteractsWithSockets, SerializesModels;
public $pirep; public $pirep;
/**
* PirepRejected constructor.
* @param Pirep $pirep
*/
public function __construct(Pirep $pirep) public function __construct(Pirep $pirep)
{ {
$this->pirep = $pirep; $this->pirep = $pirep;
+5
View File
@@ -7,6 +7,10 @@ use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
/**
* Class TestEvent
* @package App\Events
*/
class TestEvent class TestEvent
{ {
use Dispatchable, InteractsWithSockets, SerializesModels; use Dispatchable, InteractsWithSockets, SerializesModels;
@@ -15,6 +19,7 @@ class TestEvent
/** /**
* Create a new event instance. * Create a new event instance.
* @param User $user
*/ */
public function __construct(User $user) public function __construct(User $user)
{ {
+8
View File
@@ -7,12 +7,20 @@ use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
/**
* Class UserAccepted
* @package App\Events
*/
class UserAccepted class UserAccepted
{ {
use Dispatchable, InteractsWithSockets, SerializesModels; use Dispatchable, InteractsWithSockets, SerializesModels;
public $user; public $user;
/**
* UserAccepted constructor.
* @param User $user
*/
public function __construct(User $user) public function __construct(User $user)
{ {
$this->user = $user; $this->user = $user;
+8
View File
@@ -7,12 +7,20 @@ use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
/**
* Class UserRegistered
* @package App\Events
*/
class UserRegistered class UserRegistered
{ {
use Dispatchable, InteractsWithSockets, SerializesModels; use Dispatchable, InteractsWithSockets, SerializesModels;
public $user; public $user;
/**
* UserRegistered constructor.
* @param User $user
*/
public function __construct(User $user) public function __construct(User $user)
{ {
$this->user = $user; $this->user = $user;
+5
View File
@@ -17,6 +17,11 @@ class UserStateChanged
public $old_state, $user; public $old_state, $user;
/**
* UserStateChanged constructor.
* @param User $user
* @param $old_state
*/
public function __construct(User $user, $old_state) public function __construct(User $user, $old_state)
{ {
$this->old_state = $old_state; $this->old_state = $old_state;
+4
View File
@@ -7,6 +7,10 @@ use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
/**
* Class UserStatsChanged
* @package App\Events
*/
class UserStatsChanged class UserStatsChanged
{ {
use Dispatchable, InteractsWithSockets, SerializesModels; use Dispatchable, InteractsWithSockets, SerializesModels;
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Exceptions;
/**
* Class AircraftNotAtAirport
* @package App\Exceptions
*/
class AircraftNotAtAirport extends InternalError
{
public const FIELD = 'aircraft_id';
public const MESSAGE = 'The aircraft is not at the departure airport';
}
+7 -14
View File
@@ -1,20 +1,13 @@
<?php <?php
/**
*
*/
namespace App\Exceptions; namespace App\Exceptions;
use Symfony\Component\HttpKernel\Exception\HttpException; /**
* Class AircraftPermissionDenied
class AircraftPermissionDenied extends HttpException * @package App\Exceptions
*/
class AircraftPermissionDenied extends InternalError
{ {
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = []) public const FIELD = 'aircraft_id';
{ public const MESSAGE = 'User is not allowed to fly this aircraft';
parent::__construct(
400,
'User is not allowed to fly this aircraft',
$previous, $headers, $code
);
}
} }
+10 -5
View File
@@ -1,16 +1,21 @@
<?php <?php
/**
*
*/
namespace App\Exceptions; namespace App\Exceptions;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Class BidExists
* @package App\Exceptions
*/
class BidExists extends HttpException class BidExists extends HttpException
{ {
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = []) public function __construct(
{ string $message = null,
\Exception $previous = null,
int $code = 0,
array $headers = []
) {
parent::__construct( parent::__construct(
409, 409,
'A bid already exists for this flight', 'A bid already exists for this flight',
+14 -14
View File
@@ -51,7 +51,7 @@ class Handler extends ExceptionHandler
{ {
return [ return [
'error' => [ 'error' => [
'status' => $status_code, 'status' => $status_code,
'message' => $message, 'message' => $message,
] ]
]; ];
@@ -60,19 +60,18 @@ class Handler extends ExceptionHandler
/** /**
* Render an exception into an HTTP response. * Render an exception into an HTTP response.
* *
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
* @param \Exception $exception * @param \Exception $exception
* @return mixed * @return mixed
*/ */
public function render($request, Exception $exception) public function render($request, Exception $exception)
{ {
if ($request->expectsJson() || $request->is('api/*')) { if ($request->is('api/*')) {
$headers = []; $headers = [];
Log::error('API Error', $exception->getTrace()); Log::error('API Error', $exception->getTrace());
if($exception instanceof ModelNotFoundException || if ($exception instanceof ModelNotFoundException ||
$exception instanceof NotFoundHttpException) { $exception instanceof NotFoundHttpException) {
$error = $this->createError(404, $exception->getMessage()); $error = $this->createError(404, $exception->getMessage());
} }
@@ -88,10 +87,10 @@ class Handler extends ExceptionHandler
} }
# Create the detailed errors from the validation errors # Create the detailed errors from the validation errors
elseif($exception instanceof ValidationException) { elseif ($exception instanceof ValidationException) {
$error_messages = []; $error_messages = [];
$errors = $exception->errors(); $errors = $exception->errors();
foreach($errors as $field => $error) { foreach ($errors as $field => $error) {
$error_messages[] = implode(', ', $error); $error_messages[] = implode(', ', $error);
} }
@@ -107,7 +106,7 @@ class Handler extends ExceptionHandler
} }
# Only add trace if in dev # Only add trace if in dev
if(config('app.env') === 'dev') { if (config('app.env') === 'dev') {
$error['error']['trace'] = $exception->getTrace()[0]; $error['error']['trace'] = $exception->getTrace()[0];
} }
@@ -125,14 +124,15 @@ class Handler extends ExceptionHandler
/** /**
* Convert an authentication exception into an unauthenticated response. * Convert an authentication exception into an unauthenticated response.
* *
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception * @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response * @return \Illuminate\Http\Response
*/ */
protected function unauthenticated($request, AuthenticationException $exception) protected function unauthenticated($request, AuthenticationException $exception)
{ {
if ($request->expectsJson() || $request->is('api/*')) { if ($request->expectsJson() || $request->is('api/*')) {
$error = $this->createError(401, 'Unauthenticated'); $error = $this->createError(401, 'Unauthenticated');
return response()->json($error, 401); return response()->json($error, 401);
} }
@@ -148,13 +148,13 @@ class Handler extends ExceptionHandler
{ {
$status = $e->getStatusCode(); $status = $e->getStatusCode();
view()->replaceNamespace('errors', [ view()->replaceNamespace('errors', [
resource_path('views/layouts/' . config('phpvms.skin') . '/errors'), resource_path('views/layouts/'.config('phpvms.skin').'/errors'),
resource_path('views/errors'), resource_path('views/errors'),
__DIR__ . '/views', __DIR__.'/views',
]); ]);
if (view()->exists("errors::{$status}")) { if (view()->exists("errors::{$status}")) {
#if (view()->exists('layouts' . config('phpvms.skin') .'.errors.' .$status)) { #if (view()->exists('layouts' . config('phpvms.skin') .'.errors.' .$status)) {
return response()->view("errors::{$status}", [ return response()->view("errors::{$status}", [
'exception' => $e, 'exception' => $e,
'SKIN_NAME' => config('phpvms.skin'), 'SKIN_NAME' => config('phpvms.skin'),
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Exceptions;
use Illuminate\Validation\ValidationException;
use Validator;
use Log;
/**
* Show an internal error, bug piggyback off of the validation
* exception type - this has a place to show up in the UI as a
* flash message.
* @package App\Exceptions
*/
class InternalError extends ValidationException
{
public const FIELD = 'internal_error_message';
public const MESSAGE = '';
/**
* InternalError constructor.
* @param string|null $message
* @param null $field
*/
public function __construct(string $message = null, $field = null)
{
Log::error($message);
$validator = Validator::make([], []);
$validator->errors()->add(
$field ?? static::FIELD,
$message ?? static::MESSAGE);
parent::__construct($validator);
}
}
+10 -5
View File
@@ -1,16 +1,21 @@
<?php <?php
/**
*
*/
namespace App\Exceptions; namespace App\Exceptions;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Class PirepCancelled
* @package App\Exceptions
*/
class PirepCancelled extends HttpException class PirepCancelled extends HttpException
{ {
public function __construct(string $message = null, \Exception $previous = null, int $code = 0, array $headers = []) public function __construct(
{ string $message = null,
\Exception $previous = null,
int $code = 0,
array $headers = []
) {
parent::__construct( parent::__construct(
400, 400,
'PIREP has been cancelled, updates are not allowed', 'PIREP has been cancelled, updates are not allowed',
+4 -4
View File
@@ -1,13 +1,13 @@
<?php <?php
/**
*
*/
namespace App\Exceptions; namespace App\Exceptions;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* Class SettingNotFound
* @package App\Exceptions
*/
class SettingNotFound extends HttpException class SettingNotFound extends HttpException
{ {
} }
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace App\Exceptions;
/**
* Class UserNotAtAirport
* @package App\Exceptions
*/
class UserNotAtAirport extends InternalError
{
public const FIELD = 'dpt_airport_id';
public const MESSAGE = 'Pilot is not at the departure airport';
}
+46 -20
View File
@@ -5,25 +5,50 @@ namespace App\Facades;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Facade;
/**
* Class Utils
* @package App\Facades
*/
class Utils extends Facade class Utils extends Facade
{ {
/**
* @return string
*/
protected static function getFacadeAccessor() protected static function getFacadeAccessor()
{ {
return 'utils'; return 'utils';
} }
/**
* Simple check on the first character if it's an object or not
* @param $obj
* @return bool
*/
public static function isObject($obj)
{
if (!$obj) {
return false;
}
if ($obj[0] === '{' || $obj[0] === '[') {
return true;
}
return false;
}
/** /**
* Download a URI. If a file is given, it will save the downloaded * Download a URI. If a file is given, it will save the downloaded
* content into that file * content into that file
* @param $uri * @param $uri
* @param null $file * @param null $file
* @return string * @return string
* @throws \RuntimeException * @throws \RuntimeException
*/ */
public static function downloadUrl($uri, $file=null) public static function downloadUrl($uri, $file = null)
{ {
$opts = []; $opts = [];
if($file !== null) { if ($file !== null) {
$opts['sink'] = $file; $opts['sink'] = $file;
} }
@@ -31,21 +56,20 @@ class Utils extends Facade
$response = $client->request('GET', $uri, $opts); $response = $client->request('GET', $uri, $opts);
$body = $response->getBody()->getContents(); $body = $response->getBody()->getContents();
if($response->getHeader('content-type') === 'application/json') { if ($response->getHeader('content-type') === 'application/json') {
$body = \GuzzleHttp\json_decode($body); $body = \GuzzleHttp\json_decode($body);
} }
return $body; return $body;
} }
/** /**
* Returns a 40 character API key that a user can use * Returns a 40 character API key that a user can use
* @return string * @return string
*/ */
public static function generateApiKey() public static function generateApiKey()
{ {
$key = substr(sha1(time() . mt_rand()), 0, 20); $key = substr(sha1(time().mt_rand()), 0, 20);
return $key; return $key;
} }
@@ -60,7 +84,7 @@ class Utils extends Facade
public static function minutesToTimeString($minutes): string public static function minutesToTimeString($minutes): string
{ {
$hm = self::minutesToTimeParts($minutes); $hm = self::minutesToTimeParts($minutes);
return $hm['h']. 'h '. $hm['m'] . 'm'; return $hm['h'].'h '.$hm['m'].'m';
} }
/** /**
@@ -85,15 +109,15 @@ class Utils extends Facade
/** /**
* Convert seconds to HH MM format * Convert seconds to HH MM format
* @param $seconds * @param $seconds
* @param bool $incl_sec * @param bool $incl_sec
* @return string * @return string
*/ */
public static function secondsToTimeString($seconds, $incl_sec=false): string public static function secondsToTimeString($seconds, $incl_sec = false): string
{ {
$hms = self::secondsToTimeParts($seconds); $hms = self::secondsToTimeParts($seconds);
$format = $hms['h'].'h '.$hms['m'].'m'; $format = $hms['h'].'h '.$hms['m'].'m';
if($incl_sec) { if ($incl_sec) {
$format .= ' '.$hms['s'].'s'; $format .= ' '.$hms['s'].'s';
} }
@@ -116,7 +140,7 @@ class Utils extends Facade
*/ */
public static function secondsToMinutes($seconds) public static function secondsToMinutes($seconds)
{ {
return ceil($seconds/60); return ceil($seconds / 60);
} }
/** /**
@@ -126,18 +150,18 @@ class Utils extends Facade
*/ */
public static function minutesToHours($minutes) public static function minutesToHours($minutes)
{ {
return $minutes/60; return $minutes / 60;
} }
/** /**
* @param $hours * @param $hours
* @param null $minutes * @param null $minutes
* @return float|int * @return float|int
*/ */
public static function hoursToMinutes($hours, $minutes=null) public static function hoursToMinutes($hours, $minutes = null)
{ {
$total = (int) $hours * 60; $total = (int) $hours * 60;
if($minutes) { if ($minutes) {
$total += (int) $minutes; $total += (int) $minutes;
} }
@@ -146,12 +170,13 @@ class Utils extends Facade
/** /**
* Bitwise operator for setting days of week to integer field * Bitwise operator for setting days of week to integer field
* @param int $datefield initial datefield * @param int $datefield initial datefield
* @param array $day_enums Array of values from config("enum.days") * @param array $day_enums Array of values from config("enum.days")
* @return int * @return int
*/ */
public static function setDays(int $datefield, array $day_enums) { public static function setDays(int $datefield, array $day_enums)
foreach($day_enums as $day) { {
foreach ($day_enums as $day) {
$datefield |= $day; $datefield |= $day;
} }
@@ -161,10 +186,11 @@ class Utils extends Facade
/** /**
* Bit check if a day exists within a integer bitfield * Bit check if a day exists within a integer bitfield
* @param int $datefield datefield from database * @param int $datefield datefield from database
* @param int $day_enum Value from config("enum.days") * @param int $day_enum Value from config("enum.days")
* @return bool * @return bool
*/ */
public static function hasDay(int $datefield, int $day_enum) { public static function hasDay(int $datefield, int $day_enum)
{
return ($datefield & $day_enum) === $datefield; return ($datefield & $day_enum) === $datefield;
} }
} }

Some files were not shown because too many files have changed in this diff Show More