Compare commits

...

45 Commits

Author SHA1 Message Date
github-actions[bot]
664c59136a Merge pull request #10293 from firefly-iii/release-1747020359
🤖 Automatically merge the PR into the develop branch.
2025-05-12 05:26:07 +02:00
JC5
27b61aae73 🤖 Auto commit for release 'develop' on 2025-05-12 2025-05-12 05:26:00 +02:00
github-actions[bot]
d90fcd1889 Merge pull request #10288 from firefly-iii/release-1746966536
🤖 Automatically merge the PR into the develop branch.
2025-05-11 14:29:03 +02:00
JC5
979d5c579b 🤖 Auto commit for release 'develop' on 2025-05-11 2025-05-11 14:28:56 +02:00
James Cole
5124ca1738 Introduce change for CI to catch. 2025-05-11 14:24:59 +02:00
James Cole
ac5d9b656a Merge pull request #10287 from firefly-iii/add-safe
Include safe methods and require the correct package.
2025-05-11 14:19:33 +02:00
James Cole
9a02739251 Include safe methods and require the correct package. 2025-05-11 14:19:07 +02:00
James Cole
4af2aadc48 Merge pull request #10286 from firefly-iii/remove-safe-methods
Remove safe methods.
2025-05-11 14:09:02 +02:00
James Cole
84779b8d02 Remove safe methods. 2025-05-11 14:08:32 +02:00
github-actions[bot]
145e8d23f0 Merge pull request #10285 from firefly-iii/release-1746964861
🤖 Automatically merge the PR into the develop branch.
2025-05-11 14:01:08 +02:00
JC5
d0ba0583a5 🤖 Auto commit for release 'develop' on 2025-05-11 2025-05-11 14:01:01 +02:00
James Cole
17d8b54280 Merge pull request #10284 from firefly-iii/fix-missing-import-2
Temp commit because the build fails otherwise and I haven't fixed tha…
2025-05-11 13:56:41 +02:00
James Cole
2cf0bfe3c4 Temp commit because the build fails otherwise and I haven't fixed that yet. 2025-05-11 13:56:07 +02:00
James Cole
070a8cf148 Remove safe functions 2025-05-11 13:16:09 +02:00
github-actions[bot]
f94c21446a Merge pull request #10283 from firefly-iii/release-1746961946
🤖 Automatically merge the PR into the develop branch.
2025-05-11 13:12:33 +02:00
JC5
1ef1873016 🤖 Auto commit for release 'develop' on 2025-05-11 2025-05-11 13:12:26 +02:00
James Cole
32e4e29e7c Merge pull request #10282 from firefly-iii/fix-missing-import
Fix missing import.
2025-05-11 13:08:28 +02:00
James Cole
65ca0dd9e0 Fix missing import. 2025-05-11 13:07:37 +02:00
github-actions[bot]
3385e12c01 Merge pull request #10281 from firefly-iii/release-1746961196
🤖 Automatically merge the PR into the develop branch.
2025-05-11 13:00:03 +02:00
JC5
3566a4afa3 🤖 Auto commit for release 'develop' on 2025-05-11 2025-05-11 12:59:56 +02:00
James Cole
68ff033342 Merge pull request #10279 from firefly-iii/fix-10265-addendum
Fix 10265 addendum
2025-05-11 08:33:52 +02:00
James Cole
f141b0be5c Merge branch 'develop' into fix-10265-addendum
# Conflicts:
#	app/Factory/TransactionJournalFactory.php
2025-05-11 08:33:35 +02:00
James Cole
d399dd160f Merge pull request #10278 from firefly-iii/fix-10265
Fix #10265
2025-05-11 08:31:10 +02:00
James Cole
4c8ed784cd Final check for transaction types 2025-05-11 08:29:31 +02:00
James Cole
fb3402acd4 Fix storage issue with transactions. 2025-05-11 08:00:38 +02:00
James Cole
8cad430816 Fix validation error in transaction processing. 2025-05-11 07:35:20 +02:00
James Cole
01502b456e Disable fix for the moment. 2025-05-11 07:29:18 +02:00
James Cole
9b6314066b Clean up logs. 2025-05-11 07:23:35 +02:00
James Cole
e61dadcbc6 Implement correction method. 2025-05-11 07:20:17 +02:00
James Cole
f7baf5b2fd Better debug info 2025-05-11 07:11:00 +02:00
James Cole
0545826d57 Do not try to correct transactions between asset / liability with foreign amount info. 2025-05-11 07:09:48 +02:00
James Cole
a29904704c Fix #10265 2025-05-11 07:01:36 +02:00
James Cole
899d374222 Merge pull request #10271 from firefly-iii/various-updates
Fix account list and remove sanctum
2025-05-08 20:22:24 +02:00
James Cole
07ff2305fd Fix account list and remove sanctum 2025-05-08 20:22:01 +02:00
James Cole
ee96dd3ab6 Merge pull request #10270 from firefly-iii/main
Update packages
2025-05-08 20:21:12 +02:00
James Cole
a766d3a133 Merge pull request #10263 from firefly-iii/dependabot/composer/composer-761f56e718 2025-05-06 07:22:08 +02:00
dependabot[bot]
67545b0371 Bump league/commonmark in the composer group across 1 directory
Bumps the composer group with 1 update in the / directory: [league/commonmark](https://github.com/thephpleague/commonmark).


Updates `league/commonmark` from 2.6.2 to 2.7.0
- [Release notes](https://github.com/thephpleague/commonmark/releases)
- [Changelog](https://github.com/thephpleague/commonmark/blob/2.7/CHANGELOG.md)
- [Commits](https://github.com/thephpleague/commonmark/compare/2.6.2...2.7.0)

---
updated-dependencies:
- dependency-name: league/commonmark
  dependency-version: 2.7.0
  dependency-type: direct:production
  dependency-group: composer
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-06 01:59:56 +00:00
James Cole
6b86d825ea Merge pull request #10261 from firefly-iii/update-packages
Update packages
2025-05-05 07:48:50 +02:00
James Cole
31dbc57e8b Update packages 2025-05-05 07:48:13 +02:00
github-actions[bot]
00050f629c Merge pull request #10259 from firefly-iii/release-1746415513
🤖 Automatically merge the PR into the develop branch.
2025-05-05 05:25:21 +02:00
JC5
3760aabf13 🤖 Auto commit for release 'develop' on 2025-05-05 2025-05-05 05:25:13 +02:00
James Cole
22e092b513 Merge pull request #10255 from firefly-iii/fix-v2
Fix back and forth between v1 and v2
2025-05-04 21:26:52 +02:00
James Cole
a4f7c90e09 Fix back and forth between v1 and v2 2025-05-04 21:24:50 +02:00
James Cole
4b92ab46a3 Merge pull request #10253 from firefly-iii/cleanup-code
Clean up code.
2025-05-04 17:41:52 +02:00
James Cole
0573bf2402 Clean up code. 2025-05-04 17:41:26 +02:00
173 changed files with 2739 additions and 2830 deletions

View File

@@ -61,7 +61,7 @@ return $config->setRules(
'comment_to_phpdoc' => false, // breaks phpstan lines in combination with PHPStorm. 'comment_to_phpdoc' => false, // breaks phpstan lines in combination with PHPStorm.
'type_declaration_spaces' => false, 'type_declaration_spaces' => false,
'cast_spaces' => false, 'cast_spaces' => false,
'phpdoc_to_comment' => false, // do not overrule single line comment style, breaks phpstan. 'phpdoc_to_comment' => false, // do not overrule single line comment style, breaks phpstan.
// complex rules // complex rules
'array_syntax' => ['syntax' => 'short'], 'array_syntax' => ['syntax' => 'short'],

View File

@@ -5,17 +5,17 @@ declare(strict_types=1);
use Rector\Config\RectorConfig; use Rector\Config\RectorConfig;
return RectorConfig::configure() return RectorConfig::configure()
->withPaths([ ->withPaths([
__DIR__ . '/../app', __DIR__ . '/../app',
__DIR__ . '/../bootstrap', __DIR__ . '/../bootstrap',
__DIR__ . '/../config', __DIR__ . '/../config',
__DIR__ . '/../public', __DIR__ . '/../public',
__DIR__ . '/../resources', __DIR__ . '/../resources',
__DIR__ . '/../routes', __DIR__ . '/../routes',
__DIR__ . '/../tests', __DIR__ . '/../tests',
]) ])
// uncomment to reach your current PHP version // uncomment to reach your current PHP version
->withPhpSets() ->withPhpSets()
->withTypeCoverageLevel(0) ->withTypeCoverageLevel(0)
->withDeadCodeLevel(0) ->withDeadCodeLevel(0)
->withCodeQualityLevel(0); ->withCodeQualityLevel(0);

View File

@@ -296,13 +296,6 @@ STATIC_CRON_TOKEN=
# However if you know what you're doing you can significantly speed up container start times. # However if you know what you're doing you can significantly speed up container start times.
# Set each value to true to enable, or false to disable. # Set each value to true to enable, or false to disable.
# Set this to true to build all locales supported by Firefly III.
# This may take quite some time (several minutes) and is generally not recommended.
# If you wish to change or alter the list of locales, start your Docker container with
# `docker run -v locale.gen:/etc/locale.gen -e DKR_BUILD_LOCALE=true`
# and make sure your preferred locales are in your own locale.gen.
DKR_BUILD_LOCALE=false
# Check if the SQLite database exists. Can be skipped if you're not using SQLite. # Check if the SQLite database exists. Can be skipped if you're not using SQLite.
# Won't significantly speed up things. # Won't significantly speed up things.
DKR_CHECK_SQLITE=true DKR_CHECK_SQLITE=true

View File

@@ -43,6 +43,7 @@ use Illuminate\Support\Facades\Log;
class AccountController extends Controller class AccountController extends Controller
{ {
use AccountFilter; use AccountFilter;
// this array only exists to test if the constructor will use it properly. // this array only exists to test if the constructor will use it properly.
protected array $accepts = ['application/json', 'application/vnd.api+json']; protected array $accepts = ['application/json', 'application/vnd.api+json'];

View File

@@ -39,11 +39,10 @@ use Illuminate\Support\Collection;
*/ */
class TransactionController extends Controller class TransactionController extends Controller
{ {
protected array $acceptedRoles = [UserRoleEnum::READ_ONLY];
private TransactionGroupRepositoryInterface $groupRepository; private TransactionGroupRepositoryInterface $groupRepository;
private JournalRepositoryInterface $repository; private JournalRepositoryInterface $repository;
protected array $acceptedRoles = [UserRoleEnum::READ_ONLY];
/** /**
* TransactionController constructor. * TransactionController constructor.
*/ */

View File

@@ -26,8 +26,8 @@ namespace FireflyIII\Api\V1\Controllers\Chart;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Data\DateRequest;
use FireflyIII\Api\V1\Requests\Chart\ChartRequest; use FireflyIII\Api\V1\Requests\Chart\ChartRequest;
use FireflyIII\Api\V1\Requests\Data\DateRequest;
use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
@@ -48,8 +48,8 @@ class AccountController extends Controller
use ApiSupport; use ApiSupport;
use CollectsAccountsFromFilter; use CollectsAccountsFromFilter;
private AccountRepositoryInterface $repository;
private ChartData $chartData; private ChartData $chartData;
private AccountRepositoryInterface $repository;
/** /**
* AccountController constructor. * AccountController constructor.
@@ -93,6 +93,47 @@ class AccountController extends Controller
return response()->json($this->chartData->render()); return response()->json($this->chartData->render());
} }
/**
* @throws FireflyException
*/
private function renderAccountData(array $params, Account $account): void
{
$currency = $this->repository->getAccountCurrency($account);
if (null === $currency) {
$currency = $this->default;
}
$currentSet = [
'label' => $account->name,
// the currency that belongs to the account.
'currency_id' => (string) $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,
// the default currency of the user (could be the same!)
'date' => $params['start']->toAtomString(),
'start' => $params['start']->toAtomString(),
'end' => $params['end']->toAtomString(),
'period' => '1D',
'entries' => [],
];
$currentStart = clone $params['start'];
$range = Steam::finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToNative);
$previous = array_values($range)[0]['balance'];
while ($currentStart <= $params['end']) {
$format = $currentStart->format('Y-m-d');
$label = $currentStart->toAtomString();
$balance = array_key_exists($format, $range) ? $range[$format]['balance'] : $previous;
$previous = $balance;
$currentStart->addDay();
$currentSet['entries'][$label] = $balance;
}
$this->chartData->add($currentSet);
}
/** /**
* This endpoint is documented at: * This endpoint is documented at:
* https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/charts/getChartAccountOverview * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/charts/getChartAccountOverview
@@ -162,45 +203,4 @@ class AccountController extends Controller
return response()->json($chartData); return response()->json($chartData);
} }
/**
* @throws FireflyException
*/
private function renderAccountData(array $params, Account $account): void
{
$currency = $this->repository->getAccountCurrency($account);
if (null === $currency) {
$currency = $this->default;
}
$currentSet = [
'label' => $account->name,
// the currency that belongs to the account.
'currency_id' => (string) $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,
// the default currency of the user (could be the same!)
'date' => $params['start']->toAtomString(),
'start' => $params['start']->toAtomString(),
'end' => $params['end']->toAtomString(),
'period' => '1D',
'entries' => [],
];
$currentStart = clone $params['start'];
$range = Steam::finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToNative);
$previous = array_values($range)[0]['balance'];
while ($currentStart <= $params['end']) {
$format = $currentStart->format('Y-m-d');
$label = $currentStart->toAtomString();
$balance = array_key_exists($format, $range) ? $range[$format]['balance'] : $previous;
$previous = $balance;
$currentStart->addDay();
$currentSet['entries'][$label] = $balance;
}
$this->chartData->add($currentSet);
}
} }

View File

@@ -40,7 +40,6 @@ use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Collection;
use League\Fractal\Manager; use League\Fractal\Manager;
use League\Fractal\Pagination\IlluminatePaginatorAdapter; use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Resource\Collection as FractalCollection; use League\Fractal\Resource\Collection as FractalCollection;
@@ -62,15 +61,15 @@ abstract class Controller extends BaseController
use ValidatesRequests; use ValidatesRequests;
use ValidatesUserGroupTrait; use ValidatesUserGroupTrait;
protected const string CONTENT_TYPE = 'application/vnd.api+json'; protected const string CONTENT_TYPE = 'application/vnd.api+json';
protected const string JSON_CONTENT_TYPE = 'application/json'; protected const string JSON_CONTENT_TYPE = 'application/json';
protected array $accepts = ['application/json', 'application/vnd.api+json'];
/** @var array<int, string> */ /** @var array<int, string> */
protected array $allowedSort; protected array $allowedSort;
protected ParameterBag $parameters; protected bool $convertToNative = false;
protected bool $convertToNative = false;
protected array $accepts = ['application/json', 'application/vnd.api+json'];
protected TransactionCurrency $nativeCurrency; protected TransactionCurrency $nativeCurrency;
protected ParameterBag $parameters;
/** /**
* Controller constructor. * Controller constructor.

View File

@@ -39,10 +39,8 @@ class DestroyController extends Controller
{ {
use ValidatesUserGroupTrait; use ValidatesUserGroupTrait;
protected array $acceptedRoles = [UserRoleEnum::OWNER];
public const string RESOURCE_KEY = 'exchange-rates'; public const string RESOURCE_KEY = 'exchange-rates';
protected array $acceptedRoles = [UserRoleEnum::OWNER];
private ExchangeRateRepositoryInterface $repository; private ExchangeRateRepositoryInterface $repository;
public function __construct() public function __construct()

View File

@@ -50,9 +50,8 @@ class StoreController extends Controller
{ {
use TransactionFilter; use TransactionFilter;
private TransactionGroupRepositoryInterface $groupRepository;
protected array $acceptedRoles = [UserRoleEnum::MANAGE_TRANSACTIONS]; protected array $acceptedRoles = [UserRoleEnum::MANAGE_TRANSACTIONS];
private TransactionGroupRepositoryInterface $groupRepository;
/** /**
* TransactionController constructor. * TransactionController constructor.

View File

@@ -27,8 +27,8 @@ namespace FireflyIII\Api\V1\Controllers\Models\TransactionCurrency;
use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;

View File

@@ -483,7 +483,7 @@ class BasicController extends Controller
// first, create an entry for each entry in the "available" array. // first, create an entry for each entry in the "available" array.
/** @var array $availableBudget */ /** @var array $availableBudget */
foreach ($available as $currencyId => $availableBudget) { foreach ($available as $currencyId => $availableBudget) {
$currencies[$currencyId] ??= $this->currencyRepos->find($currencyId); $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId);
$return[$currencyId] = [ $return[$currencyId] = [
'key' => sprintf('left-to-spend-in-%s', $currencies[$currencyId]->code), 'key' => sprintf('left-to-spend-in-%s', $currencies[$currencyId]->code),

View File

@@ -45,7 +45,7 @@ class DestroyRequest extends FormRequest
public function rules(): array public function rules(): array
{ {
return [ return [
'date' => 'required|date|after:1900-01-01|before:2099-12-31', 'date' => 'required|date|after:1900-01-01|before:2099-12-31',
]; ];
} }
} }

View File

@@ -40,16 +40,16 @@ class StoreRequest extends FormRequest
return $this->getCarbonDate('date'); return $this->getCarbonDate('date');
} }
public function getRate(): string
{
return (string) $this->get('rate');
}
public function getFromCurrency(): TransactionCurrency public function getFromCurrency(): TransactionCurrency
{ {
return TransactionCurrency::where('code', $this->get('from'))->first(); return TransactionCurrency::where('code', $this->get('from'))->first();
} }
public function getRate(): string
{
return (string) $this->get('rate');
}
public function getToCurrency(): TransactionCurrency public function getToCurrency(): TransactionCurrency
{ {
return TransactionCurrency::where('code', $this->get('to'))->first(); return TransactionCurrency::where('code', $this->get('to'))->first();

View File

@@ -50,8 +50,8 @@ class UpdateRequest extends FormRequest
public function rules(): array public function rules(): array
{ {
return [ return [
'date' => 'date|after:1900-01-01|before:2099-12-31', 'date' => 'date|after:1900-01-01|before:2099-12-31',
'rate' => 'required|numeric|gt:0', 'rate' => 'required|numeric|gt:0',
]; ];
} }
} }

View File

@@ -83,87 +83,87 @@ class StoreRequest extends FormRequest
foreach ($this->get('transactions') as $transaction) { foreach ($this->get('transactions') as $transaction) {
$object = new NullArrayObject($transaction); $object = new NullArrayObject($transaction);
$return[] = [ $return[] = [
'type' => $this->clearString($object['type']), 'type' => $this->clearString($object['type']),
'date' => $this->dateFromValue($object['date']), 'date' => $this->dateFromValue($object['date']),
'order' => $this->integerFromValue((string) $object['order']), 'order' => $this->integerFromValue((string) $object['order']),
'currency_id' => $this->integerFromValue((string) $object['currency_id']), 'currency_id' => $this->integerFromValue((string) $object['currency_id']),
'currency_code' => $this->clearString((string) $object['currency_code']), 'currency_code' => $this->clearString((string) $object['currency_code']),
// location // location
'latitude' => $this->floatFromValue((string) $object['latitude']), 'latitude' => $this->floatFromValue((string) $object['latitude']),
'longitude' => $this->floatFromValue((string) $object['longitude']), 'longitude' => $this->floatFromValue((string) $object['longitude']),
'zoom_level' => $this->integerFromValue((string) $object['zoom_level']), 'zoom_level' => $this->integerFromValue((string) $object['zoom_level']),
// foreign currency info: // foreign currency info:
'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']), 'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']),
'foreign_currency_code' => $this->clearString((string) $object['foreign_currency_code']), 'foreign_currency_code' => $this->clearString((string) $object['foreign_currency_code']),
// amount and foreign amount. Cannot be 0. // amount and foreign amount. Cannot be 0.
'amount' => $this->clearString((string) $object['amount']), 'amount' => $this->clearString((string) $object['amount']),
'foreign_amount' => $this->clearString((string) $object['foreign_amount']), 'foreign_amount' => $this->clearString((string) $object['foreign_amount']),
// description. // description.
'description' => $this->clearString($object['description']), 'description' => $this->clearString($object['description']),
// source of transaction. If everything is null, assume cash account. // source of transaction. If everything is null, assume cash account.
'source_id' => $this->integerFromValue((string) $object['source_id']), 'source_id' => $this->integerFromValue((string) $object['source_id']),
'source_name' => $this->clearString((string) $object['source_name']), 'source_name' => $this->clearString((string) $object['source_name']),
'source_iban' => $this->clearIban((string) $object['source_iban']), 'source_iban' => $this->clearIban((string) $object['source_iban']),
'source_number' => $this->clearString((string) $object['source_number']), 'source_number' => $this->clearString((string) $object['source_number']),
'source_bic' => $this->clearString((string) $object['source_bic']), 'source_bic' => $this->clearString((string) $object['source_bic']),
// destination of transaction. If everything is null, assume cash account. // destination of transaction. If everything is null, assume cash account.
'destination_id' => $this->integerFromValue((string) $object['destination_id']), 'destination_id' => $this->integerFromValue((string) $object['destination_id']),
'destination_name' => $this->clearString((string) $object['destination_name']), 'destination_name' => $this->clearString((string) $object['destination_name']),
'destination_iban' => $this->clearIban((string) $object['destination_iban']), 'destination_iban' => $this->clearIban((string) $object['destination_iban']),
'destination_number' => $this->clearString((string) $object['destination_number']), 'destination_number' => $this->clearString((string) $object['destination_number']),
'destination_bic' => $this->clearString((string) $object['destination_bic']), 'destination_bic' => $this->clearString((string) $object['destination_bic']),
// budget info // budget info
'budget_id' => $this->integerFromValue((string) $object['budget_id']), 'budget_id' => $this->integerFromValue((string) $object['budget_id']),
'budget_name' => $this->clearString((string) $object['budget_name']), 'budget_name' => $this->clearString((string) $object['budget_name']),
// category info // category info
'category_id' => $this->integerFromValue((string) $object['category_id']), 'category_id' => $this->integerFromValue((string) $object['category_id']),
'category_name' => $this->clearString((string) $object['category_name']), 'category_name' => $this->clearString((string) $object['category_name']),
// journal bill reference. Optional. Will only work for withdrawals // journal bill reference. Optional. Will only work for withdrawals
'bill_id' => $this->integerFromValue((string) $object['bill_id']), 'bill_id' => $this->integerFromValue((string) $object['bill_id']),
'bill_name' => $this->clearString((string) $object['bill_name']), 'bill_name' => $this->clearString((string) $object['bill_name']),
// piggy bank reference. Optional. Will only work for transfers // piggy bank reference. Optional. Will only work for transfers
'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']), 'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']),
'piggy_bank_name' => $this->clearString((string) $object['piggy_bank_name']), 'piggy_bank_name' => $this->clearString((string) $object['piggy_bank_name']),
// some other interesting properties // some other interesting properties
'reconciled' => $this->convertBoolean((string) $object['reconciled']), 'reconciled' => $this->convertBoolean((string) $object['reconciled']),
'notes' => $this->clearStringKeepNewlines((string) $object['notes']), 'notes' => $this->clearStringKeepNewlines((string) $object['notes']),
'tags' => $this->arrayFromValue($object['tags']), 'tags' => $this->arrayFromValue($object['tags']),
// all custom fields: // all custom fields:
'internal_reference' => $this->clearString((string) $object['internal_reference']), 'internal_reference' => $this->clearString((string) $object['internal_reference']),
'external_id' => $this->clearString((string) $object['external_id']), 'external_id' => $this->clearString((string) $object['external_id']),
'original_source' => sprintf('ff3-v%s', config('firefly.version')), 'original_source' => sprintf('ff3-v%s', config('firefly.version')),
'recurrence_id' => $this->integerFromValue($object['recurrence_id']), 'recurrence_id' => $this->integerFromValue($object['recurrence_id']),
'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id']), 'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id']),
'external_url' => $this->clearString((string) $object['external_url']), 'external_url' => $this->clearString((string) $object['external_url']),
'sepa_cc' => $this->clearString((string) $object['sepa_cc']), 'sepa_cc' => $this->clearString((string) $object['sepa_cc']),
'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op']), 'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op']),
'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id']), 'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id']),
'sepa_db' => $this->clearString((string) $object['sepa_db']), 'sepa_db' => $this->clearString((string) $object['sepa_db']),
'sepa_country' => $this->clearString((string) $object['sepa_country']), 'sepa_country' => $this->clearString((string) $object['sepa_country']),
'sepa_ep' => $this->clearString((string) $object['sepa_ep']), 'sepa_ep' => $this->clearString((string) $object['sepa_ep']),
'sepa_ci' => $this->clearString((string) $object['sepa_ci']), 'sepa_ci' => $this->clearString((string) $object['sepa_ci']),
'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id']), 'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id']),
// custom date fields. Must be Carbon objects. Presence is optional. // custom date fields. Must be Carbon objects. Presence is optional.
'interest_date' => $this->dateFromValue($object['interest_date']), 'interest_date' => $this->dateFromValue($object['interest_date']),
'book_date' => $this->dateFromValue($object['book_date']), 'book_date' => $this->dateFromValue($object['book_date']),
'process_date' => $this->dateFromValue($object['process_date']), 'process_date' => $this->dateFromValue($object['process_date']),
'due_date' => $this->dateFromValue($object['due_date']), 'due_date' => $this->dateFromValue($object['due_date']),
'payment_date' => $this->dateFromValue($object['payment_date']), 'payment_date' => $this->dateFromValue($object['payment_date']),
'invoice_date' => $this->dateFromValue($object['invoice_date']), 'invoice_date' => $this->dateFromValue($object['invoice_date']),
]; ];
} }

