Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve imports #15898

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 87 additions & 17 deletions app/Console/Commands/ObjectImportCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@

namespace App\Console\Commands;

use App\Importer\Factory;
use App\Importer\MimeTypes;
use App\Importer\Type;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Http\File;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Symfony\Component\Console\Helper\ProgressIndicator;

ini_set('max_execution_time', env('IMPORT_TIME_LIMIT', 600)); //600 seconds = 10 minutes
Expand Down Expand Up @@ -52,33 +59,84 @@ public function __construct()
*/
public function handle()
{
if (!$this->validate()) {
return self::FAILURE;
}

$this->progressIndicator = new ProgressIndicator($this->output);

$filename = $this->argument('filename');
$class = title_case($this->option('item-type'));
$classString = "App\\Importer\\{$class}Importer";
$importer = new $classString($filename);
$importer = Factory::make($filename, $this->option('item-type'));
$importer->setCallbacks([$this, 'log'], [$this, 'progress'], [$this, 'errorCallback'])
->setUserId($this->option('user_id'))
->setUpdating($this->option('update'))
->setShouldNotify($this->option('send-welcome'))
->setUsernameFormat($this->option('username_format'));
->setCreatedBy((int)$this->option('user_id'))
->setUpdating($this->option('update'))
->setShouldNotify($this->option('send-welcome'))
->setUsernameFormat($this->option('username_format'));

// This $logFile/useFiles() bit is currently broken, so commenting it out for now
// $logFile = $this->option('logfile');
// Log::useFiles($logFile);
$this->progressIndicator->start('======= Importing Items from '.$filename.' =========');
$this->progressIndicator->start('======= Importing Items from ' . $filename . ' =========');

$importer->import();

$this->progressIndicator->finish('Import finished.');
}

protected function validate(): bool
{
$filepath = $this->argument('filename');
$importFile = new File(realpath($filepath), false);
$validator = Validator::make(
array_merge($this->options(), ['file' => $importFile]),
$this->rules(),
$this->messages()
)->stopOnFirstFailure();

if (!$importFile->isFile()) {
$this->error("file \"{$filepath}\" not found.");

return false;
}

foreach ($validator->errors()->all() as $errors) {
$this->error($errors);

return false;
}

return true;
}

/**
* Get the validation rules for this command.
*/
protected function rules(): array
{
return [
'file' => ['file', Rule::file()->types(MimeTypes::VALID)],
'item-type' => ['sometimes', Rule::in(Type::validTypesForCli())],
'user_id' => ['sometimes', 'int', 'min:1', Rule::exists(User::class, 'id')->withoutTrashed()],
'username_format' => ['nullable', 'in:firstname.lastname,firstname,filastname,email'],
'email_format' => ['nullable', 'in:firstname.lastname,firstname,filastname'],
];
}

/**
* Get custom messages for validator errors.
*/
protected function messages(): array
{
return [
'file.mimetypes' => 'The given file type is not supported.'
];
}

public function errorCallback($item, $field, $error)
{
$this->output->write("\x0D\x1B[2K");

$this->warn('Error: Item: '.$item->name.' failed validation: '.json_encode($error));
$this->warn('Error: Item: ' . $item->name . ' failed validation: ' . json_encode($error));
}

public function progress($importedItemsCount)
Expand Down Expand Up @@ -132,14 +190,26 @@ protected function getArguments()
protected function getOptions()
{
return [
['email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are firstname.lastname, firstname, filastname', null],
['username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are firstname.lastname, firstname, filastname, email', null],
['logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log')],
['item-type', null, InputOption::VALUE_REQUIRED, 'Item Type To import. Valid Options are Asset, Consumable, Accessory, License, or User', 'Asset'],
['web-importer', null, InputOption::VALUE_NONE, 'Internal: packages output for use with the web importer'],
['user_id', null, InputOption::VALUE_REQUIRED, 'ID of user creating items', 1],
['update', null, InputOption::VALUE_NONE, 'If a matching item is found, update item information'],
['send-welcome', null, InputOption::VALUE_NONE, 'Whether to send a welcome email to any new users that are created.'],
['email_format', null, InputOption::VALUE_REQUIRED, 'The format of the email addresses that should be generated. Options are <info>firstname.lastname</info>, <info>firstname</info>, <info>filastname</info>', null],
['username_format', null, InputOption::VALUE_REQUIRED, 'The format of the username that should be generated. Options are <info>firstname.lastname</info>, <info>firstname</info>, <info>filastname</info>, <info>email</info>', null],
['logfile', null, InputOption::VALUE_REQUIRED, 'The path to log output to. storage/logs/importer.log by default', storage_path('logs/importer.log')],
['item-type', null, InputOption::VALUE_REQUIRED, "Item Type To import. Valid Options are {$this->getValidImportTypesText()}", 'Asset'],
['web-importer', null, InputOption::VALUE_NONE, 'Internal: packages output for use with the web importer'],
['user_id', null, InputOption::VALUE_REQUIRED, 'ID of user creating items', 1],
['update', null, InputOption::VALUE_NONE, 'If a matching item is found, update item information'],
['send-welcome', null, InputOption::VALUE_NONE, 'Whether to send a welcome email to any new users that are created.'],
];
}

