Remodel seeds and factories.

This commit is contained in:
James Cole 2020-11-02 06:20:49 +01:00
parent 52385ae980
commit d6c7ccf62d
No known key found for this signature in database
GPG Key ID: B5669F9493CDE38D
22 changed files with 380 additions and 200 deletions

View File

@ -27,6 +27,7 @@ use DB;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
use Log;
use stdClass;
/**
@ -55,6 +56,7 @@ class FixUnevenAmount extends Command
*/
public function handle(): int
{
Log::debug(sprintf('Now in %s', __METHOD__));
$start = microtime(true);
$count = 0;
// get invalid journals
@ -64,8 +66,11 @@ class FixUnevenAmount extends Command
->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')]);
/** @var stdClass $entry */
foreach ($journals as $entry) {
if (0 !== bccomp((string) $entry->the_sum, '0')) {
$this->fixJournal((int) $entry->transaction_journal_id);
if (0 !== bccomp((string)$entry->the_sum, '0')) {
$message = sprintf('Sum of journal #%d is %s instead of zero.', $entry->transaction_journal_id, $entry->the_sum);
$this->warn($message);
Log::warning($message);
$this->fixJournal((int)$entry->transaction_journal_id);
$count++;
}
}
@ -106,7 +111,7 @@ class FixUnevenAmount extends Command
return;
}
$amount = bcmul('-1', (string) $source->amount);
$amount = bcmul('-1', (string)$source->amount);
// fix amount of destination:
/** @var Transaction $destination */

View File

@ -61,39 +61,46 @@ class CreateDatabase extends Command
return 0;
}
// try to set up a raw connection:
$pdo = false;
$exists = false;
$checked = false; // checked for existence of DB?
$dsn = sprintf('mysql:host=%s;port=%d;charset=utf8mb4', env('DB_HOST', 'localhost'), env('DB_PORT', '3306'));
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// when it fails, display error
try {
$pdo = new PDO($dsn, env('DB_USERNAME'), env('DB_PASSWORD'), $options);
} catch (PDOException $e) {
$this->error(sprintf('Error when connecting to DB: %s', $e->getMessage()));
return 1;
}
// with PDO, try to list DB's (
$stmt = $pdo->query('SHOW DATABASES;');
$exists = false;
// slightly more complex but less error prone.
foreach ($stmt as $row) {
$name = $row['Database'] ?? false;
if ($name === env('DB_DATABASE')) {
$exists = true;
// only continue when no error.
if (false !== $pdo) {
// with PDO, try to list DB's (
$stmt = $pdo->query('SHOW DATABASES;');
$checked = true;
// slightly more complex but less error prone.
foreach ($stmt as $row) {
$name = $row['Database'] ?? false;
if ($name === env('DB_DATABASE')) {
$exists = true;
}
}
}
if (false === $exists) {
if (false === $exists && true === $checked) {
$this->error(sprintf('Database "%s" does not exist.', env('DB_DATABASE')));
// try to create it.
$pdo->exec(sprintf('CREATE DATABASE `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;', env('DB_DATABASE')));
$this->info(sprintf('Created database "%s"', env('DB_DATABASE')));
return 0;
}
$this->info(sprintf('Database "%s" exists.', env('DB_DATABASE')));
if (true === $exists && true === $checked) {
$this->info(sprintf('Database "%s" exists.', env('DB_DATABASE')));
}
return 0;
}

View File

@ -57,7 +57,7 @@ class ExportData extends Command
*
* @var string
*/
protected $signature = 'firefly-iii:export-data
protected $signature = 'firefly-iii:export-data
{--user=1 : The user ID that the export should run for.}
{--token= : The user\'s access token.}
{--start= : First transaction to export. Defaults to your very first transaction. Only applies to transaction export.}
@ -74,20 +74,17 @@ class ExportData extends Command
{--export-bills : Create a file with all your bills and some meta data.}
{--export-piggies : Create a file with all your piggy banks and some meta data.}
{--force : Force overwriting of previous exports if found.}';
/** @var AccountRepositoryInterface */
private $accountRepository;
/** @var JournalRepositoryInterface */
private $journalRepository;
/** @var User */
private $user;
private AccountRepositoryInterface $accountRepository;
private JournalRepositoryInterface $journalRepository;
private User $user;
/**
* Execute the console command.
*
* @throws FireflyException
* @throws CannotInsertRecord
* @return int
* @throws CannotInsertRecord
* @throws FireflyException
*/
public function handle(): int
{
@ -111,7 +108,6 @@ class ExportData extends Command
return 1;
}
// make export object and configure it.
/** @var ExportDataGenerator $exporter */
$exporter = app(ExportDataGenerator::class);
$exporter->setUser($this->user);
@ -126,26 +122,24 @@ class ExportData extends Command
$exporter->setExportRules($options['export']['rules']);
$exporter->setExportBills($options['export']['bills']);
$exporter->setExportPiggies($options['export']['piggies']);
$data = $exporter->export();
if (0 === count($data)) {
if (empty($data)) {
$this->error('You must export *something*. Use --export-transactions or another option. See docs.firefly-iii.org');
}
$returnCode = 0;
if (!empty($data)) {
try {
$this->exportData($options, $data);
app('telemetry')->feature('system.command.executed', $this->signature);
} catch (FireflyException $e) {
$this->error(sprintf('Could not store data: %s', $e->getMessage()));
return 1;
app('telemetry')->feature('system.command.errored', $this->signature);
$returnCode = 1;
}
}
try {
$this->exportData($options, $data);
} catch (FireflyException $e) {
$this->error(sprintf('Could not store data: %s', $e->getMessage()));
app('telemetry')->feature('system.command.errored', $this->signature);
return 1;
}
app('telemetry')->feature('system.command.executed', $this->signature);
return 0;
return $returnCode;
}
/**
@ -172,8 +166,8 @@ class ExportData extends Command
}
/**
* @throws FireflyException
* @return Collection
* @throws FireflyException
*/
private function getAccountsParameter(): Collection
{
@ -181,7 +175,7 @@ class ExportData extends Command
$accounts = new Collection;
$accountList = $this->option('accounts');
$types = [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE];
if (null !== $accountList && '' !== (string) $accountList) {
if (null !== $accountList && '' !== (string)$accountList) {
$accountIds = explode(',', $accountList);
$accounts = $this->accountRepository->getAccountsById($accountIds);
}
@ -205,35 +199,30 @@ class ExportData extends Command
/**
* @param string $field
*
* @throws FireflyException
* @throws Exception
* @return Carbon
* @throws Exception
*/
private function getDateParameter(string $field): Carbon
{
$date = Carbon::now()->subYear();
$error = false;
if (null !== $this->option($field)) {
try {
$date = Carbon::createFromFormat('Y-m-d', $this->option($field));
} catch (InvalidArgumentException $e) {
Log::error($e->getMessage());
$this->error(sprintf('%s date "%s" must be formatted YYYY-MM-DD. Field will be ignored.', $field, $this->option('start')));
$error = true;
}
return $date;
}
if ('start' === $field) {
if (false === $error && 'start' === $field) {
$journal = $this->journalRepository->firstNull();
$date = null === $journal ? Carbon::now()->subYear() : $journal->date;
$date->startOfDay();
return $date;
}
if ('end' === $field) {
if (false === $error && 'end' === $field) {
$date = today(config('app.timezone'));
$date->endOfDay();
return $date;
}
// fallback
@ -241,13 +230,13 @@ class ExportData extends Command
}
/**
* @return string
* @throws FireflyException
*
* @return string
*/
private function getExportDirectory(): string
{
$directory = (string) $this->option('export_directory');
$directory = (string)$this->option('export_directory');
if (null === $directory) {
$directory = './';
}
@ -259,8 +248,8 @@ class ExportData extends Command
}
/**
* @throws FireflyException
* @return array
* @throws FireflyException
*/
private function parseOptions(): array
{

View File

@ -55,13 +55,13 @@ class TransferCurrenciesCorrections extends Command
private AccountRepositoryInterface $accountRepos;
private JournalCLIRepositoryInterface $cliRepos;
private int $count;
private Account $destinationAccount;
private TransactionCurrency $destinationCurrency;
private Transaction $destinationTransaction;
private Account $sourceAccount;
private TransactionCurrency $sourceCurrency;
private Transaction $sourceTransaction;
private ?Account $destinationAccount;
private ?TransactionCurrency $destinationCurrency;
private ?Transaction $destinationTransaction;
private ?Account $sourceAccount;
private ?TransactionCurrency $sourceCurrency;
private ?Transaction $sourceTransaction;
/**
* Execute the console command.

View File

@ -182,6 +182,11 @@ class UserEventHandler
$user = $event->user;
$email = $user->email;
$ipAddress = $event->ipAddress;
if($user->hasRole('demo')) {
return; // do not email demo user.
}
$list = app('preferences')->getForUser($user, 'login_ip_history', [])->data;
// see if user has alternative email address:

View File

@ -26,6 +26,7 @@ use Carbon\Carbon;
use Eloquent;
use FireflyIII\User;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
@ -97,7 +98,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
*/
class Account extends Model
{
use SoftDeletes;
use SoftDeletes, HasFactory;
/**
* The attributes that should be casted to native types.

View File

@ -26,6 +26,7 @@ use Carbon\Carbon;
use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
@ -132,13 +133,10 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @mixin Eloquent
* @property-read int|null $budgets_count
* @property-read int|null $categories_count
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property bool $reconciled
*/
class Transaction extends Model
{
use SoftDeletes;
use SoftDeletes, HasFactory;
/**
* The attributes that should be casted to native types.
*
@ -185,7 +183,6 @@ class Transaction extends Model
return false;
}
/**
* Get the account this object belongs to.
*

View File

@ -28,6 +28,7 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
@ -124,7 +125,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
*/
class TransactionJournal extends Model
{
use SoftDeletes;
use SoftDeletes, HasFactory;
/**
* The attributes that should be casted to native types.

View File

@ -1,38 +0,0 @@
<?php
declare(strict_types=1);
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Faker\Generator as Faker;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
$factory->define(Account::class, function (Faker $faker) {
return [
'user_id' => 1,
'account_type_id' => 1,
'name' => $faker->words(3, true),
'virtual_balance' => '0',
'active' => 1,
'encrypted' => 0,
'order' => 1,
];
});
$factory->state(Account::class, AccountType::ASSET, function ($faker) {
return [
'account_type_id' => 3,
];
});
$factory->state(Account::class, AccountType::INITIAL_BALANCE, function ($faker) {
return [
'account_type_id' => 6,
];
});
$factory->state(Account::class, AccountType::EXPENSE, function ($faker) {
return [
'account_type_id' => 4,
];
});

View File

@ -0,0 +1,101 @@
<?php
/*
* AccountFactory.php
* Copyright (c) 2020 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 <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Database\Factories\FireflyIII\Models;
use FireflyIII\Models\Account;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* Class AccountFactory
*/
class AccountFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Account::class;
/**
* @inheritDoc
*/
public function definition()
{
return [
'user_id' => 1,
'account_type_id' => 1,
'name' => $this->faker->words(3, true),
'virtual_balance' => '0',
'active' => 1,
'encrypted' => 0,
'order' => 1,
];
}
/**
* @return AccountFactory
*/
public function asset()
{
return $this->state(
function () {
return [
'account_type_id' => 3,
];
}
);
}
/**
* @return AccountFactory
*/
public function initialBalance()
{
return $this->state(
function () {
return [
'account_type_id' => 6,
];
}
);
}
/**
* @return AccountFactory
*/
public function expense()
{
return $this->state(
function () {
return [
'account_type_id' => 4,
];
}
);
}
}

View File

@ -0,0 +1,55 @@
<?php
/*
* TransactionFactory.php
* Copyright (c) 2020 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 <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Database\Factories\FireflyIII\Models;
use FireflyIII\Models\Transaction;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* Class TransactionFactory
*/
class TransactionFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Transaction::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'transaction_journal_id' => 0,
'account_id' => 0,
'amount' => 5,
];
}
}

View File

@ -0,0 +1,123 @@
<?php
/*
* TransactionJournalFactory.php
* Copyright (c) 2020 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 <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Database\Factories\FireflyIII\Models;
use FireflyIII\Models\Account;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* Class TransactionJournalFactory
*/
class TransactionJournalFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = TransactionJournal::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'user_id' => 1,
'transaction_type_id' => 1,
'description' => $this->faker->words(3, true),
'tag_count' => 0,
'date' => $this->faker->date('Y-m-d'),
];
}
/**
* @return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function openingBalance()
{
return $this
->state(fn () => ['transaction_type_id' => 4])
->afterCreating(
function (TransactionJournal $journal) {
// fix factory
$obAccount = Account::factory(Account::class)->initialBalance()->create();
$assetAccount = Account::factory(Account::class)->asset()->create();
Transaction::factory()->create(
[
'account_id' => $obAccount->id,
'transaction_journal_id' => $journal->id,
'amount' => '5',
]
);
Transaction::factory()->create(
[
'account_id' => $assetAccount->id,
'transaction_journal_id' => $journal->id,
'amount' => '-5',
]
);
}
);
}
/**
* @return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function brokenOpeningBalance()
{
return $this->state(
function () {
return [
'transaction_type_id' => 4,
];
}
)->afterCreating(
function (TransactionJournal $journal) {
$ob1 = Account::factory(Account::class)->initialBalance()->create();
$ob2 = Account::factory(Account::class)->initialBalance()->create();
Transaction::factory()->create(
[
'account_id' => $ob1->id,
'transaction_journal_id' => $journal->id,
'amount' => '5',
]
);
Transaction::factory()->create(
[
'account_id' => $ob2->id,
'transaction_journal_id' => $journal->id,
'amount' => '5',
]
);
}
);
}
}

View File

@ -1,71 +0,0 @@
<?php
declare(strict_types=1);
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Faker\Generator as Faker;
use FireflyIII\Model;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
$factory->define(TransactionJournal::class, function (Faker $faker) {
return [
'user_id' => 1,
'transaction_type_id' => 1,
'description' => $faker->words(3, true),
'tag_count' => 0,
'date' => $faker->date('Y-m-d'),
];
});
$factory->state(TransactionJournal::class, TransactionType::OPENING_BALANCE, function ($faker) {
return [
'transaction_type_id' => 4,
];
});
$factory->state(TransactionJournal::class, 'ob_broken', function ($faker) {
return [
'transaction_type_id' => 4,
];
});
$factory->afterCreatingState(TransactionJournal::class, TransactionType::OPENING_BALANCE, function ($journal, $faker) {
$obAccount = factory(Account::class)->state(AccountType::INITIAL_BALANCE)->create();
$assetAccount = factory(Account::class)->state(AccountType::ASSET)->create();
factory(Transaction::class)->create(
[
'account_id' => $obAccount->id,
'transaction_journal_id' => $journal->id,
'amount' => '5',
]);
factory(Transaction::class)->create(
[
'account_id' => $assetAccount->id,
'transaction_journal_id' => $journal->id,
'amount' => '-5',
]);
});
$factory->afterCreatingState(TransactionJournal::class, 'ob_broken', function ($journal, $faker) {
$ob1 = factory(Account::class)->state(AccountType::INITIAL_BALANCE)->create();
$ob2 = factory(Account::class)->state(AccountType::INITIAL_BALANCE)->create();
factory(Transaction::class)->create(
[
'account_id' => $ob1->id,
'transaction_journal_id' => $journal->id,
'amount' => '5',
]);
factory(Transaction::class)->create(
[
'account_id' => $ob2->id,
'transaction_journal_id' => $journal->id,
'amount' => '-5',
]);
});

View File

@ -1,15 +0,0 @@
<?php
declare(strict_types=1);
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Faker\Generator as Faker;
use FireflyIII\Models\Transaction;
$factory->define(Transaction::class, function (Faker $faker) {
return [
'transaction_journal_id' => 0,
'account_id' => 0,
'amount' => 5,
];
});

View File

@ -20,8 +20,11 @@
*/
declare(strict_types=1);
namespace Database\Seeders;
use FireflyIII\Models\AccountType;
use Illuminate\Database\Seeder;
use PDOEXception;
/**
* Class AccountTypeSeeder.
@ -48,7 +51,7 @@ class AccountTypeSeeder extends Seeder
try {
AccountType::create(['type' => $type]);
} catch (PDOException $e) {
Log::info(sprintf('Could not create account type "%s". It might exist already.', $type));
// dont care.
}
}
}

View File

@ -43,8 +43,11 @@ declare(strict_types=1);
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Database\Seeders;
use FireflyIII\Models\Configuration;
use Illuminate\Database\Seeder;
use Log;
/**
* Class ConfigSeeder.
@ -68,7 +71,7 @@ class ConfigSeeder extends Seeder
);
}
if (null !== $entry) {
$version = (int) config('firefly.db_version');
$version = (int)config('firefly.db_version');
$entry->data = $version;
$entry->save();

View File

@ -20,6 +20,8 @@
*/
declare(strict_types=1);
namespace Database\Seeders;
use Illuminate\Database\Seeder;
/**

View File

@ -20,8 +20,11 @@
*/
declare(strict_types=1);
namespace Database\Seeders;
use FireflyIII\Models\LinkType;
use Illuminate\Database\Seeder;
use PDOEXception;
/**
* Class LinkTypeSeeder.
@ -60,7 +63,7 @@ class LinkTypeSeeder extends Seeder
try {
LinkType::create($type);
} catch (PDOException $e) {
Log::info(sprintf('Could not create link type "%s". It might exist already.', $type['name']));
// dont care
}
}
}

View File

@ -20,8 +20,11 @@
*/
declare(strict_types=1);
namespace Database\Seeders;
use FireflyIII\Models\Role;
use Illuminate\Database\Seeder;
use PDOEXception;
/**
* Class PermissionSeeder.
@ -46,7 +49,7 @@ class PermissionSeeder extends Seeder
try {
Role::create($role);
} catch (PDOException $e) {
Log::info(sprintf('Could not create role "%s". It might exist already.', $role['display_name']));
// dont care
}
}
}

View File

@ -20,8 +20,11 @@
*/
declare(strict_types=1);
namespace Database\Seeders;
use FireflyIII\Models\TransactionCurrency;
use Illuminate\Database\Seeder;
use PDOEXception;
/**
* Class TransactionCurrencySeeder.
@ -78,7 +81,7 @@ class TransactionCurrencySeeder extends Seeder
try {
TransactionCurrency::create($currency);
} catch (PDOException $e) {
Log::info(sprintf('Could not create transaction currency "%s". It might exist already. This is not a problem.', $currency['code']));
// dont care
}
}
}

View File

@ -20,8 +20,11 @@
*/
declare(strict_types=1);
namespace Database\Seeders;
use FireflyIII\Models\TransactionType;
use Illuminate\Database\Seeder;
use PDOEXception;
/**
* Class TransactionTypeSeeder.
@ -42,7 +45,7 @@ class TransactionTypeSeeder extends Seeder
try {
TransactionType::create(['type' => $type]);
} catch (PDOException $e) {
Log::info(sprintf('Could not create transaction type "%s". It might exist already.', $type));
// dont care
}
}
}