View File

@@ -33,7 +33,6 @@ use FireflyIII\Transformers\AbstractTransformer;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Collection;
use League\Fractal\Manager; use League\Fractal\Manager;
use League\Fractal\Pagination\IlluminatePaginatorAdapter; use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Resource\Collection as FractalCollection; use League\Fractal\Resource\Collection as FractalCollection;
@@ -56,8 +55,8 @@ class Controller extends BaseController
protected const string CONTENT_TYPE = 'application/vnd.api+json'; protected const string CONTENT_TYPE = 'application/vnd.api+json';
protected array $acceptedRoles = [UserRoleEnum::READ_ONLY]; protected array $acceptedRoles = [UserRoleEnum::READ_ONLY];
protected ParameterBag $parameters;
protected bool $convertToNative = false; protected bool $convertToNative = false;
protected ParameterBag $parameters;
public function __construct() public function __construct()
{ {

View File

@@ -75,6 +75,65 @@ class CorrectsAmounts extends Command
return 0; return 0;
} }
private function correctTransfers(): void
{
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
$type = TransactionType::where('type', TransactionTypeEnum::TRANSFER->value)->first();
$journals = TransactionJournal::where('transaction_type_id', $type->id)->get();
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$repository->setUser($journal->user);
$native = Amount::getNativeCurrencyByUserGroup($journal->userGroup);
/** @var null|Transaction $source */
$source = $journal->transactions()->where('amount', '<', 0)->first();
/** @var null|Transaction $destination */
$destination = $journal->transactions()->where('amount', '>', 0)->first();
if (null === $source || null === $destination) {
continue;
}
if (null === $source->foreign_currency_id || null === $destination->foreign_currency_id) {
continue;
}
$sourceAccount = $source->account;
$destAccount = $destination->account;
if (null === $sourceAccount || null === $destAccount) {
continue;
}
$sourceCurrency = $repository->getAccountCurrency($sourceAccount) ?? $native;
$destCurrency = $repository->getAccountCurrency($destAccount) ?? $native;
if ($sourceCurrency->id === $destCurrency->id) {
Log::debug('Both accounts have the same currency. Removing foreign currency info.');
$source->foreign_currency_id = null;
$source->foreign_amount = null;
$source->save();
$destination->foreign_currency_id = null;
$destination->foreign_amount = null;
$destination->save();
continue;
}
// validate source
if ($destCurrency->id !== $source->foreign_currency_id) {
Log::debug(sprintf('Journal #%d: Transaction #%d refers to "%s" but should refer to "%s".', $journal->id, $source->id, $source->foreignCurrency->code, $destCurrency->code));
$source->foreign_currency_id = $destCurrency->id;
$source->save();
}
// validate destination:
if ($sourceCurrency->id !== $destination->foreign_currency_id) {
Log::debug(sprintf('Journal #%d: Transaction #%d refers to "%s" but should refer to "%s".', $journal->id, $destination->id, $destination->foreignCurrency->code, $sourceCurrency->code));
$destination->foreign_currency_id = $sourceCurrency->id;
$destination->save();
}
}
}
private function fixAutoBudgets(): void private function fixAutoBudgets(): void
{ {
$count = AutoBudget::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]); $count = AutoBudget::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]);
@@ -192,63 +251,4 @@ class CorrectsAmounts extends Command
return false; return false;
} }
private function correctTransfers(): void
{
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
$type = TransactionType::where('type', TransactionTypeEnum::TRANSFER->value)->first();
$journals = TransactionJournal::where('transaction_type_id', $type->id)->get();
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$repository->setUser($journal->user);
$native = Amount::getNativeCurrencyByUserGroup($journal->userGroup);
/** @var null|Transaction $source */
$source = $journal->transactions()->where('amount', '<', 0)->first();
/** @var null|Transaction $destination */
$destination = $journal->transactions()->where('amount', '>', 0)->first();
if (null === $source || null === $destination) {
continue;
}
if (null === $source->foreign_currency_id || null === $destination->foreign_currency_id) {
continue;
}
$sourceAccount = $source->account;
$destAccount = $destination->account;
if (null === $sourceAccount || null === $destAccount) {
continue;
}
$sourceCurrency = $repository->getAccountCurrency($sourceAccount) ?? $native;
$destCurrency = $repository->getAccountCurrency($destAccount) ?? $native;
if ($sourceCurrency->id === $destCurrency->id) {
Log::debug('Both accounts have the same currency. Removing foreign currency info.');
$source->foreign_currency_id = null;
$source->foreign_amount = null;
$source->save();
$destination->foreign_currency_id = null;
$destination->foreign_amount = null;
$destination->save();
continue;
}
// validate source
if ($destCurrency->id !== $source->foreign_currency_id) {
Log::debug(sprintf('Journal #%d: Transaction #%d refers to "%s" but should refer to "%s".', $journal->id, $source->id, $source->foreignCurrency->code, $destCurrency->code));
$source->foreign_currency_id = $destCurrency->id;
$source->save();
}
// validate destination:
if ($sourceCurrency->id !== $destination->foreign_currency_id) {
Log::debug(sprintf('Journal #%d: Transaction #%d refers to "%s" but should refer to "%s".', $journal->id, $destination->id, $destination->foreignCurrency->code, $sourceCurrency->code));
$destination->foreign_currency_id = $sourceCurrency->id;
$destination->save();
}
}
}
} }

View File

@@ -38,8 +38,8 @@ use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Models\Transaction; use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\UserGroup; use FireflyIII\Models\UserGroup;
use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface;
use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Preferences;
use FireflyIII\Support\Http\Api\ExchangeRateConverter; use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Console\Command; use Illuminate\Console\Command;

View File