private function getValidImportTypesText(): string
{
$importTypes = collect(Type::cases())
->pluck('value')
->map('ucfirst')
->map(fn (string $type) => "<info>{$type}</info>");

$last = $importTypes->pop();

return implode(' or ', [$importTypes->implode(', '), $last]);
}
}
11 changes: 6 additions & 5 deletions app/Http/Requests/ItemImportRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

namespace App\Http\Requests;

use App\Importer\Factory;
use App\Importer\Type;
use App\Models\Import;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;

class ItemImportRequest extends FormRequest
{
Expand All @@ -27,7 +29,7 @@ public function authorize()
public function rules()
{
return [
'import-type' => 'required',
'import-type' => ['required', Rule::in(Type::cases())],
];
}

Expand All @@ -38,9 +40,8 @@ public function import(Import $import)

$filename = config('app.private_uploads').'/imports/'.$import->file_path;
$import->import_type = $this->input('import-type');
$class = ucfirst($import->import_type);
$classString = "App\\Importer\\{$class}Importer";
$importer = new $classString($filename);
$importer = Factory::make($filename, $this->input('import-type'));

$import->field_map = request('column-mappings');
$import->created_by = auth()->id();
$import->save();
Expand Down
27 changes: 27 additions & 0 deletions app/Importer/Factory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace App\Importer;

use Illuminate\Support\Str;

class Factory
{
/**
* Create a new importer instance.
*/
public static function make(string $filepath, string $type): Importer
{
return match (Type::from(Str::camel($type))) {
Type::ACCESSORY => new AccessoryImporter($filepath),
Type::ASSET => new AssetImporter($filepath),
Type::COMPONENT => new ComponentImporter($filepath),
Type::CONSUMABLE => new ConsumableImporter($filepath),
Type::LICENSE => new LicenseImporter($filepath),
Type::LOCATION => new LocationImporter($filepath),
Type::USER => new UserImporter($filepath),
Type::ASSET_MODEL => new AssetModelImporter($filepath),
};
}
}
2 changes: 1 addition & 1 deletion app/Importer/Importer.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public function __construct($file)
*/
public function import()
{
$headerRow = $this->csv->fetchOne();
$headerRow = $this->csv->nth(0);
$this->csv->setHeaderOffset(0); //explicitly sets the CSV document header record

$this->populateCustomFields($headerRow);
Expand Down
19 changes: 19 additions & 0 deletions app/Importer/MimeTypes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace App\Importer;

class MimeTypes
{
/**
* The mime types supported for import file.
*/
public const VALID = [
'application/vnd.ms-excel',
'text/csv',
'application/csv',
'text/plain',
'text/comma-separated-values',
];
}
32 changes: 32 additions & 0 deletions app/Importer/Type.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace App\Importer;

enum Type: string
{
case ACCESSORY = 'accessory';
case ASSET = 'asset';
case COMPONENT = 'component';
case CONSUMABLE = 'consumable';
case LICENSE = 'license';
case LOCATION = 'location';
case USER = 'user';
case ASSET_MODEL = 'assetModel';

/**
* Get the valid import type cli options.
*
* @return array<string>
*/
public static function validTypesForCli(): array
{
$types = array_column(self::cases(), 'value');

return collect($types)
->map(ucfirst(...))
->merge($types)
->all();
}
}
Loading
Loading