Apply fixes from StyleCI

This commit is contained in:
Nabeel Shahzad
2018-08-26 16:40:04 +00:00
committed by StyleCI Bot
parent 20f46adbc4
commit 9596d88b48
407 changed files with 4032 additions and 3286 deletions

View File

@@ -11,7 +11,6 @@ use PDO;
/**
* Class AnalyticsService
* @package App\Services
*/
class AnalyticsService extends Service
{
@@ -24,13 +23,13 @@ class AnalyticsService extends Service
return;
}
# some analytics
// some analytics
$gamp = GAMP::setClientId(uniqid('', true));
$gamp->setDocumentPath('/install');
$gamp->setCustomDimension(PHP_VERSION, AnalyticsDimensions::PHP_VERSION);
# figure out database version
// figure out database version
$pdo = DB::connection()->getPdo();
$gamp->setCustomDimension(
strtolower($pdo->getAttribute(PDO::ATTR_SERVER_VERSION)),

View File

@@ -8,12 +8,12 @@ use Module;
/**
* Class AwardService
* @package App\Services
*/
class AwardService extends Service
{
/**
* Find any of the award classes
*
* @return \App\Interfaces\Award[]
*/
public function findAllAwardClasses(): array
@@ -21,11 +21,11 @@ class AwardService extends Service
$awards = [];
$formatted_awards = [];
# Find the awards in the app/Awards directory
// Find the awards in the app/Awards directory
$classes = ClassLoader::getClassesInPath(app_path('/Awards'));
$awards = array_merge($awards, $classes);
# Look throughout all the other modules, in the module/{MODULE}/Awards directory
// Look throughout all the other modules, in the module/{MODULE}/Awards directory
foreach (Module::all() as $module) {
$path = $module->getExtraPath('Awards');
$classes = ClassLoader::getClassesInPath($path);

View File

@@ -9,13 +9,12 @@ use Webpatser\Uuid\Uuid;
/**
* Class DatabaseService
* @package App\Services
*/
class DatabaseService extends Service
{
protected $time_fields = [
'created_at',
'updated_at'
'updated_at',
];
protected $uuid_tables = [
@@ -35,8 +34,10 @@ class DatabaseService extends Service
/**
* @param $yaml_file
* @param bool $ignore_errors
* @return array
*
* @throws \Exception
*
* @return array
*/
public function seed_from_yaml_file($yaml_file, $ignore_errors = false): array
{
@@ -46,8 +47,10 @@ class DatabaseService extends Service
/**
* @param $yml
* @param bool $ignore_errors
* @return array
*
* @throws \Exception
*
* @return array
*/
public function seed_from_yaml($yml, $ignore_errors = false): array
{
@@ -55,14 +58,17 @@ class DatabaseService extends Service
}
/**
* @param $table
* @param $row
* @return mixed
* @param $table
* @param $row
*
* @throws \Exception
*
* @return mixed
*/
public function insert_row($table, $row) {
# see if this table uses a UUID as the PK
# if no ID is specified
public function insert_row($table, $row)
{
// see if this table uses a UUID as the PK
// if no ID is specified
if (\in_array($table, $this->uuid_tables, true)) {
if (!array_key_exists('id', $row)) {
$row['id'] = Uuid::generate()->string;

View File

@@ -11,19 +11,19 @@ use App\Services\ImportExport\FareExporter;
use App\Services\ImportExport\FlightExporter;
use App\Services\ImportExport\SubfleetExporter;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use League\Csv\CharsetConverter;
use League\Csv\Writer;
use Illuminate\Support\Facades\Storage;
use Log;
/**
* Class ExportService
* @package App\Services
*/
class ExportService extends Service
{
/**
* @param string $path
* @param string $path
*
* @return Writer
*/
public function openCsv($path): Writer
@@ -35,20 +35,23 @@ class ExportService extends Service
/**
* Run the actual importer
*
* @param Collection $collection
* @param ImportExport $exporter
* @return string
*
* @throws \League\Csv\CannotInsertRecord
*
* @return string
*/
protected function runExport(Collection $collection, ImportExport $exporter): string
{
$filename = 'export_' . $exporter->assetType . '.csv';
$filename = 'export_'.$exporter->assetType.'.csv';
// Create the directory - makes it inside of storage/app
Storage::makeDirectory('import');
$path = storage_path('/app/import/export_'.$filename.'.csv');
Log::info('Exporting "'.$exporter->assetType.'" to ' . $path);
Log::info('Exporting "'.$exporter->assetType.'" to '.$path);
$writer = $this->openCsv($path);
@@ -65,9 +68,12 @@ class ExportService extends Service
/**
* Export all of the aircraft
*
* @param Collection $aircraft
* @return mixed
*
* @throws \League\Csv\CannotInsertRecord
*
* @return mixed
*/
public function exportAircraft($aircraft)
{
@@ -77,9 +83,12 @@ class ExportService extends Service
/**
* Export all of the airports
*
* @param Collection $airports
* @return mixed
*
* @throws \League\Csv\CannotInsertRecord
*
* @return mixed
*/
public function exportAirports($airports)
{
@@ -89,9 +98,12 @@ class ExportService extends Service
/**
* Export all of the airports
*
* @param Collection $expenses
* @return mixed
*
* @throws \League\Csv\CannotInsertRecord
*
* @return mixed
*/
public function exportExpenses($expenses)
{
@@ -101,9 +113,12 @@ class ExportService extends Service
/**
* Export all of the fares
*
* @param Collection $fares
* @return mixed
*
* @throws \League\Csv\CannotInsertRecord
*
* @return mixed
*/
public function exportFares($fares)
{
@@ -113,9 +128,12 @@ class ExportService extends Service
/**
* Export all of the flights
*
* @param Collection $flights
* @return mixed
*
* @throws \League\Csv\CannotInsertRecord
*
* @return mixed
*/
public function exportFlights($flights)
{
@@ -125,9 +143,12 @@ class ExportService extends Service
/**
* Export all of the flights
*
* @param Collection $subfleets
* @return mixed
*
* @throws \League\Csv\CannotInsertRecord
*
* @return mixed
*/
public function exportSubfleets($subfleets)
{

View File

@@ -13,7 +13,6 @@ use Illuminate\Support\Collection;
/**
* Class FareService
* @package App\Services
*/
class FareService extends Service
{
@@ -24,8 +23,10 @@ class FareService extends Service
* final "authoritative" list of the fares for a flight.
*
* If a subfleet is passed in,
*
* @param Flight|null $flight
* @param Subfleet|null $subfleet
*
* @return Collection
*/
public function getAllFares($flight, $subfleet)
@@ -38,8 +39,8 @@ class FareService extends Service
$subfleet_fares = $this->getForSubfleet($subfleet);
# Go through all of the fares assigned by the subfleet
# See if any of the same fares are assigned to the flight
// Go through all of the fares assigned by the subfleet
// See if any of the same fares are assigned to the flight
$fares = $subfleet_fares->map(function ($fare, $idx) use ($flight_fares) {
$flight_fare = $flight_fares->whereStrict('id', $fare->id)->first();
if (!$flight_fare) {
@@ -54,7 +55,9 @@ class FareService extends Service
/**
* Get fares
*
* @param $fare
*
* @return mixed
*/
protected function getFares($fare)
@@ -92,19 +95,20 @@ class FareService extends Service
* @param Flight $flight
* @param Fare $fare
* @param array set the price/cost/capacity
*
* @return Flight
*/
public function setForFlight(Flight $flight, Fare $fare, array $override = []): Flight
{
$flight->fares()->syncWithoutDetaching([$fare->id]);
foreach($override as $key => $item) {
if(!$item) {
foreach ($override as $key => $item) {
if (!$item) {
unset($override[$key]);
}
}
# modify any pivot values?
// modify any pivot values?
if (\count($override) > 0) {
$flight->fares()->updateExistingPivot($fare->id, $override);
}
@@ -119,7 +123,9 @@ class FareService extends Service
* return all the fares for a flight. check the pivot
* table to see if the price/cost/capacity has been overridden
* and return the correct amounts.
*
* @param Flight $flight
*
* @return Collection
*/
public function getForFlight(Flight $flight)
@@ -134,6 +140,7 @@ class FareService extends Service
/**
* @param Flight $flight
* @param Fare $fare
*
* @return Flight
*/
public function delFareFromFlight(Flight $flight, Fare $fare)
@@ -150,13 +157,14 @@ class FareService extends Service
* @param Subfleet $subfleet
* @param Fare $fare
* @param array set the price/cost/capacity
*
* @return Subfleet
*/
public function setForSubfleet(Subfleet $subfleet, Fare $fare, array $override = []): Subfleet
{
$subfleet->fares()->syncWithoutDetaching([$fare->id]);
# modify any pivot values?
// modify any pivot values?
if (count($override) > 0) {
$subfleet->fares()->updateExistingPivot($fare->id, $override);
}
@@ -171,7 +179,9 @@ class FareService extends Service
* return all the fares for an aircraft. check the pivot
* table to see if the price/cost/capacity has been overridden
* and return the correct amounts.
*
* @param Subfleet $subfleet
*
* @return Collection
*/
public function getForSubfleet(Subfleet $subfleet)
@@ -185,8 +195,10 @@ class FareService extends Service
/**
* Delete the fare from a subfleet
*
* @param Subfleet $subfleet
* @param Fare $fare
*
* @return Subfleet|null|static
*/
public function delFareFromSubfleet(Subfleet &$subfleet, Fare &$fare)
@@ -200,7 +212,9 @@ class FareService extends Service
/**
* Get the fares for a PIREP, this just returns the PirepFare
* model which includes the counts for that particular fare
*
* @param Pirep $pirep
*
* @return Collection
*/
public function getForPirep(Pirep $pirep)
@@ -213,8 +227,10 @@ class FareService extends Service
/**
* Save the list of fares
*
* @param Pirep $pirep
* @param array $fares ['fare_id', 'count']
*
* @throws \Exception
*/
public function saveForPirep(Pirep $pirep, array $fares)
@@ -223,13 +239,13 @@ class FareService extends Service
return;
}
# Remove all the previous fares
// Remove all the previous fares
PirepFare::where('pirep_id', $pirep->id)->delete();
# Add them in
// Add them in
foreach ($fares as $fare) {
$fare['pirep_id'] = $pirep->id;
# other fields: ['fare_id', 'count']
// other fields: ['fare_id', 'count']
$field = new PirepFare($fare);
$field->save();

View File

@@ -7,17 +7,19 @@ use App\Models\File;
/**
* Class FileService
* @package App\Services
*/
class FileService extends Service
{
/**
* Save a file to disk and return a File asset
*
* @param \Illuminate\Http\UploadedFile $file
* @param string $folder
* @param array $attrs
* @return File
*
* @throws \Hashids\HashidsException
*
* @return File
*/
public function saveFile($file, $folder, array $attrs)
{
@@ -33,12 +35,12 @@ class FileService extends Service
$id = File::createNewHashId();
$path_info = pathinfo($file->getClientOriginalName());
# Create the file, add the ID to the front of the file to account
# for any duplicate filenames, but still can be found in an `ls`
// Create the file, add the ID to the front of the file to account
// for any duplicate filenames, but still can be found in an `ls`
$filename = $id . '_'
. str_slug(trim($path_info['filename']))
. '.' . $path_info['extension'];
$filename = $id.'_'
.str_slug(trim($path_info['filename']))
.'.'.$path_info['extension'];
$file_path = $file->storeAs($folder, $filename, $attrs['disk']);

View File

@@ -18,18 +18,17 @@ use Log;
/**
* Class FinanceService
* @package App\Services
*
*/
class PirepFinanceService extends Service
{
private $expenseRepo,
$fareSvc,
$journalRepo,
$pirepSvc;
private $expenseRepo;
private $fareSvc;
private $journalRepo;
private $pirepSvc;
/**
* FinanceService constructor.
*
* @param ExpenseRepository $expenseRepo
* @param FareService $fareSvc
* @param JournalRepository $journalRepo
@@ -40,8 +39,7 @@ class PirepFinanceService extends Service
FareService $fareSvc,
JournalRepository $journalRepo,
PirepService $pirepSvc
)
{
) {
$this->expenseRepo = $expenseRepo;
$this->fareSvc = $fareSvc;
$this->journalRepo = $journalRepo;
@@ -51,12 +49,15 @@ class PirepFinanceService extends Service
/**
* Process all of the finances for a pilot report. This is called
* from a listener (FinanceEvents)
*
* @param Pirep $pirep
* @return mixed
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Prettus\Validator\Exceptions\ValidatorException
* @throws \Exception
*
* @return mixed
*/
public function processFinancesForPirep(Pirep $pirep)
{
@@ -68,12 +69,12 @@ class PirepFinanceService extends Service
$pirep->user->journal = $pirep->user->initJournal(config('phpvms.currency'));
}
# Clean out the expenses first
// Clean out the expenses first
$this->deleteFinancesForPirep($pirep);
Log::info('Finance: Starting PIREP pay for '.$pirep->id);
# Now start and pay from scratch
// Now start and pay from scratch
$this->payFaresForPirep($pirep);
$this->payExpensesForSubfleet($pirep);
$this->payExpensesForPirep($pirep);
@@ -102,7 +103,9 @@ class PirepFinanceService extends Service
/**
* Collect all of the fares and then post each fare class's profit and
* the costs for each seat and post it to the journal
*
* @param $pirep
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Prettus\Validator\Exceptions\ValidatorException
@@ -137,7 +140,9 @@ class PirepFinanceService extends Service
/**
* Calculate what the cost is for the operating an aircraft
* in this subfleet, as-per the block time
*
* @param Pirep $pirep
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Prettus\Validator\Exceptions\ValidatorException
@@ -146,18 +151,18 @@ class PirepFinanceService extends Service
{
$sf = $pirep->aircraft->subfleet;
# Haven't entered a cost
// Haven't entered a cost
if (!filled($sf->cost_block_hour)) {
return;
}
# Convert to cost per-minute
// Convert to cost per-minute
$cost_per_min = round($sf->cost_block_hour / 60, 2);
# Time to use - use the block time if it's there, actual
# flight time if that hasn't been used
// Time to use - use the block time if it's there, actual
// flight time if that hasn't been used
$block_time = $pirep->block_time;
if(!filled($block_time)) {
if (!filled($block_time)) {
Log::info('Finance: No block time, using PIREP flight time');
$block_time = $pirep->flight_time;
}
@@ -179,7 +184,9 @@ class PirepFinanceService extends Service
/**
* Collect all of the expenses and apply those to the journal
*
* @param Pirep $pirep
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
*/
@@ -190,7 +197,7 @@ class PirepFinanceService extends Service
$pirep->airline_id
);
/**
/*
* Go through the expenses and apply a mulitplier if present
*/
$expenses->map(function ($expense, $i) use ($pirep) {
@@ -200,16 +207,16 @@ class PirepFinanceService extends Service
Log::info('Finance: PIREP: '.$pirep->id.', expense:', $expense->toArray());
# Get the transaction group name from the ref_model name
# This way it can be more dynamic and don't have to add special
# tables or specific expense calls to accomodate all of these
// Get the transaction group name from the ref_model name
// This way it can be more dynamic and don't have to add special
// tables or specific expense calls to accomodate all of these
$klass = 'Expense';
if ($expense->ref_model) {
$ref = explode('\\', $expense->ref_model);
$klass = end($ref);
}
# Form the memo, with some specific ones depending on the group
// Form the memo, with some specific ones depending on the group
if ($klass === 'Airport') {
$memo = "Airport Expense: {$expense->name} ({$expense->ref_model_id})";
$transaction_group = "Airport: {$expense->ref_model_id}";
@@ -227,8 +234,8 @@ class PirepFinanceService extends Service
$debit = Money::createFromAmount($expense->amount);
# If the expense is marked to charge it to a user (only applicable to Flight)
# then change the journal to the user's to debit there
// If the expense is marked to charge it to a user (only applicable to Flight)
// then change the journal to the user's to debit there
$journal = $pirep->airline->journal;
if ($expense->charge_to_user) {
$journal = $pirep->user->journal;
@@ -249,7 +256,9 @@ class PirepFinanceService extends Service
/**
* Collect all of the expenses from the listeners and apply those to the journal
*
* @param Pirep $pirep
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Prettus\Validator\Exceptions\ValidatorException
@@ -270,7 +279,7 @@ class PirepFinanceService extends Service
}
foreach ($event_expense as $expense) {
# Make sure it's of type expense Model
// Make sure it's of type expense Model
if (!($expense instanceof Expense)) {
continue;
}
@@ -278,8 +287,8 @@ class PirepFinanceService extends Service
Log::info('Finance: Expense from listener, N="'
.$expense->name.'", A='.$expense->amount);
# If an airline_id is filled, then see if it matches
if(filled($expense->airline_id) && $expense->airline_id !== $pirep->airline_id) {
// If an airline_id is filled, then see if it matches
if (filled($expense->airline_id) && $expense->airline_id !== $pirep->airline_id) {
Log::info('Finance: Expense has an airline ID and it doesn\'t match, skipping');
continue;
}
@@ -302,7 +311,9 @@ class PirepFinanceService extends Service
/**
* Collect and apply the ground handling cost
*
* @param Pirep $pirep
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Prettus\Validator\Exceptions\ValidatorException
@@ -326,7 +337,9 @@ class PirepFinanceService extends Service
/**
* Figure out what the pilot pay is. Debit it from the airline journal
* But also reference the PIREP
*
* @param Pirep $pirep
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Prettus\Validator\Exceptions\ValidatorException
@@ -373,12 +386,14 @@ class PirepFinanceService extends Service
* capacity = max number of pax units
*
* If count > capacity, count will be adjusted to capacity
*
* @param $pirep
*
* @return \Illuminate\Support\Collection
*/
public function getReconciledFaresForPirep($pirep)
{
# Collect all of the fares and prices
// Collect all of the fares and prices
$flight_fares = $this->fareSvc->getForPirep($pirep);
Log::info('Finance: PIREP: '.$pirep->id.', flight fares: ', $flight_fares->toArray());
@@ -392,8 +407,8 @@ class PirepFinanceService extends Service
if ($fare_count) {
Log::info('Finance: PIREP: '.$pirep->id.', fare count: '.$fare_count);
# If the count is greater than capacity, then just set it
# to the maximum amount
// If the count is greater than capacity, then just set it
// to the maximum amount
if ($fare_count->count > $fare->capacity) {
$fare->count = $fare->capacity;
} else {
@@ -412,7 +427,9 @@ class PirepFinanceService extends Service
/**
* Return the costs for the ground handling, with the multiplier
* being applied from the subfleet
*
* @param Pirep $pirep
*
* @return float|null
*/
public function getGroundHandlingCost(Pirep $pirep)
@@ -432,17 +449,20 @@ class PirepFinanceService extends Service
/**
* Return the pilot's hourly pay for the given PIREP
*
* @param Pirep $pirep
* @return float
*
* @throws \InvalidArgumentException
*
* @return float
*/
public function getPilotPayRateForPirep(Pirep $pirep)
{
# Get the base rate for the rank
// Get the base rate for the rank
$rank = $pirep->user->rank;
$subfleet_id = $pirep->aircraft->subfleet_id;
# find the right subfleet
// find the right subfleet
$override_rate = $rank->subfleets()
->where('subfleet_id', $subfleet_id)
->first();
@@ -477,10 +497,13 @@ class PirepFinanceService extends Service
/**
* Get the user's payment amount for a PIREP
*
* @param Pirep $pirep
* @return Money
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
*
* @return Money
*/
public function getPilotPay(Pirep $pirep)
{

View File

@@ -13,7 +13,6 @@ use Log;
/**
* Process all of the daily expenses and charge them
* @package App\Services\Finance
*/
class RecurringFinanceService extends Service
{
@@ -21,6 +20,7 @@ class RecurringFinanceService extends Service
/**
* RecurringFinanceService constructor.
*
* @param JournalRepository $journalRepo
*/
public function __construct(JournalRepository $journalRepo)
@@ -31,7 +31,9 @@ class RecurringFinanceService extends Service
/**
* Determine the journal to charge to, otherwise, it's charged
* to every airline journal
*
* @param Expense $expense
*
* @return \Generator
*/
protected function findJournals(Expense $expense)
@@ -51,7 +53,9 @@ class RecurringFinanceService extends Service
/**
* Get the name of the transaction group from the expense
*
* @param Expense $expense
*
* @return array
*/
protected function getMemoAndGroup(Expense $expense): array
@@ -82,7 +86,9 @@ class RecurringFinanceService extends Service
/**
* Run all of the daily expense/financials
*
* @param int $type
*
* @throws \UnexpectedValueException
* @throws \InvalidArgumentException
* @throws \Prettus\Validator\Exceptions\ValidatorException
@@ -102,13 +108,13 @@ class RecurringFinanceService extends Service
* @var $expenses Expense[]
*/
foreach ($expenses as $expense) {
# Apply the expenses to the appropriate journals
// Apply the expenses to the appropriate journals
$journals = $this->findJournals($expense);
foreach ($journals as $journal) {
$amount = $expense->amount;
# Has this expense already been charged? Check
# against this specific journal, on today
// Has this expense already been charged? Check
// against this specific journal, on today
$w = [
'journal_id' => $journal->id,
'ref_model' => Expense::class,

View File

@@ -9,7 +9,6 @@ use App\Models\Subfleet;
/**
* Class FleetService
* @package App\Services
*/
class FleetService extends Service
{
@@ -17,6 +16,7 @@ class FleetService extends Service
* @param Subfleet $subfleet
* @param Rank $rank
* @param array $overrides
*
* @return Subfleet
*/
public function addSubfleetToRank(Subfleet $subfleet, Rank $rank, array $overrides = [])
@@ -45,6 +45,7 @@ class FleetService extends Service
/**
* Add the subfleet to a flight
*
* @param Subfleet $subfleet
* @param Flight $flight
*/
@@ -57,6 +58,7 @@ class FleetService extends Service
/**
* Remove the subfleet from a flight
*
* @param Subfleet $subfleet
* @param Flight $flight
*/

View File

@@ -14,17 +14,17 @@ use Log;
/**
* Class FlightService
* @package App\Services
*/
class FlightService extends Service
{
private $fareSvc,
$flightRepo,
$navDataRepo,
$userSvc;
private $fareSvc;
private $flightRepo;
private $navDataRepo;
private $userSvc;
/**
* FlightService constructor.
*
* @param FareService $fareSvc
* @param FlightRepository $flightRepo
* @param NavdataRepository $navdataRepo
@@ -35,8 +35,7 @@ class FlightService extends Service
FlightRepository $flightRepo,
NavdataRepository $navdataRepo,
UserService $userSvc
)
{
) {
$this->fareSvc = $fareSvc;
$this->flightRepo = $flightRepo;
$this->navDataRepo = $navdataRepo;
@@ -45,7 +44,9 @@ class FlightService extends Service
/**
* Filter out any flights according to different settings
*
* @param $user
*
* @return FlightRepository
*/
public function filterFlights($user)
@@ -61,15 +62,17 @@ class FlightService extends Service
/**
* Filter out subfleets to only include aircraft that a user has access to
*
* @param $user
* @param $flight
*
* @return mixed
*/
public function filterSubfleets($user, $flight)
{
$subfleets = $flight->subfleets;
/**
/*
* Only allow aircraft that the user has access to in their rank
*/
if (setting('pireps.restrict_aircraft_to_rank', false)) {
@@ -81,7 +84,7 @@ class FlightService extends Service
});
}
/**
/*
* Only allow aircraft that are at the current departure airport
*/
if (setting('pireps.only_aircraft_at_dpt_airport', false)) {
@@ -103,7 +106,9 @@ class FlightService extends Service
/**
* Check if this flight has a duplicate already
*
* @param Flight $flight
*
* @return bool
*/
public function isFlightDuplicate(Flight $flight)
@@ -140,7 +145,9 @@ class FlightService extends Service
/**
* Delete a flight, and all the user bids, etc associated with it
*
* @param Flight $flight
*
* @throws \Exception
*/
public function deleteFlight(Flight $flight): void
@@ -152,6 +159,7 @@ class FlightService extends Service
/**
* Update any custom PIREP fields
*
* @param Flight $flight
* @param array $field_values
*/
@@ -164,7 +172,7 @@ class FlightService extends Service
'name' => $fv['name'],
],
[
'value' => $fv['value']
'value' => $fv['value'],
]
);
}
@@ -172,7 +180,9 @@ class FlightService extends Service
/**
* Return all of the navaid points as a collection
*
* @param Flight $flight
*
* @return \Illuminate\Support\Collection
*/
public function getRoute(Flight $flight)
@@ -198,30 +208,33 @@ class FlightService extends Service
/**
* Allow a user to bid on a flight. Check settings and all that good stuff
*
* @param Flight $flight
* @param User $user
* @return mixed
*
* @throws \App\Exceptions\BidExists
*
* @return mixed
*/
public function addBid(Flight $flight, User $user)
{
# Get all of the bids for this user. See if they're allowed to have multiple
# bids
// Get all of the bids for this user. See if they're allowed to have multiple
// bids
$bids = Bid::where('user_id', $user->id)->get();
if ($bids->count() > 0 && setting('bids.allow_multiple_bids') === false) {
throw new BidExists('User "'.$user->ident.'" already has bids, skipping');
}
# Get all of the bids for this flight
// Get all of the bids for this flight
$bids = Bid::where('flight_id', $flight->id)->get();
if ($bids->count() > 0) {
# Does the flight have a bid set?
// Does the flight have a bid set?
if ($flight->has_bid === false) {
$flight->has_bid = true;
$flight->save();
}
# Check all the bids for one of this user
// Check all the bids for one of this user
foreach ($bids as $bid) {
if ($bid->user_id === $user->id) {
Log::info('Bid exists, user='.$user->ident.', flight='.$flight->id);
@@ -229,7 +242,7 @@ class FlightService extends Service
}
}
# Check if the flight should be blocked off
// Check if the flight should be blocked off
if (setting('bids.disable_flight_on_bid') === true) {
throw new BidExists('Flight "'.$flight->ident.'" already has a bid, skipping');
}
@@ -256,6 +269,7 @@ class FlightService extends Service
/**
* Remove a bid from a given flight
*
* @param Flight $flight
* @param User $user
*/
@@ -263,14 +277,14 @@ class FlightService extends Service
{
$bids = Bid::where([
'flight_id' => $flight->id,
'user_id' => $user->id
'user_id' => $user->id,
])->get();
foreach ($bids as $bid) {
$bid->forceDelete();
}
# Only flip the flag if there are no bids left for this flight
// Only flip the flag if there are no bids left for this flight
$bids = Bid::where('flight_id', $flight->id)->get();
if ($bids->count() === 0) {
$flight->has_bid = false;

View File

@@ -18,14 +18,15 @@ use Log;
/**
* Class GeoService
* @package App\Services
*/
class GeoService extends Service
{
private $acarsRepo, $navRepo;
private $acarsRepo;
private $navRepo;
/**
* GeoService constructor.
*
* @param AcarsRepository $acarsRepo
* @param NavdataRepository $navRepo
*/
@@ -39,10 +40,13 @@ class GeoService extends Service
/**
* Determine the closest set of coordinates from the starting position
*
* @param array $coordStart
* @param array $all_coords
* @return mixed
*
* @throws \League\Geotools\Exception\InvalidArgumentException
*
* @return mixed
*/
public function getClosestCoords($coordStart, $all_coords)
{
@@ -66,10 +70,12 @@ class GeoService extends Service
* Pass in a route string, with the departure/arrival airports, and the
* starting coordinates. Return the route points that have been found
* from the `navdata` table
*
* @param $dep_icao string ICAO to ignore
* @param $arr_icao string ICAO to ignore
* @param $start_coords array Starting point, [x, y]
* @param $route string Textual route
*
* @return array
*/
public function getCoordsFromRoute($dep_icao, $arr_icao, $start_coords, $route): array
@@ -114,12 +120,12 @@ class GeoService extends Service
continue;
}
# Find the point with the shortest distance
// Find the point with the shortest distance
Log::info('found '.$size.' for '.$route_point);
# Get the start point and then reverse the lat/lon reference
# If the first point happens to have multiple possibilities, use
# the starting point that was passed in
// Get the start point and then reverse the lat/lon reference
// If the first point happens to have multiple possibilities, use
// the starting point that was passed in
if (\count($coords) > 0) {
$start_point = $coords[\count($coords) - 1];
$start_point = [$start_point->lat, $start_point->lon];
@@ -127,14 +133,14 @@ class GeoService extends Service
$start_point = $start_coords;
}
# Put all of the lat/lon sets into an array to pick of what's clsest
# to the starting point
// Put all of the lat/lon sets into an array to pick of what's clsest
// to the starting point
$potential_coords = [];
foreach ($points as $point) {
$potential_coords[] = [$point->lat, $point->lon];
}
# returns an array with the closest lat/lon to start point
// returns an array with the closest lat/lon to start point
$closest_coords = $this->getClosestCoords($start_point, $potential_coords);
foreach ($points as $point) {
if ($point->lat === $closest_coords[0] && $point->lon === $closest_coords[1]) {
@@ -150,12 +156,15 @@ class GeoService extends Service
/**
* Determine the center point between two sets of coordinates
*
* @param $latA
* @param $lonA
* @param $latB
* @param $lonB
* @return array
*
* @throws \League\Geotools\Exception\InvalidArgumentException
*
* @return array
*/
public function getCenter($latA, $lonA, $latB, $lonB)
{
@@ -168,7 +177,7 @@ class GeoService extends Service
$center = [
$middlePoint->getLatitude(),
$middlePoint->getLongitude()
$middlePoint->getLongitude(),
];
return $center;
@@ -176,7 +185,9 @@ class GeoService extends Service
/**
* Read an array/relationship of ACARS model points
*
* @param Pirep $pirep
*
* @return array
*/
public function getFeatureFromAcars(Pirep $pirep)
@@ -206,7 +217,7 @@ class GeoService extends Service
]);
}
/**
/*
* @var $point \App\Models\Acars
*/
/*foreach ($pirep->acars as $point) {
@@ -226,20 +237,22 @@ class GeoService extends Service
'airports' => [
'a' => [
'icao' => $pirep->arr_airport->icao,
'lat' => $pirep->arr_airport->lat,
'lon' => $pirep->arr_airport->lon,
'lat' => $pirep->arr_airport->lat,
'lon' => $pirep->arr_airport->lon,
],
'd' => [
'icao' => $pirep->dpt_airport->icao,
'lat' => $pirep->dpt_airport->lat,
'lon' => $pirep->dpt_airport->lon,
'lat' => $pirep->dpt_airport->lat,
'lon' => $pirep->dpt_airport->lon,
],
]
],
];
}
/**
* Return a single feature point for the
*
* @param mixed $pireps
*/
public function getFeatureForLiveFlights($pireps)
{
@@ -269,14 +282,16 @@ class GeoService extends Service
/**
* Return a FeatureCollection GeoJSON object
*
* @param Flight $flight
*
* @return array
*/
public function flightGeoJson(Flight $flight): array
{
$route = new GeoJson();
## Departure Airport
//# Departure Airport
$route->addPoint($flight->dpt_airport->lat, $flight->dpt_airport->lon, [
'name' => $flight->dpt_airport->icao,
'popup' => $flight->dpt_airport->full_name,
@@ -295,7 +310,7 @@ class GeoService extends Service
$route->addPoint($point->lat, $point->lon, [
'name' => $point->name,
'popup' => $point->name.' ('.$point->name.')',
'icon' => ''
'icon' => '',
]);
}
}
@@ -314,7 +329,9 @@ class GeoService extends Service
/**
* Return a GeoJSON FeatureCollection for a PIREP
*
* @param Pirep $pirep
*
* @return array
*/
public function pirepGeoJson(Pirep $pirep)
@@ -322,7 +339,7 @@ class GeoService extends Service
$planned = new GeoJson();
$actual = new GeoJson();
/**
/*
* PLANNED ROUTE
*/
$planned->addPoint($pirep->dpt_airport->lat, $pirep->dpt_airport->lon, [

View File

@@ -4,13 +4,10 @@ namespace App\Services\ImportExport;
use App\Interfaces\ImportExport;
use App\Models\Aircraft;
use App\Models\Enums\AircraftStatus;
use App\Models\Flight;
/**
* The flight importer can be imported or export. Operates on rows
*
* @package App\Services\Import
*/
class AircraftExporter extends ImportExport
{
@@ -26,17 +23,19 @@ class AircraftExporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param Aircraft $aircraft
*
* @return array
*/
public function export($aircraft): array
{
$ret = [];
foreach(self::$columns as $column) {
foreach (self::$columns as $column) {
$ret[$column] = $aircraft->{$column};
}
# Modify special fields
// Modify special fields
$ret['subfleet'] = $aircraft->subfleet->type;
return $ret;

View File

@@ -11,7 +11,6 @@ use App\Support\ICAO;
/**
* Import aircraft
* @package App\Services\Import
*/
class AircraftImporter extends ImportExport
{
@@ -34,7 +33,9 @@ class AircraftImporter extends ImportExport
/**
* Find the subfleet specified, or just create it on the fly
*
* @param $type
*
* @return Subfleet|\Illuminate\Database\Eloquent\Model|null|object|static
*/
protected function getSubfleet($type)
@@ -48,8 +49,10 @@ class AircraftImporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param array $row
* @param int $index
*
* @return bool
*/
public function import(array $row, $index): bool
@@ -57,28 +60,28 @@ class AircraftImporter extends ImportExport
$subfleet = $this->getSubfleet($row['subfleet']);
$row['subfleet_id'] = $subfleet->id;
# Generate a hex code
if(!$row['hex_code']) {
// Generate a hex code
if (!$row['hex_code']) {
$row['hex_code'] = ICAO::createHexCode();
}
# Set a default status
// Set a default status
$row['status'] = trim($row['status']);
if($row['status'] === null || $row['status'] === '') {
if ($row['status'] === null || $row['status'] === '') {
$row['status'] = AircraftStatus::ACTIVE;
}
# Just set its state right now as parked
// Just set its state right now as parked
$row['state'] = AircraftState::PARKED;
# Try to add or update
// Try to add or update
$aircraft = Aircraft::firstOrNew([
'registration' => $row['registration'],
], $row);
try {
$aircraft->save();
} catch(\Exception $e) {
} catch (\Exception $e) {
$this->errorLog('Error in row '.$index.': '.$e->getMessage());
return false;
}

View File

@@ -7,8 +7,6 @@ use App\Models\Airport;
/**
* The flight importer can be imported or export. Operates on rows
*
* @package App\Services\Import
*/
class AirportExporter extends ImportExport
{
@@ -24,13 +22,15 @@ class AirportExporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param Airport $airport
*
* @return array
*/
public function export($airport): array
{
$ret = [];
foreach(self::$columns as $column) {
foreach (self::$columns as $column) {
$ret[$column] = $airport->{$column};
}

View File

@@ -7,7 +7,6 @@ use App\Models\Airport;
/**
* Import airports
* @package App\Services\Import
*/
class AirportImporter extends ImportExport
{
@@ -35,8 +34,10 @@ class AirportImporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param array $row
* @param int $index
*
* @return bool
*/
public function import(array $row, $index): bool
@@ -45,7 +46,7 @@ class AirportImporter extends ImportExport
$row['hub'] = get_truth_state($row['hub']);
$airport = Airport::firstOrNew([
'id' => $row['icao']
'id' => $row['icao'],
], $row);
try {

View File

@@ -5,13 +5,11 @@ namespace App\Services\ImportExport;
use App\Interfaces\ImportExport;
use App\Models\Aircraft;
use App\Models\Airport;
use App\Models\Enums\ExpenseType;
use App\Models\Expense;
use App\Models\Subfleet;
/**
* Import expenses
* @package App\Services\Import
*/
class ExpenseExporter extends ImportExport
{
@@ -27,20 +25,22 @@ class ExpenseExporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param Expense $expense
*
* @return array
*/
public function export($expense): array
{
$ret = [];
foreach(self::$columns as $col) {
foreach (self::$columns as $col) {
$ret[$col] = $expense->{$col};
}
// Special fields
if($ret['airline']) {
if ($ret['airline']) {
$ret['airline'] = $expense->airline->icao;
}
@@ -51,7 +51,7 @@ class ExpenseExporter extends ImportExport
$ret['ref_model_id'] = '';
} else {
$obj = $expense->getReferencedObject();
if(!$obj) { // bail out
if (!$obj) { // bail out
return $ret;
}

View File

@@ -5,14 +5,12 @@ namespace App\Services\ImportExport;
use App\Interfaces\ImportExport;
use App\Models\Aircraft;
use App\Models\Airport;
use App\Models\Enums\ExpenseType;
use App\Models\Expense;
use App\Models\Subfleet;
use Log;
/**
* Import expenses
* @package App\Services\Import
*/
class ExpenseImporter extends ImportExport
{
@@ -36,20 +34,22 @@ class ExpenseImporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param array $row
* @param int $index
*
* @return bool
*/
public function import(array $row, $index): bool
{
if($row['airline']) {
if ($row['airline']) {
$row['airline_id'] = $this->getAirline($row['airline'])->id;
}
# Figure out what this is referring to
// Figure out what this is referring to
$row = $this->getRefClassInfo($row);
if(!$row['active']) {
if (!$row['active']) {
$row['active'] = true;
}
@@ -70,7 +70,9 @@ class ExpenseImporter extends ImportExport
/**
* See if this expense refers to a ref_model
*
* @param array $row
*
* @return array
*/
protected function getRefClassInfo(array $row)
@@ -93,19 +95,19 @@ class ExpenseImporter extends ImportExport
$obj = null;
if ($class === Aircraft::class) {
Log::info('Trying to import expense on aircraft, registration: ' . $id);
Log::info('Trying to import expense on aircraft, registration: '.$id);
$obj = Aircraft::where('registration', $id)->first();
} elseif ($class === Airport::class) {
Log::info('Trying to import expense on airport, icao: ' . $id);
Log::info('Trying to import expense on airport, icao: '.$id);
$obj = Airport::where('icao', $id)->first();
} elseif ($class === Subfleet::class) {
Log::info('Trying to import expense on subfleet, type: ' . $id);
Log::info('Trying to import expense on subfleet, type: '.$id);
$obj = Subfleet::where('type', $id)->first();
} else {
$this->errorLog('Unknown/unsupported Expense class: '.$class);
}
if(!$obj) {
if (!$obj) {
return $row;
}

View File

@@ -7,8 +7,6 @@ use App\Models\Fare;
/**
* The flight importer can be imported or export. Operates on rows
*
* @package App\Services\Import
*/
class FareExporter extends ImportExport
{
@@ -24,13 +22,15 @@ class FareExporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param Fare $fare
*
* @return array
*/
public function export($fare): array
{
$ret = [];
foreach(self::$columns as $column) {
foreach (self::$columns as $column) {
$ret[$column] = $fare->{$column};
}

View File

@@ -7,7 +7,6 @@ use App\Models\Fare;
/**
* Import aircraft
* @package App\Services\Import
*/
class FareImporter extends ImportExport
{
@@ -29,20 +28,22 @@ class FareImporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param array $row
* @param int $index
*
* @return bool
*/
public function import(array $row, $index): bool
{
# Try to add or update
// Try to add or update
$fare = Fare::firstOrNew([
'code' => $row['code'],
], $row);
try {
$fare->save();
} catch(\Exception $e) {
} catch (\Exception $e) {
$this->errorLog('Error in row '.$index.': '.$e->getMessage());
return false;
}

View File

@@ -8,8 +8,6 @@ use App\Models\Flight;
/**
* The flight importer can be imported or export. Operates on rows
*
* @package App\Services\Import
*/
class FlightExporter extends ImportExport
{
@@ -25,23 +23,25 @@ class FlightExporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param Flight $flight
*
* @return array
*/
public function export($flight): array
{
$ret = [];
foreach(self::$columns as $column) {
foreach (self::$columns as $column) {
$ret[$column] = $flight->{$column};
}
# Modify special fields
// Modify special fields
$ret['airline'] = $ret['airline']->icao;
$ret['distance'] = $ret['distance'][config('phpvms.internal_units.distance')];
$ret['dpt_airport'] = $flight->dpt_airport_id;
$ret['arr_airport'] = $flight->arr_airport_id;
if($flight->alt_airport) {
if ($flight->alt_airport) {
$ret['alt_airport'] = $flight->alt_airport_id;
}
@@ -56,14 +56,16 @@ class FlightExporter extends ImportExport
/**
* Return the days string
*
* @param Flight $flight
*
* @return string
*/
protected function getDays(Flight &$flight)
{
$days_str = '';
if($flight->on_day(Days::MONDAY)) {
if ($flight->on_day(Days::MONDAY)) {
$days_str .= '1';
}
@@ -96,15 +98,17 @@ class FlightExporter extends ImportExport
/**
* Return any custom fares that have been made to this flight
*
* @param Flight $flight
*
* @return string
*/
protected function getFares(Flight &$flight): string
{
$fares = [];
foreach($flight->fares as $fare) {
foreach ($flight->fares as $fare) {
$fare_export = [];
if($fare->pivot->price) {
if ($fare->pivot->price) {
$fare_export['price'] = $fare->pivot->price;
}
@@ -124,7 +128,9 @@ class FlightExporter extends ImportExport
/**
* Parse all of the subfields
*
* @param Flight $flight
*
* @return string
*/
protected function getFields(Flight &$flight): string
@@ -139,13 +145,15 @@ class FlightExporter extends ImportExport
/**
* Create the list of subfleets that are associated here
*
* @param Flight $flight
*
* @return string
*/
protected function getSubfleets(Flight &$flight): string
{
$subfleets = [];
foreach($flight->subfleets as $subfleet) {
foreach ($flight->subfleets as $subfleet) {
$subfleets[] = $subfleet->type;
}

View File

@@ -15,8 +15,6 @@ use Log;
/**
* The flight importer can be imported or export. Operates on rows
*
* @package App\Services\Import
*/
class FlightImporter extends ImportExport
{
@@ -49,11 +47,9 @@ class FlightImporter extends ImportExport
'fields' => 'nullable',
];
/**
*
*/
private $fareSvc,
$flightSvc;
private $fareSvc;
private $flightSvc;
/**
* FlightImportExporter constructor.
@@ -66,8 +62,10 @@ class FlightImporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param array $row
* @param int $index
*
* @return bool
*/
public function import(array $row, $index): bool
@@ -108,7 +106,7 @@ class FlightImporter extends ImportExport
// Check for a valid value
$flight_type = $row['flight_type'];
if(!array_key_exists($flight_type, FlightType::labels())) {
if (!array_key_exists($flight_type, FlightType::labels())) {
$flight_type = 'J';
}
@@ -139,17 +137,19 @@ class FlightImporter extends ImportExport
/**
* Return the mask of the days
*
* @param $day_str
*
* @return int|mixed
*/
protected function setDays($day_str)
{
if(!$day_str) {
if (!$day_str) {
return 0;
}
$days = [];
if(strpos($day_str, '1') !== false) {
if (strpos($day_str, '1') !== false) {
$days[] = Days::MONDAY;
}
@@ -182,7 +182,9 @@ class FlightImporter extends ImportExport
/**
* Process the airport
*
* @param $airport
*
* @return \Illuminate\Database\Eloquent\Model
*/
protected function processAirport($airport)
@@ -195,6 +197,7 @@ class FlightImporter extends ImportExport
/**
* Parse out all of the subfleets and associate them to the flight
* The subfleet is created if it doesn't exist
*
* @param Flight $flight
* @param $col
*/
@@ -202,7 +205,7 @@ class FlightImporter extends ImportExport
{
$count = 0;
$subfleets = $this->parseMultiColumnValues($col);
foreach($subfleets as $subfleet_type) {
foreach ($subfleets as $subfleet_type) {
$subfleet = Subfleet::firstOrCreate(
['type' => $subfleet_type],
['name' => $subfleet_type]
@@ -210,9 +213,9 @@ class FlightImporter extends ImportExport
$subfleet->save();
# sync
// sync
$flight->subfleets()->syncWithoutDetaching([$subfleet->id]);
$count ++;
$count++;
}
Log::info('Subfleets added/processed: '.$count);
@@ -220,6 +223,7 @@ class FlightImporter extends ImportExport
/**
* Parse all of the fares in the multi-format
*
* @param Flight $flight
* @param $col
*/
@@ -239,6 +243,7 @@ class FlightImporter extends ImportExport
/**
* Parse all of the subfields
*
* @param Flight $flight
* @param $col
*/
@@ -246,9 +251,9 @@ class FlightImporter extends ImportExport
{
$pass_fields = [];
$fields = $this->parseMultiColumnValues($col);
foreach($fields as $field_name => $field_value) {
foreach ($fields as $field_name => $field_value) {
$pass_fields[] = [
'name' => $field_name,
'name' => $field_name,
'value' => $field_value,
];
}

View File

@@ -3,14 +3,11 @@
namespace App\Services\ImportExport;
use App\Interfaces\ImportExport;
use App\Models\Enums\FlightType;
use App\Models\Flight;
use App\Models\Subfleet;
/**
* The flight importer can be imported or export. Operates on rows
*
* @package App\Services\Import
*/
class SubfleetExporter extends ImportExport
{
@@ -26,17 +23,19 @@ class SubfleetExporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param Subfleet $subfleet
*
* @return array
*/
public function export($subfleet): array
{
$ret = [];
foreach(self::$columns as $column) {
foreach (self::$columns as $column) {
$ret[$column] = $subfleet->{$column};
}
# Modify special fields
// Modify special fields
$ret['airline'] = $subfleet->airline->icao;
$ret['fares'] = $this->getFares($subfleet);
@@ -45,15 +44,17 @@ class SubfleetExporter extends ImportExport
/**
* Return any custom fares that have been made to this flight
*
* @param Subfleet $subfleet
*
* @return string
*/
protected function getFares(Subfleet &$subfleet): string
{
$fares = [];
foreach($subfleet->fares as $fare) {
foreach ($subfleet->fares as $fare) {
$fare_export = [];
if($fare->pivot->price) {
if ($fare->pivot->price) {
$fare_export['price'] = $fare->pivot->price;
}
@@ -73,7 +74,9 @@ class SubfleetExporter extends ImportExport
/**
* Parse all of the subfields
*
* @param Flight $flight
*
* @return string
*/
protected function getFields(Flight &$flight): string
@@ -88,13 +91,15 @@ class SubfleetExporter extends ImportExport
/**
* Create the list of subfleets that are associated here
*
* @param Flight $flight
*
* @return string
*/
protected function getSubfleets(Flight &$flight): string
{
$subfleets = [];
foreach($flight->subfleets as $subfleet) {
foreach ($flight->subfleets as $subfleet) {
$subfleets[] = $subfleet->type;
}

View File

@@ -9,7 +9,6 @@ use App\Services\FareService;
/**
* Import subfleets
* @package App\Services\Import
*/
class SubfleetImporter extends ImportExport
{
@@ -38,8 +37,10 @@ class SubfleetImporter extends ImportExport
/**
* Import a flight, parse out the different rows
*
* @param array $row
* @param int $index
*
* @return bool
*/
public function import(array $row, $index): bool
@@ -48,12 +49,12 @@ class SubfleetImporter extends ImportExport
$row['airline_id'] = $airline->id;
$subfleet = Subfleet::firstOrNew([
'type' => $row['type']
'type' => $row['type'],
], $row);
try {
$subfleet->save();
} catch(\Exception $e) {
} catch (\Exception $e) {
$this->errorLog('Error in row '.$index.': '.$e->getMessage());
return false;
}
@@ -66,8 +67,9 @@ class SubfleetImporter extends ImportExport
/**
* Parse all of the fares in the multi-format
*
* @param Subfleet $subfleet
* @param $col
* @param $col
*/
protected function processFares(Subfleet &$subfleet, $col): void
{

View File

@@ -21,7 +21,6 @@ use Validator;
/**
* Class ImportService
* @package App\Services
*/
class ImportService extends Service
{
@@ -29,35 +28,42 @@ class ImportService extends Service
/**
* ImporterService constructor.
*
* @param FlightRepository $flightRepo
*/
public function __construct(FlightRepository $flightRepo) {
public function __construct(FlightRepository $flightRepo)
{
$this->flightRepo = $flightRepo;
}
/**
* Throw a validation error back up because it will automatically show
* itself under the CSV file upload, and nothing special needs to be done
*
* @param $error
* @param $e
*
* @throws ValidationException
*/
protected function throwError($error, \Exception $e= null): void
protected function throwError($error, \Exception $e = null): void
{
Log::error($error);
if($e) {
if ($e) {
Log::error($e->getMessage());
}
$validator = Validator::make([], []);
$validator->errors()->add('csv_file', $error);
throw new ValidationException($validator);
}
/**
* @param $csv_file
* @return Reader
* @param $csv_file
*
* @throws ValidationException
*
* @return Reader
*/
public function openCsv($csv_file)
{
@@ -74,10 +80,13 @@ class ImportService extends Service
/**
* Run the actual importer, pass in one of the Import classes which implements
* the ImportExport interface
*
* @param $file_path
* @param ImportExport $importer
* @return array
*
* @throws ValidationException
*
* @return array
*/
protected function runImport($file_path, ImportExport $importer): array
{
@@ -93,7 +102,7 @@ class ImportService extends Service
if ($first) {
$first = false;
if($row[$first_header] !== $first_header) {
if ($row[$first_header] !== $first_header) {
$this->throwError('CSV file doesn\'t seem to match import type');
}
@@ -109,16 +118,16 @@ class ImportService extends Service
// turn it into a collection and run some filtering
$row = collect($row)->map(function ($val, $index) {
$val = trim($val);
if($val === '') {
return null;
if ($val === '') {
return;
}
return $val;
})->toArray();
# Try to validate
// Try to validate
$validator = Validator::make($row, $importer->getColumns());
if($validator->fails()) {
if ($validator->fails()) {
$errors = 'Error in row '.$offset.','.implode(';', $validator->errors()->all());
$importer->errorLog($errors);
continue;
@@ -132,15 +141,18 @@ class ImportService extends Service
/**
* Import aircraft
*
* @param string $csv_file
* @param bool $delete_previous
* @return mixed
*
* @throws ValidationException
*
* @return mixed
*/
public function importAircraft($csv_file, bool $delete_previous = true)
{
if ($delete_previous) {
# TODO: delete airports
// TODO: delete airports
}
$importer = new AircraftImporter();
@@ -149,10 +161,13 @@ class ImportService extends Service
/**
* Import airports
*
* @param string $csv_file
* @param bool $delete_previous
* @return mixed
*
* @throws ValidationException
*
* @return mixed
*/
public function importAirports($csv_file, bool $delete_previous = true)
{
@@ -166,10 +181,13 @@ class ImportService extends Service
/**
* Import expenses
*
* @param string $csv_file
* @param bool $delete_previous
* @return mixed
*
* @throws ValidationException
*
* @return mixed
*/
public function importExpenses($csv_file, bool $delete_previous = true)
{
@@ -183,15 +201,18 @@ class ImportService extends Service
/**
* Import fares
*
* @param string $csv_file
* @param bool $delete_previous
* @return mixed
*
* @throws ValidationException
*
* @return mixed
*/
public function importFares($csv_file, bool $delete_previous = true)
{
if ($delete_previous) {
# TODO: Delete all from: fares
// TODO: Delete all from: fares
}
$importer = new FareImporter();
@@ -200,15 +221,18 @@ class ImportService extends Service
/**
* Import flights
*
* @param string $csv_file
* @param bool $delete_previous
* @return mixed
*
* @throws ValidationException
*
* @return mixed
*/
public function importFlights($csv_file, bool $delete_previous = true)
{
if ($delete_previous) {
# TODO: Delete all from: flights, flight_field_values
// TODO: Delete all from: flights, flight_field_values
}
$importer = new FlightImporter();
@@ -217,15 +241,18 @@ class ImportService extends Service
/**
* Import subfleets
*
* @param string $csv_file
* @param bool $delete_previous
* @return mixed
*
* @throws ValidationException
*
* @return mixed
*/
public function importSubfleets($csv_file, bool $delete_previous = true)
{
if ($delete_previous) {
# TODO: Cleanup subfleet data
// TODO: Cleanup subfleet data
}
$importer = new SubfleetImporter();

View File

@@ -8,7 +8,6 @@ use Cache;
/**
* Return the raw METAR string from the NOAA Aviation Weather Service
* @package App\Services\Metar
*/
class AviationWeather extends Metar
{
@@ -19,7 +18,9 @@ class AviationWeather extends Metar
/**
* Implement the METAR - Return the string
*
* @param $icao
*
* @return string
*/
protected function metar($icao): string
@@ -29,14 +30,14 @@ class AviationWeather extends Metar
config('cache.keys.WEATHER_LOOKUP.time'),
function () use ($icao) {
$url = static::METAR_URL.$icao;
try {
$res = Http::get($url, []);
$xml = simplexml_load_string($res);
if (count($xml->data->METAR->raw_text) == 0)
return '';
else
return $xml->data->METAR->raw_text->__toString();
if (count($xml->data->METAR->raw_text) == 0) {
return '';
}
return $xml->data->METAR->raw_text->__toString();
} catch (\Exception $e) {
return '';
}

View File

@@ -6,7 +6,6 @@ use App\Interfaces\Service;
/**
* Class ModuleService
* @package App\Services
*/
class ModuleService extends Service
{
@@ -17,14 +16,16 @@ class ModuleService extends Service
*/
protected static $frontendLinks = [
0 => [],
1 => []
1 => [],
];
/**
* Add a module link in the frontend
*
* @param string $title
* @param string $url
* @param string $icon
* @param mixed $logged_in
*/
public function addFrontendLink(string $title, string $url, string $icon = '', $logged_in = true)
{
@@ -37,6 +38,9 @@ class ModuleService extends Service
/**
* Get all of the frontend links
*
* @param mixed $logged_in
*
* @return array
*/
public function getFrontendLinks($logged_in): array
@@ -46,6 +50,7 @@ class ModuleService extends Service
/**
* Add a module link in the admin panel
*
* @param string $title
* @param string $url
* @param string $icon
@@ -55,12 +60,13 @@ class ModuleService extends Service
self::$adminLinks[] = [
'title' => $title,
'url' => $url,
'icon' => 'pe-7s-users'
'icon' => 'pe-7s-users',
];
}
/**
* Get all of the module links in the admin panel
*
* @return array
*/
public function getAdminLinks(): array

View File

@@ -19,9 +19,6 @@ use App\Models\Navdata;
use App\Models\Pirep;
use App\Models\PirepFieldValue;
use App\Models\User;
use App\Repositories\AcarsRepository;
use App\Repositories\FlightRepository;
use App\Repositories\NavdataRepository;
use App\Repositories\PirepRepository;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
@@ -29,19 +26,19 @@ use Log;
/**
* Class PirepService
* @package App\Services
*/
class PirepService extends Service
{
private $geoSvc,
$pilotSvc,
$pirepRepo;
private $geoSvc;
private $pilotSvc;
private $pirepRepo;
/**
* PirepService constructor.
* @param GeoService $geoSvc
* @param PirepRepository $pirepRepo
* @param UserService $pilotSvc
*
* @param GeoService $geoSvc
* @param PirepRepository $pirepRepo
* @param UserService $pilotSvc
*/
public function __construct(
GeoService $geoSvc,
@@ -56,7 +53,9 @@ class PirepService extends Service
/**
* Find if there are duplicates to a given PIREP. Ideally, the passed
* in PIREP hasn't been saved or gone through the create() method
*
* @param Pirep $pirep
*
* @return bool|Pirep
*/
public function findDuplicate(Pirep $pirep)
@@ -98,19 +97,22 @@ class PirepService extends Service
* Save the route into the ACARS table with AcarsType::ROUTE
* This attempts to create the route from the navdata and the route
* entered into the PIREP's route field
*
* @param Pirep $pirep
* @return Pirep
*
* @throws \Exception
*
* @return Pirep
*/
public function saveRoute(Pirep $pirep): Pirep
{
# Delete all the existing nav points
// Delete all the existing nav points
Acars::where([
'pirep_id' => $pirep->id,
'type' => AcarsType::ROUTE,
])->delete();
# See if a route exists
// See if a route exists
if (!filled($pirep->route)) {
return $pirep;
}
@@ -142,7 +144,7 @@ class PirepService extends Service
$acars->lon = $point->lon;
$acars->save();
++$point_count;
$point_count++;
}
return $pirep;
@@ -151,7 +153,7 @@ class PirepService extends Service
/**
* Create a new PIREP with some given fields
*
* @param Pirep $pirep
* @param Pirep $pirep
* @param array PirepFieldValue[] $field_values
*
* @return Pirep
@@ -162,24 +164,24 @@ class PirepService extends Service
$field_values = [];
}
# Check the block times. If a block on (arrival) time isn't
# specified, then use the time that it was submitted. It won't
# be the most accurate, but that might be OK
if(!$pirep->block_on_time) {
if($pirep->submitted_at) {
// Check the block times. If a block on (arrival) time isn't
// specified, then use the time that it was submitted. It won't
// be the most accurate, but that might be OK
if (!$pirep->block_on_time) {
if ($pirep->submitted_at) {
$pirep->block_on_time = $pirep->submitted_at;
} else {
$pirep->block_on_time = Carbon::now('UTC');
}
}
# If the depart time isn't set, then try to calculate it by
# subtracting the flight time from the block_on (arrival) time
if(!$pirep->block_off_time && $pirep->flight_time > 0) {
// If the depart time isn't set, then try to calculate it by
// subtracting the flight time from the block_on (arrival) time
if (!$pirep->block_off_time && $pirep->flight_time > 0) {
$pirep->block_off_time = $pirep->block_on_time->subMinutes($pirep->flight_time);
}
# Check that there's a submit time
// Check that there's a submit time
if (!$pirep->submitted_at) {
$pirep->submitted_at = Carbon::now('UTC');
}
@@ -196,12 +198,13 @@ class PirepService extends Service
/**
* Submit the PIREP. Figure out its default state
*
* @param Pirep $pirep
*/
public function submit(Pirep $pirep)
{
# Figure out what default state should be. Look at the default
# behavior from the rank that the pilot is assigned to
// Figure out what default state should be. Look at the default
// behavior from the rank that the pilot is assigned to
$default_state = PirepState::PENDING;
if ($pirep->source === PirepSource::ACARS) {
if ($pirep->pilot->rank->auto_approve_acars) {
@@ -220,13 +223,13 @@ class PirepService extends Service
Log::info('New PIREP filed', [$pirep]);
event(new PirepFiled($pirep));
# only update the pilot last state if they are accepted
// only update the pilot last state if they are accepted
if ($default_state === PirepState::ACCEPTED) {
$pirep = $this->accept($pirep);
$this->setPilotState($pirep->pilot, $pirep);
}
# Check the user state, set them to ACTIVE if on leave
// Check the user state, set them to ACTIVE if on leave
if ($pirep->user->state !== UserState::ACTIVE) {
$old_state = $pirep->user->state;
$pirep->user->state = UserState::ACTIVE;
@@ -238,6 +241,7 @@ class PirepService extends Service
/**
* Update any custom PIREP fields
*
* @param $pirep_id
* @param array $field_values
*/
@@ -246,10 +250,10 @@ class PirepService extends Service
foreach ($field_values as $fv) {
PirepFieldValue::updateOrCreate(
['pirep_id' => $pirep_id,
'name' => $fv['name']
'name' => $fv['name'],
],
['value' => $fv['value'],
'source' => $fv['source']
'source' => $fv['source'],
]
);
}
@@ -258,6 +262,7 @@ class PirepService extends Service
/**
* @param Pirep $pirep
* @param int $new_state
*
* @return Pirep
*/
public function changeState(Pirep $pirep, int $new_state)
@@ -268,7 +273,7 @@ class PirepService extends Service
return $pirep;
}
/**
/*
* Move from a PENDING status into either ACCEPTED or REJECTED
*/
if ($pirep->state === PirepState::PENDING) {
@@ -276,9 +281,8 @@ class PirepService extends Service
return $this->accept($pirep);
} elseif ($new_state === PirepState::REJECTED) {
return $this->reject($pirep);
} else {
return $pirep;
}
return $pirep;
} /*
* Move from a ACCEPTED to REJECTED status
*/
@@ -286,7 +290,7 @@ class PirepService extends Service
$pirep = $this->reject($pirep);
return $pirep;
} /**
} /*
* Move from REJECTED to ACCEPTED
*/
elseif ($pirep->state === PirepState::REJECTED) {
@@ -300,11 +304,12 @@ class PirepService extends Service
/**
* @param Pirep $pirep
*
* @return Pirep
*/
public function accept(Pirep $pirep): Pirep
{
# moving from a REJECTED state to ACCEPTED, reconcile statuses
// moving from a REJECTED state to ACCEPTED, reconcile statuses
if ($pirep->state === PirepState::ACCEPTED) {
return $pirep;
}
@@ -317,14 +322,14 @@ class PirepService extends Service
$this->pilotSvc->calculatePilotRank($pilot);
$pirep->pilot->refresh();
# Change the status
// Change the status
$pirep->state = PirepState::ACCEPTED;
$pirep->save();
$pirep->refresh();
Log::info('PIREP '.$pirep->id.' state change to ACCEPTED');
# Update the aircraft
// Update the aircraft
$pirep->aircraft->flight_time += $pirep->flight_time;
$pirep->aircraft->airport_id = $pirep->arr_airport_id;
$pirep->aircraft->landing_time = $pirep->updated_at;
@@ -332,7 +337,7 @@ class PirepService extends Service
$pirep->refresh();
# Any ancillary tasks before an event is dispatched
// Any ancillary tasks before an event is dispatched
$this->removeBid($pirep);
$this->setPilotState($pilot, $pirep);
@@ -343,12 +348,13 @@ class PirepService extends Service
/**
* @param Pirep $pirep
*
* @return Pirep
*/
public function reject(Pirep $pirep): Pirep
{
# If this was previously ACCEPTED, then reconcile the flight hours
# that have already been counted, etc
// If this was previously ACCEPTED, then reconcile the flight hours
// that have already been counted, etc
if ($pirep->state === PirepState::ACCEPTED) {
$pilot = $pirep->pilot;
$ft = $pirep->flight_time * -1;
@@ -359,7 +365,7 @@ class PirepService extends Service
$pirep->pilot->refresh();
}
# Change the status
// Change the status
$pirep->state = PirepState::REJECTED;
$pirep->save();
$pirep->refresh();
@@ -393,7 +399,9 @@ class PirepService extends Service
/**
* If the setting is enabled, remove the bid
*
* @param Pirep $pirep
*
* @throws \Exception
*/
public function removeBid(Pirep $pirep)

View File

@@ -20,15 +20,15 @@ use Log;
/**
* Class UserService
* @package App\Services
*/
class UserService extends Service
{
private $aircraftRepo,
$subfleetRepo;
private $aircraftRepo;
private $subfleetRepo;
/**
* UserService constructor.
*
* @param AircraftRepository $aircraftRepo
* @param SubfleetRepository $subfleetRepo
*/
@@ -43,14 +43,17 @@ class UserService extends Service
/**
* Register a pilot. Also attaches the initial roles
* required, and then triggers the UserRegistered event
*
* @param User $user User model
* @param array $groups Additional groups to assign
* @return mixed
*
* @throws \Exception
*
* @return mixed
*/
public function createPilot(User $user, array $groups = null)
{
# Determine if we want to auto accept
// Determine if we want to auto accept
if (setting('pilots.auto_accept') === true) {
$user->state = UserState::ACTIVE;
} else {
@@ -59,7 +62,7 @@ class UserService extends Service
$user->save();
# Attach the user roles
// Attach the user roles
$role = Role::where('name', 'user')->first();
$user->attachRole($role);
@@ -70,7 +73,7 @@ class UserService extends Service
}
}
# Let's check their rank and where they should start
// Let's check their rank and where they should start
$this->calculatePilotRank($user);
$user->refresh();
@@ -82,7 +85,9 @@ class UserService extends Service
/**
* Return the subfleets this user is allowed access to,
* based on their current rank
*
* @param $user
*
* @return Collection
*/
public function getAllowableSubfleets($user)
@@ -97,8 +102,10 @@ class UserService extends Service
/**
* Return a bool if a user is allowed to fly the current aircraft
*
* @param $user
* @param $aircraft_id
*
* @return bool
*/
public function aircraftAllowed($user, $aircraft_id)
@@ -113,8 +120,10 @@ class UserService extends Service
/**
* Change the user's state. PENDING to ACCEPTED, etc
* Send out an email
*
* @param User $user
* @param $old_state
*
* @return User
*/
public function changeUserState(User $user, $old_state): User
@@ -135,8 +144,10 @@ class UserService extends Service
/**
* Adjust the number of flights a user has. Triggers
* UserStatsChanged event
*
* @param User $user
* @param int $count
*
* @return User
*/
public function adjustFlightCount(User $user, int $count): User
@@ -153,8 +164,10 @@ class UserService extends Service
/**
* Update a user's flight times
*
* @param User $user
* @param int $minutes
*
* @return User
*/
public function adjustFlightTime(User $user, int $minutes): User
@@ -168,24 +181,26 @@ class UserService extends Service
/**
* See if a pilot's rank has change. Triggers the UserStatsChanged event
*
* @param User $user
*
* @return User
*/
public function calculatePilotRank(User $user): User
{
$user->refresh();
# If their current rank is one they were assigned, then
# don't change away from it automatically.
// If their current rank is one they were assigned, then
// don't change away from it automatically.
if ($user->rank && $user->rank->auto_promote === false) {
return $user;
}
$pilot_hours = new Time($user->flight_time);
# The current rank's hours are over the pilot's current hours,
# so assume that they were "placed" here by an admin so don't
# bother with updating it
// The current rank's hours are over the pilot's current hours,
// so assume that they were "placed" here by an admin so don't
// bother with updating it
if ($user->rank && $user->rank->hours > $pilot_hours->hours) {
return $user;
}
@@ -216,7 +231,9 @@ class UserService extends Service
/**
* Set the user's status to being on leave
*
* @param User $user
*
* @return User
*/
public function setStatusOnLeave(User $user): User
@@ -233,21 +250,23 @@ class UserService extends Service
/**
* Recount/update all of the stats for a user
*
* @param User $user
*
* @return User
*/
public function recalculateStats(User $user): User
{
# Recalc their hours
// Recalc their hours
$w = [
'user_id' => $user->id,
'state' => PirepState::ACCEPTED,
'state' => PirepState::ACCEPTED,
];
$flight_time = Pirep::where($w)->sum('flight_time');
$user->flight_time = $flight_time;
# Recalc the rank
// Recalc the rank
$this->calculatePilotRank($user);
Log::info('User '.$user->ident.' updated; rank='.$user->rank->name.'; flight_time='.$user->flight_time.' minutes');