@@ -25,9 +25,11 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Correction; namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Models\Transaction; use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Support\Models\AccountBalanceCalculator; use FireflyIII\Support\Models\AccountBalanceCalculator;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -47,7 +49,12 @@ class CorrectsUnevenAmount extends Command
public function handle(): int public function handle(): int
{ {
$this->count = 0; $this->count = 0;
// convert transfers with foreign currency info where the amount is NOT uneven (it should be)
$this->convertOldStyleTransfers(); $this->convertOldStyleTransfers();
// convert old-style transactions between assets and liabilities.
$this->convertOldStyleTransactions();
$this->fixUnevenAmounts(); $this->fixUnevenAmounts();
$this->matchCurrencies(); $this->matchCurrencies();
if (true === config('firefly.feature_flags.running_balance_column')) { if (true === config('firefly.feature_flags.running_balance_column')) {
@@ -72,8 +79,6 @@ class CorrectsUnevenAmount extends Command
; ;
$count = 0; $count = 0;
Log::debug(sprintf('Found %d potential journal(s)', $transactions->count()));
/** @var Transaction $transaction */ /** @var Transaction $transaction */
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {
/** @var null|TransactionJournal $journal */ /** @var null|TransactionJournal $journal */
@@ -115,10 +120,15 @@ class CorrectsUnevenAmount extends Command
++$count; ++$count;
} }
} }
if (0 === $count) {
return;
}
$this->friendlyPositive(sprintf('Fixed %d transfer(s) with unbalanced amounts.', $count));
} }
private function fixUnevenAmounts(): void private function fixUnevenAmounts(): void
{ {
Log::debug('fixUnevenAmounts()');
$journals = DB::table('transactions') $journals = DB::table('transactions')
->groupBy('transaction_journal_id') ->groupBy('transaction_journal_id')
->whereNull('deleted_at') ->whereNull('deleted_at')
@@ -207,8 +217,8 @@ class CorrectsUnevenAmount extends Command
} }
// may still be able to salvage this journal if it is a transfer with foreign currency info // may still be able to salvage this journal if it is a transfer with foreign currency info
if ($this->isForeignCurrencyTransfer($journal)) { if ($this->isForeignCurrencyTransfer($journal) || $this->isBetweenAssetAndLiability($journal)) {
Log::debug(sprintf('Can skip foreign currency transfer #%d.', $journal->id)); Log::debug(sprintf('Can skip foreign currency transfer / asset+liability transaction #%d.', $journal->id));
return; return;
} }
@@ -271,13 +281,13 @@ class CorrectsUnevenAmount extends Command
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
if (!$this->isForeignCurrencyTransfer($journal)) { if (!$this->isForeignCurrencyTransfer($journal) && !$this->isBetweenAssetAndLiability($journal)) {
Transaction::where('transaction_journal_id', $journal->id)->update(['transaction_currency_id' => $journal->transaction_currency_id]); Transaction::where('transaction_journal_id', $journal->id)->update(['transaction_currency_id' => $journal->transaction_currency_id]);
++$count; ++$count;
continue; continue;
} }
Log::debug(sprintf('Can skip foreign currency transfer #%d.', $journal->id)); Log::debug(sprintf('Can skip foreign currency transfer or transaction between asset and liability #%d.', $journal->id));
} }
if (0 === $count) { if (0 === $count) {
return; return;
@@ -285,4 +295,155 @@ class CorrectsUnevenAmount extends Command
$this->friendlyPositive(sprintf('Fixed %d journal(s) with mismatched currencies.', $journals->count())); $this->friendlyPositive(sprintf('Fixed %d journal(s) with mismatched currencies.', $journals->count()));
} }
private function isBetweenAssetAndLiability(TransactionJournal $journal): bool
{
/** @var Transaction $sourceTransaction */
$sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
/** @var Transaction $destinationTransaction */
$destinationTransaction = $journal->transactions()->where('amount', '>', 0)->first();
if (null === $sourceTransaction || null === $destinationTransaction) {
Log::warning('Either transaction is false, stop.');
return false;
}
if (null === $sourceTransaction->foreign_amount || null === $destinationTransaction->foreign_amount) {
Log::warning('Either foreign amount is false, stop.');
return false;
}
$source = $sourceTransaction->account;
$destination = $destinationTransaction->account;
if (null === $source || null === $destination) {
Log::warning('Either is false, stop.');
return false;
}
$sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
// source is liability, destination is asset
if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) {
Log::debug('Source is a liability account, destination is an asset account, return TRUE.');
return true;
}
// source is asset, destination is liability
if (in_array($destination->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $source->accountType->type) {
Log::debug('Destination is a liability account, source is an asset account, return TRUE.');
return true;
}
return false;
}
private function convertOldStyleTransactions(): void
{
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
Log::debug('convertOldStyleTransactions()');
$count = 0;
$transactions = Transaction::distinct()
->leftJoin('transaction_journals', 'transaction_journals.id', 'transactions.transaction_journal_id')
->leftJoin('transaction_types', 'transaction_types.id', 'transaction_journals.transaction_type_id')
->leftJoin('accounts', 'accounts.id', 'transactions.account_id')
->leftJoin('account_types', 'account_types.id', 'accounts.account_type_id')
->whereNot('transaction_types.type', TransactionTypeEnum::TRANSFER->value)
->whereNotNull('foreign_currency_id')
->whereNotNull('foreign_amount')
->whereIn('account_types.type', [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value])
->get(['transactions.transaction_journal_id'])
;
/** @var Transaction $transaction */
foreach ($transactions as $transaction) {
/** @var null|TransactionJournal $journal */
$journal = TransactionJournal::find($transaction->transaction_journal_id);
$repository->setUser($journal->user);
if (null === $journal) {
Log::debug('Found no journal, continue.');
continue;
}
if (!$this->isBetweenAssetAndLiability($journal)) {
Log::debug('Not between asset and liability, continue.');
continue;
}
$source = $journal->transactions()->where('amount', '<', 0)->first();
$destination = $journal->transactions()->where('amount', '>', 0)->first();
$sourceAccount = $source->account;
$destAccount = $destination->account;
$sourceCurrency = $repository->getAccountCurrency($sourceAccount);
$destCurrency = $repository->getAccountCurrency($destAccount);
if (null === $source || null === $destination) {
Log::debug('Either transaction is NULL, continue.');
continue;
}
if (0 === bccomp($source->amount, $source->foreign_amount) && 0 === bccomp($source->foreign_amount, $source->amount)) {
Log::debug('Already fixed, continue.');
continue;
}
// source transaction. Switch info when does not match.
if ((int) $source->transaction_currency_id !== (int) $sourceCurrency->id) {
Log::debug(sprintf('Ready to swap data in transaction #%d.', $source->id));
// swap amounts.
$amount = $source->amount;
$currency = $source->transaction_currency_id;
$source->amount = $source->foreign_amount;
$source->transaction_currency_id = $source->foreign_currency_id;
$source->foreign_amount = $amount;
$source->foreign_currency_id = $currency;
$source->saveQuietly();
$source->refresh();
// Log::debug(sprintf('source->amount = %s', $source->amount));
// Log::debug(sprintf('source->transaction_currency_id = %s', $source->transaction_currency_id));
// Log::debug(sprintf('source->foreign_amount = %s', $source->foreign_amount));
// Log::debug(sprintf('source->foreign_currency_id = %s', $source->foreign_currency_id));
++$count;
}
// same but for destination
if ((int) $destination->transaction_currency_id !== (int) $destCurrency->id) {
++$count;
Log::debug(sprintf('Ready to swap data in transaction #%d.', $destination->id));
// swap amounts.
$amount = $destination->amount;
$currency = $destination->transaction_currency_id;
$destination->amount = $destination->foreign_amount;
$destination->transaction_currency_id = $destination->foreign_currency_id;
$destination->foreign_amount = $amount;
$destination->foreign_currency_id = $currency;
$destination->balance_dirty = true;
$destination->saveQuietly();
$destination->refresh();
// Log::debug(sprintf('destination->amount = %s', $destination->amount));
// Log::debug(sprintf('destination->transaction_currency_id = %s', $destination->transaction_currency_id));
// Log::debug(sprintf('destination->foreign_amount = %s', $destination->foreign_amount));
// Log::debug(sprintf('destination->foreign_currency_id = %s', $destination->foreign_currency_id));
}
// // only fix the destination transaction
// $destination->foreign_currency_id = $source->transaction_currency_id;
// $destination->foreign_amount = app('steam')->positive($source->amount);
// $destination->transaction_currency_id = $source->foreign_currency_id;
// $destination->amount = app('steam')->positive($source->foreign_amount);
// $destination->balance_dirty = true;
// $source->balance_dirty = true;
// $destination->save();
// $source->save();
// $this->friendlyWarning(sprintf('Corrected foreign amounts of transaction #%d.', $journal->id));
}
if (0 === $count) {
return;
}
$this->friendlyPositive(sprintf('Fixed %d journal(s) with unbalanced amounts.', $count));
}
} }

View File

@@ -273,7 +273,7 @@ class ExportsData extends Command
*/ */
private function exportData(array $options, array $data): void private function exportData(array $options, array $data): void
{ {
$date = \Safe\date('Y_m_d'); $date = date('Y_m_d');
foreach ($data as $key => $content) { foreach ($data as $key => $content) {
$file = sprintf('%s%s_%s.csv', $options['directory'], $date, $key); $file = sprintf('%s%s_%s.csv', $options['directory'], $date, $key);
if (false === $options['force'] && file_exists($file)) { if (false === $options['force'] && file_exists($file)) {

View File

@@ -30,13 +30,6 @@ class ValidatesEnvironmentVariables extends Command
{ {
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'integrity:validates-environment-variables';
/** /**
* The console command description. * The console command description.
* *
@@ -44,6 +37,13 @@ class ValidatesEnvironmentVariables extends Command
*/ */
protected $description = 'Makes sure you use the correct variables.'; protected $description = 'Makes sure you use the correct variables.';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'integrity:validates-environment-variables';
/** /**
* Execute the console command. * Execute the console command.
*/ */

View File

@@ -111,8 +111,8 @@ class OutputsInstructions extends Command
*/ */
private function showLogo(): void private function showLogo(): void
{ {
$today = \Safe\date('m-d'); $today = date('m-d');
$month = \Safe\date('m'); $month = date('m');
// variation in colors and effects just because I can! // variation in colors and effects just because I can!
// default is Ukraine flag: // default is Ukraine flag:
$colors = ['blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow', 'default', 'default']; $colors = ['blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow', 'default', 'default'];
@@ -172,6 +172,13 @@ class OutputsInstructions extends Command
} }
} }
private function donationText(): void
{
$this->boxed('Did you know you can support the development of Firefly III?');
$this->boxed('You can donate in many ways, like GitHub Sponsors or Patreon.');
$this->boxed('For more information, please visit https://bit.ly/donate-to-Firefly-III');
}
/** /**
* Render instructions. * Render instructions.
*/ */
@@ -225,11 +232,4 @@ class OutputsInstructions extends Command
$this->boxed(''); $this->boxed('');
$this->showLine(); $this->showLine();
} }
private function donationText(): void
{
$this->boxed('Did you know you can support the development of Firefly III?');
$this->boxed('You can donate in many ways, like GitHub Sponsors or Patreon.');
$this->boxed('For more information, please visit https://bit.ly/donate-to-Firefly-III');
}
} }

View File

@@ -31,13 +31,6 @@ class RecalculatesRunningBalance extends Command
{ {
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'firefly-iii:refresh-running-balance {--F|force : Force the execution of this command.}';
/** /**
* The console command description. * The console command description.
* *
@@ -45,6 +38,13 @@ class RecalculatesRunningBalance extends Command
*/ */
protected $description = 'Refreshes all running balances. May take a long time to run if forced.'; protected $description = 'Refreshes all running balances. May take a long time to run if forced.';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'firefly-iii:refresh-running-balance {--F|force : Force the execution of this command.}';
/** /**
* Execute the console command. * Execute the console command.
*/ */

View File

@@ -150,6 +150,23 @@ class Cron extends Command
} }
} }
private function checkForUpdates(bool $force): void
{
$updateCheck = new UpdateCheckCronjob();
$updateCheck->setForce($force);
$updateCheck->fire();
if ($updateCheck->jobErrored) {
$this->friendlyError(sprintf('Error in "update check" cron: %s', $updateCheck->message));
}
if ($updateCheck->jobFired) {
$this->friendlyInfo(sprintf('"Update check" cron fired: %s', $updateCheck->message));
}
if ($updateCheck->jobSucceeded) {
$this->friendlyPositive(sprintf('"Update check" cron ran with success: %s', $updateCheck->message));
}
}
/** /**
* @throws FireflyException * @throws FireflyException
*/ */
@@ -221,21 +238,4 @@ class Cron extends Command
$this->friendlyPositive(sprintf('"Send bill warnings" cron ran with success: %s', $autoBudget->message)); $this->friendlyPositive(sprintf('"Send bill warnings" cron ran with success: %s', $autoBudget->message));
} }
} }
private function checkForUpdates(bool $force): void
{
$updateCheck = new UpdateCheckCronjob();
$updateCheck->setForce($force);
$updateCheck->fire();
if ($updateCheck->jobErrored) {
$this->friendlyError(sprintf('Error in "update check" cron: %s', $updateCheck->message));
}
if ($updateCheck->jobFired) {
$this->friendlyInfo(sprintf('"Update check" cron fired: %s', $updateCheck->message));
}
if ($updateCheck->jobSucceeded) {
$this->friendlyPositive(sprintf('"Update check" cron ran with success: %s', $updateCheck->message));
}
}
} }

View File

@@ -24,7 +24,14 @@ declare(strict_types=1);
namespace FireflyIII\Console\Commands\Upgrade; namespace FireflyIII\Console\Commands\Upgrade;
\Safe\set_time_limit(0); use Illuminate\Support\Facades\Log;
use Safe\Exceptions\InfoException;
try {
\Safe\set_time_limit(0);
} catch (InfoException) {
Log::warning('set_time_limit returned false. This could be an issue, unless you also run XDebug.');
}
use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command; use Illuminate\Console\Command;

View File

