Massive rewrite for import routine, part 1.

This commit is contained in:
James Cole
2017-12-16 08:03:35 +01:00
parent 985cc100e2
commit 84b6708260
34 changed files with 671 additions and 244 deletions

View File

@@ -0,0 +1,159 @@
<?php
/**
* Initial.php
* Copyright (c) 2017 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* 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
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Support\Import\Configuration\File;
use ExpandedForm;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\ImportJob;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Support\Import\Configuration\ConfigurationInterface;
use Log;
/**
* Class CsvInitial.
*/
class Initial implements ConfigurationInterface
{
private $job;
/**
* @return array
*/
public function getData(): array
{
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
$accounts = $accountRepository->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET]);
$delimiters = [
',' => trans('form.csv_comma'),
';' => trans('form.csv_semicolon'),
'tab' => trans('form.csv_tab'),
];
$specifics = [];
// collect specifics.
foreach (config('csv.import_specifics') as $name => $className) {
$specifics[$name] = [
'name' => $className::getName(),
'description' => $className::getDescription(),
];
}
$data = [
'accounts' => ExpandedForm::makeSelectList($accounts),
'specifix' => [],
'delimiters' => $delimiters,
'specifics' => $specifics,
];
return $data;
}
/**
* Return possible warning to user.
*
* @return string
*/
public function getWarningMessage(): string
{
return '';
}
/**
* @param ImportJob $job
*
* @return ConfigurationInterface
*/
public function setJob(ImportJob $job): ConfigurationInterface
{
$this->job = $job;
return $this;
}
/**
* Store the result.
*
* @param array $data
*
* @return bool
*/
public function storeConfiguration(array $data): bool
{
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
$importId = $data['csv_import_account'] ?? 0;
$account = $repository->find(intval($importId));
$hasHeaders = isset($data['has_headers']) && 1 === intval($data['has_headers']) ? true : false;
$config = $this->job->configuration;
$config['initial-config-complete'] = true;
$config['has-headers'] = $hasHeaders;
$config['date-format'] = $data['date_format'];
$config['delimiter'] = $data['csv_delimiter'];
$config['delimiter'] = 'tab' === $config['delimiter'] ? "\t" : $config['delimiter'];
$config['apply_rules'] = isset($data['apply_rules']) && 1 === intval($data['apply_rules']) ? true : false;
$config['match_bills'] = isset($data['match_bills']) && 1 === intval($data['match_bills']) ? true : false;
Log::debug('Entered import account.', ['id' => $importId]);
if (null !== $account->id) {
Log::debug('Found account.', ['id' => $account->id, 'name' => $account->name]);
$config['import-account'] = $account->id;
}
if (null === $account->id) {
Log::error('Could not find anything for csv_import_account.', ['id' => $importId]);
}
$config = $this->storeSpecifics($data, $config);
$this->job->configuration = $config;
$this->job->save();
return true;
}
/**
* @param array $data
* @param array $config
*
* @return array
*/
private function storeSpecifics(array $data, array $config): array
{
// loop specifics.
if (isset($data['specifics']) && is_array($data['specifics'])) {
$names = array_keys($data['specifics']);
foreach ($names as $name) {
// verify their content.
$className = sprintf('FireflyIII\Import\Specifics\%s', $name);
if (class_exists($className)) {
$config['specifics'][$name] = 1;
}
}
}
return $config;
}
}

View File

