diff --git a/app/Api/V1/Controllers/ImportController.php b/app/Api/V1/Controllers/ImportController.php deleted file mode 100644 index 52065ac4db..0000000000 --- a/app/Api/V1/Controllers/ImportController.php +++ /dev/null @@ -1,181 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V1\Controllers; - -use FireflyIII\Helpers\Collector\GroupCollectorInterface; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Http\Api\TransactionFilter; -use FireflyIII\Transformers\ImportJobTransformer; -use FireflyIII\Transformers\TransactionGroupTransformer; -use FireflyIII\User; -use Illuminate\Http\JsonResponse; -use Illuminate\Http\Request; -use Illuminate\Pagination\LengthAwarePaginator; -use Illuminate\Support\Collection; -use League\Fractal\Pagination\IlluminatePaginatorAdapter; -use League\Fractal\Resource\Collection as FractalCollection; -use League\Fractal\Resource\Item; - -/** - * Class ImportController - * - * @deprecated - * @codeCoverageIgnore - */ -class ImportController extends Controller -{ - use TransactionFilter; - /** @var ImportJobRepositoryInterface Import job repository. */ - private $repository; - - /** - * ImportController constructor. - * - * @codeCoverageIgnore - */ - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($user); - - return $next($request); - } - ); - } - - /** - * @return JsonResponse - * @codeCoverageIgnore - */ - public function listAll(): JsonResponse - { - // create some objects: - $manager = $this->getManager(); - $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; - - // get list of accounts. Count it and split it. - $collection = $this->repository->get(); - $count = $collection->count(); - $importJobs = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - - // make paginator: - $paginator = new LengthAwarePaginator($importJobs, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.import.list') . $this->buildParams()); - - /** @var ImportJobTransformer $transformer */ - $transformer = app(ImportJobTransformer::class); - $transformer->setParameters($this->parameters); - - $resource = new FractalCollection($importJobs, $transformer, 'import_jobs'); - $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); - - return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json'); - } - - /** - * @param ImportJob $importJob - * - * @return JsonResponse - * @codeCoverageIgnore - */ - public function show(ImportJob $importJob): JsonResponse - { - $manager = $this->getManager(); - /** @var ImportJobTransformer $transformer */ - $transformer = app(ImportJobTransformer::class); - $transformer->setParameters($this->parameters); - - $resource = new Item($importJob, $transformer, 'import_jobs'); - - return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json'); - } - - /** - * Show all transactions - * - * @param Request $request - * @param ImportJob $importJob - * - * @return JsonResponse - * @codeCoverageIgnore - */ - public function transactions(Request $request, ImportJob $importJob): JsonResponse - { - $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; - $type = $request->get('type') ?? 'default'; - $this->parameters->set('type', $type); - - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); - - $tag = $importJob->tag; - $transactions = new Collection(); - $paginator = new LengthAwarePaginator($transactions, 0, $pageSize); - $paginator->setPath(route('api.v1.import.transactions', [$importJob->key]) . $this->buildParams()); - - if (null !== $tag) { - /** @var User $admin */ - $admin = auth()->user(); - - // use new group collector: - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector - ->setUser($admin) - // filter on tag. - ->setTag($tag) - // all info needed for the API: - ->withAPIInformation() - // set page size: - ->setLimit($pageSize) - // set page to retrieve - ->setPage($this->parameters->get('page')) - // set types of transactions to return. - ->setTypes($types); - - if (null !== $this->parameters->get('start') && null !== $this->parameters->get('end')) { - $collector->setRange($this->parameters->get('start'), $this->parameters->get('end')); - } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.transactions.index') . $this->buildParams()); - $transactions = $paginator->getCollection(); - } - - /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); - $transformer->setParameters($this->parameters); - - $resource = new FractalCollection($transactions, $transformer, 'transactions'); - $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); - - return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json'); - } - -} diff --git a/app/Console/Commands/Import/CreateCSVImport.php b/app/Console/Commands/Import/CreateCSVImport.php deleted file mode 100644 index 3da93f17d8..0000000000 --- a/app/Console/Commands/Import/CreateCSVImport.php +++ /dev/null @@ -1,76 +0,0 @@ -. - */ - -/** @noinspection MultipleReturnStatementsInspection */ - -declare(strict_types=1); - -namespace FireflyIII\Console\Commands\Import; - -use Exception; -use FireflyIII\Console\Commands\VerifiesAccessToken; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Import\Routine\RoutineInterface; -use FireflyIII\Import\Storage\ImportArrayStorage; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Repositories\User\UserRepositoryInterface; -use FireflyIII\User; -use Illuminate\Console\Command; -use Log; - -/** - * Class CreateCSVImport. - * - * @deprecated - * @codeCoverageIgnore - */ -class CreateCSVImport extends Command -{ - use VerifiesAccessToken; - /** - * The console command description. - * - * @var string - */ - protected $description = 'Use this command to create a new CSV file import.'; - /** - * The name and signature of the console command. - * - * @var string - */ - protected $signature - = '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.} - {--token= : The user\'s access token.}'; - /** - * Run the command. - */ - public function handle(): int - { - $this->error('This command is disabled.'); - return 1; - } - - -} diff --git a/app/Console/Commands/Tools/ApplyRules.php b/app/Console/Commands/Tools/ApplyRules.php index 8a9fd90b5b..612b2e0f41 100644 --- a/app/Console/Commands/Tools/ApplyRules.php +++ b/app/Console/Commands/Tools/ApplyRules.php @@ -60,7 +60,7 @@ class ApplyRules extends Command */ protected $signature = 'firefly-iii:apply-rules - {--user=1 : The user ID that the import should import for.} + {--user=1 : The user ID.} {--token= : The user\'s access token.} {--accounts= : A comma-separated list of asset accounts or liabilities to apply your rules to.} {--rule_groups= : A comma-separated list of rule groups to apply. Take the ID\'s of these rule groups from the Firefly III interface.} diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php index 03eb6b2d83..9ebfc428e5 100644 --- a/app/Http/Controllers/DebugController.php +++ b/app/Http/Controllers/DebugController.php @@ -224,15 +224,14 @@ class DebugController extends Controller { $set = RouteFacade::getRoutes(); $ignore = ['chart.', 'javascript.', 'json.', 'report-data.', 'popup.', 'debugbar.', 'attachments.download', 'attachments.preview', - 'bills.rescan', 'budgets.income', 'currencies.def', 'error', 'flush', 'help.show', 'import.file', + 'bills.rescan', 'budgets.income', 'currencies.def', 'error', 'flush', 'help.show', 'login', 'logout', 'password.reset', 'profile.confirm-email-change', 'profile.undo-email-change', 'register', 'report.options', 'routes', 'rule-groups.down', 'rule-groups.up', 'rules.up', 'rules.down', 'rules.select', 'search.search', 'test-flash', 'transactions.link.delete', 'transactions.link.switch', - 'two-factor.lost', 'reports.options', 'debug', 'import.create-job', 'import.download', 'import.start', 'import.status.json', + 'two-factor.lost', 'reports.options', 'debug', 'preferences.delete-code', 'rules.test-triggers', 'piggy-banks.remove-money', 'piggy-banks.add-money', 'accounts.reconcile.transactions', 'accounts.reconcile.overview', - 'transactions.clone', 'two-factor.index', 'api.v1', 'installer.', 'attachments.view', 'import.create', - 'import.job.download', 'import.job.start', 'import.job.status.json', 'import.job.store', 'recurring.events', + 'transactions.clone', 'two-factor.index', 'api.v1', 'installer.', 'attachments.view', 'recurring.events', 'recurring.suggest', ]; $return = ' '; diff --git a/app/Http/Controllers/Import/CallbackController.php b/app/Http/Controllers/Import/CallbackController.php deleted file mode 100644 index 9e9c8ad65a..0000000000 --- a/app/Http/Controllers/Import/CallbackController.php +++ /dev/null @@ -1,82 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Http\Controllers\Import; - - -use FireflyIII\Http\Controllers\Controller; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Contracts\View\Factory; -use Illuminate\Http\RedirectResponse; -use Illuminate\Http\Request; -use Illuminate\Routing\Redirector; -use Illuminate\View\View; -use Log; - -/** - * Class CallbackController - * - * @deprecated - * @codeCoverageIgnore - */ -class CallbackController extends Controller -{ - - /** - * Callback specifically for YNAB logins. - * - * @param Request $request - * - * @param ImportJobRepositoryInterface $repository - * - * @return Factory|RedirectResponse|Redirector|View - */ - public function ynab(Request $request, ImportJobRepositoryInterface $repository) - { - $code = (string) $request->get('code'); - $jobKey = (string) $request->get('state'); - - if ('' === $code) { - return view('error')->with('message', 'You Need A Budget did not reply with a valid authorization code. Firefly III cannot continue.'); - } - - $importJob = $repository->findByKey($jobKey); - - if ('' === $jobKey || null === $importJob) { - return view('error')->with('message', 'You Need A Budget did not reply with the correct state identifier. Firefly III cannot continue.'); - } - Log::debug(sprintf('Got a code from YNAB: %s', $code)); - - // we have a code. Make the job ready for the next step, and then redirect the user. - $configuration = $repository->getConfiguration($importJob); - $configuration['auth_code'] = $code; - $repository->setConfiguration($importJob, $configuration); - - // set stage to make the import routine take the correct action: - $repository->setStatus($importJob, 'ready_to_run'); - $repository->setStage($importJob, 'get_access_token'); - - return redirect(route('import.job.status.index', [$importJob->key])); - } - -} diff --git a/app/Http/Controllers/Import/IndexController.php b/app/Http/Controllers/Import/IndexController.php deleted file mode 100644 index d06579bded..0000000000 --- a/app/Http/Controllers/Import/IndexController.php +++ /dev/null @@ -1,198 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Http\Controllers\Import; - -use FireflyIII\Http\Controllers\Controller; -use FireflyIII\Import\Prerequisites\PrerequisitesInterface; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Repositories\User\UserRepositoryInterface; -use FireflyIII\Support\Binder\ImportProvider; -use Illuminate\Contracts\View\Factory; -use Illuminate\Http\RedirectResponse; -use Illuminate\Http\Response as LaravelResponse; -use Illuminate\Routing\Redirector; -use Illuminate\View\View; -use Log; - -/** - * - * Class IndexController - * - * @deprecated - * @codeCoverageIgnore - */ -class IndexController extends Controller -{ - /** @var array All available providers */ - public $providers; - /** @var ImportJobRepositoryInterface The import job repository */ - public $repository; - /** @var UserRepositoryInterface The user repository */ - public $userRepository; - - /** - * IndexController constructor. - */ - public function __construct() - { - parent::__construct(); - - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-archive'); - app('view')->share('title', (string) trans('firefly.import_index_title')); - $this->repository = app(ImportJobRepositoryInterface::class); - $this->userRepository = app(UserRepositoryInterface::class); - $this->providers = ImportProvider::getProviders(); - - return $next($request); - } - ); - } - - /** - * Creates a new import job for $importProvider. - * - * @param string $importProvider - * - * @return RedirectResponse|Redirector - * - */ - public function create(string $importProvider) - { - $hasPreReq = (bool) config(sprintf('import.has_prereq.%s', $importProvider)); - $hasConfig = (bool) config(sprintf('import.has_job_config.%s', $importProvider)); - $allowedForDemo = (bool) config(sprintf('import.allowed_for_demo.%s', $importProvider)); - $isDemoUser = $this->userRepository->hasRole(auth()->user(), 'demo'); - - Log::debug(sprintf('Will create job for provider "%s"', $importProvider)); - Log::debug(sprintf('Is demo user? %s', var_export($isDemoUser, true))); - Log::debug(sprintf('Is allowed for user? %s', var_export($allowedForDemo, true))); - Log::debug(sprintf('Has prerequisites? %s', var_export($hasPreReq, true))); - Log::debug(sprintf('Has config? %s', var_export($hasConfig, true))); - - // @codeCoverageIgnoreStart - if ($isDemoUser && !$allowedForDemo) { - Log::debug('User is demo and this provider doesnt work for demo users.'); - - return redirect(route('import.index')); - } - // @codeCoverageIgnoreEnd - - $importJob = $this->repository->create($importProvider); - - Log::debug(sprintf('Created job #%d for provider %s', $importJob->id, $importProvider)); - - // no prerequisites but job has config: - if (false === $hasPreReq && false !== $hasConfig) { - Log::debug('Provider has no prerequisites. Continue.'); - $this->repository->setStatus($importJob, 'has_prereq'); - Log::debug('Redirect to configuration.'); - - return redirect(route('import.job.configuration.index', [$importJob->key])); - } - - // job has prerequisites: - Log::debug('Job provider has prerequisites.'); - /** @var PrerequisitesInterface $providerPre */ - $providerPre = app((string) config(sprintf('import.prerequisites.%s', $importProvider))); - $providerPre->setUser($importJob->user); - - // and are not filled in: - if (!$providerPre->isComplete()) { - Log::debug('Job provider prerequisites are not yet filled in. Redirect to prerequisites-page.'); - - // redirect to global prerequisites - return redirect(route('import.prerequisites.index', [$importProvider, $importJob->key])); - } - Log::debug('Prerequisites are complete.'); - - // but are filled in: - $this->repository->setStatus($importJob, 'has_prereq'); - - // and has no config: - if (false === $hasConfig) { - // @codeCoverageIgnoreStart - Log::debug('Provider has no configuration. Job is ready to start.'); - $this->repository->setStatus($importJob, 'ready_to_run'); - Log::debug('Redirect to status-page.'); - - return redirect(route('import.job.status.index', [$importJob->key])); - // @codeCoverageIgnoreEnd - } - - // but also needs config: - Log::debug('Job has configuration. Redirect to job-config.'); - - // Otherwise just redirect to job configuration. - return redirect(route('import.job.configuration.index', [$importJob->key])); - - } - - /** - * Generate a JSON file of the job's configuration and send it to the user. - * - * @param ImportJob $job - * - * @return LaravelResponse - */ - public function download(ImportJob $job): LaravelResponse - { - Log::debug('Now in download()', ['job' => $job->key]); - $config = $this->repository->getConfiguration($job); - // This is CSV import specific: - $config['delimiter'] = $config['delimiter'] ?? ','; - $config['delimiter'] = "\t" === $config['delimiter'] ? 'tab' : $config['delimiter']; - - $result = json_encode($config, JSON_PRETTY_PRINT); - $name = sprintf('"%s"', addcslashes('import-configuration-' . date('Y-m-d') . '.json', '"\\')); - /** @var LaravelResponse $response */ - $response = response($result); - $response->header('Content-disposition', 'attachment; filename=' . $name) - ->header('Content-Type', 'application/json') - ->header('Content-Description', 'File Transfer') - ->header('Connection', 'Keep-Alive') - ->header('Expires', '0') - ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') - ->header('Pragma', 'public') - ->header('Content-Length', strlen($result)); - - return $response; - } - - /** - * General import index. - * - * @return Factory|View - */ - public function index() - { - $providers = $this->providers; - $subTitle = (string) trans('import.index_breadcrumb'); - $subTitleIcon = 'fa-home'; - $isDemoUser = $this->userRepository->hasRole(auth()->user(), 'demo'); - - return view('import.index', compact('subTitle', 'subTitleIcon', 'providers', 'isDemoUser')); - } -} diff --git a/app/Http/Controllers/Import/JobConfigurationController.php b/app/Http/Controllers/Import/JobConfigurationController.php deleted file mode 100644 index 50c4ba1aa5..0000000000 --- a/app/Http/Controllers/Import/JobConfigurationController.php +++ /dev/null @@ -1,169 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Http\Controllers\Import; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Http\Controllers\Controller; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Http\Controllers\CreateStuff; -use Illuminate\Contracts\View\Factory; -use Illuminate\Http\RedirectResponse; -use Illuminate\Http\Request; -use Illuminate\Http\UploadedFile; -use Illuminate\Routing\Redirector; -use Illuminate\Support\MessageBag; -use Illuminate\View\View; -use Log; - -/** - * Class JobConfigurationController - * - * @deprecated - * @codeCoverageIgnore - */ -class JobConfigurationController extends Controller -{ - use CreateStuff; - /** @var ImportJobRepositoryInterface The import job repository */ - public $repository; - - /** - * JobConfigurationController constructor. - */ - public function __construct() - { - parent::__construct(); - - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-archive'); - app('view')->share('title', (string) trans('firefly.import_index_title')); - $this->repository = app(ImportJobRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * Configure the job. This method is returned to until job is deemed "configured". - * - * @param ImportJob $importJob - * - * @throws FireflyException - * - * @return Factory|RedirectResponse|Redirector|View - * - */ - public function index(ImportJob $importJob) - { - Log::debug('Now in JobConfigurationController::index()'); - $allowed = ['has_prereq', 'need_job_config']; - if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { - Log::error(sprintf('Job has state "%s", but we only accept %s', $importJob->status, json_encode($allowed))); - session()->flash('error', (string) trans('import.bad_job_status', ['status' => e($importJob->status)])); - - return redirect(route('import.index')); - } - Log::debug(sprintf('Now in JobConfigurationController::index() with job "%s" and status "%s"', $importJob->key, $importJob->status)); - - // if provider has no config, just push it through: - $importProvider = $importJob->provider; - if (!(bool) config(sprintf('import.has_job_config.%s', $importProvider))) { - // @codeCoverageIgnoreStart - Log::debug('Job needs no config, is ready to run!'); - $this->repository->setStatus($importJob, 'ready_to_run'); - - return redirect(route('import.job.status.index', [$importJob->key])); - // @codeCoverageIgnoreEnd - } - - $configurator = $this->makeConfigurator($importJob); - if ($configurator->configurationComplete()) { - Log::debug('Config is complete, set status to ready_to_run.'); - $this->repository->setStatus($importJob, 'ready_to_run'); - - return redirect(route('import.job.status.index', [$importJob->key])); - } - - $view = $configurator->getNextView(); - $data = $configurator->getNextData(); - $subTitle = (string) trans('import.job_configuration_breadcrumb', ['key' => $importJob->key]); - $subTitleIcon = 'fa-wrench'; - - return view($view, compact('data', 'importJob', 'subTitle', 'subTitleIcon')); - } - - /** - * Store the configuration. Returns to "configure" method until job is configured. - * - * @param Request $request - * @param ImportJob $importJob - * - * @throws FireflyException - * @return RedirectResponse|Redirector - * - */ - public function post(Request $request, ImportJob $importJob) - { - // catch impossible status: - $allowed = ['has_prereq', 'need_job_config']; - if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { - session()->flash('error', (string) trans('import.bad_job_status', ['status' => e($importJob->status)])); - - return redirect(route('import.index')); - } - - Log::debug('Now in postConfigure()', ['job' => $importJob->key]); - $configurator = $this->makeConfigurator($importJob); - - // is the job already configured? - if ($configurator->configurationComplete()) { - $this->repository->setStatus($importJob, 'ready_to_run'); - - return redirect(route('import.job.status.index', [$importJob->key])); - } - - // uploaded files are attached to the job. - // the configurator can then handle them. - $result = new MessageBag; - - /** @var UploadedFile $upload */ - foreach ($request->allFiles() as $name => $upload) { - $result = $this->repository->storeFileUpload($importJob, $name, $upload); - } - $data = $request->all(); - $messages = $configurator->configureJob($data); - $result->merge($messages); - - if ($messages->count() > 0) { - $request->session()->flash('warning', $messages->first()); - } - - // return to configure - return redirect(route('import.job.configuration.index', [$importJob->key])); - } - - -} diff --git a/app/Http/Controllers/Import/JobStatusController.php b/app/Http/Controllers/Import/JobStatusController.php deleted file mode 100644 index f90dc9f383..0000000000 --- a/app/Http/Controllers/Import/JobStatusController.php +++ /dev/null @@ -1,240 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Http\Controllers\Import; - -use Exception; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Http\Controllers\Controller; -use FireflyIII\Import\Routine\RoutineInterface; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Http\Controllers\CreateStuff; -use Illuminate\Http\JsonResponse; -use Log; - -/** - * Class JobStatusController - * - * @deprecated - * @codeCoverageIgnore - */ -class JobStatusController extends Controller -{ - use CreateStuff; - /** @var ImportJobRepositoryInterface The import job repository */ - private $repository; - - /** - * JobStatusController constructor. - */ - public function __construct() - { - parent::__construct(); - // set time limit to zero to prevent timeouts. - set_time_limit(0); - - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-archive'); - app('view')->share('title', (string) trans('firefly.import_index_title')); - $this->repository = app(ImportJobRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * Index for job status. - * - * @param ImportJob $importJob - * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View - */ - public function index(ImportJob $importJob) - { - $subTitleIcon = 'fa-gear'; - $subTitle = (string) trans('import.job_status_breadcrumb', ['key' => $importJob->key]); - - return view('import.status', compact('importJob', 'subTitle', 'subTitleIcon')); - } - - /** - * JSON overview of job status. - * - * @param ImportJob $importJob - * - * @return JsonResponse - */ - public function json(ImportJob $importJob): JsonResponse - { - $count = $this->repository->countTransactions($importJob); - $json = [ - 'status' => $importJob->status, - 'errors' => $importJob->errors, - 'count' => $count, - 'tag_id' => $importJob->tag_id, - 'tag_name' => null === $importJob->tag_id ? null : $importJob->tag->tag, - 'report_txt' => (string) trans('import.unknown_import_result'), - 'download_config' => false, - 'download_config_text' => '', - ]; - - if ('file' === $importJob->provider) { - $json['download_config'] = true; - $json['download_config_text'] - = trans('import.should_download_config', ['route' => route('import.job.download', [$importJob->key])]) . ' ' - . trans('import.share_config_file'); - } - - // if count is zero: - if (null !== $importJob->tag_id) { - $count = $this->repository->countByTag($importJob); - } - if (0 === $count) { - $json['report_txt'] = (string) trans('import.result_no_transactions'); - } - if (1 === $count && null !== $importJob->tag_id) { - $json['report_txt'] = trans( - 'import.result_one_transaction', - ['route' => route('tags.show', [$importJob->tag_id, 'all']), 'tag' => $importJob->tag->tag] - ); - } - if ($count > 1 && null !== $importJob->tag_id) { - $json['report_txt'] = trans( - 'import.result_many_transactions', - ['count' => $count, 'route' => route('tags.show', [$importJob->tag_id, 'all']), 'tag' => $importJob->tag->tag] - ); - } - - return response()->json($json); - } - - /** - * Calls to start the job. - * - * @param ImportJob $importJob - * - * @return JsonResponse - */ - public function start(ImportJob $importJob): JsonResponse - { - Log::info('Now in JobStatusController::start'); - // catch impossible status: - $allowed = ['ready_to_run', 'need_job_config']; - - if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { - Log::error(sprintf('Job is not ready. Status should be in array, but is %s', $importJob->status), $allowed); - $this->repository->setStatus($importJob, 'error'); - - return response()->json( - ['status' => 'NOK', 'message' => sprintf('JobStatusController::start expects status "ready_to_run" instead of "%s".', $importJob->status)] - ); - } - $importProvider = $importJob->provider; - $key = sprintf('import.routine.%s', $importProvider); - $className = config($key); - if (null === $className || !class_exists($className)) { - // @codeCoverageIgnoreStart - $message = sprintf('Cannot find import routine class for job of type "%s".', $importProvider); - Log::error($message); - - return response()->json( - ['status' => 'NOK', 'message' => $message] - ); - // @codeCoverageIgnoreEnd - } - - /** @var RoutineInterface $routine */ - $routine = app($className); - $routine->setImportJob($importJob); - - Log::debug(sprintf('Created class of type %s', $className)); - - try { - Log::debug(sprintf('Try to call %s:run()', $className)); - $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->repository->setStatus($importJob, 'error'); - - return response()->json(['status' => 'NOK', 'message' => $message]); - } - - // expect nothing from routine, just return OK to user. - Log::info('Now finished with JobStatusController::start'); - - return response()->json(['status' => 'OK', 'message' => 'stage_finished']); - } - - /** - * Store does three things: - * - * - Store the transactions. - * - Add them to a tag. - * - * @param ImportJob $importJob - * - * @return JsonResponse - */ - public function store(ImportJob $importJob): JsonResponse - { - Log::info('Now in JobStatusController::store'); - // catch impossible status: - $allowed = ['provider_finished', 'storing_data']; - if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { - Log::error(sprintf('Job is not ready. Status should be in array, but is %s', $importJob->status), $allowed); - - return response()->json( - ['status' => 'NOK', 'message' => sprintf('JobStatusController::start expects status "provider_finished" instead of "%s".', $importJob->status)] - ); - } - - // set job to be storing data: - $this->repository->setStatus($importJob, 'storing_data'); - - try { - $this->storeTransactions($importJob); - } catch (FireflyException $e) { - $message = 'The import storage routine crashed: ' . $e->getMessage(); - Log::error($message); - Log::error($e->getTraceAsString()); - - // set job errored out: - $this->repository->setStatus($importJob, 'error'); - - return response()->json(['status' => 'NOK', 'message' => $message]); - } - // set storage to be finished: - $this->repository->setStatus($importJob, 'storage_finished'); - - Log::info('Now finished with JobStatusController::start'); - - // expect nothing from routine, just return OK to user. - return response()->json(['status' => 'OK', 'message' => 'storage_finished']); - } -} diff --git a/app/Http/Controllers/Import/PrerequisitesController.php b/app/Http/Controllers/Import/PrerequisitesController.php deleted file mode 100644 index e2f361c5ba..0000000000 --- a/app/Http/Controllers/Import/PrerequisitesController.php +++ /dev/null @@ -1,177 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Http\Controllers\Import; - -use FireflyIII\Http\Controllers\Controller; -use FireflyIII\Import\Prerequisites\PrerequisitesInterface; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\User; -use Illuminate\Contracts\View\Factory; -use Illuminate\Http\RedirectResponse; -use Illuminate\Http\Request; -use Illuminate\Routing\Redirector; -use Illuminate\View\View; -use Log; - -/** - * Class PrerequisitesController - * - * @deprecated - * @codeCoverageIgnore - */ -class PrerequisitesController extends Controller -{ - - /** @var ImportJobRepositoryInterface The import job repository */ - private $repository; - - /** - * PrerequisitesController constructor. - */ - public function __construct() - { - parent::__construct(); - - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-archive'); - app('view')->share('title', (string) trans('firefly.import_index_title')); - app('view')->share('subTitleIcon', 'fa-check'); - - $this->repository = app(ImportJobRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * This method will process and store import provider global prerequisites - * such as API keys. - * - * @param string $importProvider - * @param ImportJob $importJob - * - * @return Factory|RedirectResponse|Redirector|View - */ - public function index(string $importProvider, ImportJob $importJob = null) - { - // catch impossible status: - $allowed = ['new']; - if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { - Log::error(sprintf('Job has state "%s" but this Prerequisites::index() only accepts %s', $importJob->status, json_encode($allowed))); - session()->flash('error', (string) trans('import.bad_job_status', ['status' => e($importJob->status)])); - - return redirect(route('import.index')); - } - - app('view')->share('subTitle', (string) trans('import.prerequisites_breadcrumb_' . $importProvider)); - $class = (string) config(sprintf('import.prerequisites.%s', $importProvider)); - /** @var User $user */ - $user = auth()->user(); - /** @var PrerequisitesInterface $object */ - $object = app($class); - $object->setUser($user); - - if (null !== $importJob && $object->isComplete()) { - // update job: - $this->repository->setStatus($importJob, 'has_prereq'); - - // redirect to job config: - return redirect(route('import.job.configuration.index', [$importJob->key])); - } - - - $view = $object->getView(); - $parameters = ['title' => (string) trans('firefly.import_index_title'), 'mainTitleIcon' => 'fa-archive', 'importJob' => $importJob]; - $parameters = array_merge($object->getViewParameters(), $parameters); - - return view($view, $parameters); - } - - /** - * This method processes the prerequisites the user has entered in the previous step. - * - * Whatever storePrerequisites does, it should make sure that the system is ready to continue immediately. So - * no extra calls or stuff, except maybe to open a session - * - * @param Request $request - * @param string $importProvider - * @param ImportJob $importJob - * - * @return RedirectResponse|Redirector - * @see PrerequisitesInterface::storePrerequisites - * - */ - public function post(Request $request, string $importProvider, ImportJob $importJob = null) - { - Log::debug(sprintf('Now in postPrerequisites for %s', $importProvider)); - - // catch impossible status: - $allowed = ['new']; - if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { - Log::error(sprintf('Job has state "%s" but this Prerequisites::post() only accepts %s', $importJob->status, json_encode($allowed))); - session()->flash('error', (string) trans('import.bad_job_status', ['status' => e($importJob->status)])); - - return redirect(route('import.index')); - } - - - $class = (string) config(sprintf('import.prerequisites.%s', $importProvider)); - /** @var User $user */ - $user = auth()->user(); - /** @var PrerequisitesInterface $object */ - $object = app($class); - $object->setUser($user); - Log::debug('Going to store entered prerequisites.'); - // store post data - $data = $request->all(); - $result = $object->storePrerequisites($data); - Log::debug(sprintf('Result of storePrerequisites has message count: %d', $result->count())); - - if ($result->count() > 0) { - $request->session()->flash('error', e($result->first())); - - // redirect back to job, if has job: - return redirect(route('import.prerequisites.index', [$importProvider, $importJob->key ?? '']))->withInput(); - } - - // session flash! - $request->session()->flash('success', (string) trans('import.prerequisites_saved_for_' . $importProvider)); - - // if has job, redirect to global config for provider - // if no job, back to index! - if (null === $importJob) { - return redirect(route('import.index')); - } - - // update job: - $this->repository->setStatus($importJob, 'has_prereq'); - - // redirect to job config: - return redirect(route('import.job.configuration.index', [$importJob->key])); - - - } -} diff --git a/app/Import/Converter/Amount.php b/app/Import/Converter/Amount.php deleted file mode 100644 index ee7630764d..0000000000 --- a/app/Import/Converter/Amount.php +++ /dev/null @@ -1,234 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Converter; - -use Log; - -/** - * Class Amount. - * - * @deprecated - * @codeCoverageIgnore - */ -class Amount implements ConverterInterface -{ - /** - * Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. - * - Jamie Zawinski. - * - * @param $value - * - * @return string - */ - public function convert($value): string - { - if (null === $value) { - return '0'; - } - Log::debug(sprintf('Start with amount "%s"', $value)); - $original = $value; - $value = $this->stripAmount((string) $value); - $decimal = null; - - if ($this->decimalIsDot($value)) { - $decimal = '.'; - Log::debug(sprintf('Decimal character in "%s" seems to be a dot.', $value)); - } - - if ($this->decimalIsComma($value)) { - $decimal = ','; - Log::debug(sprintf('Decimal character in "%s" seems to be a comma.', $value)); - } - - // decimal character is null? find out if "0.1" or ".1" or "0,1" or ",1" - if ($this->alternativeDecimalSign($value)) { - $decimal = $this->getAlternativeDecimalSign($value); - } - - // decimal character still null? Search from the left for '.',',' or ' '. - if (null === $decimal) { - $decimal = $this->findFromLeft($value); - } - - // if decimal is dot, replace all comma's and spaces with nothing - if (null !== $decimal) { - $value = $this->replaceDecimal($decimal, $value); - Log::debug(sprintf('Converted amount from "%s" to "%s".', $original, $value)); - } - - if (null === $decimal) { - // replace all: - $search = ['.', ' ', ',']; - $value = str_replace($search, '', $value); - Log::debug(sprintf('No decimal character found. Converted amount from "%s" to "%s".', $original, $value)); - } - if (strpos($value, '.') === 0) { - $value = '0' . $value; - } - - if (is_numeric($value)) { - Log::debug(sprintf('Final NUMERIC value is: "%s"', $value)); - - return $value; - } - // @codeCoverageIgnoreStart - Log::debug(sprintf('Final value is: "%s"', $value)); - $formatted = sprintf('%01.12f', $value); - Log::debug(sprintf('Is formatted to : "%s"', $formatted)); - - return $formatted; - // @codeCoverageIgnoreEnd - } - - /** - * Check if the value has a dot or comma on an alternative place, - * catching strings like ",1" or ".5". - * - * @param string $value - * - * @return bool - */ - private function alternativeDecimalSign(string $value): bool - { - $length = strlen($value); - $altPosition = $length - 2; - - return $length > 1 && ('.' === $value[$altPosition] || ',' === $value[$altPosition]); - } - - /** - * Helper function to see if the decimal separator is a comma. - * - * @param string $value - * - * @return bool - */ - private function decimalIsComma(string $value): bool - { - $length = strlen($value); - $decimalPosition = $length - 3; - - return $length > 2 && ',' === $value[$decimalPosition]; - } - - /** - * Helper function to see if the decimal separator is a dot. - * - * @param string $value - * - * @return bool - */ - private function decimalIsDot(string $value): bool - { - $length = strlen($value); - $decimalPosition = $length - 3; - - return ($length > 2 && '.' === $value[$decimalPosition]) || ($length > 2 && strpos($value, '.') > $decimalPosition); - } - - /** - * Search from the left for decimal sign. - * - * @param string $value - * - * @return string - */ - private function findFromLeft(string $value): ?string - { - $decimal = null; - Log::debug('Decimal is still NULL, probably number with >2 decimals. Search for a dot.'); - $res = strrpos($value, '.'); - if (!(false === $res)) { - // blandly assume this is the one. - Log::debug(sprintf('Searched from the left for "." in amount "%s", assume this is the decimal sign.', $value)); - $decimal = '.'; - } - - return $decimal; - } - - /** - * Returns the alternative decimal point used, such as a dot or a comma, - * from strings like ",1" or "0.5". - * - * @param string $value - * - * @return string - */ - private function getAlternativeDecimalSign(string $value): string - { - $length = strlen($value); - $altPosition = $length - 2; - - return $value[$altPosition]; - - } - - /** - * Replaces other characters like thousand separators with nothing to make the decimal separator the only special - * character in the string. - * - * @param string $decimal - * @param string $value - * - * @return string - */ - private function replaceDecimal(string $decimal, string $value): string - { - $search = [',', ' ']; // default when decimal sign is a dot. - if (',' === $decimal) { - $search = ['.', ' ']; - } - $value = str_replace($search, '', $value); - - /** @noinspection CascadeStringReplacementInspection */ - $value = str_replace(',', '.', $value); - - return $value; - } - - /** - * Strip amount from weird characters. - * - * @param string $value - * - * @return string - */ - private function stripAmount(string $value): string - { - if (0 === strpos($value, '--')) { - $value = substr($value, 2); - } - // have to strip the € because apparantly the Postbank (DE) thinks "1.000,00 €" is a normal way to format a number. - $value = trim((string) str_replace(['€'], '', $value)); - $str = preg_replace('/[^\-\(\)\.\,0-9 ]/', '', $value); - $len = strlen($str); - if ('(' === $str[0] && ')' === $str[$len - 1]) { - $str = '-' . substr($str, 1, $len - 2); - } - - Log::debug(sprintf('Stripped "%s" away to "%s"', $value, $str)); - - return $str; - } -} diff --git a/app/Import/Converter/AmountCredit.php b/app/Import/Converter/AmountCredit.php deleted file mode 100644 index 3bfb2e6021..0000000000 --- a/app/Import/Converter/AmountCredit.php +++ /dev/null @@ -1,49 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Converter; - -/** - * Class AmountCredit - * - * @deprecated - * @codeCoverageIgnore - */ -class AmountCredit implements ConverterInterface -{ - /** - * Convert an amount, always return positive. - * - * @param $value - * - * @return string - */ - public function convert($value): string - { - /** @var ConverterInterface $converter */ - $converter = app(Amount::class); - $result = $converter->convert($value); - $result = app('steam')->positive($result); - - return $result; - } -} diff --git a/app/Import/Converter/AmountDebit.php b/app/Import/Converter/AmountDebit.php deleted file mode 100644 index 4b96a34662..0000000000 --- a/app/Import/Converter/AmountDebit.php +++ /dev/null @@ -1,50 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Converter; - -/** - * Class AmountDebit - * - * @deprecated - * @codeCoverageIgnore - */ -class AmountDebit implements ConverterInterface -{ - /** - * Convert amount, always return positive. - * - * @param $value - * - * @return string - */ - public function convert($value): string - { - /** @var ConverterInterface $converter */ - $converter = app(Amount::class); - $result = $converter->convert($value); - $result = app('steam')->positive($result); - $result = bcmul($result, '-1'); - - return $result; - } -} diff --git a/app/Import/Converter/AmountNegated.php b/app/Import/Converter/AmountNegated.php deleted file mode 100644 index 3bb2483e19..0000000000 --- a/app/Import/Converter/AmountNegated.php +++ /dev/null @@ -1,49 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Converter; - -/** - * Class AmountNegated - * - * @deprecated - * @codeCoverageIgnore - */ -class AmountNegated implements ConverterInterface -{ - /** - * Negate amount. - * - * @param $value - * - * @return string - */ - public function convert($value): string - { - /** @var ConverterInterface $converter */ - $converter = app(Amount::class); - $result = $converter->convert($value); - $result = bcmul($result, '-1'); - - return $result; - } -} diff --git a/app/Import/Converter/BankDebitCredit.php b/app/Import/Converter/BankDebitCredit.php deleted file mode 100644 index dcaa1d08f2..0000000000 --- a/app/Import/Converter/BankDebitCredit.php +++ /dev/null @@ -1,64 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\Converter; - - -use Log; - -/** - * - * Class BankDebitCredit - * - * @deprecated - * @codeCoverageIgnore - */ -class BankDebitCredit implements ConverterInterface -{ - - /** - * Convert a value. - * - * @param $value - * - * @return int - */ - public function convert($value): int - { - Log::debug('Going to convert ', ['value' => $value]); - $negative = [ - 'D', // Old style Rabobank (NL). Short for "Debit" - 'A', // New style Rabobank (NL). Short for "Af" - 'DR', // https://old.reddit.com/r/FireflyIII/comments/bn2edf/generic_debitcredit_indicator/ - 'Af', // ING (NL). - 'Debet', // Triodos (NL) - 'S', // "Soll", German term for debit - 'Debit', // Community America (US) - ]; - if (in_array(trim($value), $negative, true)) { - return -1; - } - - return 1; - } -} diff --git a/app/Import/Converter/ConverterInterface.php b/app/Import/Converter/ConverterInterface.php deleted file mode 100644 index bdf5176eb1..0000000000 --- a/app/Import/Converter/ConverterInterface.php +++ /dev/null @@ -1,42 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Converter; - -/** - * Interface ConverterInterface. - * - * @deprecated - * @codeCoverageIgnore - */ -interface ConverterInterface -{ - /** - * Convert a value. - * - * @param $value - * - * @return mixed - * - */ - public function convert($value); -} diff --git a/app/Import/JobConfiguration/BunqJobConfiguration.php b/app/Import/JobConfiguration/BunqJobConfiguration.php deleted file mode 100644 index c4c5f3644b..0000000000 --- a/app/Import/JobConfiguration/BunqJobConfiguration.php +++ /dev/null @@ -1,136 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\JobConfiguration; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\JobConfiguration\Bunq\BunqJobConfigurationInterface; -use FireflyIII\Support\Import\JobConfiguration\Bunq\ChooseAccountsHandler; -use FireflyIII\Support\Import\JobConfiguration\Bunq\NewBunqJobHandler; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class BunqJobConfiguration - * - * @deprecated - * @codeCoverageIgnore - */ -class BunqJobConfiguration implements JobConfigurationInterface -{ - /** @var BunqJobConfigurationInterface Bunq job interface */ - private $handler; - /** @var ImportJob The import job */ - private $importJob; - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * Returns true when the initial configuration for this job is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - return $this->handler->configurationComplete(); - } - - /** - * Store any data from the $data array into the job. Anything in the message bag will be flashed - * as an error to the user, regardless of its content. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - return $this->handler->configureJob($data); - } - - /** - * Return the data required for the next step in the job configuration. - * - * @return array - */ - public function getNextData(): array - { - return $this->handler->getNextData(); - } - - /** - * Returns the view of the next step in the job configuration. - * - * @return string - */ - public function getNextView(): string - { - return $this->handler->getNextView(); - } - - /** - * Set import job. - * - * @param ImportJob $importJob - * - * @throws FireflyException - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->handler = $this->getHandler(); - } - - /** - * Get correct handler. - * - * @throws FireflyException - * @return BunqJobConfigurationInterface - */ - private function getHandler(): BunqJobConfigurationInterface - { - Log::debug(sprintf('Now in BunqJobConfiguration::getHandler() with stage "%s"', $this->importJob->stage)); - $handler = null; - switch ($this->importJob->stage) { - case 'new': - $handler = app(NewBunqJobHandler::class); - $handler->setImportJob($this->importJob); - break; - case 'choose-accounts': - /** @var ChooseAccountsHandler $handler */ - $handler = app(ChooseAccountsHandler::class); - $handler->setImportJob($this->importJob); - break; - default: - // @codeCoverageIgnoreStart - throw new FireflyException(sprintf('Firefly III cannot create a configuration handler for stage "%s"', $this->importJob->stage)); - // @codeCoverageIgnoreEnd - } - - return $handler; - } -} diff --git a/app/Import/JobConfiguration/FakeJobConfiguration.php b/app/Import/JobConfiguration/FakeJobConfiguration.php deleted file mode 100644 index 132de1ef00..0000000000 --- a/app/Import/JobConfiguration/FakeJobConfiguration.php +++ /dev/null @@ -1,169 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\JobConfiguration; - -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Support\MessageBag; - -/** - * Class FakeJobConfiguration - * - * @deprecated - * @codeCoverageIgnore - */ -class FakeJobConfiguration implements JobConfigurationInterface -{ - /** @var ImportJob The import job */ - private $importJob; - - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * Returns true when the initial configuration for this job is complete. - * configuration array of job must have two values: - * 'artist' must be 'david bowie', case insensitive - * 'song' must be 'golden years', case insensitive. - * if stage is not "new", then album must be 'station to station' - * - * @return bool - * - */ - public function configurationComplete(): bool - { - $config = $this->importJob->configuration; - if ('new' === $this->importJob->stage) { - return - isset($config['artist'], $config['song'], $config['apply-rules']) - && 'david bowie' === strtolower($config['artist']) - && 'golden years' === strtolower($config['song']); - } - - return isset($config['album']) && 'station to station' === strtolower($config['album']); - - - } - - /** - * Store any data from the $data array into the job. - * - * @param array $data - * - * @return MessageBag - * - */ - public function configureJob(array $data): MessageBag - { - $artist = strtolower($data['artist'] ?? ''); - $song = strtolower($data['song'] ?? ''); - $album = strtolower($data['album'] ?? ''); - $applyRules = isset($data['apply_rules']) ? 1 === (int) $data['apply_rules'] : null; - $configuration = $this->importJob->configuration; - if ('david bowie' === $artist) { - // store artist - $configuration['artist'] = $artist; - } - - if ('golden years' === $song) { - // store song - $configuration['song'] = $song; - } - - if ('station to station' === $album) { - // store album - $configuration['album'] = $album; - } - if (null !== $applyRules) { - $configuration['apply-rules'] = $applyRules; - } - - $this->repository->setConfiguration($this->importJob, $configuration); - $messages = new MessageBag(); - - if (3 !== count($configuration)) { - $messages->add('some_key', 'Ignore this error: ' . count($configuration)); - } - - return $messages; - } - - /** - * Return the data required for the next step in the job configuration. - * - * @codeCoverageIgnore - * @return array - */ - public function getNextData(): array - { - return [ - 'rulesOptions' => [ - 1 => (string) trans('firefly.yes'), - 0 => (string) trans('firefly.no'), - ], - ]; - } - - /** - * Returns the view of the next step in the job configuration. - * - * @return string - * - */ - public function getNextView(): string - { - // first configure artist: - $config = $this->importJob->configuration; - $artist = $config['artist'] ?? ''; - $song = $config['song'] ?? ''; - $album = $config['album'] ?? ''; - $applyRules = $config['apply-rules'] ?? null; - if (null === $applyRules) { - return 'import.fake.apply-rules'; - } - if ('david bowie' !== strtolower($artist)) { - return 'import.fake.enter-artist'; - } - if ('golden years' !== strtolower($song)) { - return 'import.fake.enter-song'; - } - if ('new' !== $this->importJob->stage && 'station to station' !== strtolower($album)) { - return 'import.fake.enter-album'; - } - - return 'impossible-view'; // @codeCoverageIgnore - } - - /** - * Set import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Import/JobConfiguration/FileJobConfiguration.php b/app/Import/JobConfiguration/FileJobConfiguration.php deleted file mode 100644 index 76cf4e2ec6..0000000000 --- a/app/Import/JobConfiguration/FileJobConfiguration.php +++ /dev/null @@ -1,161 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\JobConfiguration; - - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\JobConfiguration\File\ConfigureMappingHandler; -use FireflyIII\Support\Import\JobConfiguration\File\ConfigureRolesHandler; -use FireflyIII\Support\Import\JobConfiguration\File\ConfigureUploadHandler; -use FireflyIII\Support\Import\JobConfiguration\File\FileConfigurationInterface; -use FireflyIII\Support\Import\JobConfiguration\File\NewFileJobHandler; -use Illuminate\Support\MessageBag; - -/** - * Class FileJobConfiguration - * - * @deprecated - * @codeCoverageIgnore - */ -class FileJobConfiguration implements JobConfigurationInterface -{ - /** @var ImportJob The import job */ - private $importJob; - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * Returns true when the initial configuration for this job is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - return 'ready_to_run' === $this->importJob->stage; - } - - /** - * Store any data from the $data array into the job. Anything in the message bag will be flashed - * as an error to the user, regardless of its content. - * - * @param array $data - * - * @throws FireflyException - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - $configurator = $this->getConfigurationObject(); - $configurator->setImportJob($this->importJob); - - return $configurator->configureJob($data); - } - - /** - * Return the data required for the next step in the job configuration. - * - * @throws FireflyException - * @return array - */ - public function getNextData(): array - { - $configurator = $this->getConfigurationObject(); - $configurator->setImportJob($this->importJob); - - return $configurator->getNextData(); - } - - /** - * Returns the view of the next step in the job configuration. - * - * @throws FireflyException - * @return string - * - */ - public function getNextView(): string - { - switch ($this->importJob->stage) { - case 'new': - return 'import.file.new'; - case 'configure-upload': - return 'import.file.configure-upload'; - case 'roles': - return 'import.file.roles'; - case 'map': - return 'import.file.map'; - default: - // @codeCoverageIgnoreStart - throw new FireflyException( - sprintf('FileJobConfiguration::getNextView() cannot handle stage "%s"', $this->importJob->stage) - ); - // @codeCoverageIgnoreEnd - } - } - - /** - * Set import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } - - /** - * Get the configuration handler for this specific stage. - * - * @throws FireflyException - * - * @return FileConfigurationInterface - */ - private function getConfigurationObject(): FileConfigurationInterface - { - $class = 'DoNotExist'; - switch ($this->importJob->stage) { - case 'new': // has nothing, no file upload or anything. - $class = NewFileJobHandler::class; - break; - case 'configure-upload': - $class = ConfigureUploadHandler::class; - break; - case 'roles': - $class = ConfigureRolesHandler::class; - break; - case 'map': - $class = ConfigureMappingHandler::class; - break; - } - if (!class_exists($class)) { - throw new FireflyException(sprintf('Class %s does not exist in getConfigurationClass().', $class)); // @codeCoverageIgnore - } - - return app($class); - } -} diff --git a/app/Import/JobConfiguration/FinTSConfigurationSteps.php b/app/Import/JobConfiguration/FinTSConfigurationSteps.php deleted file mode 100644 index 4a55c548b3..0000000000 --- a/app/Import/JobConfiguration/FinTSConfigurationSteps.php +++ /dev/null @@ -1,38 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\JobConfiguration; - -/** - * - * Class FinTSConfigurationSteps - * - * @deprecated - * @codeCoverageIgnore - */ -abstract class FinTSConfigurationSteps -{ - public const NEW = 'new'; - public const CHOOSE_ACCOUNT = 'choose_account'; - public const GO_FOR_IMPORT = 'go-for-import'; -} diff --git a/app/Import/JobConfiguration/FinTSJobConfiguration.php b/app/Import/JobConfiguration/FinTSJobConfiguration.php deleted file mode 100644 index f7eb84bd95..0000000000 --- a/app/Import/JobConfiguration/FinTSJobConfiguration.php +++ /dev/null @@ -1,137 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\JobConfiguration; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Support\Import\JobConfiguration\FinTS\ChooseAccountHandler; -use FireflyIII\Support\Import\JobConfiguration\FinTS\FinTSConfigurationInterface; -use FireflyIII\Support\Import\JobConfiguration\FinTS\NewFinTSJobHandler; -use Illuminate\Support\MessageBag; - -/** - * - * Class FinTSJobConfiguration - * - * @deprecated - * @codeCoverageIgnore - */ -class FinTSJobConfiguration implements JobConfigurationInterface -{ - /** @var ImportJob */ - private $importJob; - - /** - * Returns true when the initial configuration for this job is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - return $this->importJob->stage === FinTSConfigurationSteps::GO_FOR_IMPORT; - } - - /** - * Store any data from the $data array into the job. Anything in the message bag will be flashed - * as an error to the user, regardless of its content. - * - * @param array $data - * - * @throws FireflyException - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - return $this->getConfigurationObject()->configureJob($data); - } - - /** - * Return the data required for the next step in the job configuration. - * - * @throws FireflyException - * @return array - */ - public function getNextData(): array - { - return $this->getConfigurationObject()->getNextData(); - } - - /** - * Returns the view of the next step in the job configuration. - * - * @throws FireflyException - * @return string - */ - public function getNextView(): string - { - switch ($this->importJob->stage) { - case FinTSConfigurationSteps::NEW: - case FinTSConfigurationSteps::CHOOSE_ACCOUNT: - return 'import.fints.' . $this->importJob->stage; - break; - default: - // @codeCoverageIgnoreStart - throw new FireflyException( - sprintf('FinTSJobConfiguration::getNextView() cannot handle stage "%s"', $this->importJob->stage) - ); - // @codeCoverageIgnoreEnd - } - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - } - - /** - * Get the configuration handler for this specific stage. - * - * @throws FireflyException - * @return FinTSConfigurationInterface - */ - private function getConfigurationObject(): FinTSConfigurationInterface - { - $class = 'DoNotExist'; - switch ($this->importJob->stage) { - case FinTSConfigurationSteps::NEW: - $class = NewFinTSJobHandler::class; - break; - case FinTSConfigurationSteps::CHOOSE_ACCOUNT: - $class = ChooseAccountHandler::class; - break; - } - if (!class_exists($class)) { - throw new FireflyException(sprintf('Class %s does not exist in getConfigurationClass().', $class)); // @codeCoverageIgnore - } - - $configurator = app($class); - $configurator->setImportJob($this->importJob); - - return $configurator; - } - - -} diff --git a/app/Import/JobConfiguration/JobConfigurationInterface.php b/app/Import/JobConfiguration/JobConfigurationInterface.php deleted file mode 100644 index 8d3343bb89..0000000000 --- a/app/Import/JobConfiguration/JobConfigurationInterface.php +++ /dev/null @@ -1,73 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\JobConfiguration; - -use FireflyIII\Models\ImportJob; -use Illuminate\Support\MessageBag; - -/** - * Interface JobConfigurationInterface. - * - * @deprecated - * @codeCoverageIgnore - */ -interface JobConfigurationInterface -{ - /** - * Returns true when the initial configuration for this job is complete. - * - * @return bool - */ - public function configurationComplete(): bool; - - /** - * Store any data from the $data array into the job. Anything in the message bag will be flashed - * as an error to the user, regardless of its content. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag; - - /** - * Return the data required for the next step in the job configuration. - * - * @return array - */ - public function getNextData(): array; - - /** - * Returns the view of the next step in the job configuration. - * - * @return string - */ - public function getNextView(): string; - - /** - * Set import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void; -} diff --git a/app/Import/JobConfiguration/SpectreJobConfiguration.php b/app/Import/JobConfiguration/SpectreJobConfiguration.php deleted file mode 100644 index 1bf3f12bdc..0000000000 --- a/app/Import/JobConfiguration/SpectreJobConfiguration.php +++ /dev/null @@ -1,156 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\JobConfiguration; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\JobConfiguration\Spectre\AuthenticatedHandler; -use FireflyIII\Support\Import\JobConfiguration\Spectre\ChooseAccountsHandler; -use FireflyIII\Support\Import\JobConfiguration\Spectre\ChooseLoginHandler; -use FireflyIII\Support\Import\JobConfiguration\Spectre\DoAuthenticateHandler; -use FireflyIII\Support\Import\JobConfiguration\Spectre\NewSpectreJobHandler; -use FireflyIII\Support\Import\JobConfiguration\Spectre\SpectreJobConfigurationInterface; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class SpectreJobConfiguration - * - * @deprecated - * @codeCoverageIgnore - */ -class SpectreJobConfiguration implements JobConfigurationInterface -{ - /** @var SpectreJobConfigurationInterface The job handler. */ - private $handler; - /** @var ImportJob The import job */ - private $importJob; - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * Returns true when the initial configuration for this job is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - return $this->handler->configurationComplete(); - } - - /** - * Store any data from the $data array into the job. Anything in the message bag will be flashed - * as an error to the user, regardless of its content. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - return $this->handler->configureJob($data); - } - - /** - * Return the data required for the next step in the job configuration. - * - * @return array - */ - public function getNextData(): array - { - return $this->handler->getNextData(); - } - - /** - * Returns the view of the next step in the job configuration. - * - * @return string - */ - public function getNextView(): string - { - return $this->handler->getNextView(); - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - * - * @throws FireflyException - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->handler = $this->getHandler(); - } - - /** - * Get correct handler. - * - * @throws FireflyException - * - * @return SpectreJobConfigurationInterface - */ - private function getHandler(): SpectreJobConfigurationInterface - { - Log::debug(sprintf('Now in SpectreJobConfiguration::getHandler() with stage "%s"', $this->importJob->stage)); - $handler = null; - switch ($this->importJob->stage) { - case 'new': - /** @var NewSpectreJobHandler $handler */ - $handler = app(NewSpectreJobHandler::class); - $handler->setImportJob($this->importJob); - break; - case 'do-authenticate': - /** @var DoAuthenticateHandler $handler */ - $handler = app(DoAuthenticateHandler::class); - $handler->setImportJob($this->importJob); - break; - case 'choose-login': - /** @var ChooseLoginHandler $handler */ - $handler = app(ChooseLoginHandler::class); - $handler->setImportJob($this->importJob); - break; - case 'authenticated': - /** @var AuthenticatedHandler $handler */ - $handler = app(AuthenticatedHandler::class); - $handler->setImportJob($this->importJob); - break; - case 'choose-accounts': - /** @var ChooseAccountsHandler $handler */ - $handler = app(ChooseAccountsHandler::class); - $handler->setImportJob($this->importJob); - break; - default: - // @codeCoverageIgnoreStart - throw new FireflyException(sprintf('Firefly III cannot create a configuration handler for stage "%s"', $this->importJob->stage)); - // @codeCoverageIgnoreEnd - } - - return $handler; - } -} diff --git a/app/Import/JobConfiguration/YnabJobConfiguration.php b/app/Import/JobConfiguration/YnabJobConfiguration.php deleted file mode 100644 index 60ad0a52a9..0000000000 --- a/app/Import/JobConfiguration/YnabJobConfiguration.php +++ /dev/null @@ -1,143 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\JobConfiguration; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\JobConfiguration\Ynab\NewYnabJobHandler; -use FireflyIII\Support\Import\JobConfiguration\Ynab\SelectAccountsHandler; -use FireflyIII\Support\Import\JobConfiguration\Ynab\SelectBudgetHandler; -use FireflyIII\Support\Import\JobConfiguration\Ynab\YnabJobConfigurationInterface; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class YnabJobConfiguration - * - * @deprecated - * @codeCoverageIgnore - */ -class YnabJobConfiguration implements JobConfigurationInterface -{ - /** @var YnabJobConfigurationInterface The job handler. */ - private $handler; - /** @var ImportJob The import job */ - private $importJob; - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * Returns true when the initial configuration for this job is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - return $this->handler->configurationComplete(); - } - - /** - * Store any data from the $data array into the job. Anything in the message bag will be flashed - * as an error to the user, regardless of its content. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - return $this->handler->configureJob($data); - } - - /** - * Return the data required for the next step in the job configuration. - * - * @return array - */ - public function getNextData(): array - { - return $this->handler->getNextData(); - } - - /** - * Returns the view of the next step in the job configuration. - * - * @return string - */ - public function getNextView(): string - { - return $this->handler->getNextView(); - } - - /** - * Set import job. - * - * @param ImportJob $importJob - * - * @throws FireflyException - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->handler = $this->getHandler(); - } - - /** - * Get correct handler. - * - * @throws FireflyException - * - * @return YnabJobConfigurationInterface - */ - private function getHandler(): YnabJobConfigurationInterface - { - Log::debug(sprintf('Now in YnabJobConfiguration::getHandler() with stage "%s"', $this->importJob->stage)); - $handler = null; - switch ($this->importJob->stage) { - case 'new': - /** @var NewYnabJobHandler $handler */ - $handler = app(NewYnabJobHandler::class); - $handler->setImportJob($this->importJob); - break; - case 'select_budgets': - /** @var SelectBudgetHandler $handler */ - $handler = app(SelectBudgetHandler::class); - $handler->setImportJob($this->importJob); - break; - case 'select_accounts': - $handler = app(SelectAccountsHandler::class); - $handler->setImportJob($this->importJob); - break; - default: - // @codeCoverageIgnoreStart - throw new FireflyException(sprintf('Firefly III cannot create a YNAB configuration handler for stage "%s"', $this->importJob->stage)); - // @codeCoverageIgnoreEnd - } - - return $handler; - } -} diff --git a/app/Import/Mapper/AssetAccountIbans.php b/app/Import/Mapper/AssetAccountIbans.php deleted file mode 100644 index b754f7d75a..0000000000 --- a/app/Import/Mapper/AssetAccountIbans.php +++ /dev/null @@ -1,85 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; - -/** - * Class AssetAccounts. - * - * @deprecated - * @codeCoverageIgnore - */ -class AssetAccountIbans implements MapperInterface -{ - /** - * Get map of asset accounts. - * - * @return array - */ - public function getMap(): array - { - /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $set = $accountRepository->getAccountsByType( - [AccountType::DEFAULT, AccountType::ASSET, - AccountType::LOAN, AccountType::DEBT, - AccountType::CREDITCARD, AccountType::MORTGAGE, - ] - ); - $topList = []; - $list = []; - - /** @var Account $account */ - foreach ($set as $account) { - $iban = $account->iban ?? ''; - $accountId = (int) $account->id; - if ('' !== $iban) { - $name = $account->iban . ' (' . $account->name . ')'; - - // is a liability? - if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { - $name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')'; - } - - $topList[$accountId] = $name; - } - if ('' === $iban) { - $name = $account->name; - // is a liability? - if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { - $name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')'; - } - $list[$accountId] = $name; - } - } - /** @noinspection AdditionOperationOnArraysInspection */ - $list = $topList + $list; - asort($list); - $list = [0 => (string) trans('import.map_do_not_map')] + $list; - - return $list; - } -} diff --git a/app/Import/Mapper/AssetAccounts.php b/app/Import/Mapper/AssetAccounts.php deleted file mode 100644 index 0d303977c2..0000000000 --- a/app/Import/Mapper/AssetAccounts.php +++ /dev/null @@ -1,72 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; - -/** - * Class AssetAccounts. - * - * @deprecated - * @codeCoverageIgnore - */ -class AssetAccounts implements MapperInterface -{ - /** - * Get map of asset accounts. - * - * @return array - */ - public function getMap(): array - { - /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $set = $accountRepository->getAccountsByType( - [AccountType::DEFAULT, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE,] - ); - $list = []; - - /** @var Account $account */ - foreach ($set as $account) { - $accountId = (int) $account->id; - $name = $account->name; - $iban = $account->iban ?? ''; - if ('' !== $iban) { - $name .= ' (' . $iban . ')'; - } - - // is a liability? - if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { - $name = trans('import.import_liability_select') . ': ' . $name; - } - - $list[$accountId] = $name; - } - asort($list); - $list = [0 => (string) trans('import.map_do_not_map')] + $list; - - return $list; - } -} diff --git a/app/Import/Mapper/Bills.php b/app/Import/Mapper/Bills.php deleted file mode 100644 index 5ba45bd3da..0000000000 --- a/app/Import/Mapper/Bills.php +++ /dev/null @@ -1,58 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -use FireflyIII\Models\Bill; -use FireflyIII\Repositories\Bill\BillRepositoryInterface; - -/** - * Class Bills. - * - * @deprecated - * @codeCoverageIgnore - */ -class Bills implements MapperInterface -{ - /** - * Get map of bills. - * - * @return array - */ - public function getMap(): array - { - /** @var BillRepositoryInterface $repository */ - $repository = app(BillRepositoryInterface::class); - $result = $repository->getBills(); - $list = []; - - /** @var Bill $bill */ - foreach ($result as $bill) { - $billId = (int) $bill->id; - $list[$billId] = $bill->name; - } - asort($list); - $list = [0 => (string) trans('import.map_do_not_map')] + $list; - - return $list; - } -} diff --git a/app/Import/Mapper/Budgets.php b/app/Import/Mapper/Budgets.php deleted file mode 100644 index afe68219d6..0000000000 --- a/app/Import/Mapper/Budgets.php +++ /dev/null @@ -1,58 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -use FireflyIII\Models\Budget; -use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; - -/** - * Class Budgets. - * - * @deprecated - * @codeCoverageIgnore - */ -class Budgets implements MapperInterface -{ - /** - * Get map of budgets. - * - * @return array - */ - public function getMap(): array - { - /** @var BudgetRepositoryInterface $repository */ - $repository = app(BudgetRepositoryInterface::class); - $result = $repository->getActiveBudgets(); - $list = []; - - /** @var Budget $budget */ - foreach ($result as $budget) { - $budgetId = (int) $budget->id; - $list[$budgetId] = $budget->name; - } - asort($list); - $list = [0 => (string) trans('import.map_do_not_map')] + $list; - - return $list; - } -} diff --git a/app/Import/Mapper/Categories.php b/app/Import/Mapper/Categories.php deleted file mode 100644 index 2f398d6513..0000000000 --- a/app/Import/Mapper/Categories.php +++ /dev/null @@ -1,58 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -use FireflyIII\Models\Category; -use FireflyIII\Repositories\Category\CategoryRepositoryInterface; - -/** - * Class Categories. - * - * @deprecated - * @codeCoverageIgnore - */ -class Categories implements MapperInterface -{ - /** - * Get map of categories. - * - * @return array - */ - public function getMap(): array - { - /** @var CategoryRepositoryInterface $repository */ - $repository = app(CategoryRepositoryInterface::class); - $result = $repository->getCategories(); - $list = []; - - /** @var Category $category */ - foreach ($result as $category) { - $categoryId = (int) $category->id; - $list[$categoryId] = $category->name; - } - asort($list); - $list = [0 => (string) trans('import.map_do_not_map')] + $list; - - return $list; - } -} diff --git a/app/Import/Mapper/MapperInterface.php b/app/Import/Mapper/MapperInterface.php deleted file mode 100644 index be211d418b..0000000000 --- a/app/Import/Mapper/MapperInterface.php +++ /dev/null @@ -1,39 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -/** - * Interface MapperInterface. - * - * @deprecated - * @codeCoverageIgnore - */ -interface MapperInterface -{ - /** - * Get map of objects. - * - * @return array - */ - public function getMap(): array; -} diff --git a/app/Import/Mapper/OpposingAccountIbans.php b/app/Import/Mapper/OpposingAccountIbans.php deleted file mode 100644 index 117e5db0fd..0000000000 --- a/app/Import/Mapper/OpposingAccountIbans.php +++ /dev/null @@ -1,88 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; - -/** - * Class OpposingAccounts. - * - * @deprecated - * @codeCoverageIgnore - */ -class OpposingAccountIbans implements MapperInterface -{ - /** - * Get map of opposing accounts. - * - * @return array - */ - public function getMap(): array - { - /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $set = $accountRepository->getAccountsByType( - [ - AccountType::DEFAULT, AccountType::ASSET, - AccountType::EXPENSE, AccountType::BENEFICIARY, - AccountType::REVENUE, AccountType::LOAN, AccountType::DEBT, - AccountType::CREDITCARD, AccountType::MORTGAGE, - ] - ); - $topList = []; - $list = []; - - /** @var Account $account */ - foreach ($set as $account) { - $iban = $account->iban ?? ''; - $accountId = (int) $account->id; - if ('' !== $iban) { - $name = $account->iban . ' (' . $account->name . ')'; - - // is a liability? - if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { - $name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')'; - } - - $topList[$accountId] = $name; - - } - if ('' === $iban) { - $name = $account->name; - // is a liability? - if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { - $name = $name . ' (' . strtolower(trans('import.import_liability_select')) . ')'; - } - $list[$accountId] = $name; - } - } - /** @noinspection AdditionOperationOnArraysInspection */ - $list = $topList + $list; - asort($list); - $list = [0 => (string) trans('import.map_do_not_map')] + $list; - - return $list; - } -} diff --git a/app/Import/Mapper/OpposingAccounts.php b/app/Import/Mapper/OpposingAccounts.php deleted file mode 100644 index 99453cadeb..0000000000 --- a/app/Import/Mapper/OpposingAccounts.php +++ /dev/null @@ -1,76 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; - -/** - * Class OpposingAccounts. - * - * @deprecated - * @codeCoverageIgnore - * - */ -class OpposingAccounts implements MapperInterface -{ - /** - * Get map of opposing accounts. - * - * @return array - */ - public function getMap(): array - { - /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $set = $accountRepository->getAccountsByType( - [ - AccountType::DEFAULT, AccountType::ASSET, - AccountType::EXPENSE, AccountType::BENEFICIARY, - AccountType::REVENUE, AccountType::LOAN, AccountType::DEBT, - AccountType::CREDITCARD, AccountType::MORTGAGE, - ] - ); - $list = []; - - /** @var Account $account */ - foreach ($set as $account) { - $accountId = (int) $account->id; - $name = $account->name; - $iban = $account->iban ?? ''; - if ('' !== $iban) { - $name .= ' (' . $iban . ')'; - } - // is a liability? - if (in_array($account->accountType->type, [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], true)) { - $name = trans('import.import_liability_select') . ': ' . $name; - } - $list[$accountId] = $name; - } - asort($list); - $list = [0 => (string) trans('import.map_do_not_map')] + $list; - - return $list; - } -} diff --git a/app/Import/Mapper/Tags.php b/app/Import/Mapper/Tags.php deleted file mode 100644 index ea02687994..0000000000 --- a/app/Import/Mapper/Tags.php +++ /dev/null @@ -1,58 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -use FireflyIII\Models\Tag; -use FireflyIII\Repositories\Tag\TagRepositoryInterface; - -/** - * Class Tags. - * - * @deprecated - * @codeCoverageIgnore - */ -class Tags implements MapperInterface -{ - /** - * Get map of tags. - * - * @return array - */ - public function getMap(): array - { - /** @var TagRepositoryInterface $repository */ - $repository = app(TagRepositoryInterface::class); - $result = $repository->get(); - $list = []; - - /** @var Tag $tag */ - foreach ($result as $tag) { - $tagId = (int) $tag->id; - $list[$tagId] = $tag->tag; - } - asort($list); - $list = [0 => (string) trans('import.map_do_not_map')] + $list; - - return $list; - } -} diff --git a/app/Import/Mapper/TransactionCurrencies.php b/app/Import/Mapper/TransactionCurrencies.php deleted file mode 100644 index 613afcc54d..0000000000 --- a/app/Import/Mapper/TransactionCurrencies.php +++ /dev/null @@ -1,56 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Mapper; - -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; - -/** - * Class TransactionCurrencies. - * - * @deprecated - * @codeCoverageIgnore - */ -class TransactionCurrencies implements MapperInterface -{ - /** - * Get map of currencies. - * - * @return array - */ - public function getMap(): array - { - /** @var CurrencyRepositoryInterface $repository */ - $repository = app(CurrencyRepositoryInterface::class); - $currencies = $repository->get(); - $list = []; - foreach ($currencies as $currency) { - $currencyId = (int) $currency->id; - $list[$currencyId] = $currency->name . ' (' . $currency->code . ')'; - } - asort($list); - - $list = [0 => (string) trans('import.map_do_not_map')] + $list; - - return $list; - } -} diff --git a/app/Import/MapperPreProcess/PreProcessorInterface.php b/app/Import/MapperPreProcess/PreProcessorInterface.php deleted file mode 100644 index 9436db4078..0000000000 --- a/app/Import/MapperPreProcess/PreProcessorInterface.php +++ /dev/null @@ -1,41 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\MapperPreProcess; - -/** - * Interface PreProcessorInterface. - * - * @deprecated - * @codeCoverageIgnore - */ -interface PreProcessorInterface -{ - /** - * Run preprocessor. - * - * @param string $value - * - * @return array - */ - public function run(string $value): array; -} diff --git a/app/Import/MapperPreProcess/TagsComma.php b/app/Import/MapperPreProcess/TagsComma.php deleted file mode 100644 index 23427f02cc..0000000000 --- a/app/Import/MapperPreProcess/TagsComma.php +++ /dev/null @@ -1,48 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\MapperPreProcess; - -/** - * Class TagsComma. - * - * @deprecated - * @codeCoverageIgnore - */ -class TagsComma implements PreProcessorInterface -{ - /** - * Explode and filter list of comma separated tags. - * - * @param string $value - * - * @return array - */ - public function run(string $value): array - { - $set = explode(',', $value); - $set = array_map('trim', $set); - $set = array_filter($set, '\strlen'); - - return array_values($set); - } -} diff --git a/app/Import/MapperPreProcess/TagsSpace.php b/app/Import/MapperPreProcess/TagsSpace.php deleted file mode 100644 index bab216c2a1..0000000000 --- a/app/Import/MapperPreProcess/TagsSpace.php +++ /dev/null @@ -1,48 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\MapperPreProcess; - -/** - * Class TagsSpace. - * - * @deprecated - * @codeCoverageIgnore - */ -class TagsSpace implements PreProcessorInterface -{ - /** - * Explode and filter list of space separated tags. - * - * @param string $value - * - * @return array - */ - public function run(string $value): array - { - $set = explode(' ', $value); - $set = array_map('trim', $set); - $set = array_filter($set, '\strlen'); - - return array_values($set); - } -} diff --git a/app/Import/Prerequisites/BunqPrerequisites.php b/app/Import/Prerequisites/BunqPrerequisites.php deleted file mode 100644 index 664f3aba84..0000000000 --- a/app/Import/Prerequisites/BunqPrerequisites.php +++ /dev/null @@ -1,236 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Prerequisites; - -use bunq\Util\BunqEnumApiEnvironmentType; -use Exception; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Services\Bunq\ApiContext; -use FireflyIII\Services\IP\IPRetrievalInterface; -use FireflyIII\User; -use Illuminate\Support\MessageBag; -use Log; - -/** - * This class contains all the routines necessary to connect to Bunq. - * - * @deprecated - * @codeCoverageIgnore - */ -class BunqPrerequisites implements PrerequisitesInterface -{ - /** @var User The current user */ - private $user; - - /** - * BunqPrerequisites constructor. - */ - public function __construct() - { - if ('testing' === config('app.env')) { - Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); - } - } - - /** - * Returns view name that allows user to fill in prerequisites. - * - * @codeCoverageIgnore - * - * @return string - */ - public function getView(): string - { - return 'import.bunq.prerequisites'; - } - - /** - * Returns any values required for the prerequisites-view. - * - * @return array - */ - public function getViewParameters(): array - { - Log::debug('Now in BunqPrerequisites::getViewParameters()'); - $key = ''; - $externalIP = ''; - if ($this->hasApiKey()) { - $key = app('preferences')->getForUser($this->user, 'bunq_api_key', null)->data; - } - if ($this->hasExternalIP()) { - $externalIP = app('preferences')->getForUser($this->user, 'bunq_external_ip', null)->data; - } - if (!$this->hasExternalIP()) { - /** @var IPRetrievalInterface $service */ - $service = app(IPRetrievalInterface::class); - $externalIP = (string) $service->getIP(); - } - - return ['api_key' => $key, 'external_ip' => $externalIP]; - } - - /** - * Indicate if all prerequisites have been met. - * - * @return bool - */ - public function isComplete(): bool - { - return $this->hasApiKey() && $this->hasExternalIP() && $this->hasApiContext(); - } - - /** - * Set the user for this Prerequisites-routine. Class is expected to implement and save this. - * - * @param User $user - * - * @codeCoverageIgnore - */ - public function setUser(User $user): void - { - $this->user = $user; - } - - /** - * This method responds to the user's submission of an API key. Should do nothing but store the value. - * - * Errors must be returned in the message bag under the field name they are requested by. - * - * @param array $data - * - * @return MessageBag - * - */ - public function storePrerequisites(array $data): MessageBag - { - $apiKey = $data['api_key'] ?? ''; - $externalIP = $data['external_ip'] ?? ''; - Log::debug('Storing bunq API key'); - app('preferences')->setForUser($this->user, 'bunq_api_key', $apiKey); - app('preferences')->setForUser($this->user, 'bunq_external_ip', $externalIP); - $environment = $this->getBunqEnvironment(); - $deviceDescription = 'Firefly III v' . config('firefly.version'); - $permittedIps = [$externalIP]; - Log::debug(sprintf('Environment for bunq is %s', $environment->getChoiceString())); - - try { - /** @var ApiContext $object */ - $object = app(ApiContext::class); - $apiContext = $object->create($environment, $apiKey, $deviceDescription, $permittedIps); - } catch (FireflyException $e) { - $messages = new MessageBag(); - $messages->add('bunq_error', $e->getMessage()); - - return $messages; - } - // store context in JSON: - try { - $json = $apiContext->toJson(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - $messages = new MessageBag(); - $messages->add('bunq_error', $e->getMessage()); - - return $messages; - } - // @codeCoverageIgnoreEnd - - // and store for user: - app('preferences')->setForUser($this->user, 'bunq_api_context', $json); - - return new MessageBag; - } - - /** - * Get correct bunq environment. - * - * @return BunqEnumApiEnvironmentType - * @codeCoverageIgnore - */ - private function getBunqEnvironment(): BunqEnumApiEnvironmentType - { - $env = config('firefly.bunq_use_sandbox'); - if (null === $env) { - return BunqEnumApiEnvironmentType::PRODUCTION(); - } - if (false === $env) { - return BunqEnumApiEnvironmentType::PRODUCTION(); - } - - return BunqEnumApiEnvironmentType::SANDBOX(); - } - - /** - * Check if we have API context. - * - * @return bool - */ - private function hasApiContext(): bool - { - $apiContext = app('preferences')->getForUser($this->user, 'bunq_api_context', null); - if (null === $apiContext) { - return false; - } - if ('' === (string) $apiContext->data) { - return false; - } - - return true; - } - - /** - * Check if we have the API key. - * - * @return bool - */ - private function hasApiKey(): bool - { - $apiKey = app('preferences')->getForUser($this->user, 'bunq_api_key', null); - if (null === $apiKey) { - return false; - } - if ('' === (string) $apiKey->data) { - return false; - } - - return true; - } - - /** - * Checks if we have an external IP. - * - * @return bool - */ - private function hasExternalIP(): bool - { - $externalIP = app('preferences')->getForUser($this->user, 'bunq_external_ip', null); - if (null === $externalIP) { - return false; - } - if ('' === (string) $externalIP->data) { - return false; - } - - return true; - } -} diff --git a/app/Import/Prerequisites/FakePrerequisites.php b/app/Import/Prerequisites/FakePrerequisites.php deleted file mode 100644 index 8f7ef94cb2..0000000000 --- a/app/Import/Prerequisites/FakePrerequisites.php +++ /dev/null @@ -1,146 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Prerequisites; - -use FireflyIII\User; -use Illuminate\Support\MessageBag; -use Log; -use function request; - -/** - * This class contains all the routines necessary for the fake import provider. - * - * Class FakePrerequisites - * - * @deprecated - * @codeCoverageIgnore - */ -class FakePrerequisites implements PrerequisitesInterface -{ - /** @var User The current user */ - private $user; - - /** - * FakePrerequisites constructor. - */ - public function __construct() - { - if ('testing' === config('app.env')) { - Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); - } - } - - /** - * Returns view name that allows user to fill in prerequisites. Currently asks for the API key. - * - * @codeCoverageIgnore - * @return string - */ - public function getView(): string - { - return 'import.fake.prerequisites'; - } - - /** - * Returns any values required for the prerequisites-view. - * - * @return array - */ - public function getViewParameters(): array - { - $apiKey = ''; - if ($this->hasApiKey()) { - $apiKey = app('preferences')->getForUser($this->user, 'fake_api_key', null)->data; - } - $oldKey = (string) request()->old('api_key'); - if ('' !== $oldKey) { - $apiKey = request()->old('api_key'); // @codeCoverageIgnore - } - - return ['api_key' => $apiKey]; - } - - /** - * Indicate if all prerequisites have been met. - * - * @return bool - */ - public function isComplete(): bool - { - return $this->hasApiKey(); - } - - /** - * Set the user for this Prerequisites-routine. Class is expected to implement and save this. - * - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - - } - - /** - * Store fake prerequisites. - * - * @param array $data - * - * @return MessageBag - */ - public function storePrerequisites(array $data): MessageBag - { - $apiKey = $data['api_key'] ?? ''; - $messageBag = new MessageBag(); - if (32 !== strlen($apiKey)) { - $messageBag->add('api_key', 'API key must be 32 chars.'); - - return $messageBag; - } - - app('preferences')->setForUser($this->user, 'fake_api_key', $apiKey); - - return $messageBag; - } - - /** - * Check if we have an API key. - * - * @return bool - */ - private function hasApiKey(): bool - { - $apiKey = app('preferences')->getForUser($this->user, 'fake_api_key', false); - if (null === $apiKey) { - return false; - } - if (null === $apiKey->data) { - return false; - } - if (32 === strlen((string) $apiKey->data)) { - return true; - } - - return false; - } -} diff --git a/app/Import/Prerequisites/FilePrerequisites.php b/app/Import/Prerequisites/FilePrerequisites.php deleted file mode 100644 index 8cfc105182..0000000000 --- a/app/Import/Prerequisites/FilePrerequisites.php +++ /dev/null @@ -1,102 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Prerequisites; - -use FireflyIII\User; -use Illuminate\Support\MessageBag; -use Log; - -/** - * - * This class contains all the routines necessary to import from a file. Hint: there are none. - * - * @deprecated - * @codeCoverageIgnore - */ -class FilePrerequisites implements PrerequisitesInterface -{ - - /** - * FilePrerequisites constructor. - */ - public function __construct() - { - if ('testing' === config('app.env')) { - Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); - } - } - - /** - * Returns view name that allows user to fill in prerequisites. - * - * @return string - */ - public function getView(): string - { - return ''; - } - - /** - * Returns any values required for the prerequisites-view. - * - * @return array - */ - public function getViewParameters(): array - { - return []; - } - - /** - * Indicate if all prerequisites have been met. - * - * @return bool - */ - public function isComplete(): bool - { - return true; - } - - /** - * Set the user for this Prerequisites-routine. Class is expected to implement and save this. - * - * @param User $user - */ - public function setUser(User $user): void - { - - } - - /** - * This method responds to the user's submission of an API key. Should do nothing but store the value. - * - * Errors must be returned in the message bag under the field name they are requested by. - * - * @param array $data - * - * @return MessageBag - */ - public function storePrerequisites(array $data): MessageBag - { - return new MessageBag; - } -} diff --git a/app/Import/Prerequisites/PrerequisitesInterface.php b/app/Import/Prerequisites/PrerequisitesInterface.php deleted file mode 100644 index 4ac3992b6e..0000000000 --- a/app/Import/Prerequisites/PrerequisitesInterface.php +++ /dev/null @@ -1,74 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Prerequisites; - -use FireflyIII\User; -use Illuminate\Support\MessageBag; - -/** - * Interface PrerequisitesInterface - * - * @deprecated - * @codeCoverageIgnore - */ -interface PrerequisitesInterface -{ - /** - * Returns view name that allows user to fill in prerequisites. - * - * @return string - */ - public function getView(): string; - - /** - * Returns any values required for the prerequisites-view. - * - * @return array - */ - public function getViewParameters(): array; - - /** - * Indicate if all prerequisites have been met. - * - * @return bool - */ - public function isComplete(): bool; - - /** - * Set the user for this Prerequisites-routine. Class is expected to implement and save this. - * - * @param User $user - */ - public function setUser(User $user): void; - - /** - * This method responds to the user's submission of an API key. Should do nothing but store the value. - * - * Errors must be returned in the message bag under the field name they are requested by. - * - * @param array $data - * - * @return MessageBag - */ - public function storePrerequisites(array $data): MessageBag; -} diff --git a/app/Import/Prerequisites/SpectrePrerequisites.php b/app/Import/Prerequisites/SpectrePrerequisites.php deleted file mode 100644 index 2746c870bf..0000000000 --- a/app/Import/Prerequisites/SpectrePrerequisites.php +++ /dev/null @@ -1,206 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Prerequisites; - -use FireflyIII\Models\Preference; -use FireflyIII\User; -use Illuminate\Support\MessageBag; -use Log; - -/** - * This class contains all the routines necessary to connect to Spectre. - * - * @deprecated - * @codeCoverageIgnore - */ -class SpectrePrerequisites implements PrerequisitesInterface -{ - /** @var User The current user */ - private $user; - - /** - * SpectrePrerequisites constructor. - */ - public function __construct() - { - if ('testing' === config('app.env')) { - Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); - } - } - - /** - * Returns view name that allows user to fill in prerequisites. - * - * @return string - */ - public function getView(): string - { - return 'import.spectre.prerequisites'; - } - - /** - * Returns any values required for the prerequisites-view. - * - * @return array - */ - public function getViewParameters(): array - { - /** @var Preference $appIdPreference */ - $appIdPreference = app('preferences')->getForUser($this->user, 'spectre_app_id', null); - $appId = null === $appIdPreference ? '' : $appIdPreference->data; - /** @var Preference $secretPreference */ - $secretPreference = app('preferences')->getForUser($this->user, 'spectre_secret', null); - $secret = null === $secretPreference ? '' : $secretPreference->data; - $publicKey = $this->getPublicKey(); - - return [ - 'app_id' => $appId, - 'secret' => $secret, - 'public_key' => $publicKey, - ]; - } - - /** - * Indicate if all prerequisites have been met. - * - * @return bool - */ - public function isComplete(): bool - { - return $this->hasAppId() && $this->hasSecret(); - } - - /** - * Set the user for this Prerequisites-routine. Class is expected to implement and save this. - * - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - } - - /** - * This method responds to the user's submission of an API key. Should do nothing but store the value. - * - * Errors must be returned in the message bag under the field name they are requested by. - * - * @param array $data - * - * @return MessageBag - */ - public function storePrerequisites(array $data): MessageBag - { - Log::debug('Storing Spectre API keys..'); - app('preferences')->setForUser($this->user, 'spectre_app_id', $data['app_id'] ?? null); - app('preferences')->setForUser($this->user, 'spectre_secret', $data['secret'] ?? null); - Log::debug('Done!'); - - return new MessageBag; - } - - /** - * This method creates a new public/private keypair for the user. This isn't really secure, since the key is generated on the fly with - * no regards for HSM's, smart cards or other things. It would require some low level programming to get this right. But the private key - * is stored encrypted in the database so it's something. - */ - private function createKeyPair(): void - { - Log::debug('Generate new Spectre key pair for user.'); - $keyConfig = [ - 'digest_alg' => 'sha512', - 'private_key_bits' => 2048, - 'private_key_type' => OPENSSL_KEYTYPE_RSA, - ]; - // Create the private and public key - $res = openssl_pkey_new($keyConfig); - - // Extract the private key from $res to $privKey - $privKey = ''; - openssl_pkey_export($res, $privKey); - - // Extract the public key from $res to $pubKey - $pubKey = openssl_pkey_get_details($res); - - app('preferences')->setForUser($this->user, 'spectre_private_key', $privKey); - app('preferences')->setForUser($this->user, 'spectre_public_key', $pubKey['key']); - Log::debug('Created key pair'); - - } - - /** - * Get a public key from the users preferences. - * - * @return string - */ - private function getPublicKey(): string - { - Log::debug('get public key'); - $preference = app('preferences')->getForUser($this->user, 'spectre_public_key', null); - if (null === $preference) { - Log::debug('public key is null'); - // create key pair - $this->createKeyPair(); - } - $preference = app('preferences')->getForUser($this->user, 'spectre_public_key', null); - Log::debug('Return public key for user'); - - return $preference->data; - } - - /** - * Check if we have the App ID. - * - * @return bool - */ - private function hasAppId(): bool - { - $appId = app('preferences')->getForUser($this->user, 'spectre_app_id', null); - if (null === $appId) { - return false; - } - if ('' === (string) $appId->data) { - return false; - } - - return true; - } - - /** - * Check if we have the secret. - * - * @return bool - */ - private function hasSecret(): bool - { - $secret = app('preferences')->getForUser($this->user, 'spectre_secret', null); - if (null === $secret) { - return false; - } - if ('' === (string) $secret->data) { - return false; - } - - return true; - } -} diff --git a/app/Import/Prerequisites/YnabPrerequisites.php b/app/Import/Prerequisites/YnabPrerequisites.php deleted file mode 100644 index 234ea3201f..0000000000 --- a/app/Import/Prerequisites/YnabPrerequisites.php +++ /dev/null @@ -1,159 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\Prerequisites; - -use FireflyIII\User; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class YnabPrerequisites - * - * @deprecated - * @codeCoverageIgnore - */ -class YnabPrerequisites implements PrerequisitesInterface -{ - /** @var User The current user */ - private $user; - - /** - * YnabPrerequisites constructor. - */ - public function __construct() - { - if ('testing' === config('app.env')) { - Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); - } - } - - /** - * Returns view name that allows user to fill in prerequisites. - * - * @return string - */ - public function getView(): string - { - return 'import.ynab.prerequisites'; - } - - /** - * Returns any values required for the prerequisites-view. - * - * @return array - */ - public function getViewParameters(): array - { - Log::debug('Now in YnabPrerequisites::getViewParameters()'); - $clientId = ''; - $clientSecret = ''; - if ($this->hasClientId()) { - $clientId = app('preferences')->getForUser($this->user, 'ynab_client_id', null)->data; - } - if ($this->hasClientSecret()) { - $clientSecret = app('preferences')->getForUser($this->user, 'ynab_client_secret', null)->data; - } - - $callBackUri = route('import.callback.ynab'); - $isHttps = 0 === strpos($callBackUri, 'https://'); - - return ['client_id' => $clientId, 'client_secret' => $clientSecret, 'callback_uri' => $callBackUri, 'is_https' => $isHttps]; - } - - /** - * Indicate if all prerequisites have been met. - * - * @return bool - */ - public function isComplete(): bool - { - return $this->hasClientId() && $this->hasClientSecret(); - } - - /** - * Set the user for this Prerequisites-routine. Class is expected to implement and save this. - * - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - } - - /** - * This method responds to the user's submission of an API key. Should do nothing but store the value. - * - * Errors must be returned in the message bag under the field name they are requested by. - * - * @param array $data - * - * @return MessageBag - */ - public function storePrerequisites(array $data): MessageBag - { - $clientId = $data['client_id'] ?? ''; - $clientSecret = $data['client_secret'] ?? ''; - Log::debug('Storing YNAB client data'); - app('preferences')->setForUser($this->user, 'ynab_client_id', $clientId); - app('preferences')->setForUser($this->user, 'ynab_client_secret', $clientSecret); - - return new MessageBag; - } - - /** - * Check if we have the client ID. - * - * @return bool - */ - private function hasClientId(): bool - { - $clientId = app('preferences')->getForUser($this->user, 'ynab_client_id', null); - if (null === $clientId) { - return false; - } - if ('' === (string) $clientId->data) { - return false; - } - - return true; - } - - /** - * Check if we have the client secret - * - * @return bool - */ - private function hasClientSecret(): bool - { - $clientSecret = app('preferences')->getForUser($this->user, 'ynab_client_secret', null); - if (null === $clientSecret) { - return false; - } - if ('' === (string) $clientSecret->data) { - return false; - } - - return true; - } -} diff --git a/app/Import/Routine/BunqRoutine.php b/app/Import/Routine/BunqRoutine.php deleted file mode 100644 index c70e425936..0000000000 --- a/app/Import/Routine/BunqRoutine.php +++ /dev/null @@ -1,118 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\Routine; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\Routine\Bunq\StageImportDataHandler; -use FireflyIII\Support\Import\Routine\Bunq\StageNewHandler; -use Log; - -/** - * Class BunqRoutine - * - * @deprecated - * @codeCoverageIgnore - */ -class BunqRoutine implements RoutineInterface -{ - /** @var ImportJob The import job */ - private $importJob; - - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * At the end of each run(), the import routine must set the job to the expected status. - * - * The final status of the routine must be "provider_finished". - * - * @throws FireflyException - */ - public function run(): void - { - Log::info(sprintf('Now in BunqRoutine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage)); - $valid = ['ready_to_run']; // should be only ready_to_run - if (in_array($this->importJob->status, $valid, true)) { - switch ($this->importJob->stage) { - default: - throw new FireflyException(sprintf('BunqRoutine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore - case 'new': - // list all of the users accounts. - $this->repository->setStatus($this->importJob, 'running'); - /** @var StageNewHandler $handler */ - $handler = app(StageNewHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - // make user choose accounts to import from. - $this->repository->setStage($this->importJob, 'choose-accounts'); - $this->repository->setStatus($this->importJob, 'need_job_config'); - - return; - case 'go-for-import': - // list all of the users accounts. - $this->repository->setStatus($this->importJob, 'running'); - - /** @var StageImportDataHandler $handler */ - $handler = app(StageImportDataHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - $transactions = $handler->getTransactions(); - // could be that more transactions will arrive in a second run. - if (true === $handler->isStillRunning()) { - Log::debug('Handler indicates that it is still working.'); - $this->repository->setStatus($this->importJob, 'ready_to_run'); - $this->repository->setStage($this->importJob, 'go-for-import'); - } - $this->repository->appendTransactions($this->importJob, $transactions); - if (false === $handler->isStillRunning()) { - Log::info('Handler indicates that its done!'); - $this->repository->setStatus($this->importJob, 'provider_finished'); - $this->repository->setStage($this->importJob, 'final'); - } - - - return; - } - } - throw new FireflyException(sprintf('bunq import routine cannot handle status "%s"', $this->importJob->status)); // @codeCoverageIgnore - } - - - /** - * Set the import job. - * - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } - -} diff --git a/app/Import/Routine/FakeRoutine.php b/app/Import/Routine/FakeRoutine.php deleted file mode 100644 index 8e81b8fe4a..0000000000 --- a/app/Import/Routine/FakeRoutine.php +++ /dev/null @@ -1,111 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\Routine; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\Routine\Fake\StageAhoyHandler; -use FireflyIII\Support\Import\Routine\Fake\StageFinalHandler; -use FireflyIII\Support\Import\Routine\Fake\StageNewHandler; -use Log; - -/** - * Class FakeRoutine - * - * @deprecated - * @codeCoverageIgnore - */ -class FakeRoutine implements RoutineInterface -{ - /** @var ImportJob The import job */ - private $importJob; - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * Fake import routine has three stages: - * - * "new": will quietly log gibberish for 15 seconds, then switch to stage "ahoy". - * will also set status to "ready_to_run" so it will arrive here again. - * "ahoy": will log some nonsense and then drop job into status:"need_job_config" to force it back to the job config routine. - * "final": will do some logging, sleep for 10 seconds and then finish. Generates 5 random transactions. - * - * @throws FireflyException - * - * @return void - */ - public function run(): void - { - Log::debug(sprintf('Now in run() for fake routine with status: %s', $this->importJob->status)); - if ('ready_to_run' !== $this->importJob->status) { - throw new FireflyException(sprintf('Fake job should have status "ready_to_run", not "%s"', $this->importJob->status)); // @codeCoverageIgnore - } - - switch ($this->importJob->stage) { - default: - throw new FireflyException(sprintf('Fake routine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore - case 'new': - $this->repository->setStatus($this->importJob, 'running'); - /** @var StageNewHandler $handler */ - $handler = app(StageNewHandler::class); - $handler->run(); - $this->repository->setStage($this->importJob, 'ahoy'); - // set job finished this step: - $this->repository->setStatus($this->importJob, 'ready_to_run'); - - return; - case 'ahoy': - $this->repository->setStatus($this->importJob, 'running'); - /** @var StageAhoyHandler $handler */ - $handler = app(StageAhoyHandler::class); - $handler->run(); - $this->repository->setStatus($this->importJob, 'need_job_config'); - $this->repository->setStage($this->importJob, 'final'); - break; - case 'final': - $this->repository->setStatus($this->importJob, 'running'); - /** @var StageFinalHandler $handler */ - $handler = app(StageFinalHandler::class); - $handler->setImportJob($this->importJob); - $transactions = $handler->getTransactions(); - $this->repository->setStatus($this->importJob, 'provider_finished'); - $this->repository->setStage($this->importJob, 'final'); - $this->repository->setTransactions($this->importJob, $transactions); - } - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - * - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Import/Routine/FileRoutine.php b/app/Import/Routine/FileRoutine.php deleted file mode 100644 index c54d71b911..0000000000 --- a/app/Import/Routine/FileRoutine.php +++ /dev/null @@ -1,99 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Routine; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\Routine\File\FileProcessorInterface; -use Log; - -/** - * Class FileRoutine - * - * @deprecated - * @codeCoverageIgnore - */ -class FileRoutine implements RoutineInterface -{ - /** @var ImportJob The import job */ - private $importJob; - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * At the end of each run(), the import routine must set the job to the expected status. - * - * The final status of the routine must be "provider_finished". - * - * @throws FireflyException - */ - public function run(): void - { - Log::debug(sprintf('Now in run() for file routine with status: %s', $this->importJob->status)); - if ('ready_to_run' === $this->importJob->status) { - $this->repository->setStatus($this->importJob, 'running'); - // get processor, depending on file type - // is just CSV for now. - $processor = $this->getProcessor(); - $processor->setImportJob($this->importJob); - $transactions = $processor->run(); - - $this->repository->setStatus($this->importJob, 'provider_finished'); - $this->repository->setStage($this->importJob, 'final'); - $this->repository->setTransactions($this->importJob, $transactions); - - return; - } - throw new FireflyException(sprintf('Import routine cannot handle status "%s"', $this->importJob->status)); // @codeCoverageIgnore - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } - - /** - * Return the appropriate file routine handler for - * the file type of the job. - * - * @return FileProcessorInterface - */ - private function getProcessor(): FileProcessorInterface - { - $config = $this->repository->getConfiguration($this->importJob); - $type = $config['file-type'] ?? 'csv'; - $class = config(sprintf('import.options.file.processors.%s', $type)); - - return app($class); - } -} diff --git a/app/Import/Routine/FinTSRoutine.php b/app/Import/Routine/FinTSRoutine.php deleted file mode 100644 index 6cb2f72f11..0000000000 --- a/app/Import/Routine/FinTSRoutine.php +++ /dev/null @@ -1,89 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Routine; - - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Import\JobConfiguration\FinTSConfigurationSteps; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\Routine\FinTS\StageImportDataHandler; -use Illuminate\Support\Facades\Log; - -/** - * - * Class FinTSRoutine - * - * @deprecated - * @codeCoverageIgnore - */ -class FinTSRoutine implements RoutineInterface -{ - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * At the end of each run(), the import routine must set the job to the expected status. - * - * The final status of the routine must be "provider_finished". - * - * @throws FireflyException - */ - public function run(): void - { - Log::debug(sprintf('Now in FinTSRoutine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage)); - $valid = ['ready_to_run']; // should be only ready_to_run - if (in_array($this->importJob->status, $valid, true)) { - switch ($this->importJob->stage) { - default: - throw new FireflyException(sprintf('FinTSRoutine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore - case FinTSConfigurationSteps::GO_FOR_IMPORT: - $this->repository->setStatus($this->importJob, 'running'); - /** @var StageImportDataHandler $handler */ - $handler = app(StageImportDataHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - $transactions = $handler->getTransactions(); - - $this->repository->setTransactions($this->importJob, $transactions); - $this->repository->setStatus($this->importJob, 'provider_finished'); - $this->repository->setStage($this->importJob, 'final'); - } - } - } - - /** - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } - -} diff --git a/app/Import/Routine/RoutineInterface.php b/app/Import/Routine/RoutineInterface.php deleted file mode 100644 index 8d02979e06..0000000000 --- a/app/Import/Routine/RoutineInterface.php +++ /dev/null @@ -1,53 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Routine; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; - -/** - * Interface RoutineInterface - * - * @deprecated - * @codeCoverageIgnore - */ -interface RoutineInterface -{ - /** - * At the end of each run(), the import routine must set the job to the expected status. - * - * The final status of the routine must be "provider_finished". - * - * @throws FireflyException - */ - public function run(): void; - - /** - * Set the import job. - * - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void; -} diff --git a/app/Import/Routine/SpectreRoutine.php b/app/Import/Routine/SpectreRoutine.php deleted file mode 100644 index 984ef19c68..0000000000 --- a/app/Import/Routine/SpectreRoutine.php +++ /dev/null @@ -1,128 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Routine; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\Routine\Spectre\StageAuthenticatedHandler; -use FireflyIII\Support\Import\Routine\Spectre\StageImportDataHandler; -use FireflyIII\Support\Import\Routine\Spectre\StageNewHandler; -use Log; - -/** - * Class SpectreRoutine - * - * @deprecated - * @codeCoverageIgnore - */ -class SpectreRoutine implements RoutineInterface -{ - - /** @var ImportJob The import job */ - private $importJob; - - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * At the end of each run(), the import routine must set the job to the expected status. - * - * The final status of the routine must be "provider_finished". - * - * @throws FireflyException - * - */ - public function run(): void - { - Log::debug(sprintf('Now in SpectreRoutine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage)); - $valid = ['ready_to_run']; // should be only ready_to_run - if (in_array($this->importJob->status, $valid, true)) { - switch ($this->importJob->stage) { - default: - throw new FireflyException(sprintf('SpectreRoutine cannot handle stage "%s".', $this->importJob->stage)); // @codeCoverageIgnore - case 'new': - // list all of the users logins. - $this->repository->setStatus($this->importJob, 'running'); - /** @var StageNewHandler $handler */ - $handler = app(StageNewHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - - // if count logins is zero, go to authenticate stage - if (0 === $handler->getCountLogins()) { - $this->repository->setStage($this->importJob, 'do-authenticate'); - $this->repository->setStatus($this->importJob, 'ready_to_run'); - - return; - } - // or return to config to select login. - $this->repository->setStage($this->importJob, 'choose-login'); - $this->repository->setStatus($this->importJob, 'need_job_config'); - break; - case 'do-authenticate': - // set job to require config. - $this->repository->setStatus($this->importJob, 'need_job_config'); - - return; - case 'authenticated': - $this->repository->setStatus($this->importJob, 'running'); - // get accounts from login, store in job. - /** @var StageAuthenticatedHandler $handler */ - $handler = app(StageAuthenticatedHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - - // return to config to select account(s). - $this->repository->setStage($this->importJob, 'choose-accounts'); - $this->repository->setStatus($this->importJob, 'need_job_config'); - break; - case 'go-for-import': - // user has chosen account mapping. Should now be ready to import data. - $this->repository->setStatus($this->importJob, 'running'); - $this->repository->setStage($this->importJob, 'do_import'); - /** @var StageImportDataHandler $handler */ - $handler = app(StageImportDataHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - $this->repository->setStatus($this->importJob, 'provider_finished'); - $this->repository->setStage($this->importJob, 'final'); - } - } - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } - -} diff --git a/app/Import/Routine/YnabRoutine.php b/app/Import/Routine/YnabRoutine.php deleted file mode 100644 index 5b2cd57197..0000000000 --- a/app/Import/Routine/YnabRoutine.php +++ /dev/null @@ -1,146 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\Routine; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\Routine\Ynab\GetAccountsHandler; -use FireflyIII\Support\Import\Routine\Ynab\ImportDataHandler; -use FireflyIII\Support\Import\Routine\Ynab\StageGetAccessHandler; -use FireflyIII\Support\Import\Routine\Ynab\StageGetBudgetsHandler; -use Log; - -/** - * Class YnabRoutine - * - * @deprecated - * @codeCoverageIgnore - */ -class YnabRoutine implements RoutineInterface -{ - /** @var ImportJob The import job */ - private $importJob; - - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - - /** - * At the end of each run(), the import routine must set the job to the expected status. - * - * The final status of the routine must be "provider_finished". - * - * @throws FireflyException - */ - public function run(): void - { - Log::debug(sprintf('Now in YNAB routine::run() with status "%s" and stage "%s".', $this->importJob->status, $this->importJob->stage)); - $valid = ['ready_to_run']; // should be only ready_to_run - if (in_array($this->importJob->status, $valid, true)) { - - // get access token from YNAB - if ('get_access_token' === $this->importJob->stage) { - // list all of the users accounts. - $this->repository->setStatus($this->importJob, 'running'); - /** @var StageGetAccessHandler $handler */ - $handler = app(StageGetAccessHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - - // back to correct stage: - $this->repository->setStatus($this->importJob, 'ready_to_run'); - $this->repository->setStage($this->importJob, 'get_budgets'); - - return; - } - if ('get_budgets' === $this->importJob->stage) { - $this->repository->setStatus($this->importJob, 'running'); - /** @var StageGetBudgetsHandler $handler */ - $handler = app(StageGetBudgetsHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - - // count budgets in job, to determine next step. - $configuration = $this->repository->getConfiguration($this->importJob); - $budgets = $configuration['budgets'] ?? []; - - // if more than 1 budget, select budget first. - if (count($budgets) > 1) { - $this->repository->setStage($this->importJob, 'select_budgets'); - $this->repository->setStatus($this->importJob, 'need_job_config'); - - return; - } - - if (1 === count($budgets)) { - $this->repository->setStatus($this->importJob, 'ready_to_run'); - $this->repository->setStage($this->importJob, 'get_accounts'); - } - - return; - } - if ('get_accounts' === $this->importJob->stage) { - $this->repository->setStatus($this->importJob, 'running'); - - /** @var GetAccountsHandler $handler */ - $handler = app(GetAccountsHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - - $this->repository->setStage($this->importJob, 'select_accounts'); - $this->repository->setStatus($this->importJob, 'need_job_config'); - - return; - } - if ('go-for-import' === $this->importJob->stage) { - $this->repository->setStatus($this->importJob, 'running'); - $this->repository->setStage($this->importJob, 'do_import'); - /** @var ImportDataHandler $handler */ - $handler = app(ImportDataHandler::class); - $handler->setImportJob($this->importJob); - $handler->run(); - $this->repository->setStatus($this->importJob, 'provider_finished'); - $this->repository->setStage($this->importJob, 'final'); - - return; - } - - throw new FireflyException(sprintf('YNAB import routine cannot handle stage "%s"', $this->importJob->stage)); - } - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Import/Specifics/AbnAmroDescription.php b/app/Import/Specifics/AbnAmroDescription.php deleted file mode 100644 index d15d42e35d..0000000000 --- a/app/Import/Specifics/AbnAmroDescription.php +++ /dev/null @@ -1,243 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Specifics; - -/** - * Class AbnAmroDescription. - * - * @deprecated - * @codeCoverageIgnore - * - * Parses the description from txt files for ABN AMRO bank accounts. - * - * Based on the logic as described in the following Gist: - * https://gist.github.com/vDorst/68d555a6a90f62fec004 - */ -class AbnAmroDescription implements SpecificInterface -{ - /** @var array The current row. */ - public $row; - - /** - * Description of this specific fix. - * - * @return string - * @codeCoverageIgnore - */ - public static function getDescription(): string - { - return 'import.specific_abn_descr'; - } - - /** - * Name of specific fix. - * - * @return string - * @codeCoverageIgnore - */ - public static function getName(): string - { - return 'import.specific_abn_name'; - } - - /** - * Run the fix. - * - * @param array $row - * - * @return array - * - */ - public function run(array $row): array - { - $this->row = array_values($row); - - if (!isset($row[7])) { - return $row; - } - - // Try to parse the description in known formats. - $parsed = $this->parseSepaDescription() || $this->parseTRTPDescription() || $this->parseGEABEADescription() || $this->parseABNAMRODescription(); - - // If the description could not be parsed, specify an unknown opposing - // account, as an opposing account is required - if (!$parsed) { - $this->row[8] = (string) trans('firefly.unknown'); // opposing-account-name - } - - return $this->row; - } - - /** - * Parses the current description with costs from ABN AMRO itself. - * - * @return bool true if the description is GEA/BEA-format, false otherwise - */ - protected function parseABNAMRODescription(): bool - { - // See if the current description is formatted in ABN AMRO format - if (preg_match('/ABN AMRO.{24} (.*)/', $this->row[7], $matches)) { - $this->row[8] = 'ABN AMRO'; // this one is new (opposing account name) - $this->row[7] = $matches[1]; // this is the description - - return true; - } - - return false; - } - - /** - * Parses the current description in GEA/BEA format. - * - * @return bool true if the description is GEA/BEAformat, false otherwise - */ - protected function parseGEABEADescription(): bool - { - // See if the current description is formatted in GEA/BEA format - if (preg_match('/([BG]EA) +(NR:[a-zA-Z:0-9]+) +([0-9.\/]+) +([^,]*)/', $this->row[7], $matches)) { - // description and opposing account will be the same. - $this->row[8] = $matches[4]; // 'opposing-account-name' - $this->row[7] = $matches[4]; // 'description' - - if ('GEA' === $matches[1]) { - $this->row[7] = 'GEA ' . $matches[4]; // 'description' - } - - return true; - } - - return false; - } - - /** - * Parses the current description in SEPA format. - * - * @return bool true if the description is SEPA format, false otherwise - * - */ - protected function parseSepaDescription(): bool - { - // See if the current description is formatted as a SEPA plain description - if (preg_match('/^SEPA(.{28})/', $this->row[7], $matches)) { - $type = $matches[1]; - $reference = ''; - $name = ''; - $newDescription = ''; - - // SEPA plain descriptions contain several key-value pairs, split by a colon - preg_match_all('/([A-Za-z]+(?=:\s)):\s([A-Za-z 0-9._#-]+(?=\s|$))/', $this->row[7], $matches, PREG_SET_ORDER); - - if (is_array($matches)) { - foreach ($matches as $match) { - $key = $match[1]; - $value = trim($match[2]); - switch (strtoupper($key)) { - case 'OMSCHRIJVING': - $newDescription = $value; - break; - case 'NAAM': - $this->row[8] = $value; - $name = $value; - break; - case 'KENMERK': - $reference = $value; - break; - case 'IBAN': - $this->row[9] = $value; - break; - default: // @codeCoverageIgnore - // Ignore the rest - } - } - } - - // Set a new description for the current transaction. If none was given - // set the description to type, name and reference - $this->row[7] = $newDescription; - if ('' === $newDescription) { - $this->row[7] = sprintf('%s - %s (%s)', $type, $name, $reference); - } - - return true; - } - - return false; - } - - /** - * Parses the current description in TRTP format. - * - * @return bool true if the description is TRTP format, false otherwise - * - */ - protected function parseTRTPDescription(): bool - { - // See if the current description is formatted in TRTP format - if (preg_match_all('!\/([A-Z]{3,4})\/([^/]*)!', $this->row[7], $matches, PREG_SET_ORDER)) { - $type = ''; - $name = ''; - $reference = ''; - $newDescription = ''; - - // Search for properties specified in the TRTP format. If no description - // is provided, use the type, name and reference as new description - if (is_array($matches)) { - foreach ($matches as $match) { - $key = $match[1]; - $value = trim($match[2]); - - switch (strtoupper($key)) { - case 'NAME': - $this->row[8] = $value; - break; - case 'REMI': - $newDescription = $value; - break; - case 'IBAN': - $this->row[9] = $value; - break; - case 'EREF': - $reference = $value; - break; - case 'TRTP': - $type = $value; - break; - default: // @codeCoverageIgnore - // Ignore the rest - } - } - - // Set a new description for the current transaction. If none was given - // set the description to type, name and reference - $this->row[7] = $newDescription; - if ('' === $newDescription) { - $this->row[7] = sprintf('%s - %s (%s)', $type, $name, $reference); - } - } - - return true; - } - - return false; - } -} diff --git a/app/Import/Specifics/Belfius.php b/app/Import/Specifics/Belfius.php deleted file mode 100644 index cc208eab31..0000000000 --- a/app/Import/Specifics/Belfius.php +++ /dev/null @@ -1,96 +0,0 @@ - - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * 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. - * - * This program 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Specifics; - -/** - * Class Belfius. - * - * @deprecated - * @codeCoverageIgnore - * - * Fixes Belfius CSV files to: - * - Correct descriptions for recurring transactions so doubles can be detected when the equivalent incoming - * transaction is imported. - * - */ -class Belfius implements SpecificInterface -{ - /** - * Description of this specific fix. - * - * @return string - * @codeCoverageIgnore - */ - public static function getDescription(): string - { - return 'import.specific_belfius_descr'; - } - - /** - * Name of specific fix. - * - * @return string - * @codeCoverageIgnore - */ - public static function getName(): string - { - return 'import.specific_belfius_name'; - } - - /** - * Fixes the description for outgoing recurring transactions so doubles can be detected when the equivalent incoming - * transaction is imported for another bank account. - * - * @return array the row containing the new description - */ - protected static function processRecurringTransactionDescription(array $row): array - { - if (!isset($row[5]) || !isset($row[14])) { - return $row; - } - - $opposingAccountName = $row[5]; - $description = $row[14]; - - preg_match('/DOORLOPENDE OPDRACHT.*\s+' . preg_quote($opposingAccountName, '/') . '\s+(.+)\s+REF.\s*:/', $description, $matches); - - if (isset($matches[1])) { - $row[14] = $matches[1]; - } - - return $row; - } - - /** - * Run the fix. - * - * @param array $row - * - * @return array - * - */ - public function run(array $row): array - { - return Belfius::processRecurringTransactionDescription($row); - } -} diff --git a/app/Import/Specifics/IngBelgium.php b/app/Import/Specifics/IngBelgium.php deleted file mode 100644 index f31ce7b6c6..0000000000 --- a/app/Import/Specifics/IngBelgium.php +++ /dev/null @@ -1,144 +0,0 @@ - - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * 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. - * - * This program 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Specifics; - -/** - * Class IngBelgium. - * - * @deprecated - * @codeCoverageIgnore - * - * Parses the description and opposing account information (IBAN and name) from CSV files for ING Belgium bank accounts. - * - */ -class IngBelgium implements SpecificInterface -{ - /** - * Description of the current specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getDescription(): string - { - return 'import.specific_ingbelgium_descr'; - } - - /** - * Name of the current specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getName(): string - { - return 'import.specific_ingbelgium_name'; - } - - /** - * Gets the description from the transaction details and makes sure structured descriptions are in the - * "+++090/9337/55493+++" format. - * - * @return string the description - */ - protected static function description(string $transactionDetails): string - { - $description = IngBelgium::parseInformationFromTransactionDetails($transactionDetails, '/Mededeling:\s*(.+)$/'); - - return IngBelgium::convertStructuredDescriptionToProperFormat($description); - } - - /** - * Gets the opposing account's IBAN from the transaction details. - * - * @return string the opposing account's IBAN - */ - protected static function opposingAccountIban(string $transactionDetails): string - { - return IngBelgium::parseInformationFromTransactionDetails($transactionDetails, '/IBAN:\s*(.+?)(?=\s+)/'); - } - - /** - * Gets the opposing account name from the transaction details. - * - * @return string the opposing account name - */ - protected static function opposingAccountName(string $transactionDetails): string - { - return IngBelgium::parseInformationFromTransactionDetails($transactionDetails, '/Van:\s*(.+?)(?=\s{2,})/'); - - } - - /** - * Gets the description and opposing account information (IBAN and name) from the transaction details and adds - * them to the row of data. - * - * @return array the row containing the description and opposing account's IBAN - */ - protected static function processTransactionDetails(array $row): array - { - if (isset($row[9])) { - $transactionDetails = $row[9]; - $row[11] = IngBelgium::opposingAccountName($transactionDetails); - $row[12] = IngBelgium::opposingAccountIban($transactionDetails); - $row[13] = IngBelgium::description($transactionDetails); - } - - return $row; - } - - private static function convertStructuredDescriptionToProperFormat(string $description): string - { - preg_match('/^\*\*\*(\d{3}\/\d{4}\/\d{5})\*\*\*$/', $description, $matches); - if (isset($matches[1])) { - return '+++' . $matches[1] . '+++'; - } - - return $description; - } - - private static function parseInformationFromTransactionDetails(string $transactionDetails, string $regex): string - { - if (isset($transactionDetails)) { - preg_match($regex, $transactionDetails, $matches); - if (isset($matches[1])) { - return trim($matches[1]); - } - } - - return ''; - } - - /** - * Run the specific code. - * - * @param array $row - * - * @return array - * - */ - public function run(array $row): array - { - return IngBelgium::processTransactionDetails($row); - } -} diff --git a/app/Import/Specifics/IngDescription.php b/app/Import/Specifics/IngDescription.php deleted file mode 100644 index 584a129840..0000000000 --- a/app/Import/Specifics/IngDescription.php +++ /dev/null @@ -1,173 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Specifics; - -/** - * Class IngDescription. - * - * @deprecated - * @codeCoverageIgnore - * - * Parses the description from CSV files for Ing bank accounts. - * - * With Mutation 'InternetBankieren', 'Overschrijving', 'Verzamelbetaling' and - * 'Incasso' the Name of Opposing account the Opposing IBAN number are in the - * Description. This class will remove them, and add Name in description by - * 'Betaalautomaat' so those are easily recognizable - */ -class IngDescription implements SpecificInterface -{ - /** @var array The current row. */ - public $row; - - /** - * Description of the current specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getDescription(): string - { - return 'import.specific_ing_descr'; - } - - /** - * Name of the current specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getName(): string - { - return 'import.specific_ing_name'; - } - - /** - * Run the specific code. - * - * @param array $row - * - * @return array - * - */ - public function run(array $row): array - { - $this->row = array_values($row); - array_push($this->row); // New column for "Valutadatum" - if (count($this->row) >= 8) { // check if the array is correct - switch ($this->row[4]) { // Get value for the mutation type - case 'GT': // InternetBankieren - case 'OV': // Overschrijving - case 'VZ': // Verzamelbetaling - case 'IC': // Incasso - case 'DV': // Divers - $this->removeIBANIngDescription(); // Remove "IBAN:", because it is already at "Tegenrekening" - $this->removeNameIngDescription(); // Remove "Naam:", because it is already at "Naam/ Omschrijving" - $this->removeIngDescription(); // Remove "Omschrijving", but not the value from description - $this->moveValutadatumDescription(); // Move "Valutadatum" from description to new column - $this->MoveSavingsAccount(); // Move savings account number and name - break; - case 'BA': // Betaalautomaat - $this->moveValutadatumDescription(); // Move "Valutadatum" from description to new column - $this->addNameIngDescription(); - break; - } - } - - return $this->row; - } - - /** - * Add the Opposing name from cell 1 in the description for Betaalautomaten - * Otherwise the description is only: 'Pasvolgnr: Transactie: Term:'. - */ - protected function addNameIngDescription(): void - { - $this->row[8] = $this->row[1] . ' ' . $this->row[8]; - } - - /** - * Move "Valutadatum" from the description to new column. - */ - protected function moveValutadatumDescription(): void - { - $matches = []; - if (preg_match('/Valutadatum: ([0-9-]+)/', $this->row[8], $matches)) { - $this->row[9] = date("Ymd", strtotime($matches[1])); - $this->row[8] = preg_replace('/Valutadatum: [0-9-]+/', '', $this->row[8]); - } - } - - /** - * Remove IBAN number out of the description - * Default description of Description is: Naam: Omschrijving: IBAN: . - */ - protected function removeIBANIngDescription(): void - { - // Try replace the iban number with nothing. The IBAN nr is found in the third column - $this->row[8] = preg_replace('/\sIBAN:\s' . $this->row[3] . '/', '', $this->row[8]); - } - - /** - * Remove "Omschrijving" (and NOT its value) from the description. - */ - protected function removeIngDescription(): void - { - $this->row[8] = preg_replace('/Omschrijving: /', '', $this->row[8]); - } - - /** - * Remove "Naam" (and its value) from the description. - */ - protected function removeNameIngDescription(): void - { - $this->row[8] = preg_replace('/Naam:.*?([a-zA-Z\/]+:)/', '$1', $this->row[8]); - } - - /** - * Move savings account number to column 1 and name to column 3. - */ - private function MoveSavingsAccount(): void - { - $matches = []; - - if (preg_match('/(Naar|Van) (.*rekening) ([A-Za-z0-9]+)/', $this->row[8], $matches)) { // Search for saving acount at 'Mededelingen' column - $this->row[1] = $this->row[1] . ' ' . $matches[2] . ' ' . $matches[3]; // Current name + Saving acount name + Acount number - if ('' === (string) $this->row[3]) { // if Saving account number does not yet exists - $this->row[3] = $matches[3]; // Copy savings account number - } - $this->row[8] = preg_replace('/(Naar|Van) (.*rekening) ([A-Za-z0-9]+)/', '', $this->row[8]); // Remove the savings account content from description - } elseif (preg_match('/(Naar|Van) (.*rekening) ([A-Za-z0-9]+)/', $this->row[1], $matches)) { // Search for saving acount at 'Naam / Omschrijving' column - $this->row[1] = $matches[2] . ' ' . $matches[3]; // Saving acount name + Acount number - if ('' === (string) $this->row[3]) { // if Saving account number does not yet exists - $this->row[3] = $matches[3]; // Copy savings account number - } - } - - if ('' !== (string)$this->row[3]) { // if Saving account number exists - if (! preg_match('/[A-Za-z]/', $this->row[3])) { // if Saving account number has no characters - $this->row[3] = sprintf("%010d", $this->row[3]); // Make the number 10 digits - } - } - } -} diff --git a/app/Import/Specifics/PresidentsChoice.php b/app/Import/Specifics/PresidentsChoice.php deleted file mode 100644 index 36abe52657..0000000000 --- a/app/Import/Specifics/PresidentsChoice.php +++ /dev/null @@ -1,77 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Specifics; - -/** - * Class PresidentsChoice. - * - * @deprecated - * @codeCoverageIgnore - */ -class PresidentsChoice implements SpecificInterface -{ - /** - * Description of specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getDescription(): string - { - return 'import.specific_pres_descr'; - } - - /** - * Name of specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getName(): string - { - return 'import.specific_pres_name'; - } - - /** - * Run this specific. - * - * @param array $row - * - * @return array - */ - public function run(array $row): array - { - $row = array_values($row); - // first, if column 2 is empty and 3 is not, do nothing. - // if column 3 is empty and column 2 is not, move amount to column 3, *-1 - if (isset($row[3]) && '' === $row[3]) { - $row[3] = bcmul($row[2], '-1'); - } - if (isset($row[1])) { - // copy description into column 2, which is now usable. - $row[2] = $row[1]; - } - - return $row; - } -} diff --git a/app/Import/Specifics/RabobankDescription.php b/app/Import/Specifics/RabobankDescription.php deleted file mode 100644 index 1823a6bda8..0000000000 --- a/app/Import/Specifics/RabobankDescription.php +++ /dev/null @@ -1,69 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Specifics; - -/** - * Class RabobankDescription. - * - * @codeCoverageIgnore - * @deprecated - */ -class RabobankDescription implements SpecificInterface -{ - /** - * Description of this specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getDescription(): string - { - return 'import.specific_rabo_descr'; - } - - /** - * Name of this specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getName(): string - { - return 'import.specific_rabo_name'; - } - - /** - * Run the specific. - * - * @param array $row - * - * @return array - * - */ - public function run(array $row): array - { - $row = array_values($row); - - return $row; - } -} diff --git a/app/Import/Specifics/SnsDescription.php b/app/Import/Specifics/SnsDescription.php deleted file mode 100644 index f36a683ee5..0000000000 --- a/app/Import/Specifics/SnsDescription.php +++ /dev/null @@ -1,73 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Specifics; - -/** - * Class SnsDescription. - * - * @codeCoverageIgnore - * @deprecated - */ -class SnsDescription implements SpecificInterface -{ - /** - * Get description of specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getDescription(): string - { - return 'import.specific_sns_descr'; - } - - /** - * Get name of specific. - * - * @return string - * @codeCoverageIgnore - */ - public static function getName(): string - { - return 'import.specific_sns_name'; - } - - /** - * Run specific. - * - * @param array $row - * - * @return array - */ - public function run(array $row): array - { - $row = array_values($row); - if (!isset($row[17])) { - return $row; - } - $row[17] = ltrim($row[17], "'"); - $row[17] = rtrim($row[17], "'"); - - return $row; - } -} diff --git a/app/Import/Specifics/SpecificInterface.php b/app/Import/Specifics/SpecificInterface.php deleted file mode 100644 index b2a9a6e5fa..0000000000 --- a/app/Import/Specifics/SpecificInterface.php +++ /dev/null @@ -1,55 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Import\Specifics; - -/** - * Interface SpecificInterface. - * - * @codeCoverageIgnore - * @deprecated - */ -interface SpecificInterface -{ - /** - * Get description. - * - * @return string - */ - public static function getDescription(): string; - - /** - * Get name. - * - * @return string - */ - public static function getName(): string; - - /** - * Run specific. - * - * @param array $row - * - * @return array - */ - public function run(array $row): array; -} diff --git a/app/Import/Storage/ImportArrayStorage.php b/app/Import/Storage/ImportArrayStorage.php deleted file mode 100644 index c73ec54186..0000000000 --- a/app/Import/Storage/ImportArrayStorage.php +++ /dev/null @@ -1,630 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Import\Storage; - -use Carbon\Carbon; -use DB; -use Exception; -use FireflyIII\Events\RequestedReportOnJournals; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Helpers\Collector\GroupCollectorInterface; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\Preference; -use FireflyIII\Models\TransactionGroup; -use FireflyIII\Models\TransactionJournal; -use FireflyIII\Models\TransactionType; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Repositories\Journal\JournalRepositoryInterface; -use FireflyIII\Repositories\Tag\TagRepositoryInterface; -use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; -use FireflyIII\TransactionRules\Engine\RuleEngine; -use Illuminate\Database\QueryException; -use Illuminate\Support\Collection; -use Log; - -/** - * Creates new transactions based on arrays. - * - * Class ImportArrayStorage - * - * @codeCoverageIgnore - * @deprecated - * - */ -class ImportArrayStorage -{ - /** @var int Number of hits required for a transfer to match. */ - private const REQUIRED_HITS = 4; - /** @var bool Check for transfers during import. */ - private $checkForTransfers = false; - /** @var TransactionGroupRepositoryInterface */ - private $groupRepos; - /** @var ImportJob The import job */ - private $importJob; - /** @var JournalRepositoryInterface Journal repository for storage. */ - private $journalRepos; - /** @var string */ - private $language = 'en_US'; - /** @var ImportJobRepositoryInterface Import job repository */ - private $repository; - /** @var array The transfers the user already has. */ - private $transfers; - - /** - * Set job, count transfers in the array and create the repository. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - - $this->countTransfers(); - - $this->journalRepos = app(JournalRepositoryInterface::class); - $this->journalRepos->setUser($importJob->user); - - $this->groupRepos = app(TransactionGroupRepositoryInterface::class); - $this->groupRepos->setUser($importJob->user); - - // get language of user. - /** @var Preference $pref */ - $pref = app('preferences')->getForUser($importJob->user, 'language', config('firefly.default_language', 'en_US')); - $this->language = $pref->data; - - Log::debug('Constructed ImportArrayStorage()'); - } - - /** - * Actually does the storing. Does three things. - * - Store journals - * - Link to tag - * - Run rules (if set to) - * - * @throws FireflyException - * @return Collection - */ - public function store(): Collection - { - // store transactions - $this->setStatus('storing_data'); - $collection = $this->storeGroupArray(); - $this->setStatus('stored_data'); - - // link tag: - $this->setStatus('linking_to_tag'); - $this->linkToTag($collection); - $this->setStatus('linked_to_tag'); - - // run rules, if configured to. - $config = $this->importJob->configuration; - if (isset($config['apply-rules']) && true === $config['apply-rules']) { - $this->setStatus('applying_rules'); - $this->applyRules($collection); - $this->setStatus('rules_applied'); - } - - app('preferences')->mark(); - - // email about this: - event(new RequestedReportOnJournals((int) $this->importJob->user_id, $collection)); - - return $collection; - } - - /** - * Applies the users rules to the created journals. - * - * @param Collection $collection - * - */ - private function applyRules(Collection $collection): void - { - Log::debug('Now in applyRules()'); - - /** @var RuleEngine $ruleEngine */ - $ruleEngine = app(RuleEngine::class); - $ruleEngine->setUser($this->importJob->user); - $ruleEngine->setAllRules(true); - - // for this call, the rule engine only includes "store" rules: - $ruleEngine->setTriggerMode(RuleEngine::TRIGGER_STORE); - Log::debug('Start of engine loop'); - foreach ($collection as $group) { - $this->applyRulesGroup($ruleEngine, $group); - } - Log::debug('End of engine loop.'); - } - - /** - * @param RuleEngine $ruleEngine - * @param TransactionGroup $group - */ - private function applyRulesGroup(RuleEngine $ruleEngine, TransactionGroup $group): void - { - Log::debug(sprintf('Processing group #%d', $group->id)); - foreach ($group->transactionJournals as $journal) { - Log::debug(sprintf('Processing journal #%d from group #%d', $journal->id, $group->id)); - $ruleEngine->processTransactionJournal($journal); - } - } - - /** - * Count the number of transfers in the array. If this is zero, don't bother checking for double transfers. - */ - private function countTransfers(): void - { - Log::debug('Now in countTransfers()'); - /** @var array $array */ - $array = $this->repository->getTransactions($this->importJob); - - - $count = 0; - foreach ($array as $index => $group) { - - foreach ($group['transactions'] as $transaction) { - if (strtolower(TransactionType::TRANSFER) === strtolower($transaction['type'])) { - $count++; - Log::debug(sprintf('Row #%d is a transfer, increase count to %d', $index + 1, $count)); - } - } - } - Log::debug(sprintf('Count of transfers in import array is %d.', $count)); - if ($count > 0) { - $this->checkForTransfers = true; - Log::debug('Will check for duplicate transfers.'); - // get users transfers. Needed for comparison. - $this->getTransfers(); - } - } - - /** - * @param int $index - * @param array $group - * - * @return bool - */ - private function duplicateDetected(int $index, array $group): bool - { - Log::debug(sprintf('Now in duplicateDetected(%d)', $index)); - $transactions = $group['transactions'] ?? []; - foreach ($transactions as $transaction) { - $hash = $this->getHash($transaction); - $existingId = $this->hashExists($hash); - if (null !== $existingId) { - $message = (string) trans('import.duplicate_row', ['row' => $index, 'description' => $transaction['description']]); - $this->logDuplicateObject($transaction, $existingId); - $this->repository->addErrorMessage($this->importJob, $message); - - return true; - } - - // do transfer detection: - if ($this->checkForTransfers && $this->transferExists($transaction)) { - $message = (string) trans('import.duplicate_row', ['row' => $index, 'description' => $transaction['description']]); - $this->logDuplicateTransfer($transaction); - $this->repository->addErrorMessage($this->importJob, $message); - - return true; - } - } - - return false; - } - - /** - * Get hash of transaction. - * - * @param array $transaction - * - * @return string - */ - private function getHash(array $transaction): string - { - unset($transaction['import_hash_v2'], $transaction['original_source']); - $json = json_encode($transaction, JSON_THROW_ON_ERROR); - if (false === $json) { - // @codeCoverageIgnoreStart - /** @noinspection ForgottenDebugOutputInspection */ - Log::error('Could not encode import array.', $transaction); - try { - $json = random_int(1, 10000); - } catch (Exception $e) { - // seriously? - Log::error(sprintf('random_int() just failed. I want a medal: %s', $e->getMessage())); - } - // @codeCoverageIgnoreEnd - } - - $hash = hash('sha256', $json); - Log::debug(sprintf('The hash is: %s', $hash), $transaction); - - return $hash; - } - - /** - * @param TransactionGroup $transactionGroup - * - * @return array - */ - private function getTransactionFromJournal(TransactionGroup $transactionGroup): array - { - // collect transactions using the journal collector - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - - $collector->setUser($this->importJob->user); - $collector->setGroup($transactionGroup); - - return $collector->getExtractedJournals(); - } - - /** - * Get the users transfers, so they can be compared to whatever the user is trying to import. - */ - private function getTransfers(): void - { - Log::debug('Now in getTransfers()'); - app('preferences')->mark(); - - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - - $collector->setUser($this->importJob->user); - $collector - ->setTypes([TransactionType::TRANSFER])->setLimit(10000)->setPage(1) - ->withAccountInformation(); - $this->transfers = $collector->getExtractedJournals(); - Log::debug(sprintf('Count of getTransfers() is %d', count($this->transfers))); - } - - /** - * Check if the hash exists for the array the user wants to import. - * - * @param string $hash - * - * @return int|null - */ - private function hashExists(string $hash): ?int - { - $entry = $this->journalRepos->findByHash($hash); - if (null === $entry) { - Log::debug(sprintf('Found no transactions with hash %s.', $hash)); - - return null; - } - Log::info(sprintf('Found a transaction journal with an existing hash: %s', $hash)); - - return (int) $entry->transaction_journal_id; - } - - /** - * Link all imported journals to a tag. - * - * @param Collection $collection - */ - private function linkToTag(Collection $collection): void - { - if (0 === $collection->count()) { - return; - } - /** @var TagRepositoryInterface $repository */ - $repository = app(TagRepositoryInterface::class); - $repository->setUser($this->importJob->user); - $data = [ - 'tag' => (string) trans('import.import_with_key', ['key' => $this->importJob->key]), - 'date' => new Carbon, - 'description' => null, - 'latitude' => null, - 'longitude' => null, - 'zoom_level' => null, - 'tagMode' => 'nothing', - ]; - $tag = $repository->store($data); - - Log::debug(sprintf('Created tag #%d ("%s")', $tag->id, $tag->tag)); - Log::debug('Looping groups...'); - - // TODO double loop. - - /** @var TransactionGroup $group */ - foreach ($collection as $group) { - Log::debug(sprintf('Looping journals in group #%d', $group->id)); - /** @var TransactionJournal $journal */ - $journalIds = $group->transactionJournals->pluck('id')->toArray(); - $tagId = $tag->id; - foreach ($journalIds as $journalId) { - Log::debug(sprintf('Linking journal #%d to tag #%d...', $journalId, $tagId)); - // @codeCoverageIgnoreStart - try { - DB::table('tag_transaction_journal')->insert(['transaction_journal_id' => $journalId, 'tag_id' => $tagId]); - } catch (QueryException $e) { - Log::error(sprintf('Could not link journal #%d to tag #%d because: %s', $journalId, $tagId, $e->getMessage())); - } - // @codeCoverageIgnoreEnd - } - Log::info(sprintf('Linked %d journals to tag #%d ("%s")', $collection->count(), $tag->id, $tag->tag)); - } - $this->repository->setTag($this->importJob, $tag); - - } - - /** - * Log about a duplicate object (double hash). - * - * @param array $transaction - * @param int $existingId - */ - private function logDuplicateObject(array $transaction, int $existingId): void - { - Log::info( - 'Transaction is a duplicate, and will not be imported (the hash exists).', - [ - 'existing' => $existingId, - 'description' => $transaction['description'] ?? '', - 'amount' => $transaction['transactions'][0]['amount'] ?? 0, - 'date' => $transaction['date'] ?? '', - ] - ); - - } - - /** - * Log about a duplicate transfer. - * - * @param array $transaction - */ - private function logDuplicateTransfer(array $transaction): void - { - Log::info( - 'Transaction is a duplicate transfer, and will not be imported (such a transfer exists already).', - [ - 'description' => $transaction['description'] ?? '', - 'amount' => $transaction['transactions'][0]['amount'] ?? 0, - 'date' => $transaction['date'] ?? '', - ] - ); - } - - /** - * Shorthand method to quickly set job status - * - * @param string $status - */ - private function setStatus(string $status): void - { - $this->repository->setStatus($this->importJob, $status); - } - - /** - * @param int $index - * @param array $group - * - * @return TransactionGroup|null - */ - private function storeGroup(int $index, array $group): ?TransactionGroup - { - Log::debug(sprintf('Going to store entry #%d', $index + 1)); - - // do some basic error catching. - foreach ($group['transactions'] as $groupIndex => $transaction) { - $group['transactions'][$groupIndex]['date'] = Carbon::parse($transaction['date'], config('app.timezone')); - $group['transactions'][$groupIndex]['description'] = '' === $transaction['description'] ? '(empty description)' : $transaction['description']; - } - - // do duplicate detection! - if ($this->duplicateDetected($index, $group)) { - Log::warning(sprintf('Row #%d seems to be a imported already and will be ignored.', $index)); - - return null; - } - - // store the group - try { - $newGroup = $this->groupRepos->store($group); - // @codeCoverageIgnoreStart - } catch (FireflyException $e) { - Log::error($e->getMessage()); - Log::error($e->getTraceAsString()); - $this->repository->addErrorMessage($this->importJob, sprintf('Row #%d could not be imported. %s', $index, $e->getMessage())); - - return null; - } - // @codeCoverageIgnoreEnd - Log::debug(sprintf('Stored as group #%d', $newGroup->id)); - - // add to collection of transfers, if necessary: - if ('transfer' === strtolower($group['transactions'][0]['type'])) { - $journals = $this->getTransactionFromJournal($newGroup); - Log::debug('We just stored a transfer, so add the journal to the list of transfers.'); - foreach ($journals as $newJournal) { - $this->transfers[] = $newJournal; - } - Log::debug(sprintf('List length is now %d', count($this->transfers))); - } - - return $newGroup; - } - - /** - * Store array as journals. - * - * @throws FireflyException - * - * @return Collection - */ - private function storeGroupArray(): Collection - { - /** @var array $array */ - $array = $this->repository->getTransactions($this->importJob); - $count = count($array); - - Log::notice(sprintf('Will now store the groups. Count of groups is %d.', $count)); - Log::notice('Going to store...'); - - $collection = new Collection; - foreach ($array as $index => $group) { - Log::debug(sprintf('Now store #%d', $index + 1)); - $result = $this->storeGroup($index, $group); - if (null !== $result) { - $collection->push($result); - } - } - Log::notice(sprintf('Done storing. Firefly III has stored %d transactions.', $collection->count())); - - return $collection; - } - - /** - * Check if a transfer exists. - * - * @param array $transaction - * - * @return bool - * - */ - private function transferExists(array $transaction): bool - { - Log::debug('transferExists() Check if transaction is a double transfer.'); - - // how many hits do we need? - Log::debug(sprintf('System has %d existing transfers', count($this->transfers))); - // loop over each split: - - // check if is a transfer - if (strtolower(TransactionType::TRANSFER) !== strtolower($transaction['type'])) { - // @codeCoverageIgnoreStart - Log::debug(sprintf('Is a %s, not a transfer so no.', $transaction['type'])); - - return false; - // @codeCoverageIgnoreEnd - } - - - Log::debug(sprintf('Required hits for transfer comparison is %d', self::REQUIRED_HITS)); - - // get the amount: - /** @noinspection UnnecessaryCastingInspection */ - $amount = (string) ($transaction['amount'] ?? '0'); - if (bccomp($amount, '0') === -1) { - $amount = bcmul($amount, '-1'); // @codeCoverageIgnore - } - - // get the description: - //$description = '' === (string)$transaction['description'] ? $transaction['description'] : $transaction['description']; - $description = (string) $transaction['description']; - - // get the source and destination ID's: - $transactionSourceIDs = [(int) $transaction['source_id'], (int) $transaction['destination_id']]; - sort($transactionSourceIDs); - - // get the source and destination names: - $transactionSourceNames = [(string) $transaction['source_name'], (string) $transaction['destination_name']]; - sort($transactionSourceNames); - - // then loop all transfers: - /** @var array $transfer */ - foreach ($this->transfers as $transfer) { - // number of hits for this split-transfer combination: - $hits = 0; - Log::debug(sprintf('Now looking at transaction journal #%d', $transfer['transaction_journal_id'])); - // compare amount: - $originalAmount = app('steam')->positive($transfer['amount']); - Log::debug(sprintf('Amount %s compared to %s', $amount, $originalAmount)); - if (0 !== bccomp($amount, $originalAmount)) { - Log::debug('Amount is not a match, continue with next transfer.'); - continue; - } - ++$hits; - Log::debug(sprintf('Comparison is a hit! (%s)', $hits)); - - // compare description: - // $comparison = '(empty description)' === $transfer['description'] ? '' : $transfer['description']; - $comparison = $transfer['description']; - Log::debug(sprintf('Comparing "%s" to "%s" (original: "%s")', $description, $transfer['description'], $comparison)); - if ($description !== $comparison) { - Log::debug('Description is not a match, continue with next transfer.'); - continue; // @codeCoverageIgnore - } - ++$hits; - Log::debug(sprintf('Comparison is a hit! (%s)', $hits)); - - // compare date: - $transferDate = $transfer['date']->format('Y-m-d H:i:s'); - $transactionDate = $transaction['date']->format('Y-m-d H:i:s'); - Log::debug(sprintf('Comparing dates "%s" to "%s"', $transactionDate, $transferDate)); - if ($transactionDate !== $transferDate) { - Log::debug('Date is not a match, continue with next transfer.'); - continue; // @codeCoverageIgnore - } - ++$hits; - Log::debug(sprintf('Comparison is a hit! (%s)', $hits)); - - // compare source and destination id's - $transferSourceIDs = [(int) $transfer['source_account_id'], (int) $transfer['destination_account_id']]; - sort($transferSourceIDs); - /** @noinspection DisconnectedForeachInstructionInspection */ - Log::debug('Comparing current transaction source+dest IDs', $transactionSourceIDs); - Log::debug('.. with current transfer source+dest IDs', $transferSourceIDs); - if ($transactionSourceIDs === $transferSourceIDs) { - ++$hits; - Log::debug(sprintf('Source IDs are the same! (%d)', $hits)); - } - if ($transactionSourceIDs !== $transferSourceIDs) { - Log::debug('Source IDs are not the same.'); - } - unset($transferSourceIDs); - - // compare source and destination names - $transferSource = [(string) ($transfer['source_account_name'] ?? ''), (string) ($transfer['destination_account_name'] ?? '')]; - sort($transferSource); - /** @noinspection DisconnectedForeachInstructionInspection */ - Log::debug('Comparing current transaction source+dest names', $transactionSourceNames); - Log::debug('.. with current transfer source+dest names', $transferSource); - if ($transactionSourceNames === $transferSource && $transferSource !== ['', '']) { - // @codeCoverageIgnoreStart - ++$hits; - Log::debug(sprintf('Source names are the same! (%d)', $hits)); - // @codeCoverageIgnoreEnd - } - if ($transactionSourceNames !== $transferSource) { - Log::debug('Source names are not the same.'); - } - - Log::debug(sprintf('Number of hits is %d', $hits)); - if ($hits >= self::REQUIRED_HITS) { - Log::debug(sprintf('Is more than %d, return true.', self::REQUIRED_HITS)); - - return true; - } - } - Log::debug('Is not an existing transfer, return false.'); - - return false; - } - -} diff --git a/app/Models/Account.php b/app/Models/Account.php index 1b92e96505..bf6e174537 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -94,6 +94,12 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property-read int|null $notes_count * @property-read int|null $piggy_banks_count * @property-read int|null $transactions_count + * @property \Illuminate\Support\Carbon|null $created_at + * @property \Illuminate\Support\Carbon|null $updated_at + * @property int $account_type_id + * @property bool $encrypted + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\AccountMeta[] $accountMeta + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\PiggyBank[] $piggyBanks */ class Account extends Model { diff --git a/app/Models/ImportJob.php b/app/Models/ImportJob.php deleted file mode 100644 index fd43e2c4be..0000000000 --- a/app/Models/ImportJob.php +++ /dev/null @@ -1,150 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Models; - -use Carbon\Carbon; -use Eloquent; -use FireflyIII\User; -use Illuminate\Database\Eloquent\Builder; -use Illuminate\Database\Eloquent\Collection; -use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Eloquent\Relations\BelongsTo; -use Illuminate\Database\Eloquent\Relations\MorphMany; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; - -/** - * Class ImportJob. - * - * @codeCoverageIgnore - * @deprecated - * @property array $transactions - * @property array $configuration - * @property User $user - * @property int $user_id - * @property string $status - * @property string $stage - * @property string $key - * @property string $provider - * @property string $file_type - * @property int $tag_id - * @property Tag $tag - * @property array $errors - * @property array extended_status - * @property int id - * @property Carbon $created_at - * @property Carbon $updated_at - * @property-read Collection|Attachment[] $attachments - * @method static Builder|ImportJob newModelQuery() - * @method static Builder|ImportJob newQuery() - * @method static Builder|ImportJob query() - * @method static Builder|ImportJob whereConfiguration($value) - * @method static Builder|ImportJob whereCreatedAt($value) - * @method static Builder|ImportJob whereErrors($value) - * @method static Builder|ImportJob whereExtendedStatus($value) - * @method static Builder|ImportJob whereFileType($value) - * @method static Builder|ImportJob whereId($value) - * @method static Builder|ImportJob whereKey($value) - * @method static Builder|ImportJob whereProvider($value) - * @method static Builder|ImportJob whereStage($value) - * @method static Builder|ImportJob whereStatus($value) - * @method static Builder|ImportJob whereTagId($value) - * @method static Builder|ImportJob whereTransactions($value) - * @method static Builder|ImportJob whereUpdatedAt($value) - * @method static Builder|ImportJob whereUserId($value) - * @mixin Eloquent - * @property-read int|null $attachments_count - * @property int $id - * @property array|null $extended_status - */ -class ImportJob extends Model -{ - - /** - * The attributes that should be casted to native types. - * - * @var array - */ - protected $casts - = [ - 'user_id' => 'int', - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'configuration' => 'array', - 'extended_status' => 'array', - 'transactions' => 'array', - 'errors' => 'array', - ]; - /** @var array Fields that can be filled */ - protected $fillable = ['key', 'user_id', 'file_type', 'provider', 'status', 'stage', 'configuration', 'extended_status', 'transactions', 'errors']; - - /** - * Route binder. Converts the key in the URL to the specified object (or throw 404). - * - * @param $value - * - * @throws NotFoundHttpException - * @return mixed - * - */ - public static function routeBinder(string $value): ImportJob - { - if (auth()->check()) { - $key = trim($value); - /** @var User $user */ - $user = auth()->user(); - /** @var ImportJob $importJob */ - $importJob = $user->importJobs()->where('key', $key)->first(); - if (null !== $importJob) { - return $importJob; - } - } - throw new NotFoundHttpException; - } - - /** - * @codeCoverageIgnore - * @return MorphMany - */ - public function attachments(): MorphMany - { - return $this->morphMany(Attachment::class, 'attachable'); - } - - /** - * @codeCoverageIgnore - * @return BelongsTo - */ - public function tag(): BelongsTo - { - return $this->belongsTo(Tag::class); - } - - /** - * @codeCoverageIgnore - * @return BelongsTo - */ - public function user(): BelongsTo - { - return $this->belongsTo(User::class); - } -} diff --git a/app/Models/ObjectGroup.php b/app/Models/ObjectGroup.php index 74a4dc3647..b88f396b5d 100644 --- a/app/Models/ObjectGroup.php +++ b/app/Models/ObjectGroup.php @@ -8,6 +8,13 @@ use Illuminate\Database\Eloquent\Model; /** * Class ObjectGroup + * + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\PiggyBank[] $piggyBanks + * @property-read int|null $piggy_banks_count + * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ObjectGroup newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ObjectGroup newQuery() + * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ObjectGroup query() + * @mixin \Eloquent */ class ObjectGroup extends Model { diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php index 4b9f3af2f8..03cfc64384 100644 --- a/app/Models/PiggyBank.php +++ b/app/Models/PiggyBank.php @@ -78,6 +78,9 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property-read int|null $notes_count * @property-read int|null $piggy_bank_events_count * @property-read int|null $piggy_bank_repetitions_count + * @property bool $encrypted + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\ObjectGroup[] $objectGroups + * @property-read int|null $object_groups_count */ class PiggyBank extends Model { diff --git a/app/Models/Tag.php b/app/Models/Tag.php index 1a7834771e..45c56c3368 100644 --- a/app/Models/Tag.php +++ b/app/Models/Tag.php @@ -78,6 +78,13 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property-read \Illuminate\Database\Eloquent\Collection|Location[] $locations * @property-read int|null $locations_count * @property-read int|null $transaction_journals_count + * @property \Illuminate\Support\Carbon|null $created_at + * @property \Illuminate\Support\Carbon|null $updated_at + * @property string $tagMode + * @property string|null $description + * @property float|null $latitude + * @property float|null $longitude + * @property int|null $zoomLevel */ class Tag extends Model { diff --git a/app/Providers/ImportServiceProvider.php b/app/Providers/ImportServiceProvider.php deleted file mode 100644 index 6e2fcc79a2..0000000000 --- a/app/Providers/ImportServiceProvider.php +++ /dev/null @@ -1,62 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Providers; - -use FireflyIII\Repositories\ImportJob\ImportJobRepository; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Foundation\Application; -use Illuminate\Support\ServiceProvider; - -/** - * @codeCoverageIgnore - * Class ImportServiceProvider. - * @deprecated - */ -class ImportServiceProvider extends ServiceProvider -{ - /** - * Bootstrap the application services. - */ - public function boot(): void - { - } - - /** - * Register the application services. - */ - public function register(): void - { - $this->app->bind( - ImportJobRepositoryInterface::class, - function (Application $app) { - /** @var ImportJobRepositoryInterface $repository */ - $repository = app(ImportJobRepository::class); - if ($app->auth->check()) { - $repository->setUser(auth()->user()); - } - - return $repository; - } - ); - } -} diff --git a/app/Repositories/ImportJob/ImportJobRepository.php b/app/Repositories/ImportJob/ImportJobRepository.php deleted file mode 100644 index 58b7547589..0000000000 --- a/app/Repositories/ImportJob/ImportJobRepository.php +++ /dev/null @@ -1,479 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Repositories\ImportJob; - -use Crypt; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Attachment; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\Tag; -use FireflyIII\User; -use Illuminate\Support\Collection; -use Illuminate\Support\MessageBag; -use Illuminate\Support\Str; -use Log; -use Storage; -use Symfony\Component\HttpFoundation\File\UploadedFile; - -/** - * Class ImportJobRepository. - * @codeCoverageIgnore - * @deprecated - * - */ -class ImportJobRepository implements ImportJobRepositoryInterface -{ - /** @var \Illuminate\Contracts\Filesystem\Filesystem */ - protected $uploadDisk; - /** @var int */ - private $maxUploadSize; - /** @var User */ - private $user; - - public function __construct() - { - $this->maxUploadSize = (int)config('firefly.maxUploadSize'); - $this->uploadDisk = Storage::disk('upload'); - - if ('testing' === config('app.env')) { - Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); - } - } - - /** - * Add message to job. - * - * @param ImportJob $job - * @param string $error - * - * @return ImportJob - */ - public function addErrorMessage(ImportJob $job, string $error): ImportJob - { - $errors = $job->errors; - $errors[] = $error; - $job->errors = $errors; - $job->save(); - - return $job; - } - - /** - * Append transactions to array instead of replacing them. - * - * @param ImportJob $job - * @param array $transactions - * - * @return ImportJob - * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException - */ - public function appendTransactions(ImportJob $job, array $transactions): ImportJob - { - Log::debug(sprintf('Now in appendTransactions(%s)', $job->key)); - $existingTransactions = $this->getTransactions($job); - $new = array_merge($existingTransactions, $transactions); - Log::debug(sprintf('Old transaction count: %d', count($existingTransactions))); - Log::debug(sprintf('To be added transaction count: %d', count($transactions))); - Log::debug(sprintf('New count: %d', count($new))); - $this->setTransactions($job, $new); - - return $job; - } - - /** - * @param ImportJob $job - * - * @return int - */ - public function countTransactions(ImportJob $job): int - { - $info = $job->transactions ?? []; - if (isset($info['count'])) { - return (int)$info['count']; - } - - return 0; - } - - /** - * @param string $importProvider - * - * @return ImportJob - * - * @throws FireflyException - */ - public function create(string $importProvider): ImportJob - { - $count = 0; - $importProvider = strtolower($importProvider); - - while ($count < 30) { - $key = Str::random(12); - $existing = $this->findByKey($key); - if (null === $existing) { - $importJob = ImportJob::create( - [ - 'user_id' => $this->user->id, - 'tag_id' => null, - 'provider' => $importProvider, - 'file_type' => '', - 'key' => Str::random(12), - 'status' => 'new', - 'stage' => 'new', - 'configuration' => [], - 'extended_status' => [], - 'transactions' => [], - 'errors' => [], - ] - ); - - // breaks the loop: - return $importJob; - } - ++$count; - } - throw new FireflyException('Could not create an import job with a unique key after 30 tries.'); - } - - /** - * @param int $jobId - * - * @return ImportJob|null - */ - public function find(int $jobId): ?ImportJob - { - return $this->user->importJobs()->find($jobId); - } - - /** - * @param string $key - * - * @return ImportJob|null - */ - public function findByKey(string $key): ?ImportJob - { - /** @var ImportJob $result */ - $result = $this->user->importJobs()->where('key', $key)->first(['import_jobs.*']); - if (null === $result) { - return null; - } - - return $result; - } - - /** - * Return all import jobs. - * - * @return Collection - */ - public function get(): Collection - { - return $this->user->importJobs()->get(); - } - - /** - * Return all attachments for job. - * - * @param ImportJob $job - * - * @return Collection - */ - public function getAttachments(ImportJob $job): Collection - { - return $job->attachments()->get(); - } - - /** - * Return configuration of job. - * - * @param ImportJob $job - * - * @return array - */ - public function getConfiguration(ImportJob $job): array - { - return $job->configuration; - } - - /** - * Return extended status of job. - * - * @param ImportJob $job - * - * @return array - */ - public function getExtendedStatus(ImportJob $job): array - { - $status = $job->extended_status; - if (is_array($status)) { - return $status; - } - - return []; - } - - /** - * Return transactions from attachment. - * - * @param ImportJob $job - * - * @return array - * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException - */ - public function getTransactions(ImportJob $job): array - { - // this will overwrite all transactions currently in the job. - $disk = Storage::disk('upload'); - $filename = sprintf('%s-%s.json', $job->created_at->format('Ymd'), $job->key); - $array = []; - if ($disk->exists($filename)) { - $json = $disk->get($filename); - $array = json_decode($json, true); - } - if (false === $array) { - $array = []; - } - - return $array; - } - - /** - * @param ImportJob $job - * @param array $configuration - * - * @return ImportJob - */ - public function setConfiguration(ImportJob $job, array $configuration): ImportJob - { - Log::debug('Updating configuration...'); - //Log::debug(sprintf('Incoming config for job "%s" is: ', $job->key), $configuration); - $currentConfig = $job->configuration; - $newConfig = array_merge($currentConfig, $configuration); - $job->configuration = $newConfig; - $job->save(); - - //Log::debug(sprintf('Set config of job "%s" to: ', $job->key), $newConfig); - - return $job; - } - - /** - * @param ImportJob $job - * @param string $stage - * - * @return ImportJob - */ - public function setStage(ImportJob $job, string $stage): ImportJob - { - $job->stage = $stage; - $job->save(); - - return $job; - } - - /** - * @param ImportJob $job - * @param string $status - * - * @return ImportJob - */ - public function setStatus(ImportJob $job, string $status): ImportJob - { - Log::debug(sprintf('Set status of job "%s" to "%s"', $job->key, $status)); - $job->status = $status; - $job->save(); - - return $job; - } - - /** - * @param ImportJob $job - * @param Tag $tag - * - * @return ImportJob - */ - public function setTag(ImportJob $job, Tag $tag): ImportJob - { - $job->tag()->associate($tag); - $job->save(); - - return $job; - } - - /** - * @param ImportJob $job - * @param array $transactions - * - * @return ImportJob - */ - public function setTransactions(ImportJob $job, array $transactions): ImportJob - { - // this will overwrite all transactions currently in the job. - $disk = Storage::disk('upload'); - $filename = sprintf('%s-%s.json', $job->created_at->format('Ymd'), $job->key); - $json = json_encode($transactions); - - // set count for easy access - $array = ['count' => count($transactions)]; - $job->transactions = $array; - $job->save(); - // store file. - $disk->put($filename, $json); - - return $job; - } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - } - - /** - * Handle upload for job. - * - * @param ImportJob $job - * @param string $name - * @param string $fileName - * - * @return MessageBag - */ - public function storeCLIUpload(ImportJob $job, string $name, string $fileName): MessageBag - { - $messages = new MessageBag; - if (!file_exists($fileName)) { - $messages->add('notfound', sprintf('File not found: %s', $fileName)); - - return $messages; - } - - $count = $job->attachments()->get()->filter( - function (Attachment $att) use ($name) { - return $att->filename === $name; - } - )->count(); - - if ($count > 0) {// don't upload, but also don't complain about it. - Log::error(sprintf('Detected duplicate upload. Will ignore second "%s" file.', $name)); - - return new MessageBag; - } - $content = file_get_contents($fileName); - $attachment = new Attachment; // create Attachment object. - $attachment->user()->associate($job->user); - $attachment->attachable()->associate($job); - $attachment->md5 = substr(hash('sha256', $content), 0, 32); // limit due to DB. - $attachment->filename = $name; - $attachment->mime = 'plain/txt'; - $attachment->size = strlen($content); - $attachment->uploaded = false; - $attachment->save(); - - $this->uploadDisk->put($attachment->fileName(), $content); - $attachment->uploaded = true; // update attachment - $attachment->save(); - - return new MessageBag; - } - - /** - * Handle upload for job. - * - * @param ImportJob $job - * @param string $name - * @param UploadedFile $file - * - * @return MessageBag - * @throws FireflyException - */ - public function storeFileUpload(ImportJob $job, string $name, UploadedFile $file): MessageBag - { - $messages = new MessageBag; - if ($this->validSize($file)) { - $name = e($file->getClientOriginalName()); - $messages->add('size', (string)trans('validation.file_too_large', ['name' => $name])); - - return $messages; - } - $count = $job->attachments()->get()->filter( - function (Attachment $att) use ($name) { - return $att->filename === $name; - } - )->count(); - if ($count > 0) { // don't upload, but also don't complain about it. - Log::error(sprintf('Detected duplicate upload. Will ignore second "%s" file.', $name)); - - return new MessageBag; - } - - $attachment = new Attachment; // create Attachment object. - $attachment->user()->associate($job->user); - $attachment->attachable()->associate($job); - $attachment->md5 = md5_file($file->getRealPath()); - $attachment->filename = $name; - $attachment->mime = $file->getMimeType(); - $attachment->size = $file->getSize(); - $attachment->uploaded = false; - $attachment->save(); - $fileObject = $file->openFile(); - $fileObject->rewind(); - - - if (0 === $file->getSize()) { - throw new FireflyException('Cannot upload empty or non-existent file.'); - } - - $content = $fileObject->fread($file->getSize()); - $this->uploadDisk->put($attachment->fileName(), $content); - $attachment->uploaded = true; // update attachment - $attachment->save(); - - return new MessageBag; - } - - /** - * @codeCoverageIgnore - * - * @param UploadedFile $file - * - * @return bool - */ - protected function validSize(UploadedFile $file): bool - { - $size = $file->getSize(); - - return $size > $this->maxUploadSize; - } - - /** - * @param ImportJob $job - * - * @return int - */ - public function countByTag(ImportJob $job): int - { - return $job->tag->transactionJournals->count(); - } -} diff --git a/app/Repositories/ImportJob/ImportJobRepositoryInterface.php b/app/Repositories/ImportJob/ImportJobRepositoryInterface.php deleted file mode 100644 index 4f585c78de..0000000000 --- a/app/Repositories/ImportJob/ImportJobRepositoryInterface.php +++ /dev/null @@ -1,207 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Repositories\ImportJob; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\Tag; -use FireflyIII\User; -use Illuminate\Support\Collection; -use Illuminate\Support\MessageBag; -use Symfony\Component\HttpFoundation\File\UploadedFile; - -/** - * Interface ImportJobRepositoryInterface. - * @codeCoverageIgnore - * @deprecated - */ -interface ImportJobRepositoryInterface -{ - /** - * Add message to job. - * - * @param ImportJob $job - * @param string $error - * - * @return ImportJob - */ - public function addErrorMessage(ImportJob $job, string $error): ImportJob; - - /** - * Append transactions to array instead of replacing them. - * - * @param ImportJob $job - * @param array $transactions - * - * @return ImportJob - */ - public function appendTransactions(ImportJob $job, array $transactions): ImportJob; - - /** - * @param ImportJob $job - * - * @return int - */ - public function countTransactions(ImportJob $job): int; - - /** - * @param ImportJob $job - * - * @return int - */ - public function countByTag(ImportJob $job): int; - - /** - * @param string $importProvider - * - * @return ImportJob - */ - public function create(string $importProvider): ImportJob; - - /** - * @param int $jobId - * - * @return ImportJob|null - */ - public function find(int $jobId): ?ImportJob; - - /** - * @param string $key - * - * @return ImportJob|null - */ - public function findByKey(string $key): ?ImportJob; - - /** - * Return all import jobs. - * - * @return Collection - */ - public function get(): Collection; - - /** - * Return all attachments for job. - * - * @param ImportJob $job - * - * @return Collection - */ - public function getAttachments(ImportJob $job): Collection; - - /** - * Return configuration of job. - * - * @param ImportJob $job - * - * @return array - */ - public function getConfiguration(ImportJob $job): array; - - /** - * Return extended status of job. - * - * @param ImportJob $job - * - * @return array - */ - public function getExtendedStatus(ImportJob $job): array; - - /** - * Return transactions from attachment. - * - * @param ImportJob $job - * - * @return array - */ - public function getTransactions(ImportJob $job): array; - - /** - * @param ImportJob $job - * @param array $configuration - * - * @return ImportJob - */ - public function setConfiguration(ImportJob $job, array $configuration): ImportJob; - - /** - * @param ImportJob $job - * @param string $stage - * - * @return ImportJob - */ - public function setStage(ImportJob $job, string $stage): ImportJob; - - /** - * @param ImportJob $job - * @param string $status - * - * @return ImportJob - */ - public function setStatus(ImportJob $job, string $status): ImportJob; - - /** - * @param ImportJob $job - * @param Tag $tag - * - * @return ImportJob - */ - public function setTag(ImportJob $job, Tag $tag): ImportJob; - - /** - * @param ImportJob $job - * @param array $transactions - * - * @return ImportJob - */ - public function setTransactions(ImportJob $job, array $transactions): ImportJob; - - /** - * @param User $user - */ - public function setUser(User $user); - - /** - * Store file. - * - * @param ImportJob $job - * @param string $name - * @param string $fileName - * - * @return MessageBag - */ - public function storeCLIUpload(ImportJob $job, string $name, string $fileName): MessageBag; - - /** - * Handle upload for job. - * - * @param ImportJob $job - * @param string $name - * @param UploadedFile $file - * - * @return MessageBag - * @throws FireflyException - */ - public function storeFileUpload(ImportJob $job, string $name, UploadedFile $file): MessageBag; - - -} diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php index d25545750b..118f2aeace 100644 --- a/app/Repositories/Journal/JournalRepository.php +++ b/app/Repositories/Journal/JournalRepository.php @@ -98,32 +98,6 @@ class JournalRepository implements JournalRepositoryInterface $service->destroy($journal); } - /** - * Find a journal by its hash. - * - * @param string $hash - * - * @return TransactionJournalMeta|null - */ - public function findByHash(string $hash): ?TransactionJournalMeta - { - $jsonEncode = json_encode($hash); - $hashOfHash = hash('sha256', $jsonEncode); - Log::debug(sprintf('JSON encoded hash is: %s', $jsonEncode)); - Log::debug(sprintf('Hash of hash is: %s', $hashOfHash)); - - $result = TransactionJournalMeta::withTrashed() - ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id') - ->where('hash', $hashOfHash) - ->where('name', 'import_hash_v2') - ->first(['journal_meta.*']); - if (null === $result) { - Log::debug('Result is null'); - } - - return $result; - } - /** * Find a specific journal. * diff --git a/app/Repositories/Journal/JournalRepositoryInterface.php b/app/Repositories/Journal/JournalRepositoryInterface.php index e188c69002..6c34c92337 100644 --- a/app/Repositories/Journal/JournalRepositoryInterface.php +++ b/app/Repositories/Journal/JournalRepositoryInterface.php @@ -67,18 +67,6 @@ interface JournalRepositoryInterface */ public function destroyJournal(TransactionJournal $journal): void; - - /** - * TODO move to import repository. - * - * Find a journal by its hash. - * - * @param string $hash - * - * @return TransactionJournalMeta|null - */ - public function findByHash(string $hash): ?TransactionJournalMeta; - /** * TODO Refactor to "find". * Find a specific journal. diff --git a/app/Repositories/Rule/RuleRepository.php b/app/Repositories/Rule/RuleRepository.php index c9b16dbe8a..503da28791 100644 --- a/app/Repositories/Rule/RuleRepository.php +++ b/app/Repositories/Rule/RuleRepository.php @@ -112,26 +112,6 @@ class RuleRepository implements RuleRepositoryInterface return $this->user->ruleGroups()->first(); } - /** - * Get the rules for a user tailored to the import process. - * - * @return Collection - */ - public function getForImport(): Collection - { - return Rule::distinct() - ->where('rules.user_id', $this->user->id) - ->leftJoin('rule_groups', 'rule_groups.id', '=', 'rules.rule_group_id') - ->leftJoin('rule_triggers', 'rules.id', '=', 'rule_triggers.rule_id') - ->where('rule_groups.active', 1) - ->where('rule_triggers.trigger_type', 'user_action') - ->where('rule_triggers.trigger_value', 'store-journal') - ->where('rules.active', 1) - ->orderBy('rule_groups.order', 'ASC') - ->orderBy('rules.order', 'ASC') - ->get(['rules.*', 'rule_groups.order']); - } - /** * @param RuleGroup $ruleGroup * diff --git a/app/Repositories/Rule/RuleRepositoryInterface.php b/app/Repositories/Rule/RuleRepositoryInterface.php index a979201e34..dc8e96b9a1 100644 --- a/app/Repositories/Rule/RuleRepositoryInterface.php +++ b/app/Repositories/Rule/RuleRepositoryInterface.php @@ -72,13 +72,6 @@ interface RuleRepositoryInterface */ public function getFirstRuleGroup(): RuleGroup; - /** - * Get the rules for a user tailored to the import process. - * - * @return Collection - */ - public function getForImport(): Collection; - /** * @param RuleGroup $ruleGroup * diff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.php index 8bee7968c0..0182e82bde 100644 --- a/app/Repositories/User/UserRepository.php +++ b/app/Repositories/User/UserRepository.php @@ -261,8 +261,6 @@ class UserRepository implements UserRepositoryInterface ->where('amount', '>', 0) ->whereNull('budgets.deleted_at') ->where('budgets.user_id', $user->id)->get(['budget_limits.budget_id'])->count(); - $return['import_jobs'] = $user->importJobs()->count(); - $return['import_jobs_success'] = $user->importJobs()->where('status', 'finished')->count(); $return['rule_groups'] = $user->ruleGroups()->count(); $return['rules'] = $user->rules()->count(); $return['tags'] = $user->tags()->count(); diff --git a/app/Rules/IsValidAttachmentModel.php b/app/Rules/IsValidAttachmentModel.php index 441f78b0f9..4dc3dbcf92 100644 --- a/app/Rules/IsValidAttachmentModel.php +++ b/app/Rules/IsValidAttachmentModel.php @@ -28,7 +28,6 @@ use FireflyIII\Models\Account; use FireflyIII\Models\Bill; use FireflyIII\Models\Budget; use FireflyIII\Models\Category; -use FireflyIII\Models\ImportJob; use FireflyIII\Models\PiggyBank; use FireflyIII\Models\Tag; use FireflyIII\Models\Transaction; @@ -37,7 +36,6 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; use FireflyIII\Repositories\Journal\JournalAPIRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; @@ -94,7 +92,6 @@ class IsValidAttachmentModel implements Rule Bill::class => 'validateBill', Budget::class => 'validateBudget', Category::class => 'validateCategory', - ImportJob::class => 'validateImportJob', PiggyBank::class => 'validatePiggyBank', Tag::class => 'validateTag', Transaction::class => 'validateTransaction', @@ -207,20 +204,6 @@ class IsValidAttachmentModel implements Rule return null !== $repository->findTransaction((int) $value); } - /** - * @param int $value - * - * @return bool - */ - private function validateImportJob(int $value): bool - { - /** @var ImportJobRepositoryInterface $repository */ - $repository = app(ImportJobRepositoryInterface::class); - $repository->setUser(auth()->user()); - - return null !== $repository->find($value); - } - /** * @param int $value * diff --git a/app/Services/Bunq/ApiContext.php b/app/Services/Bunq/ApiContext.php deleted file mode 100644 index 679b5b0b46..0000000000 --- a/app/Services/Bunq/ApiContext.php +++ /dev/null @@ -1,96 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Bunq; - -use bunq\Context\ApiContext as BunqApiContext; -use bunq\Context\BunqContext; -use bunq\Util\BunqEnumApiEnvironmentType; -use Exception; -use FireflyIII\Exceptions\FireflyException; -use Log; -use Tests\Object\FakeApiContext; - -/** - * Special class to hide away bunq's static initialisation methods. - * - * Class ApiContext - * - * @codeCoverageIgnore - * @deprecated - */ -class ApiContext -{ - - /** - * @param BunqEnumApiEnvironmentType $environmentType - * @param string $apiKey - * @param string $description - * @param array $permittedIps - * @param string|null $proxyUrl - * - * @return BunqApiContext|FakeApiContext - * - *@throws FireflyException - */ - public function create(BunqEnumApiEnvironmentType $environmentType, string $apiKey, string $description, array $permittedIps, string $proxyUrl = null - ) { - $permittedIps = $permittedIps ?? []; - try { - $context = BunqApiContext::create($environmentType, $apiKey, $description, $permittedIps, $proxyUrl); - } catch (Exception $e) { - $message = $e->getMessage(); - Log::error($message); - Log::error($e->getTraceAsString()); - - if (stripos($message, 'Generating a new private key failed')) { - $message = 'Could not generate key-material. Please make sure OpenSSL is installed and configured: http://bit.ly/FF3-openSSL'; - } - throw new FireflyException($message); - } - - return $context; - } - - /** - * @throws FireflyException - * - * @param string $jsonString - */ - public function fromJson(string $jsonString): void - { - try { - $apiContext = BunqApiContext::fromJson($jsonString); - BunqContext::loadApiContext($apiContext); - } catch (Exception $e) { - $message = $e->getMessage(); - Log::error($message); - Log::error($e->getTraceAsString()); - - if (stripos($message, 'Generating a new private key failed')) { - $message = 'Could not generate key-material. Please make sure OpenSSL is installed and configured: http://bit.ly/FF3-openSSL'; - } - throw new FireflyException($message); - } - } -} diff --git a/app/Services/Bunq/MonetaryAccount.php b/app/Services/Bunq/MonetaryAccount.php deleted file mode 100644 index 27cc131567..0000000000 --- a/app/Services/Bunq/MonetaryAccount.php +++ /dev/null @@ -1,59 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Bunq; - - -use bunq\Model\Generated\Endpoint\BunqResponseMonetaryAccountList; -use bunq\Model\Generated\Endpoint\MonetaryAccount as BunqMonetaryAccount; -use Exception; -use FireflyIII\Exceptions\FireflyException; - -/** - * Class MonetaryAccount - * @codeCoverageIgnore - * @deprecated - */ -class MonetaryAccount -{ - /** - * @param array $params - * @param array $customHeaders - * - * @return BunqResponseMonetaryAccountList - * @throws FireflyException - */ - public function listing(array $params = null, array $customHeaders = null): BunqResponseMonetaryAccountList - { - $params = $params ?? []; - $customHeaders = $customHeaders ?? []; - try { - $result = BunqMonetaryAccount::listing($params, $customHeaders); - } catch (Exception $e) { - throw new FireflyException($e->getMessage()); - } - - return $result; - } - -} diff --git a/app/Services/Bunq/Payment.php b/app/Services/Bunq/Payment.php deleted file mode 100644 index 1ff540e7e9..0000000000 --- a/app/Services/Bunq/Payment.php +++ /dev/null @@ -1,63 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Bunq; - - -use bunq\Model\Generated\Endpoint\BunqResponsePaymentList; -use bunq\Model\Generated\Endpoint\Payment as BunqPayment; -use Exception; -use FireflyIII\Exceptions\FireflyException; - -/** - * Class Payment - * @codeCoverageIgnore - * @deprecated - */ -class Payment -{ - /** - * @param int|null $monetaryAccountId - * @param array|null $params - * @param array|null $customHeaders - * - * @throws FireflyException - * @return BunqResponsePaymentList - */ - public function listing(int $monetaryAccountId = null, array $params = null, array $customHeaders = null): BunqResponsePaymentList - { - $monetaryAccountId = $monetaryAccountId ?? 0; - $params = $params ?? []; - $customHeaders = $customHeaders ?? []; - try { - $result = BunqPayment::listing($monetaryAccountId, $params, $customHeaders); - } catch (Exception $e) { - throw new FireflyException($e->getMessage()); - } - - return $result; - - - } - -} diff --git a/app/Services/Github/Object/GithubObject.php b/app/Services/Github/Object/GithubObject.php deleted file mode 100644 index ce2040cb16..0000000000 --- a/app/Services/Github/Object/GithubObject.php +++ /dev/null @@ -1,31 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Services\Github\Object; - -/** - * @codeCoverageIgnore - * Class GithubObject - */ -class GithubObject -{ -} diff --git a/app/Services/Github/Object/Release.php b/app/Services/Github/Object/Release.php deleted file mode 100644 index f7c2449ff5..0000000000 --- a/app/Services/Github/Object/Release.php +++ /dev/null @@ -1,94 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Github\Object; - -use Carbon\Carbon; - - -/** - * - * Class Release - * - * @SuppressWarnings(PHPMD.ShortVariable) - * - * @codeCoverageIgnore - */ -class Release extends GithubObject -{ - /** @var string */ - private $content; - /** @var string */ - private $id; - /** @var string */ - private $title; - /** @var Carbon */ - private $updated; - - /** - * Release constructor. - * - * @param array $data - */ - public function __construct(array $data) - { - $this->id = $data['id']; - $this->updated = new Carbon($data['updated']); - $this->title = $data['title']; - $this->content = $data['content']; - } - - /** - * @return string - */ - public function getContent(): string - { - return $this->content; - } - - /** - * @return string - */ - public function getId(): string - { - return $this->id; - } - - /** - * @return string - */ - public function getTitle(): string - { - return $this->title; - } - - /** - * @return Carbon - */ - public function getUpdated(): Carbon - { - return $this->updated; - } - - -} diff --git a/app/Services/Github/Request/GithubRequest.php b/app/Services/Github/Request/GithubRequest.php deleted file mode 100644 index 05424da0c3..0000000000 --- a/app/Services/Github/Request/GithubRequest.php +++ /dev/null @@ -1,34 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Github\Request; - -/** - * Interface GithubRequest - * @deprecated - */ -interface GithubRequest -{ - public function call(): void; - -} diff --git a/app/Services/Github/Request/UpdateRequest.php b/app/Services/Github/Request/UpdateRequest.php deleted file mode 100644 index 1366cb05c6..0000000000 --- a/app/Services/Github/Request/UpdateRequest.php +++ /dev/null @@ -1,96 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Github\Request; - -use Exception; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Services\Github\Object\Release; -use GuzzleHttp\Client; -use GuzzleHttp\Exception\GuzzleException; -use Log; -use RuntimeException; -use SimpleXMLElement; - -/** - * Class UpdateRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class UpdateRequest implements GithubRequest -{ - /** @var array */ - private $releases = []; - - /** - * - * @throws FireflyException - */ - public function call(): void - { - $uri = 'https://github.com/firefly-iii/firefly-iii/releases.atom'; - Log::debug(sprintf('Going to call %s', $uri)); - try { - $client = new Client(); - $res = $client->request('GET', $uri); - } catch (GuzzleException|Exception $e) { - throw new FireflyException(sprintf('Response error from Github: %s', $e->getMessage())); - } - - if (200 !== $res->getStatusCode()) { - throw new FireflyException(sprintf('Returned code %d.', $res->getStatusCode())); - } - try { - $releaseXml = new SimpleXMLElement($res->getBody()->getContents(), LIBXML_NOCDATA); - } catch (RuntimeException $e) { - Log::error(sprintf('Could not get body from github updat result: %s', $e->getMessage())); - throw new FireflyException(sprintf('Could not get body from github updat result: %s', $e->getMessage())); - } - - //fetch the products for each category - if (isset($releaseXml->entry)) { - Log::debug(sprintf('Count of entries is: %d', count($releaseXml->entry))); - foreach ($releaseXml->entry as $entry) { - $array = [ - 'id' => (string)$entry->id, - 'updated' => (string)$entry->updated, - 'title' => (string)$entry->title, - 'content' => (string)$entry->content, - ]; - Log::debug(sprintf('Found version %s', $entry->title)); - $this->releases[] = new Release($array); - } - } - } - - /** - * @return array - */ - public function getReleases(): array - { - return $this->releases; - } - - -} diff --git a/app/Services/IP/IPRetrievalInterface.php b/app/Services/IP/IPRetrievalInterface.php deleted file mode 100644 index d8d8899081..0000000000 --- a/app/Services/IP/IPRetrievalInterface.php +++ /dev/null @@ -1,40 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\IP; - -/** - * Interface IPRetrievalInterface - * @codeCoverageIgnore - * @deprecated - */ -interface IPRetrievalInterface -{ - - /** - * Returns the user's IP address. - * - * @return null|string - */ - public function getIP(): ?string; -} diff --git a/app/Services/IP/IpifyOrg.php b/app/Services/IP/IpifyOrg.php deleted file mode 100644 index 1bfb54e1f0..0000000000 --- a/app/Services/IP/IpifyOrg.php +++ /dev/null @@ -1,81 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\IP; - -use Exception; -use GuzzleHttp\Client; -use GuzzleHttp\Exception\GuzzleException; -use Log; -use RuntimeException; - -/** - * Class IpifyOrg - * - * @codeCoverageIgnore - * @deprecated - */ -class IpifyOrg implements IPRetrievalInterface -{ - /** - * Constructor. - */ - public function __construct() - { - if ('testing' === config('app.env')) { - Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); - } - } - - /** - * Returns the user's IP address. - * - * @noinspection MultipleReturnStatementsInspection - * @return null|string - */ - public function getIP(): ?string - { - try { - $client = new Client; - $res = $client->request('GET', 'https://api.ipify.org'); - } catch (GuzzleException|Exception $e) { - Log::warning(sprintf('The ipify.org service could not retrieve external IP: %s', $e->getMessage())); - Log::warning($e->getTraceAsString()); - - return null; - } - if (200 !== $res->getStatusCode()) { - Log::warning(sprintf('Could not retrieve external IP: %d', $res->getStatusCode())); - - return null; - } - try { - $body = (string)$res->getBody()->getContents(); - } catch (RuntimeException $e) { - Log::error(sprintf('Could not get body from ipify.org result: %s', $e->getMessage())); - $body = null; - } - - return $body; - } -} diff --git a/app/Services/Spectre/Exception/DuplicatedCustomerException.php b/app/Services/Spectre/Exception/DuplicatedCustomerException.php deleted file mode 100644 index 8beb4cc17d..0000000000 --- a/app/Services/Spectre/Exception/DuplicatedCustomerException.php +++ /dev/null @@ -1,34 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Exception; - -/** - * @codeCoverageIgnore - * Class DuplicatedCustomerException - * @deprecated - */ -class DuplicatedCustomerException extends SpectreException -{ - -} diff --git a/app/Services/Spectre/Exception/SpectreException.php b/app/Services/Spectre/Exception/SpectreException.php deleted file mode 100644 index 73e0e22c81..0000000000 --- a/app/Services/Spectre/Exception/SpectreException.php +++ /dev/null @@ -1,36 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Exception; - -use Exception; - -/** - * @codeCoverageIgnore - * Class SpectreException - * @deprecated - */ -class SpectreException extends Exception -{ - -} diff --git a/app/Services/Spectre/Exception/WrongRequestFormatException.php b/app/Services/Spectre/Exception/WrongRequestFormatException.php deleted file mode 100644 index 5dce219a97..0000000000 --- a/app/Services/Spectre/Exception/WrongRequestFormatException.php +++ /dev/null @@ -1,34 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Exception; - -/** - * @codeCoverageIgnore - * Class WrongRequestFormatException - * @deprecated - */ -class WrongRequestFormatException extends SpectreException -{ - -} diff --git a/app/Services/Spectre/Object/Account.php b/app/Services/Spectre/Object/Account.php deleted file mode 100644 index 2da7f1fd11..0000000000 --- a/app/Services/Spectre/Object/Account.php +++ /dev/null @@ -1,145 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Object; - -use Carbon\Carbon; - -/** - * Class Account - * - * @codeCoverageIgnore - * @SuppressWarnings(PHPMD.ShortVariable) - * @deprecated - */ -class Account extends SpectreObject -{ - /** @var float */ - private $balance; - /** @var Carbon */ - private $createdAt; - /** @var string */ - private $currencyCode; - /** @var array */ - private $extra = []; - /** @var int */ - private $id; - /** @var int */ - private $loginId; - /** @var string */ - private $name; - /** @var string */ - private $nature; - /** @var Carbon */ - private $updatedAt; - - /** - * Account constructor. - * - * @param array $data - */ - public function __construct(array $data) - { - $this->id = (int)$data['id']; - $this->loginId = $data['login_id']; - $this->currencyCode = $data['currency_code']; - $this->balance = $data['balance']; - $this->name = $data['name']; - $this->nature = $data['nature']; - $this->createdAt = new Carbon($data['created_at']); - $this->updatedAt = new Carbon($data['updated_at']); - $extraArray = is_array($data['extra']) ? $data['extra'] : []; - foreach ($extraArray as $key => $value) { - $this->extra[$key] = $value; - } - } - - /** - * @return float - */ - public function getBalance(): float - { - return $this->balance; - } - - /** - * @return string - */ - public function getCurrencyCode(): string - { - return $this->currencyCode; - } - - /** - * @return array - */ - public function getExtra(): array - { - return $this->extra; - } - - /** - * @return int - */ - public function getId(): int - { - return $this->id; - } - - /** - * @return string - */ - public function getName(): string - { - return $this->name; - } - - /** - * @return string - */ - public function getNature(): string - { - return $this->nature; - } - - /** - * @return array - */ - public function toArray(): array - { - $array = [ - 'balance' => $this->balance, - 'created_at' => $this->createdAt->toIso8601String(), - 'currency_code' => $this->currencyCode, - 'extra' => $this->extra, - 'id' => $this->id, - 'login_id' => $this->loginId, - 'name' => $this->name, - 'nature' => $this->nature, - 'updated_at' => $this->updatedAt->toIso8601String(), - ]; - - return $array; - } - -} diff --git a/app/Services/Spectre/Object/Attempt.php b/app/Services/Spectre/Object/Attempt.php deleted file mode 100644 index 434ecfbbd8..0000000000 --- a/app/Services/Spectre/Object/Attempt.php +++ /dev/null @@ -1,214 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Object; - -use Carbon\Carbon; - -/** - * - * Class Attempt - * - * @codeCoverageIgnore - * @SuppressWarnings(PHPMD.ShortVariable) - * @SuppressWarnings(PHPMD.TooManyFields) - * @deprecated - */ -class Attempt extends SpectreObject -{ - /** @var string */ - private $apiMode; - /** @var int */ - private $apiVersion; - /** @var bool */ - private $automaticFetch; - /** @var bool */ - private $categorize; - /** @var Carbon */ - private $consentGivenAt; - /** @var array */ - private $consentTypes; - /** @var Carbon */ - private $createdAt; - /** @var array */ - private $customFields; - /** @var bool */ - private $dailyRefresh; - /** @var string */ - private $deviceType; - /** @var array */ - private $excludeAccounts; - /** @var Carbon */ - private $failAt; - /** @var string */ - private $failErrorClass; - /** @var string */ - private $failMessage; - /** @var array */ - private $fetchScopes; - /** @var bool */ - private $finished; - /** @var bool */ - private $finishedRecent; - /** @var Carbon */ - private $fromDate; - /** @var int */ - private $id; - /** @var bool */ - private $interactive; - /** @var string */ - private $locale; - /** @var bool */ - private $partial; - /** @var string */ - private $remoteIp; - /** @var bool */ - private $showConsentInformation; - /** @var array */ - private $stages; - /** @var bool */ - private $storeCredentials; - /** @var Carbon */ - private $successAt; - /** @var Carbon */ - private $toDate; - /** @var Carbon */ - private $updatedAt; // undocumented - /** @var string */ - private $userAgent; - - /** - * Attempt constructor. - * - * @param array $data - */ - public function __construct(array $data) - { - $this->apiMode = $data['api_mode']; - $this->apiVersion = $data['api_version']; - $this->automaticFetch = $data['automatic_fetch']; - $this->categorize = $data['categorize']; - $this->createdAt = new Carbon($data['created_at']); - $this->consentGivenAt = new Carbon($data['consent_given_at']); - $this->consentTypes = $data['consent_types']; - $this->customFields = $data['custom_fields']; - $this->dailyRefresh = $data['daily_refresh']; - $this->deviceType = $data['device_type']; - $this->userAgent = $data['user_agent'] ?? ''; - $this->remoteIp = $data['remote_ip']; - $this->excludeAccounts = $data['exclude_accounts']; - $this->failAt = new Carbon($data['fail_at']); - $this->failErrorClass = $data['fail_error_class']; - $this->failMessage = $data['fail_message']; - $this->fetchScopes = $data['fetch_scopes']; - $this->finished = $data['finished']; - $this->finishedRecent = $data['finished_recent']; - $this->fromDate = new Carbon($data['from_date']); - $this->id = $data['id']; - $this->interactive = $data['interactive']; - $this->locale = $data['locale']; - $this->partial = $data['partial']; - $this->showConsentInformation = $data['show_consent_confirmation']; - $this->stages = $data['stages'] ?? []; - $this->storeCredentials = $data['store_credentials']; - $this->successAt = new Carbon($data['success_at']); - $this->toDate = new Carbon($data['to_date']); - $this->updatedAt = new Carbon($data['updated_at']); - - } - - /** - * @return Carbon - */ - public function getCreatedAt(): Carbon - { - return $this->createdAt; - } - - /** - * @return Carbon - */ - public function getFailAt(): Carbon - { - return $this->failAt; - } - - /** - * @return null|string - */ - public function getFailErrorClass(): ?string - { - return $this->failErrorClass; - } - - /** - * @return null|string - */ - public function getFailMessage(): ?string - { - return $this->failMessage; - } - - /** - * @return array - */ - public function toArray(): array - { - $array = [ - 'api_mode' => $this->apiMode, - 'api_version' => $this->apiVersion, - 'automatic_fetch' => $this->automaticFetch, - 'categorize' => $this->categorize, - 'created_at' => $this->createdAt->toIso8601String(), - 'consent_given_at' => $this->consentGivenAt->toIso8601String(), - 'consent_types' => $this->consentTypes, - 'custom_fields' => $this->customFields, - 'daily_refresh' => $this->dailyRefresh, - 'device_type' => $this->deviceType, - 'user_agent' => $this->userAgent, - 'remote_ip' => $this->remoteIp, - 'exclude_accounts' => $this->excludeAccounts, - 'fail_at' => $this->failAt->toIso8601String(), - 'fail_error_class' => $this->failErrorClass, - 'fail_message' => $this->failMessage, - 'fetch_scopes' => $this->fetchScopes, - 'finished' => $this->finished, - 'finished_recent' => $this->finishedRecent, - 'from_date' => $this->fromDate->toIso8601String(), - 'id' => $this->id, - 'interactive' => $this->interactive, - 'locale' => $this->locale, - 'partial' => $this->partial, - 'show_consent_confirmation' => $this->showConsentInformation, - 'stages' => $this->stages, - 'store_credentials' => $this->storeCredentials, - 'success_at' => $this->successAt->toIso8601String(), - 'to_date' => $this->toDate->toIso8601String(), - 'updated_at' => $this->updatedAt->toIso8601String(), - ]; - - return $array; - } - - -} diff --git a/app/Services/Spectre/Object/Customer.php b/app/Services/Spectre/Object/Customer.php deleted file mode 100644 index b526cd4195..0000000000 --- a/app/Services/Spectre/Object/Customer.php +++ /dev/null @@ -1,112 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Object; - -/** - * Class Customer - * - * @codeCoverageIgnore - * @SuppressWarnings(PHPMD.ShortVariable) - * @deprecated - */ -class Customer extends SpectreObject -{ - /** @var int */ - private $id; - /** @var string */ - private $identifier; - /** @var string */ - private $secret; - - /** - * Customer constructor. - * - * @param array $data - */ - public function __construct(array $data) - { - $this->id = (int)$data['id']; - $this->identifier = $data['identifier']; - $this->secret = $data['secret']; - } - - /** - * @return int - */ - public function getId(): int - { - return $this->id; - } - - /** - * @param int $id - */ - public function setId(int $id): void - { - $this->id = $id; - } - - /** - * @return string - */ - public function getIdentifier(): string - { - return $this->identifier; - } - - /** - * @param string $identifier - */ - public function setIdentifier(string $identifier): void - { - $this->identifier = $identifier; - } - - /** - * @return string - */ - public function getSecret(): string - { - return $this->secret; - } - - /** - * @param string $secret - */ - public function setSecret(string $secret): void - { - $this->secret = $secret; - } - - /** - * @return array - */ - public function toArray(): array - { - return [ - 'id' => $this->id, - 'identifier' => $this->identifier, - 'secret' => $this->secret, - ]; - } -} diff --git a/app/Services/Spectre/Object/Holder.php b/app/Services/Spectre/Object/Holder.php deleted file mode 100644 index 8c2e739342..0000000000 --- a/app/Services/Spectre/Object/Holder.php +++ /dev/null @@ -1,52 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Object; - -/** - * Class Holder - * - * @codeCoverageIgnore - * @deprecated - */ -class Holder extends SpectreObject -{ - /** - * Holder constructor. - * - * @param array $data - * - */ - public function __construct(array $data) - { - - } - - /** - * @return array - */ - public function toArray(): array - { - return []; - } -} diff --git a/app/Services/Spectre/Object/Login.php b/app/Services/Spectre/Object/Login.php deleted file mode 100644 index 55d176cb24..0000000000 --- a/app/Services/Spectre/Object/Login.php +++ /dev/null @@ -1,191 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Object; - -use Carbon\Carbon; - - -/** - * Class Login - * - * @codeCoverageIgnore - * @SuppressWarnings(PHPMD.ShortVariable) - * @SuppressWarnings(PHPMD.TooManyFields) - * @deprecated - */ -class Login extends SpectreObject -{ - /** @var Carbon */ - private $consentGivenAt; - /** @var array */ - private $consentTypes; - /** @var string */ - private $countryCode; - /** @var Carbon */ - private $createdAt; - /** @var int */ - private $customerId; - /** @var bool */ - private $dailyRefresh; - /** @var Holder */ - private $holderInfo; - /** @var int */ - private $id; - /** @var Attempt */ - private $lastAttempt; - /** @var Carbon */ - private $lastSuccessAt; - /** @var Carbon */ - private $nextRefreshPossibleAt; - /** @var string */ - private $providerCode; - /** @var int */ - private $providerId; - /** @var string */ - private $providerName; - /** @var bool */ - private $showConsentConfirmation; - /** @var string */ - private $status; - /** @var bool */ - private $storeCredentials; - /** @var Carbon */ - private $updatedAt; - - /** - * Login constructor. - * - * @param array $data - */ - public function __construct(array $data) - { - $this->consentGivenAt = new Carbon($data['consent_given_at']); - $this->consentTypes = $data['consent_types']; - $this->countryCode = $data['country_code']; - $this->createdAt = new Carbon($data['created_at']); - $this->updatedAt = new Carbon($data['updated_at']); - $this->customerId = $data['customer_id']; - $this->dailyRefresh = $data['daily_refresh']; - $this->holderInfo = new Holder($data['holder_info']); - $this->id = (int)$data['id']; - $this->lastAttempt = new Attempt($data['last_attempt']); - $this->lastSuccessAt = new Carbon($data['last_success_at']); - $this->nextRefreshPossibleAt = new Carbon($data['next_refresh_possible_at']); - $this->providerCode = $data['provider_code']; - $this->providerId = $data['provider_id']; - $this->providerName = $data['provider_name']; - $this->showConsentConfirmation = $data['show_consent_confirmation']; - $this->status = $data['status']; - $this->storeCredentials = $data['store_credentials']; - - } - - /** - * @return string - */ - public function getCountryCode(): string - { - return $this->countryCode; - } - - /** - * @return int - */ - public function getId(): int - { - return $this->id; - } - - /** - * @return Attempt - */ - public function getLastAttempt(): Attempt - { - return $this->lastAttempt; - } - - /** - * @return Carbon - */ - public function getLastSuccessAt(): Carbon - { - return $this->lastSuccessAt; - } - - /** - * @return string - */ - public function getProviderName(): string - { - return $this->providerName; - } - - /** - * @return string - */ - public function getStatus(): string - { - return $this->status; - } - - /** - * @return Carbon - */ - public function getUpdatedAt(): Carbon - { - return $this->updatedAt; - } - - /** - * @return array - */ - public function toArray(): array - { - $array = [ - 'consent_given_at' => $this->consentGivenAt->toIso8601String(), - 'consent_types' => $this->consentTypes, - 'country_code' => $this->countryCode, - 'created_at' => $this->createdAt->toIso8601String(), - 'updated_at' => $this->updatedAt->toIso8601String(), - 'customer_id' => $this->customerId, - 'daily_refresh' => $this->dailyRefresh, - 'holder_info' => $this->holderInfo->toArray(), - 'id' => $this->id, - 'last_attempt' => $this->lastAttempt->toArray(), - 'last_success_at' => $this->lastSuccessAt->toIso8601String(), - 'next_refresh_possible_at' => $this->nextRefreshPossibleAt->toIso8601String(), - 'provider_code' => $this->providerCode, - 'provider_id' => $this->providerId, - 'provider_name' => $this->providerName, - 'show_consent_confirmation' => $this->showConsentConfirmation, - 'status' => $this->status, - 'store_credentials' => $this->storeCredentials, - - ]; - - return $array; - } - - -} diff --git a/app/Services/Spectre/Object/SpectreObject.php b/app/Services/Spectre/Object/SpectreObject.php deleted file mode 100644 index 41030b0ff6..0000000000 --- a/app/Services/Spectre/Object/SpectreObject.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Object; - -/** - * @codeCoverageIgnore - * Class SpectreObject - * @deprecated - */ -class SpectreObject -{ -} diff --git a/app/Services/Spectre/Object/Token.php b/app/Services/Spectre/Object/Token.php deleted file mode 100644 index f344c2c6be..0000000000 --- a/app/Services/Spectre/Object/Token.php +++ /dev/null @@ -1,90 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Object; - -use Carbon\Carbon; - -/** - * @codeCoverageIgnore - * Class Token - * @deprecated - */ -class Token extends SpectreObject -{ - /** @var string */ - private $connectUrl; - /** @var Carbon */ - private $expiresAt; - /** @var string */ - private $token; - - /** - * Token constructor. - * - * @param array $data - */ - public function __construct(array $data) - { - $this->token = $data['token']; - $this->expiresAt = new Carbon($data['expires_at']); - $this->connectUrl = $data['connect_url']; - } - - /** - * @return string - */ - public function getConnectUrl(): string - { - return $this->connectUrl; - } - - /** - * @return Carbon - */ - public function getExpiresAt(): Carbon - { - return $this->expiresAt; - } - - /** - * @return string - */ - public function getToken(): string - { - return $this->token; - } - - /** - * - */ - public function toArray(): array - { - return [ - 'connect_url' => $this->connectUrl, - 'expires_at' => $this->expiresAt->toW3cString(), - 'token' => $this->token, - ]; - } - -} diff --git a/app/Services/Spectre/Object/Transaction.php b/app/Services/Spectre/Object/Transaction.php deleted file mode 100644 index 62fc784d2c..0000000000 --- a/app/Services/Spectre/Object/Transaction.php +++ /dev/null @@ -1,227 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Object; - -use Carbon\Carbon; - -/** - * Class Transaction - * - * @codeCoverageIgnore - * @deprecated - * - * @SuppressWarnings(PHPMD.ShortVariable) - */ -class Transaction extends SpectreObject -{ - /** @var int */ - private $accountId; - /** @var string */ - private $amount; - /** @var string */ - private $category; - /** @var Carbon */ - private $createdAt; - /** @var string */ - private $currencyCode; - /** @var string */ - private $description; - /** @var bool */ - private $duplicated; - /** @var TransactionExtra */ - private $extra; - /** @var int */ - private $id; - /** @var Carbon */ - private $madeOn; - /** @var string */ - private $mode; - /** @var string */ - private $status; - /** @var Carbon */ - private $updatedAt; - - /** - * Transaction constructor. - * - * @param array $data - */ - public function __construct(array $data) - { - $this->id = (int)$data['id']; - $this->mode = $data['mode']; - $this->status = $data['status']; - $this->madeOn = new Carbon($data['made_on']); - $this->amount = $data['amount']; - $this->currencyCode = $data['currency_code']; - $this->description = $data['description']; - $this->category = $data['category']; - $this->duplicated = $data['duplicated']; - $this->extra = new TransactionExtra($data['extra'] ?? []); - $this->accountId = $data['account_id']; - $this->createdAt = new Carbon($data['created_at']); - $this->updatedAt = new Carbon($data['updated_at']); - } - - /** - * @return string - */ - public function getAmount(): string - { - return (string)$this->amount; - } - - /** - * @return string - */ - public function getCategory(): string - { - return $this->category; - } - - /** - * @return string - */ - public function getCurrencyCode(): string - { - return $this->currencyCode; - } - - /** - * @return string - */ - public function getDescription(): string - { - return $this->description; - } - - /** - * @return TransactionExtra|null - */ - public function getExtra(): ?TransactionExtra - { - return $this->extra; - } - - /** - * @return string - */ - public function getHash(): string - { - $array = [ - 'id' => $this->id, - 'mode' => $this->mode, - 'status' => $this->status, - 'made_on' => $this->madeOn->toIso8601String(), - 'amount' => $this->amount, - 'currency_code' => $this->currencyCode, - 'description' => $this->description, - 'category' => $this->category, - 'duplicated' => $this->duplicated, - 'extra' => $this->extra->toArray(), - 'account_id' => $this->accountId, - 'created_at' => $this->createdAt->toIso8601String(), - 'updated_at' => $this->updatedAt->toIso8601String(), - ]; - - return hash('sha256', json_encode($array)); - } - - /** - * @return int - */ - public function getId(): int - { - return $this->id; - } - - /** - * @return Carbon - */ - public function getMadeOn(): Carbon - { - return $this->madeOn; - } - - /** - * @return string - */ - public function getMode(): string - { - return $this->mode; - } - - /** - * Get opposing account data. - * - * @return array - * - */ - public function getOpposingAccountData(): array - { - $data = [ - 'name' => null, - 'iban' => null, - 'number' => null, - 'bic' => null, - ]; - $extra = $this->getExtra(); - if (null !== $extra) { - $arr = $extra->toArray(); - foreach ($arr as $key => $value) { - switch ($key) { - case 'account_number': - $data['number'] = $value; - $data['name'] = $data['name'] ?? (string)trans('import.spectre_account_with_number', ['number' => $value]); - break; - case 'payee': - $data['name'] = $value; - break; - default: - break; - } - } - } - - return $data; - } - - /** - * @return string - */ - public function getStatus(): string - { - return $this->status; - } - - /** - * @return bool - */ - public function isDuplicated(): bool - { - return $this->duplicated; - } - - -} diff --git a/app/Services/Spectre/Object/TransactionExtra.php b/app/Services/Spectre/Object/TransactionExtra.php deleted file mode 100644 index 160b1247a0..0000000000 --- a/app/Services/Spectre/Object/TransactionExtra.php +++ /dev/null @@ -1,174 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Object; - -use Carbon\Carbon; - -/** - * Class TransactionExtra - * - * @SuppressWarnings(PHPMD.TooManyFields) - * @SuppressWarnings(PHPMD.ShortVariable) - * @codeCoverageIgnore - * @deprecated - */ -class TransactionExtra extends SpectreObject -{ - /** @var string */ - private $accountBalanceSnapshot; - /** @var string */ - private $accountNumber; - /** @var string */ - private $additional; - /** @var string */ - private $assetAmount; - /** @var string */ - private $assetCode; - /** @var string */ - private $categorizationConfidence; - /** @var string */ - private $checkNumber; - /** @var string */ - private $customerCategoryCode; - /** @var string */ - private $customerCategoryName; - /** @var string */ - private $id; - /** @var string */ - private $information; - /** @var string */ - private $mcc; - /** @var string */ - private $originalAmount; - /** @var string */ - private $originalCategory; - /** @var string */ - private $originalCurrencyCode; - /** @var string */ - private $originalSubCategory; - /** @var string */ - private $payee; - /** @var bool */ - private $possibleDuplicate; - /** @var Carbon */ - private $postingDate; - /** @var Carbon */ - private $postingTime; - /** @var string */ - private $recordNumber; - /** @var array */ - private $tags; - /** @var Carbon */ - private $time; - /** @var string */ - private $type; - /** @var string */ - private $unitPrice; - /** @var string */ - private $units; - - /** - * TransactionExtra constructor. - * - * @param array $data - */ - public function __construct(array $data) - { - $this->id = $data['id'] ?? null; - $this->recordNumber = $data['record_number'] ?? null; - $this->information = $data['information'] ?? null; - $this->time = isset($data['time']) ? new Carbon($data['time']) : null; - $this->postingDate = isset($data['posting_date']) ? new Carbon($data['posting_date']) : null; - $this->postingTime = isset($data['posting_time']) ? new Carbon($data['posting_time']) : null; - $this->accountNumber = $data['account_number'] ?? null; - $this->originalAmount = $data['original_amount'] ?? null; - $this->originalCurrencyCode = $data['original_currency_code'] ?? null; - $this->assetCode = $data['asset_code'] ?? null; - $this->assetAmount = $data['asset_amount'] ?? null; - $this->originalCategory = $data['original_category'] ?? null; - $this->originalSubCategory = $data['original_subcategory'] ?? null; - $this->customerCategoryCode = $data['customer_category_code'] ?? null; - $this->customerCategoryName = $data['customer_category_name'] ?? null; - $this->possibleDuplicate = $data['possible_duplicate'] ?? null; - $this->tags = $data['tags'] ?? null; - $this->mcc = $data['mcc'] ?? null; - $this->payee = $data['payee'] ?? null; - $this->type = $data['type'] ?? null; - $this->checkNumber = $data['check_number'] ?? null; - $this->units = $data['units'] ?? null; - $this->additional = $data['additional'] ?? null; - $this->unitPrice = $data['unit_price'] ?? null; - $this->accountBalanceSnapshot = $data['account_balance_snapshot'] ?? null; - $this->categorizationConfidence = $data['categorization_confidence'] ?? null; - } - - /** - * @return string|null - */ - public function getId(): ?string - { - return $this->id; - } - - /** - * @return array - */ - public function toArray(): array - { - - $array = [ - 'id' => $this->id, - 'record_number' => $this->recordNumber, - 'information' => $this->information, - 'time' => null === $this->time ? null : $this->time->toIso8601String(), - 'posting_date' => null === $this->postingDate ? null : $this->postingDate->toIso8601String(), - 'posting_time' => null === $this->postingTime ? null : $this->postingTime->toIso8601String(), - 'account_number' => $this->accountNumber, - 'original_amount' => $this->originalAmount, - 'original_currency_code' => $this->originalCurrencyCode, - 'asset_code' => $this->assetCode, - 'asset_amount' => $this->assetAmount, - 'original_category' => $this->originalCategory, - 'original_subcategory' => $this->originalSubCategory, - 'customer_category_code' => $this->customerCategoryCode, - 'customer_category_name' => $this->customerCategoryName, - 'possible_duplicate' => $this->possibleDuplicate, - 'tags' => $this->tags, - 'mcc' => $this->mcc, - 'payee' => $this->payee, - 'type' => $this->type, - 'check_number' => $this->checkNumber, - 'units' => $this->units, - 'additional' => $this->additional, - 'unit_price' => $this->unitPrice, - 'account_balance_snapshot' => $this->accountBalanceSnapshot, - 'categorization_confidence' => $this->categorizationConfidence, - ]; - - - return $array; - } - - -} diff --git a/app/Services/Spectre/Request/CreateTokenRequest.php b/app/Services/Spectre/Request/CreateTokenRequest.php deleted file mode 100644 index ff47245fd5..0000000000 --- a/app/Services/Spectre/Request/CreateTokenRequest.php +++ /dev/null @@ -1,95 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Request; - -use FireflyIII\Services\Spectre\Object\Customer; -use FireflyIII\Services\Spectre\Object\Token; - - -/** - * Class CreateTokenRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class CreateTokenRequest extends SpectreRequest -{ - /** @var Customer */ - private $customer; - - /** @var Token */ - private $token; - - /** @var string */ - private $uri; - - /** - * - * @throws \FireflyIII\Exceptions\FireflyException - */ - public function call(): void - { - // add mandatory fields to login object - $data = [ - 'data' => [ - 'customer_id' => $this->customer->getId(), - 'fetch_scopes' => ['accounts', 'transactions'], - 'daily_refresh' => true, - 'include_fake_providers' => true, - 'show_consent_confirmation' => true, - 'credentials_strategy' => 'ask', - 'return_to' => $this->uri, - ], - ]; - $uri = '/api/v4/tokens/create'; - $response = $this->sendSignedSpectrePost($uri, $data); - $this->token = new Token($response['data']); - } - - /** - * @return Token - */ - public function getToken(): Token - { - return $this->token; - } - - /** - * @param Customer $customer - */ - public function setCustomer(Customer $customer): void - { - $this->customer = $customer; - } - - /** - * @param string $uri - */ - public function setUri(string $uri): void - { - $this->uri = $uri; - } - - -} diff --git a/app/Services/Spectre/Request/ListAccountsRequest.php b/app/Services/Spectre/Request/ListAccountsRequest.php deleted file mode 100644 index 95f870018e..0000000000 --- a/app/Services/Spectre/Request/ListAccountsRequest.php +++ /dev/null @@ -1,93 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Request; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Services\Spectre\Object\Account; -use FireflyIII\Services\Spectre\Object\Login; -use Log; - -/** - * Class ListAccountsRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class ListAccountsRequest extends SpectreRequest -{ - /** @var array */ - private $accounts = []; - /** @var Login */ - private $login; - - /** - * @throws FireflyException - * - */ - public function call(): void - { - $hasNextPage = true; - $nextId = 0; - while ($hasNextPage) { - Log::debug(sprintf('Now calling ListAccountsRequest for next_id %d', $nextId)); - $parameters = ['from_id' => $nextId, 'login_id' => $this->login->getId()]; - $uri = '/api/v4/accounts?' . http_build_query($parameters); - $response = $this->sendSignedSpectreGet($uri, []); - - // count entries: - Log::debug(sprintf('Found %d entries in data-array', count($response['data']))); - - // extract next ID - $hasNextPage = false; - if (isset($response['meta']['next_id']) && (int)$response['meta']['next_id'] > $nextId) { - $hasNextPage = true; - $nextId = $response['meta']['next_id']; - Log::debug(sprintf('Next ID is now %d.', $nextId)); - } - - // store customers: - foreach ($response['data'] as $accountArray) { - $this->accounts[] = new Account($accountArray); - } - } - } - - /** - * @return array - */ - public function getAccounts(): array - { - return $this->accounts; - } - - /** - * @param Login $login - */ - public function setLogin(Login $login): void - { - $this->login = $login; - } - - -} diff --git a/app/Services/Spectre/Request/ListCustomersRequest.php b/app/Services/Spectre/Request/ListCustomersRequest.php deleted file mode 100644 index 6fd6a823c7..0000000000 --- a/app/Services/Spectre/Request/ListCustomersRequest.php +++ /dev/null @@ -1,83 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Request; - -use FireflyIII\Services\Spectre\Object\Customer; -use Log; - - -/** - * Class ListCustomersRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class ListCustomersRequest extends SpectreRequest -{ - /** @var array */ - private $customers = []; - - /** - * - * @throws \FireflyIII\Exceptions\FireflyException - * - */ - public function call(): void - { - $hasNextPage = true; - $nextId = 0; - while ($hasNextPage) { - Log::debug(sprintf('Now calling ListCustomersRequest for next_id %d', $nextId)); - $parameters = ['from_id' => $nextId]; - $uri = '/api/v4/customers/?' . http_build_query($parameters); - $response = $this->sendSignedSpectreGet($uri, []); - - // count entries: - Log::debug(sprintf('Found %d entries in data-array', count($response['data']))); - - // extract next ID - $hasNextPage = false; - if (isset($response['meta']['next_id']) && (int)$response['meta']['next_id'] > $nextId) { - $hasNextPage = true; - $nextId = $response['meta']['next_id']; - Log::debug(sprintf('Next ID is now %d.', $nextId)); - } - - // store customers: - foreach ($response['data'] as $customerArray) { - $this->customers[] = new Customer($customerArray); - } - } - } - - /** - * @return array - */ - public function getCustomers(): array - { - return $this->customers; - } - - -} diff --git a/app/Services/Spectre/Request/ListLoginsRequest.php b/app/Services/Spectre/Request/ListLoginsRequest.php deleted file mode 100644 index 9c310f7dd4..0000000000 --- a/app/Services/Spectre/Request/ListLoginsRequest.php +++ /dev/null @@ -1,103 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Request; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Services\Spectre\Object\Customer; -use FireflyIII\Services\Spectre\Object\Login; -use Illuminate\Support\Collection; -use Log; - -/** - * Class ListLoginsRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class ListLoginsRequest extends SpectreRequest -{ - /** @var Customer */ - private $customer; - - /** @var array */ - private $logins = []; - - /** - * @throws FireflyException - * - */ - public function call(): void - { - $hasNextPage = true; - $nextId = 0; - while ($hasNextPage) { - Log::debug(sprintf('Now calling ListLoginsRequest for next_id %d', $nextId)); - $parameters = ['from_id' => $nextId, 'customer_id' => $this->customer->getId()]; - $uri = '/api/v4/logins/?' . http_build_query($parameters); - $response = $this->sendSignedSpectreGet($uri, []); - - // count entries: - Log::debug(sprintf('Found %d entries in data-array', count($response['data']))); - - // extract next ID - $hasNextPage = false; - if (isset($response['meta']['next_id']) && (int)$response['meta']['next_id'] > $nextId) { - $hasNextPage = true; - $nextId = $response['meta']['next_id']; - Log::debug(sprintf('Next ID is now %d.', $nextId)); - } - $collection = new Collection; - // store logins: - /** @var array $loginArray */ - foreach ($response['data'] as $loginArray) { - $collection->push(new Login($loginArray)); - } - // sort logins by date created: - $sorted = $collection->sortByDesc( - static function (Login $login) { - return $login->getUpdatedAt()->timestamp; - } - ); - $this->logins = $sorted->toArray(); - } - } - - /** - * @return array - */ - public function getLogins(): array - { - return $this->logins; - } - - /** - * @param Customer $customer - */ - public function setCustomer(Customer $customer): void - { - $this->customer = $customer; - } - - -} diff --git a/app/Services/Spectre/Request/ListTransactionsRequest.php b/app/Services/Spectre/Request/ListTransactionsRequest.php deleted file mode 100644 index 015599273a..0000000000 --- a/app/Services/Spectre/Request/ListTransactionsRequest.php +++ /dev/null @@ -1,94 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Request; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Services\Spectre\Object\Account; -use FireflyIII\Services\Spectre\Object\Transaction; -use Log; - -/** - * Class ListTransactionsRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class ListTransactionsRequest extends SpectreRequest -{ - /** @var Account */ - private $account; - /** @var array */ - private $transactions = []; - - /** - * @throws FireflyException - * - */ - public function call(): void - { - $hasNextPage = true; - $nextId = 0; - while ($hasNextPage) { - Log::debug(sprintf('Now calling ListTransactionsRequest for next_id %d', $nextId)); - $parameters = ['from_id' => $nextId, 'account_id' => $this->account->getId()]; - $uri = '/api/v4/transactions?' . http_build_query($parameters); - $response = $this->sendSignedSpectreGet($uri, []); - - // count entries: - Log::debug(sprintf('Found %d entries in data-array', count($response['data']))); - - // extract next ID - $hasNextPage = false; - if (isset($response['meta']['next_id']) && (int)$response['meta']['next_id'] > $nextId) { - $hasNextPage = true; - $nextId = $response['meta']['next_id']; - Log::debug(sprintf('Next ID is now %d.', $nextId)); - } - - // store customers: - foreach ($response['data'] as $transactionArray) { - $this->transactions[] = new Transaction($transactionArray); - } - } - } - - /** - * @return array - */ - public function getTransactions(): array - { - return $this->transactions; - } - - - /** - * @param Account $account - */ - public function setAccount(Account $account): void - { - $this->account = $account; - } - - -} diff --git a/app/Services/Spectre/Request/NewCustomerRequest.php b/app/Services/Spectre/Request/NewCustomerRequest.php deleted file mode 100644 index 1c7aa32ffc..0000000000 --- a/app/Services/Spectre/Request/NewCustomerRequest.php +++ /dev/null @@ -1,63 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Request; - -use FireflyIII\Services\Spectre\Object\Customer; -use Log; - -/** - * Class NewCustomerRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class NewCustomerRequest extends SpectreRequest -{ - /** @var Customer */ - protected $customer; - - /** - * @throws \FireflyIII\Exceptions\FireflyException - */ - public function call(): void - { - $data = [ - 'data' => [ - 'identifier' => 'default_ff3_customer', - ], - ]; - $uri = '/api/v4/customers/'; - Log::debug(sprintf('Going to call %s with info:', $uri), $data); - $response = $this->sendSignedSpectrePost($uri, $data); - // create customer: - $this->customer = new Customer($response['data']); - } - - /** - * @return Customer - */ - public function getCustomer(): Customer - { - return $this->customer; - } -} diff --git a/app/Services/Spectre/Request/SpectreRequest.php b/app/Services/Spectre/Request/SpectreRequest.php deleted file mode 100644 index f9e959c237..0000000000 --- a/app/Services/Spectre/Request/SpectreRequest.php +++ /dev/null @@ -1,308 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Services\Spectre\Request; - -use Exception; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\User; -use GuzzleHttp\Client; -use GuzzleHttp\Exception\GuzzleException; -use Log; -use RuntimeException; - -/** - * Class SpectreRequest - * - * @codeCoverageIgnore - * @deprecated - */ -abstract class SpectreRequest -{ - /** @var int */ - protected $expiresAt = 0; - /** @var string */ - private $appId; - /** @var string */ - private $privateKey; - /** @var string */ - private $secret; - /** @var string */ - private $server; - /** @var User */ - private $user; - - /** - * - */ - abstract public function call(): void; - - /** - * @codeCoverageIgnore - * @return string - */ - public function getAppId(): string - { - return $this->appId; - } - - /** - * @codeCoverageIgnore - * - * @param string $appId - */ - public function setAppId(string $appId): void - { - $this->appId = $appId; - } - - /** - * @codeCoverageIgnore - * @return string - */ - public function getSecret(): string - { - return $this->secret; - } - - /** - * @codeCoverageIgnore - * - * @param string $secret - */ - public function setSecret(string $secret): void - { - $this->secret = $secret; - } - - /** - * @codeCoverageIgnore - * @return string - */ - public function getServer(): string - { - return $this->server; - } - - /** - * @codeCoverageIgnore - * - * @param string $privateKey - */ - public function setPrivateKey(string $privateKey): void - { - $this->privateKey = $privateKey; - } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - $this->server = 'https://' . config('import.options.spectre.server'); - $this->expiresAt = time() + 180; - $privateKey = app('preferences')->getForUser($user, 'spectre_private_key', null); - $this->privateKey = $privateKey->data; - - // set client ID - $appId = app('preferences')->getForUser($user, 'spectre_app_id', null); - if (null !== $appId && '' !== (string)$appId->data) { - $this->appId = $appId->data; - } - - // set service secret - $secret = app('preferences')->getForUser($user, 'spectre_secret', null); - if (null !== $secret && '' !== (string)$secret->data) { - $this->secret = $secret->data; - } - } - - /** - * @param string $method - * @param string $uri - * @param string $data - * - * @return string - * - * @throws FireflyException - */ - protected function generateSignature(string $method, string $uri, string $data): string - { - if ('' === $this->privateKey) { - throw new FireflyException('No private key present.'); - } - $method = strtolower($method); - if ('get' === $method || 'delete' === $method) { - $data = ''; - } - $toSign = $this->expiresAt . '|' . strtoupper($method) . '|' . $uri . '|' . $data . ''; // no file so no content there. - Log::debug(sprintf('String to sign: "%s"', $toSign)); - $signature = ''; - - // Sign the data - openssl_sign($toSign, $signature, $this->privateKey, OPENSSL_ALGO_SHA256); - $signature = base64_encode($signature); - - return $signature; - } - - /** - * @return array - */ - protected function getDefaultHeaders(): array - { - $userAgent = sprintf('FireflyIII v%s', config('firefly.version')); - - return [ - 'App-id' => $this->getAppId(), - 'Secret' => $this->getSecret(), - 'Accept' => 'application/json', - 'Content-type' => 'application/json', - 'Cache-Control' => 'no-cache', - 'User-Agent' => $userAgent, - 'Expires-at' => $this->expiresAt, - ]; - } - - /** - * @param string $uri - * @param array $data - * - * @return array - * - * @throws FireflyException - */ - protected function sendSignedSpectreGet(string $uri, array $data): array - { - if ('' === $this->server) { - throw new FireflyException('No Spectre server defined'); - } - - $headers = $this->getDefaultHeaders(); - $sendBody = json_encode($data); // OK - $fullUri = $this->server . $uri; - $signature = $this->generateSignature('get', $fullUri, $sendBody); - $headers['Signature'] = $signature; - - Log::debug('Final headers for spectre signed get request:', $headers); - try { - $client = new Client; - $res = $client->request('GET', $fullUri, ['headers' => $headers]); - } catch (GuzzleException|Exception $e) { - throw new FireflyException(sprintf('Guzzle Exception: %s', $e->getMessage())); - } - $statusCode = $res->getStatusCode(); - try { - $returnBody = $res->getBody()->getContents(); - } catch (RuntimeException $e) { - Log::error(sprintf('Could not get body from SpectreRequest::GET result: %s', $e->getMessage())); - $returnBody = ''; - } - $this->detectError($returnBody, $statusCode); - - $array = json_decode($returnBody, true); - $responseHeaders = $res->getHeaders(); - $array['ResponseHeaders'] = $responseHeaders; - $array['ResponseStatusCode'] = $statusCode; - - if (isset($array['error_class'])) { - $message = $array['error_message'] ?? '(no message)'; - throw new FireflyException(sprintf('Error of class %s: %s', $array['error_class'], $message)); - } - - - return $array; - } - - /** - * @param string $uri - * @param array $data - * - * @return array - * - * @throws FireflyException - */ - protected function sendSignedSpectrePost(string $uri, array $data): array - { - if ('' === $this->server) { - throw new FireflyException('No Spectre server defined'); - } - - $headers = $this->getDefaultHeaders(); - $body = json_encode($data); - $fullUri = $this->server . $uri; - $signature = $this->generateSignature('post', $fullUri, $body); - $headers['Signature'] = $signature; - - Log::debug('Final headers for spectre signed POST request:', $headers); - try { - $client = new Client; - $res = $client->request('POST', $fullUri, ['headers' => $headers, 'body' => $body]); - } catch (GuzzleException|Exception $e) { - throw new FireflyException(sprintf('Guzzle Exception: %s', $e->getMessage())); - } - - try { - $body = $res->getBody()->getContents(); - } catch (RuntimeException $e) { - Log::error(sprintf('Could not get body from SpectreRequest::POST result: %s', $e->getMessage())); - $body = ''; - } - - $statusCode = $res->getStatusCode(); - $this->detectError($body, $statusCode); - - $array = json_decode($body, true); - $responseHeaders = $res->getHeaders(); - $array['ResponseHeaders'] = $responseHeaders; - $array['ResponseStatusCode'] = $statusCode; - - return $array; - } - - /** - * @param string $body - * - * @param int $statusCode - * - * @throws FireflyException - */ - private function detectError(string $body, int $statusCode): void - { - $array = json_decode($body, true); - if (isset($array['error_class'])) { - $message = $array['error_message'] ?? '(no message)'; - $errorClass = $array['error_class']; - $class = sprintf('\\FireflyIII\\Services\\Spectre\Exception\\%sException', $errorClass); - if (class_exists($class)) { - throw new $class($message); - } - - throw new FireflyException(sprintf('Error of class %s: %s', $errorClass, $message)); - } - - if (200 !== $statusCode) { - throw new FireflyException(sprintf('Status code %d: %s', $statusCode, $body)); - } - } -} diff --git a/app/Services/Ynab/Request/GetAccountsRequest.php b/app/Services/Ynab/Request/GetAccountsRequest.php deleted file mode 100644 index 147dd287a6..0000000000 --- a/app/Services/Ynab/Request/GetAccountsRequest.php +++ /dev/null @@ -1,57 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Ynab\Request; - -use Log; - -/** - * Class GetAccountsRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class GetAccountsRequest extends YnabRequest -{ - /** @var array */ - public $accounts; - /** @var string */ - public $budgetId; - - /** - * - */ - public function call(): void - { - Log::debug('Now in GetAccountsRequest::call()'); - $uri = $this->api . sprintf('/budgets/%s/accounts', $this->budgetId); - - Log::debug(sprintf('URI is %s', $uri)); - - $result = $this->authenticatedGetRequest($uri, []); - //Log::debug('Raw GetAccountsRequest result', $result); - - // expect data in [data][accounts] - $this->accounts = $result['data']['accounts'] ?? []; - } -} diff --git a/app/Services/Ynab/Request/GetBudgetsRequest.php b/app/Services/Ynab/Request/GetBudgetsRequest.php deleted file mode 100644 index b392964a69..0000000000 --- a/app/Services/Ynab/Request/GetBudgetsRequest.php +++ /dev/null @@ -1,73 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Ynab\Request; - -use Log; - -/** - * Class GetBudgetsRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class GetBudgetsRequest extends YnabRequest -{ - /** @var array */ - public $budgets; - - public function __construct() - { - parent::__construct(); - $this->budgets = []; - } - - /** - * - */ - public function call(): void - { - Log::debug('Now in GetBudgetsRequest::call()'); - $uri = $this->api . '/budgets'; - - Log::debug(sprintf('URI is %s', $uri)); - - $result = $this->authenticatedGetRequest($uri, []); - Log::debug('Raw GetBudgetsRequest result', $result); - - // expect data in [data][budgets] - $rawBudgets = $result['data']['budgets'] ?? []; - $freshBudgets = []; - foreach ($rawBudgets as $rawBudget) { - Log::debug(sprintf('Raw content of budget is: %s', json_encode($rawBudget))); - Log::debug(sprintf('Content of currency format is: %s', json_encode($rawBudget['currency_format'] ?? []))); - Log::debug(sprintf('ISO code is: %s', $rawBudget['currency_format']['iso_code'] ?? '(none)')); - $freshBudgets[] = [ - 'id' => $rawBudget['id'], - 'name' => $rawBudget['name'], - 'currency_code' => $rawBudget['currency_format']['iso_code'] ?? null, - ]; - } - $this->budgets = $freshBudgets; - } -} diff --git a/app/Services/Ynab/Request/GetTransactionsRequest.php b/app/Services/Ynab/Request/GetTransactionsRequest.php deleted file mode 100644 index 3a3fe1a5ac..0000000000 --- a/app/Services/Ynab/Request/GetTransactionsRequest.php +++ /dev/null @@ -1,61 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Ynab\Request; - -use Log; - -/** - * Class GetTransactionsRequest - * - * @codeCoverageIgnore - * @deprecated - */ -class GetTransactionsRequest extends YnabRequest -{ - /** @var string */ - public $accountId; - /** @var array */ - public $accounts; - /** @var string */ - public $budgetId; - /** @var array */ - public $transactions; - - /** - * - */ - public function call(): void - { - Log::debug('Now in GetTransactionsRequest::call()'); - $uri = $this->api . sprintf('/budgets/%s/accounts/%s/transactions', $this->budgetId, $this->accountId); - - Log::debug(sprintf('URI is %s', $uri)); - - $result = $this->authenticatedGetRequest($uri, []); - //Log::debug('Raw GetTransactionsRequest result', $result); - - // expect data in [data][transactions] - $this->transactions = $result['data']['transactions'] ?? []; - } -} diff --git a/app/Services/Ynab/Request/YnabRequest.php b/app/Services/Ynab/Request/YnabRequest.php deleted file mode 100644 index 7a2034342f..0000000000 --- a/app/Services/Ynab/Request/YnabRequest.php +++ /dev/null @@ -1,104 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Services\Ynab\Request; - -use GuzzleHttp\Client; -use GuzzleHttp\Exception\GuzzleException; -use Log; -use RuntimeException; - -/** - * Class YnabRequest - * - * @codeCoverageIgnore - * @deprecated - */ -abstract class YnabRequest -{ - /** @var string */ - protected $api; - - /** @var string */ - protected $token; - - public function __construct() - { - $this->api = 'https://' . config('import.options.ynab.live') . '/' . config('import.options.ynab.version'); - } - - /** - * @param string $uri - * @param array|null $params - * - * @return array - */ - public function authenticatedGetRequest(string $uri, array $params = null): array - { - Log::debug(sprintf('Now in YnabRequest::authenticatedGetRequest(%s)', $uri), $params); - $client = new Client; - $params = $params ?? []; - $options = [ - 'headers' => [ - 'Authorization' => 'Bearer ' . $this->token, - ], - ]; - if (count($params) > 0) { - $uri = $uri . '?' . http_build_query($params); - } - Log::debug(sprintf('Going to call YNAB on URI: %s', $uri), $options); - try { - $res = $client->request('get', $uri, $options); - } catch (GuzzleException $e) { - Log::error($e->getMessage()); - Log::error($e->getTraceAsString()); - - return []; - } - try { - $content = trim($res->getBody()->getContents()); - Log::debug(sprintf('Raw body is: %s', $content)); - } catch (RuntimeException $e) { - Log::error($e->getMessage()); - Log::error($e->getTraceAsString()); - - return []; - } - - return json_decode($content, true) ?? []; - } - - /** - * - */ - abstract public function call(): void; - - /** - * @param string $token - */ - public function setAccessToken(string $token): void - { - $this->token = $token; - } - -} diff --git a/app/Support/Binder/ImportProvider.php b/app/Support/Binder/ImportProvider.php deleted file mode 100644 index b2b57cbf98..0000000000 --- a/app/Support/Binder/ImportProvider.php +++ /dev/null @@ -1,111 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Support\Binder; - -use Carbon\Carbon; -use FireflyIII\Import\Prerequisites\PrerequisitesInterface; -use FireflyIII\Repositories\User\UserRepositoryInterface; -use FireflyIII\User; -use Illuminate\Routing\Route; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; - -/** - * Class ImportProvider. - * - * @deprecated - */ -class ImportProvider implements BinderInterface -{ - /** - * @return array - * - */ - public static function getProviders(): array - { - $repository = app(UserRepositoryInterface::class); - // get and filter all import routines: - - if (!auth()->check()) { - return []; - } - - /** @var User $user */ - $user = auth()->user(); - - /** @var array $config */ - $providerNames = array_keys(config('import.enabled')); - $providers = []; - $isDemoUser = $repository->hasRole($user, 'demo'); - $isDebug = (bool)config('app.debug'); - foreach ($providerNames as $providerName) { - // only consider enabled providers - $enabled = (bool)config(sprintf('import.enabled.%s', $providerName)); - $allowedForUser = (bool)config(sprintf('import.allowed_for_user.%s', $providerName)); - $allowedForDemo = (bool)config(sprintf('import.allowed_for_demo.%s', $providerName)); - if (false === $enabled) { - continue; - } - if (false === $allowedForUser && !$isDemoUser) { - continue; - } - if (false === $allowedForDemo && $isDemoUser) { - continue; - } - - $providers[$providerName] = [ - 'has_prereq' => (bool)config('import.has_prereq.' . $providerName), - 'allowed_for_demo' => (bool)config(sprintf('import.allowed_for_demo.%s', $providerName)), - ]; - $class = (string)config(sprintf('import.prerequisites.%s', $providerName)); - $result = false; - if ('' !== $class && class_exists($class)) { - //Log::debug('Will not check prerequisites.'); - /** @var PrerequisitesInterface $object */ - $object = app($class); - $object->setUser($user); - $result = $object->isComplete(); - } - $providers[$providerName]['prereq_complete'] = $result; - } - //Log::debug(sprintf('Enabled providers: %s', json_encode(array_keys($providers)))); - - return $providers; - } - - /** - * @param string $value - * @param Route $route - * - * @return string - * - * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ - public static function routeBinder(string $value, Route $route): string - { - $providers = array_keys(self::getProviders()); - if (in_array($value, $providers, true)) { - return $value; - } - throw new NotFoundHttpException; - } -} diff --git a/app/Support/FinTS/FinTS.php b/app/Support/FinTS/FinTS.php deleted file mode 100644 index 91dfbe21ad..0000000000 --- a/app/Support/FinTS/FinTS.php +++ /dev/null @@ -1,122 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Support\FinTS; - -use Fhp\Model\SEPAAccount; -use FireflyIII\Exceptions\FireflyException; -use Illuminate\Support\Facades\Crypt; - -/** - * @codeCoverageIgnore - * @deprecated - * Class FinTS - */ -class FinTS -{ - /** @var \Fhp\FinTs */ - private $finTS; - - /** - * @param array $config - * - * @throws FireflyException - */ - public function __construct(array $config) - { - if (!isset($config['fints_url'], $config['fints_port'], $config['fints_bank_code'], $config['fints_username'], $config['fints_password'])) { - throw new FireflyException('Constructed FinTS with incomplete config.'); - } - $this->finTS = new \Fhp\FinTs( - $config['fints_url'], - $config['fints_port'], - $config['fints_bank_code'], - $config['fints_username'], - Crypt::decrypt($config['fints_password']) // verified - ); - } - - /** - * @return bool|string - */ - public function checkConnection() - { - try { - $this->finTS->getSEPAAccounts(); - - return true; - } catch (\Exception $exception) { - return $exception->getMessage(); - } - } - - /** - * @param string $accountNumber - * - * @return SEPAAccount - * @throws FireflyException - */ - public function getAccount(string $accountNumber): SEPAAccount - { - $accounts = $this->getAccounts(); - $filteredAccounts = array_filter( - $accounts, function (SEPAAccount $account) use ($accountNumber) { - return $account->getAccountNumber() === $accountNumber; - } - ); - if (1 !== count($filteredAccounts)) { - throw new FireflyException(sprintf('Cannot find account with number "%s"', $accountNumber)); - } - - return reset($filteredAccounts); - } - - /** - * @return SEPAAccount[] - * @throws FireflyException - */ - public function getAccounts(): ?array - { - try { - return $this->finTS->getSEPAAccounts(); - } catch (\Exception $exception) { - throw new FireflyException($exception->getMessage()); - } - } - - /** - * @param SEPAAccount $account - * @param \DateTime $from - * @param \DateTIme $to - * - * @return \Fhp\Model\StatementOfAccount\StatementOfAccount|null - * @throws FireflyException - */ - public function getStatementOfAccount(SEPAAccount $account, \DateTime $from, \DateTIme $to) - { - try { - return $this->finTS->getStatementOfAccount($account, $from, $to); - } catch (\Exception $exception) { - throw new FireflyException($exception->getMessage()); - } - } -} diff --git a/app/Support/FinTS/MetadataParser.php b/app/Support/FinTS/MetadataParser.php deleted file mode 100644 index 6a079202cd..0000000000 --- a/app/Support/FinTS/MetadataParser.php +++ /dev/null @@ -1,50 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Support\FinTS; - -use Fhp\Model\StatementOfAccount\Transaction as FinTSTransaction; - -/** - * @deprecated - * @codeCoverageIgnore - * Class MetadataParser - */ -class MetadataParser -{ - /** - * @param FinTSTransaction $transaction - * - * @return string - */ - public function getDescription(FinTSTransaction $transaction): string - { - //Given a description like 'EREF+AbcCRED+DE123SVWZ+DefABWA+Ghi' or 'EREF+AbcCRED+DE123SVWZ+Def' return 'Def' - $finTSDescription = $transaction->getDescription1(); - $matches = []; - if (1 === preg_match('/SVWZ\+([^\+]*)([A-Z]{4}\+|$)/', $finTSDescription, $matches)) { - return $matches[1]; - } - - return $finTSDescription; - } -} diff --git a/app/Support/Http/Controllers/CreateStuff.php b/app/Support/Http/Controllers/CreateStuff.php index 24733937a2..98f51e027f 100644 --- a/app/Support/Http/Controllers/CreateStuff.php +++ b/app/Support/Http/Controllers/CreateStuff.php @@ -27,9 +27,6 @@ use Carbon\Carbon; use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Requests\NewUserFormRequest; -use FireflyIII\Import\JobConfiguration\JobConfigurationInterface; -use FireflyIII\Import\Storage\ImportArrayStorage; -use FireflyIII\Models\ImportJob; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\User; @@ -174,46 +171,4 @@ trait CreateStuff ); } - /** - * Make a configurator object. - * - * @param ImportJob $importJob - * - * @return JobConfigurationInterface - * - * @throws FireflyException - */ - protected function makeConfigurator(ImportJob $importJob): JobConfigurationInterface // make object - { - $key = sprintf('import.configuration.%s', $importJob->provider); - $className = (string)config($key); - if (null === $className || !class_exists($className)) { - throw new FireflyException(sprintf('Cannot find configurator class for job with provider "%s".', $importJob->provider)); // @codeCoverageIgnore - } - Log::debug(sprintf('Going to create class "%s"', $className)); - /** @var JobConfigurationInterface $configurator */ - $configurator = app($className); - $configurator->setImportJob($importJob); - - return $configurator; - } - - /** - * Store the transactions. - * - * @param ImportJob $importJob - * - * @throws FireflyException - */ - protected function storeTransactions(ImportJob $importJob): void // make object + execute - { - /** @var ImportArrayStorage $storage */ - $storage = app(ImportArrayStorage::class); - $storage->setImportJob($importJob); - try { - $storage->store(); - } catch (FireflyException|Exception $e) { - throw new FireflyException($e->getMessage()); - } - } } diff --git a/app/Support/Import/Information/GetSpectreCustomerTrait.php b/app/Support/Import/Information/GetSpectreCustomerTrait.php deleted file mode 100644 index c2f0cd9058..0000000000 --- a/app/Support/Import/Information/GetSpectreCustomerTrait.php +++ /dev/null @@ -1,110 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Information; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Services\Spectre\Object\Customer; -use FireflyIII\Services\Spectre\Request\ListCustomersRequest; -use FireflyIII\Services\Spectre\Request\NewCustomerRequest; -use Log; - -/** - * Trait GetSpectreCustomerTrait - * - * @codeCoverageIgnore - * @deprecated - */ -trait GetSpectreCustomerTrait -{ - /** - * @param ImportJob $importJob - * - * @return Customer - * @throws FireflyException - */ - protected function getCustomer(ImportJob $importJob): Customer - { - Log::debug('Now in GetSpectreCustomerTrait::getCustomer()'); - $customer = $this->getExistingCustomer($importJob); - if (null === $customer) { - Log::debug('The customer is NULL, will fire a newCustomerRequest.'); - /** @var NewCustomerRequest $request */ - $request = app(NewCustomerRequest::class); - $request->setUser($importJob->user); - $request->call(); - - $customer = $request->getCustomer(); - - } - - Log::debug('The customer is not null.'); - - return $customer; - } - - /** - * @param ImportJob $importJob - * - * @return Customer|null - * @throws FireflyException - */ - protected function getExistingCustomer(ImportJob $importJob): ?Customer - { - Log::debug('Now in GetSpectreCustomerTrait::getExistingCustomer()'); - $customer = null; - - // check users preferences. - $preference = app('preferences')->getForUser($importJob->user, 'spectre_customer', null); - if (null !== $preference) { - Log::debug('Customer is in user configuration'); - $customer = new Customer($preference->data); - - return $customer; - } - - /** @var ListCustomersRequest $request */ - $request = app(ListCustomersRequest::class); - $request->setUser($importJob->user); - $request->call(); - $customers = $request->getCustomers(); - - Log::debug(sprintf('Found %d customer(s)', count($customers))); - /** @var Customer $current */ - foreach ($customers as $current) { - if ('default_ff3_customer' === $current->getIdentifier()) { - $customer = $current; - Log::debug('Found the correct customer.'); - break; - } - Log::debug(sprintf('Skip customer with name "%s"', $current->getIdentifier())); - } - if (null !== $customer) { - // store in preferences. - app('preferences')->setForUser($importJob->user, 'spectre_customer', $customer->toArray()); - } - - return $customer; - } -} diff --git a/app/Support/Import/Information/GetSpectreTokenTrait.php b/app/Support/Import/Information/GetSpectreTokenTrait.php deleted file mode 100644 index 875c905c8e..0000000000 --- a/app/Support/Import/Information/GetSpectreTokenTrait.php +++ /dev/null @@ -1,60 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Information; - -use FireflyIII\Models\ImportJob; -use FireflyIII\Services\Spectre\Object\Customer; -use FireflyIII\Services\Spectre\Object\Token; -use FireflyIII\Services\Spectre\Request\CreateTokenRequest; -use Log; - -/** - * Trait GetSpectreTokenTrait - * - * @codeCoverageIgnore - * @deprecated - */ -trait GetSpectreTokenTrait -{ - /** - * @param ImportJob $importJob - * @param Customer $customer - * - * @return Token - * @throws \FireflyIII\Exceptions\FireflyException - */ - protected function getToken(ImportJob $importJob, Customer $customer): Token - { - Log::debug('Now in GetSpectreTokenTrait::ChooseLoginsHandler::getToken()'); - /** @var CreateTokenRequest $request */ - $request = app(CreateTokenRequest::class); - $request->setUser($importJob->user); - $request->setUri(route('import.job.status.index', [$importJob->key])); - $request->setCustomer($customer); - $request->call(); - Log::debug('Call to get token is finished'); - - return $request->getToken(); - } -} diff --git a/app/Support/Import/JobConfiguration/Bunq/BunqJobConfigurationInterface.php b/app/Support/Import/JobConfiguration/Bunq/BunqJobConfigurationInterface.php deleted file mode 100644 index d662694c86..0000000000 --- a/app/Support/Import/JobConfiguration/Bunq/BunqJobConfigurationInterface.php +++ /dev/null @@ -1,74 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Bunq; - -use FireflyIII\Models\ImportJob; -use Illuminate\Support\MessageBag; - -/** - * Interface BunqJobConfigurationInterface - * @deprecated - * @codeCoverageIgnore - */ -interface BunqJobConfigurationInterface -{ - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool; - - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag; - - /** - * Get data for config view. - * - * @return array - */ - public function getNextData(): array; - - /** - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string; - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void; - -} diff --git a/app/Support/Import/JobConfiguration/Bunq/ChooseAccountsHandler.php b/app/Support/Import/JobConfiguration/Bunq/ChooseAccountsHandler.php deleted file mode 100644 index 7cf82b10bb..0000000000 --- a/app/Support/Import/JobConfiguration/Bunq/ChooseAccountsHandler.php +++ /dev/null @@ -1,271 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Bunq; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account as AccountModel; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class ChooseAccountsHandler - * @deprecated - * @codeCoverageIgnore - */ -class ChooseAccountsHandler implements BunqJobConfigurationInterface -{ - - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var CurrencyRepositoryInterface */ - private $currencyRepository; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - $config = $this->repository->getConfiguration($this->importJob); - $mapping = $config['mapping'] ?? []; - $complete = count($mapping) > 0; - if (true === $complete) { - // move job to correct stage to download transactions - $this->repository->setStage($this->importJob, 'go-for-import'); - } - - return $complete; - } - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - * @throws FireflyException - */ - public function configureJob(array $data): MessageBag - { - $config = $this->repository->getConfiguration($this->importJob); - $accounts = $config['accounts'] ?? []; - $mapping = $data['account_mapping'] ?? []; - $applyRules = 1 === (int)($data['apply_rules'] ?? 0); - $final = []; - - /* - * $ibanToAsset is used to map bunq IBAN's to Firefly III asset accounts. The array is structured like this: - * 12BUNQ123456.. => 1, - * 12BUNQ928811.. => 4, - * - * And contains the bunq asset account iban (left) and the FF3 asset ID (right). - * - * This is used to properly map transfers. - */ - $ibanToAsset = []; - Log::debug('Going to map IBANs for easy mapping later on.'); - if (0 === count($accounts)) { - throw new FireflyException('No bunq accounts found. Import cannot continue.'); // @codeCoverageIgnore - } - if (0 === count($mapping)) { - $messages = new MessageBag; - $messages->add('nomap', (string)trans('import.bunq_no_mapping')); - - return $messages; - } - foreach ($mapping as $bunqId => $localId) { - $bunqId = (int)$bunqId; - $localId = (int)$localId; - - Log::debug(sprintf('Now trying to link bunq acount #%d with Firefly III account %d', $bunqId, $localId)); - - // validate each - $bunqId = $this->validBunqAccount($bunqId); - $accountId = $this->validLocalAccount($localId); - - Log::debug(sprintf('After validation: bunq account #%d with Firefly III account %d', $bunqId, $localId)); - - $bunqIban = $this->getBunqIban($bunqId); - - Log::debug(sprintf('IBAN for bunq account #%d is "%s"', $bunqId, $bunqIban)); - if (null !== $bunqIban) { - $ibanToAsset[$bunqIban] = $accountId; // @codeCoverageIgnore - } - $final[$bunqId] = $accountId; - } - $config['mapping'] = $final; - $config['bunq-iban'] = $ibanToAsset; - $config['apply-rules'] = $applyRules; - $this->repository->setConfiguration($this->importJob, $config); - - Log::info('Account mapping: ', $final); - Log::info('Bunq IBAN array: ', $ibanToAsset); - - return new MessageBag; - } - - /** - * Get data for config view. - * - * @return array - * @throws FireflyException - */ - public function getNextData(): array - { - $config = $this->repository->getConfiguration($this->importJob); - $accounts = $config['accounts'] ?? []; - if (0 === count($accounts)) { - throw new FireflyException('No bunq accounts found. Import cannot continue.'); // @codeCoverageIgnore - } - // list the users accounts: - $collection = $this->accountRepository->getAccountsByType([AccountType::ASSET]); - - $localAccounts = []; - /** @var AccountModel $localAccount */ - foreach ($collection as $localAccount) { - $accountId = $localAccount->id; - // TODO we can use getAccountCurrency() instead - $currencyId = (int)$this->accountRepository->getMetaValue($localAccount, 'currency_id'); - $currency = $this->getCurrency($currencyId); - $localAccounts[$accountId] = [ - 'name' => $localAccount->name, - 'iban' => $localAccount->iban, - 'code' => $currency->code, - ]; - } - - return [ - 'accounts' => $accounts, - 'local_accounts' => $localAccounts, - ]; - } - - /** - * @codeCoverageIgnore - * - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - return 'import.bunq.choose-accounts'; - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->currencyRepository->setUser($importJob->user); - $this->accountRepository->setUser($importJob->user); - } - - /** - * @param int $bunqId - * - * @return null|string - */ - private function getBunqIban(int $bunqId): ?string - { - $config = $this->repository->getConfiguration($this->importJob); - $accounts = $config['accounts'] ?? []; - /** @var array $bunqAccount */ - foreach ($accounts as $bunqAccount) { - if ((int)$bunqAccount['id'] === $bunqId) { - return $bunqAccount['iban'] ?? null; - } - } - - return null; - } - - /** - * @param int $currencyId - * - * @return TransactionCurrency - */ - private function getCurrency(int $currencyId): TransactionCurrency - { - $currency = $this->currencyRepository->findNull($currencyId); - if (null === $currency) { - return app('amount')->getDefaultCurrencyByUser($this->importJob->user); - } - - return $currency; - - } - - /** - * @param int $bunqId - * - * @return int - */ - private function validBunqAccount(int $bunqId): int - { - $config = $this->repository->getConfiguration($this->importJob); - $accounts = $config['accounts'] ?? []; - /** @var array $bunqAccount */ - foreach ($accounts as $bunqAccount) { - if ((int)$bunqAccount['id'] === $bunqId) { - return $bunqId; - } - } - - return 0; - } - - /** - * @param int $accountId - * - * @return int - */ - private function validLocalAccount(int $accountId): int - { - $account = $this->accountRepository->findNull($accountId); - if (null === $account) { - return 0; - } - - return $accountId; - } -} diff --git a/app/Support/Import/JobConfiguration/Bunq/NewBunqJobHandler.php b/app/Support/Import/JobConfiguration/Bunq/NewBunqJobHandler.php deleted file mode 100644 index 847da7284d..0000000000 --- a/app/Support/Import/JobConfiguration/Bunq/NewBunqJobHandler.php +++ /dev/null @@ -1,105 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Bunq; - -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class NewBunqJobHandler - * @deprecated - * @codeCoverageIgnore - */ -class NewBunqJobHandler implements BunqJobConfigurationInterface -{ - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - return true; - } - - /** - * @codeCoverageIgnore - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - Log::debug('NewBunqJobHandler::configureJob always returns an empty message bag.'); - - return new MessageBag; - } - - /** - * @codeCoverageIgnore - * Get data for config view. - * - * @return array - */ - public function getNextData(): array - { - Log::debug('NewBunqJobHandler::getNextData always returns an empty array.'); - - return []; - } - - /** - * @codeCoverageIgnore - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - Log::debug('NewBunqJobHandler::getNextView always returns "".'); - - return ''; - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Import/JobConfiguration/File/ConfigureMappingHandler.php b/app/Support/Import/JobConfiguration/File/ConfigureMappingHandler.php deleted file mode 100644 index 8be440542a..0000000000 --- a/app/Support/Import/JobConfiguration/File/ConfigureMappingHandler.php +++ /dev/null @@ -1,354 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\File; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; -use FireflyIII\Import\Mapper\MapperInterface; -use FireflyIII\Import\Specifics\SpecificInterface; -use FireflyIII\Models\Attachment; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Support\Collection; -use Illuminate\Support\MessageBag; -use League\Csv\Exception; -use League\Csv\Reader; -use League\Csv\Statement; -use Log; - -/** - * Class ConfigureMappingHandler - * @deprecated - * @codeCoverageIgnore - */ -class ConfigureMappingHandler implements FileConfigurationInterface -{ - /** @var AttachmentHelperInterface */ - private $attachments; - /** @var array */ - private $columnConfig; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Apply the users selected specifics on the current row. - * - * @param array $config - * @param array $row - * - * @return array - */ - public function applySpecifics(array $config, array $row): array - { - // run specifics here: - // and this is the point where the specifix go to work. - $validSpecifics = array_keys(config('csv.import_specifics')); - $specifics = $config['specifics'] ?? []; - $names = array_keys($specifics); - foreach ($names as $name) { - if (!in_array($name, $validSpecifics, true)) { - continue; - } - $class = config(sprintf('csv.import_specifics.%s', $name)); - /** @var SpecificInterface $specific */ - $specific = app($class); - - // it returns the row, possibly modified: - $row = $specific->run($row); - } - - return $row; - } - - /** - * Store data associated with current stage. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - $config = $this->importJob->configuration; - - if (isset($data['mapping']) && is_array($data['mapping'])) { - foreach ($data['mapping'] as $index => $array) { - $config['column-mapping-config'][$index] = []; - foreach ($array as $value => $mapId) { - $mapId = (int)$mapId; - if (0 !== $mapId) { - $config['column-mapping-config'][$index][(string)$value] = $mapId; - } - } - } - } - $this->repository->setConfiguration($this->importJob, $config); - $this->repository->setStage($this->importJob, 'ready_to_run'); - - return new MessageBag; - } - - /** - * Create the "mapper" class that will eventually return the correct data for the user - * to map against. For example: a list of asset accounts. A list of budgets. A list of tags. - * - * @param string $column - * - * @return MapperInterface - * @throws FireflyException - */ - public function createMapper(string $column): MapperInterface - { - $mapperClass = config('csv.import_roles.' . $column . '.mapper'); - $mapperName = sprintf('FireflyIII\\Import\Mapper\\%s', $mapperClass); - if (!class_exists($mapperName)) { - throw new FireflyException(sprintf('Class "%s" does not exist. Cannot map "%s"', $mapperName, $column)); // @codeCoverageIgnore - } - - return app($mapperName); - } - - /** - * For each column in the configuration of the job, will: - * - validate the role. - * - validate if it can be used for mapping - * - if so, create an entry in $columnConfig - * - * @param array $config - * - * @return array the column configuration. - * @throws FireflyException - */ - public function doColumnConfig(array $config): array - { - /** @var array $requestMapping */ - $requestMapping = $config['column-do-mapping'] ?? []; - $columnConfig = []; - /** - * @var int - * @var bool $mustBeMapped - */ - foreach ($requestMapping as $index => $requested) { - // sanitize column name, so we're sure it's valid. - $column = $this->sanitizeColumnName($config['column-roles'][$index] ?? '_ignore'); - $doMapping = $this->doMapOfColumn($column, $requested); - if ($doMapping) { - // user want to map this column. And this is possible. - $columnConfig[$index] = [ - 'name' => $column, - 'options' => $this->createMapper($column)->getMap(), - 'preProcessMap' => $this->getPreProcessorName($column), - 'values' => [], - ]; - } - } - - return $columnConfig; - } - - /** - * For each $name given, and if the user wants to map the column, will return - * true when the column can also be mapped. - * - * Unmappable columns will always return false. - * Mappable columns will return $requested. - * - * @param string $name - * @param bool $requested - * - * @return bool - */ - public function doMapOfColumn(string $name, bool $requested): bool - { - $canBeMapped = config('csv.import_roles.' . $name . '.mappable'); - - return true === $canBeMapped && true === $requested; - } - - /** - * Get the data necessary to show the configuration screen. - * - * @return array - * @throws FireflyException - */ - public function getNextData(): array - { - $config = $this->importJob->configuration; - $columnConfig = $this->doColumnConfig($config); - - // in order to actually map we also need to read the FULL file. - try { - $reader = $this->getReader(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - Log::error($e->getMessage()); - throw new FireflyException('Cannot get reader: ' . $e->getMessage()); - } - // @codeCoverageIgnoreEnd - - // get ALL values for the mappable columns from the CSV file: - $columnConfig = $this->getValuesForMapping($reader, $config, $columnConfig); - - return $columnConfig; - } - - /** - * Will return the name of the pre-processor: a special class that will clean up any input that may be found - * in the users input (aka the file uploaded). Only two examples exist at this time: a space or comma separated - * list of tags. - * - * @param string $column - * - * @return string - */ - public function getPreProcessorName(string $column): string - { - $name = ''; - $hasPreProcess = config(sprintf('csv.import_roles.%s.pre-process-map', $column)); - $preProcessClass = config(sprintf('csv.import_roles.%s.pre-process-mapper', $column)); - - if (null !== $hasPreProcess && true === $hasPreProcess && null !== $preProcessClass) { - $name = sprintf('FireflyIII\\Import\\MapperPreProcess\\%s', $preProcessClass); - } - - return $name; - } - - /** - * Return an instance of a CSV file reader so content of the file can be read. - * - * @throws \League\Csv\Exception - */ - public function getReader(): Reader - { - $content = ''; - /** @var Collection $collection */ - $collection = $this->repository->getAttachments($this->importJob); - /** @var Attachment $attachment */ - foreach ($collection as $attachment) { - if ('import_file' === $attachment->filename) { - $content = $this->attachments->getAttachmentContent($attachment); - break; - } - } - $config = $this->repository->getConfiguration($this->importJob); - $reader = Reader::createFromString($content); - $reader->setDelimiter($config['delimiter']); - - return $reader; - } - - /** - * Read the CSV file. For each row, check for each column: - * - * - If it can be mapped. And if so, - * - Run the pre-processor - * - Add the value to the list of "values" that the user must map. - * - * @param Reader $reader - * @param array $config - * @param array $columnConfig - * - * @return array - * @throws FireflyException - * - */ - public function getValuesForMapping(Reader $reader, array $config, array $columnConfig): array - { - $offset = isset($config['has-headers']) && true === $config['has-headers'] ? 1 : 0; - try { - $stmt = (new Statement)->offset($offset); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - throw new FireflyException(sprintf('Could not create reader: %s', $e->getMessage())); - } - // @codeCoverageIgnoreEnd - $results = $stmt->process($reader); - $mappableColumns = array_keys($columnConfig); // the actually columns that can be mapped. - foreach ($results as $lineIndex => $line) { - Log::debug(sprintf('Trying to collect values for line #%d', $lineIndex)); - $line = $this->applySpecifics($config, $line); - - /** @var int $columnIndex */ - foreach ($mappableColumns as $columnIndex) { // this is simply 1, 2, 3, etc. - if (!isset($line[$columnIndex])) { - // don't need to handle this. Continue. - continue; - } - $value = trim($line[$columnIndex]); - if ('' === $value) { - // value is empty, ignore it. - continue; - } - $columnConfig[$columnIndex]['values'][] = $value; - } - } - - // loop array again. This time, do uniqueness. - // and remove arrays that have 0 values. - foreach ($mappableColumns as $columnIndex) { - $columnConfig[$columnIndex]['values'] = array_unique($columnConfig[$columnIndex]['values']); - asort($columnConfig[$columnIndex]['values']); - // if the count of this array is zero, there is nothing to map. - if (0 === count($columnConfig[$columnIndex]['values'])) { - unset($columnConfig[$columnIndex]); // @codeCoverageIgnore - } - } - - return $columnConfig; - } - - /** - * For each given column name, will return either the name (when it's a valid one) - * or return the _ignore column. - * - * @param string $name - * - * @return string - */ - public function sanitizeColumnName(string $name): string - { - /** @var array $validColumns */ - $validColumns = array_keys(config('csv.import_roles')); - if (!in_array($name, $validColumns, true)) { - $name = '_ignore'; - } - - return $name; - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->attachments = app(AttachmentHelperInterface::class); - $this->columnConfig = []; - } -} diff --git a/app/Support/Import/JobConfiguration/File/ConfigureRolesHandler.php b/app/Support/Import/JobConfiguration/File/ConfigureRolesHandler.php deleted file mode 100644 index 9c4bde5e66..0000000000 --- a/app/Support/Import/JobConfiguration/File/ConfigureRolesHandler.php +++ /dev/null @@ -1,415 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\File; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; -use FireflyIII\Import\Specifics\SpecificInterface; -use FireflyIII\Models\Attachment; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Support\Collection; -use Illuminate\Support\MessageBag; -use League\Csv\Exception; -use League\Csv\Reader; -use League\Csv\Statement; -use Log; - -/** - * Class ConfigureRolesHandler - * @deprecated - * @codeCoverageIgnore - */ -class ConfigureRolesHandler implements FileConfigurationInterface -{ - /** @var AttachmentHelperInterface */ - private $attachments; - /** @var array */ - private $examples; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - /** @var int */ - private $totalColumns; - - /** - * Verifies that the configuration of the job is actually complete, and valid. - * - * @param array $config - * - * @return MessageBag - * - */ - public function configurationComplete(array $config): MessageBag - { - /** @var array $roles */ - $roles = $config['column-roles']; - $assigned = 0; - - // check if data actually contains amount column (foreign amount does not count) - $hasAmount = false; - $hasForeignAmount = false; - $hasForeignCode = false; - foreach ($roles as $role) { - if ('_ignore' !== $role) { - ++$assigned; - } - if (in_array($role, ['amount', 'amount_credit', 'amount_debit', 'amount_negated'])) { - $hasAmount = true; - } - if ('foreign-currency-code' === $role) { - $hasForeignCode = true; - } - if ('amount_foreign' === $role) { - $hasForeignAmount = true; - } - } - - // all assigned and correct foreign info - if ($assigned > 0 && $hasAmount && ($hasForeignCode === $hasForeignAmount)) { - return new MessageBag; - } - if (0 === $assigned || !$hasAmount) { - $message = (string)trans('import.job_config_roles_rwarning'); - $messages = new MessageBag(); - $messages->add('error', $message); - - return $messages; - } - - // warn if has foreign amount but no currency code: - if ($hasForeignAmount && !$hasForeignCode) { - $message = (string)trans('import.job_config_roles_fa_warning'); - $messages = new MessageBag(); - $messages->add('error', $message); - - return $messages; - } - - - return new MessageBag; // @codeCoverageIgnore - } - - /** - * Store data associated with current stage. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - $config = $this->importJob->configuration; - $count = $config['column-count']; - for ($i = 0; $i < $count; ++$i) { - $role = $data['role'][$i] ?? '_ignore'; - $mapping = (isset($data['map'][$i]) && '1' === $data['map'][$i]); - $config['column-roles'][$i] = $role; - $config['column-do-mapping'][$i] = $mapping; - Log::debug(sprintf('Column %d has been given role %s (mapping: %s)', $i, $role, var_export($mapping, true))); - } - $config = $this->ignoreUnmappableColumns($config); - $messages = $this->configurationComplete($config); - - if (0 === $messages->count()) { - $this->repository->setStage($this->importJob, 'ready_to_run'); - if ($this->isMappingNecessary($config)) { - $this->repository->setStage($this->importJob, 'map'); - } - $this->repository->setConfiguration($this->importJob, $config); - } - - return $messages; - } - - /** - * Extracts example data from a single row and store it in the class. - * - * @param array $line - */ - public function getExampleFromLine(array $line): void - { - foreach ($line as $column => $value) { - $value = trim($value); - if ('' != $value) { - $this->examples[$column][] = $value; - } - } - } - - /** - * @return array - */ - public function getExamples(): array - { - return $this->examples; - } - - /** - * Return a bunch of examples from the CSV file the user has uploaded. - * - * @param Reader $reader - * @param array $config - * - * @throws FireflyException - */ - public function getExamplesFromFile(Reader $reader, array $config): void - { - $limit = (int)config('csv.example_rows', 5); - $offset = isset($config['has-headers']) && true === $config['has-headers'] ? 1 : 0; - - // make statement. - try { - $stmt = (new Statement)->limit($limit)->offset($offset); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - Log::error($e->getMessage()); - throw new FireflyException($e->getMessage()); - } - // @codeCoverageIgnoreEnd - - // grab the records: - $records = $stmt->process($reader); - /** @var array $line */ - foreach ($records as $line) { - $line = array_values($line); - $line = $this->processSpecifics($config, $line); - $count = count($line); - $this->totalColumns = $count > $this->totalColumns ? $count : $this->totalColumns; - $this->getExampleFromLine($line); - } - // save column count: - $this->saveColumCount(); - $this->makeExamplesUnique(); - } - - /** - * Get the header row, if one is present. - * - * @param Reader $reader - * @param array $config - * - * @return array - * @throws FireflyException - */ - public function getHeaders(Reader $reader, array $config): array - { - $headers = []; - if (isset($config['has-headers']) && true === $config['has-headers']) { - try { - $stmt = (new Statement)->limit(1)->offset(0); - $records = $stmt->process($reader); - $headers = $records->fetchOne(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - Log::error($e->getMessage()); - throw new FireflyException($e->getMessage()); - } - // @codeCoverageIgnoreEnd - Log::debug('Detected file headers:', $headers); - } - - return $headers; - } - - /** - * Get the data necessary to show the configuration screen. - * - * @return array - * @throws FireflyException - */ - public function getNextData(): array - { - try { - $reader = $this->getReader(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - Log::error($e->getMessage()); - throw new FireflyException($e->getMessage()); - } - // @codeCoverageIgnoreEnd - $configuration = $this->importJob->configuration; - $headers = $this->getHeaders($reader, $configuration); - - // get example rows: - $this->getExamplesFromFile($reader, $configuration); - - return [ - 'examples' => $this->examples, - 'roles' => $this->getRoles(), - 'total' => $this->totalColumns, - 'headers' => $headers, - ]; - } - - /** - * Return an instance of a CSV file reader so content of the file can be read. - * - * @throws \League\Csv\Exception - */ - public function getReader(): Reader - { - $content = ''; - /** @var Collection $collection */ - $collection = $this->repository->getAttachments($this->importJob); - /** @var Attachment $attachment */ - foreach ($collection as $attachment) { - if ('import_file' === $attachment->filename) { - $content = $this->attachments->getAttachmentContent($attachment); - break; - } - } - $config = $this->repository->getConfiguration($this->importJob); - $reader = Reader::createFromString($content); - $reader->setDelimiter($config['delimiter']); - - return $reader; - } - - /** - * Returns all possible roles and translate their name. Then sort them. - * - * @codeCoverageIgnore - * @return array - */ - public function getRoles(): array - { - $roles = []; - foreach (array_keys(config('csv.import_roles')) as $role) { - $roles[$role] = (string)trans('import.column_' . $role); - } - asort($roles); - - return $roles; - } - - /** - * If the user has checked columns that cannot be mapped to any value, this function will - * uncheck them and return the configuration again. - * - * @param array $config - * - * @return array - */ - public function ignoreUnmappableColumns(array $config): array - { - $count = $config['column-count']; - for ($i = 0; $i < $count; ++$i) { - $role = $config['column-roles'][$i] ?? '_ignore'; - $mapping = $config['column-do-mapping'][$i] ?? false; - // if the column can be mapped depends on the config: - $canMap = (bool)config(sprintf('csv.import_roles.%s.mappable', $role)); - $mapping = $mapping && $canMap; - $config['column-do-mapping'][$i] = $mapping; - } - - return $config; - } - - /** - * Returns false when it's not necessary to map values. This saves time and is user friendly - * (will skip to the next screen). - * - * @param array $config - * - * @return bool - */ - public function isMappingNecessary(array $config): bool - { - /** @var array $doMapping */ - $doMapping = $config['column-do-mapping'] ?? []; - $toBeMapped = 0; - foreach ($doMapping as $doMap) { - if (true === $doMap) { - ++$toBeMapped; - } - } - - return !(0 === $toBeMapped); - } - - /** - * Make sure that the examples do not contain double data values. - */ - public function makeExamplesUnique(): void - { - foreach ($this->examples as $index => $values) { - $this->examples[$index] = array_unique($values); - } - } - - /** - * if the user has configured specific fixes to be applied, they must be applied to the example data as well. - * - * @param array $config - * @param array $line - * - * @return array - */ - public function processSpecifics(array $config, array $line): array - { - $validSpecifics = array_keys(config('csv.import_specifics')); - $specifics = $config['specifics'] ?? []; - $names = array_keys($specifics); - foreach ($names as $name) { - if (!in_array($name, $validSpecifics, true)) { - continue; - } - /** @var SpecificInterface $specific */ - $specific = app('FireflyIII\Import\Specifics\\' . $name); - $line = $specific->run($line); - } - - return $line; - - } - - /** - * Save the column count in the job. It's used in a later stage. - * - * @return void - */ - public function saveColumCount(): void - { - $config = $this->importJob->configuration; - $config['column-count'] = $this->totalColumns; - $this->repository->setConfiguration($this->importJob, $config); - } - - /** - * Set job and some start values. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->attachments = app(AttachmentHelperInterface::class); - $this->totalColumns = 0; - $this->examples = []; - } -} diff --git a/app/Support/Import/JobConfiguration/File/ConfigureUploadHandler.php b/app/Support/Import/JobConfiguration/File/ConfigureUploadHandler.php deleted file mode 100644 index 8bd2a610b5..0000000000 --- a/app/Support/Import/JobConfiguration/File/ConfigureUploadHandler.php +++ /dev/null @@ -1,162 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\File; - -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Support\MessageBag; -use Log; - - -/** - * Class ConfigureUploadHandler - * @deprecated - * @codeCoverageIgnore - */ -class ConfigureUploadHandler implements FileConfigurationInterface -{ - /** @var AccountRepositoryInterface */ - private $accountRepos; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Store data associated with current stage. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - $config = $this->importJob->configuration; - $complete = true; - - // collect values: - $importId = isset($data['csv_import_account']) ? (int)$data['csv_import_account'] : 0; - $delimiter = (string)$data['csv_delimiter']; - $config['has-headers'] = 1 === (int)($data['has_headers'] ?? 0.0); - $config['date-format'] = (string)$data['date_format']; - $config['delimiter'] = 'tab' === $delimiter ? "\t" : $delimiter; - $config['apply-rules'] = 1 === (int)($data['apply_rules'] ?? 0.0); - $config['specifics'] = $this->getSpecifics($data); - // validate values: - $account = $this->accountRepos->findNull($importId); - - // respond to invalid account: - if (null === $account) { - Log::error('Could not find anything for csv_import_account.', ['id' => $importId]); - $complete = false; - } - if (null !== $account) { - $config['import-account'] = $account->id; - } - - $this->repository->setConfiguration($this->importJob, $config); - if ($complete) { - $this->repository->setStage($this->importJob, 'roles'); - } - if (!$complete) { - $messages = new MessageBag; - $messages->add('account', (string)trans('import.invalid_import_account')); - - return $messages; - } - - return new MessageBag; - } - - /** - * Get the data necessary to show the configuration screen. - * - * @return array - */ - public function getNextData(): array - { - $delimiters = [ - ',' => (string)trans('form.csv_comma'), - ';' => (string)trans('form.csv_semicolon'), - 'tab' => (string)trans('form.csv_tab'), - ]; - $config = $this->importJob->configuration; - $config['date-format'] = $config['date-format'] ?? 'Ymd'; - $specifics = []; - $this->repository->setConfiguration($this->importJob, $config); - - // collect specifics. - foreach (config('csv.import_specifics') as $name => $className) { - $specifics[$name] = [ - 'name' => trans($className::getName()), - 'description' => trans($className::getDescription()), - ]; - } - - $data = [ - 'accounts' => [], - 'delimiters' => $delimiters, - 'specifics' => $specifics, - ]; - - return $data; - } - - /** - * @param array $data - * - * @return array - */ - public function getSpecifics(array $data): array - { - $return = []; - // check if specifics given are correct: - if (isset($data['specifics']) && is_array($data['specifics'])) { - - foreach ($data['specifics'] as $name) { - // verify their content. - $className = sprintf('FireflyIII\\Import\\Specifics\\%s', $name); - if (class_exists($className)) { - $return[$name] = 1; - } - } - } - - return $return; - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->accountRepos->setUser($importJob->user); - - } -} diff --git a/app/Support/Import/JobConfiguration/File/FileConfigurationInterface.php b/app/Support/Import/JobConfiguration/File/FileConfigurationInterface.php deleted file mode 100644 index ebde2cfc45..0000000000 --- a/app/Support/Import/JobConfiguration/File/FileConfigurationInterface.php +++ /dev/null @@ -1,55 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\File; - -use FireflyIII\Models\ImportJob; -use Illuminate\Support\MessageBag; - -/** - * Class FileConfigurationInterface. - * @deprecated - * @codeCoverageIgnore - */ -interface FileConfigurationInterface -{ - /** - * Store data associated with current stage. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag; - - /** - * Get the data necessary to show the configuration screen. - * - * @return array - */ - public function getNextData(): array; - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void; -} diff --git a/app/Support/Import/JobConfiguration/File/NewFileJobHandler.php b/app/Support/Import/JobConfiguration/File/NewFileJobHandler.php deleted file mode 100644 index fe8080df74..0000000000 --- a/app/Support/Import/JobConfiguration/File/NewFileJobHandler.php +++ /dev/null @@ -1,207 +0,0 @@ -. - */ - - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\File; - -use Exception; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; -use FireflyIII\Models\Attachment; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Support\Collection; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class NewFileJobHandler - * @deprecated - * @codeCoverageIgnore - */ -class NewFileJobHandler implements FileConfigurationInterface -{ - /** @var AttachmentHelperInterface */ - private $attachments; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Store data associated with current stage. - * - * @param array $data - * - * @throws FireflyException - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - // nothing to store, validate upload - // and push to next stage. - $messages = $this->validateAttachments(); - - if ($messages->count() > 0) { - return $messages; - } - - // store config if it's in one of the attachments. - $this->storeConfiguration(); - - // set file type in config: - $config = $this->repository->getConfiguration($this->importJob); - $config['file-type'] = $data['import_file_type']; - $this->repository->setConfiguration($this->importJob, $config); - $this->repository->setStage($this->importJob, 'configure-upload'); - - return new MessageBag(); - - } - - /** - * - * Get the data necessary to show the configuration screen. - * - * @codeCoverageIgnore - * @return array - */ - public function getNextData(): array - { - /** @var array $allowedTypes */ - $allowedTypes = config('import.options.file.import_formats'); - $importFileTypes = []; - $defaultImportType = config('import.options.file.default_import_format'); - foreach ($allowedTypes as $type) { - $importFileTypes[$type] = (string)trans('import.import_file_type_' . $type); - } - - return [ - 'default_type' => $defaultImportType, - 'file_types' => $importFileTypes, - ]; - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); - $this->repository->setUser($importJob->user); - } - - /** - * Store config from job. - * - */ - public function storeConfiguration(): void - { - /** @var Collection $attachments */ - $attachments = $this->repository->getAttachments($this->importJob); - /** @var Attachment $attachment */ - foreach ($attachments as $attachment) { - // if file is configuration file, store it into the job. - if ('configuration_file' === $attachment->filename) { - $this->storeConfig($attachment); - } - } - } - - /** - * Check if all attachments are UTF8. - * - * @return MessageBag - * @throws FireflyException - */ - public function validateAttachments(): MessageBag - { - $messages = new MessageBag; - /** @var Collection $attachments */ - $attachments = $this->repository->getAttachments($this->importJob); - /** @var Attachment $attachment */ - foreach ($attachments as $attachment) { - - // check if content is UTF8: - if (!$this->isUTF8($attachment)) { - $message = (string)trans('import.file_not_utf8'); - Log::error($message); - $messages->add('import_file', $message); - // delete attachment: - try { - $attachment->delete(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - throw new FireflyException(sprintf('Could not delete attachment: %s', $e->getMessage())); - } - - // @codeCoverageIgnoreEnd - - return $messages; - } - - // if file is configuration file, store it into the job. - if ('configuration_file' === $attachment->filename) { - $this->storeConfig($attachment); - } - } - - return $messages; - } - - /** - * @param Attachment $attachment - * - * @return bool - */ - private function isUTF8(Attachment $attachment): bool - { - $content = $this->attachments->getAttachmentContent($attachment); - $result = mb_detect_encoding($content, 'UTF-8', true); - if (false === $result) { - return false; - } - if ('ASCII' !== $result && 'UTF-8' !== $result) { - return false; // @codeCoverageIgnore - } - - return true; - } - - /** - * Take attachment, extract config, and put in job.\ - * - * @param Attachment $attachment - * - */ - private function storeConfig(Attachment $attachment): void - { - $content = $this->attachments->getAttachmentContent($attachment); - $json = json_decode($content, true); - if (null !== $json) { - $this->repository->setConfiguration($this->importJob, $json); - } - } -} diff --git a/app/Support/Import/JobConfiguration/FinTS/ChooseAccountHandler.php b/app/Support/Import/JobConfiguration/FinTS/ChooseAccountHandler.php deleted file mode 100644 index 7e75cfe0e8..0000000000 --- a/app/Support/Import/JobConfiguration/FinTS/ChooseAccountHandler.php +++ /dev/null @@ -1,124 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\FinTS; - - -use Carbon\Carbon; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Import\JobConfiguration\FinTSConfigurationSteps; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\FinTS\FinTS; -use Illuminate\Support\MessageBag; - -/** - * Class ChooseAccountHandler - * - * @codeCoverageIgnore - * @deprecated - */ -class ChooseAccountHandler implements FinTSConfigurationInterface -{ - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Store data associated with current stage. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - $config = $this->repository->getConfiguration($this->importJob); - $config['fints_account'] = (string)($data['fints_account'] ?? ''); - $config['local_account'] = (string)($data['local_account'] ?? ''); - $config['from_date'] = (string)($data['from_date'] ?? ''); - $config['to_date'] = (string)($data['to_date'] ?? ''); - $this->repository->setConfiguration($this->importJob, $config); - - try { - $finTS = app(FinTS::class, ['config' => $config]); - $finTS->getAccount($config['fints_account']); - } catch (FireflyException $e) { - return new MessageBag([$e->getMessage()]); - } - - $this->repository->setStage($this->importJob, FinTSConfigurationSteps::GO_FOR_IMPORT); - - return new MessageBag(); - } - - /** - * Get the data necessary to show the configuration screen. - * - * @return array - */ - public function getNextData(): array - { - $finTS = app(FinTS::class, ['config' => $this->importJob->configuration]); - $finTSAccounts = $finTS->getAccounts(); - $finTSAccountsData = []; - foreach ($finTSAccounts as $account) { - $finTSAccountsData[$account->getAccountNumber()] = $account->getIban(); - } - - $localAccounts = []; - foreach ($this->accountRepository->getAccountsByType([AccountType::ASSET]) as $localAccount) { - $display_name = $localAccount->name; - if ($localAccount->iban) { - $display_name .= sprintf(' - %s', $localAccount->iban); - } - $localAccounts[$localAccount->id] = $display_name; - } - - $data = [ - 'fints_accounts' => $finTSAccountsData, - 'fints_account' => $this->importJob->configuration['fints_account'] ?? null, - 'local_accounts' => $localAccounts, - 'local_account' => $this->importJob->configuration['local_account'] ?? null, - 'from_date' => $this->importJob->configuration['from_date'] ?? (new Carbon('now - 1 month'))->format('Y-m-d'), - 'to_date' => $this->importJob->configuration['to_date'] ?? (new Carbon('now'))->format('Y-m-d'), - ]; - - return $data; - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Import/JobConfiguration/FinTS/FinTSConfigurationInterface.php b/app/Support/Import/JobConfiguration/FinTS/FinTSConfigurationInterface.php deleted file mode 100644 index ef44396f69..0000000000 --- a/app/Support/Import/JobConfiguration/FinTS/FinTSConfigurationInterface.php +++ /dev/null @@ -1,54 +0,0 @@ -. - */ -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\FinTS; - -use FireflyIII\Models\ImportJob; -use Illuminate\Support\MessageBag; - -/** - * @deprecated - * @codeCoverageIgnore - */ -interface FinTSConfigurationInterface -{ - /** - * Store data associated with current stage. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag; - - /** - * Get the data necessary to show the configuration screen. - * - * @return array - */ - public function getNextData(): array; - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void; -} diff --git a/app/Support/Import/JobConfiguration/FinTS/NewFinTSJobHandler.php b/app/Support/Import/JobConfiguration/FinTS/NewFinTSJobHandler.php deleted file mode 100644 index 67167a61fd..0000000000 --- a/app/Support/Import/JobConfiguration/FinTS/NewFinTSJobHandler.php +++ /dev/null @@ -1,131 +0,0 @@ -. - */ -declare(strict_types=1); - - -namespace FireflyIII\Support\Import\JobConfiguration\FinTS; - - -use FireflyIII\Import\JobConfiguration\FinTSConfigurationSteps; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\FinTS\FinTS; -use Illuminate\Support\Facades\Crypt; -use Illuminate\Support\MessageBag; - -/** - * Class NewFinTSJobHandler - * @codeCoverageIgnore - * @deprecated - */ -class NewFinTSJobHandler implements FinTSConfigurationInterface -{ - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Store data associated with current stage. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - $config = []; - - $config['fints_url'] = trim($data['fints_url'] ?? ''); - $config['fints_port'] = (int)($data['fints_port'] ?? ''); - $config['fints_bank_code'] = (string)($data['fints_bank_code'] ?? ''); - $config['fints_username'] = (string)($data['fints_username'] ?? ''); - $config['fints_password'] = (string)(Crypt::encrypt($data['fints_password']) ?? ''); // verified - $config['apply-rules'] = 1 === (int)($data['apply_rules'] ?? 0); - - // sanitize FinTS URL. - $config['fints_url'] = $this->validURI($config['fints_url']) ? $config['fints_url'] : ''; - - $this->repository->setConfiguration($this->importJob, $config); - - $incomplete = false; - foreach ($config as $value) { - $incomplete = '' === $value or $incomplete; - } - - if ($incomplete) { - return new MessageBag([trans('import.incomplete_fints_form')]); - } - $finTS = app(FinTS::class, ['config' => $this->importJob->configuration]); - if (true !== ($checkConnection = $finTS->checkConnection())) { - return new MessageBag([trans('import.fints_connection_failed', ['originalError' => $checkConnection])]); - } - - $this->repository->setStage($this->importJob, FinTSConfigurationSteps::CHOOSE_ACCOUNT); - - return new MessageBag(); - } - - /** - * Get the data necessary to show the configuration screen. - * - * @return array - */ - public function getNextData(): array - { - $config = $this->importJob->configuration; - - return [ - 'fints_url' => $config['fints_url'] ?? '', - 'fints_port' => $config['fints_port'] ?? '443', - 'fints_bank_code' => $config['fints_bank_code'] ?? '', - 'fints_username' => $config['fints_username'] ?? '', - ]; - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } - - /** - * @param string $fints_url - * - * @return bool - */ - private function validURI(string $fintsUri): bool - { - $res = filter_var($fintsUri, FILTER_VALIDATE_URL); - if (false === $res) { - return false; - } - $scheme = parse_url($fintsUri, PHP_URL_SCHEME); - - return 'https' === $scheme; - } - - -} diff --git a/app/Support/Import/JobConfiguration/Spectre/AuthenticatedHandler.php b/app/Support/Import/JobConfiguration/Spectre/AuthenticatedHandler.php deleted file mode 100644 index 9fe4faf428..0000000000 --- a/app/Support/Import/JobConfiguration/Spectre/AuthenticatedHandler.php +++ /dev/null @@ -1,96 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Spectre; - -use FireflyIII\Models\ImportJob; -use Illuminate\Support\MessageBag; -use Log; - -/** - * @codeCoverageIgnore - * - * Class AuthenticatedHandler - * @deprecated - */ -class AuthenticatedHandler implements SpectreJobConfigurationInterface -{ - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - Log::debug('AuthenticatedConfigHandler::configurationComplete() always returns true'); - - return true; - } - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - Log::debug('AuthenticatedConfigHandler::configureJob() always returns empty message bag'); - - return new MessageBag(); - } - - /** - * Get data for config view. - * - * @return array - */ - public function getNextData(): array - { - Log::debug('AuthenticatedConfigHandler::getNextData() always returns []'); - - return []; - } - - /** - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - Log::debug('AuthenticatedConfigHandler::getNextView() always returns ""'); - - return ''; - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - } -} diff --git a/app/Support/Import/JobConfiguration/Spectre/ChooseAccountsHandler.php b/app/Support/Import/JobConfiguration/Spectre/ChooseAccountsHandler.php deleted file mode 100644 index 25d57c1ec5..0000000000 --- a/app/Support/Import/JobConfiguration/Spectre/ChooseAccountsHandler.php +++ /dev/null @@ -1,255 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Spectre; - - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account as AccountModel; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Spectre\Object\Account as SpectreAccount; -use FireflyIII\Services\Spectre\Object\Login; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class ChooseAccountsHandler - * @deprecated - * @codeCoverageIgnore - */ -class ChooseAccountsHandler implements SpectreJobConfigurationInterface -{ - - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var CurrencyRepositoryInterface */ - private $currencyRepository; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - Log::debug('Now in ChooseAccountsHandler::configurationComplete()'); - $config = $this->importJob->configuration; - $importAccounts = $config['account_mapping'] ?? []; - $complete = count($importAccounts) > 0 && $importAccounts !== [0 => 0]; - if ($complete) { - Log::debug('Looks like user has mapped import accounts to Firefly III accounts', $importAccounts); - $this->repository->setStage($this->importJob, 'go-for-import'); - } - - return $complete; - } - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - Log::debug('Now in ChooseAccountsHandler::configureJob()', $data); - $config = $this->importJob->configuration; - $mapping = $data['account_mapping'] ?? []; - $final = []; - $applyRules = 1 === (int)($data['apply_rules'] ?? 0); - foreach ($mapping as $spectreId => $localId) { - // validate each - $spectreId = $this->validSpectreAccount((int)$spectreId); - $accountId = $this->validLocalAccount((int)$localId); - $final[$spectreId] = $accountId; - - } - Log::debug('Final mapping is:', $final); - $messages = new MessageBag; - $config['account_mapping'] = $final; - $config['apply-rules'] = $applyRules; - $this->repository->setConfiguration($this->importJob, $config); - if ($final === [0 => 0] || 0 === count($final)) { - $messages->add('count', (string)trans('import.spectre_no_mapping')); - } - - return $messages; - } - - /** - * Get data for config view. - * - * @return array - * @throws FireflyException - * - */ - public function getNextData(): array - { - Log::debug('Now in ChooseAccountsHandler::getnextData()'); - $config = $this->importJob->configuration; - $accounts = $config['accounts'] ?? []; - if (0 === count($accounts)) { - throw new FireflyException('It seems you have no accounts with this bank. The import cannot continue.'); // @codeCoverageIgnore - } - $converted = []; - foreach ($accounts as $accountArray) { - $converted[] = new SpectreAccount($accountArray); - } - - // get the provider that was used. - $login = null; - $logins = $config['all-logins'] ?? []; - $selected = $config['selected-login'] ?? 0; - if (0 === count($logins)) { - throw new FireflyException('It seems you have no configured logins in this import job. The import cannot continue.'); // @codeCoverageIgnore - } - Log::debug(sprintf('Selected login to use is %d', $selected)); - if (0 === $selected) { - $login = new Login($logins[0]); - Log::debug(sprintf('Will use login %d (%s %s)', $login->getId(), $login->getProviderName(), $login->getCountryCode())); - } - if (0 !== $selected) { - foreach ($logins as $loginArray) { - $loginId = $loginArray['id'] ?? -1; - if ($loginId === $selected) { - $login = new Login($loginArray); - Log::debug(sprintf('Will use login %d (%s %s)', $login->getId(), $login->getProviderName(), $login->getCountryCode())); - } - } - } - if (null === $login) { - throw new FireflyException('Was not able to determine which login to use. The import cannot continue.'); // @codeCoverageIgnore - } - - // list the users accounts: - $accounts = $this->accountRepository->getAccountsByType([AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE]); - - $array = []; - /** @var AccountModel $account */ - foreach ($accounts as $account) { - $accountId = $account->id; - // TODO we can use getAccountCurrency() instead - $currencyId = (int)$this->accountRepository->getMetaValue($account, 'currency_id'); - $currency = $this->getCurrency($currencyId); - $array[$accountId] = [ - 'name' => $account->name, - 'iban' => $account->iban, - 'code' => $currency->code, - ]; - } - - return [ - 'accounts' => $converted, - 'ff_accounts' => $array, - 'login' => $login, - - ]; - } - - /** - * @codeCoverageIgnore - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - return 'import.spectre.accounts'; - } - - /** - * @codeCoverageIgnore - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->currencyRepository->setUser($importJob->user); - $this->accountRepository->setUser($importJob->user); - } - - /** - * @param int $currencyId - * - * @return TransactionCurrency - */ - private function getCurrency(int $currencyId): TransactionCurrency - { - $currency = $this->currencyRepository->findNull($currencyId); - if (null === $currency) { - return app('amount')->getDefaultCurrencyByUser($this->importJob->user); - } - - return $currency; - - } - - /** - * @param int $accountId - * - * @return int - */ - private function validLocalAccount(int $accountId): int - { - $account = $this->accountRepository->findNull($accountId); - if (null === $account) { - return 0; - } - - return $accountId; - } - - /** - * @param int $accountId - * - * @return int - */ - private function validSpectreAccount(int $accountId): int - { - $config = $this->importJob->configuration; - $accounts = $config['accounts'] ?? []; - foreach ($accounts as $account) { - if ((int)$account['id'] === $accountId) { - return $accountId; - } - } - - return 0; - } -} diff --git a/app/Support/Import/JobConfiguration/Spectre/ChooseLoginHandler.php b/app/Support/Import/JobConfiguration/Spectre/ChooseLoginHandler.php deleted file mode 100644 index e42fe7a0f7..0000000000 --- a/app/Support/Import/JobConfiguration/Spectre/ChooseLoginHandler.php +++ /dev/null @@ -1,146 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Spectre; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Spectre\Object\Login; -use FireflyIII\Support\Import\Information\GetSpectreCustomerTrait; -use FireflyIII\Support\Import\Information\GetSpectreTokenTrait; -use Illuminate\Support\MessageBag; -use Log; - - -/** - * Class ChooseLoginHandler - * @deprecated - * @codeCoverageIgnore - */ -class ChooseLoginHandler implements SpectreJobConfigurationInterface -{ - use GetSpectreCustomerTrait, GetSpectreTokenTrait; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - Log::debug('Now in ChooseLoginHandler::configurationComplete()'); - $config = $this->importJob->configuration; - if (isset($config['selected-login'])) { - Log::debug('config[selected-login] is set, return true.'); - - return true; - } - Log::debug('config[selected-login] is not set, return false.'); - - return false; - } - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - * @throws FireflyException - */ - public function configureJob(array $data): MessageBag - { - Log::debug('Now in ChooseLoginHandler::configureJob()'); - $selectedLogin = (int)($data['spectre_login_id'] ?? 0.0); - $config = $this->importJob->configuration; - $config['selected-login'] = $selectedLogin; - $this->repository->setConfiguration($this->importJob, $config); - Log::debug(sprintf('The selected login by the user is #%d', $selectedLogin)); - - // if selected login is zero, create a new one. - if (0 === $selectedLogin) { - Log::debug('Login is zero, get Spectre customer + token and store it in config.'); - $customer = $this->getCustomer($this->importJob); - // get a token for the user and redirect to next stage - $token = $this->getToken($this->importJob, $customer); - $config['customer'] = $customer->toArray(); - $config['token'] = $token->toArray(); - $this->repository->setConfiguration($this->importJob, $config); - // move job to correct stage to redirect to Spectre: - $this->repository->setStage($this->importJob, 'do-authenticate'); - - return new MessageBag; - - } - $this->repository->setStage($this->importJob, 'authenticated'); - - return new MessageBag; - } - - /** - * Get data for config view. - * - * @return array - */ - public function getNextData(): array - { - Log::debug('Now in ChooseLoginHandler::getNextData()'); - $config = $this->importJob->configuration; - $data = ['logins' => []]; - $logins = $config['all-logins'] ?? []; - Log::debug(sprintf('Count of logins in configuration is %d.', count($logins))); - foreach ($logins as $login) { - $data['logins'][] = new Login($login); - } - - return $data; - } - - /** - * @codeCoverageIgnore - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - return 'import.spectre.choose-login'; - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Import/JobConfiguration/Spectre/DoAuthenticateHandler.php b/app/Support/Import/JobConfiguration/Spectre/DoAuthenticateHandler.php deleted file mode 100644 index ab0f441dd6..0000000000 --- a/app/Support/Import/JobConfiguration/Spectre/DoAuthenticateHandler.php +++ /dev/null @@ -1,130 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Spectre; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Spectre\Object\Token; -use FireflyIII\Support\Import\Information\GetSpectreCustomerTrait; -use FireflyIII\Support\Import\Information\GetSpectreTokenTrait; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class AuthenticateConfig - * @deprecated - * @codeCoverageIgnore - */ -class DoAuthenticateHandler implements SpectreJobConfigurationInterface -{ - use GetSpectreTokenTrait, GetSpectreCustomerTrait; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * @codeCoverageIgnore - * Return true when this stage is complete. - * - * always returns false. - * - * @return bool - */ - public function configurationComplete(): bool - { - Log::debug('DoAuthenticateHandler::configurationComplete() will always return false'); - - return false; - } - - /** - * @codeCoverageIgnore - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - Log::debug('DoAuthenticateHandler::configureJob() will do nothing.'); - - return new MessageBag; - } - - /** - * Get data for config view. - * - * @return array - * @throws FireflyException - */ - public function getNextData(): array - { - Log::debug('Now in DoAuthenticateHandler::getNextData()'); - - // getNextData() only makes sure the job is ready for the next stage. - $this->repository->setStatus($this->importJob, 'ready_to_run'); - $this->repository->setStage($this->importJob, 'authenticated'); - - // get token from configuration: - $config = $this->importJob->configuration; - $token = isset($config['token']) ? new Token($config['token']) : null; - - if (null === $token) { - // get a new one from Spectre: - Log::debug('No existing token, get a new one.'); - // get a new token from Spectre. - $customer = $this->getCustomer($this->importJob); - $token = $this->getToken($this->importJob, $customer); - } - - return ['token-url' => $token->getConnectUrl()]; - } - - /** - * @codeCoverageIgnore - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - return 'import.spectre.redirect'; - } - - /** - * @codeCoverageIgnore - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Import/JobConfiguration/Spectre/NewSpectreJobHandler.php b/app/Support/Import/JobConfiguration/Spectre/NewSpectreJobHandler.php deleted file mode 100644 index b90c8e8007..0000000000 --- a/app/Support/Import/JobConfiguration/Spectre/NewSpectreJobHandler.php +++ /dev/null @@ -1,98 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Spectre; - - -use FireflyIII\Models\ImportJob; -use Illuminate\Support\MessageBag; -use Log; - -/** - * @codeCoverageIgnore - * - * Class NewSpectreJobHandler - * @deprecated - */ -class NewSpectreJobHandler implements SpectreJobConfigurationInterface -{ - - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - Log::debug('NewSpectreJobHandler::configurationComplete() always returns true'); - - return true; - } - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - Log::debug('NewSpectreJobHandler::configureJob() always returns an empty message bag'); - - return new MessageBag; - } - - /** - * Get data for config view. - * - * @return array - */ - public function getNextData(): array - { - Log::debug('NewSpectreJobHandler::getNextData() always returns []'); - - return []; - } - - /** - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - Log::debug('NewSpectreJobHandler::getNextView() always returns ""'); - - return ''; - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - } -} diff --git a/app/Support/Import/JobConfiguration/Spectre/SpectreJobConfigurationInterface.php b/app/Support/Import/JobConfiguration/Spectre/SpectreJobConfigurationInterface.php deleted file mode 100644 index dc7846b0dd..0000000000 --- a/app/Support/Import/JobConfiguration/Spectre/SpectreJobConfigurationInterface.php +++ /dev/null @@ -1,75 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Spectre; - - -use FireflyIII\Models\ImportJob; -use Illuminate\Support\MessageBag; - -/** - * Interface SpectreJobConfigurationInterface - * @deprecated - * @codeCoverageIgnore - */ -interface SpectreJobConfigurationInterface -{ - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool; - - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag; - - /** - * Get data for config view. - * - * @return array - */ - public function getNextData(): array; - - /** - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string; - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void; - -} diff --git a/app/Support/Import/JobConfiguration/Ynab/NewYnabJobHandler.php b/app/Support/Import/JobConfiguration/Ynab/NewYnabJobHandler.php deleted file mode 100644 index 0b6cb4701a..0000000000 --- a/app/Support/Import/JobConfiguration/Ynab/NewYnabJobHandler.php +++ /dev/null @@ -1,260 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Ynab; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use GuzzleHttp\Client; -use GuzzleHttp\Exception\GuzzleException; -use Illuminate\Support\MessageBag; -use Log; -use RuntimeException; - -/** - * Class NewYnabJobHandler - * @deprecated - * @codeCoverageIgnore - */ -class NewYnabJobHandler implements YnabJobConfigurationInterface -{ - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Return true when this stage is complete. - * - * @return bool - * @throws FireflyException - */ - public function configurationComplete(): bool - { - if (!$this->hasRefreshToken()) { - Log::debug('YNAB NewYnabJobHandler configurationComplete: stage is new, no refresh token, return false'); - - return false; - } - if ($this->hasRefreshToken() && $this->hasClientId() && $this->hasClientSecret()) { - Log::debug('YNAB NewYnabJobHandler configurationComplete: stage is new, has a refresh token, return true'); - // need to grab access token using refresh token - $this->getAccessToken(); - $this->repository->setStatus($this->importJob, 'ready_to_run'); - $this->repository->setStage($this->importJob, 'get_budgets'); - - return true; - } - Log::error('YNAB NewYnabJobHandler configurationComplete: something broke, return true'); - - return true; - } - - /** - * Store the job configuration. There is never anything to store for this stage. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - Log::debug('YNAB NewYnabJobHandler configureJob: nothing to do.'); - - return new MessageBag; - } - - /** - * Get data for config view. - * - * @return array - * @throws \Psr\Container\NotFoundExceptionInterface - * @throws \Psr\Container\ContainerExceptionInterface - */ - public function getNextData(): array - { - $data = []; - // here we update the job so it can redirect properly to YNAB - if (!$this->hasRefreshToken() && $this->hasClientSecret() && $this->hasClientId()) { - // update stage to make sure we catch the token. - $this->repository->setStage($this->importJob, 'catch-auth-code'); - $clientId = app('preferences')->get('ynab_client_id')->data; - $callBackUri = route('import.callback.ynab'); - $uri = sprintf( - 'https://app.youneedabudget.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code&state=%s', $clientId, $callBackUri, - $this->importJob->key - ); - $data['token-url'] = $uri; - Log::debug(sprintf('YNAB getNextData: URI to redirect to is %s', $uri)); - } - - return $data; - } - - /** - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - Log::debug('Return YNAB redirect view.'); - - return 'import.ynab.redirect'; - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } - - - /** - * @throws \Psr\Container\NotFoundExceptionInterface - * @throws \Psr\Container\ContainerExceptionInterface - * @throws FireflyException - */ - private function getAccessToken(): void - { - $clientId = app('preferences')->get('ynab_client_id')->data; - $clientSecret = app('preferences')->get('ynab_client_secret')->data; - $refreshToken = app('preferences')->get('ynab_refresh_token')->data; - $uri = sprintf( - 'https://app.youneedabudget.com/oauth/token?client_id=%s&client_secret=%s&grant_type=refresh_token&refresh_token=%s', $clientId, $clientSecret, - $refreshToken - ); - - $client = new Client(); - try { - $res = $client->request('post', $uri); - } catch (GuzzleException $e) { - Log::error($e->getMessage()); - Log::error($e->getTraceAsString()); - throw new FireflyException($e->getMessage()); - } - $statusCode = $res->getStatusCode(); - try { - $content = trim($res->getBody()->getContents()); - } catch (RuntimeException $e) { - Log::error($e->getMessage()); - Log::error($e->getTraceAsString()); - throw new FireflyException($e->getMessage()); - } - $json = json_decode($content, true) ?? []; - Log::debug(sprintf('Status code from YNAB is %d', $statusCode)); - Log::debug(sprintf('Body of result is %s', $content), $json); - - // store refresh token (if present?) as preference - // store token in job: - $configuration = $this->repository->getConfiguration($this->importJob); - $configuration['access_token'] = $json['access_token']; - $configuration['access_token_expires'] = (int)$json['created_at'] + (int)$json['expires_in']; - $this->repository->setConfiguration($this->importJob, $configuration); - - // also store new refresh token: - $refreshToken = (string)($json['refresh_token'] ?? ''); - if ('' !== $refreshToken) { - app('preferences')->set('ynab_refresh_token', $refreshToken); - } - - - Log::debug('end of NewYnabJobHandler::getAccessToken()'); - } - - /** - * Check if we have the client ID. - * - * @return bool - */ - private function hasClientId(): bool - { - $clientId = app('preferences')->getForUser($this->importJob->user, 'ynab_client_id', null); - if (null === $clientId) { - Log::debug('user has no YNAB client ID'); - - return false; - } - if ('' === (string)$clientId->data) { - Log::debug('user has no YNAB client ID (empty)'); - - return false; - } - Log::debug('user has a YNAB client ID'); - - return true; - } - - /** - * Check if we have the client secret - * - * @return bool - */ - private function hasClientSecret(): bool - { - $clientSecret = app('preferences')->getForUser($this->importJob->user, 'ynab_client_secret', null); - if (null === $clientSecret) { - Log::debug('user has no YNAB client secret'); - - return false; - } - if ('' === (string)$clientSecret->data) { - Log::debug('user has no YNAB client secret (empty)'); - - return false; - } - Log::debug('user has a YNAB client secret'); - - return true; - } - - /** - * @return bool - * @throws \Psr\Container\NotFoundExceptionInterface - * @throws \Psr\Container\ContainerExceptionInterface - */ - private function hasRefreshToken(): bool - { - $preference = app('preferences')->get('ynab_refresh_token'); - if (null === $preference) { - Log::debug('user has no YNAB refresh token.'); - - return false; - } - if ('' === (string)$preference->data) { - Log::debug('user has no YNAB refresh token (empty).'); - - return false; - } - Log::debug(sprintf('user has YNAB refresh token: %s', $preference->data)); - - return true; - } -} diff --git a/app/Support/Import/JobConfiguration/Ynab/SelectAccountsHandler.php b/app/Support/Import/JobConfiguration/Ynab/SelectAccountsHandler.php deleted file mode 100644 index dcadd72390..0000000000 --- a/app/Support/Import/JobConfiguration/Ynab/SelectAccountsHandler.php +++ /dev/null @@ -1,241 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Ynab; - - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class SelectAccountsHandler - * @deprecated - * @codeCoverageIgnore - */ -class SelectAccountsHandler implements YnabJobConfigurationInterface -{ - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var CurrencyRepositoryInterface */ - private $currencyRepository; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - Log::debug('Now in SelectAccountsHandler::configurationComplete()'); - $config = $this->importJob->configuration; - $mapping = $config['mapping'] ?? []; - if (count($mapping) > 0) { - // mapping is complete. - Log::debug('Looks like user has mapped YNAB accounts to Firefly III accounts', $mapping); - $this->repository->setStage($this->importJob, 'go-for-import'); - - return true; - } - - return false; - } - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - Log::debug('Now in SelectAccountsHandler::configureJob()', $data); - $config = $this->importJob->configuration; - $mapping = $data['account_mapping'] ?? []; - $final = []; - $applyRules = 1 === (int)($data['apply_rules'] ?? 0); - foreach ($mapping as $ynabId => $localId) { - // validate each - $ynabId = $this->validYnabAccount($ynabId); - $accountId = $this->validLocalAccount((int)$localId); - if (0 !== $accountId) { - $final[$ynabId] = $accountId; - } - } - Log::debug('Final mapping is:', $final); - $messages = new MessageBag; - $config['mapping'] = $final; - $config['apply-rules'] = $applyRules; - $this->repository->setConfiguration($this->importJob, $config); - if ($final === ['' => 0] || 0 === count($final)) { - $messages->add('count', (string)trans('import.ynab_no_mapping')); - } - - return $messages; - } - - /** - * Get data for config view. - * - * @return array - * @throws FireflyException - */ - public function getNextData(): array - { - - Log::debug('Now in ChooseAccountsHandler::getnextData()'); - $config = $this->importJob->configuration; - $ynabAccounts = $config['accounts'] ?? []; - $budget = $this->getSelectedBudget(); - if (0 === count($ynabAccounts)) { - throw new FireflyException('It seems you have no accounts with this budget. The import cannot continue.'); // @codeCoverageIgnore - } - // list the users accounts: - $ffAccounts = $this->accountRepository->getAccountsByType([AccountType::ASSET]); - - $array = []; - /** @var Account $account */ - foreach ($ffAccounts as $account) { - $accountId = $account->id; - // TODO we can use getAccountCurrency() instead - $currencyId = (int)$this->accountRepository->getMetaValue($account, 'currency_id'); - $currency = $this->getCurrency($currencyId); - $array[$accountId] = [ - 'name' => $account->name, - 'iban' => $account->iban, - 'code' => $currency->code, - ]; - } - - return [ - 'budget' => $budget, - 'ynab_accounts' => $ynabAccounts, - 'ff_accounts' => $array, - ]; - } - - /** - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - return 'import.ynab.accounts'; - } - - /** - * @codeCoverageIgnore - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->currencyRepository->setUser($importJob->user); - $this->accountRepository->setUser($importJob->user); - } - - /** - * @param int $currencyId - * - * @return TransactionCurrency - */ - private function getCurrency(int $currencyId): TransactionCurrency - { - $currency = $this->currencyRepository->findNull($currencyId); - if (null === $currency) { - return app('amount')->getDefaultCurrencyByUser($this->importJob->user); - } - - return $currency; - - } - - /** - * @return array - */ - private function getSelectedBudget(): array - { - $config = $this->repository->getConfiguration($this->importJob); - $budgets = $config['budgets'] ?? []; - $selected = $config['selected_budget'] ?? ''; - foreach ($budgets as $budget) { - if ($budget['id'] === $selected) { - return $budget; - } - } - - return $budgets[0] ?? []; - } - - /** - * @param int $accountId - * - * @return int - */ - private function validLocalAccount(int $accountId): int - { - $account = $this->accountRepository->findNull($accountId); - if (null === $account) { - return 0; - } - - return $accountId; - } - - /** - * @param string $accountId - * - * @return string - */ - private function validYnabAccount(string $accountId): string - { - $config = $this->importJob->configuration; - $accounts = $config['accounts'] ?? []; - foreach ($accounts as $account) { - if ($account['id'] === $accountId) { - return $accountId; - } - } - - return ''; - } -} diff --git a/app/Support/Import/JobConfiguration/Ynab/SelectBudgetHandler.php b/app/Support/Import/JobConfiguration/Ynab/SelectBudgetHandler.php deleted file mode 100644 index 9a2790d270..0000000000 --- a/app/Support/Import/JobConfiguration/Ynab/SelectBudgetHandler.php +++ /dev/null @@ -1,187 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Ynab; - -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Illuminate\Support\Collection; -use Illuminate\Support\MessageBag; -use Log; - -/** - * Class SelectBudgetHandler - * @deprecated - * @codeCoverageIgnore - */ -class SelectBudgetHandler implements YnabJobConfigurationInterface -{ - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var Collection */ - private $accounts; - /** @var CurrencyRepositoryInterface */ - private $currencyRepository; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool - { - Log::debug('Now in SelectBudgetHandler::configComplete'); - $configuration = $this->repository->getConfiguration($this->importJob); - $selectedBudget = $configuration['selected_budget'] ?? ''; - if ('' !== $selectedBudget) { - Log::debug(sprintf('Selected budget is %s, config is complete. Return true.', $selectedBudget)); - $this->repository->setStage($this->importJob, 'get_accounts'); - - return true; - } - Log::debug('User has not selected a budget yet, config is not yet complete.'); - - return false; - } - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag - { - Log::debug('Now in SelectBudgetHandler::configureJob'); - $configuration = $this->repository->getConfiguration($this->importJob); - $configuration['selected_budget'] = $data['budget_id']; - - Log::debug(sprintf('Set selected budget to %s', $data['budget_id'])); - Log::debug('Mark job as ready for next stage.'); - - - $this->repository->setConfiguration($this->importJob, $configuration); - - return new MessageBag; - } - - /** - * Get data for config view. - * - * @return array - */ - public function getNextData(): array - { - Log::debug('Now in SelectBudgetHandler::getNextData'); - $configuration = $this->repository->getConfiguration($this->importJob); - $budgets = $configuration['budgets'] ?? []; - $available = []; - $notAvailable = []; - $total = count($budgets); - foreach ($budgets as $budget) { - if ($this->haveAssetWithCurrency($budget['currency_code'])) { - Log::debug('Add budget to available list.'); - $available[$budget['id']] = $budget['name'] . ' (' . $budget['currency_code'] . ')'; - continue; - } - Log::debug('Add budget to notAvailable list.'); - $notAvailable[$budget['id']] = $budget['name'] . ' (' . $budget['currency_code'] . ')'; - - } - - return [ - 'available' => $available, - 'not_available' => $notAvailable, - 'total' => $total, - ]; - } - - /** - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string - { - Log::debug('Now in SelectBudgetHandler::getNextView'); - - return 'import.ynab.select-budgets'; - } - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - - $this->repository->setUser($importJob->user); - $this->currencyRepository->setUser($importJob->user); - $this->accountRepository->setUser($importJob->user); - - $this->accounts = $this->accountRepository->getAccountsByType([AccountType::ASSET, AccountType::DEFAULT]); - } - - /** - * @param string $code - * - * @return bool - */ - private function haveAssetWithCurrency(string $code): bool - { - $currency = $this->currencyRepository->findByCodeNull($code); - if (null === $currency) { - Log::debug(sprintf('No currency X found with code "%s"', $code)); - - return false; - } - /** @var Account $account */ - foreach ($this->accounts as $account) { - // TODO we can use getAccountCurrency() instead - $currencyId = (int)$this->accountRepository->getMetaValue($account, 'currency_id'); - Log::debug(sprintf('Currency of %s is %d (looking for %d).', $account->name, $currencyId, $currency->id)); - if ($currencyId === $currency->id) { - Log::debug('Return true!'); - - return true; - } - } - Log::debug('Found nothing, return false.'); - - return false; - } -} diff --git a/app/Support/Import/JobConfiguration/Ynab/YnabJobConfigurationInterface.php b/app/Support/Import/JobConfiguration/Ynab/YnabJobConfigurationInterface.php deleted file mode 100644 index 1752b566e6..0000000000 --- a/app/Support/Import/JobConfiguration/Ynab/YnabJobConfigurationInterface.php +++ /dev/null @@ -1,73 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\JobConfiguration\Ynab; - -use FireflyIII\Models\ImportJob; -use Illuminate\Support\MessageBag; - -/** - * Interface YnabJobConfigurationInterface - * @deprecated - * @codeCoverageIgnore - */ -interface YnabJobConfigurationInterface -{ - /** - * Return true when this stage is complete. - * - * @return bool - */ - public function configurationComplete(): bool; - - - /** - * Store the job configuration. - * - * @param array $data - * - * @return MessageBag - */ - public function configureJob(array $data): MessageBag; - - /** - * Get data for config view. - * - * @return array - */ - public function getNextData(): array; - - /** - * Get the view for this stage. - * - * @return string - */ - public function getNextView(): string; - - /** - * Set the import job. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void; -} diff --git a/app/Support/Import/Placeholder/ColumnValue.php b/app/Support/Import/Placeholder/ColumnValue.php deleted file mode 100644 index 81fd343174..0000000000 --- a/app/Support/Import/Placeholder/ColumnValue.php +++ /dev/null @@ -1,116 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Placeholder; - -/** - * Class ColumnValue - * - * @codeCoverageIgnore - * @deprecated - */ -class ColumnValue -{ - /** @var int */ - private $mappedValue; - /** @var string */ - private $originalRole; - /** @var string */ - private $role; - /** @var string */ - private $value; - - /** - * ColumnValue constructor. - */ - public function __construct() - { - $this->mappedValue = 0; - } - - /** - * @return int - */ - public function getMappedValue(): int - { - return $this->mappedValue; - } - - /** - * @param int $mappedValue - */ - public function setMappedValue(int $mappedValue): void - { - $this->mappedValue = $mappedValue; - } - - /** - * @return string - */ - public function getOriginalRole(): string - { - return $this->originalRole; - } - - /** - * @param string $originalRole - */ - public function setOriginalRole(string $originalRole): void - { - $this->originalRole = $originalRole; - } - - /** - * @return string - */ - public function getRole(): string - { - return $this->role; - } - - /** - * @param string $role - */ - public function setRole(string $role): void - { - $this->role = $role; - } - - /** - * @return string - */ - public function getValue(): string - { - return $this->value; - } - - /** - * @param string $value - */ - public function setValue(string $value): void - { - $this->value = $value; - } - - -} diff --git a/app/Support/Import/Placeholder/ImportTransaction.php b/app/Support/Import/Placeholder/ImportTransaction.php deleted file mode 100644 index 63155ff058..0000000000 --- a/app/Support/Import/Placeholder/ImportTransaction.php +++ /dev/null @@ -1,446 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Placeholder; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Import\Converter\Amount; -use FireflyIII\Import\Converter\AmountCredit; -use FireflyIII\Import\Converter\AmountDebit; -use FireflyIII\Import\Converter\AmountNegated; -use FireflyIII\Import\Converter\ConverterInterface; -use Log; - -/** - * Class ImportTransaction - * @codeCoverageIgnore - * @deprecated - */ -class ImportTransaction -{ - /** @var string */ - public $accountBic; - /** @var string */ - public $accountIban; - /** @var int */ - public $accountId; - /** @var string */ - public $accountName; - /** @var string */ - public $accountNumber; - /** @var string */ - public $amount; - /** @var string */ - public $amountCredit; - /** @var string */ - public $amountDebit; - /** @var string */ - public $amountNegated; - /** @var int */ - public $billId; - /** @var string */ - public $billName; - /** @var int */ - public $budgetId; - /** @var string */ - public $budgetName; - /** @var int */ - public $categoryId; - /** @var string */ - public $categoryName; - /** @var string */ - public $currencyCode; - /** @var int */ - public $currencyId; - /** @var string */ - public $currencyName; - /** @var string */ - public $currencySymbol; - /** @var string */ - public $date; - /** @var string */ - public $description; - /** @var string */ - public $externalId; - /** @var string */ - public $foreignAmount; - /** @var string */ - public $foreignCurrencyCode; - /** @var int */ - public $foreignCurrencyId; - /** @var array */ - public $meta; - /** @var array */ - public $modifiers; - /** @var string */ - public $note; - /** @var string */ - public $opposingBic; - /** @var string */ - public $opposingIban; - /** @var int */ - public $opposingId; - /** @var string */ - public $opposingName; - /** @var string */ - public $opposingNumber; - /** @var array */ - public $tags; - - /** - * ImportTransaction constructor. - */ - public function __construct() - { - $this->tags = []; - $this->modifiers = []; - $this->meta = []; - $this->description = ''; - $this->note = ''; - - // mappable items, set to 0: - $this->accountId = 0; - $this->budgetId = 0; - $this->billId = 0; - $this->currencyId = 0; - $this->categoryId = 0; - $this->foreignCurrencyId = 0; - $this->opposingId = 0; - - } - - /** - * @param ColumnValue $columnValue - * - * @throws FireflyException - * - */ - public function addColumnValue(ColumnValue $columnValue): void - { - $role = $columnValue->getRole(); - $basics = [ - 'account-iban' => 'accountIban', - 'account-name' => 'accountName', - 'account-bic' => 'accountBic', - 'account-number' => 'accountNumber', - 'amount_debit' => 'amountDebit', - 'amount_credit' => 'amountCredit', - 'amount_negated' => 'amountNegated', - 'amount' => 'amount', - 'amount_foreign' => 'foreignAmount', - 'bill-name' => 'billName', - 'budget-name' => 'budgetName', - 'category-name' => 'categoryName', - 'currency-name' => 'currencyName', - 'currency-code' => 'currencyCode', - 'currency-symbol' => 'currencySymbol', - 'external-id' => 'externalId', - 'foreign-currency-code' => 'foreignCurrencyCode', - 'date-transaction' => 'date', - 'opposing-iban' => 'opposingIban', - 'opposing-name' => 'opposingName', - 'opposing-bic' => 'opposingBic', - 'opposing-number' => 'opposingNumber', - ]; - - $replaceOldRoles = [ - 'original-source' => 'original_source', - 'sepa-cc' => 'sepa_cc', - 'sepa-ct-op' => 'sepa_ct_op', - 'sepa-ct-id' => 'sepa_ct_id', - 'sepa-db' => 'sepa_db', - 'sepa-country' => 'sepa_country', - 'sepa-ep' => 'sepa_ep', - 'sepa-ci' => 'sepa_ci', - 'sepa-batch-id' => 'sepa_batch_id', - 'internal-reference' => 'internal_reference', - 'date-interest' => 'date_interest', - 'date-invoice' => 'date_invoice', - 'date-book' => 'date_book', - 'date-payment' => 'date_payment', - 'date-process' => 'date_process', - 'date-due' => 'date_due', - ]; - if (array_key_exists($role, $replaceOldRoles)) { - $role = $replaceOldRoles[$role]; - } - - if (isset($basics[$role])) { - $field = $basics[$role]; - $this->$field = $columnValue->getValue(); - - return; - } - - $mapped = [ - 'account-id' => 'accountId', - 'bill-id' => 'billId', - 'budget-id' => 'budgetId', - 'category-id' => 'categoryId', - 'currency-id' => 'currencyId', - 'foreign-currency-id' => 'foreignCurrencyId', - 'opposing-id' => 'opposingId', - ]; - if (isset($mapped[$role])) { - $field = $mapped[$role]; - $mappedValue = $this->getMappedValue($columnValue); - $this->$field = $mappedValue; - Log::debug(sprintf('Going to set the %s. Original value is "%s", mapped value is "%s".', $role, $columnValue->getValue(), $mappedValue)); - - return; - } - - $meta = ['sepa_ct_id', 'sepa_ct_op', 'sepa_db', 'sepa_cc', 'sepa_country', 'sepa_batch_id', 'sepa_ep', 'sepa_ci', 'internal_reference', 'date_interest', - 'date_invoice', 'date_book', 'date_payment', 'date_process', 'date_due', 'original_source']; - Log::debug(sprintf('Now going to check role "%s".', $role)); - if (in_array($role, $meta, true)) { - Log::debug(sprintf('Role "%s" is in allowed meta roles, so store its value "%s".', $role, $columnValue->getValue())); - $this->meta[$role] = $columnValue->getValue(); - - return; - } - - $modifiers = ['generic-debit-credit', 'ing-debit-credit', 'rabo-debit-credit']; - if (in_array($role, $modifiers, true)) { - $this->modifiers[$role] = $columnValue->getValue(); - - return; - } - - switch ($role) { - default: - // @codeCoverageIgnoreStart - throw new FireflyException( - sprintf('ImportTransaction cannot handle role "%s" with value "%s"', $role, $columnValue->getValue()) - ); - // @codeCoverageIgnoreEnd - case 'description': - $this->description = trim($this->description . ' ' . $columnValue->getValue()); - break; - case 'note': - $this->note = trim($this->note . ' ' . $columnValue->getValue()); - break; - case 'tags-comma': - $tags = explode(',', $columnValue->getValue()); - $this->tags = array_unique(array_merge($this->tags, $tags)); - break; - case 'tags-space': - $tags = explode(' ', $columnValue->getValue()); - $this->tags = array_unique(array_merge($this->tags, $tags)); - break; - case '_ignore': - break; - - } - } - - /** - * Calculate the amount of this transaction. - * - * @return string - */ - public function calculateAmount(): string - { - Log::debug('Now in importTransaction->calculateAmount()'); - $info = $this->selectAmountInput(); - $class = $info['class'] ?? ''; - if ('' === $class) { - Log::error('No amount information (conversion class) for this row.'); - - return ''; - } - - Log::debug(sprintf('Converter class is %s', $info['class'])); - /** @var ConverterInterface $amountConverter */ - $amountConverter = app($info['class']); - $result = $amountConverter->convert($info['amount']); - Log::debug(sprintf('First attempt to convert gives "%s"', $result)); - // modify - /** - * @var string $role - * @var string $modifier - */ - foreach ($this->modifiers as $role => $modifier) { - $class = sprintf('FireflyIII\\Import\\Converter\\%s', config(sprintf('csv.import_roles.%s.converter', $role))); - /** @var ConverterInterface $converter */ - $converter = app($class); - Log::debug(sprintf('Now launching converter %s', $class)); - $conversion = $converter->convert($modifier); - if ($conversion === -1) { - $result = app('steam')->negative($result); - } - if (1 === $conversion) { - $result = app('steam')->positive($result); - } - Log::debug(sprintf('convertedAmount after conversion is %s', $result)); - } - - Log::debug(sprintf('After modifiers the result is: "%s"', $result)); - - - return $result; - } - - /** - * The method that calculates the foreign amount isn't nearly as complex,\ - * because Firefly III only supports one foreign amount field. So the foreign amount is there - * or isn't. That's about it. However, if it's there, modifiers will be applied too. - * - * @return string - */ - public function calculateForeignAmount(): string - { - if (null === $this->foreignAmount) { - Log::debug('ImportTransaction holds no foreign amount info.'); - - return ''; - } - /** @var ConverterInterface $amountConverter */ - $amountConverter = app(Amount::class); - $result = $amountConverter->convert($this->foreignAmount); - Log::debug(sprintf('First attempt to convert foreign amount gives "%s"', $result)); - /** - * @var string $role - * @var string $modifier - */ - foreach ($this->modifiers as $role => $modifier) { - $class = sprintf('FireflyIII\\Import\\Converter\\%s', config(sprintf('csv.import_roles.%s.converter', $role))); - /** @var ConverterInterface $converter */ - $converter = app($class); - Log::debug(sprintf('Now launching converter %s', $class)); - $conversion = $converter->convert($modifier); - if ($conversion === -1) { - $result = app('steam')->negative($result); - } - if (1 === $conversion) { - $result = app('steam')->positive($result); - } - Log::debug(sprintf('Foreign amount after conversion is %s', $result)); - } - - Log::debug(sprintf('After modifiers the foreign amount is: "%s"', $result)); - - return $result; - } - - /** - * This array is being used to map the account the user is using. - * - * @codeCoverageIgnore - * @return array - */ - public function getAccountData(): array - { - return [ - 'iban' => $this->accountIban, - 'name' => $this->accountName, - 'number' => $this->accountNumber, - 'bic' => $this->accountBic, - ]; - } - - /** - * @codeCoverageIgnore - * @return array - */ - public function getCurrencyData(): array - { - return [ - 'name' => $this->currencyName, - 'code' => $this->currencyCode, - 'symbol' => $this->currencySymbol, - ]; - } - - /** - * @codeCoverageIgnore - * @return array - */ - public function getForeignCurrencyData(): array - { - return [ - 'code' => $this->foreignCurrencyCode, - ]; - } - - /** - * @codeCoverageIgnore - * @return array - */ - public function getOpposingAccountData(): array - { - return [ - 'iban' => $this->opposingIban, - 'name' => $this->opposingName, - 'number' => $this->opposingNumber, - 'bic' => $this->opposingBic, - ]; - } - - /** - * Returns the mapped value if it exists in the ColumnValue object. - * - * @param ColumnValue $columnValue - * - * @return int - */ - private function getMappedValue(ColumnValue $columnValue): int - { - return $columnValue->getMappedValue() > 0 ? $columnValue->getMappedValue() : (int)$columnValue->getValue(); - } - - /** - * This methods decides which input value to use for the amount calculation. - * - * @return array - */ - private function selectAmountInput(): array - { - $info = []; - $converterClass = ''; - if (null !== $this->amount) { - Log::debug('Amount value is not NULL, assume this is the correct value.'); - $converterClass = Amount::class; - $info['amount'] = $this->amount; - } - if (null !== $this->amountDebit) { - Log::debug('Amount DEBIT value is not NULL, assume this is the correct value (overrules Amount).'); - $converterClass = AmountDebit::class; - $info['amount'] = $this->amountDebit; - } - if (null !== $this->amountCredit) { - Log::debug('Amount CREDIT value is not NULL, assume this is the correct value (overrules Amount and AmountDebit).'); - $converterClass = AmountCredit::class; - $info['amount'] = $this->amountCredit; - } - if (null !== $this->amountNegated) { - Log::debug('Amount NEGATED value is not NULL, assume this is the correct value (overrules Amount and AmountDebit and AmountCredit).'); - $converterClass = AmountNegated::class; - $info['amount'] = $this->amountNegated; - } - $info['class'] = $converterClass; - - return $info; - } - -} diff --git a/app/Support/Import/Routine/Bunq/PaymentConverter.php b/app/Support/Import/Routine/Bunq/PaymentConverter.php deleted file mode 100644 index b40363c7a3..0000000000 --- a/app/Support/Import/Routine/Bunq/PaymentConverter.php +++ /dev/null @@ -1,251 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Bunq; - -use bunq\Model\Generated\Endpoint\Payment as BunqPayment; -use bunq\Model\Generated\Object\LabelMonetaryAccount; -use Carbon\Carbon; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Factory\AccountFactory; -use FireflyIII\Models\Account as LocalAccount; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\TransactionType; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Log; - -/** - * Class PaymentConverter - * @deprecated - * @codeCoverageIgnore - */ -class PaymentConverter -{ - /** @var AccountFactory */ - private $accountFactory; - /** @var AccountRepositoryInterface */ - private $accountRepos; - /** @var array */ - private $configuration; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $importJobRepos; - - public function __construct() - { - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->importJobRepos = app(ImportJobRepositoryInterface::class); - $this->accountFactory = app(AccountFactory::class); - if ('testing' === config('app.env')) { - Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); - } - } - - /** - * Convert a bunq transaction to a usable transaction for Firefly III. - * - * @param BunqPayment $payment - * - * @param LocalAccount $source - * - * @return array - * @throws FireflyException - */ - public function convert(BunqPayment $payment, LocalAccount $source): array - { - $paymentId = $payment->getId(); - Log::debug(sprintf('Now in convert() for payment with ID #%d', $paymentId)); - Log::debug(sprintf('Source account is assumed to be "%s" (#%d)', $source->name, $source->id)); - $type = TransactionType::WITHDRAWAL; - $counterParty = $payment->getCounterpartyAlias(); - $amount = $payment->getAmount(); - - // some debug info: - Log::debug('Assume its a witdrawal'); - Log::debug(sprintf('Subtype is %s', $payment->getSubType())); - Log::debug(sprintf('Type is %s', $payment->getType())); - Log::debug(sprintf('Amount is %s %s', $amount->getCurrency(), $amount->getValue())); - - $expected = AccountType::EXPENSE; - if (1 === bccomp($amount->getValue(), '0')) { - // amount + means that its a deposit. - $expected = AccountType::REVENUE; - $type = TransactionType::DEPOSIT; - Log::debug(sprintf('Amount is %s %s, so assume this is a deposit.', $amount->getCurrency(), $amount->getValue())); - } - Log::debug(sprintf('Now going to convert counter party to Firefly III account. Expect it to be a "%s" account.', $expected)); - $destination = $this->convertToAccount($counterParty, $expected); - - // switch source and destination if necessary. - if (1 === bccomp($amount->getValue(), '0')) { - Log::debug('Because amount is > 0, will now swap source with destination.'); - [$source, $destination] = [$destination, $source]; - } - - if ($source->accountType->type === AccountType::ASSET && $destination->accountType->type === AccountType::ASSET) { - $type = TransactionType::TRANSFER; - Log::debug('Because both transctions are asset, will make it a transfer.'); - } - Log::debug(sprintf('Bunq created = %s', $payment->getCreated())); - $created = new Carbon($payment->getCreated(), 'UTC'); - // correct timezone to system timezone. - $created->setTimezone(config('app.timezone')); - - $description = $payment->getDescription(); - if ('' === $payment->getDescription() && 'SAVINGS' === $payment->getType()) { - $description = 'Auto-save for savings goal.'; - } - - $storeData = [ - 'user' => $this->importJob->user_id, - 'type' => $type, - 'date' => $created->format('Y-m-d H:i:s'), - 'timestamp' => $created->toAtomString(), - 'description' => $description, - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - 'bill_id' => null, - 'bill_name' => null, - 'tags' => [$payment->getType(), $payment->getSubType()], - 'internal_reference' => $paymentId, - 'external_id' => $paymentId, - 'notes' => null, - 'bunq_payment_id' => $paymentId, - 'original-source' => sprintf('bunq-v%s', config('firefly.version')), - 'transactions' => [ - // single transaction: - [ - 'description' => null, - 'amount' => $amount->getValue(), - 'currency_id' => null, - 'currency_code' => $amount->getCurrency(), - 'foreign_amount' => null, - 'foreign_currency_id' => null, - 'foreign_currency_code' => null, - 'budget_id' => null, - 'budget_name' => null, - 'category_id' => null, - 'category_name' => null, - 'source_id' => $source->id, - 'source_name' => null, - 'destination_id' => $destination->id, - 'destination_name' => null, - 'reconciled' => false, - 'identifier' => 0, - ], - ], - ]; - Log::info(sprintf('Parsed %s: "%s" (%s).', $created->format('Y-m-d H:i:s'), $storeData['description'], $storeData['transactions'][0]['amount'])); - - return $storeData; - - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->accountRepos->setUser($importJob->user); - $this->importJobRepos->setUser($importJob->user); - $this->accountFactory->setUser($importJob->user); - $this->configuration = $this->importJobRepos->getConfiguration($importJob); - } - - /** - * @param LabelMonetaryAccount $party - * @param string $expectedType - * - * @return LocalAccount - * @throws FireflyException - */ - private function convertToAccount(LabelMonetaryAccount $party, string $expectedType): LocalAccount - { - Log::debug(sprintf('in convertToAccount() with LabelMonetaryAccount')); - if (null !== $party->getIban()) { - Log::debug(sprintf('Opposing party has IBAN "%s"', $party->getIban())); - - // find account in 'bunq-iban' array first. - $bunqIbans = $this->configuration['bunq-iban'] ?? []; - Log::debug('Bunq ibans configuration is', $bunqIbans); - - if (isset($bunqIbans[$party->getIban()])) { - Log::debug('IBAN is known in array.'); - $accountId = (int)$bunqIbans[$party->getIban()]; - $result = $this->accountRepos->findNull($accountId); - if (null !== $result) { - Log::debug(sprintf('Search for #%s (IBAN "%s"), found "%s" (#%d)', $accountId, $party->getIban(), $result->name, $result->id)); - - return $result; - } - } - - // find opposing party by IBAN second. - $result = $this->accountRepos->findByIbanNull($party->getIban(), [$expectedType]); - if (null !== $result) { - Log::debug(sprintf('Search for "%s" resulted in account "%s" (#%d)', $party->getIban(), $result->name, $result->id)); - - return $result; - } - - // try to find asset account just in case: - if ($expectedType !== AccountType::ASSET) { - $result = $this->accountRepos->findByIbanNull($party->getIban(), [AccountType::ASSET]); - if (null !== $result) { - Log::debug(sprintf('Search for Asset "%s" resulted in account %s (#%d)', $party->getIban(), $result->name, $result->id)); - - return $result; - } - } - } - Log::debug('Found no account for opposing party, must create a new one.'); - - // create new account: - $data = [ - 'user_id' => $this->importJob->user_id, - 'iban' => $party->getIban(), - 'name' => $party->getLabelUser()->getDisplayName(), - 'account_type_id' => null, - 'account_type' => $expectedType, - 'virtual_balance' => null, - 'active' => true, - ]; - $account = $this->accountFactory->create($data); - Log::debug( - sprintf( - 'Converted label monetary account "%s" to NEW "%s" account "%s" (#%d)', - $party->getLabelUser()->getDisplayName(), - $expectedType, - $account->name, $account->id - ) - ); - - return $account; - } - - -} diff --git a/app/Support/Import/Routine/Bunq/StageImportDataHandler.php b/app/Support/Import/Routine/Bunq/StageImportDataHandler.php deleted file mode 100644 index 199d05b7dd..0000000000 --- a/app/Support/Import/Routine/Bunq/StageImportDataHandler.php +++ /dev/null @@ -1,465 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Bunq; - -use bunq\Model\Generated\Endpoint\Payment as BunqPayment; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Factory\AccountFactory; -use FireflyIII\Models\Account as LocalAccount; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\Preference; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Bunq\ApiContext; -use FireflyIII\Services\Bunq\Payment; -use Log; - -/** - * Class StageImportDataHandler - * @deprecated - * @codeCoverageIgnore - */ -class StageImportDataHandler -{ - /** @var int */ - private const DOWNLOAD_BACKWARDS = 1; - /** @var int */ - private const DOWNLOAD_FORWARDS = 2; - - /** @var bool */ - public $stillRunning; - /** @var AccountFactory */ - private $accountFactory; - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var PaymentConverter */ - private $converter; - /** @var ImportJob */ - private $importJob; - /** @var array */ - private $jobConfiguration; - /** @var ImportJobRepositoryInterface */ - private $repository; - /** @var float */ - private $timeStart; - /** @var array */ - private $transactions; - - public function __construct() - { - $this->stillRunning = true; - $this->timeStart = microtime(true); - $this->converter = app(PaymentConverter::class); - - } - - /** - * @codeCoverageIgnore - * @return array - */ - public function getTransactions(): array - { - return $this->transactions; - } - - /** - * @return bool - */ - public function isStillRunning(): bool - { - return $this->stillRunning; - } - - /** - * - * @throws FireflyException - */ - public function run(): void - { - $this->getContext(); - $this->converter->setImportJob($this->importJob); - $config = $this->repository->getConfiguration($this->importJob); - $accounts = $config['accounts'] ?? []; - $mapping = $config['mapping'] ?? []; - $collection = [[]]; - $this->jobConfiguration = $config; - /** @var array $bunqAccount */ - foreach ($accounts as $bunqAccount) { - $bunqAccountId = $bunqAccount['id'] ?? 0; - $localId = $mapping[$bunqAccountId] ?? 0; - if (0 !== $localId && 0 !== $bunqAccountId) { - Log::info(sprintf('Now at bunq account #%d and local account #%d', $bunqAccountId, $localId)); - $localAccount = $this->getLocalAccount((int)$localId); - $collection[] = $this->getTransactionsFromBunq($bunqAccountId, $localAccount); - } - } - $totalSet = array_merge(...$collection); - $this->transactions = $totalSet; - } - - /** - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void - { - $this->transactions = []; - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->accountFactory = app(AccountFactory::class); - $this->repository->setUser($importJob->user); - $this->accountRepository->setUser($importJob->user); - $this->accountFactory->setUser($importJob->user); - } - - /** - * @param BunqPayment $payment - * @param LocalAccount $source - * - * @return array - * @throws FireflyException - */ - private function convertPayment(BunqPayment $payment, LocalAccount $source): array - { - Log::debug(sprintf('Now at payment with ID #%d', $payment->getId())); - - return $this->converter->convert($payment, $source); - } - - /** - * @throws FireflyException - */ - private function getContext(): void - { - /** @var Preference $preference */ - $preference = app('preferences')->getForUser($this->importJob->user, 'bunq_api_context', null); - if (null !== $preference && '' !== (string)$preference->data) { - // restore API context - /** @var ApiContext $apiContext */ - $apiContext = app(ApiContext::class); - $apiContext->fromJson($preference->data); - - return; - } - throw new FireflyException('The bunq API context is unexpectedly empty.'); // @codeCoverageIgnore - } - - /** - * Get the direction in which we must download. - * - * @param int $bunqAccountId - * - * @return int - */ - private function getDirection(int $bunqAccountId): int - { - Log::debug(sprintf('Now in getDirection(%d)', $bunqAccountId)); - - // if oldest transaction ID is 0, AND the newest transaction is 0 - // we don't know about this account, so we must go backward in time. - $oldest = \Preferences::getForUser($this->importJob->user, sprintf('bunq-oldest-transaction-%d', $bunqAccountId), 0); - $newest = \Preferences::getForUser($this->importJob->user, sprintf('bunq-newest-transaction-%d', $bunqAccountId), 0); - - if (0 === $oldest->data && 0 === $newest->data) { - Log::debug(sprintf('Oldest tranaction ID is %d and newest tranasction ID is %d, so go backwards.', $oldest->data, $newest->data)); - - return self::DOWNLOAD_BACKWARDS; - } - - // if newest is not zero but oldest is zero, go forward. - if (0 === $oldest->data && 0 !== $newest->data) { - Log::debug(sprintf('Oldest tranaction ID is %d and newest tranasction ID is %d, so go forwards.', $oldest->data, $newest->data)); - - return self::DOWNLOAD_FORWARDS; - } - - Log::debug(sprintf('Oldest tranaction ID is %d and newest tranasction ID is %d, so go backwards.', $oldest->data, $newest->data)); - - return self::DOWNLOAD_BACKWARDS; - } - - /** - * @param int $accountId - * - * @return LocalAccount - * @throws FireflyException - */ - private function getLocalAccount(int $accountId): LocalAccount - { - $account = $this->accountRepository->findNull($accountId); - if (null === $account) { - throw new FireflyException(sprintf('Cannot find Firefly III asset account with ID #%d. Job must stop now.', $accountId)); // @codeCoverageIgnore - } - if ($account->accountType->type !== AccountType::ASSET) { - throw new FireflyException(sprintf('Account with ID #%d is not an asset account. Job must stop now.', $accountId)); // @codeCoverageIgnore - } - - return $account; - } - - /** - * @param int $bunqAccountId - * @param LocalAccount $localAccount - * - * @return array - * @throws FireflyException - */ - private function getTransactionsFromBunq(int $bunqAccountId, LocalAccount $localAccount): array - { - Log::debug(sprintf('Now in getTransactionsFromBunq(%d).', $bunqAccountId)); - - $direction = $this->getDirection($bunqAccountId); - $return = []; - if (self::DOWNLOAD_BACKWARDS === $direction) { - Log::info('For this account we go backwards in time.'); - // go back either from NULL or from ID. - // ID is the very last transaction downloaded from bunq. - $preference = \Preferences::getForUser($this->importJob->user, sprintf('bunq-oldest-transaction-%d', $bunqAccountId), 0); - $transactionId = 0 === $preference->data ? null : $preference->data; - $return = $this->goBackInTime($bunqAccountId, $localAccount, $transactionId); - } - if (self::DOWNLOAD_FORWARDS === $direction) { - Log::info('For this account we go forwards in time.'); - // go forward from ID. There is no NULL, young padawan - $return = $this->goForwardInTime($bunqAccountId, $localAccount); - } - - return $return; - } - - /** - * This method downloads the transactions from bunq going back in time. Assuming bunq - * is fairly consistent with the transactions it provides through the API, the method - * will store both the highest and the lowest transaction ID downloaded in this manner. - * - * The highest transaction ID is used to continue forward in time. The lowest is used to continue - * even further back in time. - * - * The lowest transaction ID can also be given to this method as a parameter (as $startTransaction). - * - * @param int $bunqAccountId - * @param LocalAccount $localAccount - * @param int $startTransaction - * - * @return array - * @throws FireflyException - */ - private function goBackInTime(int $bunqAccountId, LocalAccount $localAccount, int $startTransaction = null): array - { - Log::debug(sprintf('Now in goBackInTime(#%d, #%s, #%s).', $bunqAccountId, $localAccount->id, $startTransaction)); - $hasMoreTransactions = true; - $olderId = $startTransaction; - $oldestTransaction = null; - $newestTransaction = null; - $count = 0; - $return = []; - - /* - * Do a loop during which we run: - */ - while ($hasMoreTransactions && $this->timeRunning() < 25) { - Log::debug(sprintf('Now in loop #%d', $count)); - Log::debug(sprintf('Now running for %s seconds.', $this->timeRunning())); - - /* - * Send request to bunq. - */ - /** @var Payment $paymentRequest */ - $paymentRequest = app(Payment::class); - $params = ['count' => 197, 'older_id' => $olderId]; - $response = $paymentRequest->listing($bunqAccountId, $params); - $pagination = $response->getPagination(); - Log::debug('Params for the request to bunq are: ', $params); - - /* - * If pagination is not null, we can go back even further. - */ - if (null !== $pagination) { - $olderId = $pagination->getOlderId(); - Log::debug(sprintf('Pagination object is not null, new olderID is "%s"', $olderId)); - } - - /* - * Loop the results from bunq - */ - Log::debug('Now looping results from bunq...'); - /** @var BunqPayment $payment */ - foreach ($response->getValue() as $index => $payment) { - $return[] = $this->convertPayment($payment, $localAccount); - $paymentId = $payment->getId(); - /* - * If oldest and newest transaction are null, they have to be set: - */ - $oldestTransaction = $oldestTransaction ?? $paymentId; - $newestTransaction = $newestTransaction ?? $paymentId; - - /* - * Then, overwrite if appropriate - */ - $oldestTransaction = $paymentId < $oldestTransaction ? $paymentId : $oldestTransaction; - $newestTransaction = $paymentId > $newestTransaction ? $paymentId : $newestTransaction; - } - - /* - * After the loop, check if Firefly III must loop again. - */ - Log::debug(sprintf('Count of result is now %d', count($return))); - $count++; - if (null === $olderId) { - Log::debug('Older ID is NULL, so stop looping cause we are done!'); - $hasMoreTransactions = false; - $this->stillRunning = false; - /* - * We no longer care about the oldest transaction ID: - */ - $oldestTransaction = 0; - } - if (null === $pagination) { - Log::debug('No pagination object, stop looping.'); - $hasMoreTransactions = false; - $this->stillRunning = false; - /* - * We no longer care about the oldest transaction ID: - */ - $oldestTransaction = 0; - } - // sleep 2 seconds to prevent hammering bunq. - sleep(2); - } - // store newest and oldest tranasction ID to be used later: - \Preferences::setForUser($this->importJob->user, sprintf('bunq-oldest-transaction-%d', $bunqAccountId), $oldestTransaction); - \Preferences::setForUser($this->importJob->user, sprintf('bunq-newest-transaction-%d', $bunqAccountId), $newestTransaction); - Log::info(sprintf('Downloaded and parsed %d transactions from bunq.', count($return))); - - return $return; - } - - /** - * @param int $bunqAccountId - * @param LocalAccount $localAccount - * - * @return array - * @throws FireflyException - */ - private function goForwardInTime(int $bunqAccountId, LocalAccount $localAccount): array - { - Log::debug(sprintf('Now in goForwardInTime(%d).', $bunqAccountId)); - $hasMoreTransactions = true; - $count = 0; - $return = []; - $newestTransaction = null; - - /* - * Go forward from the newest transaction we know about: - */ - $preferenceName = sprintf('bunq-newest-transaction-%d', $bunqAccountId); - $transactionPref = \Preferences::getForUser($this->importJob->user, $preferenceName, 0); - $newerId = (int)$transactionPref->data; - - /* - * Run a loop. - */ - while ($hasMoreTransactions && $this->timeRunning() < 25) { - /* - * Debug information: - */ - Log::debug(sprintf('Now in loop #%d', $count)); - Log::debug(sprintf('Now running for %s seconds.', $this->timeRunning())); - - /* - * Send a request to bunq. - */ - /** @var Payment $paymentRequest */ - $paymentRequest = app(Payment::class); - $params = ['count' => 197, 'newer_id' => $newerId]; - $response = $paymentRequest->listing($bunqAccountId, $params); - $pagination = $response->getPagination(); - Log::debug('Submit payment request with params', $params); - - /* - * If pagination is not null, we can go forward even further. - */ - if (null !== $pagination) { - $newerId = $pagination->getNewerId(); - Log::debug(sprintf('Pagination object is not null, newerID is "%s"', $newerId)); - } - Log::debug('Now looping results...'); - /* - * Process the bunq loop. - */ - /** @var BunqPayment $payment */ - foreach ($response->getValue() as $payment) { - $return[] = $this->convertPayment($payment, $localAccount); - $paymentId = $payment->getId(); - - /* - * If oldest and newest transaction are null, they have to be set: - */ - $newestTransaction = $newestTransaction ?? $paymentId; - - /* - * Then, overwrite if appropriate - */ - $newestTransaction = $paymentId > $newestTransaction ? $paymentId : $newestTransaction; - } - - /* - * After the loop, check if Firefly III must loop again. - */ - Log::debug(sprintf('Count of result is now %d', count($return))); - $count++; - if (null === $newerId) { - Log::debug('Newer ID is NULL, so stop looping cause we are done!'); - $hasMoreTransactions = false; - $this->stillRunning = false; - } - if (null === $pagination) { - Log::debug('No pagination object, stop looping.'); - $hasMoreTransactions = false; - $this->stillRunning = false; - } - // sleep 2 seconds to prevent hammering bunq. - sleep(2); - } - - // store newest tranasction ID to be used later: - \Preferences::setForUser($this->importJob->user, sprintf('bunq-newest-transaction-%d', $bunqAccountId), $newestTransaction); - Log::info(sprintf('Downloaded and parsed %d transactions from bunq.', count($return))); - - return $return; - } - - /** - * @return float - */ - private function timeRunning(): float - { - $time_end = microtime(true); - - return $time_end - $this->timeStart; - } -} diff --git a/app/Support/Import/Routine/Bunq/StageNewHandler.php b/app/Support/Import/Routine/Bunq/StageNewHandler.php deleted file mode 100644 index ab844508bc..0000000000 --- a/app/Support/Import/Routine/Bunq/StageNewHandler.php +++ /dev/null @@ -1,379 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Bunq; - -use bunq\exception\BunqException; -use bunq\Model\Generated\Endpoint\MonetaryAccount as BunqMonetaryAccount; -use bunq\Model\Generated\Endpoint\MonetaryAccountBank; -use bunq\Model\Generated\Endpoint\MonetaryAccountJoint; -use bunq\Model\Generated\Endpoint\MonetaryAccountLight; -use bunq\Model\Generated\Endpoint\MonetaryAccountSavings; -use bunq\Model\Generated\Object\CoOwner; -use bunq\Model\Generated\Object\Pointer; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\Preference; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Bunq\ApiContext; -use FireflyIII\Services\Bunq\MonetaryAccount; -use Log; - -/** - * Class StageNewHandler - * @deprecated - * @codeCoverageIgnore - */ -class StageNewHandler -{ - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * @throws FireflyException - */ - public function run(): void - { - Log::info('Now in StageNewHandler::run()'); - /** @var Preference $preference */ - $preference = app('preferences')->getForUser($this->importJob->user, 'bunq_api_context', null); - if (null !== $preference && '' !== (string)$preference->data) { - // restore API context - /** @var ApiContext $apiContext */ - $apiContext = app(ApiContext::class); - $apiContext->fromJson($preference->data); - - // list bunq accounts: - $accounts = $this->listAccounts(); - - // store in job: - $config = $this->repository->getConfiguration($this->importJob); - $config['accounts'] = $accounts; - $this->repository->setConfiguration($this->importJob, $config); - - return; - } - throw new FireflyException('The bunq API context is unexpectedly empty.'); // @codeCoverageIgnore - } // @codeCoverageIgnore - - /** - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } - - /** - * @return array - * @throws FireflyException - */ - private function listAccounts(): array - { - Log::debug('Now in StageNewHandler::listAccounts()'); - $accounts = []; - /** @var MonetaryAccount $lister */ - $lister = app(MonetaryAccount::class); - $result = $lister->listing(); - - /** @var BunqMonetaryAccount $monetaryAccount */ - foreach ($result->getValue() as $monetaryAccount) { - try { - $object = $monetaryAccount->getReferencedObject(); - // @codeCoverageIgnoreStart - } catch (BunqException $e) { - throw new FireflyException($e->getMessage()); - } - // @codeCoverageIgnoreEnd - if (null !== $object) { - $array = null; - switch (get_class($object)) { - case MonetaryAccountBank::class: - Log::debug('Going to convert a MonetaryAccountBank'); - /** @var MonetaryAccountBank $object */ - $array = $this->processMab($object); - break; - case MonetaryAccountJoint::class: - Log::debug('Going to convert a MonetaryAccountJoint'); - /** @var MonetaryAccountJoint $object */ - $array = $this->processMaj($object); - break; - case MonetaryAccountLight::class: - Log::debug('Going to convert a MonetaryAccountLight'); - /** @var MonetaryAccountLight $object */ - $array = $this->processMal($object); - break; - case MonetaryAccountSavings::class; - Log::debug('Going to convert a MonetaryAccountSavings'); - /** @var MonetaryAccountSavings $object */ - $array = $this->processMas($object); - break; - default: - // @codeCoverageIgnoreStart - throw new FireflyException(sprintf('Bunq import routine cannot handle account of type "%s".', get_class($object))); - // @codeCoverageIgnoreEnd - } - if (null !== $array) { - Log::debug('Array is not null'); - $accounts[] = $array; - $this->reportFinding($array); - } - } - } - Log::info(sprintf('Found %d account(s) at bunq', count($accounts)), $accounts); - - return $accounts; - } - - /** - * @param MonetaryAccountBank $mab - * - * @return array - */ - private function processMab(MonetaryAccountBank $mab): array - { - $setting = $mab->getSetting(); - $return = [ - 'id' => $mab->getId(), - 'currency_code' => $mab->getCurrency(), - 'description' => $mab->getDescription(), - 'balance' => $mab->getBalance(), - 'status' => $mab->getStatus(), - 'type' => 'MonetaryAccountBank', - 'iban' => null, - 'aliases' => [], - ]; - - if (null !== $setting) { - $return['settings'] = [ - 'color' => $mab->getSetting()->getColor(), - 'default_avatar_status' => $mab->getSetting()->getDefaultAvatarStatus(), - 'restriction_chat' => $mab->getSetting()->getRestrictionChat(), - ]; - } - if (null !== $mab->getAlias()) { - /** @var Pointer $alias */ - foreach ($mab->getAlias() as $alias) { - $return['aliases'][] = [ - 'type' => $alias->getType(), - 'name' => $alias->getName(), - 'value' => $alias->getValue(), - ]; - - // store IBAN alias separately: - if ('IBAN' === $alias->getType()) { - $return['iban'] = $alias->getValue(); - } - } - } - - return $return; - } - - /** - * @param MonetaryAccountJoint $maj - * - * @return array - */ - private function processMaj(MonetaryAccountJoint $maj): array - { - Log::debug('Now processing a MAJ'); - $setting = $maj->getSetting(); - $return = [ - 'id' => $maj->getId(), - 'currency_code' => $maj->getCurrency(), - 'description' => $maj->getDescription(), - 'balance' => $maj->getBalance(), - 'status' => $maj->getStatus(), - 'type' => 'MonetaryAccountJoint', - 'co-owners' => [], - 'aliases' => [], - ]; - - if (null !== $setting) { - $return['settings'] = [ - 'color' => $maj->getSetting()->getColor(), - 'default_avatar_status' => $maj->getSetting()->getDefaultAvatarStatus(), - 'restriction_chat' => $maj->getSetting()->getRestrictionChat(), - ]; - Log::debug('Setting is not null.'); - } - if (null !== $maj->getAlias()) { - Log::debug(sprintf('Alias is not NULL. Count is %d', count($maj->getAlias()))); - /** @var Pointer $alias */ - foreach ($maj->getAlias() as $alias) { - $return['aliases'][] = [ - 'type' => $alias->getType(), - 'name' => $alias->getName(), - 'value' => $alias->getValue(), - ]; - // store IBAN alias separately: - if ('IBAN' === $alias->getType()) { - $return['iban'] = $alias->getValue(); - } - } - } - $coOwners = $maj->getAllCoOwner() ?? []; - Log::debug(sprintf('Count of getAllCoOwner is %d', count($coOwners))); - /** @var CoOwner $coOwner */ - foreach ($coOwners as $coOwner) { - $alias = $coOwner->getAlias(); - if (null !== $alias) { - Log::debug('Alias is not NULL'); - $name = (string)$alias->getDisplayName(); - Log::debug(sprintf('Name is "%s"', $name)); - if ('' !== $name) { - $return['co-owners'][] = $name; - } - } - } - - return $return; - } - - /** - * @param MonetaryAccountLight $mal - * - * @return array - */ - private function processMal(MonetaryAccountLight $mal): array - { - $setting = $mal->getSetting(); - $return = [ - 'id' => $mal->getId(), - 'currency_code' => $mal->getCurrency(), - 'description' => $mal->getDescription(), - 'balance' => $mal->getBalance(), - 'status' => $mal->getStatus(), - 'type' => 'MonetaryAccountLight', - 'aliases' => [], - ]; - - if (null !== $setting) { - $return['settings'] = [ - 'color' => $mal->getSetting()->getColor(), - 'default_avatar_status' => $mal->getSetting()->getDefaultAvatarStatus(), - 'restriction_chat' => $mal->getSetting()->getRestrictionChat(), - ]; - } - if (null !== $mal->getAlias()) { - /** @var Pointer $alias */ - foreach ($mal->getAlias() as $alias) { - $return['aliases'][] = [ - 'type' => $alias->getType(), - 'name' => $alias->getName(), - 'value' => $alias->getValue(), - ]; - // store IBAN alias separately: - if ('IBAN' === $alias->getType()) { - $return['iban'] = $alias->getValue(); - } - } - } - - return $return; - } - - /** - * @param MonetaryAccountSavings $object - * - * @return array - */ - private function processMas(MonetaryAccountSavings $object): array - { - Log::debug('Now in processMas()'); - $setting = $object->getSetting(); - $return = [ - 'id' => $object->getId(), - 'currency_code' => $object->getCurrency(), - 'description' => $object->getDescription(), - 'balance' => $object->getBalance(), - 'status' => $object->getStatus(), - 'type' => 'MonetaryAccountSavings', - 'aliases' => [], - 'savingsGoal' => [], - ]; - - if (null !== $setting) { - $return['settings'] = [ - 'color' => $object->getSetting()->getColor(), - 'default_avatar_status' => $object->getSetting()->getDefaultAvatarStatus(), - 'restriction_chat' => $object->getSetting()->getRestrictionChat(), - ]; - } - if (null !== $object->getAlias()) { - Log::debug('MAS has aliases'); - /** @var Pointer $alias */ - foreach ($object->getAlias() as $alias) { - Log::debug(sprintf('Alias type is "%s", with name "%s" and value "%s"', $alias->getType(), $alias->getName(), $alias->getValue())); - $return['aliases'][] = [ - 'type' => $alias->getType(), - 'name' => $alias->getName(), - 'value' => $alias->getValue(), - ]; - // store IBAN alias separately: - if ('IBAN' === $alias->getType()) { - $return['iban'] = $alias->getValue(); - } - } - } - $goal = $object->getSavingsGoal(); - $return['savingsGoal'] = [ - 'currency' => $goal->getCurrency(), - 'value' => $goal->getValue(), - 'percentage' => $object->getSavingsGoalProgress(), - ]; - Log::debug('End of processMas()', $return); - - return $return; - } - - /** - * Basic report method. - * - * @param array $array - */ - private function reportFinding(array $array): void - { - $bunqId = $array['id'] ?? ''; - $bunqDescription = $array['description'] ?? ''; - $bunqIBAN = ''; - - // find IBAN: - $aliases = $array['aliases'] ?? []; - foreach ($aliases as $alias) { - $type = $alias['type'] ?? 'none'; - if ('IBAN' === $type) { - $bunqIBAN = $alias['value'] ?? ''; - } - } - - Log::info(sprintf('Found account at bunq. ID #%d, title "%s" and IBAN "%s" ', $bunqId, $bunqDescription, $bunqIBAN)); - } -} diff --git a/app/Support/Import/Routine/Fake/StageAhoyHandler.php b/app/Support/Import/Routine/Fake/StageAhoyHandler.php deleted file mode 100644 index a0a81f392b..0000000000 --- a/app/Support/Import/Routine/Fake/StageAhoyHandler.php +++ /dev/null @@ -1,45 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Fake; - -use Log; - -/** - * @codeCoverageIgnore - * Class StageAhoyHandler - * @deprecated - */ -class StageAhoyHandler -{ - /** - */ - public function run(): void - { - for ($i = 0; $i < 5; $i++) { - Log::debug(sprintf('Am now in stage AHOY hander, sleeping... (%d)', $i)); - sleep(1); - } - } - -} diff --git a/app/Support/Import/Routine/Fake/StageFinalHandler.php b/app/Support/Import/Routine/Fake/StageFinalHandler.php deleted file mode 100644 index f3bea38970..0000000000 --- a/app/Support/Import/Routine/Fake/StageFinalHandler.php +++ /dev/null @@ -1,157 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Fake; - -use Carbon\Carbon; -use FireflyIII\Models\ImportJob; - -/** - * @codeCoverageIgnore - * Class StageFinalHandler - * @deprecated - */ -class StageFinalHandler -{ - /** @var ImportJob */ - private $importJob; - - /** - * @return array - * @throws \Exception - */ - public function getTransactions(): array - { - $transactions = []; - - for ($i = 0; $i < 5; $i++) { - $transaction = [ - 'type' => 'withdrawal', - 'date' => Carbon::now()->format('Y-m-d'), - 'tags' => '', - 'user' => $this->importJob->user_id, - - // all custom fields: - 'internal_reference' => null, - 'notes' => null, - - // journal data: - 'description' => 'Some random description #' . random_int(1, 10000), - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - 'bill_id' => null, - 'bill_name' => null, - 'original-source' => sprintf('fake-import-v%s', config('firefly.version')), - - // transaction data: - 'transactions' => [ - [ - 'type' => 'withdrawal', - 'date' => Carbon::now()->format('Y-m-d'), - 'currency_id' => null, - 'currency_code' => 'EUR', - 'description' => 'Some random description #' . random_int(1, 10000), - 'amount' => random_int(500, 5000) / 100, - 'tags' => [], - 'user' => $this->importJob->user_id, - 'budget_id' => null, - 'budget_name' => null, - 'category_id' => null, - 'category_name' => null, - 'source_id' => null, - 'source_name' => 'Checking Account', - 'destination_id' => null, - 'destination_name' => 'Random expense account #' . random_int(1, 10000), - 'foreign_currency_id' => null, - 'foreign_currency_code' => null, - 'foreign_amount' => null, - 'reconciled' => false, - 'identifier' => 0, - ], - ], - ]; - - $transactions[] = $transaction; - } - - // add a transfer I know exists already - $transactions[] = [ - 'type' => 'transfer', - 'date' => '2017-02-28', - 'tags' => '', - 'user' => $this->importJob->user_id, - - // all custom fields: - 'internal_reference' => null, - 'notes' => null, - - // journal data: - 'description' => 'Saving money for February', - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - 'bill_id' => null, - 'bill_name' => null, - - // transaction data: - 'transactions' => [ - [ - 'type' => 'transfer', - 'user' => $this->importJob->user_id, - 'date' => '2017-02-28', - 'currency_id' => null, - 'currency_code' => 'EUR', - 'tags' => [], - 'description' => 'Saving money for February', - 'amount' => '140', - 'budget_id' => null, - 'budget_name' => null, - 'category_id' => null, - 'category_name' => null, - 'source_id' => 1, - 'source_name' => 'Checking Account', - 'destination_id' => 2, - 'destination_name' => null, - 'foreign_currency_id' => null, - 'foreign_currency_code' => null, - 'foreign_amount' => null, - 'reconciled' => false, - 'identifier' => 0, - ], - ], - ]; - - - return $transactions; - - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - } - -} diff --git a/app/Support/Import/Routine/Fake/StageNewHandler.php b/app/Support/Import/Routine/Fake/StageNewHandler.php deleted file mode 100644 index bf274d8f6e..0000000000 --- a/app/Support/Import/Routine/Fake/StageNewHandler.php +++ /dev/null @@ -1,45 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Fake; - -use Log; - -/** - * @codeCoverageIgnore - * Class StageNewHandler - * @deprecated - */ -class StageNewHandler -{ - /** - */ - public function run(): void - { - for ($i = 0; $i < 5; $i++) { - Log::debug(sprintf('Am now in stage new hander, sleeping... (%d)', $i)); - sleep(1); - } - } - -} diff --git a/app/Support/Import/Routine/File/AssetAccountMapper.php b/app/Support/Import/Routine/File/AssetAccountMapper.php deleted file mode 100644 index b7c4398ae6..0000000000 --- a/app/Support/Import/Routine/File/AssetAccountMapper.php +++ /dev/null @@ -1,135 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\User; -use Log; - -/** - * Class AssetAccountMapper - * Can also handle liability accounts. - * @deprecated - */ -class AssetAccountMapper -{ - /** @var int */ - private $defaultAccount; - /** @var AccountRepositoryInterface */ - private $repository; - /** @var User */ - private $user; - - /** @var array */ - private $types; - - /** - * AssetAccountMapper constructor. - */ - public function __construct() - { - $this->types = [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]; - } - - /** - * Based upon data in the importable, try to find or create the asset account account. - * - * @param int|null $accountId - * @param array $data - * - * @return Account - * - */ - public function map(?int $accountId, array $data): Account - { - Log::debug(sprintf('Now in AssetAccountMapper::map(%d)', $accountId), $data); - if ((int)$accountId > 0) { - // find asset account with this ID: - $result = $this->repository->findNull($accountId); - if (null !== $result && in_array($result->accountType->type, $this->types, true)) { - Log::debug(sprintf('Found %s "%s" based on given ID %d', $result->accountType->type, $result->name, $accountId)); - - return $result; - } - if (null !== $result && in_array($result->accountType->type, $this->types, true)) { - Log::warning( - sprintf('Found account "%s" based on given ID %d but its a %s, return nothing.', $result->name, $accountId, $result->accountType->type) - ); - } - } - // find by (respectively): - // IBAN, accountNumber, name, - $fields = ['iban' => 'findByIbanNull', 'number' => 'findByAccountNumber', 'name' => 'findByName']; - foreach ($fields as $field => $function) { - $value = (string)($data[$field] ?? ''); - if ('' === $value) { - Log::debug(sprintf('Array does not contain a value for %s. Continue', $field)); - continue; - } - $result = $this->repository->$function($value, $this->types); - Log::debug(sprintf('Going to run %s() with argument "%s" (asset account or liability)', $function, $value)); - if (null !== $result) { - Log::debug(sprintf('Found asset account "%s". Return it!', $result->name)); - - return $result; - } - } - Log::debug('Found nothing. Will return default account.'); - // still NULL? Return default account. - $default = null; - if ($this->defaultAccount > 0) { - $default = $this->repository->findNull($this->defaultAccount); - } - if (null === $default) { - Log::debug('Default account is NULL! Simply result first account in system.'); - $default = $this->repository->getAccountsByType([AccountType::ASSET])->first(); - } - - Log::debug(sprintf('Return default account "%s" (#%d). Return it!', $default->name, $default->id)); - - return $default; - } - - /** - * @param int $defaultAccount - */ - public function setDefaultAccount(int $defaultAccount): void - { - $this->defaultAccount = $defaultAccount; - } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - $this->repository = app(AccountRepositoryInterface::class); - $this->defaultAccount = 0; - $this->repository->setUser($user); - - } -} diff --git a/app/Support/Import/Routine/File/CSVProcessor.php b/app/Support/Import/Routine/File/CSVProcessor.php deleted file mode 100644 index 225d16d0d6..0000000000 --- a/app/Support/Import/Routine/File/CSVProcessor.php +++ /dev/null @@ -1,91 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use Log; - - -/** - * Class CSVProcessor - * @deprecated - * @codeCoverageIgnore - */ -class CSVProcessor implements FileProcessorInterface -{ - /** @var ImportJob */ - private $importJob; - - /** - * Fires the file processor. - * - * @return array - * @throws FireflyException - */ - public function run(): array - { - Log::debug('Now in CSVProcessor() run'); - - // create separate objects to handle separate tasks: - /** @var LineReader $lineReader */ - $lineReader = app(LineReader::class); - $lineReader->setImportJob($this->importJob); - $lines = $lineReader->getLines(); - - // convert each line into a small set of "ColumnValue" objects, - // joining each with its mapped counterpart. - /** @var MappingConverger $mappingConverger */ - $mappingConverger = app(MappingConverger::class); - $mappingConverger->setImportJob($this->importJob); - $converged = $mappingConverger->converge($lines); - - // validate mapped values: - /** @var MappedValuesValidator $validator */ - $validator = app(MappedValuesValidator::class); - $validator->setImportJob($this->importJob); - $mappedValues = $validator->validate($mappingConverger->getMappedValues()); - - // make import transaction things from these objects. - /** @var ImportableCreator $creator */ - $creator = app(ImportableCreator::class); - $importables = $creator->convertSets($converged); - - /** @var ImportableConverter $converter */ - $converter = app(ImportableConverter::class); - $converter->setImportJob($this->importJob); - $converter->setMappedValues($mappedValues); - - return $converter->convert($importables); - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - Log::debug('Now in setImportJob()'); - $this->importJob = $importJob; - } -} diff --git a/app/Support/Import/Routine/File/CurrencyMapper.php b/app/Support/Import/Routine/File/CurrencyMapper.php deleted file mode 100644 index 89d8aebe90..0000000000 --- a/app/Support/Import/Routine/File/CurrencyMapper.php +++ /dev/null @@ -1,103 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\User; -use Log; - -/** - * Class CurrencyMapper - * @deprecated - * @codeCoverageIgnore - */ -class CurrencyMapper -{ - /** @var CurrencyRepositoryInterface */ - private $repository; - /** @var User */ - private $user; - - /** - * @param int|null $currencyId - * @param array $data - * - * @return TransactionCurrency|null - */ - public function map(?int $currencyId, array $data): ?TransactionCurrency - { - Log::debug('Now in CurrencyMapper::map()'); - if ((int)$currencyId > 0) { - $result = $this->repository->findNull($currencyId); - if (null !== $result) { - Log::debug(sprintf('Found currency %s based on ID, return it.', $result->code)); - - return $result; - } - } - // try to find it by all other fields. - $fields = ['code' => 'findByCodeNull', 'symbol' => 'findBySymbolNull', 'name' => 'findByNameNull']; - foreach ($fields as $field => $function) { - $value = (string)($data[$field] ?? ''); - if ('' === $value) { - Log::debug(sprintf('Array does not contain a value for %s. Continue', $field)); - continue; - } - Log::debug(sprintf('Will search for currency using %s() and argument "%s".', $function, $value)); - $result = $this->repository->$function($value); - if (null !== $result) { - Log::debug(sprintf('Found result: Currency #%d, code "%s"', $result->id, $result->code)); - - return $result; - } - } - if (!isset($data['code'])) { - return null; - } - - // if still nothing, and fields not null, try to create it - $creation = [ - 'code' => $data['code'], - 'name' => $data['name'] ?? $data['code'], - 'symbol' => $data['symbol'] ?? $data['code'], - 'enabled' => true, - 'decimal_places' => 2, - ]; - - // could be NULL - return $this->repository->store($creation); - } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - $this->repository = app(CurrencyRepositoryInterface::class); - $this->repository->setUser($user); - } - -} diff --git a/app/Support/Import/Routine/File/FileProcessorInterface.php b/app/Support/Import/Routine/File/FileProcessorInterface.php deleted file mode 100644 index 5835f5ec9a..0000000000 --- a/app/Support/Import/Routine/File/FileProcessorInterface.php +++ /dev/null @@ -1,50 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use FireflyIII\Models\ImportJob; - - -/** - * Interface FileProcessorInterface - * @deprecated - * @codeCoverageIgnore - */ -interface FileProcessorInterface -{ - - /** - * Fires the file processor. - * - * @return array - */ - public function run(): array; - - /** - * Set values. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void; -} diff --git a/app/Support/Import/Routine/File/ImportableConverter.php b/app/Support/Import/Routine/File/ImportableConverter.php deleted file mode 100644 index b512a66122..0000000000 --- a/app/Support/Import/Routine/File/ImportableConverter.php +++ /dev/null @@ -1,347 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use Carbon\Carbon; -use Carbon\Exceptions\InvalidDateException; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\Placeholder\ImportTransaction; -use InvalidArgumentException; -use Log; - -/** - * Class ImportableConverter - * @deprecated - * @codeCoverageIgnore - */ -class ImportableConverter -{ - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var AssetAccountMapper */ - private $assetMapper; - /** @var array */ - private $config; - /** @var CurrencyMapper */ - private $currencyMapper; - /** @var TransactionCurrency */ - private $defaultCurrency; - /** @var ImportJob */ - private $importJob; - /** @var array */ - private $mappedValues; - /** @var OpposingAccountMapper */ - private $opposingMapper; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Convert ImportTransaction to factory-compatible array. - * - * @param array $importables - * - * @return array - */ - public function convert(array $importables): array - { - $total = count($importables); - Log::debug(sprintf('Going to convert %d import transactions', $total)); - $result = []; - /** @var ImportTransaction $importable */ - foreach ($importables as $index => $importable) { - Log::debug(sprintf('Now going to parse importable %d of %d', $index + 1, $total)); - try { - $entry = $this->convertSingle($importable); - } catch (FireflyException $e) { - $this->repository->addErrorMessage($this->importJob, sprintf('Row #%d: %s', $index + 1, $e->getMessage())); - continue; - } - if (null !== $entry) { - $result[] = $entry; - Log::debug('Final result of importable converter', $entry); - } - } - - return $result; - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->config = $importJob->configuration; - - // repository is used for error messages - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - - // asset account mapper can map asset accounts (makes sense right?) - $this->assetMapper = app(AssetAccountMapper::class); - $this->assetMapper->setUser($importJob->user); - $this->assetMapper->setDefaultAccount($this->config['import-account'] ?? 0); - - // asset account repository is used for currency information - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->accountRepository->setUser($importJob->user); - - // opposing account mapper: - $this->opposingMapper = app(OpposingAccountMapper::class); - $this->opposingMapper->setUser($importJob->user); - - // currency mapper: - $this->currencyMapper = app(CurrencyMapper::class); - $this->currencyMapper->setUser($importJob->user); - $this->defaultCurrency = app('amount')->getDefaultCurrencyByUser($importJob->user); - } - - /** - * @codeCoverageIgnore - * - * @param array $mappedValues - */ - public function setMappedValues(array $mappedValues): void - { - $this->mappedValues = $mappedValues; - } - - /** - * @param string|null $date - * - * @return string|null - */ - private function convertDateValue(string $date = null): ?string - { - $result = null; - if (null !== $date) { - try { - // add exclamation mark for better parsing. http://php.net/manual/en/datetime.createfromformat.php - $dateFormat = $this->config['date-format'] ?? 'Ymd'; - if ('!' !== $dateFormat[0]) { - $dateFormat = '!' . $dateFormat; - } - $object = Carbon::createFromFormat($dateFormat, $date); - $result = $object->format('Y-m-d H:i:s'); - Log::debug(sprintf('createFromFormat: Turning "%s" into "%s" using "%s"', $date, $result, $this->config['date-format'] ?? 'Ymd')); - } catch (InvalidDateException|InvalidArgumentException $e) { - Log::error($e->getMessage()); - Log::error($e->getTraceAsString()); - } - } - - return $result; - } - - /** - * @param ImportTransaction $importable - * - * @return array - * @throws FireflyException - */ - private function convertSingle(ImportTransaction $importable): array - { - Log::debug(sprintf('Description is: "%s"', $importable->description)); - $foreignAmount = $importable->calculateForeignAmount(); - $amount = $importable->calculateAmount(); - - Log::debug('All meta data: ', $importable->meta); - - if ('' === $amount) { - $amount = $foreignAmount; - } - if ('' === $amount) { - throw new FireflyException('No transaction amount information.'); - } - - // amount is 0? skip - if (0 === bccomp($amount, '0')) { - throw new FireflyException('Amount of transaction is zero.'); - } - - $source = $this->assetMapper->map($importable->accountId, $importable->getAccountData()); - $destination = $this->opposingMapper->map($importable->opposingId, $amount, $importable->getOpposingAccountData()); - - // if the amount is positive, switch source and destination (account and opposing account) - if (1 === bccomp($amount, '0')) { - $source = $this->opposingMapper->map($importable->opposingId, $amount, $importable->getOpposingAccountData()); - $destination = $this->assetMapper->map($importable->accountId, $importable->getAccountData()); - Log::debug( - sprintf( - '%s is positive, so "%s" (#%d) is now source and "%s" (#%d) is now destination.', - $amount, $source->name, $source->id, $destination->name, $destination->id - ) - ); - } - - $currency = $this->currencyMapper->map($importable->currencyId, $importable->getCurrencyData()); - $foreignCurrency = $this->currencyMapper->map($importable->foreignCurrencyId, $importable->getForeignCurrencyData()); - - Log::debug(sprintf('"%s" (#%d) is source and "%s" (#%d) is destination.', $source->name, $source->id, $destination->name, $destination->id)); - - - if ($destination->id === $source->id) { - throw new FireflyException( - sprintf( - 'Source ("%s", #%d) and destination ("%s", #%d) are the same account.', $source->name, $source->id, $destination->name, $destination->id - ) - ); - } - - $transactionType = $this->getTransactionType($source->accountType->type, $destination->accountType->type); - $currency = $currency ?? $this->getCurrency($source, $destination); - - if ('unknown' === $transactionType) { - $message = sprintf( - 'Cannot determine transaction type. Source account is a %s, destination is a %s', $source->accountType->type, $destination->accountType->type - ); - Log::error($message, ['source' => $source->toArray(), 'dest' => $destination->toArray()]); - throw new FireflyException($message); - } - - return [ - - 'user' => $this->importJob->user_id, - 'group_title' => null, - 'transactions' => [ - [ - 'user' => $this->importJob->user_id, - 'type' => strtolower($transactionType), - 'date' => $this->convertDateValue($importable->date) ?? Carbon::now()->format('Y-m-d H:i:s'), - 'order' => 0, - - 'currency_id' => $currency->id, - 'currency_code' => null, - - 'foreign_currency_id' => $importable->foreignCurrencyId, - 'foreign_currency_code' => null === $foreignCurrency ? null : $foreignCurrency->code, - - 'amount' => $amount, - 'foreign_amount' => $foreignAmount, - - 'description' => $importable->description, - - 'source_id' => $source->id, - 'source_name' => null, - 'destination_id' => $destination->id, - 'destination_name' => null, - - 'budget_id' => $importable->budgetId, - 'budget_name' => $importable->budgetName, - - 'category_id' => $importable->categoryId, - 'category_name' => $importable->categoryName, - - 'bill_id' => $importable->billId, - 'bill_name' => $importable->billName, - - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - - 'reconciled' => false, - - 'notes' => $importable->note, - 'tags' => $importable->tags, - - 'internal_reference' => $importable->meta['internal_reference'] ?? null, - 'external_id' => $importable->externalId, - 'original_source' => $importable->meta['original_source'] ?? null, - - 'sepa_cc' => $importable->meta['sepa_cc'] ?? null, - 'sepa_ct_op' => $importable->meta['sepa_ct_op'] ?? null, - 'sepa_ct_id' => $importable->meta['sepa_ct_id'] ?? null, - 'sepa_db' => $importable->meta['sepa_db'] ?? null, - 'sepa_country' => $importable->meta['sepa_country'] ?? null, - 'sepa_ep' => $importable->meta['sepa_ep'] ?? null, - 'sepa_ci' => $importable->meta['sepa_ci'] ?? null, - 'sepa_batch_id' => $importable->meta['sepa_batch_id'] ?? null, - - 'interest_date' => $this->convertDateValue($importable->meta['date_interest'] ?? null), - 'book_date' => $this->convertDateValue($importable->meta['date_book'] ?? null), - 'process_date' => $this->convertDateValue($importable->meta['date_process'] ?? null), - 'due_date' => $this->convertDateValue($importable->meta['date_due'] ?? null), - 'payment_date' => $this->convertDateValue($importable->meta['date_payment'] ?? null), - 'invoice_date' => $this->convertDateValue($importable->meta['date_invoice'] ?? null), - ], - ], - ]; - - } - - /** - * @param Account $source - * @param Account $destination - * - * @return TransactionCurrency - */ - private function getCurrency(Account $source, Account $destination): TransactionCurrency - { - $currency = null; - if ($destination->accountType->type === AccountType::ASSET) { - // destination is asset, might have currency preference: - $destinationCurrencyId = (int)$this->accountRepository->getMetaValue($destination, 'currency_id'); - $currency = 0 === $destinationCurrencyId ? $this->defaultCurrency : $this->currencyMapper->map($destinationCurrencyId, []); - Log::debug(sprintf('Destination is an asset account, and has currency preference %s', $currency->code)); - } - - if ($source->accountType->type === AccountType::ASSET) { - // source is asset, might have currency preference: - $sourceCurrencyId = (int)$this->accountRepository->getMetaValue($source, 'currency_id'); - $currency = 0 === $sourceCurrencyId ? $this->defaultCurrency : $this->currencyMapper->map($sourceCurrencyId, []); - Log::debug(sprintf('Source is an asset account, and has currency preference %s', $currency->code)); - } - if (null === $currency) { - Log::debug(sprintf('Could not map currency, use default (%s)', $this->defaultCurrency->code)); - $currency = $this->defaultCurrency; - } - - return $currency; - } - - /** - * @param string $source - * @param string $destination - * - * @return string - */ - private function getTransactionType(string $source, string $destination): string - { - $type = 'unknown'; - - $newType = config(sprintf('firefly.account_to_transaction.%s.%s', $source, $destination)); - if (null !== $newType) { - Log::debug(sprintf('Source is %s, destination is %s, so this is a %s.', $source, $destination, $newType)); - - return (string)$newType; - } - - return $type; - } -} diff --git a/app/Support/Import/Routine/File/ImportableCreator.php b/app/Support/Import/Routine/File/ImportableCreator.php deleted file mode 100644 index e86230a6c4..0000000000 --- a/app/Support/Import/Routine/File/ImportableCreator.php +++ /dev/null @@ -1,73 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use FireflyIII\Support\Import\Placeholder\ColumnValue; -use FireflyIII\Support\Import\Placeholder\ImportTransaction; - -/** - * Takes an array of arrays of ColumnValue objects and returns one (1) ImportTransaction - * for each line. - * - * @deprecated - * @codeCoverageIgnore - * - * Class ImportableCreator - */ -class ImportableCreator -{ - /** - * @param array $sets - * - * @return array - * @throws \FireflyIII\Exceptions\FireflyException - */ - public function convertSets(array $sets): array - { - $return = []; - foreach ($sets as $set) { - $return[] = $this->convertSet($set); - } - - return $return; - } - - /** - * @param array $set - * - * @return ImportTransaction - * @throws \FireflyIII\Exceptions\FireflyException - */ - private function convertSet(array $set): ImportTransaction - { - $transaction = new ImportTransaction; - /** @var ColumnValue $entry */ - foreach ($set as $entry) { - $transaction->addColumnValue($entry); - } - - return $transaction; - } - -} diff --git a/app/Support/Import/Routine/File/LineReader.php b/app/Support/Import/Routine/File/LineReader.php deleted file mode 100644 index b859dfcacb..0000000000 --- a/app/Support/Import/Routine/File/LineReader.php +++ /dev/null @@ -1,189 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use Exception; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; -use FireflyIII\Import\Specifics\SpecificInterface; -use FireflyIII\Models\Attachment; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use League\Csv\Reader; -use League\Csv\Statement; -use Log; - -/** - * Class LineReader - * @deprecated - * @codeCoverageIgnore - */ -class LineReader -{ - /** @var AttachmentHelperInterface */ - private $attachments; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Grab all lines from the import job. - * - * @return array - * @throws FireflyException - */ - public function getLines(): array - { - try { - $reader = $this->getReader(); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - Log::error($e->getMessage()); - throw new FireflyException('Cannot get reader: ' . $e->getMessage()); - } - // @codeCoverageIgnoreEnd - // get all lines from file: - $lines = $this->getAllLines($reader); - - // apply specifics and return. - return $this->applySpecifics($lines); - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); - $this->repository->setUser($importJob->user); - } - - /** - * @param array $lines - * - * @return array - */ - private function applySpecifics(array $lines): array - { - $config = $this->importJob->configuration; - $validSpecifics = array_keys(config('csv.import_specifics')); - $specifics = $config['specifics'] ?? []; - $names = array_keys($specifics); - $toApply = []; - foreach ($names as $name) { - if (!in_array($name, $validSpecifics, true)) { - continue; - } - $class = config(sprintf('csv.import_specifics.%s', $name)); - $toApply[] = app($class); - } - $return = []; - /** @var array $line */ - foreach ($lines as $line) { - /** @var SpecificInterface $specific */ - foreach ($toApply as $specific) { - $line = $specific->run($line); - } - $return[] = $line; - } - - return $return; - } - - /** - * @param Reader $reader - * - * @return array - * @throws FireflyException - */ - private function getAllLines(Reader $reader): array - { - /** @var array $config */ - $config = $this->importJob->configuration; - Log::debug('now in getLines()'); - $offset = isset($config['has-headers']) && true === $config['has-headers'] ? 1 : 0; - try { - $stmt = (new Statement)->offset($offset); - // @codeCoverageIgnoreStart - } catch (Exception $e) { - throw new FireflyException(sprintf('Could not execute statement: %s', $e->getMessage())); - } - // @codeCoverageIgnoreEnd - $results = $stmt->process($reader); - $lines = []; - foreach ($results as $line) { - - $lineValues = array_values($line); - - // do a first sanity check on whatever comes out of the CSV file. - array_walk( - $lineValues, static function ($element) { - $element = str_replace(' ', ' ', (string)$element); - - return $element; - } - ); - - $lines[] = $lineValues; - } - - - return $lines; - } - - /** - * @return Reader - * @throws FireflyException - */ - private function getReader(): Reader - { - Log::debug('Now in getReader()'); - $content = ''; - $collection = $this->repository->getAttachments($this->importJob); - /** @var Attachment $attachment */ - foreach ($collection as $attachment) { - if ('import_file' === $attachment->filename) { - $content = $this->attachments->getAttachmentContent($attachment); - break; - } - } - $config = $this->repository->getConfiguration($this->importJob); - $reader = Reader::createFromString($content); - try { - $reader->setDelimiter($config['delimiter'] ?? ','); - // @codeCoverageIgnoreStart - } catch (\League\Csv\Exception $e) { - throw new FireflyException(sprintf('Cannot set delimiter: %s', $e->getMessage())); - } - - // @codeCoverageIgnoreEnd - - return $reader; - } - - -} diff --git a/app/Support/Import/Routine/File/MappedValuesValidator.php b/app/Support/Import/Routine/File/MappedValuesValidator.php deleted file mode 100644 index a3a23dc12d..0000000000 --- a/app/Support/Import/Routine/File/MappedValuesValidator.php +++ /dev/null @@ -1,134 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\Bill\BillRepositoryInterface; -use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; -use FireflyIII\Repositories\Category\CategoryRepositoryInterface; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Log; - -/** - * Class MappedValuesValidator - * @deprecated - * @codeCoverageIgnore - */ -class MappedValuesValidator -{ - /** @var AccountRepositoryInterface */ - private $accountRepos; - /** @var BillRepositoryInterface */ - private $billRepos; - /** @var BudgetRepositoryInterface */ - private $budgetRepos; - /** @var CategoryRepositoryInterface */ - private $catRepos; - /** @var CurrencyRepositoryInterface */ - private $currencyRepos; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - - $this->repository = app(ImportJobRepositoryInterface::class); - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->currencyRepos = app(CurrencyRepositoryInterface::class); - $this->billRepos = app(BillRepositoryInterface::class); - $this->budgetRepos = app(BudgetRepositoryInterface::class); - $this->catRepos = app(CategoryRepositoryInterface::class); - - $this->repository->setUser($importJob->user); - $this->accountRepos->setUser($importJob->user); - $this->currencyRepos->setUser($importJob->user); - $this->billRepos->setUser($importJob->user); - $this->budgetRepos->setUser($importJob->user); - $this->catRepos->setUser($importJob->user); - } - - - /** - * @param array $mappings - * - * @return array - * @throws FireflyException - * - */ - public function validate(array $mappings): array - { - $return = []; - Log::debug('Now in validateMappedValues()'); - foreach ($mappings as $role => $values) { - Log::debug(sprintf('Now at role "%s"', $role)); - $values = array_unique($values); - if (count($values) > 0) { - switch ($role) { - default: - throw new FireflyException(sprintf('Cannot validate mapped values for role "%s"', $role)); // @codeCoverageIgnore - case 'opposing-id': - case 'account-id': - $set = $this->accountRepos->getAccountsById($values); - $valid = $set->pluck('id')->toArray(); - $return[$role] = $valid; - break; - case 'currency-id': - case 'foreign-currency-id': - $set = $this->currencyRepos->getByIds($values); - $valid = $set->pluck('id')->toArray(); - $return[$role] = $valid; - break; - case 'bill-id': - $set = $this->billRepos->getByIds($values); - $valid = $set->pluck('id')->toArray(); - $return[$role] = $valid; - break; - case 'budget-id': - $set = $this->budgetRepos->getByIds($values); - $valid = $set->pluck('id')->toArray(); - $return[$role] = $valid; - break; - case 'category-id': - Log::debug('Going to validate these category ids: ', $values); - $set = $this->catRepos->getByIds($values); - $valid = $set->pluck('id')->toArray(); - $return[$role] = $valid; - Log::debug('Valid category IDs are: ', $valid); - break; - } - } - } - - return $return; - } -} diff --git a/app/Support/Import/Routine/File/MappingConverger.php b/app/Support/Import/Routine/File/MappingConverger.php deleted file mode 100644 index 3a127ed8e2..0000000000 --- a/app/Support/Import/Routine/File/MappingConverger.php +++ /dev/null @@ -1,216 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\Import\Placeholder\ColumnValue; -use Log; - -/** - * Class MappingConverger - * @deprecated - * @codeCoverageIgnore - */ -class MappingConverger -{ - /** @var array */ - private $doMapping; - /** @var ImportJob */ - private $importJob; - /** @var array */ - private $mappedValues; - /** @var array */ - private $mapping; - /** @var ImportJobRepositoryInterface */ - private $repository; - /** @var array */ - private $roles; - - /** - * Each cell in the CSV file could be linked to a mapped value. This depends on the role of - * the column and the content of the cell. This method goes over all cells, and using their - * associated role, will see if it has been linked to a mapped value. These mapped values - * are all IDs of objects in the Firefly III database. - * - * If such a mapping exists the role of the cell changes to whatever the mapped value is. - * - * Examples: - * - * - Cell with content "Checking Account" and role "account-name". Mapping links "Checking Account" to account-id 2. - * - Cell with content "Checking Account" and role "description". No mapping, so value and role remains the same. - * - * @param array $lines - * - * @return array - * @throws FireflyException - */ - public function converge(array $lines): array - { - Log::debug('Start converging process.'); - $collection = []; - $total = count($lines); - /** @var array $line */ - foreach ($lines as $lineIndex => $line) { - Log::debug(sprintf('Now converging line %d out of %d.', $lineIndex + 1, $total)); - $set = $this->processLine($line); - $collection[] = $set; - } - - return $collection; - - } - - /** - * @codeCoverageIgnore - * @return array - */ - public function getMappedValues(): array - { - return $this->mappedValues; - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - $this->mappedValues = []; - $config = $importJob->configuration; - $this->roles = $config['column-roles'] ?? []; - $this->mapping = $config['column-mapping-config'] ?? []; - $this->doMapping = $config['column-do-mapping'] ?? []; - } - - /** - * If the value in the column is mapped to a certain ID, - * the column where this ID must be placed will change. - * - * For example, if you map role "budget-name" with value "groceries" to 1, - * then that should become the budget-id. Not the name. - * - * @param int $column - * @param int $mapped - * - * @return string - * @throws FireflyException - */ - private function getRoleForColumn(int $column, int $mapped): string - { - $role = $this->roles[$column] ?? '_ignore'; - if (0 === $mapped) { - Log::debug(sprintf('Column #%d with role "%s" is not mapped.', $column, $role)); - - return $role; - } - if (!(isset($this->doMapping[$column]) && true === $this->doMapping[$column])) { - - // if the mapping has been filled in already by a role with a higher priority, - // ignore the mapping. - Log::debug(sprintf('Column #%d ("%s") has something.', $column, $role)); - - - return $role; - } - $roleMapping = [ - 'account-id' => 'account-id', - 'account-name' => 'account-id', - 'account-iban' => 'account-id', - 'account-number' => 'account-id', - 'bill-id' => 'bill-id', - 'bill-name' => 'bill-id', - 'budget-id' => 'budget-id', - 'budget-name' => 'budget-id', - 'currency-id' => 'currency-id', - 'currency-name' => 'currency-id', - 'currency-code' => 'currency-id', - 'currency-symbol' => 'currency-id', - 'category-id' => 'category-id', - 'category-name' => 'category-id', - 'foreign-currency-id' => 'foreign-currency-id', - 'foreign-currency-code' => 'foreign-currency-id', - 'opposing-id' => 'opposing-id', - 'opposing-name' => 'opposing-id', - 'opposing-iban' => 'opposing-id', - 'opposing-number' => 'opposing-id', - ]; - if (!isset($roleMapping[$role])) { - throw new FireflyException(sprintf('Cannot indicate new role for mapped role "%s"', $role)); // @codeCoverageIgnore - } - $newRole = $roleMapping[$role]; - Log::debug(sprintf('Role was "%s", but because of mapping (mapped to #%d), role becomes "%s"', $role, $mapped, $newRole)); - - // also store the $mapped values in a "mappedValues" array. - $this->mappedValues[$newRole][] = $mapped; - Log::debug(sprintf('Values mapped to role "%s" are: ', $newRole), $this->mappedValues[$newRole]); - - return $newRole; - } - - /** - * @param array $line - * - * @return array - * @throws FireflyException - */ - private function processLine(array $line): array - { - $return = []; - foreach ($line as $columnIndex => $value) { - $value = trim($value); - $originalRole = $this->roles[$columnIndex] ?? '_ignore'; - Log::debug(sprintf('Now at column #%d (%s), value "%s"', $columnIndex, $originalRole, $value)); - if ('_ignore' !== $originalRole && '' != $value) { - - // is a mapped value present? - $mapped = $this->mapping[$columnIndex][$value] ?? 0; - // the role might change. - $role = $this->getRoleForColumn($columnIndex, $mapped); - - $columnValue = new ColumnValue; - $columnValue->setValue($value); - $columnValue->setRole($role); - $columnValue->setMappedValue($mapped); - $columnValue->setOriginalRole($originalRole); - $return[] = $columnValue; - } - if ('' === $value) { - Log::debug('Column skipped because value is empty.'); - } - } - // add a special column value for the "source" - $columnValue = new ColumnValue; - $columnValue->setValue(sprintf('csv-import-v%s', config('firefly.version'))); - $columnValue->setMappedValue(0); - $columnValue->setRole('original-source'); - $return[] = $columnValue; - - return $return; - } - -} diff --git a/app/Support/Import/Routine/File/OFXProcessor.php b/app/Support/Import/Routine/File/OFXProcessor.php deleted file mode 100644 index 0cb893f26a..0000000000 --- a/app/Support/Import/Routine/File/OFXProcessor.php +++ /dev/null @@ -1,121 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - - -use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; -use FireflyIII\Models\Attachment; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use Log; -use OfxParser\Entities\BankAccount; -use OfxParser\Entities\Transaction; - -/** - * - * Class OFXProcessor - * @deprecated - * @codeCoverageIgnore - */ -class OFXProcessor implements FileProcessorInterface -{ - /** @var AttachmentHelperInterface */ - private $attachments; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Fires the file processor. - * - * @return array - */ - public function run(): array - { - $collection = $this->repository->getAttachments($this->importJob); - $content = ''; - /** @var Attachment $attachment */ - foreach ($collection as $attachment) { - if ('import_file' === $attachment->filename) { - $content = $this->attachments->getAttachmentContent($attachment); - break; - } - } - $config = $this->repository->getConfiguration($this->importJob); - try { - Log::debug('Now in OFXProcessor() run'); - $ofxParser = new \OfxParser\Parser(); - $ofx = $ofxParser->loadFromString($content); - } catch (\Exception $e) { - echo $e->getMessage(); - exit; - } - reset($ofx->bankAccounts); - /** @var BankAccount $bankAccount */ - foreach ($ofx->bankAccounts as $bankAccount) { - /** @var Transaction $transaction */ - foreach ($bankAccount->statement->transactions as $transaction) { - //var_dump($transaction); - } - } - - // - // // Get the statement start and end dates - // $startDate = $bankAccount->statement->startDate; - // $endDate = $bankAccount->statement->endDate; - // var_dump($startDate); - // var_dump($endDate); - // - // // Get the statement transactions for the account - // $transactions = $bankAccount->statement->transactions; - // foreach($transactions as $transaction) { - // var_dump($transaction); - // } - // - // die('I am here.'); - - - exit; - - - return []; - } - - /** - * Set values. - * - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - Log::debug('Now in setImportJob()'); - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); - - $this->repository->setUser($importJob->user); - - } -} diff --git a/app/Support/Import/Routine/File/OpposingAccountMapper.php b/app/Support/Import/Routine/File/OpposingAccountMapper.php deleted file mode 100644 index 342a121e9e..0000000000 --- a/app/Support/Import/Routine/File/OpposingAccountMapper.php +++ /dev/null @@ -1,144 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\File; - -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\User; -use Log; - -/** - * Class OpposingAccountMapper - * @deprecated - * @codeCoverageIgnore - */ -class OpposingAccountMapper -{ - /** @var AccountRepositoryInterface */ - private $repository; - /** @var User */ - private $user; - - /** - * @param int|null $accountId - * @param string $amount - * @param array $data - * - * @return Account - * - */ - public function map(?int $accountId, string $amount, array $data): Account - { - Log::debug(sprintf('Now in OpposingAccountMapper::map(%d, "%s")', $accountId, $amount), $data); - // default assumption is we're looking for an expense account. - $expectedType = AccountType::EXPENSE; - $result = null; - Log::debug(sprintf('Going to search for accounts of type %s', $expectedType)); - if (1 === bccomp($amount, '0')) { - // more than zero. - $expectedType = AccountType::REVENUE; - Log::debug(sprintf('Because amount is %s, will instead search for accounts of type %s', $amount, $expectedType)); - } - - // append expected types with liability types: - $expectedTypes = [$expectedType, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]; - - - if ((int)$accountId > 0) { - // find any account with this ID: - $result = $this->repository->findNull($accountId); - if (null !== $result && (in_array($result->accountType->type, $expectedTypes, true) || $result->accountType->type === AccountType::ASSET)) { - Log::debug(sprintf('Found account "%s" (%s) based on given ID %d. Return it!', $result->name, $result->accountType->type, $accountId)); - - return $result; - } - if (null !== $result && !in_array($result->accountType->type, $expectedTypes, true)) { - Log::warning( - sprintf( - 'Found account "%s" (%s) based on given ID %d, but need a %s. Return nothing.', $result->name, $result->accountType->type, $accountId, - $expectedType - ) - ); - } - } - // if result is not null, system has found an account - // but it's of the wrong type. If we dont have a name, use - // the result's name, iban in the search below. - if (null !== $result && '' === (string)($data['name'] ?? '')) { - Log::debug(sprintf('Will search for account with name "%s" instead of NULL.', $result->name)); - $data['name'] = $result->name; - } - if (null !== $result && '' !== (string)$result->iban && '' === ($data['iban'] ?? '')) { - Log::debug(sprintf('Will search for account with IBAN "%s" instead of NULL.', $result->iban)); - $data['iban'] = $result->iban; - } - - // first search for $expectedType, then find asset: - $searchTypes = [$expectedType, AccountType::ASSET, AccountType::DEBT, AccountType::MORTGAGE, AccountType::LOAN]; - foreach ($searchTypes as $type) { - // find by (respectively): - // IBAN, accountNumber, name, - $fields = ['iban' => 'findByIbanNull', 'number' => 'findByAccountNumber', 'name' => 'findByName']; - foreach ($fields as $field => $function) { - $value = (string)($data[$field] ?? ''); - if ('' === $value) { - Log::debug(sprintf('Array does not contain a value for %s. Continue', $field)); - continue; - } - Log::debug(sprintf('Will search for account of type "%s" using %s() and argument "%s".', $type, $function, $value)); - $result = $this->repository->$function($value, [$type]); - if (null !== $result) { - Log::debug(sprintf('Found result: Account #%d, named "%s"', $result->id, $result->name)); - - return $result; - } - } - } - // not found? Create it! - $creation = [ - 'name' => $data['name'] ?? '(no name)', - 'iban' => $data['iban'] ?? null, - 'account_number' => $data['number'] ?? null, - 'account_type_id' => null, - 'account_type' => $expectedType, - 'active' => true, - 'BIC' => $data['bic'] ?? null, - ]; - Log::debug('Will try to store a new account: ', $creation); - - return $this->repository->store($creation); - } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUser($user); - - } -} diff --git a/app/Support/Import/Routine/FinTS/StageImportDataHandler.php b/app/Support/Import/Routine/FinTS/StageImportDataHandler.php deleted file mode 100644 index e2a0bf416d..0000000000 --- a/app/Support/Import/Routine/FinTS/StageImportDataHandler.php +++ /dev/null @@ -1,193 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\FinTS; - - -use Fhp\Model\StatementOfAccount\Transaction; -use Fhp\Model\StatementOfAccount\Transaction as FinTSTransaction; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account as LocalAccount; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\TransactionType; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Support\FinTS\FinTS; -use FireflyIII\Support\FinTS\MetadataParser; -use FireflyIII\Support\Import\Routine\File\OpposingAccountMapper; -use Illuminate\Support\Facades\Log; - -/** - * - * Class StageImportDataHandler - * @deprecated - * @codeCoverageIgnore - */ -class StageImportDataHandler -{ - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var ImportJob */ - private $importJob; - /** @var OpposingAccountMapper */ - private $mapper; - /** @var ImportJobRepositoryInterface */ - private $repository; - /** @var array */ - private $transactions; - - /** - * @return array - */ - public function getTransactions(): array - { - return $this->transactions; - } - - /** - * @throws FireflyException - */ - public function run(): void - { - Log::debug('Now in StageImportDataHandler::run()'); - - $localAccount = $this->accountRepository->findNull((int)$this->importJob->configuration['local_account']); - if (null === $localAccount) { - throw new FireflyException(sprintf('Cannot find Firefly account with id #%d ', $this->importJob->configuration['local_account'])); - } - $finTS = app(FinTS::class, ['config' => $this->importJob->configuration]); - $fintTSAccount = $finTS->getAccount($this->importJob->configuration['fints_account']); - $statementOfAccount = $finTS->getStatementOfAccount( - $fintTSAccount, new \DateTime($this->importJob->configuration['from_date']), new \DateTime($this->importJob->configuration['to_date']) - ); - $collection = []; - foreach ($statementOfAccount->getStatements() as $statement) { - foreach ($statement->getTransactions() as $transaction) { - $collection[] = $this->convertTransaction($transaction, $localAccount); - } - } - - $this->transactions = $collection; - } - - /** - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void - { - $this->transactions = []; - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->mapper = app(OpposingAccountMapper::class); - $this->mapper->setUser($importJob->user); - $this->repository->setUser($importJob->user); - $this->accountRepository->setUser($importJob->user); - } - - /** - * @param FinTSTransaction $transaction - * @param LocalAccount $source - * - * @return array - */ - private function convertTransaction(FinTSTransaction $transaction, LocalAccount $source): array - { - Log::debug(sprintf('Start converting transaction %s', $transaction->getDescription1())); - - $amount = (string)$transaction->getAmount(); - $debitOrCredit = $transaction->getCreditDebit(); - // assume deposit. - $type = TransactionType::DEPOSIT; - Log::debug(sprintf('Amount is %s', $amount)); - - // inverse if not. - if ($debitOrCredit !== Transaction::CD_CREDIT) { - $type = TransactionType::WITHDRAWAL; - $amount = bcmul($amount, '-1'); - } - - $destination = $this->mapper->map( - null, - $amount, - ['iban' => $transaction->getAccountNumber(), 'name' => $transaction->getName()] - ); - if ($debitOrCredit === Transaction::CD_CREDIT) { - [$source, $destination] = [$destination, $source]; - } - - if ($source->accountType->type === AccountType::ASSET && $destination->accountType->type === AccountType::ASSET) { - $type = TransactionType::TRANSFER; - Log::debug('Both are assets, will make transfer.'); - } - - $metadataParser = new MetadataParser(); - $description = $metadataParser->getDescription($transaction); - - $storeData = [ - 'user' => $this->importJob->user_id, - 'type' => $type, - 'date' => $transaction->getValutaDate()->format('Y-m-d'), - 'description' => null, - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - 'bill_id' => null, - 'bill_name' => null, - 'tags' => [], - 'internal_reference' => null, - 'external_id' => null, - 'notes' => null, - 'bunq_payment_id' => null, - 'original-source' => sprintf('fints-v%s', config('firefly.version')), - 'transactions' => [ - // single transaction: - [ - 'type' => $type, - 'description' => $description, - 'date' => $transaction->getValutaDate()->format('Y-m-d'), - 'amount' => $amount, - 'currency_id' => null, - 'currency_code' => 'EUR', - 'foreign_amount' => null, - 'foreign_currency_id' => null, - 'foreign_currency_code' => null, - 'budget_id' => null, - 'budget_name' => null, - 'category_id' => null, - 'category_name' => null, - 'source_id' => $source->id, - 'source_name' => null, - 'destination_id' => $destination->id, - 'destination_name' => null, - 'reconciled' => false, - 'identifier' => 0, - ], - ], - ]; - - return $storeData; - } -} diff --git a/app/Support/Import/Routine/Spectre/StageAuthenticatedHandler.php b/app/Support/Import/Routine/Spectre/StageAuthenticatedHandler.php deleted file mode 100644 index d3dd29973d..0000000000 --- a/app/Support/Import/Routine/Spectre/StageAuthenticatedHandler.php +++ /dev/null @@ -1,153 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Spectre; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Spectre\Object\Account; -use FireflyIII\Services\Spectre\Object\Login; -use FireflyIII\Services\Spectre\Request\ListAccountsRequest; -use FireflyIII\Services\Spectre\Request\ListLoginsRequest; -use FireflyIII\Support\Import\Information\GetSpectreCustomerTrait; -use Log; - -/** - * Class StageAuthenticatedHandler - * @deprecated - * @codeCoverageIgnore - */ -class StageAuthenticatedHandler -{ - use GetSpectreCustomerTrait; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * User has selected a login (a bank). Will grab all accounts from this bank. - * Then make user pick some to import from. - * - * @throws FireflyException - */ - public function run(): void - { - Log::debug('Now in StageAuthenticatedHandler::run()'); - // grab a list of logins. - $config = $this->importJob->configuration; - $logins = $config['all-logins'] ?? []; - Log::debug(sprintf('%d logins in config', count($logins))); - if (0 === count($logins)) { - // get logins from Spectre. - $logins = $this->getLogins(); - $config['all-logins'] = $logins; - } - - $selectedLogin = $config['selected-login'] ?? 0; - $login = null; - Log::debug(sprintf('$selectedLogin is %d', $selectedLogin)); - foreach ($logins as $loginArray) { - $loginId = $loginArray['id'] ?? -1; - if ($loginId === $selectedLogin) { - $login = new Login($loginArray); - Log::debug(sprintf('Selected login "%s" ("%s") which is in the array with logins.', $login->getProviderName(), $login->getCountryCode())); - } - } - if (null === $login) { - $login = new Login($logins[0]); - Log::debug(sprintf('Login is null, simply use the first one "%s" ("%s") from the array.', $login->getProviderName(), $login->getCountryCode())); - } - - // with existing login we can grab accounts from this login. - $accounts = $this->getAccounts($login); - $config['accounts'] = []; - /** @var Account $account */ - foreach ($accounts as $account) { - Log::debug(sprintf('Found account #%d ("%s") within Login.', $account->getId(), $account->getName())); - $config['accounts'][] = $account->toArray(); - } - $this->repository->setConfiguration($this->importJob, $config); - - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } - - /** - * @param Login $login - * - * @return array - * @throws FireflyException - */ - private function getAccounts(Login $login): array - { - Log::debug(sprintf('Now in StageAuthenticatedHandler::getAccounts() for login #%d', $login->getId())); - /** @var ListAccountsRequest $request */ - $request = app(ListAccountsRequest::class); - $request->setUser($this->importJob->user); - $request->setLogin($login); - $request->call(); - $accounts = $request->getAccounts(); - Log::debug(sprintf('Found %d accounts using login', count($accounts))); - - return $accounts; - } - - /** - * @return array - * @throws FireflyException - */ - private function getLogins(): array - { - Log::debug('Now in StageAuthenticatedHandler::getLogins().'); - $customer = $this->getCustomer($this->importJob); - - /** @var ListLoginsRequest $request */ - $request = app(ListLoginsRequest::class); - $request->setUser($this->importJob->user); - $request->setCustomer($customer); - $request->call(); - $logins = $request->getLogins(); - $return = []; - - Log::debug(sprintf('Found %d logins in users Spectre account.', count($logins))); - - /** @var Login $login */ - foreach ($logins as $login) { - $return[] = $login->toArray(); - } - - return $return; - } - - -} diff --git a/app/Support/Import/Routine/Spectre/StageImportDataHandler.php b/app/Support/Import/Routine/Spectre/StageImportDataHandler.php deleted file mode 100644 index 64e9796e2f..0000000000 --- a/app/Support/Import/Routine/Spectre/StageImportDataHandler.php +++ /dev/null @@ -1,291 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Spectre; - - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account as LocalAccount; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Spectre\Object\Account as SpectreAccount; -use FireflyIII\Services\Spectre\Object\Transaction as SpectreTransaction; -use FireflyIII\Services\Spectre\Request\ListTransactionsRequest; -use FireflyIII\Support\Import\Routine\File\OpposingAccountMapper; -use Log; - -/** - * Class StageImportDataHandler - * @deprecated - * @codeCoverageIgnore - * - */ -class StageImportDataHandler -{ - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var ImportJob */ - private $importJob; - /** @var OpposingAccountMapper */ - private $mapper; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * @throws FireflyException - */ - public function run(): void - { - Log::debug('Now in StageImportDataHandler::run()'); - $config = $this->importJob->configuration; - $accounts = $config['accounts'] ?? []; - Log::debug(sprintf('Count of accounts in array is %d', count($accounts))); - if (0 === count($accounts)) { - throw new FireflyException('There are no accounts in this import job. Cannot continue.'); // @codeCoverageIgnore - } - $toImport = $config['account_mapping'] ?? []; - $totalSet = [[]]; - foreach ($toImport as $spectreId => $localId) { - if ((int)$localId > 0) { - Log::debug(sprintf('Will get transactions from Spectre account #%d and save them in Firefly III account #%d', $spectreId, $localId)); - $spectreAccount = $this->getSpectreAccount((int)$spectreId); - $localAccount = $this->getLocalAccount((int)$localId); - $merge = $this->getTransactions($spectreAccount, $localAccount); - $totalSet[] = $merge; - Log::debug( - sprintf('Found %d transactions in account "%s" (%s)', count($merge), $spectreAccount->getName(), $spectreAccount->getCurrencyCode()) - ); - continue; - } - Log::debug(sprintf('Local account is = zero, will not import from Spectr account with ID #%d', $spectreId)); - } - $totalSet = array_merge(...$totalSet); - Log::debug(sprintf('Found %d transactions in total.', count($totalSet))); - - $this->repository->setTransactions($this->importJob, $totalSet); - } - - - /** - * @param ImportJob $importJob - * - * @return void - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->mapper = app(OpposingAccountMapper::class); - $this->accountRepository->setUser($importJob->user); - $this->repository->setUser($importJob->user); - $this->mapper->setUser($importJob->user); - } - - /** - * @param array $transactions - * @param SpectreAccount $spectreAccount - * @param LocalAccount $originalSource - * - * @return array - * - */ - private function convertToArray(array $transactions, SpectreAccount $spectreAccount, LocalAccount $originalSource): array - { - $array = []; - $total = count($transactions); - Log::debug(sprintf('Now in StageImportDataHandler::convertToArray() with count %d', count($transactions))); - /** @var SpectreTransaction $transaction */ - foreach ($transactions as $index => $transaction) { - Log::debug(sprintf('Now creating array for transaction %d of %d', $index + 1, $total)); - $extra = []; - if (null !== $transaction->getExtra()) { - $extra = $transaction->getExtra()->toArray(); - } - $destinationData = $transaction->getOpposingAccountData(); - $amount = $transaction->getAmount(); - $source = $originalSource; - $destination = $this->mapper->map(null, $amount, $destinationData); - $notes = trans('import.imported_from_account', ['account' => $spectreAccount->getName()]) . ' ' . "\n"; - $foreignAmount = null; - $foreignCurrencyCode = null; - - $currencyCode = $transaction->getCurrencyCode(); - $type = 'withdrawal'; - // switch source and destination if amount is greater than zero. - if (1 === bccomp($amount, '0')) { - [$source, $destination] = [$destination, $source]; - $type = 'deposit'; - } - - Log::debug(sprintf('Mapped destination to #%d ("%s")', $destination->id, $destination->name)); - Log::debug(sprintf('Set source to #%d ("%s")', $source->id, $source->name)); - - // put some data in tags: - $tags = []; - $tags[] = $transaction->getMode(); - $tags[] = $transaction->getStatus(); - if ($transaction->isDuplicated()) { - $tags[] = 'possibly-duplicated'; - } - - // get extra fields: - foreach ($extra as $key => $value) { - if ('' === (string)$value) { - continue; - } - switch ($key) { - case 'original_category': - case 'original_subcategory': - case 'customer_category_code': - case 'customer_category_name': - $tags[] = $value; - break; - case 'original_amount': - $foreignAmount = $value; - Log::debug(sprintf('Foreign amount is now %s', $value)); - break; - case 'original_currency_code': - $foreignCurrencyCode = $value; - Log::debug(sprintf('Foreign currency code is now %s', $value)); - break; - case 'time': - // ignore time because it breaks the duplicate detector. - break; - default: - $notes .= $key . ': ' . $value . ' ' . "\n"; // for newline in Markdown. - } - } - - $entry = [ - // transaction data: - 'transactions' => [ - [ - 'date' => $transaction->getMadeOn()->format('Y-m-d'), - 'tags' => $tags, - 'user' => $this->importJob->user_id, - 'notes' => trim($notes), - - // all custom fields: - 'external_id' => (string)$transaction->getId(), - - // journal data: - 'description' => $transaction->getDescription(), - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - 'bill_id' => null, - 'bill_name' => null, - 'original-source' => sprintf('spectre-v%s', config('firefly.version')), - 'type' => $type, - 'currency_id' => null, - 'currency_code' => $currencyCode, - 'amount' => $amount, - 'budget_id' => null, - 'budget_name' => null, - 'category_id' => null, - 'category_name' => $transaction->getCategory(), - 'source_id' => $source->id, - 'source_name' => null, - 'destination_id' => $destination->id, - 'destination_name' => null, - 'foreign_currency_id' => null, - 'foreign_currency_code' => $foreignCurrencyCode, - 'foreign_amount' => $foreignAmount, - 'reconciled' => false, - 'identifier' => 0, - ], - ], - ]; - $array[] = $entry; - } - Log::debug(sprintf('Return %d entries', count($array))); - - return $array; - } - - /** - * @param int $accountId - * - * @return LocalAccount - * @throws FireflyException - */ - private function getLocalAccount(int $accountId): LocalAccount - { - $account = $this->accountRepository->findNull($accountId); - if (null === $account) { - throw new FireflyException(sprintf('Cannot find Firefly III asset account with ID #%d. Job must stop now.', $accountId)); // @codeCoverageIgnore - } - if (!in_array($account->accountType->type, [AccountType::ASSET, AccountType::LOAN, AccountType::MORTGAGE, AccountType::DEBT], true)) { - throw new FireflyException( - sprintf('Account with ID #%d is not an asset/loan/mortgage/debt account. Job must stop now.', $accountId) - ); // @codeCoverageIgnore - } - - return $account; - } - - /** - * @param int $accountId - * - * @return SpectreAccount - * @throws FireflyException - */ - private function getSpectreAccount(int $accountId): SpectreAccount - { - $config = $this->importJob->configuration; - $accounts = $config['accounts'] ?? []; - foreach ($accounts as $account) { - $spectreId = (int)($account['id'] ?? 0.0); - if ($spectreId === $accountId) { - return new SpectreAccount($account); - } - } - throw new FireflyException(sprintf('Cannot find Spectre account with ID #%d in configuration. Job will exit.', $accountId)); // @codeCoverageIgnore - } - - /** - * @param SpectreAccount $spectreAccount - * @param LocalAccount $localAccount - * - * @return array - * @throws FireflyException - */ - private function getTransactions(SpectreAccount $spectreAccount, LocalAccount $localAccount): array - { - // grab all transactions - /** @var ListTransactionsRequest $request */ - $request = app(ListTransactionsRequest::class); - $request->setUser($this->importJob->user); - - $request->setAccount($spectreAccount); - $request->call(); - - $transactions = $request->getTransactions(); - - return $this->convertToArray($transactions, $spectreAccount, $localAccount); - } - - -} diff --git a/app/Support/Import/Routine/Spectre/StageNewHandler.php b/app/Support/Import/Routine/Spectre/StageNewHandler.php deleted file mode 100644 index 74360cc154..0000000000 --- a/app/Support/Import/Routine/Spectre/StageNewHandler.php +++ /dev/null @@ -1,109 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Spectre; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Spectre\Object\Login; -use FireflyIII\Services\Spectre\Request\ListLoginsRequest; -use FireflyIII\Support\Import\Information\GetSpectreCustomerTrait; -use Log; - -/** - * Class StageNewHandler - * @deprecated - * @codeCoverageIgnore - * - */ -class StageNewHandler -{ - use GetSpectreCustomerTrait; - /** @var int */ - private $countLogins = 0; - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * @codeCoverageIgnore - * @return int - */ - public function getCountLogins(): int - { - return $this->countLogins; - } - - - /** - * Tasks for this stage: - * - * - List all of the users logins. - * - If zero, return to "get-token" stage and make user make a login. That stage redirects here. - * - If one or more, list and let user select. - * - * @throws FireflyException - */ - public function run(): void - { - Log::debug('Now in ManageLoginsHandler::run()'); - $customer = $this->getCustomer($this->importJob); - $config = $this->repository->getConfiguration($this->importJob); - - Log::debug('Going to get a list of logins.'); - /** @var ListLoginsRequest $request */ - $request = app(ListLoginsRequest::class); - $request->setUser($this->importJob->user); - $request->setCustomer($customer); - $request->call(); - - $list = $request->getLogins(); - - // count is zero? - $this->countLogins = count($list); - Log::debug(sprintf('Number of logins is %d', $this->countLogins)); - if ($this->countLogins > 0) { - $store = []; - /** @var Login $login */ - foreach ($list as $login) { - $store[] = $login->toArray(); - } - - $config['all-logins'] = $store; - $this->repository->setConfiguration($this->importJob, $config); - Log::debug('Stored all logins in configuration.'); - } - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Import/Routine/Ynab/GetAccountsHandler.php b/app/Support/Import/Routine/Ynab/GetAccountsHandler.php deleted file mode 100644 index b51aca4ed7..0000000000 --- a/app/Support/Import/Routine/Ynab/GetAccountsHandler.php +++ /dev/null @@ -1,82 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Ynab; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Ynab\Request\GetAccountsRequest; - -/** - * Class GetAccountsHandler - * @deprecated - * @codeCoverageIgnore - */ -class GetAccountsHandler -{ - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Get list of accounts for the selected budget. - * - * @throws FireflyException - */ - public function run(): void - { - - $config = $this->repository->getConfiguration($this->importJob); - $selectedBudget = $config['selected_budget'] ?? ''; - if ('' === $selectedBudget) { - $firstBudget = $config['budgets'][0] ?? false; - if (false === $firstBudget) { - throw new FireflyException('The configuration contains no budget. Erroring out.'); - } - $selectedBudget = $firstBudget['id']; - $config['selected_budget'] = $selectedBudget; - } - $token = $config['access_token']; - $request = new GetAccountsRequest; - $request->budgetId = $selectedBudget; - $request->setAccessToken($token); - $request->call(); - $config['accounts'] = $request->accounts; - $this->repository->setConfiguration($this->importJob, $config); - if (0 === count($config['accounts'])) { - throw new FireflyException('This budget contains zero accounts.'); - } - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Import/Routine/Ynab/ImportDataHandler.php b/app/Support/Import/Routine/Ynab/ImportDataHandler.php deleted file mode 100644 index 1e8d69b534..0000000000 --- a/app/Support/Import/Routine/Ynab/ImportDataHandler.php +++ /dev/null @@ -1,290 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Ynab; - - -use Carbon\Carbon; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\ImportJob; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Ynab\Request\GetTransactionsRequest; -use FireflyIII\Support\Import\Routine\File\OpposingAccountMapper; -use Log; - -/** - * Class ImportDataHandler - * @deprecated - * @codeCoverageIgnore - */ -class ImportDataHandler -{ - /** @var AccountRepositoryInterface */ - private $accountRepository; - /** @var TransactionCurrency */ - private $defaultCurrency; - /** @var ImportJob */ - private $importJob; - /** @var OpposingAccountMapper */ - private $mapper; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Get list of accounts for the selected budget. - * - * @throws FireflyException - */ - public function run(): void - { - $config = $this->repository->getConfiguration($this->importJob); - $this->defaultCurrency = app('amount')->getDefaultCurrencyByUser($this->importJob->user); - $token = $config['access_token']; - // make request for each mapping: - $mapping = $config['mapping'] ?? []; - $total = [[]]; - - /** - * @var string $ynabId - * @var string $localId - */ - foreach ($mapping as $ynabId => $localId) { - $localAccount = $this->getLocalAccount((int)$localId); - $transactions = $this->getTransactions($token, $ynabId); - $converted = $this->convertToArray($transactions, $localAccount); - $total[] = $converted; - } - - $totalSet = array_merge(...$total); - Log::debug(sprintf('Found %d transactions in total.', count($totalSet))); - $this->repository->setTransactions($this->importJob, $totalSet); - - // assuming this works, store today's date as a preference - // (combined with the budget from which FF3 imported) - $budgetId = $this->getSelectedBudget()['id'] ?? ''; - if ('' !== $budgetId) { - app('preferences')->set('ynab_' . $budgetId, Carbon::now()->format('Y-m-d')); - } - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->mapper = app(OpposingAccountMapper::class); - $this->accountRepository->setUser($importJob->user); - $this->repository->setUser($importJob->user); - $this->mapper->setUser($importJob->user); - } - - /** - * @param array $transactions - * @param Account $localAccount - * - * @return array - * @throws FireflyException - */ - private function convertToArray(array $transactions, Account $localAccount): array - { - $config = $this->repository->getConfiguration($this->importJob); - $array = []; - $total = count($transactions); - $budget = $this->getSelectedBudget(); - Log::debug(sprintf('Now in StageImportDataHandler::convertToArray() with count %d', count($transactions))); - /** @var array $transaction */ - foreach ($transactions as $index => $transaction) { - $description = $transaction['memo'] ?? '(empty)'; - Log::debug(sprintf('Now creating array for transaction %d of %d ("%s")', $index + 1, $total, $description)); - $amount = (string)($transaction['amount'] ?? 0); - if ('0' === $amount) { - Log::debug(sprintf('Amount is zero (%s), skip this transaction.', $amount)); - continue; - } - Log::debug(sprintf('Amount detected is %s', $amount)); - $source = $localAccount; - $type = 'withdrawal'; - $tags = [ - $transaction['cleared'] ?? '', - $transaction['approved'] ? 'approved' : 'not-approved', - $transaction['flag_color'] ?? '', - ]; - $possibleDestinationId = null; - if (null !== $transaction['transfer_account_id']) { - // indication that it is a transfer. - $possibleDestinationId = $config['mapping'][$transaction['transfer_account_id']] ?? null; - Log::debug(sprintf('transfer_account_id has value %s', $transaction['transfer_account_id'])); - Log::debug(sprintf('Can map this to the following FF3 asset account: %d', $possibleDestinationId)); - $type = 'transfer'; - - } - - $destinationData = [ - 'name' => str_replace('Transfer: ', '', $transaction['payee_name']), - 'iban' => null, - 'number' => $transaction['payee_id'], - 'bic' => null, - ]; - - $destination = $this->mapper->map($possibleDestinationId, $amount, $destinationData); - if (1 === bccomp($amount, '0')) { - [$source, $destination] = [$destination, $source]; - $type = 'transfer' === $type ? 'transfer' : 'deposit'; - Log::debug(sprintf('Amount is %s, so switch source/dest and make this a %s', $amount, $type)); - } - - Log::debug(sprintf('Final source account: #%d ("%s")', $source->id, $source->name)); - Log::debug(sprintf('Final destination account: #%d ("%s")', $destination->id, $destination->name)); - - $entry = [ - 'type' => $type, - 'date' => $transaction['date'] ?? date('Y-m-d'), - 'tags' => $tags, - 'user' => $this->importJob->user_id, - 'notes' => null, - - // all custom fields: - 'external_id' => $transaction['id'] ?? '', - - // journal data: - 'description' => $description, - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - 'bill_id' => null, - 'bill_name' => null, - 'original-source' => sprintf('ynab-v%s', config('firefly.version')), - - // transaction data: - 'transactions' => [ - [ - 'type' => $type, - 'date' => $transaction['date'] ?? date('Y-m-d'), - 'tags' => $tags, - 'user' => $this->importJob->user_id, - 'notes' => null, - 'currency_id' => null, - 'currency_code' => $budget['currency_code'] ?? $this->defaultCurrency->code, - 'amount' => bcdiv((string)$transaction['amount'], '1000'), - 'budget_id' => null, - 'original-source' => sprintf('ynab-v%s', config('firefly.version')), - 'budget_name' => null, - 'category_id' => null, - 'category_name' => $transaction['category_name'], - 'source_id' => $source->id, - 'source_name' => null, - // all custom fields: - 'external_id' => $transaction['id'] ?? '', - - // journal data: - 'description' => $description, - 'destination_id' => $destination->id, - 'destination_name' => null, - 'foreign_currency_id' => null, - 'foreign_currency_code' => null, - 'foreign_amount' => null, - 'reconciled' => false, - 'identifier' => 0, - ], - ], - ]; - Log::debug(sprintf('Done with entry #%d', $index)); - $array[] = $entry; - } - - return $array; - } - - /** - * @param int $accountId - * - * @return Account - * @throws FireflyException - */ - private function getLocalAccount(int $accountId): Account - { - $account = $this->accountRepository->findNull($accountId); - if (null === $account) { - throw new FireflyException(sprintf('Cannot find Firefly III asset account with ID #%d. Job must stop now.', $accountId)); // @codeCoverageIgnore - } - if ($account->accountType->type !== AccountType::ASSET) { - throw new FireflyException(sprintf('Account with ID #%d is not an asset account. Job must stop now.', $accountId)); // @codeCoverageIgnore - } - - return $account; - } - - /** - * @return array - * @throws FireflyException - */ - private function getSelectedBudget(): array - { - $config = $this->repository->getConfiguration($this->importJob); - $budgets = $config['budgets'] ?? []; - $selected = $config['selected_budget'] ?? ''; - - if ('' === $selected) { - $firstBudget = $config['budgets'][0] ?? false; - if (false === $firstBudget) { - throw new FireflyException('The configuration contains no budget. Erroring out.'); - } - $selected = $firstBudget['id']; - } - - foreach ($budgets as $budget) { - if ($budget['id'] === $selected) { - return $budget; - } - } - - return $budgets[0] ?? []; - } - - /** - * @param string $token - * @param string $account - * - * @return array - * @throws FireflyException - */ - private function getTransactions(string $token, string $account): array - { - $budget = $this->getSelectedBudget(); - $request = new GetTransactionsRequest; - $request->budgetId = $budget['id']; - $request->accountId = $account; - - // todo grab latest date for $ynabId - $request->setAccessToken($token); - $request->call(); - - return $request->transactions; - } -} diff --git a/app/Support/Import/Routine/Ynab/StageGetAccessHandler.php b/app/Support/Import/Routine/Ynab/StageGetAccessHandler.php deleted file mode 100644 index c775a00487..0000000000 --- a/app/Support/Import/Routine/Ynab/StageGetAccessHandler.php +++ /dev/null @@ -1,110 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Ynab; - -use Exception; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use GuzzleHttp\Client; -use GuzzleHttp\Exception\GuzzleException; -use Log; -use RuntimeException; - -/** - * Class StageGetAccessHandler - * @deprecated - * @codeCoverageIgnore - */ -class StageGetAccessHandler -{ - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * Send a token request to YNAB. Return with access token (if all goes well). - * - * @throws \Psr\Container\NotFoundExceptionInterface - * @throws \Psr\Container\ContainerExceptionInterface - * @throws FireflyException - */ - public function run(): void - { - $config = $this->repository->getConfiguration($this->importJob); - $clientId = app('preferences')->get('ynab_client_id', '')->data; - $clientSecret = app('preferences')->get('ynab_client_secret', '')->data; - $redirectUri = route('import.callback.ynab'); - $code = $config['auth_code']; - $uri = sprintf( - 'https://app.youneedabudget.com/oauth/token?client_id=%s&client_secret=%s&redirect_uri=%s&grant_type=authorization_code&code=%s', $clientId, - $clientSecret, $redirectUri, $code - ); - $client = new Client; - try { - $res = $client->request('POST', $uri); - } catch (GuzzleException|Exception $e) { - Log::error($e->getMessage()); - Log::error($e->getTraceAsString()); - throw new FireflyException($e->getMessage()); - } - $statusCode = $res->getStatusCode(); - try { - $content = trim($res->getBody()->getContents()); - } catch (RuntimeException $e) { - Log::error($e->getMessage()); - Log::error($e->getTraceAsString()); - throw new FireflyException($e->getMessage()); - } - - $json = json_decode($content, true) ?? []; - Log::debug(sprintf('Status code from YNAB is %d', $statusCode)); - Log::debug(sprintf('Body of result is %s', $content), $json); - - // store refresh token (if present?) as preference - // store token in job: - $configuration = $this->repository->getConfiguration($this->importJob); - $configuration['access_token'] = $json['access_token']; - $configuration['access_token_expires'] = (int)$json['created_at'] + (int)$json['expires_in']; - $this->repository->setConfiguration($this->importJob, $configuration); - - Log::debug('end of StageGetAccessHandler::run()'); - - $refreshToken = (string)($json['refresh_token'] ?? ''); - if ('' !== $refreshToken) { - app('preferences')->set('ynab_refresh_token', $refreshToken); - } - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Import/Routine/Ynab/StageGetBudgetsHandler.php b/app/Support/Import/Routine/Ynab/StageGetBudgetsHandler.php deleted file mode 100644 index a0e0923966..0000000000 --- a/app/Support/Import/Routine/Ynab/StageGetBudgetsHandler.php +++ /dev/null @@ -1,77 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Ynab; - -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; -use FireflyIII\Services\Ynab\Request\GetBudgetsRequest; -use Log; - -/** - * Class StageGetBudgetsHandler - * @deprecated - * @codeCoverageIgnore - */ -class StageGetBudgetsHandler -{ - - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * - * @throws FireflyException - */ - public function run(): void - { - Log::debug('Now in StageGetBudgetsHandler::run()'); - // grab access token from job: - $configuration = $this->repository->getConfiguration($this->importJob); - $token = $configuration['access_token']; - $request = new GetBudgetsRequest; - $request->setAccessToken($token); - $request->call(); - - // store budgets in users preferences. - $configuration['budgets'] = $request->budgets; - $this->repository->setConfiguration($this->importJob, $configuration); - Log::debug(sprintf('Found %d budgets', count($request->budgets))); - if (0 === count($request->budgets)) { - throw new FireflyException('It seems this user has zero budgets or an error prevented Firefly III from reading them.'); - } - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Import/Routine/Ynab/StageGetTransactionsHandler.php b/app/Support/Import/Routine/Ynab/StageGetTransactionsHandler.php deleted file mode 100644 index be8cdd7ff1..0000000000 --- a/app/Support/Import/Routine/Ynab/StageGetTransactionsHandler.php +++ /dev/null @@ -1,57 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Ynab; - -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; - -/** - * Class StageGetTransactionsHandler - * @deprecated - * @codeCoverageIgnore - */ -class StageGetTransactionsHandler -{ - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * - */ - public function run(): void - { - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Import/Routine/Ynab/StageMatchAccountsHandler.php b/app/Support/Import/Routine/Ynab/StageMatchAccountsHandler.php deleted file mode 100644 index 948b64a5bb..0000000000 --- a/app/Support/Import/Routine/Ynab/StageMatchAccountsHandler.php +++ /dev/null @@ -1,59 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Support\Import\Routine\Ynab; - -use FireflyIII\Models\ImportJob; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; - -/** - * Class StageMatchAccountsHandler - * @deprecated - * @codeCoverageIgnore - */ -class StageMatchAccountsHandler -{ - - - /** @var ImportJob */ - private $importJob; - /** @var ImportJobRepositoryInterface */ - private $repository; - - /** - * - */ - public function run(): void - { - } - - /** - * @param ImportJob $importJob - */ - public function setImportJob(ImportJob $importJob): void - { - $this->importJob = $importJob; - $this->repository = app(ImportJobRepositoryInterface::class); - $this->repository->setUser($importJob->user); - } -} diff --git a/app/Support/Telemetry.php b/app/Support/Telemetry.php index 14ef9cc927..76e8bbd696 100644 --- a/app/Support/Telemetry.php +++ b/app/Support/Telemetry.php @@ -45,7 +45,6 @@ class Telemetry * - execute-cli-command [value] * - use-help-pages * - has-created-bill - * - do-big-import * - first-time-install * - more * diff --git a/app/Transformers/ImportJobTransformer.php b/app/Transformers/ImportJobTransformer.php deleted file mode 100644 index b705e766d4..0000000000 --- a/app/Transformers/ImportJobTransformer.php +++ /dev/null @@ -1,91 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers; - - -use FireflyIII\Models\ImportJob; -use Log; - -/** - * Class ImportJobTransformer - * @deprecated - */ -class ImportJobTransformer extends AbstractTransformer -{ - /** - * PiggyBankTransformer constructor. - * - * @codeCoverageIgnore - */ - public function __construct() - { - if ('testing' === config('app.env')) { - Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); - } - } - - - /** - * Transform the import job. - * - * @param ImportJob $importJob - * - * @return array - */ - public function transform(ImportJob $importJob): array - { - $tag = $importJob->tag; - $tagId = null; - $tagTag = null; - if (null !== $tag) { - $tagId = $tag->id; - $tagTag = $tag->tag; - } - $data = [ - 'id' => (int)$importJob->id, - 'created_at' => $importJob->created_at->toAtomString(), - 'updated_at' => $importJob->updated_at->toAtomString(), - 'tag_id' => $tagId, - 'tag_tag' => $tagTag, - 'key' => $importJob->key, - 'file_type' => $importJob->file_type, - 'provider' => $importJob->provider, - 'status' => $importJob->status, - 'stage' => $importJob->stage, - 'configuration' => json_encode($importJob->configuration), - 'extended_status' => json_encode($importJob->extended_status), - 'transactions' => json_encode($importJob->transactions), - 'errors' => json_encode($importJob->errors), - - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/import/' . $importJob->key, - ], - ], - ]; - - return $data; - } -} diff --git a/app/User.php b/app/User.php index 53f1cdf805..4a2f39b2b7 100644 --- a/app/User.php +++ b/app/User.php @@ -34,7 +34,6 @@ use FireflyIII\Models\Bill; use FireflyIII\Models\Budget; use FireflyIII\Models\Category; use FireflyIII\Models\CurrencyExchangeRate; -use FireflyIII\Models\ImportJob; use FireflyIII\Models\PiggyBank; use FireflyIII\Models\Preference; use FireflyIII\Models\Recurrence; @@ -89,7 +88,6 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property-read \Illuminate\Database\Eloquent\Collection|Category[] $categories * @property-read \Illuminate\Database\Eloquent\Collection|Client[] $clients * @property-read \Illuminate\Database\Eloquent\Collection|CurrencyExchangeRate[] $currencyExchangeRates - * @property-read \Illuminate\Database\Eloquent\Collection|ImportJob[] $importJobs * @property-read DatabaseNotificationCollection|DatabaseNotification[] $notifications * @property-read \Illuminate\Database\Eloquent\Collection|PiggyBank[] $piggyBanks * @property-read \Illuminate\Database\Eloquent\Collection|Preference[] $preferences @@ -123,7 +121,6 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property-read int|null $categories_count * @property-read int|null $clients_count * @property-read int|null $currency_exchange_rates_count - * @property-read int|null $import_jobs_count * @property-read int|null $notifications_count * @property-read int|null $piggy_banks_count * @property-read int|null $preferences_count @@ -138,6 +135,10 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property-read int|null $transactions_count * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\User whereMfaSecret($value) * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\User whereObjectguid($value) + * @property string $password + * @property bool $blocked + * @property string|null $blocked_code + * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Role[] $roles */ class User extends Authenticatable { @@ -292,17 +293,6 @@ class User extends Authenticatable return bin2hex($bytes); } - /** - * @codeCoverageIgnore - * Link to import jobs. - * - * @return HasMany - */ - public function importJobs(): HasMany - { - return $this->hasMany(ImportJob::class); - } - /** * @codeCoverageIgnore * Link to piggy banks. diff --git a/composer.json b/composer.json index ad4c983402..ec2d036483 100644 --- a/composer.json +++ b/composer.json @@ -84,7 +84,6 @@ "ext-xml": "*", "adldap2/adldap2-laravel": "6.*", "bacon/bacon-qr-code": "1.*", - "bunq/sdk_php": "dev-master", "davejamesmiller/laravel-breadcrumbs": "5.*", "doctrine/dbal": "2.*", "fideloper/proxy": "4.*", @@ -93,7 +92,6 @@ "laravel/passport": "8.*", "laravelcollective/html": "6.*", "league/commonmark": "1.*", - "league/csv": "9.*", "league/fractal": "0.*", "pragmarx/google2fa": "^7.0", "pragmarx/recovery": "^0.1.0", diff --git a/composer.lock b/composer.lock index 8d882affdb..5545d210b1 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "5af5d9774ef0e82cd34d08c63020e85d", + "content-hash": "f298bbfe499e6d187eddfd75734dce42", "packages": [ { "name": "adldap2/adldap2", @@ -165,70 +165,6 @@ "homepage": "https://github.com/Bacon/BaconQrCode", "time": "2017-10-17T09:59:25+00:00" }, - { - "name": "bunq/sdk_php", - "version": "dev-master", - "source": { - "type": "git", - "url": "https://github.com/bunq/sdk_php.git", - "reference": "d97d2a710038d183b711825864584e2d31e30e35" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/bunq/sdk_php/zipball/d97d2a710038d183b711825864584e2d31e30e35", - "reference": "d97d2a710038d183b711825864584e2d31e30e35", - "shasum": "" - }, - "require": { - "ext-curl": "*", - "ext-json": "*", - "ext-mbstring": "*", - "guzzlehttp/guzzle": "~6", - "php": "^7.0.13" - }, - "require-dev": { - "brianium/paratest": "^1.1", - "friendsofphp/php-cs-fixer": "^2.4", - "jakub-onderka/php-parallel-lint": "^0.9.2", - "phpro/grumphp": "^0.11.6", - "phpstan/phpstan": "^0.8", - "phpunit/phpunit": "^6.0.13", - "sebastian/phpcpd": "^3.0", - "sensiolabs/security-checker": "^5.0" - }, - "bin": [ - "bin/bunq-install" - ], - "type": "library", - "autoload": { - "psr-4": { - "bunq\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "bunq", - "email": "sdk@bunq.com", - "homepage": "https://www.bunq.com", - "role": "Owner" - } - ], - "description": "bunq PHP SDK", - "homepage": "https://bunq.com/", - "keywords": [ - "api", - "bunq", - "finance", - "open-banking", - "payment", - "sepa" - ], - "time": "2020-04-03T15:48:46+00:00" - }, { "name": "davejamesmiller/laravel-breadcrumbs", "version": "5.3.2", @@ -1915,77 +1851,6 @@ ], "time": "2020-05-04T22:15:21+00:00" }, - { - "name": "league/csv", - "version": "9.6.0", - "source": { - "type": "git", - "url": "https://github.com/thephpleague/csv.git", - "reference": "7351a74625601914409b42b32cabb91a93773b7b" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/thephpleague/csv/zipball/7351a74625601914409b42b32cabb91a93773b7b", - "reference": "7351a74625601914409b42b32cabb91a93773b7b", - "shasum": "" - }, - "require": { - "ext-json": "*", - "ext-mbstring": "*", - "php": "^7.2.5" - }, - "require-dev": { - "ext-curl": "*", - "friendsofphp/php-cs-fixer": "^2.16", - "phpstan/phpstan": "^0.12.0", - "phpstan/phpstan-phpunit": "^0.12.0", - "phpstan/phpstan-strict-rules": "^0.12.0", - "phpunit/phpunit": "^8.0" - }, - "suggest": { - "ext-dom": "Required to use the XMLConverter and or the HTMLConverter classes", - "ext-iconv": "Needed to ease transcoding CSV using iconv stream filters" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "9.x-dev" - } - }, - "autoload": { - "psr-4": { - "League\\Csv\\": "src" - }, - "files": [ - "src/functions_include.php" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Ignace Nyamagana Butera", - "email": "nyamsprod@gmail.com", - "homepage": "https://github.com/nyamsprod/", - "role": "Developer" - } - ], - "description": "CSV data manipulation made easy in PHP", - "homepage": "http://csv.thephpleague.com", - "keywords": [ - "convert", - "csv", - "export", - "filter", - "import", - "read", - "transform", - "write" - ], - "time": "2020-03-17T15:15:35+00:00" - }, { "name": "league/event", "version": "2.2.0", @@ -9428,7 +9293,6 @@ "aliases": [], "minimum-stability": "stable", "stability-flags": { - "bunq/sdk_php": 20, "roave/security-advisories": 20 }, "prefer-stable": false, diff --git a/config/app.php b/config/app.php index 3e5f86562a..59706a8860 100644 --- a/config/app.php +++ b/config/app.php @@ -21,7 +21,6 @@ declare(strict_types=1); -use FireflyIII\Providers\ImportServiceProvider; use FireflyIII\Support\Facades\Telemetry; return [ @@ -97,7 +96,6 @@ return [ FireflyIII\Providers\TagServiceProvider::class, FireflyIII\Providers\AdminServiceProvider::class, FireflyIII\Providers\RecurringServiceProvider::class, - ImportServiceProvider::class, ], 'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, diff --git a/config/csv.php b/config/csv.php deleted file mode 100644 index c459762b00..0000000000 --- a/config/csv.php +++ /dev/null @@ -1,430 +0,0 @@ -. - */ - -declare(strict_types=1); - -use FireflyIII\Import\Specifics\AbnAmroDescription; -use FireflyIII\Import\Specifics\Belfius; -use FireflyIII\Import\Specifics\IngBelgium; -use FireflyIII\Import\Specifics\IngDescription; -use FireflyIII\Import\Specifics\PresidentsChoice; -use FireflyIII\Import\Specifics\SnsDescription; - -return [ - /* - * Configuration for the CSV specifics. - */ - 'import_specifics' => [ - 'IngDescription' => IngDescription::class, - 'AbnAmroDescription' => AbnAmroDescription::class, - 'SnsDescription' => SnsDescription::class, - 'PresidentsChoice' => PresidentsChoice::class, - 'Belfius' => Belfius::class, - 'IngBelgium' => IngBelgium::class, - ], - - /* - * Configuration for possible column roles. - * - * The key is the short name for the column role. There are five values, which mean this: - * - * 'mappable' - * Whether or not the value in the CSV column can be linked to an existing value in your - * Firefly database. For example: account names can be linked to existing account names you have already - * so double entries cannot occur. This process is called "mapping". You have to make each unique value in your - * CSV file to an existing entry in your database. For example, map all account names in your CSV file to existing - * accounts. If you have an entry that does not exist in your database, you can set Firefly to ignore it, and it will - * create it. - * - * 'pre-process-map' - * In the case of tags, there are multiple values in one csv column (for example: "expense groceries snack" in one column). - * This means the content of the column must be "pre processed" aka split in parts so the importer can work with the data. - * - * 'pre-process-mapper' - * This is the class that will actually do the pre-processing. - * - * 'field' - * I don't believe this value is used any more, but I am not sure. - * - * 'converter' - * The converter is a class in app/Import/Converter that converts the given value into an object Firefly understands. - * The CategoryName converter can convert a category name into an actual category. This converter will take a mapping - * into account: if you mapped "Groceries" to category "Groceries" the converter will simply return "Groceries" instead of - * trying to make a new category also named Groceries. - * - * 'mapper' - * When you map data (see "mappable") you need a list of stuff you can map to. If you say a certain column is mappable - * and the column contains "category names", the mapper will be "Category" and it will give you a list of possible categories. - * This way the importer always presents you with a valid list of things to map to. - * - * - * - */ - 'import_roles' => [ - '_ignore' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'field' => 'ignored', - 'converter' => 'Ignore', - 'mapper' => null, - - ], - 'bill-id' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'bill', - 'converter' => 'BillId', - 'mapper' => 'Bills', - ], - 'note' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'field' => 'note', - 'converter' => 'Note', - ], - 'bill-name' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'bill', - 'converter' => 'BillName', - 'mapper' => 'Bills', - ], - 'currency-id' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'currency', - 'converter' => 'CurrencyId', - 'mapper' => 'TransactionCurrencies', - ], - 'currency-name' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'converter' => 'CurrencyName', - 'field' => 'currency', - 'mapper' => 'TransactionCurrencies', - ], - 'currency-code' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'converter' => 'CurrencyCode', - 'field' => 'currency', - 'mapper' => 'TransactionCurrencies', - ], - 'foreign-currency-code' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'converter' => 'CurrencyCode', - 'field' => 'foreign_currency', - 'mapper' => 'TransactionCurrencies', - ], - 'external-id' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'ExternalId', - 'field' => 'external-id', - ], - - 'currency-symbol' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'converter' => 'CurrencySymbol', - 'field' => 'currency', - 'mapper' => 'TransactionCurrencies', - ], - 'description' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'description', - ], - 'date-transaction' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Date', - 'field' => 'date', - ], - 'date-interest' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Date', - 'field' => 'date-interest', - ], - 'date-book' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Date', - 'field' => 'date-book', - ], - 'date-process' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Date', - 'field' => 'date-process', - ], - 'date-due' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Date', - 'field' => 'date-due', - ], - 'date-payment' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Date', - 'field' => 'date-payment', - ], - 'date-invoice' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Date', - 'field' => 'date-invoice', - ], - 'budget-id' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'converter' => 'BudgetId', - 'field' => 'budget', - 'mapper' => 'Budgets', - ], - 'budget-name' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'converter' => 'BudgetName', - 'field' => 'budget', - 'mapper' => 'Budgets', - ], - 'rabo-debit-credit' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'BankDebitCredit', - 'field' => 'amount-modifier', - ], - 'ing-debit-credit' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'BankDebitCredit', - 'field' => 'amount-modifier', - ], - 'generic-debit-credit' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'BankDebitCredit', - 'field' => 'amount-modifier', - ], - 'category-id' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'converter' => 'CategoryId', - 'field' => 'category', - 'mapper' => 'Categories', - ], - 'category-name' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'converter' => 'CategoryName', - 'field' => 'category', - 'mapper' => 'Categories', - ], - 'tags-comma' => [ - 'mappable' => false, - 'pre-process-map' => true, - 'pre-process-mapper' => 'TagsComma', - 'field' => 'tags', - 'converter' => 'TagsComma', - 'mapper' => 'Tags', - ], - 'tags-space' => [ - 'mappable' => false, - 'pre-process-map' => true, - 'pre-process-mapper' => 'TagsSpace', - 'field' => 'tags', - 'converter' => 'TagsSpace', - 'mapper' => 'Tags', - ], - 'account-id' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'asset-account-id', - 'converter' => 'AccountId', - 'mapper' => 'AssetAccounts', - ], - 'account-name' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'asset-account-name', - 'converter' => 'AssetAccountName', - 'mapper' => 'AssetAccounts', - ], - 'account-iban' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'asset-account-iban', - 'converter' => 'AssetAccountIban', - 'mapper' => 'AssetAccountIbans', - - ], - 'account-number' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'asset-account-number', - 'converter' => 'AssetAccountNumber', - 'mapper' => 'AssetAccounts', - ], - 'account-bic' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'field' => 'asset-account-bic', - 'converter' => 'AccountBic', - ], - 'opposing-id' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'opposing-account-id', - 'converter' => 'AccountId', - 'mapper' => 'OpposingAccounts', - ], - 'opposing-bic' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'field' => 'opposing-account-bic', - 'converter' => 'AccountBic', - ], - 'opposing-name' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'opposing-account-name', - 'converter' => 'OpposingAccountName', - 'mapper' => 'OpposingAccounts', - ], - 'opposing-iban' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'opposing-account-iban', - 'converter' => 'OpposingAccountIban', - 'mapper' => 'OpposingAccountIbans', - ], - 'opposing-number' => [ - 'mappable' => true, - 'pre-process-map' => false, - 'field' => 'opposing-account-number', - 'converter' => 'OpposingAccountNumber', - 'mapper' => 'OpposingAccounts', - ], - 'amount' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Amount', - 'field' => 'amount', - ], - 'amount_debit' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'AmountDebit', - 'field' => 'amount_debit', - ], - 'amount_credit' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'AmountCredit', - 'field' => 'amount_credit', - ], - 'amount_negated' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'AmountNegated', - 'field' => 'amount_negated', - ], - 'amount_foreign' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Amount', - 'field' => 'amount_foreign', - ], - - // SEPA end to end ID - 'sepa_ct_id' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'sepa_ct_id', - ], - // SEPA opposing account identifier - 'sepa_ct_op' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'sepa_ct_op', - ], - // SEPA Direct Debit Mandate Identifier - 'sepa_db' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'sepa_db', - ], - // SEPA clearing code - 'sepa_cc' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'sepa_cc', - ], - // SEPA country - 'sepa_country' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'sepa_country', - ], - // SEPA external purpose - 'sepa_ep' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'sepa_ep', - ], - // SEPA creditor identifier - 'sepa_ci' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'sepa_ci', - ], - // SEPA Batch ID - 'sepa_batch_id' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'sepa_batch', - ], - // Internal reference - 'internal-reference' => [ - 'mappable' => false, - 'pre-process-map' => false, - 'converter' => 'Description', - 'field' => 'internal_reference', - ], - ], - - // number of example rows: - 'example_rows' => 5, -]; diff --git a/config/firefly.php b/config/firefly.php index 61dde484a5..cd821fa02f 100644 --- a/config/firefly.php +++ b/config/firefly.php @@ -30,7 +30,6 @@ use FireflyIII\Models\Bill; use FireflyIII\Models\Budget; use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\Category; -use FireflyIII\Models\ImportJob; use FireflyIII\Models\LinkType; use FireflyIII\Models\PiggyBank; use FireflyIII\Models\Preference; @@ -53,7 +52,6 @@ use FireflyIII\Support\Binder\CLIToken; use FireflyIII\Support\Binder\ConfigurationName; use FireflyIII\Support\Binder\CurrencyCode; use FireflyIII\Support\Binder\Date; -use FireflyIII\Support\Binder\ImportProvider; use FireflyIII\Support\Binder\JournalList; use FireflyIII\Support\Binder\TagList; use FireflyIII\Support\Binder\TagOrId; @@ -180,7 +178,6 @@ return [ Bill::class, Budget::class, Category::class, - ImportJob::class, PiggyBank::class, Tag::class, Transaction::class, @@ -248,7 +245,6 @@ return [ 'application/vnd.oasis.opendocument.image', ], 'list_length' => 10, - 'default_import_format' => 'csv', 'bill_periods' => ['weekly', 'monthly', 'quarterly', 'half-year', 'yearly'], 'accountRoles' => ['defaultAsset', 'sharedAsset', 'savingAsset', 'ccAsset', 'cashWalletAsset'], 'ccTypes' => [ @@ -418,12 +414,10 @@ return [ 'recurrence' => Recurrence::class, 'rule' => Rule::class, 'ruleGroup' => RuleGroup::class, - 'importJob' => ImportJob::class, 'transactionGroup' => TransactionGroup::class, 'user' => User::class, // strings - 'import_provider' => ImportProvider::class, 'currency_code' => CurrencyCode::class, // dates diff --git a/config/import.php b/config/import.php deleted file mode 100644 index 21f5d74422..0000000000 --- a/config/import.php +++ /dev/null @@ -1,172 +0,0 @@ -. - */ - -declare(strict_types=1); - -use FireflyIII\Import\JobConfiguration\BunqJobConfiguration; -use FireflyIII\Import\JobConfiguration\FakeJobConfiguration; -use FireflyIII\Import\JobConfiguration\FileJobConfiguration; -use FireflyIII\Import\JobConfiguration\FinTSJobConfiguration; -use FireflyIII\Import\JobConfiguration\SpectreJobConfiguration; -use FireflyIII\Import\JobConfiguration\YnabJobConfiguration; -use FireflyIII\Import\Prerequisites\BunqPrerequisites; -use FireflyIII\Import\Prerequisites\FakePrerequisites; -use FireflyIII\Import\Prerequisites\SpectrePrerequisites; -use FireflyIII\Import\Prerequisites\YnabPrerequisites; -use FireflyIII\Import\Routine\BunqRoutine; -use FireflyIII\Import\Routine\FakeRoutine; -use FireflyIII\Import\Routine\FileRoutine; -use FireflyIII\Import\Routine\FinTSRoutine; -use FireflyIII\Import\Routine\SpectreRoutine; -use FireflyIII\Import\Routine\YnabRoutine; -use FireflyIII\Support\Import\Routine\File\CSVProcessor; - -return [ - // these import providers are available: - 'enabled' => [ - 'fake' => true, - 'file' => false, - 'bunq' => false, - 'spectre' => true, - 'ynab' => false, - 'plaid' => false, - 'quovo' => false, - 'yodlee' => false, - 'fints' => false, - 'bad' => false, // always disabled - ], - // demo user can use these import providers (when enabled): - 'allowed_for_demo' => [ - 'fake' => true, - 'file' => false, - 'bunq' => false, - 'spectre' => false, - 'ynab' => false, - 'plaid' => false, - 'quovo' => false, - 'yodlee' => false, - 'fints' => false, - ], - // a normal user user can use these import providers (when enabled): - 'allowed_for_user' => [ - 'fake' => false, - 'file' => true, - 'bunq' => false, - 'spectre' => true, - 'ynab' => true, - 'plaid' => true, - 'quovo' => true, - 'yodlee' => true, - 'fints' => true, - ], - // some providers have pre-requisites. - 'has_prereq' => [ - 'fake' => true, - 'file' => false, - 'bunq' => false, - 'spectre' => true, - 'ynab' => true, - 'plaid' => true, - 'quovo' => true, - 'yodlee' => true, - 'fints' => false, - ], - // if so, there must be a class to handle them. - 'prerequisites' => [ - 'fake' => FakePrerequisites::class, - 'file' => false, - 'bunq' => BunqPrerequisites::class, - 'spectre' => SpectrePrerequisites::class, - 'ynab' => YnabPrerequisites::class, - 'plaid' => false, - 'quovo' => false, - 'yodlee' => false, - 'fints' => false, - ], - // some providers may need extra configuration per job - 'has_job_config' => [ - 'fake' => true, - 'file' => true, - 'bunq' => true, - 'spectre' => true, - 'ynab' => true, - 'plaid' => false, - 'quovo' => false, - 'yodlee' => false, - 'fints' => true, - ], - // if so, this is the class that handles it. - 'configuration' => [ - 'fake' => FakeJobConfiguration::class, - 'file' => FileJobConfiguration::class, - 'bunq' => BunqJobConfiguration::class, - 'spectre' => SpectreJobConfiguration::class, - 'ynab' => YnabJobConfiguration::class, - 'plaid' => false, - 'quovo' => false, - 'yodlee' => false, - 'fints' => FinTSJobConfiguration::class, - ], - // this is the routine that runs the actual import. - 'routine' => [ - 'fake' => FakeRoutine::class, - 'file' => FileRoutine::class, - 'bunq' => BunqRoutine::class, - 'spectre' => SpectreRoutine::class, - 'ynab' => YnabRoutine::class, - 'plaid' => false, - 'quovo' => false, - 'yodlee' => false, - 'fints' => FinTSRoutine::class, - ], - - 'options' => [ - 'fake' => [], - 'file' => [ - 'import_formats' => ['csv'], // mt940 - 'default_import_format' => 'csv', - 'processors' => [ - 'csv' => CSVProcessor::class, - ], - ], - 'bunq' => [ - 'live' => [ - 'server' => 'api.bunq.com', - 'version' => 'v1', - ], - 'sandbox' => [ - 'server' => 'sandbox.public.api.bunq.com', // sandbox.public.api.bunq.com - api.bunq.com - 'version' => 'v1', - ], - ], - 'spectre' => [ - 'server' => 'www.saltedge.com', - ], - 'ynab' => [ - 'live' => 'api.youneedabudget.com', - 'version' => 'v1', - ], - 'plaid' => [], - 'quovo' => [], - 'yodlee' => [], - ], -]; diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php index d52f908a3c..8b0125216f 100644 --- a/database/factories/ModelFactory.php +++ b/database/factories/ModelFactory.php @@ -65,27 +65,6 @@ $factory->define( } ); -$factory->define( - FireflyIII\Models\ImportJob::class, - static function (Faker\Generator $faker) { - return [ - 'id' => $faker->numberBetween(1, 100), - 'user_id' => 1, - 'key' => $faker->words(1, true), - 'file_type' => 'csv', - 'status' => 'import_status_never_started', - 'configuration' => null, - 'extended_status' => [ - 'total_steps' => 0, - 'steps_done' => 0, - 'import_count' => 0, - 'importTag' => 0, - 'errors' => [], - ], - ]; - } -); - $factory->define( FireflyIII\Models\TransactionJournal::class, static function (Faker\Generator $faker) { diff --git a/public/v1/js/ff/import/.htaccess b/public/v1/js/ff/import/.htaccess deleted file mode 100644 index 45552cb63e..0000000000 --- a/public/v1/js/ff/import/.htaccess +++ /dev/null @@ -1 +0,0 @@ -Options -Indexes \ No newline at end of file diff --git a/public/v1/js/ff/import/file/.htaccess b/public/v1/js/ff/import/file/.htaccess deleted file mode 100644 index 45552cb63e..0000000000 --- a/public/v1/js/ff/import/file/.htaccess +++ /dev/null @@ -1 +0,0 @@ -Options -Indexes \ No newline at end of file diff --git a/public/v1/js/ff/import/file/configure-upload.js b/public/v1/js/ff/import/file/configure-upload.js deleted file mode 100644 index d07f600ae3..0000000000 --- a/public/v1/js/ff/import/file/configure-upload.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * configure-upload.js - * Copyright (c) 2019 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * 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. - * - * This program 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -$(function () { - "use strict"; - - var importMultiSelect = { - disableIfEmpty: true, - selectAllText: selectAllText, - nonSelectedText: nonSelectedText, - nSelectedText: nSelectedText, - allSelectedText: allSelectedText, - includeSelectAllOption: true, - enableFiltering: true, - enableCaseInsensitiveFiltering: true, - filterPlaceholder: filterPlaceholder, - enableHTML: true, - }; - -// make account select a hip new bootstrap multi-select thing. - $('#inputSpecifics').multiselect(importMultiSelect); - -}); \ No newline at end of file diff --git a/public/v1/js/ff/import/status.js b/public/v1/js/ff/import/status.js deleted file mode 100644 index cb36bb8d89..0000000000 --- a/public/v1/js/ff/import/status.js +++ /dev/null @@ -1,301 +0,0 @@ -/* - * status.js - * Copyright (c) 2019 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * 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. - * - * This program 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -/** global: job, langImportSingleError, langImportMultiError, jobStartUrl, langImportTimeOutError, langImportFinished, langImportFatalError */ - -var timeOutId; -var startInterval = 1000; -var interval = 500; - -// these vars are used to detect a stalled job: -var numberOfSteps = 0; -var numberOfReports = 0; -var jobFailed = false; -var pressedStart = false; - -// counts how many errors have been detected -var knownErrors = 0; - -$(function () { - "use strict"; - timeOutId = setTimeout(checkJobStatus, startInterval); - - $('.start-job').click(function () { - // notify (extra) that start button is pressed. - pressedStart = true; - startJob(); - }); - if (job.configuration['auto-start']) { - startJob(); - } -}); - -/** - * Downloads some JSON and responds to its content to see what the status is of the current import. - */ -function checkJobStatus() { - console.log('In checkJobStatus()'); - if(jobFailed) { - return; - } - $.getJSON(jobStatusUri).done(reportOnJobStatus).fail(reportFailedJob); -} - -/** - * This method is called when the JSON query returns an error. If possible, this error is relayed to the user. - */ -function reportFailedJob(jqxhr, textStatus, error) { - console.log('In reportFailedJob()'); - - // cancel refresh - clearTimeout(timeOutId); - - // hide all possible boxes: - $('.statusbox').hide(); - - // fill in some details: - var errorMessage = textStatus + " " + error; - - $('.fatal_error_txt').text(errorMessage); - - // show the fatal error box: - $('.fatal_error').show(); -} - -/** - * This method is called when the job enquiry (JSON) returns some info. - * It also decides whether or not to check again. - * - * @param data - */ -function reportOnJobStatus(data) { - console.log('In reportOnJobStatus()'); - switch (data.status) { - case "configured": - console.log('Job reports configured.'); - // job is ready. Do not check again, just show the start-box. Hide the rest. - if (!job.configuration['auto-start']) { - $('.statusbox').hide(); - $('.status_configured').show(); - } - if (job.configuration['auto-start']) { - timeOutId = setTimeout(checkJobStatus, interval); - } - if (pressedStart) { - // do a time out just in case. Could be that job is running or is even done already. - timeOutId = setTimeout(checkJobStatus, 2000); - pressedStart = false; - } - break; - case "running": - console.log('Job reports running.'); - // job is running! Show the running box: - $('.statusbox').hide(); - $('.status_running').show(); - - // update the bar - updateBar(data); - - // update the status text: - updateStatusText(data); - - // report on detected errors: - reportOnErrors(data); - - if (jobIsStalled(data)) { - // do something - showStalledBox(); - } else { - // check again in 500ms - timeOutId = setTimeout(checkJobStatus, interval); - } - break; - case "finished": - console.log('Job reports finished.'); - $('.statusbox').hide(); - $('.status_finished').show(); - // report on detected errors: - reportOnErrors(data); - // show text: - $('#import-status-more-info').html(data.finishedText); - break; - case "error": - clearTimeout(timeOutId); - console.log('Job reports ERROR.'); - // hide all possible boxes: - $('.statusbox').hide(); - - // fill in some details: - var errorMessage = data.errors.join(", "); - - $('.fatal_error_txt').text(errorMessage); - - // show the fatal error box: - $('.fatal_error').show(); - break; - case "configuring": - console.log('Job reports configuring.'); - // redirect back to configure screen. - window.location = jobConfigureUri; - break; - default: - console.error('Cannot handle job status ' + data.status); - break; - - } -} - -/** - * Shows a fatal error when the job seems to be stalled. - */ -function showStalledBox() { - console.log('In showStalledBox().'); - $('.statusbox').hide(); - $('.fatal_error').show(); - $('.fatal_error_txt').text(langImportTimeOutError); -} - -/** - * Detects if a job is frozen. - * - * @param data - */ -function jobIsStalled(data) { - console.log('In jobIsStalled().'); - if (data.done === numberOfSteps) { - numberOfReports++; - console.log('Number of reports ' + numberOfReports); - } - if (data.done !== numberOfSteps) { - numberOfReports = 0; - console.log('Number of reports ' + numberOfReports); - } - if (numberOfReports > 20) { - console.log('Number of reports > 20! ' + numberOfReports); - return true; - } - numberOfSteps = data.done; - console.log('Number of steps ' + numberOfSteps); - return false; -} - -/** - * This function tells Firefly start the job. It will also initialize a re-check in 500ms time. - * Only when job is in "configured" state. - */ -function startJob() { - console.log('In startJob().'); - if (job.status === "configured") { - console.log('Job status = configured.'); - // disable the button, add loading thing. - $('.start-job').prop('disabled', true).text('...'); - $.post(jobStartUri, {_token: token}).fail(reportOnSubmitError); - - // check status, every 500 ms. - timeOutId = setTimeout(checkJobStatus, startInterval); - return; - } - console.log('Job.status = ' + job.status); -} - -/** - * When the start button fails (returns error code) this function reports. It assumes a time out. - */ -function reportOnSubmitError(jqxhr, textStatus, error) { - console.log('In reportOnSubmitError().'); - // stop the refresh thing - clearTimeout(timeOutId); - - // hide all possible boxes: - $('.statusbox').hide(); - - // fill in some details: - var errorMessage = "Submitting the job returned an error: " + textStatus + ' ' + error; - - $('.fatal_error_txt').text(errorMessage); - - // show the fatal error box: - $('.fatal_error').show(); - jobFailed = true; - -} - -/** - * This method updates the percentage bar thing if the job is running! - */ -function updateBar(data) { - console.log('In updateBar().'); - var bar = $('#import-status-bar'); - if (data.show_percentage) { - bar.addClass('progress-bar-success').removeClass('progress-bar-info'); - bar.attr('aria-valuenow', data.percentage); - bar.css('width', data.percentage + '%'); - $('#import-status-bar').text(data.done + '/' + data.steps); - return true; - } - // dont show percentage: - bar.removeClass('progress-bar-success').addClass('progress-bar-info'); - bar.attr('aria-valuenow', 100); - bar.css('width', '100%'); - return true; -} - -/** - * Add text with current import status. - * @param data - */ -function updateStatusText(data) { - "use strict"; - console.log('In updateStatusText().'); - $('#import-status-txt').removeClass('text-danger').text(data.statusText); -} - -/** - * Report on errors found in import: - * @param data - */ -function reportOnErrors(data) { - console.log('In reportOnErrors().'); - if (knownErrors === data.errors.length) { - return; - } - if (data.errors.length === 0) { - return; - } - - if (data.errors.length === 1) { - $('#import-status-error-intro').text(langImportSingleError); - //'An error has occurred during the import. The import can continue, however.' - } - if (data.errors.length > 1) { - // 'Errors have occurred during the import. The import can continue, however.' - $('#import-status-error-intro').text(langImportMultiError); - } - $('.info_errors').show(); - // fill the list with error texts - $('#import-status-error-list').empty(); - for (var i = 0; i < data.errors.length; i++) { - var errorSet = data.errors[i]; - for (var j = 0; j < errorSet.length; j++) { - var item = $('
  • ').html(errorSet[j]); - $('#import-status-error-list').append(item); - } - } -} diff --git a/public/v1/js/ff/import/status_v2.js b/public/v1/js/ff/import/status_v2.js deleted file mode 100644 index e1e7a7f588..0000000000 --- a/public/v1/js/ff/import/status_v2.js +++ /dev/null @@ -1,296 +0,0 @@ -/* - * status_v2.js - * Copyright (c) 2019 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * 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. - * - * This program 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -/** global: jobStatusUri */ - -var timeOutId; -var jobRunRoutineStarted = false; -var jobStorageRoutineStarted = false; -var checkInitialInterval = 1000; -var checkNextInterval = 500; -var maxLoops = 65536; -var totalLoops = 0; -var startCount = 0; -var jobFailed = false; -// set to true when error is reported. -// will prevent double error reporting -var reportedError = false; - - -$(function () { - "use strict"; - timeOutId = setTimeout(checkJobJSONStatus, checkInitialInterval); -}); - -/** - * Downloads some JSON and responds to its content to see what the status is of the current import job. - */ -function checkJobJSONStatus() { - //console.log('In checkJobJSONStatus()'); - if (jobFailed === false) { - $.getJSON(jobStatusUri).done(reportJobJSONDone).fail(reportJobJSONFailure); - } - if (jobFailed === true) { - console.error('Job has failed, will not check.'); - } -} - -/** - * Reports to the user what the state is of the current job. - * - * @param data - */ -function reportJobJSONDone(data) { - //console.log('In reportJobJSONDone() with status "' + data.status + '"'); - //console.log(data); - switch (data.status) { - case "ready_to_run": - if (startCount > 0) { - jobRunRoutineStarted = false; - } - startCount++; - sendJobPOSTStart(); - recheckJobJSONStatus(); - break; - case "need_job_config": - console.log("Will redirect user to " + jobConfigurationUri); - // redirect user to configuration for this job. - window.location.replace(jobConfigurationUri); - break; - case 'error': - reportJobError(data); - break; - case 'provider_finished': - // call routine to store stuff: - sendJobPOSTStore(); - recheckJobJSONStatus(); - break; - case "storage_finished": - case "finished": - showJobResults(data); - break; - default: - //console.warn('No specific action for status ' + data.status); - showProgressBox(data.status); - recheckJobJSONStatus(); - - } -} - -/** - * - * @param data - */ -function showJobResults(data) { - //console.log('In showJobResults()'); - // hide all boxes. - $('.statusbox').hide(); - - // render the count: - $('#import-status-more-info').append($('').html(data.report_txt)); - - // render relevant data from JSON thing. - if (data.errors.length > 0) { - $('#import-status-error-txt').show(); - data.errors.forEach(function (element) { - console.error(element); - $('#import-status-errors').append($('
  • ').text(element)); - }); - } - if(data.download_config) { - $('#import-status-download').append($('').html(data.download_config_text)); - } - - // show success box. - $('.status_finished').show(); - -} - -/** - * Will refresh and get job status. - */ -function recheckJobJSONStatus() { - //console.log('In recheckJobJSONStatus()'); - if (maxLoops !== 0 && totalLoops < maxLoops && jobFailed === false) { - timeOutId = setTimeout(checkJobJSONStatus, checkNextInterval); - } - if (maxLoops !== 0) { - console.log('max: ' + maxLoops + ' current: ' + totalLoops); - } - if (jobFailed === true) { - console.error('Job has failed, will not do recheck.'); - } - totalLoops++; -} - -/** - * Start the job. - */ -function sendJobPOSTStart() { - console.log('In sendJobPOSTStart()'); - if (jobRunRoutineStarted) { - console.log('Import job already started!'); - return; - } - if (jobFailed === true) { - console.log('Job has failed, will not start again.'); - return; - } - console.log('Job was started'); - jobRunRoutineStarted = true; - $.post(jobStartUri, {_token: token}).fail(reportJobPOSTFailure).done(reportJobPOSTDone) -} - -/** - * Start the storage routine for this job. - */ -function sendJobPOSTStore() { - console.log('In sendJobPOSTStore()'); - if (jobStorageRoutineStarted) { - console.log('Store job already started!'); - return; - } - if (jobFailed === true) { - console.log('Job has failed, will not start again.'); - return; - } - console.log('Storage job has started!'); - jobStorageRoutineStarted = true; - $.post(jobStorageStartUri, {_token: token}).fail(reportJobPOSTFailure).done(reportJobPOSTDone) -} - - -/** - * Function is called when the JSON array could not be retrieved. - * - * @param xhr - * @param status - * @param error - */ -function reportJobJSONFailure(xhr, status, error) { - console.log('In reportJobJSONFailure()'); - jobFailed = true; - if (reportedError === false) { - reportedError = true; - // cancel checking again for job status: - clearTimeout(timeOutId); - - - // hide status boxes: - $('.statusbox').hide(); - - // show fatal error box: - $('.fatal_error').show(); - $('.fatal_error_txt').text('Cannot get status of current job: ' + status + ': ' + error); - } -} - -/** - * - */ -function showProgressBox(status) { - //console.log('In showProgressBox()'); - // hide fatal error box: - $('.fatal_error').hide(); - - // hide initial status box: - $('.status_initial').hide(); - - // show running box: - $('.status_running').show(); - - if (status === 'running' || status === 'ready_to_run') { - $('#import-status-txt').text(langImportRunning); - return; - } - if (status === 'storing_data' || status === 'storage_finished' || status === 'stored_data') { - $('#import-status-txt').text(langImportStoring); - return; - } - if (status === 'applying_rules' || status === 'linking_to_tag' || status === 'linked_to_tag' || status === 'rules_applied') { - $('#import-status-txt').text(langImportRules); - return; - } - - $('#import-status-txt').text('Job status: ' + status); - - -} - -/** - * Function is called when the job could not be started. - * - * @param xhr - * @param status - * @param error - */ -function reportJobPOSTFailure(xhr, status, error) { - //console.log('In reportJobPOSTFailure()'); - // cancel checking again for job status: - clearTimeout(timeOutId); - if (reportedError === false) { - reportedError = true; - // hide status boxes: - $('.statusbox').hide(); - - // show fatal error box: - $('.fatal_error').show(); - console.error('Job could not be started or crashed: ' + status + ': ' + error); - $('.fatal_error_txt').text('Job could not be started or crashed: ' + status + ': ' + error); - // show error box. - } -} - -/** - * Show error to user. - */ -function reportJobError(data) { - console.log('In reportJobError()'); - // cancel checking again for job status: - clearTimeout(timeOutId); - if (reportedError === false) { - reportedError = true; - // hide status boxes: - $('.statusbox').hide(); - // show fatal error box: - $('.fatal_error').show(); - console.error(data.report_txt); - $('.fatal_error_txt').text('Job reports error. Please start again. Apologies. Error message is: ' + data.report_txt); - } -} - -function reportJobPOSTDone(data) { - console.log('In function reportJobPOSTDone() with status "' + data.status + '"'); - if (data.status === 'NOK' && reportedError === false) { - reportedError = true; - // cancel checking again for job status: - clearTimeout(timeOutId); - - // hide status boxes: - $('.statusbox').hide(); - - // show fatal error box: - $('.fatal_error').show(); - console.error(data.message); - $('.fatal_error_txt').text('Job could not be started or crashed: ' + data.message); - - - } -} \ No newline at end of file diff --git a/resources/lang/en_US/bank.php b/resources/lang/en_US/bank.php deleted file mode 100644 index 5dd3af2232..0000000000 --- a/resources/lang/en_US/bank.php +++ /dev/null @@ -1,26 +0,0 @@ -. - */ - -declare(strict_types=1); - -return [ -]; diff --git a/resources/lang/en_US/csv.php b/resources/lang/en_US/csv.php deleted file mode 100644 index 135701aba3..0000000000 --- a/resources/lang/en_US/csv.php +++ /dev/null @@ -1,26 +0,0 @@ -. - */ - -declare(strict_types=1); - -return [ -]; diff --git a/resources/lang/en_US/demo.php b/resources/lang/en_US/demo.php index c7f4532c56..2cbff59eed 100644 --- a/resources/lang/en_US/demo.php +++ b/resources/lang/en_US/demo.php @@ -33,6 +33,5 @@ return [ 'currencies-index' => 'Firefly III supports multiple currencies. Although it defaults to the Euro it can be set to the US Dollar and many other currencies. As you can see a small selection of currencies has been included but you can add your own if you wish to. Changing the default currency will not change the currency of existing transactions however: Firefly III supports the use of multiple currencies at the same time.', 'transactions-index' => 'These expenses, deposits and transfers are not particularly imaginative. They have been generated automatically.', 'piggy-banks-index' => 'As you can see, there are three piggy banks. Use the plus and minus buttons to influence the amount of money in each piggy bank. Click the name of the piggy bank to see the administration for each piggy bank.', - 'import-index' => 'Any CSV file can be imported into Firefly III. It also supports importing data from bunq and Spectre. Other banks and financial aggregators will be implemented in the future. As a demo-user however, you can only see the "fake"-provider in action. It will generate some random transactions to show you how the process works.', 'profile-index' => 'Keep in mind that the demo site resets every four hours. Your access may be revoked at any time. This happens automatically and is not a bug.', ]; diff --git a/resources/lang/en_US/firefly.php b/resources/lang/en_US/firefly.php index cadc73fefa..80621a6e17 100644 --- a/resources/lang/en_US/firefly.php +++ b/resources/lang/en_US/firefly.php @@ -645,7 +645,7 @@ return [ 'secure_pw_should' => 'Should I check the box?', 'secure_pw_long_password' => 'Yes. Always verify your password is safe.', 'command_line_token' => 'Command line token', - 'explain_command_line_token' => 'You need this token to perform command line options, such as importing or exporting data. Without it, such sensitive commands will not work. Do not share your command line token. Nobody will ask you for this token, not even me. If you fear you lost this, or when you\'re paranoid, regenerate this token using the button.', + 'explain_command_line_token' => 'You need this token to perform command line options, such as exporting data. Without it, that sensitive command will not work. Do not share your command line token. Nobody will ask you for this token, not even me. If you fear you lost this, or when you\'re paranoid, regenerate this token using the button.', 'regenerate_command_line_token' => 'Regenerate command line token', 'token_regenerated' => 'A new command line token was generated', 'change_your_email' => 'Change your email address', @@ -684,7 +684,6 @@ return [ 'profile_try_again' => 'Something went wrong. Please try again.', // export data: - 'import_and_export_menu' => 'Import and export', 'export_data_title' => 'Export data from Firefly III', 'export_data_menu' => 'Export data', 'export_data_bc' => 'Export data from Firefly III', @@ -1500,16 +1499,6 @@ return [ 'reset_after' => 'Reset form after submission', 'errors_submission' => 'There was something wrong with your submission. Please check out the errors below.', - // Import page (general strings only) - 'import_index_title' => 'Import transactions into Firefly III', - 'import_transactions' => 'Import transactions', - 'import_tools_title' => 'Import tools', - 'tools_index_intro' => 'Several tools exist to import data into Firefly III. Check them out below. For more information, check out this page.', - 'firefly_iii_csv_importer_name' => 'Firefly III CSV importer', - 'firefly_iii_bunq_importer_name' => 'Firefly III bunq 🌈 importer', - 'firefly_iii_ynab_importer_name' => 'Firefly III YNAB importer', - 'ludo_revolut_importer_name' => 'Ludo444\'s Revolut importer', - // // sandstorm.io errors and messages: 'sandstorm_not_available' => 'This function is not available when you are using Firefly III within a Sandstorm.io environment.', diff --git a/resources/lang/en_US/form.php b/resources/lang/en_US/form.php index 518181efcd..ee3fdd6002 100644 --- a/resources/lang/en_US/form.php +++ b/resources/lang/en_US/form.php @@ -184,14 +184,11 @@ return [ 'is_demo_site' => 'Is demo site', // import - 'import_file' => 'Import file', 'configuration_file' => 'Configuration file', - 'import_file_type' => 'Import file type', 'csv_comma' => 'A comma (,)', 'csv_semicolon' => 'A semicolon (;)', 'csv_tab' => 'A tab (invisible)', 'csv_delimiter' => 'CSV field delimiter', - 'csv_import_account' => 'Default import account', 'client_id' => 'Client ID', 'app_id' => 'App ID', 'secret' => 'Secret', diff --git a/resources/lang/en_US/import.php b/resources/lang/en_US/import.php deleted file mode 100644 index 5afc66e78c..0000000000 --- a/resources/lang/en_US/import.php +++ /dev/null @@ -1,174 +0,0 @@ -. - */ - -declare(strict_types=1); - -return [ - // ALL breadcrumbs and subtitles: - 'index_breadcrumb' => 'Import data into Firefly III', - 'prerequisites_breadcrumb_fake' => 'Prerequisites for the fake import provider', - 'prerequisites_breadcrumb_spectre' => 'Prerequisites for Spectre', - 'job_configuration_breadcrumb' => 'Configuration for ":key"', - 'job_status_breadcrumb' => 'Import status for ":key"', - 'disabled_for_demo_user' => 'disabled in demo', - - // index page: - 'general_index_intro' => 'Welcome to Firefly III\'s import routine. There are a few ways of importing data into Firefly III, displayed here as buttons.', - - // notices about the CSV importer: - 'deprecate_csv_import' => 'As outlined in this Patreon post, the way Firefly III manages importing data is going to change. That means that the CSV importer will be moved to a new, separate tool. You can already beta-test this tool if you visit this GitHub repository. I would appreciate it if you would test the new importer and let me know what you think.', - 'final_csv_import' => 'As outlined in this Patreon post, the way Firefly III manages importing data is going to change. That means that this is the last version of Firefly III that will feature a CSV importer. A separated tool is available that you should try for yourself: the Firefly III CSV importer. I would appreciate it if you would test the new importer and let me know what you think.', - - // import provider strings (index): - 'button_fake' => 'Fake an import', - 'button_file' => 'Import a file', - 'button_spectre' => 'Import using Spectre', - - // prerequisites box (index) - 'need_prereq_title' => 'Import prerequisites', - 'need_prereq_intro' => 'Some import methods need your attention before they can be used. For example, they might require special API keys or application secrets. You can configure them here. The icon indicates if these prerequisites have been met.', - 'do_prereq_fake' => 'Prerequisites for the fake provider', - 'do_prereq_file' => 'Prerequisites for file imports', - 'do_prereq_spectre' => 'Prerequisites for imports using Spectre', - - // prerequisites: - 'prereq_fake_title' => 'Prerequisites for an import from the fake import provider', - 'prereq_fake_text' => 'This fake provider requires a fake API key. It must be 32 characters long. You can use this one: 123456789012345678901234567890AA', - 'prereq_spectre_title' => 'Prerequisites for an import using the Spectre API', - 'prereq_spectre_text' => 'In order to import data using the Spectre API (v4), you must provide Firefly III with two secret values. They can be found on the secrets page.', - 'prereq_spectre_pub' => 'Likewise, the Spectre API needs to know the public key you see below. Without it, it will not recognize you. Please enter this public key on your secrets page.', - 'callback_not_tls' => 'Firefly III has detected the following callback URI. It seems your server is not set up to accept TLS-connections (https). YNAB will not accept this URI. You may continue with the import (because Firefly III could be wrong) but please keep this in mind.', - // prerequisites success messages: - 'prerequisites_saved_for_fake' => 'Fake API key stored successfully!', - 'prerequisites_saved_for_spectre' => 'App ID and secret stored!', - - // job configuration: - 'job_config_apply_rules_title' => 'Job configuration - apply your rules?', - 'job_config_apply_rules_text' => 'Once the fake provider has run, your rules can be applied to the transactions. This adds time to the import.', - 'job_config_input' => 'Your input', - // job configuration for the fake provider: - 'job_config_fake_artist_title' => 'Enter album name', - 'job_config_fake_artist_text' => 'Many import routines have a few configuration steps you must go through. In the case of the fake import provider, you must answer some weird questions. In this case, enter "David Bowie" to continue.', - 'job_config_fake_song_title' => 'Enter song name', - 'job_config_fake_song_text' => 'Mention the song "Golden years" to continue with the fake import.', - 'job_config_fake_album_title' => 'Enter album name', - 'job_config_fake_album_text' => 'Some import routines require extra data halfway through the import. In the case of the fake import provider, you must answer some weird questions. Enter "Station to station" to continue.', - // job configuration form the file provider - 'job_config_file_upload_title' => 'Import setup (1/4) - Upload your file', - 'job_config_file_upload_text' => 'This routine will help you import files from your bank into Firefly III. ', - 'job_config_file_upload_help' => 'Select your file. Please make sure the file is UTF-8 encoded.', - 'job_config_file_upload_config_help' => 'If you have previously imported data into Firefly III, you may have a configuration file, which will pre-set configuration values for you. For some banks, other users have kindly provided their configuration file', - 'job_config_file_upload_type_help' => 'Select the type of file you will upload', - 'job_config_file_upload_submit' => 'Upload files', - 'import_file_type_csv' => 'CSV (comma separated values)', - 'import_file_type_ofx' => 'OFX', - 'file_not_utf8' => 'The file you have uploaded is not encoded as UTF-8 or ASCII. Firefly III cannot handle such files. Please use Notepad++ or Sublime to convert your file to UTF-8.', - 'job_config_uc_title' => 'Import setup (2/4) - Basic file setup', - 'job_config_uc_text' => 'To be able to import your file correctly, please validate the options below.', - 'job_config_uc_header_help' => 'Check this box if the first row of your CSV file are the column titles.', - 'job_config_uc_date_help' => 'Date time format in your file. Follow the format as this page indicates. The default value will parse dates that look like this: :dateExample.', - 'job_config_uc_delimiter_help' => 'Choose the field delimiter that is used in your input file. If not sure, comma is the safest option.', - 'job_config_uc_account_help' => 'If your file does NOT contain information about your asset account(s), use this dropdown to select to which account the transactions in the file belong to.', - 'job_config_uc_apply_rules_title' => 'Apply rules', - 'job_config_uc_apply_rules_text' => 'Applies your rules to every imported transaction. Note that this slows the import significantly.', - 'job_config_uc_specifics_title' => 'Bank-specific options', - 'job_config_uc_specifics_txt' => 'Some banks deliver badly formatted files. Firefly III can fix those automatically. If your bank delivers such files but it\'s not listed here, please open an issue on GitHub.', - 'job_config_uc_submit' => 'Continue', - 'invalid_import_account' => 'You have selected an invalid account to import into.', - 'import_liability_select' => 'Liability', - // job configuration for Spectre: - 'job_config_spectre_login_title' => 'Choose your login', - 'job_config_spectre_login_text' => 'Firefly III has found :count existing login(s) in your Spectre account. Which one would you like to use to import from?', - 'spectre_login_status_active' => 'Active', - 'spectre_login_status_inactive' => 'Inactive', - 'spectre_login_status_disabled' => 'Disabled', - 'spectre_login_new_login' => 'Login with another bank, or one of these banks with different credentials.', - 'job_config_spectre_accounts_title' => 'Select accounts to import from', - 'job_config_spectre_accounts_text' => 'You have selected ":name" (:country). You have :count account(s) available from this provider. Please select the Firefly III asset account(s) where the transactions from these accounts should be stored. Remember, in order to import data both the Firefly III account and the ":name"-account must have the same currency.', - 'spectre_do_not_import' => '(do not import)', - 'spectre_no_mapping' => 'It seems you have not selected any accounts to import from.', - 'imported_from_account' => 'Imported from ":account"', - 'spectre_account_with_number' => 'Account :number', - 'job_config_spectre_apply_rules' => 'Apply rules', - 'job_config_spectre_apply_rules_text' => 'By default, your rules will be applied to the transactions created during this import routine. If you do not want this to happen, deselect this checkbox.', - - // job configuration for bunq: - 'should_download_config' => 'You should download the configuration file for this job. This will make future imports way easier.', - 'share_config_file' => 'If you have imported data from a public bank, you should share your configuration file so it will be easy for other users to import their data. Sharing your configuration file will not expose your financial details.', - - // keys from "extra" array: - 'spectre_extra_key_iban' => 'IBAN', - 'spectre_extra_key_swift' => 'SWIFT', - 'spectre_extra_key_status' => 'Status', - 'spectre_extra_key_card_type' => 'Card type', - 'spectre_extra_key_account_name' => 'Account name', - 'spectre_extra_key_client_name' => 'Client name', - 'spectre_extra_key_account_number' => 'Account number', - 'spectre_extra_key_blocked_amount' => 'Blocked amount', - 'spectre_extra_key_available_amount' => 'Available amount', - 'spectre_extra_key_credit_limit' => 'Credit limit', - 'spectre_extra_key_interest_rate' => 'Interest rate', - 'spectre_extra_key_expiry_date' => 'Expiry date', - 'spectre_extra_key_open_date' => 'Open date', - 'spectre_extra_key_current_time' => 'Current time', - 'spectre_extra_key_current_date' => 'Current date', - 'spectre_extra_key_cards' => 'Cards', - 'spectre_extra_key_units' => 'Units', - 'spectre_extra_key_unit_price' => 'Unit price', - 'spectre_extra_key_transactions_count' => 'Transaction count', - - // job config for the file provider (stage: mapping): - 'job_config_map_title' => 'Import setup (4/4) - Connect import data to Firefly III data', - 'job_config_map_text' => 'In the following tables, the left value shows you information found in your uploaded file. It is your task to map this value, if possible, to a value already present in your database. Firefly will stick to this mapping. If there is no value to map to, or you do not wish to map the specific value, select nothing.', - 'job_config_map_nothing' => 'There is no data present in your file that you can map to existing values. Please press "Start the import" to continue.', - 'job_config_field_value' => 'Field value', - 'job_config_field_mapped' => 'Mapped to', - 'map_do_not_map' => '(do not map)', - 'job_config_map_submit' => 'Start the import', - - - // import status page: - 'import_with_key' => 'Import with key \':key\'', - 'status_wait_title' => 'Please hold...', - 'status_wait_text' => 'This box will disappear in a moment.', - 'status_running_title' => 'The import is running', - 'status_job_running' => 'Please wait, running the import...', - 'status_job_storing' => 'Please wait, storing data...', - 'status_job_rules' => 'Please wait, running rules...', - 'status_fatal_title' => 'Fatal error', - 'status_fatal_text' => 'The import has suffered from an error it could not recover from. Apologies!', - 'status_fatal_more' => 'This (possibly very cryptic) error message is complemented by log files, which you can find on your hard drive, or in the Docker container where you run Firefly III from.', - 'status_finished_title' => 'Import finished', - 'status_finished_text' => 'The import has finished.', - 'finished_with_errors' => 'There were some errors during the import. Please review them carefully.', - 'unknown_import_result' => 'Unknown import result', - 'result_no_transactions' => 'No transactions have been imported. Perhaps they were all duplicates is simply no transactions where present to be imported. Perhaps the log files can tell you what happened. If you import data regularly, this is normal.', - 'result_one_transaction' => 'Exactly one transaction has been imported. It is stored under tag :tag where you can inspect it further.', - 'result_many_transactions' => 'Firefly III has imported :count transactions. They are stored under tag :tag where you can inspect them further.', - - // general errors and warnings: - 'bad_job_status' => 'To access this page, your import job cannot have status ":status".', - - // error message - 'duplicate_row' => 'Row #:row (":description") could not be imported. It already exists.', - -]; diff --git a/resources/lang/en_US/list.php b/resources/lang/en_US/list.php index 91e3123e75..5f18245381 100644 --- a/resources/lang/en_US/list.php +++ b/resources/lang/en_US/list.php @@ -88,7 +88,6 @@ return [ 'attachments_count' => 'Number of attachments', 'bills_count' => 'Number of bills', 'categories_count' => 'Number of categories', - 'import_jobs_count' => 'Number of import jobs', 'budget_count' => 'Number of budgets', 'rule_and_groups_count' => 'Number of rules and rule groups', 'tags_count' => 'Number of tags', @@ -104,9 +103,6 @@ return [ 'sum_transfers' => 'Sum of transfers', 'sum_reconciliations' => 'Sum of reconciliations', 'reconcile' => 'Reconcile', - 'account_on_spectre' => 'Account (Spectre)', - 'account_on_ynab' => 'Account (YNAB)', - 'do_import' => 'Import from this account', 'sepa_ct_id' => 'SEPA End to End Identifier', 'sepa_ct_op' => 'SEPA Opposing Account Identifier', 'sepa_db' => 'SEPA Mandate Identifier', diff --git a/resources/views/v1/admin/users/show.twig b/resources/views/v1/admin/users/show.twig index 95aeea4ead..3196a5df87 100644 --- a/resources/views/v1/admin/users/show.twig +++ b/resources/views/v1/admin/users/show.twig @@ -97,10 +97,6 @@ {{ trans('list.categories_count') }} {{ information.categories }} - - {{ trans('list.import_jobs_count') }} - {{ information.import_jobs }}, {{ trans('firefly.successful_count', {count: information.import_jobs_success}) }} - {{ trans('list.budget_count') }} {{ trans_choice('firefly.budget_or_budgets', information.budgets ) }}, diff --git a/resources/views/v1/demo/import/index.twig b/resources/views/v1/demo/import/index.twig deleted file mode 100644 index 31fe3ab386..0000000000 --- a/resources/views/v1/demo/import/index.twig +++ /dev/null @@ -1 +0,0 @@ -{{ trans('demo.import-index') }} diff --git a/resources/views/v1/import/bank/form.twig b/resources/views/v1/import/bank/form.twig deleted file mode 100644 index a7c6507a01..0000000000 --- a/resources/views/v1/import/bank/form.twig +++ /dev/null @@ -1,69 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - -
    -
    -
    -

    {{ trans('bank.bank_form_title') }}

    -
    -
    -
    -
    -

    - {{ trans('bank.bank_form_text') }} -

    -
    -
    -
    -
    - - - - - - - - - - {% for remoteAccount in remoteAccounts %} - - - - - - {% endfor %} - -
    {{ 'list.account'|_ }}{{ 'list.currentBalance'|_ }}
    - - - - {{ remoteAccount.name }} - -
    {{ remoteAccount.number }} -
    - {{ remoteAccount.currency }} - {{ remoteAccount.balance }} -
    -
    -
    -
    - -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/bunq/choose-accounts.twig b/resources/views/v1/import/bunq/choose-accounts.twig deleted file mode 100644 index b43e6f3d48..0000000000 --- a/resources/views/v1/import/bunq/choose-accounts.twig +++ /dev/null @@ -1,108 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - - -
    -
    -
    -

    {{ trans('import.job_config_bunq_apply_rules') }}

    -
    -
    -
    -
    -

    - {{ trans('import.job_config_bunq_apply_rules_text') }} -

    - {{ ExpandedForm.checkbox('apply_rules', 1, true) }} -
    -
    - -
    -
    -
    - -
    -
    -
    -

    {{ trans('import.job_config_bunq_accounts_title') }}

    -
    -
    -
    -
    -

    - {{ trans('import.job_config_bunq_accounts_text') }} -

    -
    -
    -
    -
    - - - - - - - - - - {% for account in data.accounts %} - {% set currentIban = 'not-iban' %} - - - - - - - {% endfor %} - -
     {{ trans('list.account_at_bunq') }}{{ trans('list.account') }}
    - {{ account.description }} -
      - {% for alias in account.aliases %} - {% if alias.type == 'IBAN' %} -
    • {{ alias.name }}: {{ alias.value }}{% set currentIban = alias.value %}
    • - {% endif %} - {% endfor %} - {% if account.status != 'ACTIVE' %} -
    • {{ trans('import.bunq_account_status_'~account.status|escape) }}
    • - {% endif %} - {% if account.type == 'MonetaryAccountSavings' %} -
    • {{ trans('import.bunq_savings_goal', {'amount': account.savingsGoal.currency ~' '~account.savingsGoal.value,'percentage' : account.savingsGoal.percentage}) }}
    • - {% endif %} -
    -
    - -
    -
    -
    - -
    -
    - -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/bunq/prerequisites.twig b/resources/views/v1/import/bunq/prerequisites.twig deleted file mode 100644 index c6bc3f38a3..0000000000 --- a/resources/views/v1/import/bunq/prerequisites.twig +++ /dev/null @@ -1,57 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - -
    -
    -
    -

    {{ trans('import.prereq_bunq_title') }}

    -
    -
    -
    -
    -

    - {{ trans('import.prereq_bunq_text') }} -

    -
    -
    - -
    -
    - {{ ExpandedForm.text('api_key', api_key) }} -
    -
    - -
    -
    -

    - {{ trans('import.prereq_bunq_ip')|raw }} -

    -
    -
    - -
    -
    - {{ ExpandedForm.text('external_ip', external_ip) }} -
    -
    -
    - -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/fake/apply-rules.twig b/resources/views/v1/import/fake/apply-rules.twig deleted file mode 100644 index 922ce43bd0..0000000000 --- a/resources/views/v1/import/fake/apply-rules.twig +++ /dev/null @@ -1,56 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    -
    -
    -

    {{ trans('import.job_config_apply_rules_title') }}

    -
    -
    -

    - {{ trans('import.job_config_apply_rules_text') }} -

    -
    -
    - -
    -
    - -
    - -
    -
    -
    -
    -

    - {{ trans('import.job_config_input') }} -

    -
    -
    - {{ ExpandedForm.select('apply_rules', data.rulesOptions) }} -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/fake/enter-album.twig b/resources/views/v1/import/fake/enter-album.twig deleted file mode 100644 index 01ee24a3b3..0000000000 --- a/resources/views/v1/import/fake/enter-album.twig +++ /dev/null @@ -1,53 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    -
    -
    -

    {{ trans('import.job_config_fake_album_title') }}

    -
    -
    -

    - {{ trans('import.job_config_fake_album_text') }} -

    -
    -
    - -
    -
    - -
    - -
    -
    -
    -
    -

    {{ trans('import.job_config_input') }}

    -
    -
    - {{ ExpandedForm.text('album') }} -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/fake/enter-artist.twig b/resources/views/v1/import/fake/enter-artist.twig deleted file mode 100644 index a422a31552..0000000000 --- a/resources/views/v1/import/fake/enter-artist.twig +++ /dev/null @@ -1,53 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    -
    -
    -

    {{ trans('import.job_config_fake_artist_title') }}

    -
    -
    -

    - {{ trans('import.job_config_fake_artist_text') }} -

    -
    -
    - -
    -
    - -
    - -
    -
    -
    -
    -

    {{ trans('import.job_config_input') }}

    -
    -
    - {{ ExpandedForm.text('artist') }} -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/fake/enter-song.twig b/resources/views/v1/import/fake/enter-song.twig deleted file mode 100644 index dc1de31a2b..0000000000 --- a/resources/views/v1/import/fake/enter-song.twig +++ /dev/null @@ -1,53 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    -
    -
    -

    {{ trans('import.job_config_fake_song_title') }}

    -
    -
    -

    - {{ trans('import.job_config_fake_song_text') }} -

    -
    -
    - -
    -
    - -
    - -
    -
    -
    -
    -

    {{ trans('import.job_config_input') }}

    -
    -
    - {{ ExpandedForm.text('song') }} -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/fake/prerequisites.twig b/resources/views/v1/import/fake/prerequisites.twig deleted file mode 100644 index 39af64e195..0000000000 --- a/resources/views/v1/import/fake/prerequisites.twig +++ /dev/null @@ -1,43 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - -
    -
    -
    -

    {{ trans('import.prereq_fake_title') }}

    -
    -
    -
    -
    -

    - {{ trans('import.prereq_fake_text') }} -

    -
    -
    - -
    -
    - {{ ExpandedForm.text('api_key', api_key) }} -
    -
    -
    - -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/file/configure-upload.twig b/resources/views/v1/import/file/configure-upload.twig deleted file mode 100644 index 63fefe4a3f..0000000000 --- a/resources/views/v1/import/file/configure-upload.twig +++ /dev/null @@ -1,115 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render(Route.getCurrentRoute.getName, importJob) }} -{% endblock %} - -{% block content %} - -
    -
    -
    -
    -

    {{ trans('import.job_config_uc_title') }}

    -
    -
    -

    - {{ trans('import.job_config_uc_text') }} -

    -
    -
    - -
    -
    - -
    - - -
    -
    -
    -
    -

    {{ trans('import.job_config_input') }}

    -
    -
    -
    -
    -

    {{ 'mandatoryFields'|_ }}

    - {{ ExpandedForm.checkbox('has_headers',1,importJob.configuration['has-headers'],{helpText: trans('import.job_config_uc_header_help')}) }} - {{ ExpandedForm.text('date_format',importJob.configuration['date-format'],{helpText: trans('import.job_config_uc_date_help', {dateExample: phpdate('Ymd')}) }) }} - {{ ExpandedForm.select('csv_delimiter', data.delimiters, importJob.configuration['delimiter'], {helpText: trans('import.job_config_uc_delimiter_help') } ) }} - {{ AccountForm.activeAssetAccountList('csv_import_account', importJob.configuration['import-account'], {helpText: trans('import.job_config_uc_account_help')}) }} - -

    {{ 'optionalFields'|_ }}

    -
    - - -
    -
    -
    -
    -
    -
    - - -
    -

    - {{ trans('import.job_config_uc_specifics_txt') }} -

    - - -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    - -

    -
     
     
     
     
     
     
    -

    - - - -{% endblock %} -{% block styles %} - -{% endblock %} -{% block scripts %} - - - -{% endblock %} diff --git a/resources/views/v1/import/file/map.twig b/resources/views/v1/import/file/map.twig deleted file mode 100644 index 3f2035d263..0000000000 --- a/resources/views/v1/import/file/map.twig +++ /dev/null @@ -1,86 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render(Route.getCurrentRoute.getName, importJob) }} -{% endblock %} - -{% block content %} - - -
    -
    -
    -
    -

    {{ trans('import.job_config_map_title') }}

    -
    -
    -

    - {{ trans('import.job_config_map_text') }} -

    - {% if data|length == 0 %} -

    - {{ trans('import.job_config_map_nothing') }} -

    - {% endif %} -
    -
    - -
    -
    -
    - - - - {% for index, field in data %} -
    -
    -
    -
    -

    {{ trans('import.column_'~field.name) }}

    -
    -
    - - - - - - - - - {% for option in field.values %} - - - - - {% endfor %} - -
    {{ trans('import.job_config_field_value') }}{{ trans('import.job_config_field_mapped') }}
    - {{ option }} - - {{ Form.select('mapping['~index~']['~option~']', - field.options, - importJob.configuration['column-mapping-config'][index][option], {class: 'form-control'}) }} -
    -
    -
    -
    -
    - {% endfor %} - - -
    -
    -
    -
    - -
    -
    -
    -
    - -
    - - -{% endblock %} diff --git a/resources/views/v1/import/file/new.twig b/resources/views/v1/import/file/new.twig deleted file mode 100644 index 758c9a6a65..0000000000 --- a/resources/views/v1/import/file/new.twig +++ /dev/null @@ -1,60 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    -
    -
    -

    {{ trans('import.job_config_file_upload_title') }}

    -
    -
    -

    - {{ trans('import.job_config_file_upload_text') }} -

    -

    - {{ trans('import.final_csv_import')|raw }} -

    -
    -
    - -
    -
    - -
    - - - -
    -
    -
    -
    -

    {{ trans('import.job_config_input') }}

    -
    -
    - {{ ExpandedForm.file('import_file', {helpText: trans('import.job_config_file_upload_help')}) }} - {{ ExpandedForm.file('configuration_file', {helpText: trans('import.job_config_file_upload_config_help')|raw}) }} - {{ ExpandedForm.select('import_file_type', data.file_types, data.default_type, {'helpText' : trans('import.job_config_file_upload_type_help')}) }} -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/file/roles.twig b/resources/views/v1/import/file/roles.twig deleted file mode 100644 index a983dc1b35..0000000000 --- a/resources/views/v1/import/file/roles.twig +++ /dev/null @@ -1,100 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render(Route.getCurrentRoute.getName, importJob) }} -{% endblock %} - -{% block content %} - -
    -
    -
    -
    -

    {{ trans('import.job_config_roles_title') }}

    -
    -
    -

    - {{ trans('import.job_config_roles_text') }} -

    -
    -
    - -
    -
    -
    - - -
    -
    -
    -
    -

    {{ trans('import.job_config_input') }}

    -
    -
    - - - - - - - - - - {% for i in 0..(data.total -1) %} - - - - - - - - {% endfor %} - - -
    {{ trans('import.job_config_roles_column_name') }}{{ trans('import.job_config_roles_column_example') }}{{ trans('import.job_config_roles_column_role') }}{{ trans('import.job_config_roles_do_map_value') }}
    - {% if data.headers[i] == '' %} - {{ trans('import.job_config_roles_colum_count') }} #{{ loop.index }} - {% else %} - {{ data.headers[i] }} - {% endif %} - - {% if data.examples[i]|length == 0 %} - {{ trans('import.job_config_roles_no_example') }} - {% else %} - {% for example in data.examples[i] %} - {{ example }}
    - {% endfor %} - {% endif %} - -
    - {{ Form.select(('role['~loop.index0~']'), - data.roles, - importJob.configuration['column-roles'][loop.index0], - {class: 'form-control'}) }} - - {{ Form.checkbox(('map['~loop.index0~']'),1, - importJob.configuration['column-do-mapping'][loop.index0] - - ) }} -
    - -
    -
    -
    -
    - -
    -
    -
    -
    - -
    -
    -
    -
    -
    - - -{% endblock %} diff --git a/resources/views/v1/import/fints/choose_account.twig b/resources/views/v1/import/fints/choose_account.twig deleted file mode 100644 index f658988c8b..0000000000 --- a/resources/views/v1/import/fints/choose_account.twig +++ /dev/null @@ -1,44 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    - - -
    -
    -
    -
    -

    {{ trans('import.job_config_input') }}

    -
    -
    - {{ ExpandedForm.select('fints_account', data.fints_accounts, data.fints_account, {helpText: trans('import.job_config_fints_account_help'), required: true}) }} -
    -
    - {{ ExpandedForm.select('local_account', data.local_accounts, data.local_account, {helpText: trans('import.job_config_local_account_help'), required: true}) }} -
    -
    - {{ ExpandedForm.date('from_date', data.from_date, {required: true}) }} -
    -
    - {{ ExpandedForm.date('to_date', data.to_date, {required: true}) }} -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -{% endblock %} diff --git a/resources/views/v1/import/fints/new.twig b/resources/views/v1/import/fints/new.twig deleted file mode 100644 index a5858e7be8..0000000000 --- a/resources/views/v1/import/fints/new.twig +++ /dev/null @@ -1,40 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    - - -
    -
    -
    -
    -

    {{ trans('import.job_config_input') }}

    -
    -
    - {{ ExpandedForm.text('fints_url', data.fints_url, {helpText: trans('import.job_config_fints_url_help'), required: true}) }} - {{ ExpandedForm.text('fints_port', data.fints_port, {helpText: trans('import.job_config_fints_port_help'), required: true}) }} - {{ ExpandedForm.text('fints_bank_code', data.fints_bank_code, {required: true}) }} - {{ ExpandedForm.text('fints_username', data.fints_username, {helpText: trans('import.job_config_fints_username_help'), required: false}) }} - {{ ExpandedForm.password('fints_password', {required: true}) }} - {{ ExpandedForm.checkbox('apply_rules', 1, true) }} -
    -
    -
    -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    -{% endblock %} diff --git a/resources/views/v1/import/index.twig b/resources/views/v1/import/index.twig deleted file mode 100644 index da24b04a3e..0000000000 --- a/resources/views/v1/import/index.twig +++ /dev/null @@ -1,101 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    -
    -
    -

    {{ trans('firefly.import_index_title') }}

    -
    -
    -

    - {{ trans('import.general_index_intro') }} -

    -

    - {{ trans('import.final_csv_import')|raw }} -

    -
    - {% for name, provider in providers %} - {# button for each import thing: #} -
    - {% if not provider.allowed_for_demo and isDemoUser %} - {{ trans(('import.button_'~name)) }}
    - {{ trans(('import.button_'~name)) }}
    - ({{ trans('import.disabled_for_demo_user') }}) - {% else %} - - {{ trans(('import.button_'~name)) }}
    - {{ trans(('import.button_'~name)) }} -
    - {% endif %} -
    - - {% endfor %} -
    -
    -
    -
    -
    -
    -
    -

    {{ trans('firefly.import_tools_title') }}

    -
    - -
    -
    -
    - -
    -
    -
    -
    -

    {{ trans('import.need_prereq_title') }}

    -
    -
    -

    - {{ trans('import.need_prereq_intro') }} -

    -
      - {% for name, provider in providers %} - {% if provider.has_prereq %} -
    • - {% if provider.prereq_complete %} - - {% else %} - - {% endif %} - {{ trans('import.do_prereq_'~name) }} -
    • - {% endif %} - {% endfor %} -
    -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/spectre/accounts.twig b/resources/views/v1/import/spectre/accounts.twig deleted file mode 100644 index 4fbf0ba248..0000000000 --- a/resources/views/v1/import/spectre/accounts.twig +++ /dev/null @@ -1,107 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - - -
    -
    -
    -

    {{ trans('import.job_config_spectre_apply_rules') }}

    -
    -
    -
    -
    -

    - {{ trans('import.job_config_spectre_apply_rules_text') }} -

    - {{ ExpandedForm.checkbox('apply_rules', 1, true) }} -
    -
    - -
    -
    -
    - -
    -
    -
    -

    {{ trans('import.job_config_spectre_accounts_title') }}

    -
    -
    -
    -
    -

    - {{ trans('import.job_config_spectre_accounts_text', {count: data.accounts|length,country: data.login.getCountryCode(),name: data.login.getProviderName()}) }} -

    -
    -
    -
    -
    - - - - - - - - - {% for account in data.accounts %} - - - - - - {% endfor %} - -
    {{ trans('list.account_on_spectre') }}{{ trans('list.account') }}
    - {{ account.getNature()|capitalize }} "{{ account.getName() }}" - ({{ formatAmountBySymbol(account.getBalance(), account.getCurrencyCode()~' ') }})
    - {% set currentIban = '' %} - {% for name, value in account.getExtra() %} - {% if not value is iterable and name != 'sort_code' and name !='current_date' and name != 'available_amount' and name !='current_time' and name != 'last_posted_transaction_id' %} - {{ trans('import.spectre_extra_key_'~name) }}: {{ value }}
    - {% endif %} - {% if name == 'available_amount' %} - {{ trans('import.spectre_extra_key_'~name) }}: {{ formatAmountBySymbol(value, account.getCurrencyCode()~' ') }} - {% endif %} - {% if name == 'iban' %} - {% set currentIban = value %} - {% endif %} - {% endfor %} -
    - -
    - - -
    -
    - -
    -
    - -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/spectre/choose-login.twig b/resources/views/v1/import/spectre/choose-login.twig deleted file mode 100644 index 61394d0402..0000000000 --- a/resources/views/v1/import/spectre/choose-login.twig +++ /dev/null @@ -1,87 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - -
    -
    -
    -

    {{ trans('import.job_config_spectre_login_title') }}

    -
    -
    -
    -
    -

    - {{ trans('import.job_config_spectre_login_text', {count: data.logins|length}) }} -

    -
    -
    - -
    -
    - - - - - - - - - - - {% for login in data.logins %} - - - - - - - - {% endfor %} - - - - - -
     {{ trans('list.spectre_bank') }}{{ trans('list.spectre_last_use') }}{{ trans('list.spectre_status') }}
    - - - - - {{ login.getLastSuccessAt().formatLocalized(monthAndDayFormat) }}
    - {{ login.getUpdatedAt().format("Y-m-d H:i:s") }}
    -
    - {{ trans('import.spectre_login_status_'~login.getStatus()) }} -
    - - - -
    -
    -
    - -
    -
    - -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/spectre/prerequisites.twig b/resources/views/v1/import/spectre/prerequisites.twig deleted file mode 100644 index 1a1909bc0a..0000000000 --- a/resources/views/v1/import/spectre/prerequisites.twig +++ /dev/null @@ -1,57 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - -
    -
    -
    -

    {{ trans('import.prereq_spectre_title') }}

    -
    -
    -
    -
    -

    - {{ trans('import.prereq_spectre_text')|raw }} -

    -
    -
    - -
    -
    - {{ ExpandedForm.text('app_id', app_id) }} - {{ ExpandedForm.text('secret', secret) }} -
    -
    -
    -
    -

    {{ trans('import.prereq_spectre_pub')|raw }}

    -
    - - -
    - -
    -
    -
    -
    - -
    -
    - -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/spectre/redirect.twig b/resources/views/v1/import/spectre/redirect.twig deleted file mode 100644 index 22c838e691..0000000000 --- a/resources/views/v1/import/spectre/redirect.twig +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Page Redirection - - -If you are not redirected automatically, follow this link to Spectre.. - - diff --git a/resources/views/v1/import/status.twig b/resources/views/v1/import/status.twig deleted file mode 100644 index 7c9b0fbf91..0000000000 --- a/resources/views/v1/import/status.twig +++ /dev/null @@ -1,196 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} - - {# Initial display. Will refresh (and disappear almost immediately. #} -
    -
    -
    -
    -

    {{ trans('import.status_wait_title') }}

    -
    -
    -

    - {{ trans('import.status_wait_text') }} -

    -
    -
    -
    -
    - - {# Fatal error display. Will be shown (duh) when something goes horribly wrong. #} - - {# box to show when job is running ... #} - - - {# Box for when the job is ready to start - - #} - - {# Box for when the job is running! - - #} - {# displays the finished status of the import #} - - {# box to show error information. #} - {# - - #} - -{% endblock %} -{% block scripts %} - - -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/ynab/accounts.twig b/resources/views/v1/import/ynab/accounts.twig deleted file mode 100644 index d4e3b8a718..0000000000 --- a/resources/views/v1/import/ynab/accounts.twig +++ /dev/null @@ -1,100 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - - -
    -
    -
    -

    {{ trans('import.job_config_ynab_apply_rules') }}

    -
    -
    -
    -
    -

    - {{ trans('import.job_config_ynab_apply_rules_text') }} -

    - {{ ExpandedForm.checkbox('apply_rules', 1, true) }} -
    -
    - -
    -
    -
    - -
    -
    -
    -

    {{ trans('import.job_config_ynab_accounts_title') }}

    -
    -
    -
    -
    -

    - {{ trans('import.job_config_ynab_accounts_text', {count: data.accounts|length}) }} -

    -
    -
    -
    -
    - - - - - - - - - {% for account in data.ynab_accounts %} - - - - - - {% endfor %} - -
    {{ trans('list.account_on_ynab') }}{{ trans('list.account') }}
    - {{ account.name }} ({{ trans('import.ynab_account_type_'~account.type) }}) - {% if account.closed %} -
    {{ trans('import.ynab_account_closed') }} - {% endif %} - {% if account.deleted %} -
    {{ trans('import.ynab_account_deleted') }} - {% endif %} -
    - -
    - - -
    -
    - -
    -
    - -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/ynab/prerequisites.twig b/resources/views/v1/import/ynab/prerequisites.twig deleted file mode 100644 index c7faab048a..0000000000 --- a/resources/views/v1/import/ynab/prerequisites.twig +++ /dev/null @@ -1,69 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - -
    -
    -
    -

    {{ trans('import.prereq_ynab_title') }}

    -
    -
    -
    -
    -

    - {{ trans('import.prereq_ynab_text')|raw }} -

    - {% if not is_https %} -

    - {{ trans('import.callback_not_tls') }} -

    - {{ callback_uri }} -

    - {% endif %} - {% if is_https %} -

    - {{ trans('import.prereq_ynab_redirect')|raw }} -

    - {{ callback_uri }} -

    - {% endif %} -
    -
    - -
    -
    - {{ ExpandedForm.text('client_id', client_id) }} -
    -
    -
    -
    - {{ ExpandedForm.text('client_secret', client_secret) }} -
    -
    -
    - -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/import/ynab/redirect.twig b/resources/views/v1/import/ynab/redirect.twig deleted file mode 100644 index f241a7aa22..0000000000 --- a/resources/views/v1/import/ynab/redirect.twig +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Page Redirection - - -If you are not redirected automatically, follow this link to YNAB.. - - diff --git a/resources/views/v1/import/ynab/select-budgets.twig b/resources/views/v1/import/ynab/select-budgets.twig deleted file mode 100644 index 1c6c37b8fd..0000000000 --- a/resources/views/v1/import/ynab/select-budgets.twig +++ /dev/null @@ -1,58 +0,0 @@ -{% extends "./layout/default" %} - -{% block breadcrumbs %} - {{ Breadcrumbs.render }} -{% endblock %} -{% block content %} -
    -
    - - -
    -
    -
    -

    {{ trans('import.job_config_ynab_select_budgets') }}

    -
    -
    -
    -
    -

    - {{ trans('import.job_config_ynab_select_budgets_text', {count: data.total}) }} -

    - {% if data.available|length == 0 %} -

    - {{ trans('import.job_config_ynab_no_budgets') }} -

    - {% else %} - {{ ExpandedForm.select('budget_id', data.available) }} - {% endif %} - - {% if data.not_available|length > 0 %} -

    - {{ trans('import.job_config_ynab_bad_currency') }} -

    -
      - {% for budget in data.not_available %} -
    • {{ budget }}
    • - {% endfor %} -
    - {% endif %} -
    -
    - -
    -
    -
    -
    -
    -{% endblock %} -{% block scripts %} -{% endblock %} -{% block styles %} -{% endblock %} diff --git a/resources/views/v1/partials/menu-sidebar.twig b/resources/views/v1/partials/menu-sidebar.twig index b4074ad486..4553632771 100644 --- a/resources/views/v1/partials/menu-sidebar.twig +++ b/resources/views/v1/partials/menu-sidebar.twig @@ -158,32 +158,15 @@
  • -
  • - - - {{ 'tools'|_ }} - - - - - -
  • + {% if config('firefly.feature_flags.export') %} +
  • + + + {{ 'export_data_menu'|_ }} + +
  • + {% endif %}
  • diff --git a/routes/api.php b/routes/api.php index a18c9d34dd..66199d2501 100644 --- a/routes/api.php +++ b/routes/api.php @@ -212,17 +212,6 @@ Route::group( } ); -Route::group( - ['namespace' => 'FireflyIII\Api\V1\Controllers', 'prefix' => 'import', - 'as' => 'api.v1.import.',], - static function () { - - // Transaction Links API routes: - Route::get('list', ['uses' => 'ImportController@listAll', 'as' => 'list']); - Route::get('{importJob}', ['uses' => 'ImportController@show', 'as' => 'show']); - Route::get('{importJob}/transactions', ['uses' => 'ImportController@transactions', 'as' => 'transactions']); - } -); Route::group( ['namespace' => 'FireflyIII\Api\V1\Controllers', 'prefix' => 'link_types', 'as' => 'api.v1.link_types.',], diff --git a/routes/breadcrumbs.php b/routes/breadcrumbs.php index 2253421d53..e1ed8b8b7c 100644 --- a/routes/breadcrumbs.php +++ b/routes/breadcrumbs.php @@ -29,7 +29,6 @@ use FireflyIII\Models\Bill; use FireflyIII\Models\Budget; use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\Category; -use FireflyIII\Models\ImportJob; use FireflyIII\Models\LinkType; use FireflyIII\Models\PiggyBank; use FireflyIII\Models\Recurrence; @@ -645,39 +644,6 @@ try { } ); - // IMPORT - Breadcrumbs::register( - 'import.index', - static function (BreadcrumbsGenerator $breadcrumbs) { - $breadcrumbs->parent('home'); - $breadcrumbs->push(trans('firefly.import_index_title'), route('import.index')); - } - ); - - Breadcrumbs::register( - 'import.prerequisites.index', - static function (BreadcrumbsGenerator $breadcrumbs, string $importProvider) { - $breadcrumbs->parent('import.index'); - $breadcrumbs->push(trans('import.prerequisites_breadcrumb_' . $importProvider), route('import.prerequisites.index', [$importProvider])); - } - ); - - Breadcrumbs::register( - 'import.job.configuration.index', - static function (BreadcrumbsGenerator $breadcrumbs, ImportJob $job) { - $breadcrumbs->parent('import.index'); - $breadcrumbs->push(trans('import.job_configuration_breadcrumb', ['key' => $job->key]), route('import.job.configuration.index', [$job->key])); - } - ); - - Breadcrumbs::register( - 'import.job.status.index', - static function (BreadcrumbsGenerator $breadcrumbs, ImportJob $job) { - $breadcrumbs->parent('import.index'); - $breadcrumbs->push(trans('import.job_status_breadcrumb', ['key' => $job->key]), route('import.job.status.index', [$job->key])); - } - ); - // PREFERENCES Breadcrumbs::register( 'preferences.index', diff --git a/routes/web.php b/routes/web.php index 2c1eed8b34..deae53554a 100644 --- a/routes/web.php +++ b/routes/web.php @@ -546,42 +546,6 @@ Route::group( Route::get('export', ['uses' => 'Export\IndexController@export', 'as' => 'export']); } ); -/** - * Import Controller. - */ -Route::group( - ['middleware' => 'user-full-auth', 'namespace' => 'FireflyIII\Http\Controllers', 'prefix' => 'import', 'as' => 'import.'], - static function () { - - // index - Route::get('', ['uses' => 'Import\IndexController@index', 'as' => 'index']); - - // create new job - Route::get('create/{import_provider}', ['uses' => 'Import\IndexController@create', 'as' => 'create']); - - // set global prerequisites for an import source, possible with a job already attached. - Route::get('prerequisites/{import_provider}/{importJob?}', ['uses' => 'Import\PrerequisitesController@index', 'as' => 'prerequisites.index']); - Route::post('prerequisites/{import_provider}/{importJob?}', ['uses' => 'Import\PrerequisitesController@post', 'as' => 'prerequisites.post']); - - // configure a job: - Route::get('job/configuration/{importJob}', ['uses' => 'Import\JobConfigurationController@index', 'as' => 'job.configuration.index']); - Route::post('job/configuration/{importJob}', ['uses' => 'Import\JobConfigurationController@post', 'as' => 'job.configuration.post']); - - // get status of a job. This is also the landing page of a job after job config is complete. - Route::get('job/status/{importJob}', ['uses' => 'Import\JobStatusController@index', 'as' => 'job.status.index']); - Route::get('job/json/{importJob}', ['uses' => 'Import\JobStatusController@json', 'as' => 'job.status.json']); - - // start the job! - Route::any('job/start/{importJob}', ['uses' => 'Import\JobStatusController@start', 'as' => 'job.start']); - Route::any('job/store/{importJob}', ['uses' => 'Import\JobStatusController@store', 'as' => 'job.store']); - - // download config: - Route::get('download/{importJob}', ['uses' => 'Import\IndexController@download', 'as' => 'job.download']); - - // callback URI for YNAB OAuth. Sadly, needs a custom solution. - Route::get('ynab-callback', ['uses' => 'Import\CallbackController@ynab', 'as' => 'callback.ynab']); - } -); /** * Help Controller. diff --git a/tests/Feature/Controllers/Admin/UserControllerTest.php b/tests/Feature/Controllers/Admin/UserControllerTest.php index 3248765b33..e82302554e 100644 --- a/tests/Feature/Controllers/Admin/UserControllerTest.php +++ b/tests/Feature/Controllers/Admin/UserControllerTest.php @@ -128,7 +128,6 @@ class UserControllerTest extends TestCase $repository->shouldReceive('getUserData')->andReturn( [ 'export_jobs_success' => 0, - 'import_jobs_success' => 0, 'attachments_size' => 0, ] ); diff --git a/tests/TestCase.php b/tests/TestCase.php index 057517b80c..5b926b55d0 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -39,7 +39,6 @@ use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\Category; use FireflyIII\Models\Configuration; use FireflyIII\Models\CurrencyExchangeRate; -use FireflyIII\Models\ImportJob; use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBankEvent; use FireflyIII\Models\Preference; @@ -52,7 +51,6 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournalLink; use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; -use FireflyIII\Transformers\TransactionTransformer; use FireflyIII\User; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; use Log; @@ -72,21 +70,6 @@ use RuntimeException; abstract class TestCase extends BaseTestCase { - /** - * @return ImportJob - */ - public function getRandomPiggyBankEvent(): PiggyBankEvent - { - return PiggyBankEvent::inRandomOrder()->first(); - } - - /** - * @return ImportJob - */ - public function getRandomImportJob(): ImportJob - { - return $this->user()->importJobs()->inRandomOrder()->first(); - } /** * @return Recurrence */ diff --git a/tests/Unit/Middleware/BinderTest.php b/tests/Unit/Middleware/BinderTest.php index 458581eced..ca364a9233 100644 --- a/tests/Unit/Middleware/BinderTest.php +++ b/tests/Unit/Middleware/BinderTest.php @@ -28,11 +28,6 @@ use Carbon\Carbon; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Fiscal\FiscalHelperInterface; use FireflyIII\Http\Middleware\Binder; -use FireflyIII\Import\Prerequisites\BunqPrerequisites; -use FireflyIII\Import\Prerequisites\FakePrerequisites; -use FireflyIII\Import\Prerequisites\PrerequisitesInterface; -use FireflyIII\Import\Prerequisites\SpectrePrerequisites; -use FireflyIII\Import\Prerequisites\YnabPrerequisites; use FireflyIII\Models\AccountType; use FireflyIII\Models\AvailableBudget; use FireflyIII\Models\Preference; @@ -950,59 +945,6 @@ class BinderTest extends TestCase $this->assertEquals(Response::HTTP_NOT_FOUND, $response->getStatusCode()); } - /** - * @covers \FireflyIII\Http\Middleware\Binder - * @covers \FireflyIII\Models\ImportJob - */ - public function testImportJob(): void - { - Log::info(sprintf('Now in test %s.', __METHOD__)); - Route::middleware(Binder::class)->any( - '/_test/binder/{importJob}', function () { - return 'OK'; - } - ); - - $this->be($this->user()); - $response = $this->get('/_test/binder/testImport'); - $this->assertEquals(Response::HTTP_OK, $response->getStatusCode()); - } - - /** - * @covers \FireflyIII\Http\Middleware\Binder - * @covers \FireflyIII\Models\ImportJob - */ - public function testImportJobNotFound(): void - { - Log::info(sprintf('Now in test %s.', __METHOD__)); - Route::middleware(Binder::class)->any( - '/_test/binder/{importJob}', function () { - return 'OK'; - } - ); - - $this->be($this->user()); - $response = $this->get('/_test/binder/0'); - $this->assertEquals(Response::HTTP_NOT_FOUND, $response->getStatusCode()); - } - - /** - * @covers \FireflyIII\Http\Middleware\Binder - * @covers \FireflyIII\Models\ImportJob - */ - public function testImportJobNotLoggedIn(): void - { - Log::info(sprintf('Now in test %s.', __METHOD__)); - Route::middleware(Binder::class)->any( - '/_test/binder/{importJob}', function () { - return 'OK'; - } - ); - - $response = $this->get('/_test/binder/testImport'); - $this->assertEquals(Response::HTTP_NOT_FOUND, $response->getStatusCode()); - } - /** * @covers \FireflyIII\Http\Middleware\Binder * @covers \FireflyIII\Support\Binder\JournalList diff --git a/tests/Unit/Rules/IsValidAttachmentModelTest.php b/tests/Unit/Rules/IsValidAttachmentModelTest.php index 6f32da8457..29a2fb1a99 100644 --- a/tests/Unit/Rules/IsValidAttachmentModelTest.php +++ b/tests/Unit/Rules/IsValidAttachmentModelTest.php @@ -25,11 +25,9 @@ namespace Tests\Unit\Rules; use FireflyIII\Models\Bill; -use FireflyIII\Models\ImportJob; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Bill\BillRepositoryInterface; -use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; use FireflyIII\Repositories\Journal\JournalAPIRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Rules\IsValidAttachmentModel; @@ -71,24 +69,6 @@ class IsValidAttachmentModelTest extends TestCase $this->assertTrue($engine->passes($attribute, $value)); } - /** - * @covers \FireflyIII\Rules\IsValidAttachmentModel - */ - public function testImportJob(): void - { - $job = $this->getRandomImportJob(); - $jobRepos = $this->mock(ImportJobRepositoryInterface::class); - - $jobRepos->shouldReceive('setUser')->atLeast()->once(); - $jobRepos->shouldReceive('find')->atLeast()->once()->withArgs([$job->id])->andReturn($job); - - $value = $job->id; - $attribute = 'not-important'; - $this->be($this->user()); - $engine = new IsValidAttachmentModel(ImportJob::class); - $this->assertTrue($engine->passes($attribute, $value)); - } - /** * @covers \FireflyIII\Rules\IsValidAttachmentModel */ diff --git a/tests/Unit/Transformers/ImportJobTransformerTest.php b/tests/Unit/Transformers/ImportJobTransformerTest.php deleted file mode 100644 index 1536297e9f..0000000000 --- a/tests/Unit/Transformers/ImportJobTransformerTest.php +++ /dev/null @@ -1,76 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace Tests\Unit\Transformers; - - -use FireflyIII\Models\ImportJob; -use FireflyIII\Transformers\ImportJobTransformer; -use Log; -use Symfony\Component\HttpFoundation\ParameterBag; -use Tests\TestCase; - -/** - * - * Class ImportJobTransformerTest - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - * @SuppressWarnings(PHPMD.TooManyPublicMethods) - */ -class ImportJobTransformerTest extends TestCase -{ - /** - * - */ - public function setUp(): void - { - parent::setUp(); - Log::info(sprintf('Now in %s.', get_class($this))); - } - - /** - * Basic coverage - * - * @covers \FireflyIII\Transformers\ImportJobTransformer - */ - public function testBasic(): void - { - - $job = ImportJob::first(); - $job->tag_id = 1; - $parameters = new ParameterBag; - $transformer = app(ImportJobTransformer::class); - $transformer->setParameters($parameters); - - $result = $transformer->transform($job); - - $this->assertEquals($job->key, $result['key']); - $this->assertEquals($job->tag_id, $result['tag_id']); - $this->assertEquals(json_encode($job->configuration), $result['configuration']); - $this->assertEquals(json_encode($job->extended_status), $result['extended_status']); - $this->assertEquals(json_encode($job->transactions), $result['transactions']); - $this->assertEquals(json_encode($job->errors), $result['errors']); - - - } -}