@@ -32,6 +32,7 @@ use Illuminate\Support\Facades\Artisan;
class UpgradesNativeAmounts extends Command class UpgradesNativeAmounts extends Command
{ {
use ShowsFriendlyMessages; use ShowsFriendlyMessages;
public const string CONFIG_NAME = '620_native_amounts'; public const string CONFIG_NAME = '620_native_amounts';
protected $description = 'Runs the native amounts calculations.'; protected $description = 'Runs the native amounts calculations.';
@@ -61,7 +62,7 @@ class UpgradesNativeAmounts extends Command
{ {
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
if (null !== $configVar) { if (null !== $configVar) {
return (bool)$configVar->data; return (bool) $configVar->data;
} }
return false; return false;

View File

@@ -366,8 +366,8 @@ class UpgradesToGroups extends Command
{ {
$groupId = DB::table('transaction_groups')->insertGetId( $groupId = DB::table('transaction_groups')->insertGetId(
[ [
'created_at' => \Safe\date('Y-m-d H:i:s'), 'created_at' => date('Y-m-d H:i:s'),
'updated_at' => \Safe\date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'),
'title' => null, 'title' => null,
'user_id' => $array['user_id'], 'user_id' => $array['user_id'],
] ]

View File

@@ -32,7 +32,9 @@ use Illuminate\Queue\SerializesModels;
*/ */
class DestroyedTransactionLink extends Event class DestroyedTransactionLink extends Event
{ {
use SerializesModels; // @phpstan-ignore-line use SerializesModels;
// @phpstan-ignore-line
/** /**
* DestroyedTransactionLink constructor. * DestroyedTransactionLink constructor.

View File

@@ -37,8 +37,8 @@ class ChangedAmount extends Event
{ {
use SerializesModels; use SerializesModels;
public string $amount; public string $amount;
public PiggyBank $piggyBank; public PiggyBank $piggyBank;
/** /**
* Create a new event instance. * Create a new event instance.

View File

@@ -32,6 +32,7 @@ use Illuminate\Queue\SerializesModels;
class MFABackupFewLeft extends Event class MFABackupFewLeft extends Event
{ {
use SerializesModels; use SerializesModels;
public User $user; public User $user;
public function __construct(null|Authenticatable|User $user, public int $count) public function __construct(null|Authenticatable|User $user, public int $count)

View File

@@ -32,6 +32,7 @@ use Illuminate\Queue\SerializesModels;
class MFAManyFailedAttempts extends Event class MFAManyFailedAttempts extends Event
{ {
use SerializesModels; use SerializesModels;
public User $user; public User $user;
public function __construct(null|Authenticatable|User $user, public int $count) public function __construct(null|Authenticatable|User $user, public int $count)

View File

@@ -31,7 +31,7 @@ class OwnerTestNotificationChannel
{ {
use SerializesModels; use SerializesModels;
public string $channel; public string $channel;
/** /**
* Create a new event instance. * Create a new event instance.

View File

@@ -45,6 +45,7 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
// temp
/** /**
* Class Handler * Class Handler
*/ */
@@ -227,7 +228,7 @@ class Handler extends ExceptionHandler
$data = [ $data = [
'class' => $e::class, 'class' => $e::class,
'errorMessage' => $e->getMessage(), 'errorMessage' => $e->getMessage(),
'time' => \Safe\date('r'), 'time' => date('r'),
'stackTrace' => $e->getTraceAsString(), 'stackTrace' => $e->getTraceAsString(),
'file' => $e->getFile(), 'file' => $e->getFile(),
'line' => $e->getLine(), 'line' => $e->getLine(),

View File

@@ -34,7 +34,7 @@ use FireflyIII\User;
*/ */
class TagFactory class TagFactory
{ {
private User $user; private User $user;
private UserGroup $userGroup; private UserGroup $userGroup;
public function findOrCreate(string $tag): ?Tag public function findOrCreate(string $tag): ?Tag

View File

@@ -36,8 +36,8 @@ use FireflyIII\User;
class TransactionGroupFactory class TransactionGroupFactory
{ {
private readonly TransactionJournalFactory $journalFactory; private readonly TransactionJournalFactory $journalFactory;
private User $user; private User $user;
private UserGroup $userGroup; private UserGroup $userGroup;
/** /**
* TransactionGroupFactory constructor. * TransactionGroupFactory constructor.

View File

@@ -25,6 +25,7 @@ declare(strict_types=1);
namespace FireflyIII\Factory; namespace FireflyIII\Factory;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Exceptions\DuplicateTransactionException; use FireflyIII\Exceptions\DuplicateTransactionException;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
@@ -39,9 +40,9 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Repositories\TransactionType\TransactionTypeRepositoryInterface; use FireflyIII\Repositories\TransactionType\TransactionTypeRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Services\Internal\Destroy\JournalDestroyService; use FireflyIII\Services\Internal\Destroy\JournalDestroyService;
use FireflyIII\Services\Internal\Support\JournalServiceTrait; use FireflyIII\Services\Internal\Support\JournalServiceTrait;
use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Facades\FireflyConfig;
@@ -70,7 +71,7 @@ class TransactionJournalFactory
private PiggyBankRepositoryInterface $piggyRepository; private PiggyBankRepositoryInterface $piggyRepository;
private TransactionTypeRepositoryInterface $typeRepository; private TransactionTypeRepositoryInterface $typeRepository;
private User $user; private User $user;
private UserGroup $userGroup; private UserGroup $userGroup;
/** /**
* Constructor. * Constructor.
@@ -101,15 +102,15 @@ class TransactionJournalFactory
*/ */
public function create(array $data): Collection public function create(array $data): Collection
{ {
app('log')->debug('Now in TransactionJournalFactory::create()'); Log::debug('Now in TransactionJournalFactory::create()');
// convert to special object. // convert to special object.
$dataObject = new NullArrayObject($data); $dataObject = new NullArrayObject($data);
app('log')->debug('Start of TransactionJournalFactory::create()'); Log::debug('Start of TransactionJournalFactory::create()');
$collection = new Collection(); $collection = new Collection();
$transactions = $dataObject['transactions'] ?? []; $transactions = $dataObject['transactions'] ?? [];
if (0 === count($transactions)) { if (0 === count($transactions)) {
app('log')->error('There are no transactions in the array, the TransactionJournalFactory cannot continue.'); Log::error('There are no transactions in the array, the TransactionJournalFactory cannot continue.');
return new Collection(); return new Collection();
} }
@@ -117,26 +118,26 @@ class TransactionJournalFactory
try { try {
/** @var array $row */ /** @var array $row */
foreach ($transactions as $index => $row) { foreach ($transactions as $index => $row) {
app('log')->debug(sprintf('Now creating journal %d/%d', $index + 1, count($transactions))); Log::debug(sprintf('Now creating journal %d/%d', $index + 1, count($transactions)));
$journal = $this->createJournal(new NullArrayObject($row)); $journal = $this->createJournal(new NullArrayObject($row));
if (null !== $journal) { if (null !== $journal) {
$collection->push($journal); $collection->push($journal);
} }
if (null === $journal) { if (null === $journal) {
app('log')->error('The createJournal() method returned NULL. This may indicate an error.'); Log::error('The createJournal() method returned NULL. This may indicate an error.');
} }
} }
} catch (DuplicateTransactionException $e) { } catch (DuplicateTransactionException $e) {
app('log')->warning('TransactionJournalFactory::create() caught a duplicate journal in createJournal()'); Log::warning('TransactionJournalFactory::create() caught a duplicate journal in createJournal()');
app('log')->error($e->getMessage()); Log::error($e->getMessage());
app('log')->error($e->getTraceAsString()); Log::error($e->getTraceAsString());
$this->forceDeleteOnError($collection); $this->forceDeleteOnError($collection);
throw new DuplicateTransactionException($e->getMessage(), 0, $e); throw new DuplicateTransactionException($e->getMessage(), 0, $e);
} catch (FireflyException $e) { } catch (FireflyException $e) {
app('log')->warning('TransactionJournalFactory::create() caught an exception.'); Log::warning('TransactionJournalFactory::create() caught an exception.');
app('log')->error($e->getMessage()); Log::error($e->getMessage());
app('log')->error($e->getTraceAsString()); Log::error($e->getTraceAsString());
$this->forceDeleteOnError($collection); $this->forceDeleteOnError($collection);
throw new FireflyException($e->getMessage(), 0, $e); throw new FireflyException($e->getMessage(), 0, $e);
@@ -156,6 +157,7 @@ class TransactionJournalFactory
*/ */
private function createJournal(NullArrayObject $row): ?TransactionJournal private function createJournal(NullArrayObject $row): ?TransactionJournal
{ {
Log::debug('Now in TransactionJournalFactory::createJournal()');
$row['import_hash_v2'] = $this->hashArray($row); $row['import_hash_v2'] = $this->hashArray($row);
$this->errorIfDuplicate($row['import_hash_v2']); $this->errorIfDuplicate($row['import_hash_v2']);
@@ -164,7 +166,11 @@ class TransactionJournalFactory
$type = $this->typeRepository->findTransactionType(null, $row['type']); $type = $this->typeRepository->findTransactionType(null, $row['type']);
$carbon = $row['date'] ?? today(config('app.timezone')); $carbon = $row['date'] ?? today(config('app.timezone'));
$order = $row['order'] ?? 0; $order = $row['order'] ?? 0;
Log::debug('Find currency or return default.');
$currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']); $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']);
Log::debug('Find foreign currency or return NULL.');
$foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']);
$bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']); $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']);
$billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && null !== $bill ? $bill->id : null; $billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && null !== $bill ? $bill->id : null;
@@ -183,8 +189,8 @@ class TransactionJournalFactory
// validate source and destination using a new Validator. // validate source and destination using a new Validator.
$this->validateAccounts($row); $this->validateAccounts($row);
} catch (FireflyException $e) { } catch (FireflyException $e) {
app('log')->error('Could not validate source or destination.'); Log::error('Could not validate source or destination.');
app('log')->error($e->getMessage()); Log::error($e->getMessage());
return null; return null;
} }
@@ -207,11 +213,12 @@ class TransactionJournalFactory
'bic' => $row['destination_bic'], 'bic' => $row['destination_bic'],
'currency_id' => $currency->id, 'currency_id' => $currency->id,
]; ];
app('log')->debug('Source info:', $sourceInfo); Log::debug('Source info:', $sourceInfo);
app('log')->debug('Destination info:', $destInfo); Log::debug('Destination info:', $destInfo);
$sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo); $sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo);
$destinationAccount = $this->getAccount($type->type, 'destination', $destInfo); $destinationAccount = $this->getAccount($type->type, 'destination', $destInfo);
app('log')->debug('Done with getAccount(2x)'); Log::debug('Done with getAccount(2x)');
// this is the moment for a reconciliation sanity check (again). // this is the moment for a reconciliation sanity check (again).
if (TransactionTypeEnum::RECONCILIATION->value === $type->type) { if (TransactionTypeEnum::RECONCILIATION->value === $type->type) {
@@ -223,7 +230,8 @@ class TransactionJournalFactory
$foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount); $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount);
$description = $this->getDescription($description); $description = $this->getDescription($description);
app('log')->debug(sprintf('Date: %s (%s)', $carbon->toW3cString(), $carbon->getTimezone()->getName())); Log::debug(sprintf('Currency is #%d "%s", foreign currency is #%d "%s"', $currency->id, $currency->code, $foreignCurrency?->id, $foreignCurrency));
Log::debug(sprintf('Date: %s (%s)', $carbon->toW3cString(), $carbon->getTimezone()->getName()));
/** Create a basic journal. */ /** Create a basic journal. */
$journal = TransactionJournal::create( $journal = TransactionJournal::create(
@@ -241,7 +249,7 @@ class TransactionJournalFactory
'completed' => 0, 'completed' => 0,
] ]
); );
app('log')->debug(sprintf('Created new journal #%d: "%s"', $journal->id, $journal->description)); Log::debug(sprintf('Created new journal #%d: "%s"', $journal->id, $journal->description));
/** Create two transactions. */ /** Create two transactions. */
$transactionFactory = app(TransactionFactory::class); $transactionFactory = app(TransactionFactory::class);
@@ -255,7 +263,7 @@ class TransactionJournalFactory
try { try {
$negative = $transactionFactory->createNegative((string) $row['amount'], (string) $row['foreign_amount']); $negative = $transactionFactory->createNegative((string) $row['amount'], (string) $row['foreign_amount']);
} catch (FireflyException $e) { } catch (FireflyException $e) {
app('log')->error(sprintf('Exception creating negative transaction: %s', $e->getMessage())); Log::error(sprintf('Exception creating negative transaction: %s', $e->getMessage()));
$this->forceDeleteOnError(new Collection([$journal])); $this->forceDeleteOnError(new Collection([$journal]));
throw new FireflyException($e->getMessage(), 0, $e); throw new FireflyException($e->getMessage(), 0, $e);
@@ -277,7 +285,7 @@ class TransactionJournalFactory
$amount = (string) $row['amount']; $amount = (string) $row['amount'];
$foreignAmount = (string) $row['foreign_amount']; $foreignAmount = (string) $row['foreign_amount'];
if (null !== $foreignCurrency && $foreignCurrency->id !== $currency->id if (null !== $foreignCurrency && $foreignCurrency->id !== $currency->id
&& TransactionTypeEnum::TRANSFER->value === $type->type && (TransactionTypeEnum::TRANSFER->value === $type->type || $this->isBetweenAssetAndLiability($sourceAccount, $destinationAccount))
) { ) {
$transactionFactory->setCurrency($foreignCurrency); $transactionFactory->setCurrency($foreignCurrency);
$transactionFactory->setForeignCurrency($currency); $transactionFactory->setForeignCurrency($currency);
@@ -289,7 +297,7 @@ class TransactionJournalFactory
try { try {
$transactionFactory->createPositive($amount, $foreignAmount); $transactionFactory->createPositive($amount, $foreignAmount);
} catch (FireflyException $e) { } catch (FireflyException $e) {
app('log')->error(sprintf('Exception creating positive transaction: %s', $e->getMessage())); Log::error(sprintf('Exception creating positive transaction: %s', $e->getMessage()));
$this->forceTrDelete($negative); $this->forceTrDelete($negative);
$this->forceDeleteOnError(new Collection([$journal])); $this->forceDeleteOnError(new Collection([$journal]));
@@ -317,11 +325,11 @@ class TransactionJournalFactory
try { try {
$json = \Safe\json_encode($dataRow, JSON_THROW_ON_ERROR); $json = \Safe\json_encode($dataRow, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) { } catch (\JsonException $e) {
app('log')->error(sprintf('Could not encode dataRow: %s', $e->getMessage())); Log::error(sprintf('Could not encode dataRow: %s', $e->getMessage()));
$json = microtime(); $json = microtime();
} }
$hash = hash('sha256', $json); $hash = hash('sha256', $json);
app('log')->debug(sprintf('The hash is: %s', $hash), $dataRow); Log::debug(sprintf('The hash is: %s', $hash), $dataRow);
return $hash; return $hash;
} }
@@ -333,11 +341,11 @@ class TransactionJournalFactory
*/ */
private function errorIfDuplicate(string $hash): void private function errorIfDuplicate(string $hash): void
{ {
app('log')->debug(sprintf('In errorIfDuplicate(%s)', $hash)); Log::debug(sprintf('In errorIfDuplicate(%s)', $hash));
if (false === $this->errorOnHash) { if (false === $this->errorOnHash) {
return; return;
} }
app('log')->debug('Will verify duplicate!'); Log::debug('Will verify duplicate!');
/** @var null|TransactionJournalMeta $result */ /** @var null|TransactionJournalMeta $result */
$result = TransactionJournalMeta::withTrashed() $result = TransactionJournalMeta::withTrashed()
@@ -349,7 +357,7 @@ class TransactionJournalFactory
->first(['journal_meta.*']) ->first(['journal_meta.*'])
; ;
if (null !== $result) { if (null !== $result) {
app('log')->warning(sprintf('Found a duplicate in errorIfDuplicate because hash %s is not unique!', $hash)); Log::warning(sprintf('Found a duplicate in errorIfDuplicate because hash %s is not unique!', $hash));
$journal = $result->transactionJournal()->withTrashed()->first(); $journal = $result->transactionJournal()->withTrashed()->first();
$group = $journal?->transactionGroup()->withTrashed()->first(); $group = $journal?->transactionGroup()->withTrashed()->first();
$groupId = (int) $group?->id; $groupId = (int) $group?->id;
@@ -363,7 +371,7 @@ class TransactionJournalFactory
*/ */
private function validateAccounts(NullArrayObject $data): void private function validateAccounts(NullArrayObject $data): void
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
$transactionType = $data['type'] ?? 'invalid'; $transactionType = $data['type'] ?? 'invalid';
$this->accountValidator->setUser($this->user); $this->accountValidator->setUser($this->user);
$this->accountValidator->setTransactionType($transactionType); $this->accountValidator->setTransactionType($transactionType);
@@ -381,7 +389,7 @@ class TransactionJournalFactory
if (false === $validSource) { if (false === $validSource) {
throw new FireflyException(sprintf('Source: %s', $this->accountValidator->sourceError)); throw new FireflyException(sprintf('Source: %s', $this->accountValidator->sourceError));
} }
app('log')->debug('Source seems valid.'); Log::debug('Source seems valid.');
// validate destination account // validate destination account
$array = [ $array = [
@@ -414,42 +422,30 @@ class TransactionJournalFactory
$this->accountRepository->setUser($this->user); $this->accountRepository->setUser($this->user);
} }
public function setUserGroup(UserGroup $userGroup): void
{
$this->userGroup = $userGroup;
$this->currencyRepository->setUserGroup($userGroup);
$this->tagFactory->setUserGroup($userGroup);
$this->billRepository->setUserGroup($userGroup);
$this->budgetRepository->setUserGroup($userGroup);
$this->categoryRepository->setUserGroup($userGroup);
$this->piggyRepository->setUserGroup($userGroup);
$this->accountRepository->setUserGroup($userGroup);
}
private function reconciliationSanityCheck(?Account $sourceAccount, ?Account $destinationAccount): array private function reconciliationSanityCheck(?Account $sourceAccount, ?Account $destinationAccount): array
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
if (null !== $sourceAccount && null !== $destinationAccount) { if (null !== $sourceAccount && null !== $destinationAccount) {
app('log')->debug('Both accounts exist, simply return them.'); Log::debug('Both accounts exist, simply return them.');
return [$sourceAccount, $destinationAccount]; return [$sourceAccount, $destinationAccount];
} }
if (null === $destinationAccount) { if (null === $destinationAccount) {
app('log')->debug('Destination account is NULL, source account is not.'); Log::debug('Destination account is NULL, source account is not.');
$account = $this->accountRepository->getReconciliation($sourceAccount); $account = $this->accountRepository->getReconciliation($sourceAccount);
app('log')->debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type)); Log::debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type));
return [$sourceAccount, $account]; return [$sourceAccount, $account];
} }
if (null === $sourceAccount) { // @phpstan-ignore-line if (null === $sourceAccount) { // @phpstan-ignore-line
app('log')->debug('Source account is NULL, destination account is not.'); Log::debug('Source account is NULL, destination account is not.');
$account = $this->accountRepository->getReconciliation($destinationAccount); $account = $this->accountRepository->getReconciliation($destinationAccount);
app('log')->debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type)); Log::debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type));
return [$account, $destinationAccount]; return [$account, $destinationAccount];
} }
app('log')->debug('Unused fallback'); // @phpstan-ignore-line Log::debug('Unused fallback'); // @phpstan-ignore-line
return [$sourceAccount, $destinationAccount]; return [$sourceAccount, $destinationAccount];
} }
@@ -459,7 +455,15 @@ class TransactionJournalFactory
*/ */
private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency
{ {
app('log')->debug('Now in getCurrencyByAccount()'); Log::debug('Now in getCurrencyByAccount()');
/*
* Deze functie moet bij een transactie van liability naar asset wel degelijk de currency
* van de liability teruggeven en niet die van de destination. Fix voor #10265
*/
if ($this->isBetweenAssetAndLiability($source, $destination) && TransactionTypeEnum::DEPOSIT->value === $type) {
return $this->getCurrency($currency, $source);
}
return match ($type) { return match ($type) {
default => $this->getCurrency($currency, $source), default => $this->getCurrency($currency, $source),
@@ -472,7 +476,7 @@ class TransactionJournalFactory
*/ */
private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency
{ {
app('log')->debug('Now in getCurrency()'); Log::debug(sprintf('Now in getCurrency(#%d, "%s")', $currency->id, $account->name));
/** @var null|TransactionCurrency $preference */ /** @var null|TransactionCurrency $preference */
$preference = $this->accountRepository->getAccountCurrency($account); $preference = $this->accountRepository->getAccountCurrency($account);
@@ -481,7 +485,7 @@ class TransactionJournalFactory
return app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); return app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup);
} }
$result = $preference ?? $currency; $result = $preference ?? $currency;
app('log')->debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name)); Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name));
return $result; return $result;
} }
@@ -491,6 +495,7 @@ class TransactionJournalFactory
*/ */
private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency
{ {
Log::debug(sprintf('Now in compareCurrencies("%s", "%s")', $currency?->code, $foreignCurrency?->code));
if (null === $currency) { if (null === $currency) {
return null; return null;
} }
@@ -506,6 +511,7 @@ class TransactionJournalFactory
*/ */
private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency
{ {
Log::debug(sprintf('Now in getForeignByAccount("%s", #%d, "%s")', $type, $foreignCurrency?->id, $destination->name));
if (TransactionTypeEnum::TRANSFER->value === $type) { if (TransactionTypeEnum::TRANSFER->value === $type) {
return $this->getCurrency($foreignCurrency, $destination); return $this->getCurrency($foreignCurrency, $destination);
} }
@@ -526,12 +532,12 @@ class TransactionJournalFactory
*/ */
private function forceDeleteOnError(Collection $collection): void private function forceDeleteOnError(Collection $collection): void
{ {
app('log')->debug(sprintf('forceDeleteOnError on collection size %d item(s)', $collection->count())); Log::debug(sprintf('forceDeleteOnError on collection size %d item(s)', $collection->count()));
$service = app(JournalDestroyService::class); $service = app(JournalDestroyService::class);
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($collection as $journal) { foreach ($collection as $journal) {
app('log')->debug(sprintf('forceDeleteOnError on journal #%d', $journal->id)); Log::debug(sprintf('forceDeleteOnError on journal #%d', $journal->id));
$service->destroy($journal); $service->destroy($journal);
} }
} }
@@ -546,17 +552,17 @@ class TransactionJournalFactory
*/ */
private function storePiggyEvent(TransactionJournal $journal, NullArrayObject $data): void private function storePiggyEvent(TransactionJournal $journal, NullArrayObject $data): void
{ {
app('log')->debug('Will now store piggy event.'); Log::debug('Will now store piggy event.');
$piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']); $piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']);
if (null !== $piggyBank) { if (null !== $piggyBank) {
$this->piggyEventFactory->create($journal, $piggyBank); $this->piggyEventFactory->create($journal, $piggyBank);
app('log')->debug('Create piggy event.'); Log::debug('Create piggy event.');
return; return;
} }
app('log')->debug('Create no piggy event'); Log::debug('Create no piggy event');
} }
private function storeMetaFields(TransactionJournal $journal, NullArrayObject $transaction): void private function storeMetaFields(TransactionJournal $journal, NullArrayObject $transaction): void
@@ -575,11 +581,11 @@ class TransactionJournalFactory
]; ];
if ($data[$field] instanceof Carbon) { if ($data[$field] instanceof Carbon) {
$data[$field]->setTimezone(config('app.timezone')); $data[$field]->setTimezone(config('app.timezone'));
app('log')->debug(sprintf('%s Date: %s (%s)', $field, $data[$field], $data[$field]->timezone->getName())); Log::debug(sprintf('%s Date: %s (%s)', $field, $data[$field], $data[$field]->timezone->getName()));
$set['data'] = $data[$field]->format('Y-m-d H:i:s'); $set['data'] = $data[$field]->format('Y-m-d H:i:s');
} }
app('log')->debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data'])); Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data']));
/** @var TransactionJournalMetaFactory $factory */ /** @var TransactionJournalMetaFactory $factory */
$factory = app(TransactionJournalMetaFactory::class); $factory = app(TransactionJournalMetaFactory::class);
@@ -602,7 +608,40 @@ class TransactionJournalFactory
{ {
$this->errorOnHash = $errorOnHash; $this->errorOnHash = $errorOnHash;
if (true === $errorOnHash) { if (true === $errorOnHash) {
app('log')->info('Will trigger duplication alert for this journal.'); Log::info('Will trigger duplication alert for this journal.');
} }
} }
public function setUserGroup(UserGroup $userGroup): void
{
$this->userGroup = $userGroup;
$this->currencyRepository->setUserGroup($userGroup);
$this->tagFactory->setUserGroup($userGroup);
$this->billRepository->setUserGroup($userGroup);
$this->budgetRepository->setUserGroup($userGroup);
$this->categoryRepository->setUserGroup($userGroup);
$this->piggyRepository->setUserGroup($userGroup);
$this->accountRepository->setUserGroup($userGroup);
}
private function isBetweenAssetAndLiability(Account $source, Account $destination): bool
{
$sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
// source is liability, destination is asset
if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) {
Log::debug('Source is a liability account, destination is an asset account, return TRUE.');
return true;
}
// source is asset, destination is liability
if (in_array($destination->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $source->accountType->type) {
Log::debug('Destination is a liability account, source is an asset account, return TRUE.');
return true;
}
Log::debug('Not between asset and liability, return FALSE');
return false;
}
} }