@@ -0,0 +1,289 @@
<?php
/**
* Map.php
* Copyright (c) 2017 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* 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
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Support\Import\Configuration\File;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Import\Mapper\MapperInterface;
use FireflyIII\Import\MapperPreProcess\PreProcessorInterface;
use FireflyIII\Import\Specifics\SpecificInterface;
use FireflyIII\Models\ImportJob;
use FireflyIII\Support\Import\Configuration\ConfigurationInterface;
use League\Csv\Reader;
use Log;
/**
* Class Mapping.
*/
class Map implements ConfigurationInterface
{
/** @var array */
private $configuration = [];
/** @var array that holds each column to be mapped by the user */
private $data = [];
/** @var ImportJob */
private $job;
/** @var array */
private $validSpecifics = [];
/**
* @return array
*
* @throws FireflyException
*/
public function getData(): array
{
$this->configuration = $this->job->configuration;
$this->getMappableColumns();
// in order to actually map we also need all possible values from the CSV file.
$content = $this->job->uploadFileContents();
/** @var Reader $reader */
$reader = Reader::createFromString($content);
$reader->setDelimiter($this->configuration['delimiter']);
if($this->configuration['has-headers']) {
$reader->setHeaderOffset(0);
}
$results = $reader->getRecords();
$this->validSpecifics = array_keys(config('csv.import_specifics'));
$indexes = array_keys($this->data);
$rowIndex = 0;
foreach ($results as $rowIndex => $row) {
$row = $this->runSpecifics($row);
//do something here
foreach ($indexes as $index) { // this is simply 1, 2, 3, etc.
if (!isset($row[$index])) {
// don't really know how to handle this. Just skip, for now.
continue;
}
$value = $row[$index];
if (strlen($value) > 0) {
// we can do some preprocessing here,
// which is exclusively to fix the tags:
if (null !== $this->data[$index]['preProcessMap'] && strlen($this->data[$index]['preProcessMap']) > 0) {
/** @var PreProcessorInterface $preProcessor */
$preProcessor = app($this->data[$index]['preProcessMap']);
$result = $preProcessor->run($value);
$this->data[$index]['values'] = array_merge($this->data[$index]['values'], $result);
Log::debug($rowIndex . ':' . $index . 'Value before preprocessor', ['value' => $value]);
Log::debug($rowIndex . ':' . $index . 'Value after preprocessor', ['value-new' => $result]);
Log::debug($rowIndex . ':' . $index . 'Value after joining', ['value-complete' => $this->data[$index]['values']]);
continue;
}
$this->data[$index]['values'][] = $value;
}
}
}
$setIndexes = array_keys($this->data);
foreach ($setIndexes as $index) {
$this->data[$index]['values'] = array_unique($this->data[$index]['values']);
asort($this->data[$index]['values']);
}
unset($setIndexes);
// save number of rows, thus number of steps, in job:
$steps = $rowIndex * 5;
$extended = $this->job->extended_status;
$extended['steps'] = $steps;
$this->job->extended_status = $extended;
$this->job->save();
return $this->data;
}
/**
* Return possible warning to user.
*
* @return string
*/
public function getWarningMessage(): string
{
return '';
}
/**
* @param ImportJob $job
*
* @return ConfigurationInterface
*/
public function setJob(ImportJob $job): ConfigurationInterface
{
$this->job = $job;
return $this;
}
/**
* Store the result.
*
* @param array $data
*
* @return bool
*/
public function storeConfiguration(array $data): bool
{
$config = $this->job->configuration;
if (isset($data['mapping'])) {
foreach ($data['mapping'] as $index => $data) {
$config['column-mapping-config'][$index] = [];
foreach ($data as $value => $mapId) {
$mapId = intval($mapId);
if (0 !== $mapId) {
$config['column-mapping-config'][$index][$value] = intval($mapId);
}
}
}
}
// set thing to be completed.
$config['column-mapping-complete'] = true;
$this->job->configuration = $config;
$this->job->save();
return true;
}
/**
* @param string $column
*
* @return MapperInterface
*/
private function createMapper(string $column): MapperInterface
{
$mapperClass = config('csv.import_roles.' . $column . '.mapper');
$mapperName = sprintf('\\FireflyIII\\Import\Mapper\\%s', $mapperClass);
/** @var MapperInterface $mapper */
$mapper = new $mapperName;
return $mapper;
}
/**
* @return bool
*/
private function getMappableColumns(): bool
{
$config = $this->job->configuration;
/**
* @var int
* @var bool $mustBeMapped
*/
foreach ($config['column-do-mapping'] as $index => $mustBeMapped) {
$column = $this->validateColumnName($config['column-roles'][$index] ?? '_ignore');
$shouldMap = $this->shouldMapColumn($column, $mustBeMapped);
if ($shouldMap) {
// create configuration entry for this specific column and add column to $this->data array for later processing.
$this->data[$index] = [
'name' => $column,
'index' => $index,
'options' => $this->createMapper($column)->getMap(),
'preProcessMap' => $this->getPreProcessorName($column),
'values' => [],
];
}
}
return true;
}
/**
* @param string $column
*
* @return string
*/
private function getPreProcessorName(string $column): string
{
$name = '';
$hasPreProcess = config('csv.import_roles.' . $column . '.pre-process-map');
$preProcessClass = config('csv.import_roles.' . $column . '.pre-process-mapper');
if (null !== $hasPreProcess && true === $hasPreProcess && null !== $preProcessClass) {
$name = sprintf('\\FireflyIII\\Import\\MapperPreProcess\\%s', $preProcessClass);
}
return $name;
}
/**
* @param array $row
*
* @return array
*
* @throws FireflyException
*/
private function runSpecifics(array $row): array
{
// run specifics here:
// and this is the point where the specifix go to work.
$names = array_keys($this->job->configuration['specifics']);
foreach ($names as $name) {
if (!in_array($name, $this->validSpecifics)) {
throw new FireflyException(sprintf('"%s" is not a valid class name', $name));
}
$class = config('csv.import_specifics.' . $name);
/** @var SpecificInterface $specific */
$specific = app($class);
// it returns the row, possibly modified:
$row = $specific->run($row);
}
return $row;
}
/**
* @param string $column
* @param bool $mustBeMapped
*
* @return bool
*/
private function shouldMapColumn(string $column, bool $mustBeMapped): bool
{
$canBeMapped = config('csv.import_roles.' . $column . '.mappable');
return $canBeMapped && $mustBeMapped;
}
/**
* @param string $column
*
* @return string
*
* @throws FireflyException
*/
private function validateColumnName(string $column): string
{
// is valid column?
$validColumns = array_keys(config('csv.import_roles'));
if (!in_array($column, $validColumns)) {
throw new FireflyException(sprintf('"%s" is not a valid column.', $column));
}
return $column;
}
}

