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

289 lines
9.7 KiB
PHP
Raw Normal View History

2016-10-20 19:10:43 +02:00
<?php
/**
2019-06-07 17:57:46 +02:00
* CreateCSVImport.php
* Copyright (c) 2019 thegrumpydictator@gmail.com
2016-10-20 19:10:43 +02:00
*
2017-10-21 08:40:00 +02:00
* This file is part of Firefly III.
2016-10-20 19:10:43 +02:00
*
2017-10-21 08:40:00 +02:00
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2017-12-17 14:41:58 +01:00
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
2016-10-20 19:10:43 +02:00
*/
/** @noinspection MultipleReturnStatementsInspection */
2018-05-11 10:08:34 +02:00
declare(strict_types=1);
2019-06-07 17:57:46 +02:00
namespace FireflyIII\Console\Commands\Import;
2016-10-20 19:10:43 +02:00
use Exception;
2019-06-07 17:57:46 +02:00
use FireflyIII\Console\Commands\VerifiesAccessToken;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Import\Prerequisites\PrerequisitesInterface;
use FireflyIII\Import\Routine\RoutineInterface;
use FireflyIII\Import\Storage\ImportArrayStorage;
2016-10-20 19:10:43 +02:00
use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Console\Command;
use Log;
/**
2019-06-07 17:57:46 +02:00
* Class CreateCSVImport.
*
* @codeCoverageIgnore
2016-10-20 19:10:43 +02:00
*/
2019-06-07 17:57:46 +02:00
class CreateCSVImport extends Command
2016-10-20 19:10:43 +02:00
{
use VerifiesAccessToken;
2016-10-20 19:10:43 +02:00
/**
* The console command description.
*
* @var string
*/
2019-06-07 17:57:46 +02:00
protected $description = 'Use this command to create a new CSV file import.';
2016-10-20 19:10:43 +02:00
/**
* The name and signature of the console command.
*
* @var string
*/
2017-10-05 11:49:06 +02:00
protected $signature
2019-06-07 17:57:46 +02: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 17:57:46 +02:00
{--token= : The user\'s access token.}';
2016-10-20 19:10:43 +02:00
/**
2017-08-15 17:26:43 +02:00
* Run the command.
*
* @throws FireflyException
2016-10-20 19:10:43 +02:00
*/
2018-03-30 19:41:16 +02:00
public function handle(): int
2016-10-20 19:10:43 +02:00
{
if (!$this->verifyAccessToken()) {
$this->errorLine('Invalid access token.');
2018-03-30 19:41:16 +02:00
return 1;
}
2016-10-20 19:10:43 +02:00
/** @var UserRepositoryInterface $userRepository */
$userRepository = app(UserRepositoryInterface::class);
$file = (string)$this->argument('file');
$configuration = (string)$this->argument('configuration');
$user = $userRepository->findNull((int)$this->option('user'));
$cwd = getcwd();
$configurationData = [];
2016-10-20 19:10:43 +02:00
2018-07-05 21:18:53 +02:00
if (null === $user) {
$this->errorLine('User is NULL.');
return 1;
}
2016-10-20 19:10:43 +02:00
if (!$this->validArguments()) {
2018-03-30 19:41:16 +02:00
$this->errorLine('Invalid arguments.');
return 1;
2016-10-20 19:10:43 +02:00
}
2019-02-13 17:38:41 +01:00
if ('' !== $configuration) {
$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));
2016-10-20 19:10:43 +02:00
return 1;
}
2016-10-20 19:10:43 +02:00
}
$this->infoLine(sprintf('Going to create a job to import file: %s', $file));
$this->infoLine(sprintf('Using configuration file: %s', $configuration));
$this->infoLine(sprintf('Import into user: #%d (%s)', $user->id, $user->email));
2017-07-15 10:26:16 +02:00
2016-10-20 19:10:43 +02:00
/** @var ImportJobRepositoryInterface $jobRepository */
2017-02-05 16:16:15 +01:00
$jobRepository = app(ImportJobRepositoryInterface::class);
$jobRepository->setUser($user);
2019-06-07 17:57:46 +02:00
$importJob = $jobRepository->create('file');
$this->infoLine(sprintf('Created job "%s"', $importJob->key));
// make sure that job has no prerequisites.
2019-06-07 17:57:46 +02:00
if ((bool)config('import.has_prereq.csv')) {
// make prerequisites thing.
2019-06-07 17:57:46 +02:00
$class = (string)config('import.prerequisites.csv');
if (!class_exists($class)) {
2019-06-07 17:57:46 +02:00
throw new FireflyException('No class to handle prerequisites for CSV.'); // @codeCoverageIgnore
}
/** @var PrerequisitesInterface $object */
$object = app($class);
$object->setUser($user);
if (!$object->isComplete()) {
2019-06-07 17:57:46 +02:00
$this->errorLine('CSV Import provider has prerequisites that can only be filled in using the browser.');
2017-07-15 10:26:16 +02:00
return 1;
}
}
2018-03-30 19:41:16 +02:00
// store file as attachment.
2019-02-13 17:38:41 +01:00
if ('' !== $file) {
$messages = $jobRepository->storeCLIUpload($importJob, 'import_file', $file);
if ($messages->count() > 0) {
$this->errorLine($messages->first());
return 1;
}
$this->infoLine('File content saved.');
}
$this->infoLine('Job configuration saved.');
$jobRepository->setConfiguration($importJob, $configurationData);
$jobRepository->setStatus($importJob, 'ready_to_run');
2016-10-20 19:10:43 +02:00
2019-06-07 17:57:46 +02:00
$this->infoLine('The import routine has started. The process is not visible. Please wait.');
Log::debug('Go for import!');
2017-07-15 10:26:16 +02:00
2019-06-07 17:57:46 +02:00
// run it!
$className = config('import.routine.file');
if (null === $className || !class_exists($className)) {
// @codeCoverageIgnoreStart
$this->errorLine('No routine for file provider.');
return 1;
// @codeCoverageIgnoreEnd
}
// keep repeating this call until job lands on "provider_finished"
$valid = ['provider_finished'];
$count = 0;
while (!in_array($importJob->status, $valid, true) && $count < 6) {
Log::debug(sprintf('Now in loop #%d.', $count + 1));
/** @var RoutineInterface $routine */
$routine = app($className);
$routine->setImportJob($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:
$jobRepository->setStatus($importJob, 'error');
$this->errorLine($message);
return 1;
}
2019-06-07 17:57:46 +02:00
$count++;
}
if ('provider_finished' === $importJob->status) {
$this->infoLine('Import has finished. Please wait for storage of data.');
// set job to be storing data:
$jobRepository->setStatus($importJob, 'storing_data');
/** @var ImportArrayStorage $storage */
$storage = app(ImportArrayStorage::class);
$storage->setImportJob($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:
$jobRepository->setStatus($importJob, 'error');
$this->errorLine($message);
2019-06-07 17:57:46 +02:00
return 1;
2017-07-15 10:26:16 +02:00
}
2019-06-07 17:57:46 +02:00
// set storage to be finished:
$jobRepository->setStatus($importJob, 'storage_finished');
}
2016-10-20 19:10:43 +02:00
2019-06-07 17:57:46 +02:00
// give feedback:
$this->infoLine('Job has finished.');
if (null !== $importJob->tag) {
$this->infoLine(sprintf('%d transaction(s) have been imported.', $importJob->tag->transactionJournals->count()));
$this->infoLine(sprintf('You can find your transactions under tag "%s"', $importJob->tag->tag));
}
2019-06-07 17:57:46 +02:00
if (null === $importJob->tag) {
$this->errorLine('No transactions have been imported :(.');
}
if (count($importJob->errors) > 0) {
$this->infoLine(sprintf('%d error(s) occurred:', count($importJob->errors)));
foreach ($importJob->errors as $err) {
$this->errorLine('- ' . $err);
}
}
2017-10-22 13:49:39 +02:00
// clear cache for user:
2018-07-15 09:27:38 +02:00
app('preferences')->setForUser($user, 'lastActivity', microtime());
2017-10-22 13:49:39 +02:00
2018-03-30 19:41:16 +02:00
return 0;
}
/**
2019-06-07 17:57:46 +02:00
* @param string $message
2018-03-30 19:41:16 +02:00
* @param array|null $data
*/
private function errorLine(string $message, array $data = null): void
{
Log::error($message, $data ?? []);
$this->error($message);
}
/**
* @param string $message
2019-06-07 17:57:46 +02:00
* @param array $data
2018-03-30 19:41:16 +02:00
*/
private function infoLine(string $message, array $data = null): void
{
Log::info($message, $data ?? []);
$this->line($message);
2016-10-20 19:10:43 +02:00
}
/**
2017-08-15 17:26:43 +02:00
* Verify user inserts correct arguments.
*
2018-03-30 19:41:16 +02:00
* @noinspection MultipleReturnStatementsInspection
2016-10-20 19:10:43 +02:00
* @return bool
*/
private function validArguments(): bool
{
2018-07-26 06:10:17 +02:00
$file = (string)$this->argument('file');
$configuration = (string)$this->argument('configuration');
2018-03-30 19:41:16 +02:00
$cwd = getcwd();
2019-06-07 17:57:46 +02:00
$enabled = (bool)config('import.enabled.file');
if (false === $enabled) {
2019-06-07 17:57:46 +02:00
$this->errorLine('CSV Provider is not enabled.');
2016-10-20 19:10:43 +02:00
return false;
}
2019-06-07 17:57:46 +02:00
if (!file_exists($file)) {
$this->errorLine(sprintf('Firefly III cannot find file "%s" (working directory: "%s").', $file, $cwd));
2016-10-20 19:10:43 +02:00
return false;
}
2019-06-07 17:57:46 +02:00
if (!file_exists($configuration)) {
$this->errorLine(sprintf('Firefly III cannot find configuration file "%s" (working directory: "%s").', $configuration, $cwd));
2016-10-20 19:10:43 +02:00
return false;
}
return true;
}
}