View File

@@ -53,6 +53,55 @@ class UpdatedGroupEventHandler
} }
/**
* This method will make sure all source / destination accounts are the same.
*/
public function unifyAccounts(UpdatedTransactionGroup $updatedGroupEvent): void
{
$group = $updatedGroupEvent->transactionGroup;
if (1 === $group->transactionJournals->count()) {
return;
}
// first journal:
/** @var null|TransactionJournal $first */
$first = $group->transactionJournals()
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->orderBy('transaction_journals.description', 'DESC')
->first()
;
if (null === $first) {
Log::warning(sprintf('Group #%d has no transaction journals.', $group->id));
return;
}
$all = $group->transactionJournals()->get()->pluck('id')->toArray();
/** @var Account $sourceAccount */
$sourceAccount = $first->transactions()->where('amount', '<', '0')->first()->account;
/** @var Account $destAccount */
$destAccount = $first->transactions()->where('amount', '>', '0')->first()->account;
$type = $first->transactionType->type;
if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::WITHDRAWAL->value === $type) {
// set all source transactions to source account:
Transaction::whereIn('transaction_journal_id', $all)
->where('amount', '<', 0)->update(['account_id' => $sourceAccount->id])
;
}
if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::DEPOSIT->value === $type) {
// set all destination transactions to destination account:
Transaction::whereIn('transaction_journal_id', $all)
->where('amount', '>', 0)->update(['account_id' => $destAccount->id])
;
}
}
/** /**
* This method will check all the rules when a journal is updated. * This method will check all the rules when a journal is updated.
*/ */
@@ -119,55 +168,6 @@ class UpdatedGroupEventHandler
event(new RequestedSendWebhookMessages()); event(new RequestedSendWebhookMessages());
} }
/**
* This method will make sure all source / destination accounts are the same.
*/
public function unifyAccounts(UpdatedTransactionGroup $updatedGroupEvent): void
{
$group = $updatedGroupEvent->transactionGroup;
if (1 === $group->transactionJournals->count()) {
return;
}
// first journal:
/** @var null|TransactionJournal $first */
$first = $group->transactionJournals()
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->orderBy('transaction_journals.description', 'DESC')
->first()
;
if (null === $first) {
Log::warning(sprintf('Group #%d has no transaction journals.', $group->id));
return;
}
$all = $group->transactionJournals()->get()->pluck('id')->toArray();
/** @var Account $sourceAccount */
$sourceAccount = $first->transactions()->where('amount', '<', '0')->first()->account;
/** @var Account $destAccount */
$destAccount = $first->transactions()->where('amount', '>', '0')->first()->account;
$type = $first->transactionType->type;
if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::WITHDRAWAL->value === $type) {
// set all source transactions to source account:
Transaction::whereIn('transaction_journal_id', $all)
->where('amount', '<', 0)->update(['account_id' => $sourceAccount->id])
;
}
if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::DEPOSIT->value === $type) {
// set all destination transactions to destination account:
Transaction::whereIn('transaction_journal_id', $all)
->where('amount', '>', 0)->update(['account_id' => $destAccount->id])
;
}
}
private function updateRunningBalance(UpdatedTransactionGroup $event): void private function updateRunningBalance(UpdatedTransactionGroup $event): void
{ {
Log::debug(__METHOD__); Log::debug(__METHOD__);

View File

@@ -73,7 +73,7 @@ class VersionCheckEventHandler
$diff = $now - $lastCheckTime->data; $diff = $now - $lastCheckTime->data;
Log::debug(sprintf('Last check time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff)); Log::debug(sprintf('Last check time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff));
if ($diff < 604800) { if ($diff < 604800) {
Log::debug(sprintf('Checked for updates less than a week ago (on %s).', \Safe\date('Y-m-d H:i:s', $lastCheckTime->data))); Log::debug(sprintf('Checked for updates less than a week ago (on %s).', date('Y-m-d H:i:s', $lastCheckTime->data)));
return; return;
} }
@@ -105,7 +105,7 @@ class VersionCheckEventHandler
$diff = $now - $lastCheckTime->data; $diff = $now - $lastCheckTime->data;
Log::debug(sprintf('Last warning time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff)); Log::debug(sprintf('Last warning time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff));
if ($diff < 604800 * 4) { if ($diff < 604800 * 4) {
Log::debug(sprintf('Warned about updates less than four weeks ago (on %s).', \Safe\date('Y-m-d H:i:s', $lastCheckTime->data))); Log::debug(sprintf('Warned about updates less than four weeks ago (on %s).', date('Y-m-d H:i:s', $lastCheckTime->data)));
return; return;
} }

View File

@@ -29,8 +29,8 @@ use FireflyIII\Models\Attachment;
use FireflyIII\Models\Transaction; use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface;
use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Facades\Amount;
use FireflyIII\Support\Http\Api\ExchangeRateConverter; use FireflyIII\Support\Http\Api\ExchangeRateConverter;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;

View File

@@ -37,12 +37,6 @@ class AutoBudgetObserver
$this->updateNativeAmount($autoBudget); $this->updateNativeAmount($autoBudget);
} }
public function updated(AutoBudget $autoBudget): void
{
Log::debug('Observe "updated" of an auto budget.');
$this->updateNativeAmount($autoBudget);
}
private function updateNativeAmount(AutoBudget $autoBudget): void private function updateNativeAmount(AutoBudget $autoBudget): void
{ {
if (!Amount::convertToNative($autoBudget->budget->user)) { if (!Amount::convertToNative($autoBudget->budget->user)) {
@@ -59,4 +53,10 @@ class AutoBudgetObserver
$autoBudget->saveQuietly(); $autoBudget->saveQuietly();
Log::debug('Auto budget native amount is updated.'); Log::debug('Auto budget native amount is updated.');
} }
public function updated(AutoBudget $autoBudget): void
{
Log::debug('Observe "updated" of an auto budget.');
$this->updateNativeAmount($autoBudget);
}
} }

View File

@@ -37,12 +37,6 @@ class AvailableBudgetObserver
$this->updateNativeAmount($availableBudget); $this->updateNativeAmount($availableBudget);
} }
public function updated(AvailableBudget $availableBudget): void
{
// Log::debug('Observe "updated" of an available budget.');
$this->updateNativeAmount($availableBudget);
}
private function updateNativeAmount(AvailableBudget $availableBudget): void private function updateNativeAmount(AvailableBudget $availableBudget): void
{ {
if (!Amount::convertToNative($availableBudget->user)) { if (!Amount::convertToNative($availableBudget->user)) {
@@ -61,4 +55,10 @@ class AvailableBudgetObserver
$availableBudget->saveQuietly(); $availableBudget->saveQuietly();
Log::debug('Available budget native amount is updated.'); Log::debug('Available budget native amount is updated.');
} }
public function updated(AvailableBudget $availableBudget): void
{
// Log::debug('Observe "updated" of an available budget.');
$this->updateNativeAmount($availableBudget);
}
} }

View File

@@ -41,25 +41,6 @@ class BillObserver
$this->updateNativeAmount($bill); $this->updateNativeAmount($bill);
} }
public function deleting(Bill $bill): void
{
$repository = app(AttachmentRepositoryInterface::class);
$repository->setUser($bill->user);
// app('log')->debug('Observe "deleting" of a bill.');
/** @var Attachment $attachment */
foreach ($bill->attachments()->get() as $attachment) {
$repository->destroy($attachment);
}
$bill->notes()->delete();
}
public function updated(Bill $bill): void
{
// Log::debug('Observe "updated" of a bill.');
$this->updateNativeAmount($bill);
}
private function updateNativeAmount(Bill $bill): void private function updateNativeAmount(Bill $bill): void
{ {
if (!Amount::convertToNative($bill->user)) { if (!Amount::convertToNative($bill->user)) {
@@ -78,4 +59,23 @@ class BillObserver
$bill->saveQuietly(); $bill->saveQuietly();
Log::debug('Bill native amounts are updated.'); Log::debug('Bill native amounts are updated.');
} }
public function deleting(Bill $bill): void
{
$repository = app(AttachmentRepositoryInterface::class);
$repository->setUser($bill->user);
// app('log')->debug('Observe "deleting" of a bill.');
/** @var Attachment $attachment */
foreach ($bill->attachments()->get() as $attachment) {
$repository->destroy($attachment);
}
$bill->notes()->delete();
}
public function updated(Bill $bill): void
{
// Log::debug('Observe "updated" of a bill.');
$this->updateNativeAmount($bill);
}
} }

View File

@@ -37,12 +37,6 @@ class BudgetLimitObserver
$this->updateNativeAmount($budgetLimit); $this->updateNativeAmount($budgetLimit);
} }
public function updated(BudgetLimit $budgetLimit): void
{
Log::debug('Observe "updated" of a budget limit.');
$this->updateNativeAmount($budgetLimit);
}
private function updateNativeAmount(BudgetLimit $budgetLimit): void private function updateNativeAmount(BudgetLimit $budgetLimit): void
{ {
if (!Amount::convertToNative($budgetLimit->budget->user)) { if (!Amount::convertToNative($budgetLimit->budget->user)) {
@@ -61,4 +55,10 @@ class BudgetLimitObserver
$budgetLimit->saveQuietly(); $budgetLimit->saveQuietly();
Log::debug('Budget limit native amounts are updated.'); Log::debug('Budget limit native amounts are updated.');
} }
public function updated(BudgetLimit $budgetLimit): void
{
Log::debug('Observe "updated" of a budget limit.');
$this->updateNativeAmount($budgetLimit);
}
} }

View File

@@ -37,12 +37,6 @@ class PiggyBankEventObserver
$this->updateNativeAmount($event); $this->updateNativeAmount($event);
} }
public function updated(PiggyBankEvent $event): void
{
Log::debug('Observe "updated" of a piggy bank event.');
$this->updateNativeAmount($event);
}
private function updateNativeAmount(PiggyBankEvent $event): void private function updateNativeAmount(PiggyBankEvent $event): void
{ {
$user = $event->piggyBank->accounts()->first()?->user; $user = $event->piggyBank->accounts()->first()?->user;
@@ -65,4 +59,10 @@ class PiggyBankEventObserver
$event->saveQuietly(); $event->saveQuietly();
Log::debug('Piggy bank event native amount is updated.'); Log::debug('Piggy bank event native amount is updated.');
} }
public function updated(PiggyBankEvent $event): void
{
Log::debug('Observe "updated" of a piggy bank event.');
$this->updateNativeAmount($event);
}
} }

View File

@@ -41,6 +41,26 @@ class PiggyBankObserver
$this->updateNativeAmount($piggyBank); $this->updateNativeAmount($piggyBank);
} }
private function updateNativeAmount(PiggyBank $piggyBank): void
{
$group = $piggyBank->accounts()->first()?->user->userGroup;
if (null === $group) {
Log::debug(sprintf('No account(s) yet for piggy bank #%d.', $piggyBank->id));
return;
}
$userCurrency = app('amount')->getNativeCurrencyByUserGroup($group);
$piggyBank->native_target_amount = null;
if ($piggyBank->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$converter->setUserGroup($group);
$piggyBank->native_target_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $piggyBank->target_amount);
}
$piggyBank->saveQuietly();
Log::debug('Piggy bank native target amount is updated.');
}
/** /**
* Also delete related objects. * Also delete related objects.
*/ */
@@ -67,24 +87,4 @@ class PiggyBankObserver
Log::debug('Observe "updated" of a piggy bank.'); Log::debug('Observe "updated" of a piggy bank.');
$this->updateNativeAmount($piggyBank); $this->updateNativeAmount($piggyBank);
} }
private function updateNativeAmount(PiggyBank $piggyBank): void
{
$group = $piggyBank->accounts()->first()?->user->userGroup;
if (null === $group) {
Log::debug(sprintf('No account(s) yet for piggy bank #%d.', $piggyBank->id));
return;
}
$userCurrency = app('amount')->getNativeCurrencyByUserGroup($group);
$piggyBank->native_target_amount = null;
if ($piggyBank->transactionCurrency->id !== $userCurrency->id) {
$converter = new ExchangeRateConverter();
$converter->setIgnoreSettings(true);
$converter->setUserGroup($group);
$piggyBank->native_target_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $piggyBank->target_amount);
}
$piggyBank->saveQuietly();
Log::debug('Piggy bank native target amount is updated.');
}
} }

View File

@@ -48,24 +48,6 @@ class TransactionObserver
$this->updateNativeAmount($transaction); $this->updateNativeAmount($transaction);
} }
public function deleting(?Transaction $transaction): void
{
app('log')->debug('Observe "deleting" of a transaction.');
$transaction?->transactionJournal?->delete();
}
public function updated(Transaction $transaction): void
{
// Log::debug('Observe "updated" of a transaction.');
if (true === config('firefly.feature_flags.running_balance_column') && true === self::$recalculate) {
if (1 === bccomp($transaction->amount, '0')) {
Log::debug('Trigger recalculateForJournal');
AccountBalanceCalculator::recalculateForJournal($transaction->transactionJournal);
}
}
$this->updateNativeAmount($transaction);
}
private function updateNativeAmount(Transaction $transaction): void private function updateNativeAmount(Transaction $transaction): void
{ {
if (!Amount::convertToNative($transaction->transactionJournal->user)) { if (!Amount::convertToNative($transaction->transactionJournal->user)) {
@@ -92,4 +74,22 @@ class TransactionObserver
$transaction->saveQuietly(); $transaction->saveQuietly();
Log::debug('Transaction native amounts are updated.'); Log::debug('Transaction native amounts are updated.');
} }
public function deleting(?Transaction $transaction): void
{
app('log')->debug('Observe "deleting" of a transaction.');
$transaction?->transactionJournal?->delete();
}
public function updated(Transaction $transaction): void
{
// Log::debug('Observe "updated" of a transaction.');
if (true === config('firefly.feature_flags.running_balance_column') && true === self::$recalculate) {
if (1 === bccomp($transaction->amount, '0')) {
Log::debug('Trigger recalculateForJournal');
AccountBalanceCalculator::recalculateForJournal($transaction->transactionJournal);
}
}
$this->updateNativeAmount($transaction);
}
} }

View File

