7.0.0-beta3 Release (#541)

* 391 Notification refactorings (#441)

* Refactor notifications to allow easier plugins

* Notification refactoring

* Formatting

* Move news to NewsService; cleanup of events

* More refactoring; added send email out for news item and the template

* Formatting

* Formatting

* Fix missing newsRepo (#445)

* Refactor and add importer to Installer module #443 (#444)

* Refactor and add importer to Installer module #443

* Refactor for finances to use in import

* Import groups into roles

* Formatting

* Formatting

* Add interface in installer for import

* Notes about importing

* Check for installer folder

* Formatting

* Fix pirep->user mapping

* Unused import

* Formatting

* Replace importer with AJAX powered; better error handling #443 (#447)

* Replace importer with AJAX powered; better error handling #443

* Formatting

* Fix command line importer

* Remove bootstrap cache (#448)

* Cleanup the bootstrap/cache directory when packaging

* Fix removal of bootstrap cache

* Formatting

* Stricter checks on ACARS API data (#451)

* Stricter checks on ACARS API data

* More checks

* Fix for flight_number check forcing to exist

* Allow nullable on flight_id

* Avoid proc_open use #455 (#456)

* Use PhpExecutableFinder() closes #457 #458 (#460)

* Use DateTimeZone instead of int for creating datetime

closes #461

* Fix CSV imports giving Storage class not found #454 (#462)

* Fix CSV imports giving Storage class not found #454

* Update yarn files for security alert

* Add PHP 7.4 support (#464)

* Add PHP 7.4 to build matrix

* DB fix

* YAML parser fix in test data

* Show versions

* Package updates

* Track used ICAOs

* 7.4 METAR parsing fix

* METAR parser fix

* Formatting

* Add meters to response units

* Call instance for unit conversion

* Return value

* Catch exception for unknown quantity

* Comment fix

* Formatting

* METAR parsing fixes on PHP 7.4

* Package updates

* More random airport ID

* More random airport ID

* Properly disable toolbar

* Semver written out to version file

* Use dev as default identifier

* Fix BindingResolutionError when debug toolbar isn't present (#465)

* Fix BindingResolutionError when debug toolbar isn't present

* Formatting

* Split the importer module out from the installer module (#468)

* Split the importer module out from the installer module

* Cleanup of unused imports

* Move updater into separate module #453

* Remove unused imports/formatting

* Disable the install and importer modules at the end of the setup

* Unused imports; update IJ style

* test explicit stage for php+mysql

* add more to matrix

* Add different MariaDB versions

* undo

* Cleanup Model doc

* Pilots cannot use the dashboard or flights without admin rights (#481)

* Use auth middleware instead of specific groups for logged in state

* Auth check for admin access

* Check user admin access for updates

* Formatting

* Allow nullable field and calculate distance if nulled for flight import #478 (#482)

* Check for no roles being attached #480 (#483)

* Return the flight fares if there are no subfleet fares #488 (#489)

* Return the flight fares if there are no subfleet fares #488

* Formatting

* Formatting

* Account for units when entering fuel amounts #493

* Search for ICAO not working properly (#496)

* /flights and /flights/search direct to the same endpoint

* Properly set the distance/planned_distance on save (#497)

* 491 Installation Error (#495)

* Disable CSRF token

* Add error handling around looking up the theme and set a default

* Note about logs in issue template

* Formatting

* Fix GeoService errors when viewing PIREP #498 (#499)

* Add new command to export a specific PIREP for debugging (#501)

* Set a default model value for airports on PIREP (#500)

* Set a default model value for airports on PIREP

* Fix airport icao reference

* Default airport models

* Catch broader exception writing out config files #491

* style

* Add reference to docs on doc site (#502)

* Properly create/update rows importing #486 (#503)

* Add base Dockerfile for Dockerhub builds (#504)

* New subfleet not being attached to an airline on import #479 (#505)

* Fix subfleet not being attached to an airline on creation in import #479

* Call airline name with optional() around subfleet

* Minor cleanup

* Search flights by subfleet #484 (#506)

* API level search of flights #484

* Add Subfleet to flights page for search

* Make the fuel used optional (#512)

* Add make to Docker container

* Add getRootDomain() to Utils (#514)

* Show admin dropdown for admin-access ability (#515)

* Show admin dropdown for admin-access ability closes #509

* Formatting

* Check user permissions on the routes #508 (#516)

* Check user permissions on the routes #508

* Formatting

* Return default value on exception for setting()

* Correct text for no subfleets #507 (#518)

* Add a public_url() helper #513 (#519)

* Reduce number of queries for update check (#520)

* Try to clear caches before updating (#522)

* Try to clear caches before updating

* Add clear-compiled to maintenance cache list

* Formatting

* Set PIREPs page to public (#526)

Set PIREPs page to public

* Fix live and route map errors #527 (#528)

* Add menu bar for mobile (#529)

* Format all blade templates to 2 spaces #530 (#531)

* Fix PIREP edit endpoint closes #533 (#534)

* Fix import during flight cron #532 (#535)

* PIREPS resource except for show (#536)

* Use optional() around the airport fields (#537)

* Use optional() around the airport fields

* Add null-coalesce around full_name

* Add link to download ACARS config from profile (#539)

* Add link to download ACARS config from profile

* Formatting

* Update xml config file template (#540)
This commit is contained in:
Nabeel S 2020-02-08 13:29:34 -05:00 committed by GitHub
parent a335ed8e9b
commit 073e48c396
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
515 changed files with 13939 additions and 10717 deletions

1
.dockerignore Normal file
View File

@ -0,0 +1 @@
vendor

View File

@ -8,7 +8,7 @@ assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
A clear and concise description of what the bug is. Please upload the Laravel logs as well from `storage/logs/laravel.log` (or the file with the correct date)
**Version**
Please enter the version

View File

@ -6,12 +6,11 @@ language: php
php:
- '7.2'
- '7.3'
- '7.4'
matrix:
include:
- php: '7.2'
- php: '7.3'
fast_finish: true
env:
- DB=mysql
- DB=mariadb
cache:
# Cache lives for 10 min
@ -24,7 +23,12 @@ cache:
services:
- mysql
addons:
mariadb: '10.2'
install:
- php --version
- mysql --version
- composer install --dev --no-interaction --verbose
- cp .travis/env.travis.php env.php
- cp .travis/phpunit.travis.xml phpunit.xml
@ -40,8 +44,83 @@ script:
after_failure:
- cat storage/logs/*.log
# Refer to: https://github.com/doctrine/dbal/blob/master/.travis.yml#L39
jobs:
include:
# Different test stages
# - stage: Test
# name: PHP 7.2 + MySQL 5.7
# php: 7.2
# env: DB=mysql
# services:
# - mysql
# - stage: Test
# name: PHP 7.3 + MySQL 5.7
# php: 7.3
# env: DB=mysql
# services:
# - mysql
# - stage: Test
# name: PHP 7.4 + MySQL 5.7
# php: 7.4
# env: DB=mysql
# services:
# - mysql
# - stage: Test
# name: PHP 7.2 + MariaDB 10.1
# php: 7.2
# env: DB=mariadb
# addons:
# mariadb: '10.1'
# - stage: Test
# name: PHP 7.3 + MariaDB 10.1
# php: 7.3
# env: DB=mariadb
# addons:
# mariadb: '10.1'
# - stage: Test
# name: PHP 7.4 + MariaDB 10.1
# php: 7.4
# env: DB=mariadb MARIADB_VERSION=10.1
# addons:
# mariadb: '10.1'
# - stage: Test
# name: PHP 7.2 + MariaDB 10.2
# php: 7.2
# env: DB=mariadb
# addons:
# mariadb: '10.2'
# - stage: Test
# name: PHP 7.3 + MariaDB 10.3
# php: 7.3
# env: DB=mariadb
# addons:
# mariadb: '10.2'
# - stage: Test
# name: PHP 7.4 + MariaDB 10.2
# php: 7.4
# env: DB=mariadb
# addons:
# mariadb: '10.2'
# - stage: Test
# name: PHP 7.2 + MariaDB 10.3
# php: 7.2
# env: DB=mariadb
# addons:
# mariadb: '10.3'
# - stage: Test
# name: PHP 7.3 + MariaDB 10.3
# php: 7.3
# env: DB=mariadb
# addons:
# mariadb: '10.3'
# - stage: Test
# name: PHP 7.4 + MariaDB 10.3
# php: 7.4
# env: DB=mariadb
# addons:
# mariadb: '10.3'
# Just packages up a release
- stage: package
script: skip

View File

@ -6,48 +6,41 @@ if [ "$TRAVIS" = "true" ]; then
if test "$TRAVIS_TAG"; then
PKG_NAME=$TRAVIS_TAG
VERSION=$TRAVIS_TAG
# Pass in the tag as the version to write out
php artisan phpvms:version --write $VERSION
else
echo "On branch $TRAVIS_BRANCH"
if [ "$TRAVIS_BRANCH" != "master" ] && [ "$TRAVIS_BRANCH" != "dev" ]; then
echo "Not on valid branch, exiting"
exit 0;
fi;
BASE_VERSION=$(php artisan phpvms:version --base-only)
PKG_NAME=${BASE_VERSION}-${TRAVIS_BRANCH}
exit 0
fi
# Write the version out but place the branch ID in there
# This is only for the dev branch
BASE_VERSION=$(php artisan phpvms:version --base-only)
# This now includes the pre-release version, so "-dev" by default
PKG_NAME=${BASE_VERSION}
# Don't pass in a version here, just write out the latest hash
php artisan phpvms:version --write >VERSION
VERSION=$(cat VERSION)
fi
echo "Version: $VERSION"
echo "Package name: $TAR_NAME"
FILE_NAME="phpvms-$PKG_NAME"
TAR_NAME="$FILE_NAME.tar.gz"
echo "Writing $TAR_NAME"
php artisan phpvms:version --write > VERSION
VERSION=$(cat VERSION)
echo "Version: $VERSION"
echo "Cleaning files"
rm -rf vendor
composer install --no-dev --prefer-dist --no-interaction --verbose
# Clean up the dependencies to remove some of the dev packages
# declare -a remove_packages=(
# 'barryvdh/laravel-ide-helper'
# 'bpocallaghan/generators'
# 'codedungeon/phpunit-result-printer'
# 'fzaninotto/faker'
# 'nikic/php-parser'
# 'phpstan/phpstan'
# 'phpunit/phpunit',
# 'weebly/phpstan-laravel'
# )
#
# for pkg in "${remove_packages[@]}"
# do
# composer --optimize-autoloader --no-interaction remove $pkg
# done
# Leftover individual files to delete
declare -a remove_files=(
.git
@ -56,8 +49,8 @@ if [ "$TRAVIS" = "true" ]; then
.idea
.travis
docker
tests
_ide_helper.php
.dockerignore
.dpl
.editorconfig
.eslintignore
@ -82,8 +75,7 @@ if [ "$TRAVIS" = "true" ]; then
vendor/willdurand/geocoder/tests
)
for file in "${remove_files[@]}"
do
for file in "${remove_files[@]}"; do
rm -rf $file
done
@ -91,6 +83,7 @@ if [ "$TRAVIS" = "true" ]; then
find . -type d -name "sass-cache" -print0 | xargs rm -rf
# clear any app specific stuff that might have been loaded in
find bootstrap/cache -mindepth 1 -maxdepth 1 -not -name '.gitignore' -print0 -exec rm -rf {} +
find storage/app -mindepth 1 -maxdepth 1 -not -name '.gitignore' -not -name public -not -name import -print0 -exec rm -rf {} +
find storage/app/public -mindepth 1 -maxdepth 1 -not -name '.gitignore' -not -name avatars -not -name uploads -print0 -exec rm -rf {} +
find storage/app/public/avatars -mindepth 1 -not -name '.gitignore' -print0 -exec rm -rf {} +
@ -112,7 +105,6 @@ if [ "$TRAVIS" = "true" ]; then
composer dump-autoload
make clean
echo "Creating Tarball"
cd /tmp
tar -czf $TAR_NAME -C $TRAVIS_BUILD_DIR/../ phpvms
sha256sum $TAR_NAME >"$TAR_NAME.sha256"

28
Dockerfile Normal file
View File

@ -0,0 +1,28 @@
FROM php:7.4-fpm-alpine
WORKDIR /var/www/
RUN apk add gmp-dev
RUN curl --silent --show-error https://getcomposer.org/installer | php
# Copy any config files in
COPY resources/docker/php/ext-opcache.ini $PHP_INI_DIR/conf.d/
COPY resources/docker/php/www.conf /usr/local/etc/php-fpm.d/www.conf
RUN ln -sf /dev/stderr /var/log/fpm-error.log
RUN docker-php-ext-install \
calendar \
pdo_mysql \
gmp \
opcache && \
docker-php-ext-enable pdo_mysql opcache
COPY . /var/www/
RUN php composer.phar install \
--ignore-platform-reqs \
--no-interaction \
--no-plugins \
--no-scripts \
--prefer-dist
EXPOSE 9000

View File

@ -19,7 +19,7 @@ clean:
@php artisan view:clear
@find bootstrap/cache -type f -not -name '.gitignore' -print0 | xargs -0 rm -rf
@find storage/framework/cache/ -mindepth 1 -not -name '.gitignore' -print0 | xargs -0 rm -rf
@find storage/framework/cache/ -mindepth 1 -type f -not -name '.gitignore' -print0 | xargs -0 rm -rf
@find storage/framework/sessions/ -mindepth 1 -type f -not -name '.gitignore' -print0 | xargs -0 rm -rf
@find storage/framework/views/ -mindepth 1 -not -name '.gitignore' -print0 | xargs -0 rm -rf

View File

@ -5,13 +5,11 @@ namespace App\Bootstrap;
use Illuminate\Contracts\Config\Repository as RepositoryContract;
use Illuminate\Contracts\Foundation\Application;
/**
* Class LoadConfiguration
*/
class LoadConfiguration extends \Illuminate\Foundation\Bootstrap\LoadConfiguration
{
/**
* Load the configuration items from all of the files.
* Load the configuration items from all of the files. This reads the config.php from
* that's sitting in the root, and then recursively merges it with the current configs
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @param \Illuminate\Contracts\Config\Repository $repository

View File

@ -0,0 +1,95 @@
<?php
namespace App\Console\Commands;
use App;
use App\Contracts\Command;
use App\Services\Installer\SeederService;
use DatabaseSeeder;
use Modules\Installer\Services\ConfigService;
/**
* Create the config files
*/
class CreateConfigs extends Command
{
protected $signature = 'phpvms:config {db_host} {db_name} {db_user} {db_pass}';
protected $description = 'Create the config files';
private $databaseSeeder;
private $seederSvc;
public function __construct(DatabaseSeeder $databaseSeeder, SeederService $seederSvc)
{
parent::__construct();
$this->databaseSeeder = $databaseSeeder;
$this->seederSvc = $seederSvc;
}
/**
* Run dev related commands
*
* @throws \Symfony\Component\HttpFoundation\File\Exception\FileException
*/
public function handle()
{
$this->writeConfigs();
// Reload the configuration
App::boot();
$this->info('Recreating database');
$this->call('database:create', [
'--reset' => true,
]);
$this->info('Running migrations');
$this->call('migrate:fresh', [
'--seed' => true,
]);
$this->seederSvc->syncAllSeeds();
$this->info('Done!');
}
/**
* Rewrite the configuration files
*
* @throws \Symfony\Component\HttpFoundation\File\Exception\FileException
*/
protected function writeConfigs()
{
/** @var ConfigService $cfgSvc */
$cfgSvc = app(ConfigService::class);
$this->info('Removing the old config files');
// Remove the old files
$config_file = base_path('config.php');
if (file_exists($config_file)) {
unlink($config_file);
}
$env_file = base_path('env.php');
if (file_exists($env_file)) {
unlink($env_file);
}
//{name} {db_host} {db_name} {db_user} {db_pass}
$this->info('Regenerating the config files');
$cfgSvc->createConfigFiles([
'APP_ENV' => 'dev',
'SITE_NAME' => $this->argument('name'),
'DB_CONN' => 'mysql',
'DB_HOST' => $this->argument('db_host'),
'DB_NAME' => $this->argument('db_name'),
'DB_USER' => $this->argument('db_user'),
'DB_PASS' => $this->argument('db_pass'),
]);
$this->info('Config files generated!');
}
}

View File

@ -2,13 +2,14 @@
namespace App\Console\Commands;
use App\Console\Services\Database;
use App\Contracts\Command;
use Illuminate\Support\Facades\Log;
use Tivie\OS\Detector;
class CreateDatabase extends Command
{
protected $signature = 'database:create {--reset} {--conn=?}';
protected $signature = 'database:create {--reset} {--migrate} {--conn=?}';
protected $description = 'Create a database';
protected $os;
@ -36,8 +37,7 @@ class CreateDatabase extends Command
$user = config($dbkey.'username');
$pass = config($dbkey.'password');
$dbSvc = new \App\Console\Services\Database();
$dbSvc = new Database();
$dsn = $dbSvc->createDsn($host, $port);
Log::info('Connection string: '.$dsn);

View File

@ -0,0 +1,52 @@
<?php
namespace App\Console\Commands;
use App\Contracts\Command;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Yaml\Yaml;
class PirepExport extends Command
{
protected $signature = 'phpvms:pirep-export {id}';
protected $description = 'PIREP table export';
/**
* Run dev related commands
*/
public function handle()
{
$pirep_id = $this->argument('id');
if (empty($pirep_id)) {
$this->error('No PIREP ID specified');
exit();
}
// List the tables to export and the column name for the pirep id
$tables = [
'pireps' => 'id',
'acars' => 'pirep_id',
'pirep_comments' => 'pirep_id',
'pirep_fares' => 'pirep_id',
'pirep_field_values' => 'pirep_id',
'expenses' => 'ref_model_id',
'journal_transactions' => 'ref_model_id',
];
$export_tables = [];
foreach ($tables as $table => $key) {
$export_tables[$table] = [];
$rows = DB::table($table)
->where($key, '=', $pirep_id)
->get();
foreach ($rows as $row) {
$export_tables[$table][] = (array) $row;
}
}
$yaml = Yaml::dump($export_tables, 4, 2);
echo $yaml;
}
}

View File

@ -8,7 +8,7 @@ use Symfony\Component\Yaml\Yaml;
class Version extends Command
{
protected $signature = 'phpvms:version {--write} {--base-only}';
protected $signature = 'phpvms:version {--write} {--base-only} {--write-full-version} {version?}';
private $versionSvc;
@ -26,11 +26,33 @@ class Version extends Command
*/
public function handle()
{
// Write the updated build number out to the file
if ($this->option('write')) {
// Write the updated build number out to the file
$version_file = config_path('version.yml');
$cfg = Yaml::parse(file_get_contents($version_file));
// If a version is being passed in, the update the build, etc data against this
if ($this->argument('version')) {
$version = \SemVer\SemVer\Version::fromString($this->argument('version'));
if ($this->option('write_full_version')) {
$cfg['current']['major'] = $version->getMajor();
$cfg['current']['minor'] = $version->getMinor();
$cfg['current']['patch'] = $version->getPatch();
}
$prerelease = $version->getPreRelease();
if (strpos($prerelease, '.') !== false) {
$prerelease = explode('.', $prerelease);
$cfg['current']['prerelease'] = $prerelease[0];
$cfg['current']['buildmetadata'] = $prerelease[1];
} else {
$cfg['current']['prerelease'] = $prerelease;
}
}
// Always write out the build ID/build number which is the commit hash
$build_number = $this->versionSvc->getBuildId($cfg);
$cfg['current']['commit'] = $build_number;
$cfg['build']['number'] = $build_number;
file_put_contents($version_file, Yaml::dump($cfg, 4, 2));

View File

@ -42,7 +42,6 @@ class Kernel extends ConsoleKernel
*/
protected function commands(): void
{
require app_path('Http/Routes/console.php');
$this->load(__DIR__.'/Commands');
$this->load(__DIR__.'/Cron');
}

View File

@ -1,704 +0,0 @@
<?php
namespace App\Console\Services;
use App\Facades\Utils;
use App\Models\Aircraft;
use App\Models\Airline;
use App\Models\Airport;
use App\Models\Enums\FlightType;
use App\Models\Enums\PirepSource;
use App\Models\Enums\UserState;
use App\Models\Flight;
use App\Models\Pirep;
use App\Models\Rank;
use App\Models\Subfleet;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use PDO;
use PDOException;
use Symfony\Component\Console\Output\ConsoleOutput;
/**
* Class Importer
* TODO: Batch import
*/
class Importer
{
/**
* Hold references
*/
private $mappedEntities = [];
/**
* Hold the PDO connection to the old database
*
* @var
*/
private $conn;
/**
* @var array
*/
private $creds;
/**
* Hold the instance of the console logger
*
* @var
*/
private $log;
/**
* CONSTANTS
*/
public const BATCH_READ_ROWS = 300;
public const SUBFLEET_NAME = 'Imported Aircraft';
/**
* Importer constructor.
*
* @param $db_creds
*/
public function __construct($db_creds)
{
// Setup the logger
$this->log = new ConsoleOutput();
// The db credentials
$this->creds = array_merge([
'host' => '127.0.0.1',
'port' => 3306,
'name' => '',
'user' => '',
'pass' => '',
'table_prefix' => '',
], $db_creds);
}
/**
* @return int|void
*/
public function run()
{
$this->reconnect();
// Import all the different parts
$this->importRanks();
$this->importAirlines();
$this->importAircraft();
$this->importAirports();
$this->importUsers();
$this->importFlights();
$this->importPireps();
// Finish up
$this->findLastPireps();
$this->recalculateRanks();
}
/**
* Reconnect to the old phpVMS DB using PDO
*/
protected function reconnect()
{
$dsn = 'mysql:'.implode(';', [
'host='.$this->creds['host'],
'port='.$this->creds['port'],
'dbname='.$this->creds['name'],
]);
$this->info('Connection string: '.$dsn);
try {
$this->conn = new PDO($dsn, $this->creds['user'], $this->creds['pass']);
$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
} catch (\PDOException $e) {
$this->error($e);
exit();
}
}
/**
* @param $message
*/
protected function comment($message)
{
$this->log->writeln('<comment>'.$message.'</comment>');
}
/**
* @param $message
*/
protected function error($message)
{
$this->log->writeln('<error>'.$message.'</error>');
}
/**
* @param string|array $message
*/
protected function info($message)
{
if (\is_array($message)) {
/* @noinspection ForgottenDebugOutputInspection */
print_r($message);
} else {
$this->log->writeln('<info>'.$message.'</info>');
}
}
/**
* Return the table name with the prefix
*
* @param $table
*
* @return string
*/
protected function tableName($table)
{
if ($this->creds['table_prefix'] !== false) {
return $this->creds['table_prefix'].$table;
}
return $table;
}
/**
* @param \Illuminate\Database\Eloquent\Model $model
*
* @return bool
*/
protected function saveModel($model)
{
try {
$model->save();
return true;
} catch (QueryException $e) {
if ($e->getCode() !== '23000') {
$this->error($e);
}
return false;
}
}
/**
* Create a new mapping between an old ID and the new one
*
* @param $entity
* @param $old_id
* @param $new_id
*/
protected function addMapping($entity, $old_id, $new_id)
{
if (!array_key_exists($entity, $this->mappedEntities)) {
$this->mappedEntities[$entity] = [];
}
$this->mappedEntities[$entity][$old_id] = $new_id;
}
/**
* Return the ID for a mapping
*
* @param $entity
* @param $old_id
*
* @return bool
*/
protected function getMapping($entity, $old_id)
{
if (!array_key_exists($entity, $this->mappedEntities)) {
return 0;
}
$entity = $this->mappedEntities[$entity];
if (array_key_exists($old_id, $entity)) {
return $entity[$old_id];
}
return 0;
}
/**
* @param $date
*
* @return Carbon
*/
protected function parseDate($date)
{
$carbon = Carbon::parse($date);
return $carbon;
}
/**
* Take a decimal duration and convert it to minutes
*
* @param $duration
*
* @return float|int
*/
protected function convertDuration($duration)
{
if (strpos($duration, '.') !== false) {
$delim = '.';
} elseif (strpos($duration, ':')) {
$delim = ':';
} else {
// no delimiter, assume it's just a straight hour
return (int) $duration * 60;
}
$hm = explode($delim, $duration);
$hours = (int) $hm[0] * 60;
$mins = (int) $hm[1];
return $hours + $mins;
}
/**
* @param $table
*
* @return mixed
*/
protected function getTotalRows($table)
{
$table = $this->tableName($table);
$sql = 'SELECT COUNT(*) FROM '.$table;
$rows = $this->conn->query($sql)->fetchColumn();
$this->info('Found '.$rows.' rows in '.$table);
return (int) $rows;
}
/**
* Read all the rows in a table, but read them in a batched manner
*
* @param string $table The name of the table
* @param null $read_rows Number of rows to read
*
* @return \Generator
*/
protected function readRows($table, $read_rows = null)
{
// Set the table prefix if it has been entered
$this->tableName($table);
$offset = 0;
if ($read_rows === null) {
$read_rows = self::BATCH_READ_ROWS;
}
$total_rows = $this->getTotalRows($table);
while ($offset < $total_rows) {
$rows_to_read = $offset + $read_rows;
if ($rows_to_read > $total_rows) {
$rows_to_read = $total_rows;
}
$this->info('Reading '.$offset.' to '.$rows_to_read.' of '.$total_rows);
$sql = 'SELECT * FROM '.$this->tableName($table)
.' LIMIT '.self::BATCH_READ_ROWS.' OFFSET '.$offset;
try {
foreach ($this->conn->query($sql) as $row) {
yield $row;
}
} catch (PDOException $e) {
// Without incrementing the offset, it should re-run the same query
$this->error($e);
if (strpos($e->getMessage(), 'server has gone away') !== false) {
$this->reconnect();
continue;
}
}
$offset += self::BATCH_READ_ROWS;
}
}
/**
* Return the subfleet
*
* @return mixed
*/
protected function getSubfleet()
{
$airline = Airline::first();
$subfleet = Subfleet::firstOrCreate(
['airline_id' => $airline->id, 'name' => self::SUBFLEET_NAME],
['type' => 'PHPVMS']
);
return $subfleet;
}
/**
* All the individual importers, done on a per-table basis
* Some tables get saved locally for tables that use FK refs
*/
/**
* Import all of the ranks
*/
protected function importRanks()
{
$this->comment('--- RANK IMPORT ---');
$count = 0;
foreach ($this->readRows('ranks') as $row) {
$rank = Rank::firstOrCreate(
['name' => $row->rank],
['image_url' => $row->rankimage, 'hours' => $row->minhours]
);
$this->addMapping('ranks', $row->rankid, $rank->id);
$this->addMapping('ranks', $row->rank, $rank->id);
if ($rank->wasRecentlyCreated) {
$count++;
}
}
$this->info('Imported '.$count.' ranks');
}
/**
* Import all of the airlines. Save them all in the private var $airlines
* They're used to lookup from other reference tables
*/
protected function importAirlines()
{
$this->comment('--- AIRLINE IMPORT ---');
$count = 0;
foreach ($this->readRows('airlines') as $row) {
$airline = Airline::firstOrCreate(
['icao' => $row->code],
['iata' => $row->code, 'name' => $row->name, 'active' => $row->enabled]
);
$this->addMapping('airlines', $row->id, $airline->id);
$this->addMapping('airlines', $row->code, $airline->id);
if ($airline->wasRecentlyCreated) {
$count++;
}
}
$this->info('Imported '.$count.' airlines');
}
/**
* Imported the aircraft
*/
protected function importAircraft()
{
$this->comment('--- AIRCRAFT IMPORT ---');
$subfleet = $this->getSubfleet();
$this->info('Subfleet ID is '.$subfleet->id);
$count = 0;
foreach ($this->readRows('aircraft') as $row) {
$aircraft = Aircraft::firstOrCreate(
['name' => $row->fullname, 'registration' => $row->registration],
['icao' => $row->icao,
'subfleet_id' => $subfleet->id,
'active' => $row->enabled,
]
);
$this->addMapping('aircraft', $row->id, $aircraft->id);
if ($aircraft->wasRecentlyCreated) {
$count++;
}
}
$this->info('Imported '.$count.' aircraft');
}
/**
* Import all of the airports
*/
protected function importAirports()
{
$this->comment('--- AIRPORT IMPORT ---');
$count = 0;
foreach ($this->readRows('airports') as $row) {
$attrs = [
'id' => trim($row->icao),
'icao' => trim($row->icao),
'name' => $row->name,
'country' => $row->country,
'lat' => $row->lat,
'lon' => $row->lng,
'hub' => $row->hub,
];
$airport = Airport::updateOrCreate(
['id' => $attrs['id']],
$attrs
);
if ($airport->wasRecentlyCreated) {
$count++;
}
}
$this->info('Imported '.$count.' airports');
}
/**
* Import the flights and schedules
*/
protected function importFlights()
{
$this->comment('--- FLIGHT SCHEDULE IMPORT ---');
$count = 0;
foreach ($this->readRows('schedules') as $row) {
$airline_id = $this->getMapping('airlines', $row->code);
$flight_num = trim($row->flightnum);
$attrs = [
'dpt_airport_id' => $row->depicao,
'arr_airport_id' => $row->arricao,
'route' => $row->route ?: '',
'distance' => round($row->distance ?: 0, 2),
'level' => $row->flightlevel ?: 0,
'dpt_time' => $row->deptime ?: '',
'arr_time' => $row->arrtime ?: '',
'flight_time' => $this->convertDuration($row->flighttime) ?: '',
'notes' => $row->notes ?: '',
'active' => $row->enabled ?: true,
];
try {
$flight = Flight::updateOrCreate(
['airline_id' => $airline_id, 'flight_number' => $flight_num],
$attrs
);
} catch (\Exception $e) {
//$this->error($e);
}
$this->addMapping('flights', $row->id, $flight->id);
// TODO: deserialize route_details into ACARS table
if ($flight->wasRecentlyCreated) {
$count++;
}
}
$this->info('Imported '.$count.' flights');
}
/**
* Import all of the PIREPs
*/
protected function importPireps()
{
$this->comment('--- PIREP IMPORT ---');
$count = 0;
foreach ($this->readRows('pireps') as $row) {
$pirep_id = $row->pirepid;
$user_id = $this->getMapping('users', $row->pilotid);
$airline_id = $this->getMapping('airlines', $row->code);
$aircraft_id = $this->getMapping('aircraft', $row->aircraft);
$attrs = [
//'id' => $pirep_id,
'user_id' => $user_id,
'airline_id' => $airline_id,
'aircraft_id' => $aircraft_id,
'flight_number' => $row->flightnum ?: '',
'dpt_airport_id' => $row->depicao,
'arr_airport_id' => $row->arricao,
'block_fuel' => $row->fuelused,
'route' => $row->route ?: '',
'source_name' => $row->source,
'created_at' => $this->parseDate($row->submitdate),
'updated_at' => $this->parseDate($row->modifieddate),
];
// Set the distance
$distance = round($row->distance ?: 0, 2);
$attrs['distance'] = $distance;
$attrs['planned_distance'] = $distance;
// Set the flight time properly
$duration = $this->convertDuration($row->flighttime_stamp);
$attrs['flight_time'] = $duration;
$attrs['planned_flight_time'] = $duration;
// Set how it was filed
if (strtoupper($row->source) === 'MANUAL') {
$attrs['source'] = PirepSource::MANUAL;
} else {
$attrs['source'] = PirepSource::ACARS;
}
// Set the flight type
$row->flighttype = strtoupper($row->flighttype);
if ($row->flighttype === 'P') {
$attrs['flight_type'] = FlightType::SCHED_PAX;
} elseif ($row->flighttype === 'C') {
$attrs['flight_type'] = FlightType::SCHED_CARGO;
} else {
$attrs['flight_type'] = FlightType::CHARTER_PAX_ONLY;
}
// Set the flight level of the PIREP is set
if (property_exists($row, 'flightlevel')) {
$attrs['level'] = $row->flightlevel;
} else {
$attrs['level'] = 0;
}
$pirep = Pirep::updateOrCreate(
['id' => $pirep_id],
$attrs
);
$source = strtoupper($row->source);
if ($source === 'SMARTCARS') {
// TODO: Parse smartcars log into the acars table
} elseif ($source === 'KACARS') {
// TODO: Parse kACARS log into acars table
} elseif ($source === 'XACARS') {
// TODO: Parse XACARS log into acars table
}
// TODO: Add extra fields in as PIREP fields
$this->addMapping('pireps', $row->pirepid, $pirep->id);
if ($pirep->wasRecentlyCreated) {
$count++;
}
}
$this->info('Imported '.$count.' pireps');
}
protected function importUsers()
{
$this->comment('--- USER IMPORT ---');
$count = 0;
foreach ($this->readRows('pilots', 50) as $row) {
// TODO: What to do about pilot ids
$name = $row->firstname.' '.$row->lastname;
$airline_id = $this->getMapping('airlines', $row->code);
$rank_id = $this->getMapping('ranks', $row->rank);
$state = $this->getUserState($row->retired);
$new_password = Str::random(60);
$attrs = [
'name' => $name,
'password' => Hash::make($new_password),
'api_key' => Utils::generateApiKey(),
'airline_id' => $airline_id,
'rank_id' => $rank_id,
'home_airport_id' => $row->hub,
'curr_airport_id' => $row->hub,
'flights' => (int) $row->totalflights,
'flight_time' => Utils::hoursToMinutes($row->totalhours),
'state' => $state,
'created_at' => $this->parseDate($row->joindate),
];
$user = User::updateOrCreate(
['email' => $row->email],
$attrs
);
$this->addMapping('users', $row->pilotid, $user->id);
if ($user->wasRecentlyCreated) {
$count++;
}
}
$this->info('Imported '.$count.' users');
}
/**
* Go through and set the last PIREP ID for the users
*/
protected function findLastPireps()
{
}
/**
* Recalculate all of the user ranks
*/
protected function recalculateRanks()
{
/*$this->comment('--- RECALCULATING RANKS ---');*/
}
/**
* Get the user's new state from their original state
*
* @param $state
*
* @return int
*/
protected function getUserState($state)
{
// TODO: This state might differ between simpilot and classic version
$state = (int) $state;
// Declare array of classic states
$phpvms_classic_states = [
'ACTIVE' => 0,
'INACTIVE' => 1,
'BANNED' => 2,
'ON_LEAVE' => 3,
];
// Decide which state they will be in accordance with v7
if ($state === $phpvms_classic_states['ACTIVE']) {
return UserState::ACTIVE;
}
if ($state === $phpvms_classic_states['INACTIVE']) {
// TODO: Make an inactive state?
return UserState::REJECTED;
}
if ($state === $phpvms_classic_states['BANNED']) {
return UserState::SUSPENDED;
}
if ($state === $phpvms_classic_states['ON_LEAVE']) {
return UserState::ON_LEAVE;
}
$this->error('Unknown status: '.$state);
return UserState::ACTIVE;
}
}

View File

@ -6,7 +6,8 @@ use App\Facades\Utils;
use App\Models\Award as AwardModel;
use App\Models\User;
use App\Models\UserAward;
use Log;
use Exception;
use Illuminate\Support\Facades\Log;
/**
* Base class for the Awards, you need to extend this, and implement:
@ -38,12 +39,6 @@ abstract class Award
protected $award;
protected $user;
/**
* AwardInterface constructor.
*
* @param AwardModel $award
* @param User $user
*/
public function __construct(AwardModel $award = null, User $user = null)
{
$this->award = $award;
@ -73,7 +68,7 @@ abstract class Award
*
* @return bool|UserAward
*/
final protected function addAward()
protected function addAward()
{
$w = [
'user_id' => $this->user->id,
@ -90,7 +85,7 @@ abstract class Award
try {
$award->save();
} catch (\Exception $e) {
} catch (Exception $e) {
Log::error(
'Error saving award: '.$e->getMessage(),
$e->getTrace()

View File

@ -12,7 +12,9 @@ use Illuminate\Http\Request;
*/
abstract class Controller extends \Illuminate\Routing\Controller
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
use AuthorizesRequests;
use DispatchesJobs;
use ValidatesRequests;
/**
* Write a error to the flash and redirect the user to a route

View File

@ -2,9 +2,21 @@
namespace App\Contracts;
/**
* Class Listener
*/
use Illuminate\Contracts\Events\Dispatcher;
abstract class Listener
{
public static $callbacks = [];
/**
* Sets up any callbacks that are defined in the child class
*
* @param $events
*/
public function subscribe(Dispatcher $events): void
{
foreach (static::$callbacks as $klass => $cb) {
$events->listen($klass, get_class($this).'@'.$cb);
}
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace App\Contracts;
use Closure;
use Illuminate\Http\Request;
interface Middleware
{
public function handle(Request $request, Closure $next);
}

View File

@ -2,7 +2,9 @@
namespace App\Contracts;
use App\Support\Database;
use DB;
use Illuminate\Support\Facades\Log;
/**
* Class Migration
@ -23,6 +25,22 @@ abstract class Migration extends \Illuminate\Database\Migrations\Migration
{
}
/**
* Seed a YAML file into the database
*
* @param string $file Full path to yml file to seed
*/
public function seedFile($file): void
{
try {
$path = base_path($file);
Database::seed_from_yaml_file($path, false);
} catch (\Exception $e) {
Log::error('Unable to load '.$file.' file');
Log::error($e);
}
}
/**
* Add rows to a table
*

View File

@ -3,21 +3,20 @@
namespace App\Contracts;
/**
* Class Model
*
* @property mixed $id
* @property bool $skip_mutator
*
* @method static where(array $array)
* @mixin \Illuminate\Database\Eloquent\Builder
*/
abstract class Model extends \Illuminate\Database\Eloquent\Model
{
/**
* Max length of ID for string columns
*/
public const ID_MAX_LENGTH = 12;
/**
* For the factories, skip the mutators. Only apply to one instance
*
* @var bool
*/
public $skip_mutator = false;
}

View File

@ -3,13 +3,10 @@
namespace App\Contracts;
use ArrayAccess;
use PhpUnitsOfMeasure\Exception\UnknownUnitOfMeasure;
/**
* Class Unit
*
* @property mixed $instance
* @property string $unit
* @property array $units
* Abstract unit wrapper
*/
class Unit implements ArrayAccess
{
@ -25,6 +22,8 @@ class Unit implements ArrayAccess
/**
* Holds an instance of the PhpUnit type
*
* @var \PhpUnitsOfMeasure\AbstractPhysicalQuantity
*/
protected $instance;
@ -75,7 +74,7 @@ class Unit implements ArrayAccess
*/
public function offsetExists($offset)
{
return array_key_exists($offset, $this->units);
return $this->offsetGet($offset) !== null;
}
/**
@ -87,7 +86,16 @@ class Unit implements ArrayAccess
*/
public function offsetGet($offset)
{
return round($this->instance->toUnit($offset), 2);
try {
$value = $this->instance->toUnit($offset);
if (!$value) {
return;
}
} catch (UnknownUnitOfMeasure $e) {
return;
}
return round($value, 2);
}
/**
@ -116,6 +124,6 @@ class Unit implements ArrayAccess
*/
public function __toString()
{
return (string) $this->units[$this->unit];
return (string) $this->offsetGet($this->unit);
}
}

View File

@ -4,6 +4,7 @@ namespace App\Cron\Hourly;
use App\Contracts\Listener;
use App\Events\CronHourly;
use App\Models\Enums\PirepState;
use App\Models\Pirep;
use Carbon\Carbon;
@ -13,7 +14,7 @@ use Carbon\Carbon;
class RemoveExpiredLiveFlights extends Listener
{
/**
* Remove expired live flights
* Remove expired live flights that haven't had an update in the live time
*
* @param CronHourly $event
*
@ -26,7 +27,7 @@ class RemoveExpiredLiveFlights extends Listener
}
$date = Carbon::now()->subHours(setting('acars.live_time'));
Pirep::whereDate('created_at', '<', $date)
Pirep::whereDate('updated_at', '<', $date)
->where('state', PirepState::IN_PROGRESS)
->delete();
}

View File

@ -8,7 +8,7 @@ use Faker\Generator as Faker;
if (!function_exists('createFactoryICAO')) {
function createFactoryICAO(): string
{
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$max = strlen($characters) - 1;
$string = '';
for ($i = 0; $i < 4; $i++) {
@ -26,14 +26,15 @@ if (!function_exists('createFactoryICAO')) {
* Add any number of airports. Don't really care if they're real or not
*/
$factory->define(App\Models\Airport::class, function (Faker $faker) {
$used = [];
return [
'id' => function () use ($used) {
do {
$string = createFactoryICAO();
} while (in_array($string, $used, true));
$usedIcaos = [];
return $string;
return [
'id' => function () use ($usedIcaos) {
do {
$airport = createFactoryICAO();
} while (in_array($airport, $usedIcaos, true));
return $airport;
},
'icao' => function (array $apt) {
return $apt['id'];

View File

@ -28,28 +28,6 @@ class UsersAddPilotId extends Migration
// Migrate the current pilot IDs
DB::update('UPDATE `users` SET `pilot_id`=`id`');
// Drop the old ID column and add a new one
/*Schema::table('users', function (Blueprint $table) {
$table->dropPrimary('users_id_primary');
$table->dropColumn('id');
$table->string('id', Model::ID_MAX_LENGTH)->primary();
});
// Update the users to use the `pilot_id` (so we don't need to migrate data from other tables)
$users = DB::table('users')->get(['id']);
foreach ($users as $user) {
$user->id = $user->pilot_id;
$user->save();
}*/
// role_user
// permission_user
// sessions
// pireps
// bids
// news
// user_awards
}
/**

View File

@ -20,7 +20,7 @@ awards:
name: Pilot 50 flights
description: When a pilot has 50 flights, give this award
image_url:
ref_model: App\Awards\PilotFlightAwards
ref_model: Modules\Awards\Awards\PilotFlightAwards
ref_model_params: 50
created_at: now
updated_at: now
@ -307,10 +307,10 @@ flights:
dpt_airport_id: MKJP
arr_airport_id: MWCR
flight_time: 70
flight_type: J
dpt_time: 0800
arr_time: 0900
route: MLY5 KEMBO UG442 SIA UG633 OTEKO UR640 NALRO GUBEL3
flight_type: 'J'
dpt_time: '0800'
arr_time: '0900'
route: 'MLY5 KEMBO UG442 SIA UG633 OTEKO UR640 NALRO GUBEL3'
created_at: NOW
updated_at: NOW

View File

@ -21,10 +21,10 @@ users:
updated_at: now
- id: 2
pilot_id: 2
name: Carla Walters
email: carla.walters68@example.com
password: admin
api_key: testuserapikey1
name: Test User
email: user@phpvms.net
password: user
api_key: testuserapikey
airline_id: 1
rank_id: 1
home_airport_id: KJFK
@ -34,7 +34,7 @@ users:
transfer_time: 360
created_at: now
updated_at: now
state: 0
state: 1
opt_in: 1
toc_accepted: 1
- id: 3

View File

@ -1,7 +1,7 @@
# All of the different permissions that can be assigned to roles
---
- name: admin-access
display_name: Admin Access
display_name: Admin Panel
description: Access the admin panel
- name: airlines
display_name: Airlines
@ -24,6 +24,9 @@
- name: fares
display_name: Fares
description: Create/edit fares
- name: files
display_name: Files
description: Manage the files available
- name: finances
display_name: Finances
description: Create/view finance related items

View File

@ -222,3 +222,17 @@
options: ''
type: boolean
description: 'Count transfer hours in calculations, like ranks and the total hours'
- key: notifications.discord_api_key
name: Discord API token
group: notifications
value: ''
options: ''
type: text
description: Discord API token for notifications
- key: 'notifications.discord_public_channel_id'
name: 'Discord Public Channel ID'
group: 'notifications'
value: ''
options: ''
type: 'text'
description: 'Discord public channel ID for broadcasat notifications'

14
app/Events/BaseEvent.php Normal file
View File

@ -0,0 +1,14 @@
<?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class BaseEvent
{
use Dispatchable;
use InteractsWithSockets;
use SerializesModels;
}

View File

@ -2,20 +2,6 @@
namespace App\Events;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* This event is dispatched when the hourly cron is run
*/
class CronHourly
{
use Dispatchable, SerializesModels;
/**
* CronHourly constructor.
*/
public function __construct()
class CronHourly extends BaseEvent
{
}
}

View File

@ -2,21 +2,10 @@
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
*/
class CronMonthly
{
use Dispatchable, SerializesModels;
/**
* CronMonthly constructor.
*/
public function __construct()
class CronMonthly extends BaseEvent
{
}
}

View File

@ -2,21 +2,10 @@
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
*/
class CronNightly
{
use Dispatchable, SerializesModels;
/**
* CronNightly constructor.
*/
public function __construct()
class CronNightly extends BaseEvent
{
}
}

View File

@ -2,20 +2,12 @@
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
*/
class CronWeekly
class CronWeekly extends BaseEvent
{
use Dispatchable, SerializesModels;
/**
* CronWeekly constructor.
*/
public function __construct()
{
}

View File

@ -3,8 +3,6 @@
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
@ -27,9 +25,8 @@ use Illuminate\Queue\SerializesModels;
*
* The event will have a copy of the PIREP model, if it's applicable
*/
class Expenses
class Expenses extends BaseEvent
{
use Dispatchable, SerializesModels;
public $pirep;
/**

15
app/Events/NewsAdded.php Normal file
View File

@ -0,0 +1,15 @@
<?php
namespace App\Events;
use App\Models\News;
class NewsAdded extends BaseEvent
{
public $news;
public function __construct(News $news)
{
$this->news = $news;
}
}

View File

@ -3,24 +3,11 @@
namespace App\Events;
use App\Models\Pirep;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* Class PirepAccepted
*/
class PirepAccepted
class PirepAccepted extends BaseEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $pirep;
/**
* PirepAccepted constructor.
*
* @param Pirep $pirep
*/
public function __construct(Pirep $pirep)
{
$this->pirep = $pirep;

View File

@ -3,13 +3,9 @@
namespace App\Events;
use App\Models\Pirep;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PirepFiled
class PirepFiled extends BaseEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $pirep;
public function __construct(Pirep $pirep)

View File

@ -3,24 +3,11 @@
namespace App\Events;
use App\Models\Pirep;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* Class PirepRejected
*/
class PirepRejected
class PirepRejected extends BaseEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $pirep;
/**
* PirepRejected constructor.
*
* @param Pirep $pirep
*/
public function __construct(Pirep $pirep)
{
$this->pirep = $pirep;

View File

@ -3,24 +3,11 @@
namespace App\Events;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* Class TestEvent
*/
class TestEvent
class TestEvent extends BaseEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
/**
* Create a new event instance.
*
* @param User $user
*/
public function __construct(User $user)
{
$this->user = $user;

View File

@ -3,24 +3,11 @@
namespace App\Events;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* Class UserAccepted
*/
class UserAccepted
class UserAccepted extends BaseEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
/**
* UserAccepted constructor.
*
* @param User $user
*/
public function __construct(User $user)
{
$this->user = $user;

View File

@ -3,24 +3,11 @@
namespace App\Events;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* Class UserRegistered
*/
class UserRegistered
class UserRegistered extends BaseEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
/**
* UserRegistered constructor.
*
* @param User $user
*/
public function __construct(User $user)
{
$this->user = $user;

View File

@ -3,26 +3,15 @@
namespace App\Events;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* Event triggered when a user's state changes
*/
class UserStateChanged
class UserStateChanged extends BaseEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $old_state;
public $user;
/**
* UserStateChanged constructor.
*
* @param User $user
* @param $old_state
*/
public function __construct(User $user, $old_state)
{
$this->old_state = $old_state;

View File

@ -3,17 +3,9 @@
namespace App\Events;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/**
* Class UserStatsChanged
*/
class UserStatsChanged
class UserStatsChanged extends BaseEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $stat_name;
public $old_value;
public $user;

View File

@ -30,8 +30,8 @@ class Handler extends ExceptionHandler
* A list of the exception types that should not be reported.
*/
protected $dontReport = [
AuthenticationException::class,
AuthorizationException::class,
//AuthenticationException::class,
//AuthorizationException::class,
AbstractHttpException::class,
IlluminateValidationException::class,
ModelNotFoundException::class,
@ -50,6 +50,27 @@ class Handler extends ExceptionHandler
public function render($request, Exception $exception)
{
if ($request->is('api/*')) {
return $this->handleApiError($request, $exception);
}
if ($exception instanceof AbstractHttpException
&& $exception->getStatusCode() === 403) {
return redirect()->guest('login');
}
return parent::render($request, $exception);
}
/**
* Handle errors in the API
*
* @param $request
* @param \Exception $exception
*
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
*/
private function handleApiError($request, Exception $exception)
{
Log::error('API Error', $exception->getTrace());
if ($exception instanceof AbstractHttpException) {
@ -60,36 +81,31 @@ class Handler extends ExceptionHandler
* Not of the HttpException abstract class. Map these into
*/
if ($exception instanceof ModelNotFoundException ||
$exception instanceof NotFoundHttpException) {
if ($exception instanceof ModelNotFoundException || $exception instanceof NotFoundHttpException) {
$error = new AssetNotFound($exception);
return $error->getResponse();
}
// Custom exceptions should be extending HttpException
if ($exception instanceof SymfonyHttpException) {
$error = new SymfonyException($exception);
return $error->getResponse();
}
// Create the detailed errors from the validation errors
if ($exception instanceof IlluminateValidationException) {
$error = new ValidationException($exception);
return $error->getResponse();
}
$error = new GenericExceptionAbstract($exception);
return $error->getResponse();
}
if ($exception instanceof AbstractHttpException
&& $exception->getStatusCode() === 403) {
return redirect()->guest('login');
}
return parent::render($request, $exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*

View File

@ -5,9 +5,6 @@ namespace App\Facades;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Facade;
/**
* Class Utils
*/
class Utils extends Facade
{
/**

View File

@ -14,10 +14,10 @@ use App\Repositories\AircraftRepository;
use App\Repositories\AirportRepository;
use App\Services\ExportService;
use App\Services\ImportService;
use Flash;
use Illuminate\Http\Request;
use Log;
use Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Laracasts\Flash\Flash;
/**
* Class AircraftController

View File

@ -13,15 +13,11 @@ use App\Repositories\Criteria\WhereCriteria;
use App\Services\ExportService;
use App\Services\ImportService;
use App\Support\Timezonelist;
use Flash;
use Illuminate\Http\Request;
use Log;
use Response;
use Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Laracasts\Flash\Flash;
/**
* Class AirportController
*/
class AirportController extends Controller
{
private $airportRepo;
@ -46,7 +42,7 @@ class AirportController extends Controller
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return Response
* @return mixed
*/
public function index(Request $request)
{
@ -68,7 +64,7 @@ class AirportController extends Controller
/**
* Show the form for creating a new Airport.
*
* @return Response
* @return mixed
*/
public function create()
{
@ -84,7 +80,7 @@ class AirportController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function store(CreateAirportRequest $request)
{
@ -102,7 +98,7 @@ class AirportController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function show($id)
{
@ -123,7 +119,7 @@ class AirportController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -148,7 +144,7 @@ class AirportController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function update($id, UpdateAirportRequest $request)
{
@ -173,7 +169,7 @@ class AirportController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{

View File

@ -7,10 +7,9 @@ use App\Http\Requests\CreateAwardRequest;
use App\Http\Requests\UpdateAwardRequest;
use App\Repositories\AwardRepository;
use App\Services\AwardService;
use Flash;
use Illuminate\Http\Request;
use Laracasts\Flash\Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
class AwardController extends Controller
{
@ -62,7 +61,7 @@ class AwardController extends Controller
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return Response
* @return mixed
*/
public function index(Request $request)
{
@ -76,8 +75,6 @@ class AwardController extends Controller
/**
* Show the form for creating a new Fare.
*
* @return Response
*/
public function create()
{
@ -96,7 +93,7 @@ class AwardController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function store(CreateAwardRequest $request)
{
@ -112,7 +109,7 @@ class AwardController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function show($id)
{
@ -133,7 +130,7 @@ class AwardController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -161,7 +158,7 @@ class AwardController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function update($id, UpdateAwardRequest $request)
{
@ -183,7 +180,7 @@ class AwardController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{

View File

@ -7,6 +7,8 @@ use App\Repositories\KvpRepository;
use App\Repositories\NewsRepository;
use App\Repositories\PirepRepository;
use App\Repositories\UserRepository;
use App\Services\CronService;
use App\Services\NewsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
@ -14,27 +16,35 @@ use Laracasts\Flash\Flash;
class DashboardController extends Controller
{
private $cronSvc;
private $kvpRepo;
private $newsRepo;
private $newsSvc;
private $pirepRepo;
private $userRepo;
/**
* DashboardController constructor.
*
* @param CronService $cronSvc
* @param KvpRepository $kvpRepo
* @param NewsRepository $newsRepo
* @param NewsService $newsSvc
* @param PirepRepository $pirepRepo
* @param UserRepository $userRepo
*/
public function __construct(
CronService $cronSvc,
KvpRepository $kvpRepo,
NewsRepository $newsRepo,
NewsService $newsSvc,
PirepRepository $pirepRepo,
UserRepository $userRepo
) {
$this->cronSvc = $cronSvc;
$this->kvpRepo = $kvpRepo;
$this->newsRepo = $newsRepo;
$this->newsSvc = $newsSvc;
$this->pirepRepo = $pirepRepo;
$this->userRepo = $userRepo;
}
@ -77,6 +87,7 @@ class DashboardController extends Controller
'news' => $this->newsRepo->getLatest(),
'pending_pireps' => $this->pirepRepo->getPendingCount(),
'pending_users' => $this->userRepo->getPendingCount(),
'cron_problem_exists' => $this->cronSvc->cronProblemExists(),
]);
}
@ -93,10 +104,10 @@ class DashboardController extends Controller
$attrs = $request->post();
$attrs['user_id'] = Auth::user()->id;
$this->newsRepo->create($attrs);
$this->newsSvc->addNews($attrs);
} elseif ($request->isMethod('delete')) {
$news_id = $request->input('news_id');
$this->newsRepo->delete($news_id);
$id = $request->input('news_id');
$this->newsSvc->deleteNews($id);
}
return view('admin.dashboard.news', [

View File

@ -10,16 +10,12 @@ use App\Repositories\AirlineRepository;
use App\Repositories\ExpenseRepository;
use App\Services\ExportService;
use App\Services\ImportService;
use Flash;
use Illuminate\Http\Request;
use Log;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Laracasts\Flash\Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
use Storage;
/**
* Class ExpenseController
*/
class ExpenseController extends Controller
{
private $airlineRepo;
@ -122,7 +118,7 @@ class ExpenseController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -149,7 +145,7 @@ class ExpenseController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function update($id, Request $request)
{
@ -173,7 +169,7 @@ class ExpenseController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{

View File

@ -9,16 +9,12 @@ use App\Http\Requests\UpdateFareRequest;
use App\Repositories\FareRepository;
use App\Services\ExportService;
use App\Services\ImportService;
use Flash;
use Illuminate\Http\Request;
use Log;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Laracasts\Flash\Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
use Storage;
/**
* Class FareController
*/
class FareController extends Controller
{
private $fareRepo;
@ -45,7 +41,7 @@ class FareController extends Controller
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return Response
* @return mixed
*/
public function index(Request $request)
{
@ -58,8 +54,6 @@ class FareController extends Controller
/**
* Show the form for creating a new Fare.
*
* @return Response
*/
public function create()
{
@ -73,7 +67,7 @@ class FareController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function store(CreateFareRequest $request)
{
@ -89,7 +83,7 @@ class FareController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function show($id)
{
@ -107,7 +101,7 @@ class FareController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -128,7 +122,7 @@ class FareController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function update($id, UpdateFareRequest $request)
{
@ -149,7 +143,7 @@ class FareController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{

View File

@ -8,12 +8,8 @@ use App\Services\FileService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Laracasts\Flash\Flash;
/**
* Class FileController
*/
class FileController extends Controller
{
private $fileSvc;

View File

@ -10,9 +10,6 @@ use App\Services\FinanceService;
use App\Support\Dates;
use Illuminate\Http\Request;
/**
* Class FinanceController
*/
class FinanceController extends Controller
{
private $airlineRepo;
@ -43,25 +40,14 @@ class FinanceController extends Controller
public function index(Request $request)
{
$month = $request->query('month', date('Y-m'));
$between = Dates::getMonthBoundary($month);
$transaction_groups = $this->financeSvc->getAllAirlineTransactionsBetween($month);
$first_journal = Journal::where(['type' => JournalType::AIRLINE])
$first_journal = Journal::select(['created_at'])
->where(['type' => JournalType::AIRLINE])
->orderBy('created_at', 'asc')
->limit(1)
->first();
$transaction_groups = [];
$airlines = $this->airlineRepo->orderBy('icao')->all();
// group by the airline
foreach ($airlines as $airline) {
$transaction_groups[] = $this->financeSvc->getAirlineTransactionsBetween(
$airline,
$between[0],
$between[1]
);
}
return view('admin.finances.index', [
'current_month' => $month,
'months_list' => Dates::getMonthsList($first_journal->created_at),

View File

@ -23,6 +23,7 @@ use App\Services\ImportService;
use App\Support\Units\Time;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Laracasts\Flash\Flash;
/**

View File

@ -4,14 +4,10 @@ namespace App\Http\Controllers\Admin;
use App\Contracts\Controller;
use App\Repositories\FlightFieldRepository;
use Flash;
use Illuminate\Http\Request;
use Laracasts\Flash\Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
/**
* Class FlightFieldController
*/
class FlightFieldController extends Controller
{
private $flightFieldRepo;
@ -34,7 +30,7 @@ class FlightFieldController extends Controller
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return Response
* @return mixed
*/
public function index(Request $request)
{
@ -48,8 +44,6 @@ class FlightFieldController extends Controller
/**
* Show the form for creating a new FlightField.
*
* @return Response
*/
public function create()
{
@ -63,7 +57,7 @@ class FlightFieldController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function store(Request $request)
{
@ -81,7 +75,7 @@ class FlightFieldController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function show($id)
{
@ -102,7 +96,7 @@ class FlightFieldController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -126,7 +120,7 @@ class FlightFieldController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
* @return mixed
*/
public function update($id, Request $request)
{
@ -150,7 +144,7 @@ class FlightFieldController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{

View File

@ -19,15 +19,8 @@ class MaintenanceController extends Controller
public function index()
{
// Generate the cron path. Replace php-fpm with just php
$cron_path = [
'* * * * *',
$this->cronSvc->getCronPath(),
'>> /dev/null 2>&1',
];
return view('admin.maintenance.index', [
'cron_path' => implode(' ', $cron_path),
'cron_path' => $this->cronSvc->getCronExecString(),
'cron_problem_exists' => $this->cronSvc->cronProblemExists(),
]);
}
@ -49,6 +42,7 @@ class MaintenanceController extends Controller
$calls[] = 'config:cache';
$calls[] = 'cache:clear';
$calls[] = 'route:cache';
$calls[] = 'clear-compiled';
}
// If we want to clear only the views but keep everything else

View File

@ -21,16 +21,12 @@ use App\Services\FareService;
use App\Services\PirepService;
use App\Services\UserService;
use App\Support\Units\Time;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Log;
use Illuminate\Support\Facades\Log;
use Laracasts\Flash\Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
/**
* Class PirepController
*/
class PirepController extends Controller
{
private $airportRepo;
@ -170,7 +166,7 @@ class PirepController extends Controller
*
* @param Request $request
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
public function fares(Request $request)
{
@ -192,7 +188,7 @@ class PirepController extends Controller
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
public function index(Request $request)
{
@ -218,7 +214,7 @@ class PirepController extends Controller
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
public function pending(Request $request)
{
@ -238,7 +234,7 @@ class PirepController extends Controller
/**
* Show the form for creating a new Pirep.
*
* @return Response
* @return mixed
*/
public function create()
{
@ -279,7 +275,7 @@ class PirepController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function show($id)
{
@ -302,7 +298,7 @@ class PirepController extends Controller
*
* @throws \InvalidArgumentException
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -388,7 +384,7 @@ class PirepController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{

View File

@ -6,14 +6,10 @@ use App\Contracts\Controller;
use App\Http\Requests\CreatePirepFieldRequest;
use App\Http\Requests\UpdatePirepFieldRequest;
use App\Repositories\PirepFieldRepository;
use Flash;
use Illuminate\Http\Request;
use Laracasts\Flash\Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
/**
* Class PirepFieldController
*/
class PirepFieldController extends Controller
{
private $pirepFieldRepo;
@ -36,7 +32,7 @@ class PirepFieldController extends Controller
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return Response
* @return mixed
*/
public function index(Request $request)
{
@ -51,7 +47,7 @@ class PirepFieldController extends Controller
/**
* Show the form for creating a new PirepField.
*
* @return Response
* @return mixed
*/
public function create()
{
@ -65,7 +61,7 @@ class PirepFieldController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function store(CreatePirepFieldRequest $request)
{
@ -85,7 +81,7 @@ class PirepFieldController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function show($id)
{
@ -107,7 +103,7 @@ class PirepFieldController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -158,7 +154,7 @@ class PirepFieldController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{

View File

@ -9,14 +9,10 @@ use App\Repositories\RankRepository;
use App\Repositories\SubfleetRepository;
use App\Services\FleetService;
use Cache;
use Flash;
use Illuminate\Http\Request;
use Laracasts\Flash\Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
/**
* Class RankController
*/
class RankController extends Controller
{
private $fleetSvc;
@ -67,7 +63,7 @@ class RankController extends Controller
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return Response
* @return mixed
*/
public function index(Request $request)
{
@ -82,7 +78,7 @@ class RankController extends Controller
/**
* Show the form for creating a new Ranking.
*
* @return Response
* @return mixed
*/
public function create()
{
@ -96,7 +92,7 @@ class RankController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function store(CreateRankRequest $request)
{
@ -115,7 +111,7 @@ class RankController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function show($id)
{
@ -137,7 +133,7 @@ class RankController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -165,7 +161,7 @@ class RankController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function update($id, UpdateRankRequest $request)
{
@ -190,7 +186,7 @@ class RankController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{

View File

@ -7,29 +7,33 @@ use App\Http\Requests\CreateRoleRequest;
use App\Http\Requests\UpdateRoleRequest;
use App\Repositories\PermissionsRepository;
use App\Repositories\RoleRepository;
use Flash;
use App\Services\RoleService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Laracasts\Flash\Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
/**
* Class AirlinesController
*/
class RolesController extends Controller
{
private $permsRepo;
private $rolesRepo;
private $roleSvc;
/**
* AirlinesController constructor.
*
* @param PermissionsRepository $permsRepo
* @param RoleRepository $rolesRepo
* @param $roleSvc
*/
public function __construct(PermissionsRepository $permsRepo, RoleRepository $rolesRepo)
{
public function __construct(
PermissionsRepository $permsRepo,
RoleRepository $rolesRepo,
RoleService $roleSvc
) {
$this->permsRepo = $permsRepo;
$this->rolesRepo = $rolesRepo;
$this->roleSvc = $roleSvc;
}
/**
@ -132,8 +136,6 @@ class RolesController extends Controller
* @param int $id
* @param UpdateRoleRequest $request
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
*/
public function update($id, UpdateRoleRequest $request)
@ -145,14 +147,8 @@ class RolesController extends Controller
return redirect(route('admin.roles.index'));
}
$this->rolesRepo->update($request->all(), $id);
// Update the permissions, filter out null/invalid values
$perms = collect($request->permissions)->filter(static function ($v, $k) {
return $v;
});
$role->permissions()->sync($perms);
$this->roleSvc->updateRole($role, $request->all());
$this->roleSvc->setPermissionsForRole($role, $request->permissions);
Flash::success('Roles updated successfully.');
return redirect(route('admin.roles.index'));

View File

@ -8,9 +8,6 @@ use Igaster\LaravelTheme\Facades\Theme;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
/**
* Class SettingsController
*/
class SettingsController extends Controller
{
/**

View File

@ -18,16 +18,12 @@ use App\Services\ExportService;
use App\Services\FareService;
use App\Services\FleetService;
use App\Services\ImportService;
use Flash;
use Illuminate\Http\Request;
use Log;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Laracasts\Flash\Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
use Storage;
/**
* Class SubfleetController
*/
class SubfleetController extends Controller
{
private $aircraftRepo;
@ -115,7 +111,7 @@ class SubfleetController extends Controller
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return Response
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request)
{
@ -129,8 +125,6 @@ class SubfleetController extends Controller
/**
* Show the form for creating a new Subfleet.
*
* @return Response
*/
public function create()
{
@ -147,7 +141,7 @@ class SubfleetController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function store(CreateSubfleetRequest $request)
{
@ -163,7 +157,7 @@ class SubfleetController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function show($id)
{
@ -186,7 +180,7 @@ class SubfleetController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -217,7 +211,7 @@ class SubfleetController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function update($id, UpdateSubfleetRequest $request)
{
@ -239,7 +233,7 @@ class SubfleetController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{
@ -269,8 +263,6 @@ class SubfleetController extends Controller
*
* @param Request $request
*
* @throws \League\Csv\CannotInsertRecord
*
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse
*/
public function export(Request $request)
@ -291,7 +283,7 @@ class SubfleetController extends Controller
*
* @throws \Illuminate\Validation\ValidationException
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
public function import(Request $request)
{
@ -322,7 +314,7 @@ class SubfleetController extends Controller
/**
* @param Subfleet $subfleet
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
protected function return_ranks_view(?Subfleet $subfleet)
{
@ -338,7 +330,7 @@ class SubfleetController extends Controller
/**
* @param Subfleet $subfleet
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
protected function return_fares_view(?Subfleet $subfleet)
{
@ -357,7 +349,7 @@ class SubfleetController extends Controller
* @param $id
* @param Request $request
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
public function ranks($id, Request $request)
{
@ -396,7 +388,7 @@ class SubfleetController extends Controller
/**
* @param Subfleet $subfleet
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
protected function return_expenses_view(?Subfleet $subfleet)
{
@ -414,7 +406,7 @@ class SubfleetController extends Controller
*
* @throws \Exception
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
public function expenses($id, Request $request)
{
@ -454,7 +446,7 @@ class SubfleetController extends Controller
* @param $id
* @param Request $request
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
public function fares($id, Request $request)
{

View File

@ -15,17 +15,13 @@ use App\Repositories\PirepRepository;
use App\Repositories\UserRepository;
use App\Services\UserService;
use App\Support\Timezonelist;
use DB;
use Flash;
use Hash;
use Illuminate\Http\Request;
use Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Laracasts\Flash\Flash;
use Prettus\Repository\Exceptions\RepositoryException;
use Response;
/**
* Class UserController
*/
class UserController extends Controller
{
private $airlineRepo;
@ -80,7 +76,7 @@ class UserController extends Controller
/**
* Show the form for creating a new User.
*
* @return Response
* @return mixed
*/
public function create()
{
@ -106,7 +102,7 @@ class UserController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function store(CreateUserRequest $request)
{
@ -122,7 +118,7 @@ class UserController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function show($id)
{
@ -158,7 +154,7 @@ class UserController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function edit($id)
{
@ -202,7 +198,7 @@ class UserController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return Response
* @return mixed
*/
public function update($id, UpdateUserRequest $request)
{
@ -247,10 +243,12 @@ class UserController extends Controller
}
// Delete all of the roles and then re-attach the valid ones
if (!empty($request->input('roles'))) {
DB::table('role_user')->where('user_id', $id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
}
Flash::success('User updated successfully.');
@ -262,7 +260,7 @@ class UserController extends Controller
*
* @param int $id
*
* @return Response
* @return mixed
*/
public function destroy($id)
{

View File

@ -13,9 +13,6 @@ use Illuminate\Support\Facades\Auth;
use Prettus\Repository\Criteria\RequestCriteria;
use Prettus\Repository\Exceptions\RepositoryException;
/**
* Class FlightController
*/
class FlightController extends Controller
{
private $flightRepo;
@ -44,32 +41,7 @@ class FlightController extends Controller
*/
public function index(Request $request)
{
/**
* @var $user \App\Models\User
*/
$user = Auth::user();
$where = [
'active' => true,
'visible' => true,
];
if (setting('pilots.restrict_to_company')) {
$where['airline_id'] = $user->airline_id;
}
if (setting('pilots.only_flights_from_current', false)) {
$where['dpt_airport_id'] = $user->curr_airport_id;
}
$flights = $this->flightRepo
->whereOrder($where, 'flight_number', 'asc')
->paginate();
foreach ($flights as $flight) {
$this->flightSvc->filterSubfleets($user, $flight);
}
return FlightResource::collection($flights);
return $this->search($request);
}
/**
@ -121,6 +93,7 @@ class FlightController extends Controller
return response($e, 503);
}
// TODO: Remove any flights here that a user doesn't have permissions to
foreach ($flights as $flight) {
$this->flightSvc->filterSubfleets(Auth::user(), $flight);
}

View File

@ -17,9 +17,6 @@ use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
/**
* Class RegisterController
*/
class RegisterController extends Controller
{
use RegistersUsers;
@ -58,7 +55,7 @@ class RegisterController extends Controller
/**
* @throws \Exception
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
* @return mixed
*/
public function showRegistrationForm()
{

View File

@ -8,22 +8,21 @@ use App\Repositories\AirlineRepository;
use App\Repositories\AirportRepository;
use App\Repositories\Criteria\WhereCriteria;
use App\Repositories\FlightRepository;
use App\Repositories\SubfleetRepository;
use App\Services\GeoService;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Log;
use Illuminate\Support\Facades\Log;
use Prettus\Repository\Criteria\RequestCriteria;
use Prettus\Repository\Exceptions\RepositoryException;
/**
* Class FlightController
*/
class FlightController extends Controller
{
private $airlineRepo;
private $airportRepo;
private $flightRepo;
private $subfleetRepo;
private $geoSvc;
/**
@ -33,25 +32,44 @@ class FlightController extends Controller
* @param AirportRepository $airportRepo
* @param FlightRepository $flightRepo
* @param GeoService $geoSvc
* @param SubfleetRepository $subfleetRepo
*/
public function __construct(
AirlineRepository $airlineRepo,
AirportRepository $airportRepo,
FlightRepository $flightRepo,
GeoService $geoSvc
GeoService $geoSvc,
SubfleetRepository $subfleetRepo
) {
$this->airlineRepo = $airlineRepo;
$this->airportRepo = $airportRepo;
$this->flightRepo = $flightRepo;
$this->geoSvc = $geoSvc;
$this->subfleetRepo = $subfleetRepo;
}
/**
* @param Request $request
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function index(Request $request)
{
return $this->search($request);
}
/**
* Make a search request using the Repository search
*
* @param Request $request
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return mixed
*/
public function search(Request $request)
{
$where = [
'active' => true,
@ -67,14 +85,17 @@ class FlightController extends Controller
$where['dpt_airport_id'] = Auth::user()->curr_airport_id;
}
$this->flightRepo->resetCriteria();
try {
$this->flightRepo->searchCriteria($request);
$this->flightRepo->pushCriteria(new WhereCriteria($request, $where));
$this->flightRepo->pushCriteria(new RequestCriteria($request));
} catch (RepositoryException $e) {
Log::emergency($e);
}
$flights = $this->flightRepo
$flights = $this->flightRepo->searchCriteria($request)
->with(['dpt_airport', 'arr_airport', 'airline'])
->orderBy('flight_number', 'asc')
->orderBy('route_leg', 'asc')
@ -88,6 +109,11 @@ class FlightController extends Controller
'airports' => $this->airportRepo->selectBoxList(true),
'flights' => $flights,
'saved' => $saved_flights,
'subfleets' => $this->subfleetRepo->selectBoxList(true),
'flight_number' => $request->input('flight_number'),
'arr_icao' => $request->input('arr_icao'),
'dep_icao' => $request->input('dep_icao'),
'subfleet_id' => $request->input('subfleet_id'),
]);
}
@ -114,62 +140,12 @@ class FlightController extends Controller
]);
}
/**
* Make a search request using the Repository search
*
* @param Request $request
*
* @throws \Prettus\Repository\Exceptions\RepositoryException
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function search(Request $request)
{
$where = [
'active' => true,
'visible' => true,
];
if (setting('pilots.restrict_to_company')) {
$where['airline_id'] = Auth::user()->airline_id;
}
// default restrictions on the flights shown. Handle search differently
if (setting('pilots.only_flights_from_current')) {
$where['dpt_airport_id'] = Auth::user()->curr_airport_id;
}
$this->flightRepo->resetCriteria();
try {
$this->flightRepo->pushCriteria(new WhereCriteria($request, $where));
} catch (RepositoryException $e) {
Log::emergency($e);
}
$flights = $this->flightRepo->searchCriteria($request)
->with(['dpt_airport', 'arr_airport', 'airline'])
->orderBy('flight_number', 'asc')
->orderBy('route_leg', 'asc')
->paginate();
$saved_flights = Bid::where('user_id', Auth::id())
->pluck('flight_id')->toArray();
return view('flights.index', [
'airlines' => $this->airlineRepo->selectBoxList(true),
'airports' => $this->airportRepo->selectBoxList(true),
'flights' => $flights,
'saved' => $saved_flights,
]);
}
/**
* Show the flight information page
*
* @param $id
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
* @return mixed
*/
public function show($id)
{

View File

@ -21,6 +21,7 @@ use App\Services\FareService;
use App\Services\GeoService;
use App\Services\PirepService;
use App\Services\UserService;
use App\Support\Units\Fuel;
use App\Support\Units\Time;
use Carbon\Carbon;
use Illuminate\Http\Request;
@ -325,8 +326,13 @@ class PirepController extends Controller
$minutes = (int) $request->input('minutes', 0);
$pirep->flight_time = Utils::hoursToMinutes($hours) + $minutes;
// Set the correct fuel units
$pirep->block_fuel = new Fuel((float) $request->input('block_fuel'), setting('units.fuel'));
$pirep->fuel_used = new Fuel((float) $request->input('fuel_used'), setting('units.fuel'));
// Put the time that this is currently submitted
$attrs['submitted_at'] = Carbon::now('UTC');
$pirep->submitted_at = Carbon::now('UTC');
$pirep = $this->pirepSvc->create($pirep);
$this->saveCustomFields($pirep, $request);

View File

@ -18,10 +18,8 @@ use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;
use Laracasts\Flash\Flash;
use Nwidart\Modules\Facades\Module;
/**
* Class ProfileController
*/
class ProfileController extends Controller
{
private $airlineRepo;
@ -45,6 +43,21 @@ class ProfileController extends Controller
$this->userRepo = $userRepo;
}
/**
* Return whether the vmsACARS module is enabled or not
*/
private function acarsEnabled(): bool
{
// Is the ACARS module enabled?
$acars_enabled = false;
$acars = Module::find('VMSACARS');
if ($acars) {
$acars_enabled = $acars->isEnabled();
}
return $acars_enabled;
}
/**
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
@ -57,6 +70,7 @@ class ProfileController extends Controller
}
return view('profile.index', [
'acars' => $this->acarsEnabled(),
'user' => Auth::user(),
'airports' => $airports,
]);
@ -119,7 +133,7 @@ class ProfileController extends Controller
*
* @throws \Prettus\Validator\Exceptions\ValidatorException
*
* @return $this
* @return mixed
*/
public function update(Request $request)
{
@ -200,4 +214,24 @@ class ProfileController extends Controller
return redirect(route('frontend.profile.index'));
}
/**
* Generate the ACARS config and send it to download
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
*/
public function acars(Request $request)
{
$user = Auth::user();
$config = view('system.acars.config', ['user' => $user])->render();
return response($config)->withHeaders([
'Content-Type' => 'text/xml',
'Content-Length' => strlen($config),
'Cache-Control' => 'no-store, no-cache',
'Content-Disposition' => 'attachment; filename="settings.xml',
]);
}
}

View File

@ -8,9 +8,7 @@ use App\Http\Middleware\InstalledCheck;
use App\Http\Middleware\JsonResponse;
use App\Http\Middleware\RedirectIfAuthenticated;
use App\Http\Middleware\UpdatePending;
use App\Http\Middleware\VerifyCsrfToken;
use Illuminate\Auth\Middleware\Authenticate;
use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
use Illuminate\Auth\Middleware\Authorize;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
@ -42,16 +40,14 @@ class Kernel extends HttpKernel
AddQueuedCookiesToResponse::class,
StartSession::class,
ShareErrorsFromSession::class,
VerifyCsrfToken::class,
// VerifyCsrfToken::class,
SubstituteBindings::class,
//\Spatie\Pjax\Middleware\FilterIfPjax::class,
],
];
protected $routeMiddleware = [
'api.auth' => ApiAuth::class,
'auth' => Authenticate::class,
'auth.basic' => AuthenticateWithBasicAuth::class,
'bindings' => SubstituteBindings::class,
'can' => Authorize::class,
'guest' => RedirectIfAuthenticated::class,

View File

@ -5,12 +5,14 @@
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use App\Models\Enums\UserState;
use App\Models\User;
use Auth;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ApiAuth
class ApiAuth implements Middleware
{
/**
* Handle an incoming request.
@ -20,7 +22,7 @@ class ApiAuth
*
* @return mixed
*/
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next)
{
// Check if Authorization header is in place
$api_key = $request->header('x-api-key', null);

View File

@ -2,9 +2,10 @@
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
class EncryptCookies extends BaseEncrypter
class EncryptCookies extends BaseEncrypter implements Middleware
{
/**
* The names of the cookies that should not be encrypted.

View File

@ -5,17 +5,18 @@
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use Closure;
use Illuminate\Http\Request;
class InstalledCheck
{
/**
* Check the app.key to see whether we're installed or not
*
* If the default key is set and we're not in any of the installer routes
* show the message that we need to be installed
*/
class InstalledCheck implements Middleware
{
public function handle(Request $request, Closure $next)
{
if (config('app.key') === 'base64:zdgcDqu9PM8uGWCtMxd74ZqdGJIrnw812oRMmwDF6KY='

View File

@ -5,11 +5,13 @@
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use Closure;
use Illuminate\Http\Request;
class JsonResponse
class JsonResponse implements Middleware
{
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next)
{
$response = $next($request);
$response->headers->set('Content-Type', 'application/json');

View File

@ -5,19 +5,13 @@
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use Closure;
use Illuminate\Http\Request;
class MeasureExecutionTime
class MeasureExecutionTime implements Middleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next)
{
// Get the response
$response = $next($request);

View File

@ -2,21 +2,14 @@
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
class RedirectIfAuthenticated implements Middleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
*
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
public function handle(Request $request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');

View File

@ -2,17 +2,26 @@
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use Closure;
use Igaster\LaravelTheme\Facades\Theme;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
/**
* Read the current theme from the settings (set in admin), and set it
*/
class SetActiveTheme
class SetActiveTheme implements Middleware
{
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next)
{
try {
$theme = setting('general.theme');
} catch (\Exception $e) {
Log::error($e->getMessage());
$theme = 'default';
}
if (!empty($theme)) {
Theme::set($theme);
}

View File

@ -2,13 +2,15 @@
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use App\Services\Installer\InstallerService;
use Closure;
use Illuminate\Http\Request;
/**
* Determine if an update is pending by checking in with the Installer service
*/
class UpdatePending
class UpdatePending implements Middleware
{
private $installerSvc;
@ -17,13 +19,7 @@ class UpdatePending
$this->installerSvc = $installerSvc;
}
/**
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next)
{
if ($this->installerSvc->isUpgradePending()) {
return redirect('/update/step1');

View File

@ -2,9 +2,10 @@
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
class VerifyCsrfToken extends BaseVerifier implements Middleware
{
/**
* The URIs that should be excluded from CSRF verification.

View File

@ -10,7 +10,7 @@ class CommentRequest extends FormRequest
{
$rules = [
'comment' => 'required',
'created_at' => 'nullable|date',
'created_at' => 'sometimes|date',
];
return $rules;

View File

@ -19,9 +19,9 @@ class EventRequest extends FormRequest
$rules = [
'events' => 'required|array',
'events.*.event' => 'required',
'events.*.lat' => 'nullable|numeric',
'events.*.lon' => 'nullable|numeric',
'events.*.created_at' => 'nullable|date',
'events.*.lat' => 'sometimes|numeric',
'events.*.lon' => 'sometimes|numeric',
'events.*.created_at' => 'sometimes|date',
];
return $rules;

View File

@ -20,28 +20,28 @@ class FileRequest extends FormRequest
'distance' => 'required|numeric',
'flight_time' => 'required|integer',
'fuel_used' => 'required|numeric',
'block_time' => 'nullable|integer',
'airline_id' => 'nullable|exists:airlines,id',
'aircraft_id' => 'nullable|exists:aircraft,id',
'flight_number' => 'nullable',
'flight_type' => 'nullable',
'dpt_airport_id' => 'nullable',
'arr_airport_id' => 'nullable',
'route_code' => 'nullable',
'route_leg' => 'nullable',
'planned_distance' => 'nullable|numeric',
'planned_flight_time' => 'nullable|integer',
'level' => 'nullable|numeric',
'zfw' => 'nullable|numeric',
'block_fuel' => 'nullable|numeric',
'route' => 'nullable',
'notes' => 'nullable',
'source_name' => 'nullable',
'score' => 'nullable|integer',
'landing_rate' => 'nullable|numeric',
'block_off_time' => 'nullable|date',
'block_on_time' => 'nullable|date',
'created_at' => 'nullable|date',
'block_time' => 'sometimes|integer',
'airline_id' => 'sometimes|exists:airlines,id',
'aircraft_id' => 'sometimes|exists:aircraft,id',
'flight_number' => 'sometimes',
'flight_type' => 'sometimes',
'dpt_airport_id' => 'sometimes|size:4',
'arr_airport_id' => 'sometimes|size:4',
'route_code' => 'sometimes',
'route_leg' => 'sometimes',
'planned_distance' => 'sometimes|numeric',
'planned_flight_time' => 'sometimes|integer',
'level' => 'sometimes|numeric',
'zfw' => 'sometimes|numeric',
'block_fuel' => 'sometimes|numeric',
'route' => 'sometimes',
'notes' => 'sometimes',
'source_name' => 'sometimes',
'score' => 'sometimes|integer',
'landing_rate' => 'sometimes|numeric',
'block_off_time' => 'sometimes|date',
'block_on_time' => 'sometimes|date',
'created_at' => 'sometimes|date',
// See if the fare objects are included and formatted properly
'fares' => 'nullable|array',

View File

@ -19,9 +19,9 @@ class LogRequest extends FormRequest
$rules = [
'logs' => 'required|array',
'logs.*.log' => 'required',
'logs.*.lat' => 'nullable|numeric',
'logs.*.lon' => 'nullable|numeric',
'logs.*.created_at' => 'nullable|date',
'logs.*.lat' => 'sometimes|numeric',
'logs.*.lon' => 'sometimes|numeric',
'logs.*.created_at' => 'sometimes|date',
];
return $rules;

View File

@ -23,18 +23,18 @@ class PositionRequest extends FormRequest
'positions' => 'required|array',
'positions.*.lat' => 'required|numeric',
'positions.*.lon' => 'required|numeric',
'positions.*.status' => 'nullable',
'positions.*.altitude' => 'nullable|numeric',
'positions.*.heading' => 'nullable|numeric|between:0,360',
'positions.*.vs' => 'nullable',
'positions.*.gs' => 'nullable',
'positions.*.transponder' => 'nullable',
'positions.*.autopilot' => 'nullable',
'positions.*.fuel' => 'nullable|numeric',
'positions.*.fuel_flow' => 'nullable|numeric',
'positions.*.log' => 'nullable',
'positions.*.sim_time' => 'nullable|date',
'positions.*.created_at' => 'nullable|date',
'positions.*.status' => 'sometimes',
'positions.*.altitude' => 'sometimes|numeric',
'positions.*.heading' => 'sometimes|numeric|between:0,360',
'positions.*.vs' => 'sometimes',
'positions.*.gs' => 'sometimes',
'positions.*.transponder' => 'sometimes',
'positions.*.autopilot' => 'sometimes',
'positions.*.fuel' => 'sometimes|numeric',
'positions.*.fuel_flow' => 'sometimes|numeric',
'positions.*.log' => 'sometimes|nullable',
'positions.*.sim_time' => 'sometimes|date',
'positions.*.created_at' => 'sometimes|date',
];
return $rules;

View File

@ -11,30 +11,30 @@ class PrefileRequest extends FormRequest
$rules = [
'airline_id' => 'required|exists:airlines,id',
'aircraft_id' => 'required|exists:aircraft,id',
'flight_id' => 'sometimes|exists:flights,id',
'flight_number' => 'required',
'dpt_airport_id' => 'required',
'arr_airport_id' => 'required',
'flight_id' => 'nullable',
'dpt_airport_id' => 'required|size:4',
'arr_airport_id' => 'required|size:4',
'source_name' => 'required',
'alt_airport_id' => 'nullable',
'status' => 'nullable',
'alt_airport_id' => 'sometimes|size:4',
'status' => 'sometimes',
'level' => 'nullable|numeric',
'flight_type' => 'nullable',
'route_code' => 'nullable',
'route_leg' => 'nullable',
'distance' => 'nullable|numeric',
'block_time' => 'nullable|integer',
'flight_time' => 'nullable|integer',
'planned_distance' => 'nullable|numeric',
'planned_flight_time' => 'nullable|integer',
'zfw' => 'nullable|numeric',
'block_fuel' => 'nullable|numeric',
'flight_type' => 'sometimes',
'route_code' => 'sometimes',
'route_leg' => 'sometimes',
'distance' => 'sometimes|numeric',
'block_time' => 'sometimes|integer',
'flight_time' => 'sometimes|integer',
'planned_distance' => 'sometimes|numeric',
'planned_flight_time' => 'sometimes|integer',
'zfw' => 'sometimes|numeric',
'block_fuel' => 'sometimes|numeric',
'route' => 'nullable',
'notes' => 'nullable',
'score' => 'nullable|integer',
'block_off_time' => 'nullable|date',
'block_on_time' => 'nullable|date',
'created_at' => 'nullable|date',
'score' => 'sometimes|integer',
'block_off_time' => 'sometimes|date',
'block_on_time' => 'sometimes|date',
'created_at' => 'sometimes|date',
// See if the fare objects are included and formatted properly
'fares' => 'nullable|array',

View File

@ -20,7 +20,7 @@ class RouteRequest extends FormRequest
'route' => 'required|array',
'route.*.name' => 'required',
'route.*.order' => 'required|int',
'route.*.nav_type' => 'nullable|int',
'route.*.nav_type' => 'sometimes|int',
'route.*.lat' => 'required|numeric',
'route.*.lon' => 'required|numeric',
];

View File

@ -19,29 +19,30 @@ class UpdateRequest extends FormRequest
$rules = [
'airline_id' => 'nullable|exists:airlines,id',
'aircraft_id' => 'nullable|exists:aircraft,id',
'flight_number' => 'nullable',
'dpt_airport_id' => 'nullable',
'arr_airport_id' => 'nullable',
'flight_id' => 'sometimes|nullable|exists:flights,id',
'flight_number' => 'sometimes|required',
'dpt_airport_id' => 'sometimes|required|size:4',
'arr_airport_id' => 'sometimes|required|size:4',
'route_code' => 'nullable',
'route_leg' => 'nullable',
'distance' => 'nullable|numeric',
'planned_distance' => 'nullable|numeric',
'block_time' => 'nullable|integer',
'flight_time' => 'nullable|integer',
'distance' => 'sometimes|numeric',
'planned_distance' => 'sometimes|numeric',
'block_time' => 'sometimes|integer',
'flight_time' => 'sometimes|integer',
'flight_type' => 'nullable',
'planned_flight_time' => 'nullable|integer',
'level' => 'nullable|numeric',
'zfw' => 'nullable|numeric',
'fuel_used' => 'nullable|numeric',
'block_fuel' => 'nullable|numeric',
'route' => 'nullable',
'notes' => 'nullable',
'source_name' => 'nullable|max:25',
'landing_rate' => 'nullable|numeric',
'block_off_time' => 'nullable',
'block_on_time' => 'nullable',
'created_at' => 'nullable',
'status' => 'nullable',
'planned_flight_time' => 'sometimes|integer',
'level' => 'sometimes|numeric',
'zfw' => 'sometimes|numeric',
'fuel_used' => 'sometimes|numeric',
'block_fuel' => 'sometimes|numeric',
'route' => 'sometimes|nullable',
'notes' => 'sometimes|nullable',
'source_name' => 'sometimes|max:25',
'landing_rate' => 'sometimes|numeric',
'block_off_time' => 'sometimes|date',
'block_on_time' => 'sometimes|date',
'created_at' => 'sometimes|date',
'status' => 'sometimes',
'score' => 'nullable|integer',
// See if the fare objects are included and formatted properly

View File

@ -2,101 +2,214 @@
/**
* Admin Routes
*/
Route::group([
'namespace' => 'Admin', 'prefix' => 'admin', 'as' => 'admin.',
'middleware' => ['ability:admin,admin-access'],
], static function () {
use Illuminate\Support\Facades\Route;
Route::group(
[
'namespace' => 'Admin',
'prefix' => 'admin',
'as' => 'admin.',
'middleware' => ['auth', 'ability:admin,admin-access'],
],
static function () {
// CRUD for airlines
Route::resource('airlines', 'AirlinesController');
Route::resource('airlines', 'AirlinesController')->middleware('ability:admin,airlines');
// CRUD for roles
Route::resource('roles', 'RolesController');
Route::resource('roles', 'RolesController')->middleware('role:admin');
Route::get('airports/export', 'AirportController@export')->name('airports.export');
Route::match(['get', 'post', 'put'], 'airports/fuel', 'AirportController@fuel');
Route::match(['get', 'post'], 'airports/import', 'AirportController@import')->name('airports.import');
Route::match(['get', 'post', 'put', 'delete'], 'airports/{id}/expenses', 'AirportController@expenses');
Route::resource('airports', 'AirportController');
Route::get('airports/export', 'AirportController@export')
->name('airports.export')
->middleware('ability:admin,airports');
Route::match(['get', 'post', 'put'], 'airports/fuel', 'AirportController@fuel')
->middleware('ability:admin,airports');
Route::match(['get', 'post'], 'airports/import', 'AirportController@import')
->name('airports.import')->middleware('ability:admin,airports');
Route::match(
['get', 'post', 'put', 'delete'],
'airports/{id}/expenses',
'AirportController@expenses'
)->middleware('ability:admin,airports');
Route::resource('airports', 'AirportController')->middleware('ability:admin,airports');
// Awards
Route::resource('awards', 'AwardController');
Route::resource('awards', 'AwardController')->middleware('ability:admin,awards');
// aircraft and fare associations
Route::get('aircraft/export', 'AircraftController@export')->name('aircraft.export');
Route::match(['get', 'post'], 'aircraft/import', 'AircraftController@import')->name('aircraft.import');
Route::match(['get', 'post', 'put', 'delete'], 'aircraft/{id}/expenses', 'AircraftController@expenses');
Route::resource('aircraft', 'AircraftController');
Route::get('aircraft/export', 'AircraftController@export')
->name('aircraft.export')
->middleware('ability:admin,aircraft');
Route::match(['get', 'post'], 'aircraft/import', 'AircraftController@import')
->name('aircraft.import')->middleware('ability:admin,aircraft');
Route::match(
['get', 'post', 'put', 'delete'],
'aircraft/{id}/expenses',
'AircraftController@expenses'
)->middleware('ability:admin,aircraft');
Route::resource('aircraft', 'AircraftController')->middleware('ability:admin,aircraft');
// expenses
Route::get('expenses/export', 'ExpenseController@export')->name('expenses.export');
Route::match(['get', 'post'], 'expenses/import', 'ExpenseController@import')->name('expenses.import');
Route::resource('expenses', 'ExpenseController');
Route::get('expenses/export', 'ExpenseController@export')
->name('expenses.export')
->middleware('ability:admin,finances');
Route::match(['get', 'post'], 'expenses/import', 'ExpenseController@import')
->name('expenses.import')
->middleware('ability:admin,finances');
Route::resource('expenses', 'ExpenseController')->middleware('ability:admin,finances');
// fares
Route::get('fares/export', 'FareController@export')->name('fares.export');
Route::match(['get', 'post'], 'fares/import', 'FareController@import')->name('fares.import');
Route::resource('fares', 'FareController');
Route::get('fares/export', 'FareController@export')
->name('fares.export')
->middleware('ability:admin,finances');
Route::match(['get', 'post'], 'fares/import', 'FareController@import')
->name('fares.import')->middleware('ability:admin,finances');
Route::resource('fares', 'FareController')->middleware('ability:admin,finances');
// files
Route::post('files', 'FileController@store')->name('files.store');
Route::delete('files/{id}', 'FileController@destroy')->name('files.delete');
Route::post('files', 'FileController@store')
->name('files.store')
->middleware('ability:admin,files');
Route::delete('files/{id}', 'FileController@destroy')
->name('files.delete')
->middleware('ability:admin,files');
// finances
Route::resource('finances', 'FinanceController');
Route::resource('finances', 'FinanceController')->middleware('ability:admin,finances');
// flights and aircraft associations
Route::get('flights/export', 'FlightController@export')->name('flights.export');
Route::match(['get', 'post'], 'flights/import', 'FlightController@import')->name('flights.import');
Route::match(['get', 'post', 'put', 'delete'], 'flights/{id}/fares', 'FlightController@fares');
Route::match(['get', 'post', 'put', 'delete'], 'flights/{id}/fields', 'FlightController@field_values');
Route::match(['get', 'post', 'put', 'delete'], 'flights/{id}/subfleets', 'FlightController@subfleets');
Route::resource('flights', 'FlightController');
Route::get('flights/export', 'FlightController@export')
->name('flights.export')
->middleware('ability:admin,flights');
Route::resource('flightfields', 'FlightFieldController');
Route::match(['get', 'post'], 'flights/import', 'FlightController@import')
->name('flights.import')
->middleware('ability:admin,flights');
Route::match(
['get', 'post', 'put', 'delete'],
'flights/{id}/fares',
'FlightController@fares'
)->middleware('ability:admin,flights');
Route::match(
['get', 'post', 'put', 'delete'],
'flights/{id}/fields',
'FlightController@field_values'
)->middleware('ability:admin,flights');
Route::match(
['get', 'post', 'put', 'delete'],
'flights/{id}/subfleets',
'FlightController@subfleets'
)->middleware('ability:admin,flights');
Route::resource('flights', 'FlightController')
->middleware('ability:admin,flights');
Route::resource('flightfields', 'FlightFieldController')
->middleware('ability:admin,flights');
// pirep related routes
Route::get('pireps/fares', 'PirepController@fares');
Route::get('pireps/pending', 'PirepController@pending');
Route::resource('pireps', 'PirepController');
Route::match(['get', 'post', 'delete'], 'pireps/{id}/comments', 'PirepController@comments');
Route::match(['post', 'put'], 'pireps/{id}/status', 'PirepController@status')->name('pirep.status');
Route::get('pireps/fares', 'PirepController@fares')->middleware('ability:admin,pireps');
Route::get('pireps/pending', 'PirepController@pending')->middleware('ability:admin,pireps');
Route::resource('pireps', 'PirepController')->middleware('ability:admin,pireps');
Route::resource('pirepfields', 'PirepFieldController');
Route::match(['get', 'post', 'delete'], 'pireps/{id}/comments', 'PirepController@comments')
->middleware('ability:admin,pireps');
Route::match(['post', 'put'], 'pireps/{id}/status', 'PirepController@status')
->name('pirep.status')
->middleware('ability:admin,pireps');
Route::resource('pirepfields', 'PirepFieldController')
->middleware('ability:admin,pireps');
// rankings
Route::resource('ranks', 'RankController');
Route::match(['get', 'post', 'put', 'delete'], 'ranks/{id}/subfleets', 'RankController@subfleets');
Route::resource('ranks', 'RankController')->middleware('ability:admin,ranks');
Route::match(
['get', 'post', 'put', 'delete'],
'ranks/{id}/subfleets',
'RankController@subfleets'
)->middleware('ability:admin,ranks');
// settings
Route::match(['get'], 'settings', 'SettingsController@index');
Route::match(['post', 'put'], 'settings', 'SettingsController@update')->name('settings.update');
Route::match(['get'], 'settings', 'SettingsController@index')
->middleware('ability:admin,settings');
Route::match(['post', 'put'], 'settings', 'SettingsController@update')
->name('settings.update')
->middleware('ability:admin,settings');
// maintenance
Route::match(['get'], 'maintenance', 'MaintenanceController@index')->name('maintenance.index');
Route::match(['post'], 'maintenance', 'MaintenanceController@cache')->name('maintenance.cache');
Route::match(['get'], 'maintenance', 'MaintenanceController@index')
->name('maintenance.index')
->middleware('ability:admin,maintenance');
Route::match(['post'], 'maintenance', 'MaintenanceController@cache')
->name('maintenance.cache')
->middleware('ability:admin,maintenance');
// subfleet
Route::get('subfleets/export', 'SubfleetController@export')->name('subfleets.export');
Route::match(['get', 'post'], 'subfleets/import', 'SubfleetController@import')->name('subfleets.import');
Route::match(['get', 'post', 'put', 'delete'], 'subfleets/{id}/expenses', 'SubfleetController@expenses');
Route::match(['get', 'post', 'put', 'delete'], 'subfleets/{id}/fares', 'SubfleetController@fares');
Route::match(['get', 'post', 'put', 'delete'], 'subfleets/{id}/ranks', 'SubfleetController@ranks');
Route::resource('subfleets', 'SubfleetController');
Route::get('subfleets/export', 'SubfleetController@export')
->name('subfleets.export')
->middleware('ability:admin,fleet');
Route::resource('users', 'UserController');
Route::match(['get', 'post'], 'subfleets/import', 'SubfleetController@import')
->name('subfleets.import')
->middleware('ability:admin,fleet');
Route::match(
['get', 'post', 'put', 'delete'],
'subfleets/{id}/expenses',
'SubfleetController@expenses'
)->middleware('ability:admin,fleet');
Route::match(
['get', 'post', 'put', 'delete'],
'subfleets/{id}/fares',
'SubfleetController@fares'
)->middleware('ability:admin,fleet');
Route::match(
['get', 'post', 'put', 'delete'],
'subfleets/{id}/ranks',
'SubfleetController@ranks'
)->middleware('ability:admin,fleet');
Route::resource('subfleets', 'SubfleetController')->middleware('ability:admin,fleet');
Route::resource('users', 'UserController')->middleware('ability:admin,users');
Route::get(
'users/{id}/regen_apikey',
'UserController@regen_apikey'
)->name('users.regen_apikey');
)->name('users.regen_apikey')->middleware('ability:admin,users');
// defaults
Route::get('', ['uses' => 'DashboardController@index'])->middleware('update_pending');
Route::get('/', ['uses' => 'DashboardController@index'])->middleware('update_pending');
Route::get('', ['uses' => 'DashboardController@index'])
->middleware('update_pending', 'ability:admin,admin-access');
Route::get('/', ['uses' => 'DashboardController@index'])
->middleware('update_pending', 'ability:admin,admin-access');
Route::get('dashboard', ['uses' => 'DashboardController@index', 'name' => 'dashboard'])
->middleware('update_pending', 'ability:admin,admin-access');
Route::get('dashboard', ['uses' => 'DashboardController@index', 'name' => 'dashboard']);
Route::match(
['get', 'post', 'delete'],
'dashboard/news',
['uses' => 'DashboardController@news']
)->name('dashboard.news');
});
)->name('dashboard.news')->middleware('update_pending', 'ability:admin,admin-access');
}
);

View File

@ -3,6 +3,8 @@
/**
* Public routes
*/
use Illuminate\Support\Facades\Route;
Route::group([], function () {
Route::get('acars', 'AcarsController@live_flights');
Route::get('acars/geojson', 'AcarsController@pireps_geojson');
@ -43,6 +45,8 @@ Route::group(['middleware' => ['api.auth']], function () {
* ACARS related
*/
Route::post('pireps/prefile', 'PirepController@prefile');
Route::post('pireps/{pirep_id}', 'PirepController@update');
Route::patch('pireps/{pirep_id}', 'PirepController@update');
Route::post('pireps/{pirep_id}/update', 'PirepController@update');
Route::post('pireps/{pirep_id}/file', 'PirepController@file');
Route::post('pireps/{pirep_id}/comments', 'PirepController@comments_post');

View File

@ -1,18 +0,0 @@
<?php
use Illuminate\Foundation\Inspiring;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
});

View File

@ -4,6 +4,8 @@
* User doesn't need to be logged in for these
*/
use App\Http\Middleware\SetActiveTheme;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
Route::group([
'namespace' => 'Frontend', 'prefix' => '', 'as' => 'frontend.',
@ -11,8 +13,9 @@ Route::group([
], function () {
Route::get('/', 'HomeController@index')->name('home');
Route::get('r/{id}', 'PirepController@show')->name('pirep.show.public');
Route::get('p/{id}', 'ProfileController@show')->name('profile.show.public');
Route::get('pireps/{id}', 'PirepController@show')->name('pireps.show');
Route::get('p/{id}', 'ProfileController@show')->name('profile.show.public');
Route::get('users', 'UserController@index')->name('users.index');
Route::get('pilots', 'UserController@index')->name('pilots.index');
@ -24,7 +27,7 @@ Route::group([
*/
Route::group([
'namespace' => 'Frontend', 'prefix' => '', 'as' => 'frontend.',
'middleware' => ['role:admin|user', SetActiveTheme::class],
'middleware' => ['auth', SetActiveTheme::class],
], function () {
Route::resource('dashboard', 'DashboardController');
@ -38,12 +41,16 @@ Route::group([
Route::get('flights/search', 'FlightController@search')->name('flights.search');
Route::resource('flights', 'FlightController');
Route::resource('pireps', 'PirepController', [
'except' => ['show'],
]);
Route::get('pireps/fares', 'PirepController@fares');
Route::resource('pireps', 'PirepController');
Route::post('pireps/{id}/submit', 'PirepController@submit')->name('pireps.submit');
Route::get('profile/regen_apikey', 'ProfileController@regen_apikey')
->name('profile.regen_apikey');
Route::get('profile/acars', 'ProfileController@acars')->name('profile.acars');
Route::get('profile/regen_apikey', 'ProfileController@regen_apikey')->name('profile.regen_apikey');
Route::resource('profile', 'ProfileController');
});

View File

@ -4,14 +4,19 @@ namespace App\Listeners;
use App\Contracts\Listener;
use App\Events\PirepAccepted;
use App\Events\PirepRejected;
use App\Services\BidService;
use Illuminate\Contracts\Events\Dispatcher;
/**
* Do stuff with bids - like if a PIREP is accepted, then remove the bid
*/
class BidEvents extends Listener
class BidEventHandler extends Listener
{
public static $callbacks = [
PirepAccepted::class => 'onPirepAccept',
PirepRejected::class => 'onPirepReject',
];
private $bidSvc;
public function __construct(BidService $bidSvc)
@ -19,17 +24,6 @@ class BidEvents extends Listener
$this->bidSvc = $bidSvc;
}
/**
* @param $events
*/
public function subscribe(Dispatcher $events): void
{
$events->listen(
PirepAccepted::class,
'App\Listeners\BidEvents@onPirepAccept'
);
}
/**
* When a PIREP is accepted, remove any bids
*
@ -43,4 +37,18 @@ class BidEvents extends Listener
{
$this->bidSvc->removeBidForPirep($event->pirep);
}
/**
* When a PIREP is accepted, remove any bids
*
* @param PirepRejected $event
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Exception
*/
public function onPirepReject(PirepRejected $event): void
{
$this->bidSvc->removeBidForPirep($event->pirep);
}
}

View File

@ -5,9 +5,6 @@ namespace App\Listeners;
use App\Contracts\Listener;
use App\Events\Expenses;
/**
* Class ExpenseListener
*/
class ExpenseListener extends Listener
{
/**

View File

@ -6,41 +6,23 @@ use App\Contracts\Listener;
use App\Events\PirepAccepted;
use App\Events\PirepRejected;
use App\Services\Finance\PirepFinanceService;
use Illuminate\Contracts\Events\Dispatcher;
/**
* Subscribe for events that we do some financial processing for
* This includes when a PIREP is accepted, or rejected
*/
class FinanceEvents extends Listener
class FinanceEventHandler extends Listener
{
private $financeSvc;
/**
* FinanceEvents constructor.
*
* @param PirepFinanceService $financeSvc
*/
public function __construct(
PirepFinanceService $financeSvc
) {
$this->financeSvc = $financeSvc;
}
public static $callbacks = [
PirepAccepted::class => 'onPirepAccept',
PirepRejected::class => 'onPirepReject',
];
/**
* @param $events
*/
public function subscribe(Dispatcher $events): void
public function __construct(PirepFinanceService $financeSvc)
{
$events->listen(
PirepAccepted::class,
'App\Listeners\FinanceEvents@onPirepAccept'
);
$events->listen(
PirepRejected::class,
'App\Listeners\FinanceEvents@onPirepReject'
);
$this->financeSvc = $financeSvc;
}
/**

View File

@ -7,7 +7,7 @@ use App\Events\PirepFiled;
use App\Events\UserStateChanged;
use App\Models\Enums\UserState;
class SetUserActive extends Listener
class UserStateListener extends Listener
{
public function handle(PirepFiled $event): void
{

View File

@ -6,6 +6,7 @@ use App\Contracts\Model;
use App\Models\Enums\AircraftStatus;
use App\Models\Traits\ExpensableTrait;
use App\Models\Traits\FilesTrait;
use Carbon\Carbon;
/**
* @property int id

View File

@ -66,10 +66,10 @@ class Airport extends Model
* Validation rules
*/
public static $rules = [
'icao' => 'required',
'iata' => 'nullable',
'icao' => 'required|size:4',
'iata' => 'sometimes|nullable',
'name' => 'required',
'location' => 'nullable',
'location' => 'sometimes',
'lat' => 'required|numeric',
'lon' => 'required|numeric',
'ground_handling_cost' => 'nullable|numeric',

View File

@ -93,8 +93,8 @@ class Flight extends Model
'flight_number' => 'required',
'route_code' => 'nullable',
'route_leg' => 'nullable',
'dpt_airport_id' => 'required',
'arr_airport_id' => 'required',
'dpt_airport_id' => 'required|size:4|exists:airports,id',
'arr_airport_id' => 'required|size:4|exists:airports,id',
'level' => 'nullable',
];

View File

@ -11,7 +11,7 @@ use App\Support\Money;
use Carbon\Carbon;
/**
* Class Journal
* Holds various journals, depending on the morphed_type and morphed_id columns
*
* @property mixed id
* @property Money $balance

View File

@ -4,6 +4,10 @@ namespace App\Models;
use App\Contracts\Model;
/**
* @property string subject
* @property string body
*/
class News extends Model
{
public $table = 'news';

View File

@ -4,6 +4,9 @@ namespace App\Models;
use Laratrust\Models\LaratrustPermission;
/**
* @method static firstOrCreate(array $array, array $array1)
*/
class Permission extends LaratrustPermission
{
}

View File

@ -126,8 +126,8 @@ class Pirep extends Model
'flight_number' => 'required',
'dpt_airport_id' => 'required',
'arr_airport_id' => 'required',
'block_fuel' => 'required|numeric',
'fuel_used' => 'required|numeric',
'block_fuel' => 'sometimes|numeric',
'fuel_used' => 'sometimes|numeric',
'level' => 'nullable|numeric',
'notes' => 'nullable',
'route' => 'nullable',
@ -260,16 +260,17 @@ class Pirep extends Model
*/
public function getProgressPercentAttribute()
{
$upper_bound = $this->distance['nmi'];
$distance = $this->distance;
$upper_bound = $distance;
if ($this->planned_distance) {
$upper_bound = $this->planned_distance['nmi'];
$upper_bound = $this->planned_distance;
}
if (!$upper_bound) {
$upper_bound = 1;
}
$upper_bound = empty($upper_bound) ? 1 : $upper_bound;
$distance = empty($distance) ? $upper_bound : $distance;
return round(($this->distance['nmi'] / $upper_bound) * 100, 0);
return round(($distance / $upper_bound) * 100, 0);
}
/**
@ -419,7 +420,16 @@ class Pirep extends Model
public function arr_airport()
{
return $this->belongsTo(Airport::class, 'arr_airport_id');
return $this->belongsTo(Airport::class, 'arr_airport_id')
->withDefault(function ($model) {
if (!empty($this->attributes['arr_airport_id'])) {
$model->id = $this->attributes['arr_airport_id'];
$model->icao = $this->attributes['arr_airport_id'];
$model->name = $this->attributes['arr_airport_id'];
}
return $model;
});
}
public function alt_airport()
@ -429,7 +439,16 @@ class Pirep extends Model
public function dpt_airport()
{
return $this->belongsTo(Airport::class, 'dpt_airport_id');
return $this->belongsTo(Airport::class, 'dpt_airport_id')
->withDefault(function ($model) {
if (!empty($this->attributes['dpt_airport_id'])) {
$model->id = $this->attributes['dpt_airport_id'];
$model->icao = $this->attributes['dpt_airport_id'];
$model->name = $this->attributes['dpt_airport_id'];
}
return $model;
});
}
public function comments()

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