View File

@@ -0,0 +1,293 @@
<?php
/**
* Roles.php
* Copyright (c) 2017 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* 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
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Support\Import\Configuration\File;
use FireflyIII\Import\Specifics\SpecificInterface;
use FireflyIII\Models\ImportJob;
use FireflyIII\Support\Import\Configuration\ConfigurationInterface;
use League\Csv\Reader;
use League\Csv\Statement;
use Log;
/**
* Class Roles.
*/
class Roles implements ConfigurationInterface
{
private $data = [];
/** @var ImportJob */
private $job;
/** @var string */
private $warning = '';
/**
* Get the data necessary to show the configuration screen.
*
* @return array
*/
public function getData(): array
{
$config = $this->job->configuration;
$content = $this->job->uploadFileContents();
// create CSV reader.
$reader = Reader::createFromString($content);
$reader->setDelimiter($config['delimiter']);
if ($config['has-headers']) {
$reader->setHeaderOffset(0);
}
$stmt = (new Statement)->limit(intval(config('csv.example_rows', 5)));
// set data:
$roles = $this->getRoles();
asort($roles);
$this->data = [
'examples' => [],
'roles' => $roles,
'total' => 0,
'headers' => $config['has-headers'] ? $reader->fetchOne(0) : [],
];
$records = $stmt->process($reader);
foreach ($records as $row) {
$row = $this->processSpecifics($row);
$count = count($row);
$this->data['total'] = $count > $this->data['total'] ? $count : $this->data['total'];
$this->processRow($row);
}
$this->updateColumCount();
$this->makeExamplesUnique();
return $this->data;
}
/**
* Return possible warning to user.
*
* @return string
*/
public function getWarningMessage(): string
{
return $this->warning;
}
/**
* @param ImportJob $job
*
* @return ConfigurationInterface
*/
public function setJob(ImportJob $job): ConfigurationInterface
{
$this->job = $job;
return $this;
}
/**
* Store the result.
*
* @param array $data
*
* @return bool
*/
public function storeConfiguration(array $data): bool
{
Log::debug('Now in storeConfiguration of Roles.');
$config = $this->job->configuration;
$count = $config['column-count'];
for ($i = 0; $i < $count; ++$i) {
$role = $data['role'][$i] ?? '_ignore';
$mapping = isset($data['map'][$i]) && $data['map'][$i] === '1' ? true : false;
$config['column-roles'][$i] = $role;
$config['column-do-mapping'][$i] = $mapping;
Log::debug(sprintf('Column %d has been given role %s', $i, $role));
}
$this->job->configuration = $config;
$this->job->save();
$this->ignoreUnmappableColumns();
$this->setRolesComplete();
$this->isMappingNecessary();
return true;
}
/**
* @return array
*/
private function getRoles(): array
{
$roles = [];
foreach (array_keys(config('csv.import_roles')) as $role) {
$roles[$role] = trans('csv.column_' . $role);
}
return $roles;
}
/**
* @return bool
*/
private function ignoreUnmappableColumns(): bool
{
$config = $this->job->configuration;
$count = $config['column-count'];
for ($i = 0; $i < $count; ++$i) {
$role = $config['column-roles'][$i] ?? '_ignore';
$mapping = $config['column-do-mapping'][$i] ?? false;
if ('_ignore' === $role && true === $mapping) {
$mapping = false;
Log::debug(sprintf('Column %d has type %s so it cannot be mapped.', $i, $role));
}
$config['column-do-mapping'][$i] = $mapping;
}
$this->job->configuration = $config;
$this->job->save();
return true;
}
/**
* @return bool
*/
private function isMappingNecessary()
{
$config = $this->job->configuration;
$count = $config['column-count'];
$toBeMapped = 0;
for ($i = 0; $i < $count; ++$i) {
$mapping = $config['column-do-mapping'][$i] ?? false;
if (true === $mapping) {
++$toBeMapped;
}
}
Log::debug(sprintf('Found %d columns that need mapping.', $toBeMapped));
if (0 === $toBeMapped) {
// skip setting of map, because none need to be mapped:
$config['column-mapping-complete'] = true;
$this->job->configuration = $config;
$this->job->save();
}
return true;
}
/**
* make unique example data.
*/
private function makeExamplesUnique(): bool
{
foreach ($this->data['examples'] as $index => $values) {
$this->data['examples'][$index] = array_unique($values);
}
return true;
}
/**
* @param array $row
*
* @return bool
*/
private function processRow(array $row): bool
{
foreach ($row as $index => $value) {
$value = trim($value);
if (strlen($value) > 0) {
$this->data['examples'][$index][] = $value;
}
}
return true;
}
/**
* run specifics here:
* and this is the point where the specifix go to work.
*
* @param array $row
*
* @return array
*/
private function processSpecifics(array $row): array
{
$names = array_keys($this->job->configuration['specifics']);
foreach ($names as $name) {
/** @var SpecificInterface $specific */
$specific = app('FireflyIII\Import\Specifics\\' . $name);
$row = $specific->run($row);
}
return $row;
}
/**
* @return bool
*/
private function setRolesComplete(): bool
{
$config = $this->job->configuration;
$count = $config['column-count'];
$assigned = 0;
$hasAmount = false;
for ($i = 0; $i < $count; ++$i) {
$role = $config['column-roles'][$i] ?? '_ignore';
if ('_ignore' !== $role) {
++$assigned;
}
if (in_array($role, ['amount', 'amount_credit', 'amount_debet'])) {
$hasAmount = true;
}
}
if ($assigned > 0 && $hasAmount) {
$config['column-roles-complete'] = true;
$this->job->configuration = $config;
$this->job->save();
$this->warning = '';
}
if (0 === $assigned || !$hasAmount) {
$this->warning = strval(trans('csv.roles_warning'));
}
return true;
}
/**
* @return bool
*/
private function updateColumCount(): bool
{
$config = $this->job->configuration;
$count = $this->data['total'];
$config['column-count'] = $count;
$this->job->configuration = $config;
$this->job->save();
return true;
}
}

View File

@@ -0,0 +1,89 @@
<?php
/**
* Upload.php
* Copyright (c) 2017 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* 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
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Support\Import\Configuration\File;
use FireflyIII\Import\Specifics\SpecificInterface;
use FireflyIII\Models\ImportJob;
use FireflyIII\Support\Import\Configuration\ConfigurationInterface;
use League\Csv\Reader;
use League\Csv\Statement;
use Log;
/**
* Class Upload.
*/
class Upload implements ConfigurationInterface
{
/** @var ImportJob */
private $job;
/** @var string */
private $warning = '';
/**
* Get the data necessary to show the configuration screen.
*
* @return array
*/
public function getData(): array
{
return [];
}
/**
* Return possible warning to user.
*
* @return string
*/
public function getWarningMessage(): string
{
return $this->warning;
}
/**
* @param ImportJob $job
*
* @return ConfigurationInterface
*/
public function setJob(ImportJob $job): ConfigurationInterface
{
$this->job = $job;
return $this;
}
/**
* Store the result.
*
* @param array $data
*
* @return bool
*/
public function storeConfiguration(array $data): bool
{
echo 'do something with data.';
exit;
return true;
}
}