@@ -36,6 +36,89 @@ use Illuminate\Support\Facades\Log;
*/ */
trait AccountCollection trait AccountCollection
{ {
#[\Override]
public function accountBalanceIs(string $direction, string $operator, string $value): GroupCollectorInterface
{
Log::warning(sprintf('GroupCollector will be SLOW: accountBalanceIs: "%s" "%s" "%s"', $direction, $operator, $value));
/**
* @param int $index
* @param array $object
*
* @return bool
*/
$filter = static function (array $object) use ($direction, $operator, $value): bool {
/** @var array $transaction */
foreach ($object['transactions'] as $transaction) {
$key = sprintf('%s_account_id', $direction);
$accountId = $transaction[$key] ?? 0;
if (0 === $accountId) {
return false;
}
// in theory, this could lead to finding other users accounts.
/** @var null|Account $account */
$account = Account::find($accountId);
if (null === $account) {
continue;
}
// the balance must be found BEFORE the transaction date.
// so sub one second. This is not perfect, but works well enough.
$date = clone $transaction['date'];
$date->subSecond();
Log::debug(sprintf('accountBalanceIs: Call finalAccountBalance with date/time "%s"', $date->toIso8601String()));
$balance = Steam::finalAccountBalance($account, $date);
$result = bccomp((string) $balance['balance'], $value);
Log::debug(sprintf('"%s" vs "%s" is %d', $balance['balance'], $value, $result));
switch ($operator) {
default:
Log::error(sprintf('GroupCollector: accountBalanceIs: unknown operator "%s"', $operator));
return false;
case '==':
Log::debug('Expect result to be 0 (equal)');
return 0 === $result;
case '!=':
Log::debug('Expect result to be -1 or 1 (not equal)');
return 0 !== $result;
case '>':
Log::debug('Expect result to be 1 (greater then)');
return 1 === $result;
case '>=':
Log::debug('Expect result to be 0 or 1 (greater then or equal)');
return -1 !== $result;
case '<':
Log::debug('Expect result to be -1 (less than)');
return -1 === $result;
case '<=':
Log::debug('Expect result to be -1 or 0 (less than or equal)');
return 1 !== $result;
}
// if($balance['balance'] $operator $value) {
// }
}
return false;
};
$this->postFilters[] = $filter;
return $this;
}
/** /**
* These accounts must not be included. * These accounts must not be included.
*/ */
@@ -231,87 +314,4 @@ trait AccountCollection
return $this; return $this;
} }
#[\Override]
public function accountBalanceIs(string $direction, string $operator, string $value): GroupCollectorInterface
{
Log::warning(sprintf('GroupCollector will be SLOW: accountBalanceIs: "%s" "%s" "%s"', $direction, $operator, $value));
/**
* @param int $index
* @param array $object
*
* @return bool
*/
$filter = static function (array $object) use ($direction, $operator, $value): bool {
/** @var array $transaction */
foreach ($object['transactions'] as $transaction) {
$key = sprintf('%s_account_id', $direction);
$accountId = $transaction[$key] ?? 0;
if (0 === $accountId) {
return false;
}
// in theory, this could lead to finding other users accounts.
/** @var null|Account $account */
$account = Account::find($accountId);
if (null === $account) {
continue;
}
// the balance must be found BEFORE the transaction date.
// so sub one second. This is not perfect, but works well enough.
$date = clone $transaction['date'];
$date->subSecond();
Log::debug(sprintf('accountBalanceIs: Call finalAccountBalance with date/time "%s"', $date->toIso8601String()));
$balance = Steam::finalAccountBalance($account, $date);
$result = bccomp((string) $balance['balance'], $value);
Log::debug(sprintf('"%s" vs "%s" is %d', $balance['balance'], $value, $result));
switch ($operator) {
default:
Log::error(sprintf('GroupCollector: accountBalanceIs: unknown operator "%s"', $operator));
return false;
case '==':
Log::debug('Expect result to be 0 (equal)');
return 0 === $result;
case '!=':
Log::debug('Expect result to be -1 or 1 (not equal)');
return 0 !== $result;
case '>':
Log::debug('Expect result to be 1 (greater then)');
return 1 === $result;
case '>=':
Log::debug('Expect result to be 0 or 1 (greater then or equal)');
return -1 !== $result;
case '<':
Log::debug('Expect result to be -1 (less than)');
return -1 === $result;
case '<=':
Log::debug('Expect result to be -1 or 0 (less than or equal)');
return 1 !== $result;
}
// if($balance['balance'] $operator $value) {
// }
}
return false;
};
$this->postFilters[] = $filter;
return $this;
}
} }

View File

@@ -37,6 +37,7 @@ trait CollectorProperties
/** @var array<int, string> */ /** @var array<int, string> */
public array $sorting; public array $sorting;
private array $booleanFields;
private ?int $endRow; private ?int $endRow;
private bool $expandGroupSearch; private bool $expandGroupSearch;
private array $fields; private array $fields;
@@ -55,7 +56,6 @@ trait CollectorProperties
private HasMany $query; private HasMany $query;
private ?int $startRow; private ?int $startRow;
private array $stringFields; private array $stringFields;
private array $booleanFields;
/* /*
* This array is used to collect ALL tags the user may search for (using 'setTags'). * This array is used to collect ALL tags the user may search for (using 'setTags').
* This way the user can call 'setTags' multiple times and get a joined result. * This way the user can call 'setTags' multiple times and get a joined result.

View File

@@ -29,12 +29,12 @@ use FireflyIII\Models\Bill;
use FireflyIII\Models\Budget; use FireflyIII\Models\Budget;
use FireflyIII\Models\Category; use FireflyIII\Models\Category;
use FireflyIII\Models\Tag; use FireflyIII\Models\Tag;
use FireflyIII\Models\TransactionJournal;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\JoinClause; use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use FireflyIII\Models\TransactionJournal;
/** /**
* Trait MetaCollection * Trait MetaCollection

View File

@@ -900,16 +900,6 @@ class GroupCollector implements GroupCollectorInterface
return $this; return $this;
} }
/**
* Limit results to a specific currency, only normal one.
*/
public function setNormalCurrency(TransactionCurrency $currency): GroupCollectorInterface
{
$this->query->where('source.transaction_currency_id', $currency->id);
return $this;
}
public function setEndRow(int $endRow): self public function setEndRow(int $endRow): self
{ {
$this->endRow = $endRow; $this->endRow = $endRow;
@@ -957,6 +947,16 @@ class GroupCollector implements GroupCollectorInterface
return $this; return $this;
} }
/**
* Limit results to a specific currency, only normal one.
*/
public function setNormalCurrency(TransactionCurrency $currency): GroupCollectorInterface
{
$this->query->where('source.transaction_currency_id', $currency->id);
return $this;
}
/** /**
* Set the page to get. * Set the page to get.
*/ */

View File

@@ -41,6 +41,8 @@ use Illuminate\Support\Collection;
*/ */
interface GroupCollectorInterface interface GroupCollectorInterface
{ {
public function accountBalanceIs(string $direction, string $operator, string $value): self;
/** /**
* Get transactions with a specific amount. * Get transactions with a specific amount.
*/ */
@@ -457,11 +459,6 @@ interface GroupCollectorInterface
*/ */
public function setCurrency(TransactionCurrency $currency): self; public function setCurrency(TransactionCurrency $currency): self;
/**
* Limit results to a specific currency, either foreign or normal one.
*/
public function setNormalCurrency(TransactionCurrency $currency): self;
/** /**
* Set destination accounts. * Set destination accounts.
*/ */
@@ -526,6 +523,11 @@ interface GroupCollectorInterface
*/ */
public function setMetaDateRange(Carbon $start, Carbon $end, string $field): self; public function setMetaDateRange(Carbon $start, Carbon $end, string $field): self;
/**
* Limit results to a specific currency, either foreign or normal one.
*/
public function setNormalCurrency(TransactionCurrency $currency): self;
/** /**
* Define which accounts can NOT be part of the source and destination transactions. * Define which accounts can NOT be part of the source and destination transactions.
*/ */
@@ -737,6 +739,4 @@ interface GroupCollectorInterface
public function yearIs(string $year): self; public function yearIs(string $year): self;
public function yearIsNot(string $year): self; public function yearIsNot(string $year): self;
public function accountBalanceIs(string $direction, string $operator, string $value): self;
} }

View File

@@ -49,7 +49,7 @@ class NetWorth implements NetWorthInterface
{ {
private AccountRepositoryInterface $accountRepository; private AccountRepositoryInterface $accountRepository;
private CurrencyRepositoryInterface $currencyRepos; private CurrencyRepositoryInterface $currencyRepos;
private User $user; // @phpstan-ignore-line private User $user; // @phpstan-ignore-line
private ?UserGroup $userGroup = null; // @phpstan-ignore-line private ?UserGroup $userGroup = null; // @phpstan-ignore-line
/** /**

View File

@@ -29,8 +29,8 @@ use FireflyIII\Models\Account;
use FireflyIII\Models\Budget; use FireflyIII\Models\Budget;
use FireflyIII\Models\Category; use FireflyIII\Models\Category;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
/** /**

View File

@@ -121,6 +121,16 @@ class IndexController extends Controller
return view('accounts.index', compact('objectType', 'inactivePage', 'subTitleIcon', 'subTitle', 'page', 'accounts')); return view('accounts.index', compact('objectType', 'inactivePage', 'subTitleIcon', 'subTitle', 'page', 'accounts'));
} }
private function subtract(array $startBalances, array $endBalances): array
{
$result = [];
foreach ($endBalances as $key => $value) {
$result[$key] = bcsub((string) $value, $startBalances[$key] ?? '0');
}
return $result;
}
/** /**
* Show list of accounts. * Show list of accounts.
* *
@@ -153,7 +163,9 @@ class IndexController extends Controller
/** @var Carbon $end */ /** @var Carbon $end */
$end = clone session('end', today(config('app.timezone'))->endOfMonth()); $end = clone session('end', today(config('app.timezone'))->endOfMonth());
$start->subDay();
// 2025-05-11 removed this so start is exactly the start of the month.
// $start->subDay();
$ids = $accounts->pluck('id')->toArray(); $ids = $accounts->pluck('id')->toArray();
Log::debug(sprintf('index start: finalAccountsBalance("%s")', $start->format('Y-m-d H:i:s'))); Log::debug(sprintf('index start: finalAccountsBalance("%s")', $start->format('Y-m-d H:i:s')));
@@ -199,14 +211,4 @@ class IndexController extends Controller
return view('accounts.index', compact('objectType', 'inactiveCount', 'subTitleIcon', 'subTitle', 'page', 'accounts')); return view('accounts.index', compact('objectType', 'inactiveCount', 'subTitleIcon', 'subTitle', 'page', 'accounts'));
} }
private function subtract(array $startBalances, array $endBalances): array
{
$result = [];
foreach ($endBalances as $key => $value) {
$result[$key] = bcsub((string) $value, $startBalances[$key] ?? '0');
}
return $result;
}
} }

View File

@@ -225,10 +225,10 @@ class ReconcileController extends Controller
] ]
); );
$submission = [ $submission = [
'user' => auth()->user(), 'user' => auth()->user(),
'user_group' => auth()->user()->userGroup, 'user_group' => auth()->user()->userGroup,
'group_title' => null, 'group_title' => null,
'transactions' => [ 'transactions' => [
[ [
'user' => auth()->user(), 'user' => auth()->user(),
'user_group' => auth()->user()->userGroup, 'user_group' => auth()->user()->userGroup,

View File

@@ -33,7 +33,6 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Support\Debug\Timer; use FireflyIII\Support\Debug\Timer;
use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Facades\Steam;
use FireflyIII\Support\Http\Controllers\PeriodOverview; use FireflyIII\Support\Http\Controllers\PeriodOverview;
use FireflyIII\Support\JsonApi\Enrichments\TransactionGroupEnrichment;
use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;

View File

@@ -35,7 +35,6 @@ use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Support\CacheProperties; use FireflyIII\Support\CacheProperties;
use FireflyIII\Support\Facades\Amount;
use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Facades\Steam;
use FireflyIII\Support\Http\Controllers\AugumentData; use FireflyIII\Support\Http\Controllers\AugumentData;
use FireflyIII\Support\Http\Controllers\ChartGeneration; use FireflyIII\Support\Http\Controllers\ChartGeneration;
@@ -535,6 +534,17 @@ class AccountController extends Controller
return response()->json($data); return response()->json($data);
} }
private function updateChartKeys(array $array, array $balances): array
{
foreach (array_keys($balances) as $key) {
$array[$key] ??= [
'key' => $key,
];
}
return $array;
}
/** /**
* Shows the balances for a given set of dates and accounts. * Shows the balances for a given set of dates and accounts.
* *
@@ -676,15 +686,4 @@ class AccountController extends Controller
return response()->json($data); return response()->json($data);
} }
private function updateChartKeys(array $array, array $balances): array
{
foreach (array_keys($balances) as $key) {
$array[$key] ??= [
'key' => $key,
];
}
return $array;
}
} }

View File

@@ -38,7 +38,6 @@ use FireflyIII\Repositories\Budget\NoBudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use FireflyIII\Support\CacheProperties; use FireflyIII\Support\CacheProperties;
use FireflyIII\Support\Chart\Budget\FrontpageChartGenerator; use FireflyIII\Support\Chart\Budget\FrontpageChartGenerator;
use FireflyIII\Support\Facades\Amount;
use FireflyIII\Support\Http\Controllers\AugumentData; use FireflyIII\Support\Http\Controllers\AugumentData;
use FireflyIII\Support\Http\Controllers\DateCalculation; use FireflyIII\Support\Http\Controllers\DateCalculation;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;

View File

@@ -32,6 +32,7 @@ use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\View; use Illuminate\Support\Facades\View;
use Route; use Route;
@@ -51,13 +52,12 @@ abstract class Controller extends BaseController
// fails on PHP < 8.4 // fails on PHP < 8.4
public protected(set) string $name; public protected(set) string $name;
protected bool $convertToNative = false;
protected string $dateTimeFormat; protected string $dateTimeFormat;
protected string $monthAndDayFormat;
protected bool $convertToNative = false;
protected ?TransactionCurrency $defaultCurrency; protected ?TransactionCurrency $defaultCurrency;
protected string $monthFormat; protected string $monthAndDayFormat;
protected string $redirectUrl = '/'; protected string $monthFormat;
protected string $redirectUrl = '/';
/** /**
* Controller constructor. * Controller constructor.
@@ -81,6 +81,8 @@ abstract class Controller extends BaseController
// overrule v2 layout back to v1. // overrule v2 layout back to v1.
if ('true' === request()->get('force_default_layout') && 'v2' === config('view.layout')) { if ('true' === request()->get('force_default_layout') && 'v2' === config('view.layout')) {
//config('view.layout','v1');
Config::set('view.layout', 'v1');
View::getFinder()->setPaths([\Safe\realpath(base_path('resources/views'))]); // @phpstan-ignore-line View::getFinder()->setPaths([\Safe\realpath(base_path('resources/views'))]); // @phpstan-ignore-line
} }
@@ -94,8 +96,8 @@ abstract class Controller extends BaseController
View::share('uploadSize', $uploadSize); View::share('uploadSize', $uploadSize);
// share is alpha, is beta // share is alpha, is beta
$isAlpha = false; $isAlpha = false;
$isBeta = false; $isBeta = false;
$isDevelop = false; $isDevelop = false;
if (str_contains((string) config('firefly.version'), 'alpha')) { if (str_contains((string) config('firefly.version'), 'alpha')) {
$isAlpha = true; $isAlpha = true;
@@ -120,16 +122,16 @@ abstract class Controller extends BaseController
$this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale); $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale);
$this->dateTimeFormat = (string) trans('config.date_time_js', [], $locale); $this->dateTimeFormat = (string) trans('config.date_time_js', [], $locale);
$darkMode = 'browser'; $darkMode = 'browser';
$this->defaultCurrency =null; $this->defaultCurrency = null;
// get shown-intro-preference: // get shown-intro-preference:
if (auth()->check()) { if (auth()->check()) {
$this->defaultCurrency = Amount::getNativeCurrency(); $this->defaultCurrency = Amount::getNativeCurrency();
$language = Steam::getLanguage(); $language = Steam::getLanguage();
$locale = Steam::getLocale(); $locale = Steam::getLocale();
$darkMode = app('preferences')->get('darkMode', 'browser')->data; $darkMode = app('preferences')->get('darkMode', 'browser')->data;
$this->convertToNative =Amount::convertToNative(); $this->convertToNative = Amount::convertToNative();
$page = $this->getPageName(); $page = $this->getPageName();
$shownDemo = $this->hasSeenDemo(); $shownDemo = $this->hasSeenDemo();
View::share('language', $language); View::share('language', $language);
View::share('locale', $locale); View::share('locale', $locale);
View::share('convertToNative', $this->convertToNative); View::share('convertToNative', $this->convertToNative);

View File

@@ -25,6 +25,7 @@ declare(strict_types=1);
namespace FireflyIII\Http\Controllers; namespace FireflyIII\Http\Controllers;
use Carbon\Carbon; use Carbon\Carbon;
use Exception;
use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
@@ -65,110 +66,6 @@ class DebugController extends Controller
$this->middleware(IsDemoUser::class)->except(['displayError']); $this->middleware(IsDemoUser::class)->except(['displayError']);
} }
public function routes(Request $request): never
{
if (!auth()->user()->hasRole('owner')) {
throw new NotFoundHttpException();
}
/** @var iterable $routes */
$routes = Route::getRoutes();
if ('true' === $request->get('api')) {
$collection = [];
$i = 0;
echo 'PATHS="';
/** @var \Illuminate\Routing\Route $route */
foreach ($routes as $route) {
++$i;
// skip API and other routes.
if (!str_starts_with($route->uri(), 'api/v1')
) {
continue;
}
// skip non GET routes
if (!in_array('GET', $route->methods(), true)) {
continue;
}
// no name route:
if (null === $route->getName()) {
var_dump($route);
exit;
}
echo substr($route->uri(), 3);
if (0 === $i % 5) {
echo '"<br>PATHS="${PATHS},';
}
if (0 !== $i % 5) {
echo ',';
}
}
exit;
}
$return = [];
/** @var \Illuminate\Routing\Route $route */
foreach ($routes as $route) {
// skip API and other routes.
if (
str_starts_with($route->uri(), 'api')
|| str_starts_with($route->uri(), '_debugbar')
|| str_starts_with($route->uri(), '_ignition')
|| str_starts_with($route->uri(), 'oauth')
|| str_starts_with($route->uri(), 'chart')
|| str_starts_with($route->uri(), 'v1/jscript')
|| str_starts_with($route->uri(), 'v2/jscript')
|| str_starts_with($route->uri(), 'json')
|| str_starts_with($route->uri(), 'sanctum')
) {
continue;
}
// skip non GET routes
if (!in_array('GET', $route->methods(), true)) {
continue;
}
// no name route:
if (null === $route->getName()) {
var_dump($route);
exit;
}
if (!str_contains($route->uri(), '{')) {
$return[$route->getName()] = route($route->getName());
continue;
}
$params = [];
foreach ($route->parameterNames() as $name) {
$params[] = $this->getParameter($name);
}
$return[$route->getName()] = route($route->getName(), $params);
}
$count = 0;
echo '<hr>';
echo '<h1>Routes</h1>';
echo sprintf('<h2>%s</h2>', $count);
foreach ($return as $name => $path) {
echo sprintf('<a href="%1$s">%2$s</a><br>', $path, $name).PHP_EOL;
++$count;
if (0 === $count % 10) {
echo '<hr>';
echo sprintf('<h2>%s</h2>', $count);
}
}
exit;
}
/** /**
* Show all possible errors. * Show all possible errors.
* *
@@ -316,10 +213,10 @@ class DebugController extends Controller
app('log')->debug('Could not check build date, but thats ok.'); app('log')->debug('Could not check build date, but thats ok.');
app('log')->warning($e->getMessage()); app('log')->warning($e->getMessage());
} }
if ('' !== (string) env('BASE_IMAGE_BUILD')) { // @phpstan-ignore-line if ('' !== (string) env('BASE_IMAGE_BUILD')) { // @phpstan-ignore-line
$return['base_build'] = env('BASE_IMAGE_BUILD'); // @phpstan-ignore-line $return['base_build'] = env('BASE_IMAGE_BUILD'); // @phpstan-ignore-line
} }
if ('' !== (string) env('BASE_IMAGE_DATE')) { // @phpstan-ignore-line if ('' !== (string) env('BASE_IMAGE_DATE')) { // @phpstan-ignore-line
$return['base_build_date'] = env('BASE_IMAGE_DATE'); // @phpstan-ignore-line $return['base_build_date'] = env('BASE_IMAGE_DATE'); // @phpstan-ignore-line
} }
@@ -442,19 +339,107 @@ class DebugController extends Controller
return implode(' ', $flags); return implode(' ', $flags);
} }
/** public function routes(Request $request): never
* Flash all types of messages.
*
* @return Redirector|RedirectResponse
*/
public function testFlash(Request $request)
{ {
$request->session()->flash('success', 'This is a success message.'); if (!auth()->user()->hasRole('owner')) {
$request->session()->flash('info', 'This is an info message.'); throw new NotFoundHttpException();
$request->session()->flash('warning', 'This is a warning.'); }
$request->session()->flash('error', 'This is an error!');
return redirect(route('home')); /** @var iterable $routes */
$routes = Route::getRoutes();
if ('true' === $request->get('api')) {
$collection = [];
$i = 0;
echo 'PATHS="';
/** @var \Illuminate\Routing\Route $route */
foreach ($routes as $route) {
++$i;
// skip API and other routes.
if (!str_starts_with($route->uri(), 'api/v1')
) {
continue;
}
// skip non GET routes
if (!in_array('GET', $route->methods(), true)) {
continue;
}
// no name route:
if (null === $route->getName()) {
var_dump($route);
exit;
}
echo substr($route->uri(), 3);
if (0 === $i % 5) {
echo '"<br>PATHS="${PATHS},';
}
if (0 !== $i % 5) {
echo ',';
}
}
exit;
}
$return = [];
/** @var \Illuminate\Routing\Route $route */
foreach ($routes as $route) {
// skip API and other routes.
if (
str_starts_with($route->uri(), 'api')
|| str_starts_with($route->uri(), '_debugbar')
|| str_starts_with($route->uri(), '_ignition')
|| str_starts_with($route->uri(), 'oauth')
|| str_starts_with($route->uri(), 'chart')
|| str_starts_with($route->uri(), 'v1/jscript')
|| str_starts_with($route->uri(), 'v2/jscript')
|| str_starts_with($route->uri(), 'json')
|| str_starts_with($route->uri(), 'sanctum')
) {
continue;
}
// skip non GET routes
if (!in_array('GET', $route->methods(), true)) {
continue;
}
// no name route:
if (null === $route->getName()) {
var_dump($route);
exit;
}
if (!str_contains($route->uri(), '{')) {
$return[$route->getName()] = route($route->getName());
continue;
}
$params = [];
foreach ($route->parameterNames() as $name) {
$params[] = $this->getParameter($name);
}
$return[$route->getName()] = route($route->getName(), $params);
}
$count = 0;
echo '<hr>';
echo '<h1>Routes</h1>';
echo sprintf('<h2>%s</h2>', $count);
foreach ($return as $name => $path) {
echo sprintf('<a href="%1$s">%2$s</a><br>', $path, $name).PHP_EOL;
++$count;
if (0 === $count % 10) {
echo '<hr>';
echo sprintf('<h2>%s</h2>', $count);
}
}
exit;
} }
private function getParameter(string $name): string private function getParameter(string $name): string
@@ -582,4 +567,19 @@ class DebugController extends Controller
} }
} }
/**
* Flash all types of messages.
*
* @return Redirector|RedirectResponse
*/
public function testFlash(Request $request)
{
$request->session()->flash('success', 'This is a success message.');
$request->session()->flash('info', 'This is an info message.');
$request->session()->flash('warning', 'This is a warning.');
$request->session()->flash('error', 'This is an error!');
return redirect(route('home'));
}
} }

