firefly-iii/app/Console/Commands/Import/CreateCSVImport.php

333 lines
11 KiB
PHP
Raw Normal View History

2016-10-20 12:10:43 -05:00
<?php
/**
2019-06-07 10:57:46 -05:00
* CreateCSVImport.php
2020-01-23 13:35:02 -06:00
* Copyright (c) 2020 james@firefly-iii.org
2016-10-20 12:10:43 -05:00
*
* This file is part of Firefly III (https://github.com/firefly-iii).
2016-10-20 12:10:43 -05:00
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
2017-10-21 01:40:00 -05:00
*
* This program is distributed in the hope that it will be useful,
2017-10-21 01:40:00 -05:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
2017-10-21 01:40:00 -05:00
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2016-10-20 12:10:43 -05:00
*/
/** @noinspection MultipleReturnStatementsInspection */
2018-05-11 03:08:34 -05:00
declare(strict_types=1);
2019-06-07 10:57:46 -05:00
namespace FireflyIII\Console\Commands\Import;
2016-10-20 12:10:43 -05:00
use Exception;
2019-06-07 10:57:46 -05:00
use FireflyIII\Console\Commands\VerifiesAccessToken;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Import\Routine\RoutineInterface;
use FireflyIII\Import\Storage\ImportArrayStorage;
2019-06-10 13:14:00 -05:00
use FireflyIII\Models\ImportJob;
2016-10-20 12:10:43 -05:00
use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
2019-06-10 13:14:00 -05:00
use FireflyIII\User;
2016-10-20 12:10:43 -05:00
use Illuminate\Console\Command;
use Log;
/**
2019-06-07 10:57:46 -05:00
* Class CreateCSVImport.
2016-10-20 12:10:43 -05:00
*/
2019-06-07 10:57:46 -05:00
class CreateCSVImport extends Command
2016-10-20 12:10:43 -05:00
{
use VerifiesAccessToken;
2016-10-20 12:10:43 -05:00
/**
* The console command description.
*
* @var string
*/
2019-06-07 10:57:46 -05:00
protected $description = 'Use this command to create a new CSV file import.';
2016-10-20 12:10:43 -05:00
/**
* The name and signature of the console command.
*
* @var string
*/
2017-10-05 04:49:06 -05:00
protected $signature
2019-06-07 10:57:46 -05:00
= 'firefly-iii:csv-import
{file? : The CSV file to import.}
{configuration? : The configuration file to use for the import.}
{--user=1 : The user ID that the import should import for.}
2019-06-07 10:57:46 -05:00
{--token= : The user\'s access token.}';
2019-06-10 13:14:00 -05:00
/** @var UserRepositoryInterface */
private $userRepository;
/** @var ImportJobRepositoryInterface */
private $importRepository;
/** @var ImportJob */
private $importJob;
2016-10-20 12:10:43 -05:00
/**
2017-08-15 10:26:43 -05:00
* Run the command.
2016-10-20 12:10:43 -05:00
*/
2018-03-30 12:41:16 -05:00
public function handle(): int
2016-10-20 12:10:43 -05:00
{
2019-06-13 08:48:35 -05:00
$this->stupidLaravel();
2019-06-10 13:14:00 -05:00
// @codeCoverageIgnoreStart
if (!$this->verifyAccessToken()) {
$this->errorLine('Invalid access token.');
2018-03-30 12:41:16 -05:00
return 1;
}
2018-07-05 14:18:53 -05:00
2016-10-20 12:10:43 -05:00
if (!$this->validArguments()) {
2018-03-30 12:41:16 -05:00
$this->errorLine('Invalid arguments.');
return 1;
2016-10-20 12:10:43 -05:00
}
2019-06-10 13:14:00 -05:00
// @codeCoverageIgnoreEnd
/** @var User $user */
$user = $this->userRepository->findNull((int)$this->option('user'));
$file = (string)$this->argument('file');
$configuration = (string)$this->argument('configuration');
2019-06-10 13:14:00 -05:00
$this->importRepository->setUser($user);
2017-07-15 03:26:16 -05:00
2019-06-10 13:14:00 -05:00
$configurationData = json_decode(file_get_contents($configuration), true);
$this->importJob = $this->importRepository->create('file');
2017-07-15 03:26:16 -05:00
2019-06-10 13:14:00 -05:00
// inform user (and log it)
$this->infoLine(sprintf('Import file : %s', $file));
$this->infoLine(sprintf('Configuration file : %s', $configuration));
$this->infoLine(sprintf('User : #%d (%s)', $user->id, $user->email));
$this->infoLine(sprintf('Job : %s', $this->importJob->key));
2018-03-30 12:41:16 -05:00
2019-06-10 13:14:00 -05:00
try {
$this->storeFile($file);
} catch (FireflyException $e) {
$this->errorLine($e->getMessage());
2019-06-10 13:14:00 -05:00
return 1;
}
2019-06-10 13:14:00 -05:00
// job is ready to go
$this->importRepository->setConfiguration($this->importJob, $configurationData);
$this->importRepository->setStatus($this->importJob, 'ready_to_run');
2016-10-20 12:10:43 -05:00
2019-06-07 10:57:46 -05:00
$this->infoLine('The import routine has started. The process is not visible. Please wait.');
Log::debug('Go for import!');
2017-07-15 03:26:16 -05:00
2019-06-07 10:57:46 -05:00
// keep repeating this call until job lands on "provider_finished"
2019-06-10 13:14:00 -05:00
try {
$this->processFile();
} catch (FireflyException $e) {
$this->errorLine($e->getMessage());
2019-06-10 13:14:00 -05:00
return 1;
2019-06-07 10:57:46 -05:00
}
2019-06-10 13:14:00 -05:00
// then store data:
try {
$this->storeData();
} catch (FireflyException $e) {
$this->errorLine($e->getMessage());
2019-06-07 10:57:46 -05:00
2019-06-10 13:14:00 -05:00
return 1;
2019-06-07 10:57:46 -05:00
}
2016-10-20 12:10:43 -05:00
2019-06-07 10:57:46 -05:00
// give feedback:
2019-06-10 13:14:00 -05:00
$this->giveFeedback();
2017-10-22 06:49:39 -05:00
// clear cache for user:
2018-07-15 02:27:38 -05:00
app('preferences')->setForUser($user, 'lastActivity', microtime());
2017-10-22 06:49:39 -05:00
2018-03-30 12:41:16 -05:00
return 0;
}
2019-06-13 08:48:35 -05:00
/**
* Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
* executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
* be called from the handle method instead of using the constructor to initialize the command.
*
* @codeCoverageIgnore
*/
private function stupidLaravel(): void
{
$this->userRepository = app(UserRepositoryInterface::class);
$this->importRepository = app(ImportJobRepositoryInterface::class);
}
2018-03-30 12:41:16 -05:00
/**
2019-06-07 10:57:46 -05:00
* @param string $message
2018-03-30 12:41:16 -05:00
* @param array|null $data
2019-06-10 13:14:00 -05:00
* @codeCoverageIgnore
2018-03-30 12:41:16 -05:00
*/
private function errorLine(string $message, array $data = null): void
{
Log::error($message, $data ?? []);
$this->error($message);
}
/**
* @param string $message
2019-06-07 10:57:46 -05:00
* @param array $data
2019-06-10 13:14:00 -05:00
* @codeCoverageIgnore
2018-03-30 12:41:16 -05:00
*/
private function infoLine(string $message, array $data = null): void
{
Log::info($message, $data ?? []);
$this->line($message);
2016-10-20 12:10:43 -05:00
}
/**
2017-08-15 10:26:43 -05:00
* Verify user inserts correct arguments.
*
2018-03-30 12:41:16 -05:00
* @noinspection MultipleReturnStatementsInspection
2016-10-20 12:10:43 -05:00
* @return bool
2019-06-10 13:14:00 -05:00
* @codeCoverageIgnore
2016-10-20 12:10:43 -05:00
*/
private function validArguments(): bool
{
2018-07-25 23:10:17 -05:00
$file = (string)$this->argument('file');
$configuration = (string)$this->argument('configuration');
2018-03-30 12:41:16 -05:00
$cwd = getcwd();
2019-06-07 10:57:46 -05:00
$enabled = (bool)config('import.enabled.file');
if (false === $enabled) {
2019-06-07 10:57:46 -05:00
$this->errorLine('CSV Provider is not enabled.');
2016-10-20 12:10:43 -05:00
return false;
}
2019-06-07 10:57:46 -05:00
if (!file_exists($file)) {
$this->errorLine(sprintf('Firefly III cannot find file "%s" (working directory: "%s").', $file, $cwd));
2016-10-20 12:10:43 -05:00
return false;
}
2019-06-07 10:57:46 -05:00
if (!file_exists($configuration)) {
$this->errorLine(sprintf('Firefly III cannot find configuration file "%s" (working directory: "%s").', $configuration, $cwd));
2016-10-20 12:10:43 -05:00
return false;
}
2019-06-10 13:14:00 -05:00
$configurationData = json_decode(file_get_contents($configuration), true);
if (null === $configurationData) {
$this->errorLine(sprintf('Firefly III cannot read the contents of configuration file "%s" (working directory: "%s").', $configuration, $cwd));
return false;
}
2016-10-20 12:10:43 -05:00
return true;
}
2019-06-10 13:14:00 -05:00
/**
* Store the supplied file as an attachment to this job.
*
* @param string $file
* @throws FireflyException
*/
private function storeFile(string $file): void
{
// store file as attachment.
if ('' !== $file) {
$messages = $this->importRepository->storeCLIUpload($this->importJob, 'import_file', $file);
if ($messages->count() > 0) {
throw new FireflyException($messages->first());
}
}
}
/**
* Keep repeating import call until job lands on "provider_finished".
*
* @throws FireflyException
*/
private function processFile(): void
{
$className = config('import.routine.file');
$valid = ['provider_finished'];
$count = 0;
while (!in_array($this->importJob->status, $valid, true) && $count < 6) {
Log::debug(sprintf('Now in loop #%d.', $count + 1));
/** @var RoutineInterface $routine */
$routine = app($className);
$routine->setImportJob($this->importJob);
try {
$routine->run();
} catch (FireflyException|Exception $e) {
$message = 'The import routine crashed: ' . $e->getMessage();
Log::error($message);
Log::error($e->getTraceAsString());
// set job errored out:
$this->importRepository->setStatus($this->importJob, 'error');
throw new FireflyException($message);
}
$count++;
}
$this->importRepository->setStatus($this->importJob, 'provider_finished');
$this->importJob->status = 'provider_finished';
}
/**
*
* @throws FireflyException
*/
private function storeData(): void
{
if ('provider_finished' === $this->importJob->status) {
$this->infoLine('Import has finished. Please wait for storage of data.');
// set job to be storing data:
$this->importRepository->setStatus($this->importJob, 'storing_data');
/** @var ImportArrayStorage $storage */
$storage = app(ImportArrayStorage::class);
$storage->setImportJob($this->importJob);
try {
$storage->store();
} catch (FireflyException|Exception $e) {
$message = 'The import routine crashed: ' . $e->getMessage();
Log::error($message);
Log::error($e->getTraceAsString());
// set job errored out:
$this->importRepository->setStatus($this->importJob, 'error');
throw new FireflyException($message);
}
// set storage to be finished:
$this->importRepository->setStatus($this->importJob, 'storage_finished');
}
}
/**
*
*/
private function giveFeedback(): void
{
$this->infoLine('Job has finished.');
if (null !== $this->importJob->tag) {
$this->infoLine(sprintf('%d transaction(s) have been imported.', $this->importJob->tag->transactionJournals->count()));
$this->infoLine(sprintf('You can find your transactions under tag "%s"', $this->importJob->tag->tag));
}
if (null === $this->importJob->tag) {
$this->errorLine('No transactions have been imported :(.');
}
if (count($this->importJob->errors) > 0) {
$this->infoLine(sprintf('%d error(s) occurred:', count($this->importJob->errors)));
foreach ($this->importJob->errors as $err) {
$this->errorLine('- ' . $err);
}
}
}
2016-10-20 12:10:43 -05:00
}