View File

@@ -91,7 +91,7 @@ class IndexController extends Controller
$generator->setStart($firstDate); $generator->setStart($firstDate);
$result = $generator->export(); $result = $generator->export();
$name = sprintf('%s_transaction_export.csv', \Safe\date('Y_m_d')); $name = sprintf('%s_transaction_export.csv', date('Y_m_d'));
$quoted = sprintf('"%s"', addcslashes($name, '"\\')); $quoted = sprintf('"%s"', addcslashes($name, '"\\'));
// headers for CSV file. // headers for CSV file.

View File

@@ -153,7 +153,7 @@ class RecurrenceController extends Controller
*/ */
public function suggest(Request $request): JsonResponse public function suggest(Request $request): JsonResponse
{ {
$string = '' === (string) $request->get('date') ? \Safe\date('Y-m-d') : (string) $request->get('date'); $string = '' === (string) $request->get('date') ? date('Y-m-d') : (string) $request->get('date');
$today = today(config('app.timezone'))->startOfDay(); $today = today(config('app.timezone'))->startOfDay();
try { try {

View File

@@ -110,7 +110,7 @@ class PreferencesController extends Controller
if (is_array($fiscalYearStartStr)) { if (is_array($fiscalYearStartStr)) {
$fiscalYearStartStr = '01-01'; $fiscalYearStartStr = '01-01';
} }
$fiscalYearStart = sprintf('%s-%s', \Safe\date('Y'), (string) $fiscalYearStartStr); $fiscalYearStart = sprintf('%s-%s', date('Y'), (string) $fiscalYearStartStr);
$tjOptionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; $tjOptionalFields = Preferences::get('transaction_journal_optional_fields', [])->data;
$availableDarkModes = config('firefly.available_dark_modes'); $availableDarkModes = config('firefly.available_dark_modes');
@@ -273,7 +273,7 @@ class PreferencesController extends Controller
$customFiscalYear = 1 === (int) $request->get('customFiscalYear'); $customFiscalYear = 1 === (int) $request->get('customFiscalYear');
$string = \Safe\strtotime((string) $request->get('fiscalYearStart')); $string = \Safe\strtotime((string) $request->get('fiscalYearStart'));
if (false !== $string) { if (false !== $string) {
$fiscalYearStart = \Safe\date('m-d', $string); $fiscalYearStart = date('m-d', $string);
Preferences::set('customFiscalYear', $customFiscalYear); Preferences::set('customFiscalYear', $customFiscalYear);
Preferences::set('fiscalYearStart', $fiscalYearStart); Preferences::set('fiscalYearStart', $fiscalYearStart);
} }

View File

@@ -27,8 +27,8 @@ namespace FireflyIII\Http\Controllers\TransactionCurrency;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\CurrencyFormRequest; use FireflyIII\Http\Requests\CurrencyFormRequest;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;

View File

@@ -26,8 +26,8 @@ namespace FireflyIII\Http\Controllers\TransactionCurrency;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;

View File

@@ -27,8 +27,8 @@ namespace FireflyIII\Http\Controllers\TransactionCurrency;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\CurrencyFormRequest; use FireflyIII\Http\Requests\CurrencyFormRequest;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;

View File

@@ -26,8 +26,8 @@ namespace FireflyIII\Http\Controllers\TransactionCurrency;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request; use Illuminate\Http\Request;

View File

@@ -177,7 +177,7 @@ class Kernel extends HttpKernel
// full API authentication // full API authentication
'api' => [ 'api' => [
AcceptHeaders::class, AcceptHeaders::class,
EnsureFrontendRequestsAreStateful::class, // EnsureFrontendRequestsAreStateful::class,
'auth:api,sanctum', 'auth:api,sanctum',
'bindings', 'bindings',
], ],

View File

@@ -94,15 +94,6 @@ class InterestingMessage
return null !== $transactionGroupId && null !== $message; return null !== $transactionGroupId && null !== $message;
} }
private function userGroupMessage(Request $request): bool
{
// get parameters from request.
$transactionGroupId = $request->get('user_group_id');
$message = $request->get('message');
return null !== $transactionGroupId && null !== $message;
}
private function handleGroupMessage(Request $request): void private function handleGroupMessage(Request $request): void
{ {
// get parameters from request. // get parameters from request.
@@ -141,13 +132,13 @@ class InterestingMessage
} }
} }
private function accountMessage(Request $request): bool private function userGroupMessage(Request $request): bool
{ {
// get parameters from request. // get parameters from request.
$accountId = $request->get('account_id'); $transactionGroupId = $request->get('user_group_id');
$message = $request->get('message'); $message = $request->get('message');
return null !== $accountId && null !== $message; return null !== $transactionGroupId && null !== $message;
} }
private function handleUserGroupMessage(Request $request): void private function handleUserGroupMessage(Request $request): void
@@ -188,6 +179,15 @@ class InterestingMessage
} }
} }
private function accountMessage(Request $request): bool
{
// get parameters from request.
$accountId = $request->get('account_id');
$message = $request->get('message');
return null !== $accountId && null !== $message;
}
private function handleAccountMessage(Request $request): void private function handleAccountMessage(Request $request): void
{ {
// get parameters from request. // get parameters from request.

View File

@@ -32,7 +32,8 @@ use Symfony\Component\HttpFoundation\Request;
class TrustProxies extends Middleware class TrustProxies extends Middleware
{ {
// After... // After...
protected $headers = Request::HEADER_X_FORWARDED_FOR protected $headers
= Request::HEADER_X_FORWARDED_FOR
| Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_HOST
| Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PORT
| Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_PROTO

View File

@@ -378,10 +378,10 @@ class CreateRecurringTransactions implements ShouldQueue
} }
$array = [ $array = [
'user' => $recurrence->user, 'user' => $recurrence->user,
'user_group' => $recurrence->user->userGroup, 'user_group' => $recurrence->user->userGroup,
'group_title' => $groupTitle, 'group_title' => $groupTitle,
'transactions' => $this->getTransactionData($recurrence, $repetition, $date), 'transactions' => $this->getTransactionData($recurrence, $repetition, $date),
]; ];
/** @var TransactionGroup $group */ /** @var TransactionGroup $group */

View File

@@ -35,6 +35,7 @@ class InvitationMail extends Mailable
{ {
use Queueable; use Queueable;
use SerializesModels; use SerializesModels;
public string $host; public string $host;
/** /**

View File

@@ -40,7 +40,8 @@ class ReportNewJournalsMail extends Mailable
{ {
use Queueable; use Queueable;
use SerializesModels; use SerializesModels;
public array $transformed;
public array $transformed;
/** /**
* ConfirmEmailChangeMail constructor. * ConfirmEmailChangeMail constructor.

View File

@@ -48,15 +48,15 @@ class Account extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'active' => 'boolean', 'active' => 'boolean',
'encrypted' => 'boolean', 'encrypted' => 'boolean',
'virtual_balance' => 'string', 'virtual_balance' => 'string',
'native_virtual_balance' => 'string', 'native_virtual_balance' => 'string',
]; ];
protected $fillable = ['user_id', 'user_group_id', 'account_type_id', 'name', 'active', 'virtual_balance', 'iban', 'native_virtual_balance']; protected $fillable = ['user_id', 'user_group_id', 'account_type_id', 'name', 'active', 'virtual_balance', 'iban', 'native_virtual_balance'];

View File

@@ -42,12 +42,12 @@ class Attachment extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'uploaded' => 'boolean', 'uploaded' => 'boolean',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['attachable_id', 'attachable_type', 'user_id', 'user_group_id', 'md5', 'filename', 'mime', 'title', 'description', 'size', 'uploaded']; protected $fillable = ['attachable_id', 'attachable_type', 'user_id', 'user_group_id', 'md5', 'filename', 'mime', 'title', 'description', 'size', 'uploaded'];

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Deprecated;
use FireflyIII\Support\Models\ReturnsIntegerIdTrait; use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -35,13 +36,13 @@ class AutoBudget extends Model
use ReturnsIntegerIdTrait; use ReturnsIntegerIdTrait;
use SoftDeletes; use SoftDeletes;
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const int AUTO_BUDGET_ADJUSTED = 3; public const int AUTO_BUDGET_ADJUSTED = 3;
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const int AUTO_BUDGET_RESET = 1; public const int AUTO_BUDGET_RESET = 1;
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const int AUTO_BUDGET_ROLLOVER = 2; public const int AUTO_BUDGET_ROLLOVER = 2;
protected $casts protected $casts
= [ = [

View File

@@ -41,16 +41,16 @@ class AvailableBudget extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'start_date' => 'date', 'start_date' => 'date',
'end_date' => 'date', 'end_date' => 'date',
'transaction_currency_id' => 'int', 'transaction_currency_id' => 'int',
'amount' => 'string', 'amount' => 'string',
'native_amount' => 'string', 'native_amount' => 'string',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['user_id', 'user_group_id', 'transaction_currency_id', 'amount', 'start_date', 'end_date', 'start_date_tz', 'end_date_tz', 'native_amount']; protected $fillable = ['user_id', 'user_group_id', 'transaction_currency_id', 'amount', 'start_date', 'end_date', 'start_date_tz', 'end_date_tz', 'native_amount'];
@@ -95,10 +95,11 @@ class AvailableBudget extends Model
); );
} }
protected function transactionCurrencyId(): Attribute protected function endDate(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int) $value, get: fn (string $value) => Carbon::parse($value),
set: fn (Carbon $value) => $value->format('Y-m-d'),
); );
} }
@@ -110,11 +111,10 @@ class AvailableBudget extends Model
); );
} }
protected function endDate(): Attribute protected function transactionCurrencyId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: fn (string $value) => Carbon::parse($value), get: static fn ($value) => (int) $value,
set: fn (Carbon $value) => $value->format('Y-m-d'),
); );
} }
} }

View File

@@ -44,21 +44,21 @@ class Bill extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'date' => SeparateTimezoneCaster::class, 'date' => SeparateTimezoneCaster::class,
'end_date' => SeparateTimezoneCaster::class, 'end_date' => SeparateTimezoneCaster::class,
'extension_date' => SeparateTimezoneCaster::class, 'extension_date' => SeparateTimezoneCaster::class,
'skip' => 'int', 'skip' => 'int',
'automatch' => 'boolean', 'automatch' => 'boolean',
'active' => 'boolean', 'active' => 'boolean',
'name_encrypted' => 'boolean', 'name_encrypted' => 'boolean',
'match_encrypted' => 'boolean', 'match_encrypted' => 'boolean',
'amount_min' => 'string', 'amount_min' => 'string',
'amount_max' => 'string', 'amount_max' => 'string',
'native_amount_min' => 'string', 'native_amount_min' => 'string',
'native_amount_max' => 'string', 'native_amount_max' => 'string',
]; ];
protected $fillable protected $fillable

View File

@@ -43,13 +43,13 @@ class Budget extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'active' => 'boolean', 'active' => 'boolean',
'encrypted' => 'boolean', 'encrypted' => 'boolean',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['user_id', 'user_group_id', 'name', 'active', 'order', 'user_group_id']; protected $fillable = ['user_id', 'user_group_id', 'name', 'active', 'order', 'user_group_id'];

View File

@@ -40,13 +40,13 @@ class BudgetLimit extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'start_date' => SeparateTimezoneCaster::class, 'start_date' => SeparateTimezoneCaster::class,
'end_date' => SeparateTimezoneCaster::class, 'end_date' => SeparateTimezoneCaster::class,
'auto_budget' => 'boolean', 'auto_budget' => 'boolean',
'amount' => 'string', 'amount' => 'string',
'native_amount' => 'string', 'native_amount' => 'string',
]; ];
protected $dispatchesEvents protected $dispatchesEvents
= [ = [

View File

@@ -42,12 +42,12 @@ class Category extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'encrypted' => 'boolean', 'encrypted' => 'boolean',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['user_id', 'user_group_id', 'name']; protected $fillable = ['user_id', 'user_group_id', 'name'];

View File

@@ -40,15 +40,15 @@ class CurrencyExchangeRate extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
'from_currency_id' => 'integer', 'from_currency_id' => 'integer',
'to_currency_id' => 'integer', 'to_currency_id' => 'integer',
'date' => SeparateTimezoneCaster::class, 'date' => SeparateTimezoneCaster::class,
'rate' => 'string', 'rate' => 'string',
'user_rate' => 'string', 'user_rate' => 'string',
]; ];
protected $fillable = ['user_id', 'from_currency_id', 'to_currency_id', 'date', 'date_tz', 'rate']; protected $fillable = ['user_id', 'from_currency_id', 'to_currency_id', 'date', 'date_tz', 'rate'];

View File

@@ -36,12 +36,13 @@ class GroupMembership extends Model
use ReturnsIntegerIdTrait; use ReturnsIntegerIdTrait;
use ReturnsIntegerUserIdTrait; use ReturnsIntegerUserIdTrait;
protected $casts = [ protected $casts
'created_at' => 'datetime', = [
'updated_at' => 'datetime', 'created_at' => 'datetime',
'user_id' => 'integer', 'updated_at' => 'datetime',
'user_group_id' => 'integer', 'user_id' => 'integer',
]; 'user_group_id' => 'integer',
];
protected $fillable = ['user_id', 'user_group_id', 'user_role_id']; protected $fillable = ['user_id', 'user_group_id', 'user_role_id'];

View File

@@ -39,10 +39,10 @@ class InvitedUser extends Model
protected $casts protected $casts
= [ = [
'expires' => SeparateTimezoneCaster::class, 'expires' => SeparateTimezoneCaster::class,
'redeemed' => 'boolean', 'redeemed' => 'boolean',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['user_group_id', 'user_id', 'email', 'invite_code', 'expires', 'expires_tz', 'redeemed']; protected $fillable = ['user_group_id', 'user_id', 'email', 'invite_code', 'expires', 'expires_tz', 'redeemed'];

View File

@@ -40,11 +40,11 @@ class ObjectGroup extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
]; ];
protected $fillable = ['title', 'order', 'user_id', 'user_group_id']; protected $fillable = ['title', 'order', 'user_id', 'user_group_id'];

View File

@@ -37,11 +37,11 @@ class Preference extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'data' => 'array', 'data' => 'array',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['user_id', 'data', 'name', 'user_group_id']; protected $fillable = ['user_id', 'data', 'name', 'user_group_id'];

View File

@@ -44,20 +44,20 @@ class Recurrence extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'title' => 'string', 'title' => 'string',
'id' => 'int', 'id' => 'int',
'description' => 'string', 'description' => 'string',
'first_date' => SeparateTimezoneCaster::class, 'first_date' => SeparateTimezoneCaster::class,
'repeat_until' => SeparateTimezoneCaster::class, 'repeat_until' => SeparateTimezoneCaster::class,
'latest_date' => SeparateTimezoneCaster::class, 'latest_date' => SeparateTimezoneCaster::class,
'repetitions' => 'int', 'repetitions' => 'int',
'active' => 'bool', 'active' => 'bool',
'apply_rules' => 'bool', 'apply_rules' => 'bool',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable protected $fillable

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Deprecated;
use FireflyIII\Support\Models\ReturnsIntegerIdTrait; use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -35,16 +36,16 @@ class RecurrenceRepetition extends Model
use ReturnsIntegerIdTrait; use ReturnsIntegerIdTrait;
use SoftDeletes; use SoftDeletes;
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const int WEEKEND_DO_NOTHING = 1; public const int WEEKEND_DO_NOTHING = 1;
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const int WEEKEND_SKIP_CREATION = 2; public const int WEEKEND_SKIP_CREATION = 2;
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const int WEEKEND_TO_FRIDAY = 3; public const int WEEKEND_TO_FRIDAY = 3;
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const int WEEKEND_TO_MONDAY = 4; public const int WEEKEND_TO_MONDAY = 4;
protected $casts protected $casts

View File

@@ -41,16 +41,16 @@ class Rule extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'active' => 'boolean', 'active' => 'boolean',
'order' => 'int', 'order' => 'int',
'stop_processing' => 'boolean', 'stop_processing' => 'boolean',
'id' => 'int', 'id' => 'int',
'strict' => 'boolean', 'strict' => 'boolean',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['rule_group_id', 'order', 'active', 'title', 'description', 'user_id', 'user_group_id', 'strict']; protected $fillable = ['rule_group_id', 'order', 'active', 'title', 'description', 'user_id', 'user_group_id', 'strict'];

View File

@@ -41,14 +41,14 @@ class RuleGroup extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'active' => 'boolean', 'active' => 'boolean',
'stop_processing' => 'boolean', 'stop_processing' => 'boolean',
'order' => 'int', 'order' => 'int',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['user_id', 'user_group_id', 'stop_processing', 'order', 'title', 'description', 'active']; protected $fillable = ['user_id', 'user_group_id', 'stop_processing', 'order', 'title', 'description', 'active'];

View File

@@ -42,15 +42,15 @@ class Tag extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'date' => SeparateTimezoneCaster::class, 'date' => SeparateTimezoneCaster::class,
'zoomLevel' => 'int', 'zoomLevel' => 'int',
'latitude' => 'float', 'latitude' => 'float',
'longitude' => 'float', 'longitude' => 'float',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['user_id', 'user_group_id', 'tag', 'date', 'date_tz', 'description', 'tagMode']; protected $fillable = ['user_id', 'user_group_id', 'tag', 'date', 'date_tz', 'description', 'tagMode'];

View File

@@ -41,21 +41,21 @@ class Transaction extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'identifier' => 'int', 'identifier' => 'int',
'encrypted' => 'boolean', // model does not have these fields though 'encrypted' => 'boolean', // model does not have these fields though
'bill_name_encrypted' => 'boolean', 'bill_name_encrypted' => 'boolean',
'reconciled' => 'boolean', 'reconciled' => 'boolean',
'balance_dirty' => 'boolean', 'balance_dirty' => 'boolean',
'balance_before' => 'string', 'balance_before' => 'string',
'balance_after' => 'string', 'balance_after' => 'string',
'date' => 'datetime', 'date' => 'datetime',
'amount' => 'string', 'amount' => 'string',
'foreign_amount' => 'string', 'foreign_amount' => 'string',
'native_amount' => 'string', 'native_amount' => 'string',
'native_foreign_amount' => 'string', 'native_foreign_amount' => 'string',
]; ];
protected $fillable protected $fillable

View File

@@ -37,8 +37,8 @@ class TransactionCurrency extends Model
use ReturnsIntegerIdTrait; use ReturnsIntegerIdTrait;
use SoftDeletes; use SoftDeletes;
public ?bool $userGroupNative = null;
public ?bool $userGroupEnabled = null; public ?bool $userGroupEnabled = null;
public ?bool $userGroupNative = null;
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',

View File

@@ -40,14 +40,14 @@ class TransactionGroup extends Model
protected $casts protected $casts
= [ = [
'id' => 'integer', 'id' => 'integer',
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'title' => 'string', 'title' => 'string',
'date' => 'datetime', 'date' => 'datetime',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['user_id', 'user_group_id', 'title']; protected $fillable = ['user_id', 'user_group_id', 'title'];

View File

@@ -54,19 +54,19 @@ class TransactionJournal extends Model
protected $casts protected $casts
= [ = [
'created_at' => 'datetime', 'created_at' => 'datetime',
'updated_at' => 'datetime', 'updated_at' => 'datetime',
'deleted_at' => 'datetime', 'deleted_at' => 'datetime',
'date' => SeparateTimezoneCaster::class, 'date' => SeparateTimezoneCaster::class,
'interest_date' => 'date', 'interest_date' => 'date',
'book_date' => 'date', 'book_date' => 'date',
'process_date' => 'date', 'process_date' => 'date',
'order' => 'int', 'order' => 'int',
'tag_count' => 'int', 'tag_count' => 'int',
'encrypted' => 'boolean', 'encrypted' => 'boolean',
'completed' => 'boolean', 'completed' => 'boolean',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable protected $fillable
@@ -114,11 +114,6 @@ class TransactionJournal extends Model
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }
public function userGroup(): BelongsTo
{
return $this->belongsTo(UserGroup::class);
}
public function attachments(): MorphMany public function attachments(): MorphMany
{ {
return $this->morphMany(Attachment::class, 'attachable'); return $this->morphMany(Attachment::class, 'attachable');
@@ -246,6 +241,11 @@ class TransactionJournal extends Model
return $this->hasMany(Transaction::class); return $this->hasMany(Transaction::class);
} }
public function userGroup(): BelongsTo
{
return $this->belongsTo(UserGroup::class);
}
protected function order(): Attribute protected function order(): Attribute
{ {
return Attribute::make( return Attribute::make(

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use Deprecated;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Support\Models\ReturnsIntegerIdTrait; use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -35,25 +36,25 @@ class TransactionType extends Model
use ReturnsIntegerIdTrait; use ReturnsIntegerIdTrait;
use SoftDeletes; use SoftDeletes;
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const string DEPOSIT = 'Deposit'; public const string DEPOSIT = 'Deposit';
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const string INVALID = 'Invalid'; public const string INVALID = 'Invalid';
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const string LIABILITY_CREDIT = 'Liability credit'; public const string LIABILITY_CREDIT = 'Liability credit';
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const string OPENING_BALANCE = 'Opening balance'; public const string OPENING_BALANCE = 'Opening balance';
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const string RECONCILIATION = 'Reconciliation'; public const string RECONCILIATION = 'Reconciliation';
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const string TRANSFER = 'Transfer'; public const string TRANSFER = 'Transfer';
#[\Deprecated] /** @deprecated */ #[\Deprecated] /** @deprecated */
public const string WITHDRAWAL = 'Withdrawal'; public const string WITHDRAWAL = 'Withdrawal';
protected $casts protected $casts

View File

@@ -44,12 +44,12 @@ class Webhook extends Model
protected $casts protected $casts
= [ = [
'active' => 'boolean', 'active' => 'boolean',
'trigger' => 'integer', 'trigger' => 'integer',
'response' => 'integer', 'response' => 'integer',
'delivery' => 'integer', 'delivery' => 'integer',
'user_id' => 'integer', 'user_id' => 'integer',
'user_group_id' => 'integer', 'user_group_id' => 'integer',
]; ];
protected $fillable = ['active', 'trigger', 'response', 'delivery', 'user_id', 'user_group_id', 'url', 'title', 'secret']; protected $fillable = ['active', 'trigger', 'response', 'delivery', 'user_id', 'user_group_id', 'url', 'title', 'secret'];

View File

@@ -50,30 +50,36 @@ class ReturnsAvailableChannels
private static function returnOwnerChannels(): array private static function returnOwnerChannels(): array
{ {
$channels = ['mail']; $channels = ['mail'];
$slackUrl = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data; if (true === config('notifications.channels.slack.enabled', false)) {
if (UrlValidator::isValidWebhookURL($slackUrl)) { $slackUrl = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data;
$channels[] = 'slack'; if (UrlValidator::isValidWebhookURL($slackUrl)) {
$channels[] = 'slack';
}
} }
// validate presence of of Ntfy settings. if (true === config('notifications.channels.ntfy.enabled', false)) {
if ('' !== (string) app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data) { // validate presence of of Ntfy settings.
Log::debug('Enabled ntfy.'); if ('' !== (string) app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data) {
$channels[] = NtfyChannel::class; Log::debug('Enabled ntfy.');
} $channels[] = NtfyChannel::class;
if ('' === (string) app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data) { }
Log::warning('No topic name for Ntfy, channel is disabled.'); if ('' === (string) app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data) {
Log::warning('No topic name for Ntfy, channel is disabled.');
}
} }
// pushover // pushover
$pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data; if (true === config('notifications.channels.pushover.enabled', false)) {
$pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data; $pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data;
if ('' === $pushoverAppToken || '' === $pushoverUserToken) { $pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data;
Log::warning('[b] No Pushover token, channel is disabled.'); if ('' === $pushoverAppToken || '' === $pushoverUserToken) {
} Log::warning('[b] No Pushover token, channel is disabled.');
if ('' !== $pushoverAppToken && '' !== $pushoverUserToken) { }
Log::debug('Enabled pushover.'); if ('' !== $pushoverAppToken && '' !== $pushoverUserToken) {
$channels[] = PushoverChannel::class; Log::debug('Enabled pushover.');
$channels[] = PushoverChannel::class;
}
} }
Log::debug(sprintf('Final channel set in ReturnsAvailableChannels: %s ', implode(', ', $channels))); Log::debug(sprintf('Final channel set in ReturnsAvailableChannels: %s ', implode(', ', $channels)));
@@ -84,31 +90,38 @@ class ReturnsAvailableChannels
private static function returnUserChannels(User $user): array private static function returnUserChannels(User $user): array
{ {
Log::debug(sprintf('Checking channels for user #%d', $user->id)); Log::debug(sprintf('Checking channels for user #%d', $user->id));
$channels = ['mail']; $channels = ['mail'];
$slackUrl = (string) app('preferences')->getEncryptedForUser($user, 'slack_webhook_url', '')->data;
if (UrlValidator::isValidWebhookURL($slackUrl)) { if (true === config('notifications.channels.slack.enabled', false)) {
$channels[] = 'slack'; $slackUrl = (string) app('preferences')->getEncryptedForUser($user, 'slack_webhook_url', '')->data;
if (UrlValidator::isValidWebhookURL($slackUrl)) {
$channels[] = 'slack';
}
} }
// validate presence of of Ntfy settings. // validate presence of of Ntfy settings.
$ntfyTopic = (string) app('preferences')->getEncryptedForUser($user, 'ntfy_topic', '')->data; if (true === config('notifications.channels.nfy.enabled', false)) {
if ('' !== $ntfyTopic) { $ntfyTopic = (string) app('preferences')->getEncryptedForUser($user, 'ntfy_topic', '')->data;
Log::debug(sprintf('Enabled ntfy, "%s"', $ntfyTopic)); if ('' !== $ntfyTopic) {
$channels[] = NtfyChannel::class; Log::debug(sprintf('Enabled ntfy, "%s"', $ntfyTopic));
} $channels[] = NtfyChannel::class;
if ('' === (string) app('preferences')->getEncryptedForUser($user, 'ntfy_topic', '')->data) { }
Log::warning('No topic name for Ntfy, channel is disabled.'); if ('' === (string) app('preferences')->getEncryptedForUser($user, 'ntfy_topic', '')->data) {
Log::warning('No topic name for Ntfy, channel is disabled.');
}
} }
// pushover // pushover
$pushoverAppToken = (string) app('preferences')->getEncryptedForUser($user, 'pushover_app_token', '')->data; if (true === config('notifications.channels.slack.enabled', false)) {
$pushoverUserToken = (string) app('preferences')->getEncryptedForUser($user, 'pushover_user_token', '')->data; $pushoverAppToken = (string) app('preferences')->getEncryptedForUser($user, 'pushover_app_token', '')->data;
if ('' === $pushoverAppToken || '' === $pushoverUserToken) { $pushoverUserToken = (string) app('preferences')->getEncryptedForUser($user, 'pushover_user_token', '')->data;
Log::warning('[b] No Pushover token, channel is disabled.'); if ('' === $pushoverAppToken || '' === $pushoverUserToken) {
} Log::warning('[b] No Pushover token, channel is disabled.');
if ('' !== $pushoverAppToken && '' !== $pushoverUserToken) { }
Log::debug('Enabled pushover.'); if ('' !== $pushoverAppToken && '' !== $pushoverUserToken) {
$channels[] = PushoverChannel::class; Log::debug('Enabled pushover.');
$channels[] = PushoverChannel::class;
}
} }
Log::debug(sprintf('Final channel set in ReturnsAvailableChannels (user): %s ', implode(', ', $channels))); Log::debug(sprintf('Final channel set in ReturnsAvailableChannels (user): %s ', implode(', ', $channels)));

View File

@@ -40,6 +40,14 @@ class AccountPolicy
return $this->view($user, $account); return $this->view($user, $account);
} }
/**
* TODO needs better authentication, also for group.
*/
public function view(User $user, Account $account): bool
{
return auth()->check() && $user->id === $account->user_id;
}
/** /**
* Everybody can do this, but selection should limit to user. * Everybody can do this, but selection should limit to user.
*/ */
@@ -57,12 +65,4 @@ class AccountPolicy
{ {
return $this->view($user, $account); return $this->view($user, $account);
} }
/**
* TODO needs better authentication, also for group.
*/
public function view(User $user, Account $account): bool
{
return auth()->check() && $user->id === $account->user_id;
}
} }

View File

@@ -24,8 +24,8 @@ declare(strict_types=1);
namespace FireflyIII\Providers; namespace FireflyIII\Providers;
use FireflyIII\Repositories\Currency\CurrencyRepository; use FireflyIII\Repositories\Currency\CurrencyRepository;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepository as GroupCurrencyRepository; use FireflyIII\Repositories\Currency\CurrencyRepository as GroupCurrencyRepository;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface as GroupCurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface as GroupCurrencyRepositoryInterface;
use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepository; use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepository;
use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepositoryInterface; use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepositoryInterface;

Some files were not shown because too many files have changed in this diff Show More