From 4ba1c5bcfcb444a9d078d23122a13f5df56b95f6 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Tue, 26 Nov 2024 18:04:32 +0100
Subject: [PATCH 001/122] New set of PHP 8.4 files
---
app/Http/Controllers/Controller.php | 3 +
app/Http/Controllers/HomeController.php | 1 +
app/Models/AccountType.php | 28 ++--
app/Models/AutoBudget.php | 6 +-
app/Models/RecurrenceRepetition.php | 8 +-
app/Models/TransactionType.php | 14 +-
composer.json | 2 +-
composer.lock | 206 ++++++++++++------------
8 files changed, 137 insertions(+), 131 deletions(-)
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php
index 772020f672..c5db5b85f7 100644
--- a/app/Http/Controllers/Controller.php
+++ b/app/Http/Controllers/Controller.php
@@ -44,6 +44,9 @@ abstract class Controller extends BaseController
use UserNavigation;
use ValidatesRequests;
+ // fails on PHP < 8.4
+ public protected(set) string $name;
+
protected string $dateTimeFormat;
protected string $monthAndDayFormat;
protected string $monthFormat;
diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php
index 72fc6ba722..0370161be8 100644
--- a/app/Http/Controllers/HomeController.php
+++ b/app/Http/Controllers/HomeController.php
@@ -43,6 +43,7 @@ use Illuminate\Support\Facades\Log;
*/
class HomeController extends Controller
{
+
/**
* HomeController constructor.
*/
diff --git a/app/Models/AccountType.php b/app/Models/AccountType.php
index 013b7269bd..6517f16dee 100644
--- a/app/Models/AccountType.php
+++ b/app/Models/AccountType.php
@@ -35,46 +35,46 @@ class AccountType extends Model
{
use ReturnsIntegerIdTrait;
- /** @deprecated */
+ #[\Deprecated]
public const string ASSET = 'Asset account';
- /** @deprecated */
+ #[\Deprecated]
public const string BENEFICIARY = 'Beneficiary account';
- /** @deprecated */
+ #[\Deprecated]
public const string CASH = 'Cash account';
- /** @deprecated */
+ #[\Deprecated]
public const string CREDITCARD = 'Credit card';
- /** @deprecated */
+ #[\Deprecated]
public const string DEBT = 'Debt';
- /** @deprecated */
+ #[\Deprecated]
public const string DEFAULT = 'Default account';
- /** @deprecated */
+ #[\Deprecated]
public const string EXPENSE = 'Expense account';
- /** @deprecated */
+ #[\Deprecated]
public const string IMPORT = 'Import account';
- /** @deprecated */
+ #[\Deprecated]
public const string INITIAL_BALANCE = 'Initial balance account';
- /** @deprecated */
+ #[\Deprecated]
public const string LIABILITY_CREDIT = 'Liability credit account';
- /** @deprecated */
+ #[\Deprecated]
public const string LOAN = 'Loan';
- /** @deprecated */
+ #[\Deprecated]
public const string MORTGAGE = 'Mortgage';
- /** @deprecated */
+ #[\Deprecated]
public const string RECONCILIATION = 'Reconciliation account';
- /** @deprecated */
+ #[\Deprecated]
public const string REVENUE = 'Revenue account';
protected $casts
diff --git a/app/Models/AutoBudget.php b/app/Models/AutoBudget.php
index b67ca3be23..4504522edf 100644
--- a/app/Models/AutoBudget.php
+++ b/app/Models/AutoBudget.php
@@ -39,13 +39,13 @@ class AutoBudget extends Model
use ReturnsIntegerIdTrait;
use SoftDeletes;
- /** @deprecated */
+ #[\Deprecated]
public const int AUTO_BUDGET_ADJUSTED = 3;
- /** @deprecated */
+ #[\Deprecated]
public const int AUTO_BUDGET_RESET = 1;
- /** @deprecated */
+ #[\Deprecated]
public const int AUTO_BUDGET_ROLLOVER = 2;
protected $fillable = ['budget_id', 'amount', 'period'];
diff --git a/app/Models/RecurrenceRepetition.php b/app/Models/RecurrenceRepetition.php
index f3daa1657b..5680b09c51 100644
--- a/app/Models/RecurrenceRepetition.php
+++ b/app/Models/RecurrenceRepetition.php
@@ -39,16 +39,16 @@ class RecurrenceRepetition extends Model
use ReturnsIntegerIdTrait;
use SoftDeletes;
- /** @deprecated */
+ #[\Deprecated]
public const int WEEKEND_DO_NOTHING = 1;
- /** @deprecated */
+ #[\Deprecated]
public const int WEEKEND_SKIP_CREATION = 2;
- /** @deprecated */
+ #[\Deprecated]
public const int WEEKEND_TO_FRIDAY = 3;
- /** @deprecated */
+ #[\Deprecated]
public const int WEEKEND_TO_MONDAY = 4;
protected $casts
diff --git a/app/Models/TransactionType.php b/app/Models/TransactionType.php
index dfc466cf3a..d0b948a469 100644
--- a/app/Models/TransactionType.php
+++ b/app/Models/TransactionType.php
@@ -38,25 +38,25 @@ class TransactionType extends Model
use ReturnsIntegerIdTrait;
use SoftDeletes;
- /** @deprecated */
+ #[\Deprecated]
public const string DEPOSIT = 'Deposit';
- /** @deprecated */
+ #[\Deprecated]
public const string INVALID = 'Invalid';
- /** @deprecated */
+ #[\Deprecated]
public const string LIABILITY_CREDIT = 'Liability credit';
- /** @deprecated */
+ #[\Deprecated]
public const string OPENING_BALANCE = 'Opening balance';
- /** @deprecated */
+ #[\Deprecated]
public const string RECONCILIATION = 'Reconciliation';
- /** @deprecated */
+ #[\Deprecated]
public const string TRANSFER = 'Transfer';
- /** @deprecated */
+ #[\Deprecated]
public const string WITHDRAWAL = 'Withdrawal';
protected $casts
diff --git a/composer.json b/composer.json
index b28b135953..c85437acdc 100644
--- a/composer.json
+++ b/composer.json
@@ -65,7 +65,7 @@
}
],
"require": {
- "php": ">=8.3",
+ "php": ">=8.4",
"ext-bcmath": "*",
"ext-curl": "*",
"ext-fileinfo": "*",
diff --git a/composer.lock b/composer.lock
index 761703e201..79b33dcb29 100644
--- a/composer.lock
+++ b/composer.lock
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "eb0a48bb5142f68837c2ca1f9b82aa0d",
+ "content-hash": "f813653aac7be9e344fb4ca91513df61",
"packages": [
{
"name": "bacon/bacon-qr-code",
@@ -1936,20 +1936,21 @@
},
{
"name": "laravel-json-api/core",
- "version": "v4.2.0",
+ "version": "v4.3.0",
"source": {
"type": "git",
"url": "https://github.com/laravel-json-api/core.git",
- "reference": "5a3d1771a63e222d902ccd7d57c9323c8aac8d32"
+ "reference": "37c4734dbd5c9fd7f2d5cca490553a0a664b2a69"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/laravel-json-api/core/zipball/5a3d1771a63e222d902ccd7d57c9323c8aac8d32",
- "reference": "5a3d1771a63e222d902ccd7d57c9323c8aac8d32",
+ "url": "https://api.github.com/repos/laravel-json-api/core/zipball/37c4734dbd5c9fd7f2d5cca490553a0a664b2a69",
+ "reference": "37c4734dbd5c9fd7f2d5cca490553a0a664b2a69",
"shasum": ""
},
"require": {
"ext-json": "*",
+ "illuminate/auth": "^11.33",
"illuminate/contracts": "^11.0",
"illuminate/http": "^11.0",
"illuminate/support": "^11.0",
@@ -1994,9 +1995,9 @@
],
"support": {
"issues": "https://github.com/laravel-json-api/core/issues",
- "source": "https://github.com/laravel-json-api/core/tree/v4.2.0"
+ "source": "https://github.com/laravel-json-api/core/tree/v4.3.0"
},
- "time": "2024-08-21T19:29:20+00:00"
+ "time": "2024-11-26T16:37:40+00:00"
},
{
"name": "laravel-json-api/eloquent",
@@ -2547,23 +2548,23 @@
},
{
"name": "laravel/framework",
- "version": "v11.33.2",
+ "version": "v11.34.0",
"source": {
"type": "git",
"url": "https://github.com/laravel/framework.git",
- "reference": "6b9832751cf8eed18b3c73df5071f78f0682aa5d"
+ "reference": "858184e8def3f20f588f9ab88355003750845a6c"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/laravel/framework/zipball/6b9832751cf8eed18b3c73df5071f78f0682aa5d",
- "reference": "6b9832751cf8eed18b3c73df5071f78f0682aa5d",
+ "url": "https://api.github.com/repos/laravel/framework/zipball/858184e8def3f20f588f9ab88355003750845a6c",
+ "reference": "858184e8def3f20f588f9ab88355003750845a6c",
"shasum": ""
},
"require": {
"brick/math": "^0.9.3|^0.10.2|^0.11|^0.12",
"composer-runtime-api": "^2.2",
"doctrine/inflector": "^2.0.5",
- "dragonmantank/cron-expression": "^3.3.2",
+ "dragonmantank/cron-expression": "^3.4",
"egulias/email-validator": "^3.2.1|^4.0",
"ext-ctype": "*",
"ext-filter": "*",
@@ -2573,35 +2574,36 @@
"ext-session": "*",
"ext-tokenizer": "*",
"fruitcake/php-cors": "^1.3",
- "guzzlehttp/guzzle": "^7.8",
+ "guzzlehttp/guzzle": "^7.8.2",
"guzzlehttp/uri-template": "^1.0",
"laravel/prompts": "^0.1.18|^0.2.0|^0.3.0",
"laravel/serializable-closure": "^1.3|^2.0",
"league/commonmark": "^2.2.1",
- "league/flysystem": "^3.8.0",
+ "league/flysystem": "^3.25.1",
+ "league/flysystem-local": "^3.25.1",
"monolog/monolog": "^3.0",
- "nesbot/carbon": "^2.72.2|^3.0",
+ "nesbot/carbon": "^2.72.2|^3.4",
"nunomaduro/termwind": "^2.0",
"php": "^8.2",
"psr/container": "^1.1.1|^2.0.1",
"psr/log": "^1.0|^2.0|^3.0",
"psr/simple-cache": "^1.0|^2.0|^3.0",
"ramsey/uuid": "^4.7",
- "symfony/console": "^7.0",
- "symfony/error-handler": "^7.0",
- "symfony/finder": "^7.0",
- "symfony/http-foundation": "^7.0",
- "symfony/http-kernel": "^7.0",
- "symfony/mailer": "^7.0",
- "symfony/mime": "^7.0",
- "symfony/polyfill-php83": "^1.28",
- "symfony/process": "^7.0",
- "symfony/routing": "^7.0",
- "symfony/uid": "^7.0",
- "symfony/var-dumper": "^7.0",
+ "symfony/console": "^7.0.3",
+ "symfony/error-handler": "^7.0.3",
+ "symfony/finder": "^7.0.3",
+ "symfony/http-foundation": "^7.0.3",
+ "symfony/http-kernel": "^7.0.3",
+ "symfony/mailer": "^7.0.3",
+ "symfony/mime": "^7.0.3",
+ "symfony/polyfill-php83": "^1.31",
+ "symfony/process": "^7.0.3",
+ "symfony/routing": "^7.0.3",
+ "symfony/uid": "^7.0.3",
+ "symfony/var-dumper": "^7.0.3",
"tijsverkoyen/css-to-inline-styles": "^2.2.5",
- "vlucas/phpdotenv": "^5.4.1",
- "voku/portable-ascii": "^2.0"
+ "vlucas/phpdotenv": "^5.6.1",
+ "voku/portable-ascii": "^2.0.2"
},
"conflict": {
"mockery/mockery": "1.6.8",
@@ -2651,29 +2653,32 @@
},
"require-dev": {
"ably/ably-php": "^1.0",
- "aws/aws-sdk-php": "^3.235.5",
+ "aws/aws-sdk-php": "^3.322.9",
"ext-gmp": "*",
- "fakerphp/faker": "^1.23",
- "league/flysystem-aws-s3-v3": "^3.0",
- "league/flysystem-ftp": "^3.0",
- "league/flysystem-path-prefixing": "^3.3",
- "league/flysystem-read-only": "^3.3",
- "league/flysystem-sftp-v3": "^3.0",
+ "fakerphp/faker": "^1.24",
+ "guzzlehttp/promises": "^2.0.3",
+ "guzzlehttp/psr7": "^2.4",
+ "league/flysystem-aws-s3-v3": "^3.25.1",
+ "league/flysystem-ftp": "^3.25.1",
+ "league/flysystem-path-prefixing": "^3.25.1",
+ "league/flysystem-read-only": "^3.25.1",
+ "league/flysystem-sftp-v3": "^3.25.1",
"mockery/mockery": "^1.6.10",
"nyholm/psr7": "^1.2",
"orchestra/testbench-core": "^9.6",
- "pda/pheanstalk": "^5.0",
+ "pda/pheanstalk": "^5.0.6",
"phpstan/phpstan": "^1.11.5",
- "phpunit/phpunit": "^10.5|^11.0",
- "predis/predis": "^2.0.2",
+ "phpunit/phpunit": "^10.5.35|^11.3.6",
+ "predis/predis": "^2.3",
"resend/resend-php": "^0.10.0",
- "symfony/cache": "^7.0",
- "symfony/http-client": "^7.0",
- "symfony/psr-http-message-bridge": "^7.0"
+ "symfony/cache": "^7.0.3",
+ "symfony/http-client": "^7.0.3",
+ "symfony/psr-http-message-bridge": "^7.0.3",
+ "symfony/translation": "^7.0.3"
},
"suggest": {
"ably/ably-php": "Required to use the Ably broadcast driver (^1.0).",
- "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage, and SES mail driver (^3.235.5).",
+ "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage, and SES mail driver (^3.322.9).",
"brianium/paratest": "Required to run tests in parallel (^7.0|^8.0).",
"ext-apcu": "Required to use the APC cache driver.",
"ext-fileinfo": "Required to use the Filesystem class.",
@@ -2687,16 +2692,16 @@
"fakerphp/faker": "Required to use the eloquent factory builder (^1.9.1).",
"filp/whoops": "Required for friendly error pages in development (^2.14.3).",
"laravel/tinker": "Required to use the tinker console command (^2.0).",
- "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^3.0).",
- "league/flysystem-ftp": "Required to use the Flysystem FTP driver (^3.0).",
- "league/flysystem-path-prefixing": "Required to use the scoped driver (^3.3).",
- "league/flysystem-read-only": "Required to use read-only disks (^3.3)",
- "league/flysystem-sftp-v3": "Required to use the Flysystem SFTP driver (^3.0).",
+ "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^3.25.1).",
+ "league/flysystem-ftp": "Required to use the Flysystem FTP driver (^3.25.1).",
+ "league/flysystem-path-prefixing": "Required to use the scoped driver (^3.25.1).",
+ "league/flysystem-read-only": "Required to use read-only disks (^3.25.1)",
+ "league/flysystem-sftp-v3": "Required to use the Flysystem SFTP driver (^3.25.1).",
"mockery/mockery": "Required to use mocking (^1.6).",
"nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).",
"pda/pheanstalk": "Required to use the beanstalk queue driver (^5.0).",
"phpunit/phpunit": "Required to use assertions and run tests (^10.5|^11.0).",
- "predis/predis": "Required to use the predis connector (^2.0.2).",
+ "predis/predis": "Required to use the predis connector (^2.3).",
"psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).",
"pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^6.0|^7.0).",
"resend/resend-php": "Required to enable support for the Resend mail transport (^0.10.0).",
@@ -2752,7 +2757,7 @@
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
- "time": "2024-11-19T22:47:13+00:00"
+ "time": "2024-11-26T15:11:52+00:00"
},
{
"name": "laravel/passport",
@@ -2891,16 +2896,16 @@
},
{
"name": "laravel/sanctum",
- "version": "v4.0.4",
+ "version": "v4.0.5",
"source": {
"type": "git",
"url": "https://github.com/laravel/sanctum.git",
- "reference": "819782c75aaf2b08da1765503893bd2b8023d3b3"
+ "reference": "fe361b9a63407a228f884eb78d7217f680b50140"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/laravel/sanctum/zipball/819782c75aaf2b08da1765503893bd2b8023d3b3",
- "reference": "819782c75aaf2b08da1765503893bd2b8023d3b3",
+ "url": "https://api.github.com/repos/laravel/sanctum/zipball/fe361b9a63407a228f884eb78d7217f680b50140",
+ "reference": "fe361b9a63407a228f884eb78d7217f680b50140",
"shasum": ""
},
"require": {
@@ -2951,7 +2956,7 @@
"issues": "https://github.com/laravel/sanctum/issues",
"source": "https://github.com/laravel/sanctum"
},
- "time": "2024-11-15T14:47:23+00:00"
+ "time": "2024-11-26T14:36:23+00:00"
},
{
"name": "laravel/serializable-closure",
@@ -3016,16 +3021,16 @@
},
{
"name": "laravel/slack-notification-channel",
- "version": "v3.4.0",
+ "version": "v3.4.1",
"source": {
"type": "git",
"url": "https://github.com/laravel/slack-notification-channel.git",
- "reference": "8ffbb9f0578956cc192bffc8d75f5b07beb35aa3"
+ "reference": "f43f63f1e0d22de1ded93425e4a9a5f977bfe34c"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/laravel/slack-notification-channel/zipball/8ffbb9f0578956cc192bffc8d75f5b07beb35aa3",
- "reference": "8ffbb9f0578956cc192bffc8d75f5b07beb35aa3",
+ "url": "https://api.github.com/repos/laravel/slack-notification-channel/zipball/f43f63f1e0d22de1ded93425e4a9a5f977bfe34c",
+ "reference": "f43f63f1e0d22de1ded93425e4a9a5f977bfe34c",
"shasum": ""
},
"require": {
@@ -3075,22 +3080,22 @@
],
"support": {
"issues": "https://github.com/laravel/slack-notification-channel/issues",
- "source": "https://github.com/laravel/slack-notification-channel/tree/v3.4.0"
+ "source": "https://github.com/laravel/slack-notification-channel/tree/v3.4.1"
},
- "time": "2024-10-24T15:06:08+00:00"
+ "time": "2024-11-21T15:06:30+00:00"
},
{
"name": "laravel/ui",
- "version": "v4.5.2",
+ "version": "v4.6.0",
"source": {
"type": "git",
"url": "https://github.com/laravel/ui.git",
- "reference": "c75396f63268c95b053c8e4814eb70e0875e9628"
+ "reference": "a34609b15ae0c0512a0cf47a21695a2729cb7f93"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/laravel/ui/zipball/c75396f63268c95b053c8e4814eb70e0875e9628",
- "reference": "c75396f63268c95b053c8e4814eb70e0875e9628",
+ "url": "https://api.github.com/repos/laravel/ui/zipball/a34609b15ae0c0512a0cf47a21695a2729cb7f93",
+ "reference": "a34609b15ae0c0512a0cf47a21695a2729cb7f93",
"shasum": ""
},
"require": {
@@ -3138,9 +3143,9 @@
"ui"
],
"support": {
- "source": "https://github.com/laravel/ui/tree/v4.5.2"
+ "source": "https://github.com/laravel/ui/tree/v4.6.0"
},
- "time": "2024-05-08T18:07:10+00:00"
+ "time": "2024-11-21T15:06:41+00:00"
},
{
"name": "lcobucci/clock",
@@ -5150,21 +5155,21 @@
},
{
"name": "php-http/guzzle7-adapter",
- "version": "1.0.0",
+ "version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-http/guzzle7-adapter.git",
- "reference": "fb075a71dbfa4847cf0c2938c4e5a9c478ef8b01"
+ "reference": "03a415fde709c2f25539790fecf4d9a31bc3d0eb"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/php-http/guzzle7-adapter/zipball/fb075a71dbfa4847cf0c2938c4e5a9c478ef8b01",
- "reference": "fb075a71dbfa4847cf0c2938c4e5a9c478ef8b01",
+ "url": "https://api.github.com/repos/php-http/guzzle7-adapter/zipball/03a415fde709c2f25539790fecf4d9a31bc3d0eb",
+ "reference": "03a415fde709c2f25539790fecf4d9a31bc3d0eb",
"shasum": ""
},
"require": {
"guzzlehttp/guzzle": "^7.0",
- "php": "^7.2 | ^8.0",
+ "php": "^7.3 | ^8.0",
"php-http/httplug": "^2.0",
"psr/http-client": "^1.0"
},
@@ -5175,14 +5180,11 @@
},
"require-dev": {
"php-http/client-integration-tests": "^3.0",
+ "php-http/message-factory": "^1.1",
+ "phpspec/prophecy-phpunit": "^2.0",
"phpunit/phpunit": "^8.0|^9.3"
},
"type": "library",
- "extra": {
- "branch-alias": {
- "dev-master": "0.2.x-dev"
- }
- },
"autoload": {
"psr-4": {
"Http\\Adapter\\Guzzle7\\": "src/"
@@ -5206,9 +5208,9 @@
],
"support": {
"issues": "https://github.com/php-http/guzzle7-adapter/issues",
- "source": "https://github.com/php-http/guzzle7-adapter/tree/1.0.0"
+ "source": "https://github.com/php-http/guzzle7-adapter/tree/1.1.0"
},
- "time": "2021-03-09T07:35:15+00:00"
+ "time": "2024-11-26T11:14:36+00:00"
},
{
"name": "php-http/httplug",
@@ -10443,16 +10445,16 @@
"packages-dev": [
{
"name": "barryvdh/laravel-debugbar",
- "version": "v3.14.7",
+ "version": "v3.14.9",
"source": {
"type": "git",
"url": "https://github.com/barryvdh/laravel-debugbar.git",
- "reference": "f484b8c9124de0b163da39958331098ffcd4a65e"
+ "reference": "2e805a6bd4e1aa83774316bb062703c65d0691ef"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/barryvdh/laravel-debugbar/zipball/f484b8c9124de0b163da39958331098ffcd4a65e",
- "reference": "f484b8c9124de0b163da39958331098ffcd4a65e",
+ "url": "https://api.github.com/repos/barryvdh/laravel-debugbar/zipball/2e805a6bd4e1aa83774316bb062703c65d0691ef",
+ "reference": "2e805a6bd4e1aa83774316bb062703c65d0691ef",
"shasum": ""
},
"require": {
@@ -10511,7 +10513,7 @@
],
"support": {
"issues": "https://github.com/barryvdh/laravel-debugbar/issues",
- "source": "https://github.com/barryvdh/laravel-debugbar/tree/v3.14.7"
+ "source": "https://github.com/barryvdh/laravel-debugbar/tree/v3.14.9"
},
"funding": [
{
@@ -10523,7 +10525,7 @@
"type": "github"
}
],
- "time": "2024-11-14T09:12:35+00:00"
+ "time": "2024-11-25T14:51:20+00:00"
},
{
"name": "barryvdh/laravel-ide-helper",
@@ -10731,16 +10733,16 @@
},
{
"name": "composer/class-map-generator",
- "version": "1.4.0",
+ "version": "1.5.0",
"source": {
"type": "git",
"url": "https://github.com/composer/class-map-generator.git",
- "reference": "98bbf6780e56e0fd2404fe4b82eb665a0f93b783"
+ "reference": "4b0a223cf5be7c9ee7e0ef1bc7db42b4a97c9915"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/composer/class-map-generator/zipball/98bbf6780e56e0fd2404fe4b82eb665a0f93b783",
- "reference": "98bbf6780e56e0fd2404fe4b82eb665a0f93b783",
+ "url": "https://api.github.com/repos/composer/class-map-generator/zipball/4b0a223cf5be7c9ee7e0ef1bc7db42b4a97c9915",
+ "reference": "4b0a223cf5be7c9ee7e0ef1bc7db42b4a97c9915",
"shasum": ""
},
"require": {
@@ -10749,10 +10751,10 @@
"symfony/finder": "^4.4 || ^5.3 || ^6 || ^7"
},
"require-dev": {
- "phpstan/phpstan": "^1.6",
- "phpstan/phpstan-deprecation-rules": "^1",
- "phpstan/phpstan-phpunit": "^1",
- "phpstan/phpstan-strict-rules": "^1.1",
+ "phpstan/phpstan": "^1.12 || ^2",
+ "phpstan/phpstan-deprecation-rules": "^1 || ^2",
+ "phpstan/phpstan-phpunit": "^1 || ^2",
+ "phpstan/phpstan-strict-rules": "^1.1 || ^2",
"phpunit/phpunit": "^8",
"symfony/filesystem": "^5.4 || ^6"
},
@@ -10784,7 +10786,7 @@
],
"support": {
"issues": "https://github.com/composer/class-map-generator/issues",
- "source": "https://github.com/composer/class-map-generator/tree/1.4.0"
+ "source": "https://github.com/composer/class-map-generator/tree/1.5.0"
},
"funding": [
{
@@ -10800,7 +10802,7 @@
"type": "tidelift"
}
],
- "time": "2024-10-03T18:14:00+00:00"
+ "time": "2024-11-25T16:11:06+00:00"
},
{
"name": "composer/pcre",
@@ -11218,16 +11220,16 @@
},
{
"name": "laravel-json-api/testing",
- "version": "v3.0.0",
+ "version": "v3.0.1",
"source": {
"type": "git",
"url": "https://github.com/laravel-json-api/testing.git",
- "reference": "1ada998d2087479351e01dd22ca13a00a96b4118"
+ "reference": "5ec2a84e725f93b6e0f79091b92c30bec88fe639"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/laravel-json-api/testing/zipball/1ada998d2087479351e01dd22ca13a00a96b4118",
- "reference": "1ada998d2087479351e01dd22ca13a00a96b4118",
+ "url": "https://api.github.com/repos/laravel-json-api/testing/zipball/5ec2a84e725f93b6e0f79091b92c30bec88fe639",
+ "reference": "5ec2a84e725f93b6e0f79091b92c30bec88fe639",
"shasum": ""
},
"require": {
@@ -11277,9 +11279,9 @@
],
"support": {
"issues": "https://github.com/laravel-json-api/testing/issues",
- "source": "https://github.com/laravel-json-api/testing/tree/v3.0.0"
+ "source": "https://github.com/laravel-json-api/testing/tree/v3.0.1"
},
- "time": "2024-03-12T20:30:38+00:00"
+ "time": "2024-11-26T16:49:53+00:00"
},
{
"name": "maximebf/debugbar",
@@ -13565,7 +13567,7 @@
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
- "php": ">=8.3",
+ "php": ">=8.4",
"ext-bcmath": "*",
"ext-curl": "*",
"ext-fileinfo": "*",
From c25c0d37c5969ac1caf9bcc00232fb862a85eb6d Mon Sep 17 00:00:00 2001
From: James Cole
Date: Wed, 27 Nov 2024 08:08:52 +0100
Subject: [PATCH 002/122] Replace constants with enums.
---
app/Models/AccountType.php | 2 +-
config/firefly.php | 632 ++++++++++++++++++-------------------
2 files changed, 317 insertions(+), 317 deletions(-)
diff --git a/app/Models/AccountType.php b/app/Models/AccountType.php
index 6517f16dee..0ef77adcc2 100644
--- a/app/Models/AccountType.php
+++ b/app/Models/AccountType.php
@@ -44,7 +44,7 @@ class AccountType extends Model
#[\Deprecated]
public const string CASH = 'Cash account';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string CREDITCARD = 'Credit card';
#[\Deprecated]
diff --git a/config/firefly.php b/config/firefly.php
index 1cce0a20e0..2b651de7d9 100644
--- a/config/firefly.php
+++ b/config/firefly.php
@@ -22,9 +22,9 @@
declare(strict_types=1);
+use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Models\Account;
-use FireflyIII\Models\AccountType;
use FireflyIII\Models\Attachment;
use FireflyIII\Models\AvailableBudget;
use FireflyIII\Models\Bill;
@@ -226,14 +226,14 @@ return [
// account types that may have or set a currency
'valid_currency_account_types' => [
- AccountType::ASSET,
- AccountType::LOAN,
- AccountType::DEBT,
- AccountType::MORTGAGE,
- AccountType::CASH,
- AccountType::INITIAL_BALANCE,
- AccountType::LIABILITY_CREDIT,
- AccountType::RECONCILIATION,
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::CASH->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LIABILITY_CREDIT->value,
+ AccountTypeEnum::RECONCILIATION->value,
],
// "value must be in this list" values
@@ -324,7 +324,7 @@ return [
'application/json',
],
'accountRoles' => ['defaultAsset', 'sharedAsset', 'savingAsset', 'ccAsset', 'cashWalletAsset'],
- 'valid_liabilities' => [AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
+ 'valid_liabilities' => [AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value],
'ccTypes' => ['monthlyFull' => 'Full payment every month'],
'credit_card_types' => ['monthlyFull'],
@@ -351,60 +351,60 @@ return [
'liability' => 'Liabilities',
],
'subIconsByIdentifier' => [
- 'asset' => 'fa-money',
- AccountType::ASSET => 'fa-money',
- AccountType::DEFAULT => 'fa-money',
- AccountType::CASH => 'fa-money',
- 'expense' => 'fa-shopping-cart',
- AccountType::EXPENSE => 'fa-shopping-cart',
- AccountType::BENEFICIARY => 'fa-shopping-cart',
- 'revenue' => 'fa-download',
- AccountType::REVENUE => 'fa-download',
- 'import' => 'fa-download',
- AccountType::IMPORT => 'fa-download',
- 'liabilities' => 'fa-ticket',
+ 'asset' => 'fa-money',
+ AccountTypeEnum::ASSET->value => 'fa-money',
+ AccountTypeEnum::DEFAULT->value => 'fa-money',
+ AccountTypeEnum::CASH->value => 'fa-money',
+ 'expense' => 'fa-shopping-cart',
+ AccountTypeEnum::EXPENSE->value => 'fa-shopping-cart',
+ AccountTypeEnum::BENEFICIARY->value => 'fa-shopping-cart',
+ 'revenue' => 'fa-download',
+ AccountTypeEnum::REVENUE->value => 'fa-download',
+ 'import' => 'fa-download',
+ AccountTypeEnum::IMPORT->value => 'fa-download',
+ 'liabilities' => 'fa-ticket',
],
'accountTypesByIdentifier' => [
- 'asset' => [AccountType::DEFAULT, AccountType::ASSET],
- 'expense' => [AccountType::EXPENSE, AccountType::BENEFICIARY],
- 'revenue' => [AccountType::REVENUE],
- 'import' => [AccountType::IMPORT],
- 'liabilities' => [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE],
+ 'asset' => [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value],
+ 'expense' => [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::BENEFICIARY->value],
+ 'revenue' => [AccountTypeEnum::REVENUE->value],
+ 'import' => [AccountTypeEnum::IMPORT->value],
+ 'liabilities' => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::MORTGAGE->value],
],
'accountTypeByIdentifier' => [
- 'asset' => [AccountType::ASSET],
- 'expense' => [AccountType::EXPENSE],
- 'revenue' => [AccountType::REVENUE],
- 'opening' => [AccountType::INITIAL_BALANCE],
- 'initial' => [AccountType::INITIAL_BALANCE],
- 'import' => [AccountType::IMPORT],
- 'reconcile' => [AccountType::RECONCILIATION],
- 'loan' => [AccountType::LOAN],
- 'debt' => [AccountType::DEBT],
- 'mortgage' => [AccountType::MORTGAGE],
- 'liabilities' => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE, AccountType::CREDITCARD],
- 'liability' => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE, AccountType::CREDITCARD],
+ 'asset' => [AccountTypeEnum::ASSET->value],
+ 'expense' => [AccountTypeEnum::EXPENSE->value],
+ 'revenue' => [AccountTypeEnum::REVENUE->value],
+ 'opening' => [AccountTypeEnum::INITIAL_BALANCE->value],
+ 'initial' => [AccountTypeEnum::INITIAL_BALANCE->value],
+ 'import' => [AccountTypeEnum::IMPORT->value],
+ 'reconcile' => [AccountTypeEnum::RECONCILIATION->value],
+ 'loan' => [AccountTypeEnum::LOAN->value],
+ 'debt' => [AccountTypeEnum::DEBT->value],
+ 'mortgage' => [AccountTypeEnum::MORTGAGE->value],
+ 'liabilities' => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::CREDITCARD->value],
+ 'liability' => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::CREDITCARD->value],
],
'shortNamesByFullName' => [
- AccountType::DEFAULT => 'asset',
- AccountType::ASSET => 'asset',
- AccountType::IMPORT => 'import',
- AccountType::EXPENSE => 'expense',
- AccountType::BENEFICIARY => 'expense',
- AccountType::REVENUE => 'revenue',
- AccountType::CASH => 'cash',
- AccountType::INITIAL_BALANCE => 'initial-balance',
- AccountType::RECONCILIATION => 'reconciliation',
- AccountType::CREDITCARD => 'liabilities',
- AccountType::LOAN => 'liabilities',
- AccountType::DEBT => 'liabilities',
- AccountType::MORTGAGE => 'liabilities',
+ AccountTypeEnum::DEFAULT->value => 'asset',
+ AccountTypeEnum::ASSET->value => 'asset',
+ AccountTypeEnum::IMPORT->value => 'import',
+ AccountTypeEnum::EXPENSE->value => 'expense',
+ AccountTypeEnum::BENEFICIARY->value => 'expense',
+ AccountTypeEnum::REVENUE->value => 'revenue',
+ AccountTypeEnum::CASH->value => 'cash',
+ AccountTypeEnum::INITIAL_BALANCE->value => 'initial-balance',
+ AccountTypeEnum::RECONCILIATION->value => 'reconciliation',
+ AccountTypeEnum::CREDITCARD->value => 'liabilities',
+ AccountTypeEnum::LOAN->value => 'liabilities',
+ AccountTypeEnum::DEBT->value => 'liabilities',
+ AccountTypeEnum::MORTGAGE->value => 'liabilities',
],
'shortLiabilityNameByFullName' => [
- AccountType::CREDITCARD => 'creditcard',
- AccountType::LOAN => AccountType::LOAN,
- AccountType::DEBT => AccountType::DEBT,
- AccountType::MORTGAGE => AccountType::MORTGAGE,
+ AccountTypeEnum::CREDITCARD->value => 'creditcard',
+ AccountTypeEnum::LOAN->value => AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value => AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value => AccountTypeEnum::MORTGAGE->value,
],
'transactionTypesByType' => [
'expenses' => ['Withdrawal'],
@@ -430,7 +430,7 @@ return [
'transfers' => 'fa-exchange',
],
- 'bindables' => [
+ 'bindables' => [
// models
'account' => Account::class,
'attachment' => Attachment::class,
@@ -488,7 +488,7 @@ return [
'userGroupBill' => UserGroupBill::class,
'userGroup' => UserGroup::class,
],
- 'rule-actions' => [
+ 'rule-actions' => [
'set_category' => SetCategory::class,
'clear_category' => ClearCategory::class,
'set_budget' => SetBudget::class,
@@ -522,7 +522,7 @@ return [
// 'set_foreign_amount' => SetForeignAmount::class,
// 'set_foreign_currency' => SetForeignCurrency::class,
],
- 'context-rule-actions' => [
+ 'context-rule-actions' => [
'set_category',
'set_budget',
'add_tag',
@@ -541,321 +541,321 @@ return [
'convert_transfer',
],
- 'test-triggers' => [
+ 'test-triggers' => [
'limit' => 10,
'range' => 200,
],
// expected source types for each transaction type, in order of preference.
- 'expected_source_types' => [
+ 'expected_source_types' => [
'source' => [
- TransactionTypeModel::WITHDRAWAL => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
- TransactionTypeEnum::DEPOSIT->value => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE, AccountType::REVENUE, AccountType::CASH],
- TransactionTypeModel::TRANSFER => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
- TransactionTypeModel::OPENING_BALANCE => [
- AccountType::INITIAL_BALANCE,
- AccountType::ASSET,
- AccountType::LOAN,
- AccountType::DEBT,
- AccountType::MORTGAGE,
+ TransactionTypeEnum::WITHDRAWAL->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
+ TransactionTypeEnum::DEPOSIT->value => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::REVENUE->value, AccountTypeEnum::CASH->value],
+ TransactionTypeEnum::TRANSFER->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
+ TransactionTypeEnum::OPENING_BALANCE->value => [
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value,
],
- TransactionTypeModel::RECONCILIATION => [AccountType::RECONCILIATION, AccountType::ASSET],
- TransactionTypeModel::LIABILITY_CREDIT => [AccountType::LIABILITY_CREDIT, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
+ TransactionTypeEnum::RECONCILIATION->value => [AccountTypeEnum::RECONCILIATION->value, AccountTypeEnum::ASSET->value],
+ TransactionTypeEnum::LIABILITY_CREDIT->value => [AccountTypeEnum::LIABILITY_CREDIT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
// in case no transaction type is known yet, it could be anything.
'none' => [
- AccountType::ASSET,
- AccountType::EXPENSE,
- AccountType::REVENUE,
- AccountType::LOAN,
- AccountType::DEBT,
- AccountType::MORTGAGE,
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::EXPENSE->value,
+ AccountTypeEnum::REVENUE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value,
],
],
'destination' => [
- TransactionTypeModel::WITHDRAWAL => [
- AccountType::LOAN,
- AccountType::DEBT,
- AccountType::MORTGAGE,
- AccountType::EXPENSE,
- AccountType::CASH,
+ TransactionTypeEnum::WITHDRAWAL->value => [
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::EXPENSE->value,
+ AccountTypeEnum::CASH->value,
],
- TransactionTypeEnum::DEPOSIT->value => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
- TransactionTypeModel::TRANSFER => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
- TransactionTypeModel::OPENING_BALANCE => [
- AccountType::INITIAL_BALANCE,
- AccountType::ASSET,
- AccountType::LOAN,
- AccountType::DEBT,
- AccountType::MORTGAGE,
+ TransactionTypeEnum::DEPOSIT->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
+ TransactionTypeEnum::TRANSFER->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
+ TransactionTypeEnum::OPENING_BALANCE->value => [
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value,
],
- TransactionTypeModel::RECONCILIATION => [AccountType::RECONCILIATION, AccountType::ASSET],
- TransactionTypeModel::LIABILITY_CREDIT => [AccountType::LIABILITY_CREDIT, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
+ TransactionTypeEnum::RECONCILIATION->value => [AccountTypeEnum::RECONCILIATION->value, AccountTypeEnum::ASSET->value],
+ TransactionTypeEnum::LIABILITY_CREDIT->value => [AccountTypeEnum::LIABILITY_CREDIT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
],
],
- 'allowed_opposing_types' => [
+ 'allowed_opposing_types' => [
'source' => [
- AccountType::ASSET => [
- AccountType::ASSET,
- AccountType::CASH,
- AccountType::DEBT,
- AccountType::EXPENSE,
- AccountType::INITIAL_BALANCE,
- AccountType::LOAN,
- AccountType::RECONCILIATION,
- AccountType::MORTGAGE,
+ AccountTypeEnum::ASSET->value => [
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::CASH->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::EXPENSE->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::RECONCILIATION->value,
+ AccountTypeEnum::MORTGAGE->value,
],
- AccountType::CASH => [AccountType::ASSET],
- AccountType::DEBT => [
- AccountType::ASSET,
- AccountType::DEBT,
- AccountType::EXPENSE,
- AccountType::INITIAL_BALANCE,
- AccountType::LOAN,
- AccountType::MORTGAGE,
- AccountType::LIABILITY_CREDIT,
+ AccountTypeEnum::CASH->value => [AccountTypeEnum::ASSET->value],
+ AccountTypeEnum::DEBT->value => [
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::EXPENSE->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::LIABILITY_CREDIT->value,
],
- AccountType::EXPENSE => [], // is not allowed as a source.
- AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
- AccountType::LOAN => [
- AccountType::ASSET,
- AccountType::DEBT,
- AccountType::EXPENSE,
- AccountType::INITIAL_BALANCE,
- AccountType::LOAN,
- AccountType::MORTGAGE,
- AccountType::LIABILITY_CREDIT,
+ AccountTypeEnum::EXPENSE->value => [], // is not allowed as a source.
+ AccountTypeEnum::INITIAL_BALANCE->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value],
+ AccountTypeEnum::LOAN->value => [
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::EXPENSE->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::LIABILITY_CREDIT->value,
],
- AccountType::MORTGAGE => [
- AccountType::ASSET,
- AccountType::DEBT,
- AccountType::EXPENSE,
- AccountType::INITIAL_BALANCE,
- AccountType::LOAN,
- AccountType::MORTGAGE,
- AccountType::LIABILITY_CREDIT,
+ AccountTypeEnum::MORTGAGE->value => [
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::EXPENSE->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::LIABILITY_CREDIT->value,
],
- AccountType::RECONCILIATION => [AccountType::ASSET],
- AccountType::REVENUE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
- AccountType::LIABILITY_CREDIT => [AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
+ AccountTypeEnum::RECONCILIATION->value => [AccountTypeEnum::ASSET->value],
+ AccountTypeEnum::REVENUE->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value],
+ AccountTypeEnum::LIABILITY_CREDIT->value => [AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value],
],
'destination' => [
- AccountType::ASSET => [
- AccountType::ASSET,
- AccountType::CASH,
- AccountType::DEBT,
- AccountType::INITIAL_BALANCE,
- AccountType::LOAN,
- AccountType::MORTGAGE,
- AccountType::RECONCILIATION,
- AccountType::REVENUE,
+ AccountTypeEnum::ASSET->value => [
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::CASH->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::RECONCILIATION->value,
+ AccountTypeEnum::REVENUE->value,
],
- AccountType::CASH => [AccountType::ASSET],
- AccountType::DEBT => [
- AccountType::ASSET,
- AccountType::DEBT,
- AccountType::INITIAL_BALANCE,
- AccountType::LOAN,
- AccountType::MORTGAGE,
- AccountType::REVENUE,
+ AccountTypeEnum::CASH->value => [AccountTypeEnum::ASSET->value],
+ AccountTypeEnum::DEBT->value => [
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::REVENUE->value,
],
- AccountType::EXPENSE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
- AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
- AccountType::LOAN => [
- AccountType::ASSET,
- AccountType::DEBT,
- AccountType::INITIAL_BALANCE,
- AccountType::LOAN,
- AccountType::MORTGAGE,
- AccountType::REVENUE,
+ AccountTypeEnum::EXPENSE->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value],
+ AccountTypeEnum::INITIAL_BALANCE->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value],
+ AccountTypeEnum::LOAN->value => [
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::REVENUE->value,
],
- AccountType::MORTGAGE => [
- AccountType::ASSET,
- AccountType::DEBT,
- AccountType::INITIAL_BALANCE,
- AccountType::LOAN,
- AccountType::MORTGAGE,
- AccountType::REVENUE,
+ AccountTypeEnum::MORTGAGE->value => [
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::REVENUE->value,
],
- AccountType::RECONCILIATION => [AccountType::ASSET],
- AccountType::REVENUE => [], // is not allowed as a destination
- AccountType::LIABILITY_CREDIT => [], // is not allowed as a destination
+ AccountTypeEnum::RECONCILIATION->value => [AccountTypeEnum::ASSET->value],
+ AccountTypeEnum::REVENUE->value => [], // is not allowed as a destination
+ AccountTypeEnum::LIABILITY_CREDIT->value => [], // is not allowed as a destination
],
],
// depending on the account type, return the allowed transaction types:
- 'allowed_transaction_types' => [
+ 'allowed_transaction_types' => [
'source' => [
- AccountType::ASSET => [
- TransactionTypeModel::WITHDRAWAL,
- TransactionTypeModel::TRANSFER,
- TransactionTypeModel::OPENING_BALANCE,
- TransactionTypeModel::RECONCILIATION,
+ AccountTypeEnum::ASSET->value => [
+ TransactionTypeEnum::WITHDRAWAL->value,
+ TransactionTypeEnum::TRANSFER->value,
+ TransactionTypeEnum::OPENING_BALANCE->value,
+ TransactionTypeEnum::RECONCILIATION->value,
],
- AccountType::EXPENSE => [], // is not allowed as a source.
- AccountType::REVENUE => [TransactionTypeEnum::DEPOSIT->value],
- AccountType::LOAN => [
- TransactionTypeModel::WITHDRAWAL,
+ AccountTypeEnum::EXPENSE->value => [], // is not allowed as a source.
+ AccountTypeEnum::REVENUE->value => [TransactionTypeEnum::DEPOSIT->value],
+ AccountTypeEnum::LOAN->value => [
+ TransactionTypeEnum::WITHDRAWAL->value,
TransactionTypeEnum::DEPOSIT->value,
- TransactionTypeModel::TRANSFER,
- TransactionTypeModel::OPENING_BALANCE,
- TransactionTypeModel::LIABILITY_CREDIT,
+ TransactionTypeEnum::TRANSFER->value,
+ TransactionTypeEnum::OPENING_BALANCE->value,
+ TransactionTypeEnum::LIABILITY_CREDIT->value,
],
- AccountType::DEBT => [
- TransactionTypeModel::WITHDRAWAL,
+ AccountTypeEnum::DEBT->value => [
+ TransactionTypeEnum::WITHDRAWAL->value,
TransactionTypeEnum::DEPOSIT->value,
- TransactionTypeModel::TRANSFER,
- TransactionTypeModel::OPENING_BALANCE,
- TransactionTypeModel::LIABILITY_CREDIT,
+ TransactionTypeEnum::TRANSFER->value,
+ TransactionTypeEnum::OPENING_BALANCE->value,
+ TransactionTypeEnum::LIABILITY_CREDIT->value,
],
- AccountType::MORTGAGE => [
- TransactionTypeModel::WITHDRAWAL,
+ AccountTypeEnum::MORTGAGE->value => [
+ TransactionTypeEnum::WITHDRAWAL->value,
TransactionTypeEnum::DEPOSIT->value,
- TransactionTypeModel::TRANSFER,
- TransactionTypeModel::OPENING_BALANCE,
- TransactionTypeModel::LIABILITY_CREDIT,
+ TransactionTypeEnum::TRANSFER->value,
+ TransactionTypeEnum::OPENING_BALANCE->value,
+ TransactionTypeEnum::LIABILITY_CREDIT->value,
],
- AccountType::INITIAL_BALANCE => [TransactionTypeModel::OPENING_BALANCE],
- AccountType::RECONCILIATION => [TransactionTypeModel::RECONCILIATION],
- AccountType::LIABILITY_CREDIT => [TransactionTypeModel::LIABILITY_CREDIT],
+ AccountTypeEnum::INITIAL_BALANCE->value => [TransactionTypeEnum::OPENING_BALANCE->value],
+ AccountTypeEnum::RECONCILIATION->value => [TransactionTypeEnum::RECONCILIATION->value],
+ AccountTypeEnum::LIABILITY_CREDIT->value => [TransactionTypeEnum::LIABILITY_CREDIT->value],
],
'destination' => [
- AccountType::ASSET => [
+ AccountTypeEnum::ASSET->value => [
TransactionTypeEnum::DEPOSIT->value,
- TransactionTypeModel::TRANSFER,
- TransactionTypeModel::OPENING_BALANCE,
- TransactionTypeModel::RECONCILIATION,
+ TransactionTypeEnum::TRANSFER->value,
+ TransactionTypeEnum::OPENING_BALANCE->value,
+ TransactionTypeEnum::RECONCILIATION->value,
],
- AccountType::EXPENSE => [TransactionTypeModel::WITHDRAWAL],
- AccountType::REVENUE => [], // is not allowed as destination.
- AccountType::LOAN => [
- TransactionTypeModel::WITHDRAWAL,
+ AccountTypeEnum::EXPENSE->value => [TransactionTypeEnum::WITHDRAWAL->value],
+ AccountTypeEnum::REVENUE->value => [], // is not allowed as destination.
+ AccountTypeEnum::LOAN->value => [
+ TransactionTypeEnum::WITHDRAWAL->value,
TransactionTypeEnum::DEPOSIT->value,
- TransactionTypeModel::TRANSFER,
- TransactionTypeModel::OPENING_BALANCE,
+ TransactionTypeEnum::TRANSFER->value,
+ TransactionTypeEnum::OPENING_BALANCE->value,
],
- AccountType::DEBT => [
- TransactionTypeModel::WITHDRAWAL,
+ AccountTypeEnum::DEBT->value => [
+ TransactionTypeEnum::WITHDRAWAL->value,
TransactionTypeEnum::DEPOSIT->value,
- TransactionTypeModel::TRANSFER,
- TransactionTypeModel::OPENING_BALANCE,
+ TransactionTypeEnum::TRANSFER->value,
+ TransactionTypeEnum::OPENING_BALANCE->value,
],
- AccountType::MORTGAGE => [
- TransactionTypeModel::WITHDRAWAL,
+ AccountTypeEnum::MORTGAGE->value => [
+ TransactionTypeEnum::WITHDRAWAL->value,
TransactionTypeEnum::DEPOSIT->value,
- TransactionTypeModel::TRANSFER,
- TransactionTypeModel::OPENING_BALANCE,
+ TransactionTypeEnum::TRANSFER->value,
+ TransactionTypeEnum::OPENING_BALANCE->value,
],
- AccountType::INITIAL_BALANCE => [TransactionTypeModel::OPENING_BALANCE],
- AccountType::RECONCILIATION => [TransactionTypeModel::RECONCILIATION],
- AccountType::LIABILITY_CREDIT => [], // is not allowed as a destination
+ AccountTypeEnum::INITIAL_BALANCE->value => [TransactionTypeEnum::OPENING_BALANCE->value],
+ AccountTypeEnum::RECONCILIATION->value => [TransactionTypeEnum::RECONCILIATION->value],
+ AccountTypeEnum::LIABILITY_CREDIT->value => [], // is not allowed as a destination
],
],
// having the source + dest will tell you the transaction type.
- 'account_to_transaction' => [
- AccountType::ASSET => [
- AccountType::ASSET => TransactionTypeModel::TRANSFER,
- AccountType::CASH => TransactionTypeModel::WITHDRAWAL,
- AccountType::DEBT => TransactionTypeModel::WITHDRAWAL,
- AccountType::EXPENSE => TransactionTypeModel::WITHDRAWAL,
- AccountType::INITIAL_BALANCE => TransactionTypeModel::OPENING_BALANCE,
- AccountType::LOAN => TransactionTypeModel::WITHDRAWAL,
- AccountType::MORTGAGE => TransactionTypeModel::WITHDRAWAL,
- AccountType::RECONCILIATION => TransactionTypeModel::RECONCILIATION,
+ 'account_to_transaction' => [
+ AccountTypeEnum::ASSET->value => [
+ AccountTypeEnum::ASSET->value => TransactionTypeEnum::TRANSFER->value,
+ AccountTypeEnum::CASH->value => TransactionTypeEnum::WITHDRAWAL->value,
+ AccountTypeEnum::DEBT->value => TransactionTypeEnum::WITHDRAWAL->value,
+ AccountTypeEnum::EXPENSE->value => TransactionTypeEnum::WITHDRAWAL->value,
+ AccountTypeEnum::INITIAL_BALANCE->value => TransactionTypeEnum::OPENING_BALANCE->value,
+ AccountTypeEnum::LOAN->value => TransactionTypeEnum::WITHDRAWAL->value,
+ AccountTypeEnum::MORTGAGE->value => TransactionTypeEnum::WITHDRAWAL->value,
+ AccountTypeEnum::RECONCILIATION->value => TransactionTypeEnum::RECONCILIATION->value,
],
- AccountType::CASH => [
- AccountType::ASSET => TransactionTypeModel::DEPOSIT,
- AccountType::LOAN => TransactionTypeModel::DEPOSIT,
- AccountType::DEBT => TransactionTypeModel::DEPOSIT,
- AccountType::MORTGAGE => TransactionTypeModel::DEPOSIT,
+ AccountTypeEnum::CASH->value => [
+ AccountTypeEnum::ASSET->value => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::LOAN->value => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::DEBT->value => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::MORTGAGE->value => TransactionTypeEnum::DEPOSIT->value,
],
- AccountType::DEBT => [
- AccountType::ASSET => TransactionTypeEnum::DEPOSIT->value,
- AccountType::DEBT => TransactionTypeModel::TRANSFER,
- AccountType::EXPENSE => TransactionTypeModel::WITHDRAWAL,
- AccountType::INITIAL_BALANCE => TransactionTypeModel::OPENING_BALANCE,
- AccountType::LOAN => TransactionTypeModel::TRANSFER,
- AccountType::MORTGAGE => TransactionTypeModel::TRANSFER,
+ AccountTypeEnum::DEBT->value => [
+ AccountTypeEnum::ASSET->value => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::DEBT->value => TransactionTypeEnum::TRANSFER->value,
+ AccountTypeEnum::EXPENSE->value => TransactionTypeEnum::WITHDRAWAL->value,
+ AccountTypeEnum::INITIAL_BALANCE->value => TransactionTypeEnum::OPENING_BALANCE->value,
+ AccountTypeEnum::LOAN->value => TransactionTypeEnum::TRANSFER->value,
+ AccountTypeEnum::MORTGAGE->value => TransactionTypeEnum::TRANSFER->value,
],
- AccountType::INITIAL_BALANCE => [
- AccountType::ASSET => TransactionTypeModel::OPENING_BALANCE,
- AccountType::DEBT => TransactionTypeModel::OPENING_BALANCE,
- AccountType::LOAN => TransactionTypeModel::OPENING_BALANCE,
- AccountType::MORTGAGE => TransactionTypeModel::OPENING_BALANCE,
+ AccountTypeEnum::INITIAL_BALANCE->value => [
+ AccountTypeEnum::ASSET->value => TransactionTypeEnum::OPENING_BALANCE->value,
+ AccountTypeEnum::DEBT->value => TransactionTypeEnum::OPENING_BALANCE->value,
+ AccountTypeEnum::LOAN->value => TransactionTypeEnum::OPENING_BALANCE->value,
+ AccountTypeEnum::MORTGAGE->value => TransactionTypeEnum::OPENING_BALANCE->value,
],
- AccountType::LOAN => [
- AccountType::ASSET => TransactionTypeEnum::DEPOSIT->value,
- AccountType::DEBT => TransactionTypeModel::TRANSFER,
- AccountType::EXPENSE => TransactionTypeModel::WITHDRAWAL,
- AccountType::INITIAL_BALANCE => TransactionTypeModel::OPENING_BALANCE,
- AccountType::LOAN => TransactionTypeModel::TRANSFER,
- AccountType::MORTGAGE => TransactionTypeModel::TRANSFER,
+ AccountTypeEnum::LOAN->value => [
+ AccountTypeEnum::ASSET->value => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::DEBT->value => TransactionTypeEnum::TRANSFER->value,
+ AccountTypeEnum::EXPENSE->value => TransactionTypeEnum::WITHDRAWAL->value,
+ AccountTypeEnum::INITIAL_BALANCE->value => TransactionTypeEnum::OPENING_BALANCE->value,
+ AccountTypeEnum::LOAN->value => TransactionTypeEnum::TRANSFER->value,
+ AccountTypeEnum::MORTGAGE->value => TransactionTypeEnum::TRANSFER->value,
],
- AccountType::MORTGAGE => [
- AccountType::ASSET => TransactionTypeEnum::DEPOSIT->value,
- AccountType::DEBT => TransactionTypeModel::TRANSFER,
- AccountType::EXPENSE => TransactionTypeModel::WITHDRAWAL,
- AccountType::INITIAL_BALANCE => TransactionTypeModel::OPENING_BALANCE,
- AccountType::LOAN => TransactionTypeModel::TRANSFER,
- AccountType::MORTGAGE => TransactionTypeModel::TRANSFER,
+ AccountTypeEnum::MORTGAGE->value => [
+ AccountTypeEnum::ASSET->value => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::DEBT->value => TransactionTypeEnum::TRANSFER->value,
+ AccountTypeEnum::EXPENSE->value => TransactionTypeEnum::WITHDRAWAL->value,
+ AccountTypeEnum::INITIAL_BALANCE->value => TransactionTypeEnum::OPENING_BALANCE->value,
+ AccountTypeEnum::LOAN->value => TransactionTypeEnum::TRANSFER->value,
+ AccountTypeEnum::MORTGAGE->value => TransactionTypeEnum::TRANSFER->value,
],
- AccountType::RECONCILIATION => [
- AccountType::ASSET => TransactionTypeModel::RECONCILIATION,
+ AccountTypeEnum::RECONCILIATION->value => [
+ AccountTypeEnum::ASSET->value => TransactionTypeEnum::RECONCILIATION->value,
],
- AccountType::REVENUE => [
- AccountType::ASSET => TransactionTypeEnum::DEPOSIT->value,
- AccountType::DEBT => TransactionTypeEnum::DEPOSIT->value,
- AccountType::LOAN => TransactionTypeEnum::DEPOSIT->value,
- AccountType::MORTGAGE => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::REVENUE->value => [
+ AccountTypeEnum::ASSET->value => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::DEBT->value => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::LOAN->value => TransactionTypeEnum::DEPOSIT->value,
+ AccountTypeEnum::MORTGAGE->value => TransactionTypeEnum::DEPOSIT->value,
],
- AccountType::LIABILITY_CREDIT => [
- AccountType::DEBT => TransactionTypeModel::LIABILITY_CREDIT,
- AccountType::LOAN => TransactionTypeModel::LIABILITY_CREDIT,
- AccountType::MORTGAGE => TransactionTypeModel::LIABILITY_CREDIT,
+ AccountTypeEnum::LIABILITY_CREDIT->value => [
+ AccountTypeEnum::DEBT->value => TransactionTypeEnum::LIABILITY_CREDIT->value,
+ AccountTypeEnum::LOAN->value => TransactionTypeEnum::LIABILITY_CREDIT->value,
+ AccountTypeEnum::MORTGAGE->value => TransactionTypeEnum::LIABILITY_CREDIT->value,
],
- // AccountType::EXPENSE unlisted because it cant be a source
+ // AccountTypeEnum::EXPENSE->value unlisted because it cant be a source
],
// allowed source -> destination accounts.
- 'source_dests' => [
- TransactionTypeModel::WITHDRAWAL => [
- AccountType::ASSET => [AccountType::EXPENSE, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE, AccountType::CASH],
- AccountType::LOAN => [AccountType::EXPENSE, AccountType::CASH],
- AccountType::DEBT => [AccountType::EXPENSE, AccountType::CASH],
- AccountType::MORTGAGE => [AccountType::EXPENSE, AccountType::CASH],
+ 'source_dests' => [
+ TransactionTypeEnum::WITHDRAWAL->value => [
+ AccountTypeEnum::ASSET->value => [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::CASH->value],
+ AccountTypeEnum::LOAN->value => [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::CASH->value],
+ AccountTypeEnum::DEBT->value => [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::CASH->value],
+ AccountTypeEnum::MORTGAGE->value => [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::CASH->value],
],
TransactionTypeEnum::DEPOSIT->value => [
- AccountType::REVENUE => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
- AccountType::CASH => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
- AccountType::LOAN => [AccountType::ASSET],
- AccountType::DEBT => [AccountType::ASSET],
- AccountType::MORTGAGE => [AccountType::ASSET],
+ AccountTypeEnum::REVENUE->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
+ AccountTypeEnum::CASH->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
+ AccountTypeEnum::LOAN->value => [AccountTypeEnum::ASSET->value],
+ AccountTypeEnum::DEBT->value => [AccountTypeEnum::ASSET->value],
+ AccountTypeEnum::MORTGAGE->value => [AccountTypeEnum::ASSET->value],
],
- TransactionTypeModel::TRANSFER => [
- AccountType::ASSET => [AccountType::ASSET],
- AccountType::LOAN => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
- AccountType::DEBT => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
- AccountType::MORTGAGE => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
+ TransactionTypeEnum::TRANSFER->value => [
+ AccountTypeEnum::ASSET->value => [AccountTypeEnum::ASSET->value],
+ AccountTypeEnum::LOAN->value => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
+ AccountTypeEnum::DEBT->value => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
+ AccountTypeEnum::MORTGAGE->value => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
],
- TransactionTypeModel::OPENING_BALANCE => [
- AccountType::ASSET => [AccountType::INITIAL_BALANCE],
- AccountType::LOAN => [AccountType::INITIAL_BALANCE],
- AccountType::DEBT => [AccountType::INITIAL_BALANCE],
- AccountType::MORTGAGE => [AccountType::INITIAL_BALANCE],
- AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
+ TransactionTypeEnum::OPENING_BALANCE->value => [
+ AccountTypeEnum::ASSET->value => [AccountTypeEnum::INITIAL_BALANCE->value],
+ AccountTypeEnum::LOAN->value => [AccountTypeEnum::INITIAL_BALANCE->value],
+ AccountTypeEnum::DEBT->value => [AccountTypeEnum::INITIAL_BALANCE->value],
+ AccountTypeEnum::MORTGAGE->value => [AccountTypeEnum::INITIAL_BALANCE->value],
+ AccountTypeEnum::INITIAL_BALANCE->value => [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
],
- TransactionTypeModel::RECONCILIATION => [
- AccountType::RECONCILIATION => [AccountType::ASSET],
- AccountType::ASSET => [AccountType::RECONCILIATION],
+ TransactionTypeEnum::RECONCILIATION->value => [
+ AccountTypeEnum::RECONCILIATION->value => [AccountTypeEnum::ASSET->value],
+ AccountTypeEnum::ASSET->value => [AccountTypeEnum::RECONCILIATION->value],
],
- TransactionTypeModel::LIABILITY_CREDIT => [
- AccountType::LOAN => [AccountType::LIABILITY_CREDIT],
- AccountType::DEBT => [AccountType::LIABILITY_CREDIT],
- AccountType::MORTGAGE => [AccountType::LIABILITY_CREDIT],
- AccountType::LIABILITY_CREDIT => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
+ TransactionTypeEnum::LIABILITY_CREDIT->value => [
+ AccountTypeEnum::LOAN->value => [AccountTypeEnum::LIABILITY_CREDIT->value],
+ AccountTypeEnum::DEBT->value => [AccountTypeEnum::LIABILITY_CREDIT->value],
+ AccountTypeEnum::MORTGAGE->value => [AccountTypeEnum::LIABILITY_CREDIT->value],
+ AccountTypeEnum::LIABILITY_CREDIT->value => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
],
],
// if you add fields to this array, don't forget to update the export routine (ExportDataGenerator).
- 'journal_meta_fields' => [
+ 'journal_meta_fields' => [
// sepa
'sepa_cc',
'sepa_ct_op',
@@ -889,28 +889,28 @@ return [
'recurrence_count',
'recurrence_date',
],
- 'webhooks' => [
+ 'webhooks' => [
'max_attempts' => env('WEBHOOK_MAX_ATTEMPTS', 3),
],
- 'can_have_virtual_amounts' => [AccountType::ASSET],
- 'can_have_opening_balance' => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
- 'dynamic_creation_allowed' => [
- AccountType::EXPENSE,
- AccountType::REVENUE,
- AccountType::INITIAL_BALANCE,
- AccountType::RECONCILIATION,
- AccountType::LIABILITY_CREDIT,
+ 'can_have_virtual_amounts' => [AccountTypeEnum::ASSET->value],
+ 'can_have_opening_balance' => [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
+ 'dynamic_creation_allowed' => [
+ AccountTypeEnum::EXPENSE->value,
+ AccountTypeEnum::REVENUE->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::RECONCILIATION->value,
+ AccountTypeEnum::LIABILITY_CREDIT->value,
],
- 'valid_asset_fields' => ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth'],
- 'valid_cc_fields' => ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth'],
- 'valid_account_fields' => ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth', 'liability_direction'],
+ 'valid_asset_fields' => ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth'],
+ 'valid_cc_fields' => ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth'],
+ 'valid_account_fields' => ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth', 'liability_direction'],
// dynamic date ranges are as follows:
- 'dynamic_date_ranges' => ['last7', 'last30', 'last90', 'last365', 'MTD', 'QTD', 'YTD'],
+ 'dynamic_date_ranges' => ['last7', 'last30', 'last90', 'last365', 'MTD', 'QTD', 'YTD'],
// only used in v1
- 'allowed_sort_parameters' => ['order', 'name', 'iban'],
+ 'allowed_sort_parameters' => ['order', 'name', 'iban'],
// preselected account lists possibilities:
- 'preselected_accounts' => ['all', 'assets', 'liabilities'],
+ 'preselected_accounts' => ['all', 'assets', 'liabilities'],
];
From f5c56e02da25dc178f4f691907cb2e0af0403b84 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Sat, 30 Nov 2024 05:42:59 +0100
Subject: [PATCH 003/122] API allows update/set of budget limit notes.
https://github.com/firefly-iii/firefly-iii/issues/5523
---
.../Models/BudgetLimit/StoreController.php | 9 +-
.../Models/BudgetLimit/StoreRequest.php | 2 +
.../Models/BudgetLimit/UpdateRequest.php | 9 +-
app/Models/Account.php | 2 +-
app/Models/BudgetLimit.php | 9 +
.../Budget/BudgetLimitRepository.php | 280 ++++++++++--------
.../Budget/BudgetLimitRepositoryInterface.php | 3 +
app/Transformers/BudgetLimitTransformer.php | 17 +-
8 files changed, 187 insertions(+), 144 deletions(-)
diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php b/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php
index 6f899b19ce..6f4cd02427 100644
--- a/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php
+++ b/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php
@@ -69,16 +69,17 @@ class StoreController extends Controller
$data = $request->getAll();
$data['start_date'] = $data['start'];
$data['end_date'] = $data['end'];
+ $data['notes'] = $data['notes'];
$data['budget_id'] = $budget->id;
- $budgetLimit = $this->blRepository->store($data);
- $manager = $this->getManager();
+ $budgetLimit = $this->blRepository->store($data);
+ $manager = $this->getManager();
/** @var BudgetLimitTransformer $transformer */
- $transformer = app(BudgetLimitTransformer::class);
+ $transformer = app(BudgetLimitTransformer::class);
$transformer->setParameters($this->parameters);
- $resource = new Item($budgetLimit, $transformer, 'budget_limits');
+ $resource = new Item($budgetLimit, $transformer, 'budget_limits');
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
diff --git a/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php b/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php
index 4fc0e8bf5b..48c77cf2a2 100644
--- a/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php
+++ b/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php
@@ -48,6 +48,7 @@ class StoreRequest extends FormRequest
'amount' => $this->convertString('amount'),
'currency_id' => $this->convertInteger('currency_id'),
'currency_code' => $this->convertString('currency_code'),
+ 'notes' => $this->stringWithNewlines('notes'),
];
}
@@ -62,6 +63,7 @@ class StoreRequest extends FormRequest
'amount' => ['required', new IsValidPositiveAmount()],
'currency_id' => 'numeric|exists:transaction_currencies,id',
'currency_code' => 'min:3|max:51|exists:transaction_currencies,code',
+ 'notes' => 'nullable|min:0|max:32768',
];
}
}
diff --git a/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php b/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php
index f93cebb012..08f2a160be 100644
--- a/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php
+++ b/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php
@@ -51,8 +51,12 @@ class UpdateRequest extends FormRequest
'amount' => ['amount', 'convertString'],
'currency_id' => ['currency_id', 'convertInteger'],
'currency_code' => ['currency_code', 'convertString'],
+ 'notes' => ['notes', 'stringWithNewlines'],
];
-
+ if(false === $this->has('notes')) {
+ // ignore notes, not submitted.
+ unset($fields['notes']);
+ }
return $this->getAllData($fields);
}
@@ -67,6 +71,7 @@ class UpdateRequest extends FormRequest
'amount' => ['nullable', new IsValidPositiveAmount()],
'currency_id' => 'numeric|exists:transaction_currencies,id',
'currency_code' => 'min:3|max:51|exists:transaction_currencies,code',
+ 'notes' => 'nullable|min:0|max:32768',
];
}
@@ -84,7 +89,7 @@ class UpdateRequest extends FormRequest
$start = new Carbon($data['start']);
$end = new Carbon($data['end']);
if ($end->isBefore($start)) {
- $validator->errors()->add('end', (string)trans('validation.date_after'));
+ $validator->errors()->add('end', (string) trans('validation.date_after'));
}
}
}
diff --git a/app/Models/Account.php b/app/Models/Account.php
index 39b5e1f8ed..fe523e2fe4 100644
--- a/app/Models/Account.php
+++ b/app/Models/Account.php
@@ -144,7 +144,7 @@ class Account extends Model
}
/**
- * Get all of the notes.
+ * Get all the notes.
*/
public function notes(): MorphMany
{
diff --git a/app/Models/BudgetLimit.php b/app/Models/BudgetLimit.php
index 22f3c0de2d..1f20c69482 100644
--- a/app/Models/BudgetLimit.php
+++ b/app/Models/BudgetLimit.php
@@ -31,6 +31,7 @@ use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\MorphMany;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
@@ -90,6 +91,14 @@ class BudgetLimit extends Model
return $this->belongsTo(TransactionCurrency::class);
}
+ /**
+ * Get all the notes.
+ */
+ public function notes(): MorphMany
+ {
+ return $this->morphMany(Note::class, 'noteable');
+ }
+
/**
* Get the amount
*/
diff --git a/app/Repositories/Budget/BudgetLimitRepository.php b/app/Repositories/Budget/BudgetLimitRepository.php
index 6921968dc3..f98b3da334 100644
--- a/app/Repositories/Budget/BudgetLimitRepository.php
+++ b/app/Repositories/Budget/BudgetLimitRepository.php
@@ -29,6 +29,7 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\TransactionCurrencyFactory;
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
+use FireflyIII\Models\Note;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\User;
use Illuminate\Contracts\Auth\Authenticatable;
@@ -49,10 +50,10 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
*/
public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, ?Collection $budgets = null): string
{
- $query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
+ $query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
// same complex where query as below.
- ->where(
+ ->where(
static function (Builder $q5) use ($start, $end): void {
$q5->where(
static function (Builder $q1) use ($start, $end): void {
@@ -62,30 +63,27 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d'));
}
)
- ->orWhere(
- static function (Builder $q3) use ($start, $end): void {
- $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d'));
- $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d'));
- }
- )
- ;
+ ->orWhere(
+ static function (Builder $q3) use ($start, $end): void {
+ $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d'));
+ $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d'));
+ }
+ );
}
)
- ->orWhere(
- static function (Builder $q4) use ($start, $end): void {
- // or start is before start AND end is after end.
- $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d'));
- $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d'));
- }
- )
- ;
+ ->orWhere(
+ static function (Builder $q4) use ($start, $end): void {
+ // or start is before start AND end is after end.
+ $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d'));
+ $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d'));
+ }
+ );
}
)
- ->where('budget_limits.transaction_currency_id', $currency->id)
- ->whereNull('budgets.deleted_at')
- ->where('budgets.active', true)
- ->where('budgets.user_id', $this->user->id)
- ;
+ ->where('budget_limits.transaction_currency_id', $currency->id)
+ ->whereNull('budgets.deleted_at')
+ ->where('budgets.active', true)
+ ->where('budgets.user_id', $this->user->id);
if (null !== $budgets && $budgets->count() > 0) {
$query->whereIn('budget_limits.budget_id', $budgets->pluck('id')->toArray());
}
@@ -137,19 +135,17 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
// both are NULL:
if (null === $start && null === $end) {
return BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
- ->with(['budget'])
- ->where('budgets.user_id', $this->user->id)
- ->whereNull('budgets.deleted_at')
- ->get(['budget_limits.*'])
- ;
+ ->with(['budget'])
+ ->where('budgets.user_id', $this->user->id)
+ ->whereNull('budgets.deleted_at')
+ ->get(['budget_limits.*']);
}
// one of the two is NULL.
if (null === $start xor null === $end) {
$query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
- ->with(['budget'])
- ->whereNull('budgets.deleted_at')
- ->where('budgets.user_id', $this->user->id)
- ;
+ ->with(['budget'])
+ ->whereNull('budgets.deleted_at')
+ ->where('budgets.user_id', $this->user->id);
if (null !== $end) {
// end date must be before $end.
$query->where('end_date', '<=', $end->format('Y-m-d 00:00:00'));
@@ -164,39 +160,36 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
// neither are NULL:
return BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
- ->with(['budget'])
- ->where('budgets.user_id', $this->user->id)
- ->whereNull('budgets.deleted_at')
- ->where(
- static function (Builder $q5) use ($start, $end): void {
- $q5->where(
- static function (Builder $q1) use ($start, $end): void {
- $q1->where(
- static function (Builder $q2) use ($start, $end): void {
- $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d'));
- $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d'));
- }
- )
- ->orWhere(
- static function (Builder $q3) use ($start, $end): void {
- $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d'));
- $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d'));
- }
- )
- ;
- }
- )
- ->orWhere(
- static function (Builder $q4) use ($start, $end): void {
- // or start is before start AND end is after end.
- $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d'));
- $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d'));
- }
- )
- ;
- }
- )->get(['budget_limits.*'])
- ;
+ ->with(['budget'])
+ ->where('budgets.user_id', $this->user->id)
+ ->whereNull('budgets.deleted_at')
+ ->where(
+ static function (Builder $q5) use ($start, $end): void {
+ $q5->where(
+ static function (Builder $q1) use ($start, $end): void {
+ $q1->where(
+ static function (Builder $q2) use ($start, $end): void {
+ $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d'));
+ $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d'));
+ }
+ )
+ ->orWhere(
+ static function (Builder $q3) use ($start, $end): void {
+ $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d'));
+ $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d'));
+ }
+ );
+ }
+ )
+ ->orWhere(
+ static function (Builder $q4) use ($start, $end): void {
+ // or start is before start AND end is after end.
+ $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d'));
+ $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d'));
+ }
+ );
+ }
+ )->get(['budget_limits.*']);
}
public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection
@@ -221,41 +214,38 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
// when both dates are set:
return $budget->budgetlimits()
- ->where(
- static function (Builder $q5) use ($start, $end): void { // @phpstan-ignore-line
- $q5->where(
- static function (Builder $q1) use ($start, $end): void {
- // budget limit ends within period
- $q1->where(
- static function (Builder $q2) use ($start, $end): void {
- $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d 00:00:00'));
- $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d 23:59:59'));
- }
- )
- // budget limit start within period
- ->orWhere(
- static function (Builder $q3) use ($start, $end): void {
- $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d 00:00:00'));
- $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d 23:59:59'));
- }
- )
- ;
- }
- )
- ->orWhere(
- static function (Builder $q4) use ($start, $end): void {
- // or start is before start AND end is after end.
- $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d 23:59:59'));
- $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d 00:00:00'));
- }
- )
- ;
- }
- )->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*'])
- ;
+ ->where(
+ static function (Builder $q5) use ($start, $end): void { // @phpstan-ignore-line
+ $q5->where(
+ static function (Builder $q1) use ($start, $end): void {
+ // budget limit ends within period
+ $q1->where(
+ static function (Builder $q2) use ($start, $end): void {
+ $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d 00:00:00'));
+ $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d 23:59:59'));
+ }
+ )
+ // budget limit start within period
+ ->orWhere(
+ static function (Builder $q3) use ($start, $end): void {
+ $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d 00:00:00'));
+ $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d 23:59:59'));
+ }
+ );
+ }
+ )
+ ->orWhere(
+ static function (Builder $q4) use ($start, $end): void {
+ // or start is before start AND end is after end.
+ $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d 23:59:59'));
+ $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d 00:00:00'));
+ }
+ );
+ }
+ )->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*']);
}
- public function setUser(null|Authenticatable|User $user): void
+ public function setUser(null | Authenticatable | User $user): void
{
if ($user instanceof User) {
$this->user = $user;
@@ -269,52 +259,57 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
{
// if no currency has been provided, use the user's default currency:
/** @var TransactionCurrencyFactory $factory */
- $factory = app(TransactionCurrencyFactory::class);
- $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null);
+ $factory = app(TransactionCurrencyFactory::class);
+ $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null);
if (null === $currency) {
$currency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
}
- $currency->enabled = true;
+ $currency->enabled = true;
$currency->save();
// find the budget:
- $budget = $this->user->budgets()->find((int) $data['budget_id']);
+ $budget = $this->user->budgets()->find((int) $data['budget_id']);
if (null === $budget) {
throw new FireflyException('200004: Budget does not exist.');
}
// find limit with same date range and currency.
- $limit = $budget->budgetlimits()
- ->where('budget_limits.start_date', $data['start_date']->format('Y-m-d'))
- ->where('budget_limits.end_date', $data['end_date']->format('Y-m-d'))
- ->where('budget_limits.transaction_currency_id', $currency->id)
- ->first(['budget_limits.*'])
- ;
+ $limit = $budget->budgetlimits()
+ ->where('budget_limits.start_date', $data['start_date']->format('Y-m-d'))
+ ->where('budget_limits.end_date', $data['end_date']->format('Y-m-d'))
+ ->where('budget_limits.transaction_currency_id', $currency->id)
+ ->first(['budget_limits.*']);
if (null !== $limit) {
throw new FireflyException('200027: Budget limit already exists.');
}
app('log')->debug('No existing budget limit, create a new one');
// or create one and return it.
- $limit = new BudgetLimit();
+ $limit = new BudgetLimit();
$limit->budget()->associate($budget);
$limit->start_date = $data['start_date']->format('Y-m-d');
$limit->end_date = $data['end_date']->format('Y-m-d');
$limit->amount = $data['amount'];
$limit->transaction_currency_id = $currency->id;
$limit->save();
+
+ $noteText = (string) ($data['notes'] ?? '');
+ if ('' !== $noteText) {
+ $this->setNoteText($limit, $noteText);
+ }
+
app('log')->debug(sprintf('Created new budget limit with ID #%d and amount %s', $limit->id, $data['amount']));
return $limit;
}
+
public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit
{
return $budget->budgetlimits()
- ->where('transaction_currency_id', $currency->id)
- ->where('start_date', $start->format('Y-m-d'))
- ->where('end_date', $end->format('Y-m-d'))->first()
- ;
+ ->where('transaction_currency_id', $currency->id)
+ ->where('start_date', $start->format('Y-m-d'))
+ ->where('end_date', $end->format('Y-m-d'))->first();
}
/**
@@ -322,8 +317,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
*/
public function update(BudgetLimit $budgetLimit, array $data): BudgetLimit
{
- $budgetLimit->amount = array_key_exists('amount', $data) ? $data['amount'] : $budgetLimit->amount;
- $budgetLimit->budget_id = array_key_exists('budget_id', $data) ? $data['budget_id'] : $budgetLimit->budget_id;
+ $budgetLimit->amount = array_key_exists('amount', $data) ? $data['amount'] : $budgetLimit->amount;
+ $budgetLimit->budget_id = array_key_exists('budget_id', $data) ? $data['budget_id'] : $budgetLimit->budget_id;
if (array_key_exists('start', $data)) {
$budgetLimit->start_date = $data['start']->startOfDay();
@@ -335,7 +330,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
}
// if no currency has been provided, use the user's default currency:
- $currency = null;
+ $currency = null;
// update if relevant:
if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
@@ -347,41 +342,43 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
if (null === $currency) {
$currency = $budgetLimit->transactionCurrency ?? app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
}
- $currency->enabled = true;
+ $currency->enabled = true;
$currency->save();
$budgetLimit->transaction_currency_id = $currency->id;
$budgetLimit->save();
+ // update notes if they exist.
+ if(array_key_exists('notes', $data)) {
+ $this->setNoteText($budgetLimit, (string)$data['notes']);
+ }
+
return $budgetLimit;
}
public function updateLimitAmount(Budget $budget, Carbon $start, Carbon $end, string $amount): ?BudgetLimit
{
// count the limits:
- $limits = $budget->budgetlimits()
- ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
- ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
- ->count('budget_limits.*')
- ;
+ $limits = $budget->budgetlimits()
+ ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
+ ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
+ ->count('budget_limits.*');
app('log')->debug(sprintf('Found %d budget limits.', $limits));
// there might be a budget limit for these dates:
/** @var null|BudgetLimit $limit */
- $limit = $budget->budgetlimits()
- ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
- ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
- ->first(['budget_limits.*'])
- ;
+ $limit = $budget->budgetlimits()
+ ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
+ ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
+ ->first(['budget_limits.*']);
// if more than 1 limit found, delete the others:
if ($limits > 1 && null !== $limit) {
app('log')->debug(sprintf('Found more than 1, delete all except #%d', $limit->id));
$budget->budgetlimits()
- ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
- ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
- ->where('budget_limits.id', '!=', $limit->id)->delete()
- ;
+ ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
+ ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
+ ->where('budget_limits.id', '!=', $limit->id)->delete();
}
// delete if amount is zero.
@@ -403,7 +400,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
}
app('log')->debug('No existing budget limit, create a new one');
// or create one and return it.
- $limit = new BudgetLimit();
+ $limit = new BudgetLimit();
$limit->budget()->associate($budget);
$limit->start_date = $start->startOfDay();
$limit->start_date_tz = $start->format('e');
@@ -415,4 +412,25 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
return $limit;
}
+
+ #[\Override] public function getNoteText(BudgetLimit $budgetLimit): string
+ {
+ return (string) $budgetLimit->notes()->first()?->text;
+ }
+
+ #[\Override] public function setNoteText(BudgetLimit $budgetLimit, string $text): void
+ {
+ $dbNote = $budgetLimit->notes()->first();
+ if ('' !== $text) {
+ if (null === $dbNote) {
+ $dbNote = new Note();
+ $dbNote->noteable()->associate($budgetLimit);
+ }
+ $dbNote->text = trim($text);
+ $dbNote->save();
+
+ return;
+ }
+ $dbNote?->delete();
+ }
}
diff --git a/app/Repositories/Budget/BudgetLimitRepositoryInterface.php b/app/Repositories/Budget/BudgetLimitRepositoryInterface.php
index 9bb52abb15..12cbcd9da4 100644
--- a/app/Repositories/Budget/BudgetLimitRepositoryInterface.php
+++ b/app/Repositories/Budget/BudgetLimitRepositoryInterface.php
@@ -48,6 +48,9 @@ interface BudgetLimitRepositoryInterface
*/
public function destroyAll(): void;
+ public function getNoteText(BudgetLimit $budgetLimit): string;
+ public function setNoteText(BudgetLimit $budgetLimit, string $text): void;
+
/**
* Destroy a budget limit.
*/
diff --git a/app/Transformers/BudgetLimitTransformer.php b/app/Transformers/BudgetLimitTransformer.php
index ad8225ceec..d75440a8fd 100644
--- a/app/Transformers/BudgetLimitTransformer.php
+++ b/app/Transformers/BudgetLimitTransformer.php
@@ -25,6 +25,7 @@ declare(strict_types=1);
namespace FireflyIII\Transformers;
use FireflyIII\Models\BudgetLimit;
+use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepository;
use Illuminate\Support\Collection;
use League\Fractal\Resource\Item;
@@ -54,8 +55,10 @@ class BudgetLimitTransformer extends AbstractTransformer
*/
public function transform(BudgetLimit $budgetLimit): array
{
- $repository = app(OperationsRepository::class);
+ $repository = app(OperationsRepository::class);
+ $limitRepos = app(BudgetLimitRepositoryInterface::class);
$repository->setUser($budgetLimit->budget->user);
+ $limitRepos->setUser($budgetLimit->budget->user);
$expenses = $repository->sumExpenses(
$budgetLimit->start_date,
$budgetLimit->end_date,
@@ -65,6 +68,7 @@ class BudgetLimitTransformer extends AbstractTransformer
);
$currency = $budgetLimit->transactionCurrency;
$amount = $budgetLimit->amount;
+ $notes = $limitRepos->getNoteText($budgetLimit);
$currencyDecimalPlaces = 2;
$currencyId = null;
$currencyName = null;
@@ -78,16 +82,16 @@ class BudgetLimitTransformer extends AbstractTransformer
$currencySymbol = $currency->symbol;
$currencyDecimalPlaces = $currency->decimal_places;
}
- $amount = app('steam')->bcround($amount, $currencyDecimalPlaces);
+ $amount = app('steam')->bcround($amount, $currencyDecimalPlaces);
return [
- 'id' => (string)$budgetLimit->id,
+ 'id' => (string) $budgetLimit->id,
'created_at' => $budgetLimit->created_at->toAtomString(),
'updated_at' => $budgetLimit->updated_at->toAtomString(),
'start' => $budgetLimit->start_date->toAtomString(),
'end' => $budgetLimit->end_date->endOfDay()->toAtomString(),
- 'budget_id' => (string)$budgetLimit->budget_id,
- 'currency_id' => (string)$currencyId,
+ 'budget_id' => (string) $budgetLimit->budget_id,
+ 'currency_id' => (string) $currencyId,
'currency_code' => $currencyCode,
'currency_name' => $currencyName,
'currency_decimal_places' => $currencyDecimalPlaces,
@@ -95,10 +99,11 @@ class BudgetLimitTransformer extends AbstractTransformer
'amount' => $amount,
'period' => $budgetLimit->period,
'spent' => $expenses[$currencyId]['sum'] ?? '0',
+ 'notes' => '' === $notes ? null : $notes,
'links' => [
[
'rel' => 'self',
- 'uri' => '/budgets/limits/'.$budgetLimit->id,
+ 'uri' => '/budgets/limits/' . $budgetLimit->id,
],
],
];
From 9ad005e31fcabca44840c927c2772a1fbcc09937 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Sat, 30 Nov 2024 06:19:21 +0100
Subject: [PATCH 004/122] Add edit button for notes
https://github.com/firefly-iii/firefly-iii/issues/5523
---
.../Budget/BudgetLimitController.php | 95 ++++++++++++-------
.../Controllers/Budget/IndexController.php | 1 +
public/v1/js/ff/budgets/index.js | 20 ++++
resources/lang/en_US/firefly.php | 4 +
.../views/budgets/budget-limits/create.twig | 4 +
.../views/budgets/budget-limits/edit.twig | 28 ++++++
.../views/budgets/budget-limits/show.twig | 20 ++++
resources/views/budgets/index.twig | 11 ++-
routes/web.php | 8 +-
9 files changed, 154 insertions(+), 37 deletions(-)
create mode 100644 resources/views/budgets/budget-limits/edit.twig
create mode 100644 resources/views/budgets/budget-limits/show.twig
diff --git a/app/Http/Controllers/Budget/BudgetLimitController.php b/app/Http/Controllers/Budget/BudgetLimitController.php
index effd7ac2cb..c1dbe62020 100644
--- a/app/Http/Controllers/Budget/BudgetLimitController.php
+++ b/app/Http/Controllers/Budget/BudgetLimitController.php
@@ -63,7 +63,7 @@ class BudgetLimitController extends Controller
parent::__construct();
$this->middleware(
function ($request, $next) {
- app('view')->share('title', (string)trans('firefly.budgets'));
+ app('view')->share('title', (string) trans('firefly.budgets'));
app('view')->share('mainTitleIcon', 'fa-pie-chart');
$this->repository = app(BudgetRepositoryInterface::class);
$this->opsRepository = app(OperationsRepositoryInterface::class);
@@ -84,7 +84,7 @@ class BudgetLimitController extends Controller
$budgetLimits = $this->blRepository->getBudgetLimits($budget, $start, $end);
// remove already budgeted currencies with the same date range
- $currencies = $collection->filter(
+ $currencies = $collection->filter(
static function (TransactionCurrency $currency) use ($budgetLimits, $start, $end) {
/** @var BudgetLimit $limit */
foreach ($budgetLimits as $limit) {
@@ -101,6 +101,24 @@ class BudgetLimitController extends Controller
return view('budgets.budget-limits.create', compact('start', 'end', 'currencies', 'budget'));
}
+ /**
+ * @return Factory|View
+ */
+ public function show(BudgetLimit $budgetLimit)
+ {
+ $notes = $this->blRepository->getNoteText($budgetLimit);
+ return view('budgets.budget-limits.show', compact('budgetLimit', 'notes'));
+ }
+
+ /**
+ * @return Factory|View
+ */
+ public function edit(BudgetLimit $budgetLimit)
+ {
+ $notes = $this->blRepository->getNoteText($budgetLimit);
+ return view('budgets.budget-limits.edit', compact('budgetLimit', 'notes'));
+ }
+
/**
* @return Redirector|RedirectResponse
*/
@@ -117,23 +135,23 @@ class BudgetLimitController extends Controller
*
* @throws FireflyException
*/
- public function store(Request $request): JsonResponse|RedirectResponse
+ public function store(Request $request): JsonResponse | RedirectResponse
{
app('log')->debug('Going to store new budget-limit.', $request->all());
// first search for existing one and update it if necessary.
- $currency = $this->currencyRepos->find((int)$request->get('transaction_currency_id'));
- $budget = $this->repository->find((int)$request->get('budget_id'));
+ $currency = $this->currencyRepos->find((int) $request->get('transaction_currency_id'));
+ $budget = $this->repository->find((int) $request->get('budget_id'));
if (null === $currency || null === $budget) {
throw new FireflyException('No valid currency or budget.');
}
- $start = Carbon::createFromFormat('Y-m-d', $request->get('start'));
- $end = Carbon::createFromFormat('Y-m-d', $request->get('end'));
+ $start = Carbon::createFromFormat('Y-m-d', $request->get('start'));
+ $end = Carbon::createFromFormat('Y-m-d', $request->get('end'));
if (null === $start || null === $end) {
return response()->json([]);
}
- $amount = (string)$request->get('amount');
+ $amount = (string) $request->get('amount');
$start->startOfDay();
$end->startOfDay();
@@ -143,7 +161,7 @@ class BudgetLimitController extends Controller
app('log')->debug(sprintf('Start: %s, end: %s', $start->format('Y-m-d'), $end->format('Y-m-d')));
- $limit = $this->blRepository->find($budget, $currency, $start, $end);
+ $limit = $this->blRepository->find($budget, $currency, $start, $end);
// sanity check on amount:
if (0 === bccomp($amount, '0')) {
@@ -154,7 +172,7 @@ class BudgetLimitController extends Controller
// return empty=ish array:
return response()->json([]);
}
- if ((int)$amount > 268435456) { // intentional cast to integer
+ if ((int) $amount > 268435456) { // intentional cast to integer
$amount = '268435456';
}
if (-1 === bccomp($amount, '0')) {
@@ -169,41 +187,47 @@ class BudgetLimitController extends Controller
$limit = $this->blRepository->store(
[
'budget_id' => $request->get('budget_id'),
- 'currency_id' => (int)$request->get('transaction_currency_id'),
+ 'currency_id' => (int) $request->get('transaction_currency_id'),
'start_date' => $start,
'end_date' => $end,
'amount' => $amount,
]
);
}
+ // parse notes, if any.
+ $notes = (string) $request->get('notes');
+ $this->blRepository->setNoteText($limit, $notes);
if ($request->expectsJson()) {
- $array = $limit->toArray();
+ $array = $limit->toArray();
// add some extra metadata:
- $spentArr = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection([$budget]), $currency);
- $array['spent'] = $spentArr[$currency->id]['sum'] ?? '0';
- $array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
- $array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
- $array['days_left'] = (string)$this->activeDaysLeft($start, $end);
+ $spentArr = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection([$budget]), $currency);
+ $array['spent'] = $spentArr[$currency->id]['sum'] ?? '0';
+ $array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
+ $array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
+ $array['days_left'] = (string) $this->activeDaysLeft($start, $end);
// left per day:
- $array['left_per_day'] = 0 === bccomp('0', $array['days_left']) ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
+ $array['left_per_day'] = 0 === bccomp('0', $array['days_left']) ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
// left per day formatted.
$array['left_per_day_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $array['left_per_day']);
+ // notes:
+ $array['notes'] = $this->blRepository->getNoteText($limit);
+
return response()->json($array);
}
return redirect(route('budgets.index'));
}
- public function update(Request $request, BudgetLimit $budgetLimit): JsonResponse
+ public function update(Request $request, BudgetLimit $budgetLimit): JsonResponse|RedirectResponse
{
- $amount = (string)$request->get('amount');
+ $amount = (string) $request->get('amount');
if ('' === $amount) {
$amount = '0';
}
- if ((int)$amount > 268435456) { // 268 million, intentional integer
+ if ((int) $amount > 268435456) { // 268 million, intentional integer
$amount = '268435456';
}
// sanity check on amount:
@@ -211,7 +235,7 @@ class BudgetLimitController extends Controller
$budgetId = $budgetLimit->budget_id;
$currency = $budgetLimit->transactionCurrency;
$this->blRepository->destroyBudgetLimit($budgetLimit);
- $array = [
+ $array = [
'budget_id' => $budgetId,
'left_formatted' => app('amount')->formatAnything($currency, '0'),
'left_per_day_formatted' => app('amount')->formatAnything($currency, '0'),
@@ -224,29 +248,36 @@ class BudgetLimitController extends Controller
if (-1 === bccomp($amount, '0')) {
$amount = bcmul($amount, '-1');
}
+ $notes = (string)$request->get('notes');
+ if(strlen($notes) > 32768) {
+ $notes = substr($notes, 0, 32768);
+ }
- $limit = $this->blRepository->update($budgetLimit, ['amount' => $amount]);
+
+ $limit = $this->blRepository->update($budgetLimit, ['amount' => $amount,'notes' => $notes]);
app('preferences')->mark();
- $array = $limit->toArray();
+ $array = $limit->toArray();
- $spentArr = $this->opsRepository->sumExpenses(
+ $spentArr = $this->opsRepository->sumExpenses(
$limit->start_date,
$limit->end_date,
null,
new Collection([$budgetLimit->budget]),
$budgetLimit->transactionCurrency
);
- $daysLeft = $this->activeDaysLeft($limit->start_date, $limit->end_date);
- $array['spent'] = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0';
- $array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
- $array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
- $array['days_left'] = (string)$daysLeft;
- $array['left_per_day'] = 0 === $daysLeft ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
+ $daysLeft = $this->activeDaysLeft($limit->start_date, $limit->end_date);
+ $array['spent'] = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0';
+ $array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
+ $array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
+ $array['days_left'] = (string) $daysLeft;
+ $array['left_per_day'] = 0 === $daysLeft ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
// left per day formatted.
$array['amount'] = app('steam')->bcround($limit['amount'], $limit->transactionCurrency->decimal_places);
$array['left_per_day_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $array['left_per_day']);
-
+ if ('true' === $request->get('redirect')) {
+ return redirect(route('budgets.index'));
+ }
return response()->json($array);
}
}
diff --git a/app/Http/Controllers/Budget/IndexController.php b/app/Http/Controllers/Budget/IndexController.php
index fd182e9212..5fde689d96 100644
--- a/app/Http/Controllers/Budget/IndexController.php
+++ b/app/Http/Controllers/Budget/IndexController.php
@@ -213,6 +213,7 @@ class IndexController extends Controller
$array['budgeted'][] = [
'id' => $limit->id,
'amount' => $amount,
+ 'notes' => $this->blRepository->getNoteText($limit),
'start_date' => $limit->start_date->isoFormat($this->monthAndDayFormat),
'end_date' => $limit->end_date->isoFormat($this->monthAndDayFormat),
'in_range' => $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end),
diff --git a/public/v1/js/ff/budgets/index.js b/public/v1/js/ff/budgets/index.js
index b6d702fa95..63444d096b 100644
--- a/public/v1/js/ff/budgets/index.js
+++ b/public/v1/js/ff/budgets/index.js
@@ -35,6 +35,8 @@ $(function () {
$('.budget_amount').on('change', updateBudgetedAmount);
$('.create_bl').on('click', createBudgetLimit);
+ $('.edit_bl').on('click', editBudgetLimit);
+ $('.show_bl').on('click', showBudgetLimit);
$('.delete_bl').on('click', deleteBudgetLimit);
@@ -216,6 +218,24 @@ function createBudgetLimit(e) {
return false;
}
+function editBudgetLimit(e) {
+ var button = $(e.currentTarget);
+ var budgetLimitId = button.data('id');
+ $('#defaultModal').empty().load(editBudgetLimitUrl.replace('REPLACEME', budgetLimitId.toString()), function () {
+ $('#defaultModal').modal('show');
+ });
+ return false;
+}
+
+function showBudgetLimit(e) {
+ var button = $(e.currentTarget);
+ var budgetLimitId = button.data('id');
+ $('#defaultModal').empty().load(showBudgetLimitUrl.replace('REPLACEME', budgetLimitId.toString()), function () {
+ $('#defaultModal').modal('show');
+ });
+ return false;
+}
+
function deleteBudgetLimit(e) {
e.preventDefault();
var button = $(e.currentTarget);
diff --git a/resources/lang/en_US/firefly.php b/resources/lang/en_US/firefly.php
index e472b7484a..aa395cd3da 100644
--- a/resources/lang/en_US/firefly.php
+++ b/resources/lang/en_US/firefly.php
@@ -2068,6 +2068,10 @@ return [
'opt_group_l_Mortgage' => 'Liability: Mortgage',
'opt_group_l_Credit card' => 'Liability: Credit card',
'notes' => 'Notes',
+ 'view_notes' => 'View notes',
+ 'set_budget_limit_notes' => 'View the notes for this budgeted amount',
+ 'edit_bl_notes' => 'Edit notes',
+ 'update_bl_notes' => 'Update notes',
'unknown_journal_error' => 'Could not store the transaction. Please check the log files.',
'attachment_not_found' => 'This attachment could not be found.',
'journal_link_bill' => 'This transaction is linked to bill :name. To remove the connection, uncheck the checkbox. Use rules to connect it to another bill.',
diff --git a/resources/views/budgets/budget-limits/create.twig b/resources/views/budgets/budget-limits/create.twig
index ce0c05d06a..112bd739e7 100644
--- a/resources/views/budgets/budget-limits/create.twig
+++ b/resources/views/budgets/budget-limits/create.twig
@@ -25,6 +25,10 @@
+
+
+ {{ trans('firefly.field_supports_markdown')|raw }}
+
@@ -444,6 +451,8 @@
var createBudgetLimitUrl = "{{ route('budget-limits.create', ['REPLACEME', start.format('Y-m-d'), end.format('Y-m-d')]) }}";
var storeBudgetLimitUrl = "{{ route('budget-limits.store') }}";
var updateBudgetLimitUrl = "{{ route('budget-limits.update', ['REPLACEME']) }}";
+ var showBudgetLimitUrl = "{{ route('budget-limits.show', ['REPLACEME']) }}";
+ var editBudgetLimitUrl = "{{ route('budget-limits.edit', ['REPLACEME']) }}";
var deleteBudgetLimitUrl = "{{ route('budget-limits.delete', ['REPLACEME']) }}";
var totalBudgetedUrl = "{{ route('json.budget.total-budgeted', ['REPLACEME', start.format('Y-m-d'), end.format('Y-m-d')]) }}";
diff --git a/routes/web.php b/routes/web.php
index e5a9b8c84f..a702e49163 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -304,10 +304,10 @@ Route::group(
Route::group(
['middleware' => 'user-full-auth', 'namespace' => 'FireflyIII\Http\Controllers', 'prefix' => 'budget-limits', 'as' => 'budget-limits.'],
static function (): void {
- Route::get('create/{budget}/{start_date}/{end_date}', ['uses' => 'Budget\BudgetLimitController@create', 'as' => 'create'])
- ->where(['start_date' => DATEFORMAT])
- ->where(['end_date' => DATEFORMAT])
- ;
+ Route::get('create/{budget}/{start_date}/{end_date}', ['uses' => 'Budget\BudgetLimitController@create', 'as' => 'create'])->where(['start_date' => DATEFORMAT])->where(['end_date' => DATEFORMAT]);
+ Route::get('edit/{budgetLimit}', ['uses' => 'Budget\BudgetLimitController@edit', 'as' => 'edit']);
+ Route::get('show/{budgetLimit}', ['uses' => 'Budget\BudgetLimitController@show', 'as' => 'show']);
+
Route::post('store', ['uses' => 'Budget\BudgetLimitController@store', 'as' => 'store']);
Route::post('delete/{budgetLimit}', ['uses' => 'Budget\BudgetLimitController@delete', 'as' => 'delete']);
From 92190bbc54bf681891d5d739da678e1bf38311f8 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Sat, 30 Nov 2024 15:57:11 +0100
Subject: [PATCH 005/122] Rename fields in piggy bank.
---
.../Autocomplete/PiggyBankController.php | 2 +-
.../Commands/Correction/CorrectAmounts.php | 4 +-
app/Handlers/Observer/PiggyBankObserver.php | 10 +-
.../Controllers/PiggyBank/IndexController.php | 1 +
app/Models/PiggyBank.php | 22 ++--
app/Models/PiggyBankRepetition.php | 2 +-
.../2021_08_28_073733_user_groups.php | 1 +
.../2024_11_30_075826_multi_piggy.php | 103 ++++++++++++++++++
8 files changed, 127 insertions(+), 18 deletions(-)
create mode 100644 database/migrations/2024_11_30_075826_multi_piggy.php
diff --git a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php
index 3373d6c708..1c29c51bec 100644
--- a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php
+++ b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php
@@ -105,7 +105,7 @@ class PiggyBankController extends Controller
/** @var PiggyBank $piggy */
foreach ($piggies as $piggy) {
$currency = $this->accountRepository->getAccountCurrency($piggy->account) ?? $defaultCurrency;
- $currentAmount = $this->piggyRepository->getRepetition($piggy)->currentamount ?? '0';
+ $currentAmount = $this->piggyRepository->getRepetition($piggy)->current_amount ?? '0';
$objectGroup = $piggy->objectGroups()->first();
$response[] = [
'id' => (string)$piggy->id,
diff --git a/app/Console/Commands/Correction/CorrectAmounts.php b/app/Console/Commands/Correction/CorrectAmounts.php
index ad30463120..73ff3b3309 100644
--- a/app/Console/Commands/Correction/CorrectAmounts.php
+++ b/app/Console/Commands/Correction/CorrectAmounts.php
@@ -173,7 +173,7 @@ class CorrectAmounts extends Command
/** @var PiggyBankRepetition $item */
foreach ($set as $item) {
- $item->currentamount = app('steam')->positive($item->currentamount);
+ $item->currentamount = app('steam')->positive($item->current_amount);
$item->save();
}
$this->friendlyInfo(sprintf('Corrected %d piggy bank repetition amount(s).', $count));
@@ -191,7 +191,7 @@ class CorrectAmounts extends Command
/** @var PiggyBank $item */
foreach ($set as $item) {
- $item->targetamount = app('steam')->positive($item->targetamount);
+ $item->targetamount = app('steam')->positive($item->target_amount);
$item->save();
}
$this->friendlyInfo(sprintf('Corrected %d piggy bank amount(s).', $count));
diff --git a/app/Handlers/Observer/PiggyBankObserver.php b/app/Handlers/Observer/PiggyBankObserver.php
index 5bd961f0e5..2857f7c2b7 100644
--- a/app/Handlers/Observer/PiggyBankObserver.php
+++ b/app/Handlers/Observer/PiggyBankObserver.php
@@ -37,11 +37,11 @@ class PiggyBankObserver
app('log')->debug('Observe "created" of a piggy bank.');
$repetition = new PiggyBankRepetition();
$repetition->piggyBank()->associate($piggyBank);
- $repetition->startdate = $piggyBank->startdate;
- $repetition->startdate_tz = $piggyBank->startdate->format('e');
- $repetition->targetdate = $piggyBank->targetdate;
- $repetition->targetdate_tz = $piggyBank->targetdate?->format('e');
- $repetition->currentamount = '0';
+ $repetition->start_date = $piggyBank->startdate;
+ $repetition->start_date_tz = $piggyBank->startdate->format('e');
+ $repetition->target_date = $piggyBank->targetdate;
+ $repetition->target_date_tz = $piggyBank->targetdate?->format('e');
+ $repetition->current_amount = '0';
$repetition->save();
}
diff --git a/app/Http/Controllers/PiggyBank/IndexController.php b/app/Http/Controllers/PiggyBank/IndexController.php
index 72396eb20d..9c3578550e 100644
--- a/app/Http/Controllers/PiggyBank/IndexController.php
+++ b/app/Http/Controllers/PiggyBank/IndexController.php
@@ -27,6 +27,7 @@ namespace FireflyIII\Http\Controllers\PiggyBank;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller;
+use FireflyIII\Models\Account;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\ObjectGroup\OrganisesObjectGroups;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php
index abef05764f..0edfa05b9e 100644
--- a/app/Models/PiggyBank.php
+++ b/app/Models/PiggyBank.php
@@ -27,6 +27,7 @@ use FireflyIII\Support\Models\ReturnsIntegerIdTrait;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
@@ -46,17 +47,15 @@ class PiggyBank extends Model
'created_at' => 'datetime',
'updated_at' => 'datetime',
'deleted_at' => 'datetime',
- 'startdate' => 'date',
- 'targetdate' => 'date',
+ 'start_date' => 'date',
+ 'target_date' => 'date',
'order' => 'int',
'active' => 'boolean',
'encrypted' => 'boolean',
- 'targetamount' => 'string',
+ 'target_amount' => 'string',
];
- protected $fillable = ['name', 'account_id', 'order', 'targetamount', 'startdate', 'startdate_tz', 'targetdate', 'targetdate_tz', 'active'];
-
- protected $hidden = ['targetamount_encrypted', 'encrypted'];
+ protected $fillable = ['name', 'account_id', 'order', 'target_amount', 'start_date', 'start_date_tz', 'target_date', 'target_date_tz', 'active'];
/**
* Route binder. Converts the key in the URL to the specified object (or throw 404).
@@ -110,6 +109,11 @@ class PiggyBank extends Model
return $this->hasMany(PiggyBankEvent::class);
}
+ public function accounts(): BelongsToMany
+ {
+ return $this->belongsToMany(Account::class);
+ }
+
public function piggyBankRepetitions(): HasMany
{
return $this->hasMany(PiggyBankRepetition::class);
@@ -118,9 +122,9 @@ class PiggyBank extends Model
/**
* @param mixed $value
*/
- public function setTargetamountAttribute($value): void
+ public function setTargetAmountAttribute($value): void
{
- $this->attributes['targetamount'] = (string)$value;
+ $this->attributes['target_amount'] = (string)$value;
}
protected function accountId(): Attribute
@@ -140,7 +144,7 @@ class PiggyBank extends Model
/**
* Get the max amount
*/
- protected function targetamount(): Attribute
+ protected function targetAmount(): Attribute
{
return Attribute::make(
get: static fn ($value) => (string)$value,
diff --git a/app/Models/PiggyBankRepetition.php b/app/Models/PiggyBankRepetition.php
index 38008361dd..eaa42bed7d 100644
--- a/app/Models/PiggyBankRepetition.php
+++ b/app/Models/PiggyBankRepetition.php
@@ -47,7 +47,7 @@ class PiggyBankRepetition extends Model
'virtual_balance' => 'string',
];
- protected $fillable = ['piggy_bank_id', 'startdate', 'startdate_tz', 'targetdate', 'targetdate_tz', 'currentamount'];
+ protected $fillable = ['piggy_bank_id', 'start_date', 'start_date_tz', 'target_date', 'target_date_tz', 'current_amount'];
public function piggyBank(): BelongsTo
{
diff --git a/database/migrations/2021_08_28_073733_user_groups.php b/database/migrations/2021_08_28_073733_user_groups.php
index 21a25beed4..1111ddc671 100644
--- a/database/migrations/2021_08_28_073733_user_groups.php
+++ b/database/migrations/2021_08_28_073733_user_groups.php
@@ -42,6 +42,7 @@ class UserGroups extends Migration
'categories',
'recurrences',
'object_groups',
+ 'preferences',
'rule_groups',
'rules',
'tags',
diff --git a/database/migrations/2024_11_30_075826_multi_piggy.php b/database/migrations/2024_11_30_075826_multi_piggy.php
new file mode 100644
index 0000000000..d1675663f2
--- /dev/null
+++ b/database/migrations/2024_11_30_075826_multi_piggy.php
@@ -0,0 +1,103 @@
+dropForeign('piggy_banks_account_id_foreign');
+ });
+ Schema::table('piggy_banks', static function (Blueprint $table) {
+ // 2. make column nullable.
+ $table->unsignedInteger('account_id')->nullable()->change();
+ });
+ Schema::table('piggy_banks', static function (Blueprint $table) {
+ // 3. add currency
+ $table->integer('transaction_currency_id', false, true)->after('account_id');
+ $table->foreign('transaction_currency_id','unique_currency')->references('id')->on('transaction_currencies')->onDelete('cascade');
+ });
+ Schema::table('piggy_banks', static function (Blueprint $table) {
+ // 4. rename columns
+ $table->renameColumn('targetamount', 'target_amount');
+ $table->renameColumn('startdate', 'start_date');
+ $table->renameColumn('targetdate', 'target_date');
+ $table->renameColumn('startdate_tz', 'start_date_tz');
+ $table->renameColumn('targetdate_tz', 'target_date_tz');
+ });
+ Schema::table('piggy_banks', static function (Blueprint $table) {
+ // 5. add new index
+ $table->foreign('account_id')->references('id')->on('accounts')->onDelete('set null');
+ });
+
+ // rename some fields in piggy bank reps.
+ Schema::table('piggy_bank_repetitions', static function (Blueprint $table) {
+ // 6. rename columns
+ $table->renameColumn('currentamount', 'current_amount');
+ $table->renameColumn('startdate', 'start_date');
+ $table->renameColumn('targetdate', 'target_date');
+ $table->renameColumn('startdate_tz', 'start_date_tz');
+ $table->renameColumn('targetdate_tz', 'target_date_tz');
+ });
+
+ // create table account_piggy_bank
+ Schema::create('account_piggy_bank', static function (Blueprint $table) {
+ $table->id();
+ $table->integer('account_id', false, true);
+ $table->integer('piggy_bank_id',false, true);
+ $table->decimal('current_amount', 32, 12)->default('0');
+ $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
+ $table->foreign('piggy_bank_id')->references('id')->on('piggy_banks')->onDelete('cascade');
+ $table->unique(['account_id', 'piggy_bank_id'],'unique_piggy_save');
+ });
+
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::table('piggy_banks', static function (Blueprint $table) {
+ // 1. drop account index again.
+ $table->dropForeign('piggy_banks_account_id_foreign');
+
+ // rename columns again.
+ $table->renameColumn('target_amount', 'targetamount');
+ $table->renameColumn('start_date', 'startdate');
+ $table->renameColumn('target_date', 'targetdate');
+ $table->renameColumn('start_date_tz', 'startdate_tz');
+ $table->renameColumn('target_date_tz', 'targetdate_tz');
+
+ // 3. drop currency again + index
+ $table->dropForeign('unique_currency');
+ $table->dropColumn('transaction_currency_id');
+
+ // 2. make column non-nullable.
+ $table->unsignedInteger('account_id')->change();
+
+ // 5. add new index
+ $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
+ });
+
+ // rename some fields in piggy bank reps.
+ Schema::table('piggy_bank_repetitions', static function (Blueprint $table) {
+ // 6. rename columns
+ $table->renameColumn('current_amount', 'currentamount');
+ $table->renameColumn('start_date', 'startdate');
+ $table->renameColumn('target_date', 'targetdate');
+ $table->renameColumn('start_date_tz', 'startdate_tz');
+ $table->renameColumn('target_date_tz', 'targetdate_tz');
+ });
+
+ Schema::dropIfExists('account_piggy_bank');
+ }
+};
From 21a6927279f25ab41b3462d10c7e9d74e4325da1 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Sat, 30 Nov 2024 16:02:30 +0100
Subject: [PATCH 006/122] Rename fields for piggy bank
---
.../Autocomplete/PiggyBankController.php | 2 +-
.../Commands/Correction/CorrectAmounts.php | 4 +-
app/Console/Commands/Tools/ApplyRules.php | 4 +-
app/Handlers/Observer/PiggyBankObserver.php | 8 ++--
.../Controllers/Chart/PiggyBankController.php | 2 +-
.../Controllers/Json/FrontpageController.php | 6 +--
.../PiggyBank/AmountController.php | 8 ++--
.../Controllers/PiggyBank/EditController.php | 8 ++--
app/Models/PiggyBankRepetition.php | 20 ++++-----
.../PiggyBank/ModifiesPiggyBanks.php | 42 +++++++++----------
.../PiggyBank/PiggyBankRepository.php | 22 +++++-----
app/Support/Export/ExportDataGenerator.php | 8 ++--
.../Actions/UpdatePiggybank.php | 6 +--
app/Transformers/PiggyBankTransformer.php | 8 ++--
app/Transformers/V2/PiggyBankTransformer.php | 10 ++---
15 files changed, 79 insertions(+), 79 deletions(-)
diff --git a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php
index 1c29c51bec..cf29aa037a 100644
--- a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php
+++ b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php
@@ -114,7 +114,7 @@ class PiggyBankController extends Controller
'%s (%s / %s)',
$piggy->name,
app('amount')->formatAnything($currency, $currentAmount, false),
- app('amount')->formatAnything($currency, $piggy->targetamount, false),
+ app('amount')->formatAnything($currency, $piggy->target_amount, false),
),
'currency_id' => (string)$currency->id,
'currency_name' => $currency->name,
diff --git a/app/Console/Commands/Correction/CorrectAmounts.php b/app/Console/Commands/Correction/CorrectAmounts.php
index 73ff3b3309..639c96edec 100644
--- a/app/Console/Commands/Correction/CorrectAmounts.php
+++ b/app/Console/Commands/Correction/CorrectAmounts.php
@@ -173,7 +173,7 @@ class CorrectAmounts extends Command
/** @var PiggyBankRepetition $item */
foreach ($set as $item) {
- $item->currentamount = app('steam')->positive($item->current_amount);
+ $item->current_amount = app('steam')->positive($item->current_amount);
$item->save();
}
$this->friendlyInfo(sprintf('Corrected %d piggy bank repetition amount(s).', $count));
@@ -191,7 +191,7 @@ class CorrectAmounts extends Command
/** @var PiggyBank $item */
foreach ($set as $item) {
- $item->targetamount = app('steam')->positive($item->target_amount);
+ $item->target_amount = app('steam')->positive($item->target_amount);
$item->save();
}
$this->friendlyInfo(sprintf('Corrected %d piggy bank amount(s).', $count));
diff --git a/app/Console/Commands/Tools/ApplyRules.php b/app/Console/Commands/Tools/ApplyRules.php
index 5e6e64552f..023864e1aa 100644
--- a/app/Console/Commands/Tools/ApplyRules.php
+++ b/app/Console/Commands/Tools/ApplyRules.php
@@ -128,7 +128,7 @@ class ApplyRules extends Command
$ruleEngine->addOperator(['type' => 'account_id', 'value' => $list]);
// add the date as a filter:
- $ruleEngine->addOperator(['type' => 'date_after', 'value' => $this->startDate->format('Y-m-d')]);
+ $ruleEngine->addOperator(['type' => 'date_after', 'value' => $this->start_date->format('Y-m-d')]);
$ruleEngine->addOperator(['type' => 'date_before', 'value' => $this->endDate->format('Y-m-d')]);
// start running rules.
@@ -296,7 +296,7 @@ class ApplyRules extends Command
[$inputEnd, $inputStart] = [$inputStart, $inputEnd];
}
- $this->startDate = $inputStart;
+ $this->start_date = $inputStart;
$this->endDate = $inputEnd;
}
diff --git a/app/Handlers/Observer/PiggyBankObserver.php b/app/Handlers/Observer/PiggyBankObserver.php
index 2857f7c2b7..40bde63a1a 100644
--- a/app/Handlers/Observer/PiggyBankObserver.php
+++ b/app/Handlers/Observer/PiggyBankObserver.php
@@ -37,10 +37,10 @@ class PiggyBankObserver
app('log')->debug('Observe "created" of a piggy bank.');
$repetition = new PiggyBankRepetition();
$repetition->piggyBank()->associate($piggyBank);
- $repetition->start_date = $piggyBank->startdate;
- $repetition->start_date_tz = $piggyBank->startdate->format('e');
- $repetition->target_date = $piggyBank->targetdate;
- $repetition->target_date_tz = $piggyBank->targetdate?->format('e');
+ $repetition->start_date = $piggyBank->start_date;
+ $repetition->start_date_tz = $piggyBank->start_date->format('e');
+ $repetition->target_date = $piggyBank->target_date;
+ $repetition->target_date_tz = $piggyBank->target_date?->format('e');
$repetition->current_amount = '0';
$repetition->save();
}
diff --git a/app/Http/Controllers/Chart/PiggyBankController.php b/app/Http/Controllers/Chart/PiggyBankController.php
index 4bf27e2748..7bbfd0aae0 100644
--- a/app/Http/Controllers/Chart/PiggyBankController.php
+++ b/app/Http/Controllers/Chart/PiggyBankController.php
@@ -75,7 +75,7 @@ class PiggyBankController extends Controller
$locale = app('steam')->getLocale();
// get first event or start date of piggy bank or today
- $startDate = $piggyBank->startdate ?? today(config('app.timezone'));
+ $startDate = $piggyBank->start_date ?? today(config('app.timezone'));
/** @var null|PiggyBankEvent $firstEvent */
$firstEvent = $set->first();
diff --git a/app/Http/Controllers/Json/FrontpageController.php b/app/Http/Controllers/Json/FrontpageController.php
index a8ab134e96..959c1ce4e6 100644
--- a/app/Http/Controllers/Json/FrontpageController.php
+++ b/app/Http/Controllers/Json/FrontpageController.php
@@ -50,15 +50,15 @@ class FrontpageController extends Controller
if (1 === bccomp($amount, '0')) {
// percentage!
$pct = 0;
- if (0 !== bccomp($piggyBank->targetamount, '0')) {
- $pct = (int)bcmul(bcdiv($amount, $piggyBank->targetamount), '100');
+ if (0 !== bccomp($piggyBank->target_amount, '0')) {
+ $pct = (int)bcmul(bcdiv($amount, $piggyBank->target_amount), '100');
}
$entry = [
'id' => $piggyBank->id,
'name' => $piggyBank->name,
'amount' => $amount,
- 'target' => $piggyBank->targetamount,
+ 'target' => $piggyBank->target_amount,
'percentage' => $pct,
];
diff --git a/app/Http/Controllers/PiggyBank/AmountController.php b/app/Http/Controllers/PiggyBank/AmountController.php
index 28085daa06..d14446d291 100644
--- a/app/Http/Controllers/PiggyBank/AmountController.php
+++ b/app/Http/Controllers/PiggyBank/AmountController.php
@@ -72,8 +72,8 @@ class AmountController extends Controller
$leftOnAccount = $this->piggyRepos->leftOnAccount($piggyBank, today(config('app.timezone')));
$savedSoFar = $this->piggyRepos->getCurrentAmount($piggyBank);
$maxAmount = $leftOnAccount;
- if (0 !== bccomp($piggyBank->targetamount, '0')) {
- $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar);
+ if (0 !== bccomp($piggyBank->target_amount, '0')) {
+ $leftToSave = bcsub($piggyBank->target_amount, $savedSoFar);
$maxAmount = min($leftOnAccount, $leftToSave);
}
$currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency();
@@ -94,8 +94,8 @@ class AmountController extends Controller
$savedSoFar = $this->piggyRepos->getCurrentAmount($piggyBank);
$maxAmount = $leftOnAccount;
- if (0 !== bccomp($piggyBank->targetamount, '0')) {
- $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar);
+ if (0 !== bccomp($piggyBank->target_amount, '0')) {
+ $leftToSave = bcsub($piggyBank->target_amount, $savedSoFar);
$maxAmount = min($leftOnAccount, $leftToSave);
}
$currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency();
diff --git a/app/Http/Controllers/PiggyBank/EditController.php b/app/Http/Controllers/PiggyBank/EditController.php
index c0a2de083e..6df3ec3101 100644
--- a/app/Http/Controllers/PiggyBank/EditController.php
+++ b/app/Http/Controllers/PiggyBank/EditController.php
@@ -77,8 +77,8 @@ class EditController extends Controller
$subTitleIcon = 'fa-pencil';
$note = $piggyBank->notes()->first();
// Flash some data to fill the form.
- $targetDate = $piggyBank->targetdate?->format('Y-m-d');
- $startDate = $piggyBank->startdate?->format('Y-m-d');
+ $targetDate = $piggyBank->target_date?->format('Y-m-d');
+ $startDate = $piggyBank->start_date?->format('Y-m-d');
$currency = $this->accountRepository->getAccountCurrency($piggyBank->account);
if (null === $currency) {
$currency = app('amount')->getDefaultCurrency();
@@ -87,13 +87,13 @@ class EditController extends Controller
$preFilled = [
'name' => $piggyBank->name,
'account_id' => $piggyBank->account_id,
- 'targetamount' => app('steam')->bcround($piggyBank->targetamount, $currency->decimal_places),
+ 'targetamount' => app('steam')->bcround($piggyBank->target_amount, $currency->decimal_places),
'targetdate' => $targetDate,
'startdate' => $startDate,
'object_group' => null !== $piggyBank->objectGroups->first() ? $piggyBank->objectGroups->first()->title : '',
'notes' => null === $note ? '' : $note->text,
];
- if (0 === bccomp($piggyBank->targetamount, '0')) {
+ if (0 === bccomp($piggyBank->target_amount, '0')) {
$preFilled['targetamount'] = '';
}
session()->flash('preFilled', $preFilled);
diff --git a/app/Models/PiggyBankRepetition.php b/app/Models/PiggyBankRepetition.php
index eaa42bed7d..378af8edb7 100644
--- a/app/Models/PiggyBankRepetition.php
+++ b/app/Models/PiggyBankRepetition.php
@@ -42,8 +42,8 @@ class PiggyBankRepetition extends Model
= [
'created_at' => 'datetime',
'updated_at' => 'datetime',
- 'startdate' => SeparateTimezoneCaster::class,
- 'targetdate' => SeparateTimezoneCaster::class,
+ 'start_date' => SeparateTimezoneCaster::class,
+ 'target_date' => SeparateTimezoneCaster::class,
'virtual_balance' => 'string',
];
@@ -56,7 +56,7 @@ class PiggyBankRepetition extends Model
public function scopeOnDates(EloquentBuilder $query, Carbon $start, Carbon $target): EloquentBuilder
{
- return $query->where('startdate', $start->format('Y-m-d'))->where('targetdate', $target->format('Y-m-d'));
+ return $query->where('start_date', $start->format('Y-m-d'))->where('target_date', $target->format('Y-m-d'));
}
/**
@@ -66,14 +66,14 @@ class PiggyBankRepetition extends Model
{
return $query->where(
static function (EloquentBuilder $q) use ($date): void {
- $q->where('startdate', '<=', $date->format('Y-m-d 00:00:00'));
- $q->orWhereNull('startdate');
+ $q->where('start_date', '<=', $date->format('Y-m-d 00:00:00'));
+ $q->orWhereNull('start_date');
}
)
->where(
static function (EloquentBuilder $q) use ($date): void {
- $q->where('targetdate', '>=', $date->format('Y-m-d 00:00:00'));
- $q->orWhereNull('targetdate');
+ $q->where('target_date', '>=', $date->format('Y-m-d 00:00:00'));
+ $q->orWhereNull('target_date');
}
)
;
@@ -82,15 +82,15 @@ class PiggyBankRepetition extends Model
/**
* @param mixed $value
*/
- public function setCurrentamountAttribute($value): void
+ public function setCurrentAmountAttribute($value): void
{
- $this->attributes['currentamount'] = (string)$value;
+ $this->attributes['current_amount'] = (string)$value;
}
/**
* Get the amount
*/
- protected function currentamount(): Attribute
+ protected function currentAmount(): Attribute
{
return Attribute::make(
get: static fn ($value) => (string)$value,
diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
index df3e98c10e..c5f9293c2e 100644
--- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
+++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
@@ -59,7 +59,7 @@ trait ModifiesPiggyBanks
if (null === $repetition) {
return false;
}
- $repetition->currentamount = bcsub($repetition->currentamount, $amount);
+ $repetition->current_amount = bcsub($repetition->current_amount, $amount);
$repetition->save();
app('log')->debug('addAmount [a]: Trigger change for negative amount.');
@@ -74,8 +74,8 @@ trait ModifiesPiggyBanks
if (null === $repetition) {
return false;
}
- $currentAmount = $repetition->currentamount ?? '0';
- $repetition->currentamount = bcadd($currentAmount, $amount);
+ $currentAmount = $repetition->current_amount ?? '0';
+ $repetition->current_amount = bcadd($currentAmount, $amount);
$repetition->save();
app('log')->debug('addAmount [b]: Trigger change for positive amount.');
@@ -88,11 +88,11 @@ trait ModifiesPiggyBanks
{
$today = today(config('app.timezone'));
$leftOnAccount = $this->leftOnAccount($piggyBank, $today);
- $savedSoFar = $this->getRepetition($piggyBank)->currentamount;
+ $savedSoFar = $this->getRepetition($piggyBank)->current_amount;
$maxAmount = $leftOnAccount;
$leftToSave = null;
- if (0 !== bccomp($piggyBank->targetamount, '0')) {
- $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar);
+ if (0 !== bccomp($piggyBank->target_amount, '0')) {
+ $leftToSave = bcsub($piggyBank->target_amount, $savedSoFar);
$maxAmount = 1 === bccomp($leftOnAccount, $leftToSave) ? $leftToSave : $leftOnAccount;
}
@@ -114,7 +114,7 @@ trait ModifiesPiggyBanks
if (null === $repetition) {
return false;
}
- $savedSoFar = $repetition->currentamount;
+ $savedSoFar = $repetition->current_amount;
return bccomp($amount, $savedSoFar) <= 0;
}
@@ -143,12 +143,12 @@ trait ModifiesPiggyBanks
if (null === $repetition) {
return $piggyBank;
}
- $max = $piggyBank->targetamount;
- if (1 === bccomp($amount, $max) && 0 !== bccomp($piggyBank->targetamount, '0')) {
+ $max = $piggyBank->target_amount;
+ if (1 === bccomp($amount, $max) && 0 !== bccomp($piggyBank->target_amount, '0')) {
$amount = $max;
}
- $difference = bcsub($amount, $repetition->currentamount);
- $repetition->currentamount = $amount;
+ $difference = bcsub($amount, $repetition->current_amount);
+ $repetition->current_amount = $amount;
$repetition->save();
if (-1 === bccomp($difference, '0')) {
@@ -213,7 +213,7 @@ trait ModifiesPiggyBanks
// repetition is auto created.
$repetition = $this->getRepetition($piggyBank);
if (null !== $repetition && array_key_exists('current_amount', $data) && '' !== $data['current_amount']) {
- $repetition->currentamount = $data['current_amount'];
+ $repetition->current_amount = $data['current_amount'];
$repetition->save();
}
@@ -318,13 +318,13 @@ trait ModifiesPiggyBanks
// if the piggy bank is now smaller than the current relevant rep,
// remove money from the rep.
$repetition = $this->getRepetition($piggyBank);
- if (null !== $repetition && $repetition->currentamount > $piggyBank->targetamount && 0 !== bccomp($piggyBank->targetamount, '0')) {
- $difference = bcsub($piggyBank->targetamount, $repetition->currentamount);
+ if (null !== $repetition && $repetition->current_amount > $piggyBank->target_amount && 0 !== bccomp($piggyBank->target_amount, '0')) {
+ $difference = bcsub($piggyBank->target_amount, $repetition->current_amount);
// an amount will be removed, create "negative" event:
event(new ChangedAmount($piggyBank, $difference, null, null));
- $repetition->currentamount = $piggyBank->targetamount;
+ $repetition->current_amount = $piggyBank->target_amount;
$repetition->save();
}
@@ -370,18 +370,18 @@ trait ModifiesPiggyBanks
$piggyBank->account_id = (int)$data['account_id'];
}
if (array_key_exists('targetamount', $data) && '' !== $data['targetamount']) {
- $piggyBank->targetamount = $data['targetamount'];
+ $piggyBank->target_amount = $data['targetamount'];
}
if (array_key_exists('targetamount', $data) && '' === $data['targetamount']) {
- $piggyBank->targetamount = '0';
+ $piggyBank->target_amount = '0';
}
if (array_key_exists('targetdate', $data) && '' !== $data['targetdate']) {
- $piggyBank->targetdate = $data['targetdate'];
- $piggyBank->targetdate_tz = $data['targetdate']?->format('e');
+ $piggyBank->target_date = $data['targetdate'];
+ $piggyBank->target_date_tz = $data['targetdate']?->format('e');
}
if (array_key_exists('startdate', $data)) {
- $piggyBank->startdate = $data['startdate'];
- $piggyBank->startdate_tz = $data['targetdate']?->format('e');
+ $piggyBank->start_date = $data['startdate'];
+ $piggyBank->start_date_tz = $data['targetdate']?->format('e');
}
$piggyBank->save();
diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php
index 99d19353a9..b31571b043 100644
--- a/app/Repositories/PiggyBank/PiggyBankRepository.php
+++ b/app/Repositories/PiggyBank/PiggyBankRepository.php
@@ -120,7 +120,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
return '0';
}
- return $rep->currentamount;
+ return $rep->current_amount;
}
public function getRepetition(PiggyBank $piggyBank): ?PiggyBankRepetition
@@ -200,10 +200,10 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
}
app('log')->debug(sprintf('The currency is %s and the amount is %s', $currency->code, $amount));
- $room = bcsub($piggyBank->targetamount, $repetition->currentamount);
- $compare = bcmul($repetition->currentamount, '-1');
+ $room = bcsub($piggyBank->target_amount, $repetition->current_amount);
+ $compare = bcmul($repetition->current_amount, '-1');
- if (0 === bccomp($piggyBank->targetamount, '0')) {
+ if (0 === bccomp($piggyBank->target_amount, '0')) {
// amount is zero? then the "room" is positive amount of we wish to add or remove.
$room = app('steam')->positive($amount);
app('log')->debug(sprintf('Room is now %s', $room));
@@ -223,7 +223,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
// amount is negative and $currentamount is smaller than $amount
if (-1 === bccomp($amount, '0') && 1 === bccomp($compare, $amount)) {
- app('log')->debug(sprintf('Max amount to remove is %f', $repetition->currentamount));
+ app('log')->debug(sprintf('Max amount to remove is %f', $repetition->current_amount));
app('log')->debug(sprintf('Cannot remove %f from piggy bank #%d ("%s")', $amount, $piggyBank->id, $piggyBank->name));
app('log')->debug(sprintf('New amount is %f', $compare));
@@ -267,7 +267,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
/** @var PiggyBank $piggy */
foreach ($set as $piggy) {
- $currentAmount = $this->getRepetition($piggy)->currentamount ?? '0';
+ $currentAmount = $this->getRepetition($piggy)->current_amount ?? '0';
$piggy->name = $piggy->name.' ('.app('amount')->formatAnything($currency, $currentAmount, false).')';
}
@@ -298,11 +298,11 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
if (null === $repetition) {
return $savePerMonth;
}
- if (null !== $piggyBank->targetdate && $repetition->currentamount < $piggyBank->targetamount) {
+ if (null !== $piggyBank->target_date && $repetition->current_amount < $piggyBank->target_amount) {
$now = today(config('app.timezone'));
- $startDate = null !== $piggyBank->startdate && $piggyBank->startdate->gte($now) ? $piggyBank->startdate : $now;
- $diffInMonths = (int)$startDate->diffInMonths($piggyBank->targetdate);
- $remainingAmount = bcsub($piggyBank->targetamount, $repetition->currentamount);
+ $startDate = null !== $piggyBank->start_date && $piggyBank->start_date->gte($now) ? $piggyBank->start_date : $now;
+ $diffInMonths = (int)$startDate->diffInMonths($piggyBank->target_date);
+ $remainingAmount = bcsub($piggyBank->target_amount, $repetition->current_amount);
// more than 1 month to go and still need money to save:
if ($diffInMonths > 0 && 1 === bccomp($remainingAmount, '0')) {
@@ -332,7 +332,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
foreach ($piggies as $current) {
$repetition = $this->getRepetition($current);
if (null !== $repetition) {
- $balance = bcsub($balance, $repetition->currentamount);
+ $balance = bcsub($balance, $repetition->current_amount);
}
}
diff --git a/app/Support/Export/ExportDataGenerator.php b/app/Support/Export/ExportDataGenerator.php
index 2ac986eb7f..7fb74e610b 100644
--- a/app/Support/Export/ExportDataGenerator.php
+++ b/app/Support/Export/ExportDataGenerator.php
@@ -456,10 +456,10 @@ class ExportDataGenerator
$piggy->account->accountType->type,
$piggy->name,
$currency?->code,
- $piggy->targetamount,
- $repetition?->currentamount,
- $piggy->startdate?->format('Y-m-d'),
- $piggy->targetdate?->format('Y-m-d'),
+ $piggy->target_amount,
+ $repetition?->current_amount,
+ $piggy->start_date?->format('Y-m-d'),
+ $piggy->target_date?->format('Y-m-d'),
$piggy->order,
$piggy->active,
];
diff --git a/app/TransactionRules/Actions/UpdatePiggybank.php b/app/TransactionRules/Actions/UpdatePiggybank.php
index 3e90a79ad9..1e748c1926 100644
--- a/app/TransactionRules/Actions/UpdatePiggybank.php
+++ b/app/TransactionRules/Actions/UpdatePiggybank.php
@@ -178,15 +178,15 @@ class UpdatePiggybank implements ActionInterface
$repository->setUser($journal->user);
// how much can we add to the piggy bank?
- if (0 !== bccomp($piggyBank->targetamount, '0')) {
- $toAdd = bcsub($piggyBank->targetamount, $repository->getCurrentAmount($piggyBank));
+ if (0 !== bccomp($piggyBank->target_amount, '0')) {
+ $toAdd = bcsub($piggyBank->target_amount, $repository->getCurrentAmount($piggyBank));
app('log')->debug(sprintf('Max amount to add to piggy bank is %s, amount is %s', $toAdd, $amount));
// update amount to fit:
$amount = -1 === bccomp($amount, $toAdd) ? $amount : $toAdd;
app('log')->debug(sprintf('Amount is now %s', $amount));
}
- if (0 === bccomp($piggyBank->targetamount, '0')) {
+ if (0 === bccomp($piggyBank->target_amount, '0')) {
app('log')->debug('Target amount is zero, can add anything.');
}
diff --git a/app/Transformers/PiggyBankTransformer.php b/app/Transformers/PiggyBankTransformer.php
index aaccf20c63..4cc10cc466 100644
--- a/app/Transformers/PiggyBankTransformer.php
+++ b/app/Transformers/PiggyBankTransformer.php
@@ -84,18 +84,18 @@ class PiggyBankTransformer extends AbstractTransformer
// Amounts, depending on 0.0 state of target amount
$percentage = null;
- $targetAmount = $piggyBank->targetamount;
+ $targetAmount = $piggyBank->target_amount;
$leftToSave = null;
$savePerMonth = null;
if (0 !== bccomp($targetAmount, '0')) { // target amount is not 0.00
- $leftToSave = bcsub($piggyBank->targetamount, $currentAmount);
+ $leftToSave = bcsub($piggyBank->target_amount, $currentAmount);
$percentage = (int)bcmul(bcdiv($currentAmount, $targetAmount), '100');
$targetAmount = app('steam')->bcround($targetAmount, $currency->decimal_places);
$leftToSave = app('steam')->bcround($leftToSave, $currency->decimal_places);
$savePerMonth = app('steam')->bcround($this->piggyRepos->getSuggestedMonthlyAmount($piggyBank), $currency->decimal_places);
}
- $startDate = $piggyBank->startdate?->format('Y-m-d');
- $targetDate = $piggyBank->targetdate?->format('Y-m-d');
+ $startDate = $piggyBank->start_date?->format('Y-m-d');
+ $targetDate = $piggyBank->target_date?->format('Y-m-d');
return [
'id' => (string)$piggyBank->id,
diff --git a/app/Transformers/V2/PiggyBankTransformer.php b/app/Transformers/V2/PiggyBankTransformer.php
index b1d3abada7..30ebe367a7 100644
--- a/app/Transformers/V2/PiggyBankTransformer.php
+++ b/app/Transformers/V2/PiggyBankTransformer.php
@@ -119,7 +119,7 @@ class PiggyBankTransformer extends AbstractTransformer
/** @var PiggyBankRepetition $repetition */
foreach ($repetitions as $repetition) {
$this->repetitions[$repetition->piggy_bank_id] = [
- 'amount' => $repetition->currentamount,
+ 'amount' => $repetition->current_amount,
];
}
@@ -178,14 +178,14 @@ class PiggyBankTransformer extends AbstractTransformer
$nativeLeftToSave = null;
$savePerMonth = null;
$nativeSavePerMonth = null;
- $startDate = $piggyBank->startdate?->format('Y-m-d');
- $targetDate = $piggyBank->targetdate?->format('Y-m-d');
+ $startDate = $piggyBank->start_date?->format('Y-m-d');
+ $targetDate = $piggyBank->target_date?->format('Y-m-d');
$accountId = $piggyBank->account_id;
$accountName = $this->accounts[$accountId]['name'] ?? null;
$currency = $this->currencies[$accountId] ?? $this->default;
$currentAmount = app('steam')->bcround($this->repetitions[$piggyBank->id]['amount'] ?? '0', $currency->decimal_places);
$nativeCurrentAmount = $this->converter->convert($this->default, $currency, today(), $currentAmount);
- $targetAmount = $piggyBank->targetamount;
+ $targetAmount = $piggyBank->target_amount;
$nativeTargetAmount = $this->converter->convert($this->default, $currency, today(), $targetAmount);
$note = $this->notes[$piggyBank->id] ?? null;
$group = $this->groups[$piggyBank->id] ?? null;
@@ -194,7 +194,7 @@ class PiggyBankTransformer extends AbstractTransformer
$leftToSave = bcsub($targetAmount, $currentAmount);
$nativeLeftToSave = $this->converter->convert($this->default, $currency, today(), $leftToSave);
$percentage = (int)bcmul(bcdiv($currentAmount, $targetAmount), '100');
- $savePerMonth = $this->getSuggestedMonthlyAmount($currentAmount, $targetAmount, $piggyBank->startdate, $piggyBank->targetdate);
+ $savePerMonth = $this->getSuggestedMonthlyAmount($currentAmount, $targetAmount, $piggyBank->start_date, $piggyBank->target_date);
$nativeSavePerMonth = $this->converter->convert($this->default, $currency, today(), $savePerMonth);
}
$this->converter->summarize();
From f2fab5d4eef9040f0145f5a330f3576e1be8eb11 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Sun, 1 Dec 2024 06:48:15 +0100
Subject: [PATCH 007/122] Update code for piggy banks.
---
.../Commands/Correction/CorrectAmounts.php | 4 +-
.../Commands/System/ForceDecimalSize.php | 4 +-
.../Upgrade/UpgradeMultiPiggyBanks.php | 118 ++++++++++++++++++
.../Commands/Upgrade/UpgradeSkeleton.php.stub | 1 -
app/Handlers/Observer/PiggyBankObserver.php | 19 +--
5 files changed, 132 insertions(+), 14 deletions(-)
create mode 100644 app/Console/Commands/Upgrade/UpgradeMultiPiggyBanks.php
diff --git a/app/Console/Commands/Correction/CorrectAmounts.php b/app/Console/Commands/Correction/CorrectAmounts.php
index 639c96edec..10e65e07be 100644
--- a/app/Console/Commands/Correction/CorrectAmounts.php
+++ b/app/Console/Commands/Correction/CorrectAmounts.php
@@ -163,7 +163,7 @@ class CorrectAmounts extends Command
private function fixRepetitions(): void
{
- $set = PiggyBankRepetition::where('currentamount', '<', 0)->get();
+ $set = PiggyBankRepetition::where('current_amount', '<', 0)->get();
$count = $set->count();
if (0 === $count) {
$this->friendlyPositive('All piggy bank repetition amounts are positive.');
@@ -181,7 +181,7 @@ class CorrectAmounts extends Command
private function fixPiggyBanks(): void
{
- $set = PiggyBank::where('targetamount', '<', 0)->get();
+ $set = PiggyBank::where('target_amount', '<', 0)->get();
$count = $set->count();
if (0 === $count) {
$this->friendlyPositive('All piggy bank amounts are positive.');
diff --git a/app/Console/Commands/System/ForceDecimalSize.php b/app/Console/Commands/System/ForceDecimalSize.php
index 426e7fbcbd..9f3c42a12c 100644
--- a/app/Console/Commands/System/ForceDecimalSize.php
+++ b/app/Console/Commands/System/ForceDecimalSize.php
@@ -83,8 +83,8 @@ class ForceDecimalSize extends Command
'currency_exchange_rates' => ['rate', 'user_rate'],
'limit_repetitions' => ['amount'],
'piggy_bank_events' => ['amount'],
- 'piggy_bank_repetitions' => ['currentamount'],
- 'piggy_banks' => ['targetamount'],
+ 'piggy_bank_repetitions' => ['current_amount'],
+ 'piggy_banks' => ['target_amount'],
'recurrences_transactions' => ['amount', 'foreign_amount'],
'transactions' => ['amount', 'foreign_amount'],
];
diff --git a/app/Console/Commands/Upgrade/UpgradeMultiPiggyBanks.php b/app/Console/Commands/Upgrade/UpgradeMultiPiggyBanks.php
new file mode 100644
index 0000000000..f987a0b3d5
--- /dev/null
+++ b/app/Console/Commands/Upgrade/UpgradeMultiPiggyBanks.php
@@ -0,0 +1,118 @@
+isExecuted() && true !== $this->option('force')) {
+ $this->friendlyInfo('This command has already been executed.');
+
+ return 0;
+ }
+ $this->upgradePiggyBanks();
+ $this->friendlyInfo('Upgraded all piggy banks.');
+
+ $this->markAsExecuted();
+
+ return 0;
+ }
+
+ /**
+ * @return bool
+ */
+ private function isExecuted(): bool
+ {
+ $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
+ if (null !== $configVar) {
+ return (bool) $configVar->data;
+ }
+
+ return false;
+ }
+
+
+ /**
+ *
+ */
+ private function markAsExecuted(): void
+ {
+ app('fireflyconfig')->set(self::CONFIG_NAME, true);
+ }
+
+ private function upgradePiggyBanks(): void
+ {
+ $this->repository = app(PiggyBankRepositoryInterface::class);
+ $this->accountRepository = app(AccountRepositoryInterface::class);
+ $set = PiggyBank::whereNotNull('account_id')->get();
+ Log::debug(sprintf('Will update %d piggy banks(s).', $set->count()));
+ /** @var PiggyBank $piggyBank */
+ foreach ($set as $piggyBank) {
+ $this->upgradePiggyBank($piggyBank);
+ }
+ }
+
+ private function upgradePiggyBank(PiggyBank $piggyBank): void
+ {
+ $this->repository->setUser($piggyBank->account->user);
+ $this->accountRepository->setUser($piggyBank->account->user);
+ $repetition = $this->repository->getRepetition($piggyBank);
+ $currency = $this->accountRepository->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrencyByUserGroup($piggyBank->account->user->userGroup);
+
+ // update piggy bank to have a currency.
+ $piggyBank->transaction_currency_id = $currency->id;
+ $piggyBank->save();
+
+ // store current amount in account association.
+ $piggyBank->accounts()->sync([$piggyBank->account->id => ['current_amount' => $repetition->current_amount]]);
+ $piggyBank->account_id = null;
+ $piggyBank->save();
+
+ // remove all repetitions (no longer used)
+ $piggyBank->piggyBankRepetitions()->delete();
+
+ }
+}
diff --git a/app/Console/Commands/Upgrade/UpgradeSkeleton.php.stub b/app/Console/Commands/Upgrade/UpgradeSkeleton.php.stub
index d2f5b627c0..5d2dba01f5 100644
--- a/app/Console/Commands/Upgrade/UpgradeSkeleton.php.stub
+++ b/app/Console/Commands/Upgrade/UpgradeSkeleton.php.stub
@@ -6,7 +6,6 @@ use Illuminate\Console\Command;
/**
* Class UpgradeSkeleton.
- * TODO DONT FORGET TO ADD THIS TO THE DOCKER BUILD
*/
class UpgradeSkeleton extends Command
{
diff --git a/app/Handlers/Observer/PiggyBankObserver.php b/app/Handlers/Observer/PiggyBankObserver.php
index 40bde63a1a..74eb37b211 100644
--- a/app/Handlers/Observer/PiggyBankObserver.php
+++ b/app/Handlers/Observer/PiggyBankObserver.php
@@ -34,15 +34,16 @@ class PiggyBankObserver
{
public function created(PiggyBank $piggyBank): void
{
- app('log')->debug('Observe "created" of a piggy bank.');
- $repetition = new PiggyBankRepetition();
- $repetition->piggyBank()->associate($piggyBank);
- $repetition->start_date = $piggyBank->start_date;
- $repetition->start_date_tz = $piggyBank->start_date->format('e');
- $repetition->target_date = $piggyBank->target_date;
- $repetition->target_date_tz = $piggyBank->target_date?->format('e');
- $repetition->current_amount = '0';
- $repetition->save();
+ app('log')->debug('Observe "created" of a piggy bank. DO NOTHING.');
+
+// $repetition = new PiggyBankRepetition();
+// $repetition->piggyBank()->associate($piggyBank);
+// $repetition->start_date = $piggyBank->start_date;
+// $repetition->start_date_tz = $piggyBank->start_date->format('e');
+// $repetition->target_date = $piggyBank->target_date;
+// $repetition->target_date_tz = $piggyBank->target_date?->format('e');
+// $repetition->current_amount = '0';
+// $repetition->save();
}
/**
From cdf1ebf3f709d29ddc9319ca74eebe1039a21d26 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Sun, 1 Dec 2024 18:16:48 +0100
Subject: [PATCH 008/122] Better ability to store piggy banks.
---
.../Autocomplete/PiggyBankController.php | 6 +-
.../V1/Controllers/Data/PurgeController.php | 20 +--
.../Models/Account/ListController.php | 2 +-
.../Models/PiggyBank/ListController.php | 33 +++++
.../Models/PiggyBank/StoreRequest.php | 96 ++++++++++---
app/Factory/PiggyBankFactory.php | 129 ++++++++++++++++++
.../Controllers/PiggyBank/IndexController.php | 2 +-
app/Models/PiggyBank.php | 8 +-
.../Currency/CurrencyRepository.php | 5 +
.../Currency/CurrencyRepositoryInterface.php | 2 +
.../PiggyBank/ModifiesPiggyBanks.php | 87 ++----------
.../PiggyBank/PiggyBankRepository.php | 9 +-
.../PiggyBankRepositoryInterface.php | 17 ++-
app/Validation/FireflyValidator.php | 11 +-
config/firefly.php | 3 +
resources/lang/en_US/validation.php | 1 +
routes/api.php | 1 +
17 files changed, 297 insertions(+), 135 deletions(-)
diff --git a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php
index cf29aa037a..5a757dd35f 100644
--- a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php
+++ b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php
@@ -68,12 +68,11 @@ class PiggyBankController extends Controller
{
$data = $request->getData();
$piggies = $this->piggyRepository->searchPiggyBank($data['query'], $this->parameters->get('limit'));
- $defaultCurrency = app('amount')->getDefaultCurrency();
$response = [];
/** @var PiggyBank $piggy */
foreach ($piggies as $piggy) {
- $currency = $this->accountRepository->getAccountCurrency($piggy->account) ?? $defaultCurrency;
+ $currency = $piggy->transactionCurrency;
$objectGroup = $piggy->objectGroups()->first();
$response[] = [
'id' => (string)$piggy->id,
@@ -99,12 +98,11 @@ class PiggyBankController extends Controller
{
$data = $request->getData();
$piggies = $this->piggyRepository->searchPiggyBank($data['query'], $this->parameters->get('limit'));
- $defaultCurrency = app('amount')->getDefaultCurrency();
$response = [];
/** @var PiggyBank $piggy */
foreach ($piggies as $piggy) {
- $currency = $this->accountRepository->getAccountCurrency($piggy->account) ?? $defaultCurrency;
+ $currency = $piggy->transactionCurrency;
$currentAmount = $this->piggyRepository->getRepetition($piggy)->current_amount ?? '0';
$objectGroup = $piggy->objectGroups()->first();
$response[] = [
diff --git a/app/Api/V1/Controllers/Data/PurgeController.php b/app/Api/V1/Controllers/Data/PurgeController.php
index 8d076b62cf..d80b60315b 100644
--- a/app/Api/V1/Controllers/Data/PurgeController.php
+++ b/app/Api/V1/Controllers/Data/PurgeController.php
@@ -36,6 +36,7 @@ use FireflyIII\Models\RuleGroup;
use FireflyIII\Models\Tag;
use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
+use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\User;
use Illuminate\Http\JsonResponse;
@@ -63,14 +64,17 @@ class PurgeController extends Controller
Bill::whereUserId($user->id)->onlyTrashed()->forceDelete();
// piggies
- $set = PiggyBank::leftJoin('accounts', 'accounts.id', 'piggy_banks.account_id')
- ->where('accounts.user_id', $user->id)->onlyTrashed()->get(['piggy_banks.*'])
- ;
-
- /** @var PiggyBank $piggy */
- foreach ($set as $piggy) {
- $piggy->forceDelete();
- }
+ $repository = app(PiggyBankRepositoryInterface::class);
+ $repository->setUser($user);
+ $repository->purgeAll();
+// $set = PiggyBank::leftJoin('accounts', 'accounts.id', 'piggy_banks.account_id')
+// ->where('accounts.user_id', $user->id)->onlyTrashed()->get(['piggy_banks.*'])
+// ;
+//
+// /** @var PiggyBank $piggy */
+// foreach ($set as $piggy) {
+// $piggy->forceDelete();
+// }
// rule group
RuleGroup::whereUserId($user->id)->onlyTrashed()->forceDelete();
diff --git a/app/Api/V1/Controllers/Models/Account/ListController.php b/app/Api/V1/Controllers/Models/Account/ListController.php
index c85456f901..b2d4e39d90 100644
--- a/app/Api/V1/Controllers/Models/Account/ListController.php
+++ b/app/Api/V1/Controllers/Models/Account/ListController.php
@@ -111,7 +111,7 @@ class ListController extends Controller
// types to get, page size:
$pageSize = $this->parameters->get('limit');
- // get list of budgets. Count it and split it.
+ // get list of piggy banks. Count it and split it.
$collection = $this->repository->getPiggyBanks($account);
$count = $collection->count();
$piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
diff --git a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php
index 3c3ac1672b..8fda63be8e 100644
--- a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php
+++ b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php
@@ -28,6 +28,7 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
+use FireflyIII\Transformers\AccountTransformer;
use FireflyIII\Transformers\AttachmentTransformer;
use FireflyIII\Transformers\PiggyBankEventTransformer;
use Illuminate\Http\JsonResponse;
@@ -118,4 +119,36 @@ class ListController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
+
+ /**
+ * This endpoint is documented at:
+ * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/piggy_banks/listAccountByPiggyBank
+ *
+ * List single resource.
+ *
+ * @throws FireflyException
+ */
+ public function accounts(PiggyBank $piggyBank): JsonResponse
+ {
+ // types to get, page size:
+ $pageSize = $this->parameters->get('limit');
+ $manager = $this->getManager();
+
+ $collection = $piggyBank->accounts;
+ $count = $collection->count();
+ $events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
+
+ // make paginator:
+ $paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page'));
+ $paginator->setPath(route('api.v1.piggy-banks.accounts', [$piggyBank->id]).$this->buildParams());
+
+ /** @var AccountTransformer $transformer */
+ $transformer = app(AccountTransformer::class);
+ $transformer->setParameters($this->parameters);
+
+ $resource = new FractalCollection($events, $transformer, 'accounts');
+ $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
+
+ return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
+ }
}
diff --git a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php
index 8adc656a65..d73abc7b8c 100644
--- a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php
+++ b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php
@@ -24,10 +24,13 @@ declare(strict_types=1);
namespace FireflyIII\Api\V1\Requests\Models\PiggyBank;
+use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Rules\IsValidPositiveAmount;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Validation\Validator;
/**
* Class StoreRequest
@@ -42,19 +45,20 @@ class StoreRequest extends FormRequest
*/
public function getAll(): array
{
- $fields = [
+ $fields = [
'order' => ['order', 'convertInteger'],
];
- $data = $this->getAllData($fields);
- $data['name'] = $this->convertString('name');
- $data['account_id'] = $this->convertInteger('account_id');
- $data['targetamount'] = $this->convertString('target_amount');
- $data['current_amount'] = $this->convertString('current_amount');
- $data['startdate'] = $this->getCarbonDate('start_date');
- $data['targetdate'] = $this->getCarbonDate('target_date');
- $data['notes'] = $this->stringWithNewlines('notes');
- $data['object_group_id'] = $this->convertInteger('object_group_id');
- $data['object_group_title'] = $this->convertString('object_group_title');
+ $data = $this->getAllData($fields);
+ $data['name'] = $this->convertString('name');
+ $data['accounts'] = $this->parseAccounts($this->get('accounts'));
+ $data['target_amount'] = $this->convertString('target_amount');
+ $data['start_date'] = $this->getCarbonDate('start_date');
+ $data['target_date'] = $this->getCarbonDate('target_date');
+ $data['notes'] = $this->stringWithNewlines('notes');
+ $data['object_group_id'] = $this->convertInteger('object_group_id');
+ $data['transaction_currency_id'] = $this->convertInteger('transaction_currency_id');
+ $data['transaction_currency_code'] = $this->convertString('transaction_currency_code');
+ $data['object_group_title'] = $this->convertString('object_group_title');
return $data;
}
@@ -65,15 +69,67 @@ class StoreRequest extends FormRequest
public function rules(): array
{
return [
- 'name' => 'required|min:1|max:255|uniquePiggyBankForUser',
- 'current_amount' => ['nullable', new IsValidPositiveAmount()],
- 'account_id' => 'required|numeric|belongsToUser:accounts,id',
- 'object_group_id' => 'numeric|belongsToUser:object_groups,id',
- 'object_group_title' => ['min:1', 'max:255'],
- 'target_amount' => ['required', new IsValidPositiveAmount()],
- 'start_date' => 'date|nullable',
- 'target_date' => 'date|nullable|after:start_date',
- 'notes' => 'max:65000',
+ 'name' => 'required|min:1|max:255|uniquePiggyBankForUser',
+ 'accounts' => 'required',
+ 'accounts.*' => 'array|required',
+ 'accounts.*.account_id' => 'required|numeric|belongsToUser:accounts,id',
+ 'accounts.*.current_amount' => ['numeric', new IsValidPositiveAmount()],
+ 'object_group_id' => 'numeric|belongsToUser:object_groups,id',
+ 'object_group_title' => ['min:1', 'max:255'],
+ 'target_amount' => ['required', new IsValidPositiveAmount()],
+ 'start_date' => 'date|nullable',
+ 'transaction_currency_id' => 'exists:transaction_currencies,id',
+ 'transaction_currency_code' => 'exists:transaction_currencies,code',
+ 'target_date' => 'date|nullable|after:start_date',
+ 'notes' => 'max:65000',
];
}
+
+ /**
+ * Can only store money on liabilities and asset accouns.
+ */
+ public function withValidator(Validator $validator): void
+ {
+ $validator->after(
+ function (Validator $validator): void {
+ // validate start before end only if both are there.
+ $data = $validator->getData();
+ if (array_key_exists('accounts', $data) && is_array($data['accounts'])) {
+ $repository = app(AccountRepositoryInterface::class);
+ $types = config('firefly.piggy_bank_account_types');
+ foreach ($data['accounts'] as $index => $array) {
+ $accountId = (int) ($array['account_id'] ?? 0);
+ $account = $repository->find($accountId);
+ if (null !== $account) {
+ $type = $account->accountType->type;
+ if (!in_array($type, $types, true)) {
+ $validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_type'));
+ }
+ }
+ }
+ }
+ }
+ );
+ if ($validator->fails()) {
+ Log::channel('audit')->error(sprintf('Validation errors in %s', __CLASS__), $validator->errors()->toArray());
+ }
+ }
+
+ private function parseAccounts(mixed $array): array
+ {
+ if (!is_array($array)) {
+ return [];
+ }
+ $return = [];
+ foreach ($array as $entry) {
+ if (!is_array($entry)) {
+ continue;
+ }
+ $return[] = [
+ 'account_id' => $this->integerFromValue((string)($entry['account_id'] ?? '0')),
+ 'current_amount' => $this->clearString($entry['current_amount'] ?? '0'),
+ ];
+ }
+ return $return;
+ }
}
diff --git a/app/Factory/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php
index 505c92d0da..df9b54bc46 100644
--- a/app/Factory/PiggyBankFactory.php
+++ b/app/Factory/PiggyBankFactory.php
@@ -23,8 +23,14 @@ declare(strict_types=1);
namespace FireflyIII\Factory;
+use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\PiggyBank;
+use FireflyIII\Models\TransactionCurrency;
+use FireflyIII\Repositories\Account\AccountRepositoryInterface;
+use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
+use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\User;
+use Illuminate\Database\QueryException;
/**
* Class PiggyBankFactory
@@ -32,6 +38,72 @@ use FireflyIII\User;
class PiggyBankFactory
{
private User $user;
+ private CurrencyRepositoryInterface $currencyRepository;
+ private AccountRepositoryInterface $accountRepository;
+ private PiggyBankRepositoryInterface $piggyBankRepository;
+
+ /**
+ * Store a piggy bank or come back with an exception.
+ *
+ * @param array $data
+ *
+ * @return PiggyBank
+ */
+ public function store(array $data): PiggyBank {
+ $this->currencyRepository = app(CurrencyRepositoryInterface::class);
+ $this->accountRepository = app(AccountRepositoryInterface::class);
+ $this->piggyBankRepository = app(PiggyBankRepositoryInterface::class);
+ $this->currencyRepository->setUser($this->user);
+ $this->accountRepository->setUser($this->user);
+ $this->piggyBankRepository->setUser($this->user);
+ $piggyBankData =$data;
+
+ // unset some fields
+ unset($piggyBankData['object_group_title'],$piggyBankData['transaction_currency_code'],$piggyBankData['transaction_currency_id'],$piggyBankData['accounts'], $piggyBankData['object_group_id'], $piggyBankData['notes']);
+
+ // validate amount:
+ if (array_key_exists('target_amount', $piggyBankData) && '' === (string)$piggyBankData['target_amount']) {
+ $piggyBankData['target_amount'] = '0';
+ }
+
+ $piggyBankData['start_date_tz'] = $piggyBankData['start_date']?->format('e');
+ $piggyBankData['target_date_tz'] = $piggyBankData['target_date']?->format('e');
+ $piggyBankData['account_id'] = null;
+ $piggyBankData['transaction_currency_id'] = $this->getCurrency($data)->id;
+ $piggyBankData['order'] = 131337;
+
+ try {
+ /** @var PiggyBank $piggyBank */
+ $piggyBank = PiggyBank::create($piggyBankData);
+ } catch (QueryException $e) {
+ app('log')->error(sprintf('Could not store piggy bank: %s', $e->getMessage()), $piggyBankData);
+
+ throw new FireflyException('400005: Could not store new piggy bank.', 0, $e);
+ }
+ $piggyBank = $this->setOrder($piggyBank, $data);
+ $this->linkToAccountIds($piggyBank, $data['accounts']);
+ $this->piggyBankRepository->updateNote($piggyBank, $data['notes']);
+
+ $objectGroupTitle = $data['object_group_title'] ?? '';
+ if ('' !== $objectGroupTitle) {
+ $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle);
+ if (null !== $objectGroup) {
+ $piggyBank->objectGroups()->sync([$objectGroup->id]);
+ $piggyBank->save();
+ }
+ }
+ // try also with ID
+ $objectGroupId = (int)($data['object_group_id'] ?? 0);
+ if (0 !== $objectGroupId) {
+ $objectGroup = $this->findObjectGroupById($objectGroupId);
+ if (null !== $objectGroup) {
+ $piggyBank->objectGroups()->sync([$objectGroup->id]);
+ $piggyBank->save();
+ }
+ }
+
+ return $piggyBank;
+ }
public function find(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank
{
@@ -70,4 +142,61 @@ class PiggyBankFactory
{
$this->user = $user;
}
+
+ private function getCurrency(array $data): TransactionCurrency {
+ // currency:
+ $defaultCurrency = app('amount')->getDefaultCurrency();
+ $currency = null;
+ if (array_key_exists('transaction_currency_code', $data)) {
+ $currency = $this->currencyRepository->findByCode((string)($data['transaction_currency_code'] ?? ''));
+ }
+ if (array_key_exists('transaction_currency_id', $data)) {
+ $currency = $this->currencyRepository->find((int)($data['transaction_currency_id'] ?? 0));
+ }
+ $currency ??= $defaultCurrency;
+ return $currency;
+ }
+
+ private function setOrder(PiggyBank $piggyBank, array $data): PiggyBank {
+ $this->resetOrder();
+ $order = $this->getMaxOrder() + 1;
+ if (array_key_exists('order', $data)) {
+ $order = $data['order'];
+ }
+ $piggyBank->order = $order;
+ $piggyBank->save();
+ return $piggyBank;
+
+ }
+
+ private function resetOrder(): void
+ {
+ $set = $this->user->piggyBanks()->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']);
+ $current = 1;
+ foreach ($set as $piggyBank) {
+ if ($piggyBank->order !== $current) {
+ app('log')->debug(sprintf('Piggy bank #%d ("%s") was at place %d but should be on %d', $piggyBank->id, $piggyBank->name, $piggyBank->order, $current));
+ $piggyBank->order = $current;
+ $piggyBank->save();
+ }
+ ++$current;
+ }
+ }
+
+
+ private function getMaxOrder(): int
+ {
+ return (int)$this->user->piggyBanks()->max('piggy_banks.order');
+ }
+
+ private function linkToAccountIds(PiggyBank $piggyBank, array $accounts): void {
+ /** @var array $info */
+ foreach($accounts as $info) {
+ $account = $this->accountRepository->find((int)($info['account_id'] ?? 0));
+ if(null === $account) {
+ continue;
+ }
+ $piggyBank->accounts()->syncWithoutDetaching([$account->id, ['current_amount' => $info['current_amount'] ?? '0']]);
+ }
+ }
}
diff --git a/app/Http/Controllers/PiggyBank/IndexController.php b/app/Http/Controllers/PiggyBank/IndexController.php
index 9c3578550e..9c08ebdf25 100644
--- a/app/Http/Controllers/PiggyBank/IndexController.php
+++ b/app/Http/Controllers/PiggyBank/IndexController.php
@@ -79,7 +79,7 @@ class IndexController extends Controller
public function index()
{
$this->cleanupObjectGroups();
- $this->piggyRepos->resetOrder();
+ //$this->piggyRepos->resetOrder();
$collection = $this->piggyRepos->getPiggyBanks();
$accounts = [];
diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php
index 0edfa05b9e..911566e628 100644
--- a/app/Models/PiggyBank.php
+++ b/app/Models/PiggyBank.php
@@ -55,7 +55,7 @@ class PiggyBank extends Model
'target_amount' => 'string',
];
- protected $fillable = ['name', 'account_id', 'order', 'target_amount', 'start_date', 'start_date_tz', 'target_date', 'target_date_tz', 'active'];
+ protected $fillable = ['name', 'account_id', 'order', 'target_amount', 'start_date', 'start_date_tz', 'target_date', 'target_date_tz', 'active','transaction_currency_id'];
/**
* Route binder. Converts the key in the URL to the specified object (or throw 404).
@@ -67,9 +67,9 @@ class PiggyBank extends Model
if (auth()->check()) {
$piggyBankId = (int)$value;
$piggyBank = self::where('piggy_banks.id', $piggyBankId)
- ->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')
- ->where('accounts.user_id', auth()->user()->id)->first(['piggy_banks.*'])
- ;
+ ->leftJoin('account_piggy_bank','account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
+ ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
+ ->where('accounts.user_id', auth()->user()->id)->first(['piggy_banks.*']);
if (null !== $piggyBank) {
return $piggyBank;
}
diff --git a/app/Repositories/Currency/CurrencyRepository.php b/app/Repositories/Currency/CurrencyRepository.php
index 5ca4924769..97cb7ba79f 100644
--- a/app/Repositories/Currency/CurrencyRepository.php
+++ b/app/Repositories/Currency/CurrencyRepository.php
@@ -105,4 +105,9 @@ class CurrencyRepository implements CurrencyRepositoryInterface
$this->user = $user;
}
}
+
+ #[\Override] public function find(int $currencyId): ?TransactionCurrency
+ {
+ return TransactionCurrency::find($currencyId);
+ }
}
diff --git a/app/Repositories/Currency/CurrencyRepositoryInterface.php b/app/Repositories/Currency/CurrencyRepositoryInterface.php
index e714977abb..b5fb7d7acb 100644
--- a/app/Repositories/Currency/CurrencyRepositoryInterface.php
+++ b/app/Repositories/Currency/CurrencyRepositoryInterface.php
@@ -42,6 +42,8 @@ interface CurrencyRepositoryInterface
*/
public function findByCode(string $currencyCode): ?TransactionCurrency;
+ public function find(int $currencyId): ?TransactionCurrency;
+
/**
* Returns the complete set of transactions but needs
* no user object.
diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
index c5f9293c2e..998fed9b23 100644
--- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
+++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
@@ -26,11 +26,14 @@ namespace FireflyIII\Repositories\PiggyBank;
use FireflyIII\Events\Model\PiggyBank\ChangedAmount;
use FireflyIII\Exceptions\FireflyException;
+use FireflyIII\Factory\PiggyBankFactory;
use FireflyIII\Models\Note;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankRepetition;
+use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups;
+use FireflyIII\Support\Facades\Amount;
use Illuminate\Database\QueryException;
/**
@@ -178,82 +181,11 @@ trait ModifiesPiggyBanks
*/
public function store(array $data): PiggyBank
{
- $order = $this->getMaxOrder() + 1;
- if (array_key_exists('order', $data)) {
- $order = $data['order'];
- }
- $data['order'] = 31337; // very high when creating.
- $piggyData = $data;
- // unset fields just in case.
- unset($piggyData['object_group_title'], $piggyData['object_group_id'], $piggyData['notes'], $piggyData['current_amount']);
-
- // validate amount:
- if (array_key_exists('targetamount', $piggyData) && '' === (string)$piggyData['targetamount']) {
- $piggyData['targetamount'] = '0';
- }
-
- $piggyData['startdate_tz'] = $piggyData['startdate']?->format('e');
- $piggyData['targetdate_tz'] = $piggyData['targetdate']?->format('e');
-
- try {
- /** @var PiggyBank $piggyBank */
- $piggyBank = PiggyBank::create($piggyData);
- } catch (QueryException $e) {
- app('log')->error(sprintf('Could not store piggy bank: %s', $e->getMessage()), $piggyData);
-
- throw new FireflyException('400005: Could not store new piggy bank.', 0, $e);
- }
-
- // reset order then set order:
- $this->resetOrder();
- $this->setOrder($piggyBank, $order);
-
- $this->updateNote($piggyBank, $data['notes']);
-
- // repetition is auto created.
- $repetition = $this->getRepetition($piggyBank);
- if (null !== $repetition && array_key_exists('current_amount', $data) && '' !== $data['current_amount']) {
- $repetition->current_amount = $data['current_amount'];
- $repetition->save();
- }
-
- $objectGroupTitle = $data['object_group_title'] ?? '';
- if ('' !== $objectGroupTitle) {
- $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle);
- if (null !== $objectGroup) {
- $piggyBank->objectGroups()->sync([$objectGroup->id]);
- $piggyBank->save();
- }
- }
- // try also with ID
- $objectGroupId = (int)($data['object_group_id'] ?? 0);
- if (0 !== $objectGroupId) {
- $objectGroup = $this->findObjectGroupById($objectGroupId);
- if (null !== $objectGroup) {
- $piggyBank->objectGroups()->sync([$objectGroup->id]);
- $piggyBank->save();
- }
- }
-
- return $piggyBank;
+ $factory = new PiggyBankFactory();
+ $factory->setUser($this->user);
+ return $factory->store($data);
}
- /**
- * Correct order of piggies in case of issues.
- */
- public function resetOrder(): void
- {
- $set = $this->user->piggyBanks()->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']);
- $current = 1;
- foreach ($set as $piggyBank) {
- if ($piggyBank->order !== $current) {
- app('log')->debug(sprintf('Piggy bank #%d ("%s") was at place %d but should be on %d', $piggyBank->id, $piggyBank->name, $piggyBank->order, $current));
- $piggyBank->order = $current;
- $piggyBank->save();
- }
- ++$current;
- }
- }
public function setOrder(PiggyBank $piggyBank, int $newOrder): bool
{
@@ -282,13 +214,12 @@ trait ModifiesPiggyBanks
return true;
}
- private function updateNote(PiggyBank $piggyBank, string $note): bool
+ public function updateNote(PiggyBank $piggyBank, string $note): void
{
if ('' === $note) {
$dbNote = $piggyBank->notes()->first();
$dbNote?->delete();
-
- return true;
+ return ;
}
$dbNote = $piggyBank->notes()->first();
if (null === $dbNote) {
@@ -297,8 +228,6 @@ trait ModifiesPiggyBanks
}
$dbNote->text = trim($note);
$dbNote->save();
-
- return true;
}
public function update(PiggyBank $piggyBank, array $data): PiggyBank
diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php
index b31571b043..1e9658d290 100644
--- a/app/Repositories/PiggyBank/PiggyBankRepository.php
+++ b/app/Repositories/PiggyBank/PiggyBankRepository.php
@@ -240,10 +240,6 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
}
}
- public function getMaxOrder(): int
- {
- return (int)$this->user->piggyBanks()->max('piggy_banks.order');
- }
/**
* Return note for piggy bank.
@@ -351,4 +347,9 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
return $search->take($limit)->get();
}
+
+ #[\Override] public function purgeAll(): void
+ {
+ throw new FireflyException('TODO Not implemented');
+ }
}
diff --git a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php
index 7c1e12becc..dfe534f4cf 100644
--- a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php
+++ b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php
@@ -52,6 +52,8 @@ interface PiggyBankRepositoryInterface
public function destroyAll(): void;
+ public function purgeAll(): void;
+
public function find(int $piggyBankId): ?PiggyBank;
/**
@@ -78,10 +80,7 @@ interface PiggyBankRepositoryInterface
*/
public function getExactAmount(PiggyBank $piggyBank, PiggyBankRepetition $repetition, TransactionJournal $journal): string;
- /**
- * Highest order of all piggy banks.
- */
- public function getMaxOrder(): int;
+ public function updateNote(PiggyBank $piggyBank, string $note): void;
/**
* Return note for piggy bank.
@@ -114,10 +113,10 @@ interface PiggyBankRepositoryInterface
public function removeObjectGroup(PiggyBank $piggyBank): PiggyBank;
- /**
- * Correct order of piggies in case of issues.
- */
- public function resetOrder(): void;
+// /**
+// * Correct order of piggies in case of issues.
+// */
+// public function resetOrder(): void;
/**
* Search for piggy banks.
@@ -133,7 +132,7 @@ interface PiggyBankRepositoryInterface
*/
public function setOrder(PiggyBank $piggyBank, int $newOrder): bool;
- public function setUser(null|Authenticatable|User $user): void;
+ public function setUser(null | Authenticatable | User $user): void;
/**
* Store new piggy bank.
diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php
index 95553306ff..136bc2f9a5 100644
--- a/app/Validation/FireflyValidator.php
+++ b/app/Validation/FireflyValidator.php
@@ -27,6 +27,7 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountMeta;
use FireflyIII\Models\AccountType;
+use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\TransactionType;
use FireflyIII\Models\Webhook;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
@@ -812,15 +813,15 @@ class FireflyValidator extends Validator
public function validateUniquePiggyBankForUser($attribute, $value, $parameters): bool
{
$exclude = $parameters[0] ?? null;
- $query = \DB::table('piggy_banks')->whereNull('piggy_banks.deleted_at')
- ->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where('accounts.user_id', auth()->user()->id)
- ;
+ $query = PiggyBank
+ ::leftJoin('account_piggy_bank','account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
+ ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
+ ->where('accounts.user_id', auth()->user()->id);
if (null !== $exclude) {
$query->where('piggy_banks.id', '!=', (int) $exclude);
}
$query->where('piggy_banks.name', $value);
-
- return null === $query->first(['piggy_banks.*']);
+ return 0 === $query->get(['piggy_banks.*'])->count();
}
/**
diff --git a/config/firefly.php b/config/firefly.php
index 2b651de7d9..c13ef5ecbe 100644
--- a/config/firefly.php
+++ b/config/firefly.php
@@ -913,4 +913,7 @@ return [
// preselected account lists possibilities:
'preselected_accounts' => ['all', 'assets', 'liabilities'],
+
+ // allowed to store a piggy bank in:
+ 'piggy_bank_account_types' => [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value],
];
diff --git a/resources/lang/en_US/validation.php b/resources/lang/en_US/validation.php
index bdf68a07fd..9f6dc2fe54 100644
--- a/resources/lang/en_US/validation.php
+++ b/resources/lang/en_US/validation.php
@@ -25,6 +25,7 @@
declare(strict_types=1);
return [
+ 'invalid_account_type' => 'A piggy bank can only be linked to asset accounts and liabilities',
'filter_must_be_in' => 'Filter ":filter" must be one of: :values',
'filter_not_string' => 'Filter ":filter" is expected to be a string of text',
'bad_api_filter' => 'This API endpoint does not support ":filter" as a filter.',
diff --git a/routes/api.php b/routes/api.php
index 750450b257..ec16affdd9 100644
--- a/routes/api.php
+++ b/routes/api.php
@@ -615,6 +615,7 @@ Route::group(
Route::get('{piggyBank}/events', ['uses' => 'ListController@piggyBankEvents', 'as' => 'events']);
Route::get('{piggyBank}/attachments', ['uses' => 'ListController@attachments', 'as' => 'attachments']);
+ Route::get('{piggyBank}/accounts', ['uses' => 'ListController@accounts', 'as' => 'accounts']);
}
);
From d740814f8845c9007479602bcffa0912770b05f3 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Sun, 1 Dec 2024 18:32:05 +0100
Subject: [PATCH 009/122] API works for multi-account piggies, the rest throws
an exception
---
.../Models/PiggyBank/ShowController.php | 2 +-
.../Integrity/AddTimezonesToDates.php | 4 +-
app/Models/PiggyBank.php | 5 ++
.../PiggyBank/ModifiesPiggyBanks.php | 1 +
.../PiggyBank/PiggyBankRepository.php | 74 +++++++++----------
app/Transformers/PiggyBankTransformer.php | 58 +++++++++------
app/Transformers/V2/PiggyBankTransformer.php | 1 +
app/User.php | 8 --
8 files changed, 82 insertions(+), 71 deletions(-)
diff --git a/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php b/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php
index 2005bc4de5..442b47cb38 100644
--- a/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php
+++ b/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php
@@ -72,7 +72,7 @@ class ShowController extends Controller
// types to get, page size:
$pageSize = $this->parameters->get('limit');
- // get list of budgets. Count it and split it.
+ // get list of piggy banks. Count it and split it.
$collection = $this->repository->getPiggyBanks();
$count = $collection->count();
$piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
diff --git a/app/Console/Commands/Integrity/AddTimezonesToDates.php b/app/Console/Commands/Integrity/AddTimezonesToDates.php
index 7dafa505c4..cd347bd274 100644
--- a/app/Console/Commands/Integrity/AddTimezonesToDates.php
+++ b/app/Console/Commands/Integrity/AddTimezonesToDates.php
@@ -67,8 +67,8 @@ class AddTimezonesToDates extends Command
CurrencyExchangeRate::class => ['date'], // done
InvitedUser::class => ['expires'],
PiggyBankEvent::class => ['date'],
- PiggyBankRepetition::class => ['startdate', 'targetdate'],
- PiggyBank::class => ['startdate', 'targetdate'], // done
+ PiggyBankRepetition::class => ['start_date', 'target_date'],
+ PiggyBank::class => ['start_date', 'target_date'], // done
Recurrence::class => ['first_date', 'repeat_until', 'latest_date'],
Tag::class => ['date'],
TransactionJournal::class => ['date'],
diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php
index 911566e628..d5a936cf31 100644
--- a/app/Models/PiggyBank.php
+++ b/app/Models/PiggyBank.php
@@ -78,6 +78,11 @@ class PiggyBank extends Model
throw new NotFoundHttpException();
}
+ public function transactionCurrency(): BelongsTo
+ {
+ return $this->belongsTo(TransactionCurrency::class);
+ }
+
public function account(): BelongsTo
{
return $this->belongsTo(Account::class);
diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
index 998fed9b23..09169ef898 100644
--- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
+++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
@@ -45,6 +45,7 @@ trait ModifiesPiggyBanks
public function addAmountToRepetition(PiggyBankRepetition $repetition, string $amount, TransactionJournal $journal): void
{
+ throw new FireflyException('[a] Piggy bank repetitions are EOL.');
app('log')->debug(sprintf('addAmountToRepetition: %s', $amount));
if (-1 === bccomp($amount, '0')) {
app('log')->debug('Remove amount.');
diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php
index 1e9658d290..ce32ca3269 100644
--- a/app/Repositories/PiggyBank/PiggyBankRepository.php
+++ b/app/Repositories/PiggyBank/PiggyBankRepository.php
@@ -94,7 +94,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
public function getAttachments(PiggyBank $piggyBank): Collection
{
- $set = $piggyBank->attachments()->get();
+ $set = $piggyBank->attachments()->get();
/** @var \Storage $disk */
$disk = \Storage::disk('upload');
@@ -115,16 +115,18 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
*/
public function getCurrentAmount(PiggyBank $piggyBank): string
{
- $rep = $this->getRepetition($piggyBank);
- if (null === $rep) {
- return '0';
+ $sum = '0';
+ foreach ($piggyBank->accounts as $account) {
+ $amount = (string) $account->pivot->current_amount;
+ $amount = '' === $amount ? '0' : $amount;
+ $sum = bcadd($sum, $amount);
}
-
- return $rep->current_amount;
+ return $sum;
}
public function getRepetition(PiggyBank $piggyBank): ?PiggyBankRepetition
{
+ throw new FireflyException('[b] Piggy bank repetitions are EOL.');
return $piggyBank->piggyBankRepetitions()->first();
}
@@ -140,17 +142,18 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
*/
public function getExactAmount(PiggyBank $piggyBank, PiggyBankRepetition $repetition, TransactionJournal $journal): string
{
+ throw new FireflyException('[c] Piggy bank repetitions are EOL.');
app('log')->debug(sprintf('Now in getExactAmount(%d, %d, %d)', $piggyBank->id, $repetition->id, $journal->id));
- $operator = null;
- $currency = null;
+ $operator = null;
+ $currency = null;
/** @var JournalRepositoryInterface $journalRepost */
- $journalRepost = app(JournalRepositoryInterface::class);
+ $journalRepost = app(JournalRepositoryInterface::class);
$journalRepost->setUser($this->user);
/** @var AccountRepositoryInterface $accountRepos */
- $accountRepos = app(AccountRepositoryInterface::class);
+ $accountRepos = app(AccountRepositoryInterface::class);
$accountRepos->setUser($this->user);
$defaultCurrency = app('amount')->getDefaultCurrencyByUserGroup($this->user->userGroup);
@@ -159,10 +162,10 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
app('log')->debug(sprintf('Piggy bank #%d currency is %s', $piggyBank->id, $piggyBankCurrency->code));
/** @var Transaction $source */
- $source = $journal->transactions()->with(['account'])->where('amount', '<', 0)->first();
+ $source = $journal->transactions()->with(['account'])->where('amount', '<', 0)->first();
/** @var Transaction $destination */
- $destination = $journal->transactions()->with(['account'])->where('amount', '>', 0)->first();
+ $destination = $journal->transactions()->with(['account'])->where('amount', '>', 0)->first();
// matches source, which means amount will be removed from piggy:
if ($source->account_id === $piggyBank->account_id) {
@@ -184,12 +187,12 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
}
// currency of the account + the piggy bank currency are almost the same.
// which amount from the transaction matches?
- $amount = null;
- if ((int)$source->transaction_currency_id === $currency->id) {
+ $amount = null;
+ if ((int) $source->transaction_currency_id === $currency->id) {
app('log')->debug('Use normal amount');
$amount = app('steam')->{$operator}($source->amount); // @phpstan-ignore-line
}
- if ((int)$source->foreign_currency_id === $currency->id) {
+ if ((int) $source->foreign_currency_id === $currency->id) {
app('log')->debug('Use foreign amount');
$amount = app('steam')->{$operator}($source->foreign_amount); // @phpstan-ignore-line
}
@@ -200,8 +203,8 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
}
app('log')->debug(sprintf('The currency is %s and the amount is %s', $currency->code, $amount));
- $room = bcsub($piggyBank->target_amount, $repetition->current_amount);
- $compare = bcmul($repetition->current_amount, '-1');
+ $room = bcsub($piggyBank->target_amount, $repetition->current_amount);
+ $compare = bcmul($repetition->current_amount, '-1');
if (0 === bccomp($piggyBank->target_amount, '0')) {
// amount is zero? then the "room" is positive amount of we wish to add or remove.
@@ -230,10 +233,10 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
return $compare;
}
- return (string)$amount;
+ return (string) $amount;
}
- public function setUser(null|Authenticatable|User $user): void
+ public function setUser(null | Authenticatable | User $user): void
{
if ($user instanceof User) {
$this->user = $user;
@@ -249,7 +252,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
/** @var null|Note $note */
$note = $piggyBank->notes()->first();
- return (string)$note?->text;
+ return (string) $note?->text;
}
/**
@@ -259,12 +262,12 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
{
$currency = app('amount')->getDefaultCurrency();
- $set = $this->getPiggyBanks();
+ $set = $this->getPiggyBanks();
/** @var PiggyBank $piggy */
foreach ($set as $piggy) {
$currentAmount = $this->getRepetition($piggy)->current_amount ?? '0';
- $piggy->name = $piggy->name.' ('.app('amount')->formatAnything($currency, $currentAmount, false).')';
+ $piggy->name = $piggy->name . ' (' . app('amount')->formatAnything($currency, $currentAmount, false) . ')';
}
return $set;
@@ -272,16 +275,17 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
public function getPiggyBanks(): Collection
{
- return $this->user // @phpstan-ignore-line (phpstan does not recognize objectGroups)
- ->piggyBanks()
+ return PiggyBank
+ ::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
+ ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
+ ->where('accounts.user_id', auth()->user()->id)
->with(
[
'account',
'objectGroups',
]
)
- ->orderBy('order', 'ASC')->get()
- ;
+ ->orderBy('piggy_banks.order', 'ASC')->get();
}
/**
@@ -289,20 +293,17 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
*/
public function getSuggestedMonthlyAmount(PiggyBank $piggyBank): string
{
- $savePerMonth = '0';
- $repetition = $this->getRepetition($piggyBank);
- if (null === $repetition) {
- return $savePerMonth;
- }
- if (null !== $piggyBank->target_date && $repetition->current_amount < $piggyBank->target_amount) {
+ $savePerMonth = '0';
+ $currentAmount = $this->getCurrentAmount($piggyBank);
+ if (null !== $piggyBank->target_date && $currentAmount < $piggyBank->target_amount) {
$now = today(config('app.timezone'));
$startDate = null !== $piggyBank->start_date && $piggyBank->start_date->gte($now) ? $piggyBank->start_date : $now;
- $diffInMonths = (int)$startDate->diffInMonths($piggyBank->target_date);
- $remainingAmount = bcsub($piggyBank->target_amount, $repetition->current_amount);
+ $diffInMonths = (int) $startDate->diffInMonths($piggyBank->target_date);
+ $remainingAmount = bcsub($piggyBank->target_amount, $currentAmount);
// more than 1 month to go and still need money to save:
if ($diffInMonths > 0 && 1 === bccomp($remainingAmount, '0')) {
- $savePerMonth = bcdiv($remainingAmount, (string)$diffInMonths);
+ $savePerMonth = bcdiv($remainingAmount, (string) $diffInMonths);
}
// less than 1 month to go but still need money to save:
@@ -342,8 +343,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
$search->whereLike('piggy_banks.name', sprintf('%%%s%%', $query));
}
$search->orderBy('piggy_banks.order', 'ASC')
- ->orderBy('piggy_banks.name', 'ASC')
- ;
+ ->orderBy('piggy_banks.name', 'ASC');
return $search->take($limit)->get();
}
diff --git a/app/Transformers/PiggyBankTransformer.php b/app/Transformers/PiggyBankTransformer.php
index 4cc10cc466..701c816257 100644
--- a/app/Transformers/PiggyBankTransformer.php
+++ b/app/Transformers/PiggyBankTransformer.php
@@ -54,25 +54,22 @@ class PiggyBankTransformer extends AbstractTransformer
*/
public function transform(PiggyBank $piggyBank): array
{
- $account = $piggyBank->account;
+ $user = $piggyBank->accounts()->first()->user;
// set up repositories
- $this->accountRepos->setUser($account->user);
- $this->piggyRepos->setUser($account->user);
-
- // get currency from account, or use default.
- $currency = $this->accountRepos->getAccountCurrency($account) ?? app('amount')->getDefaultCurrencyByUserGroup($account->user->userGroup);
+ $this->accountRepos->setUser($user);
+ $this->piggyRepos->setUser($user);
// note
- $notes = $this->piggyRepos->getNoteText($piggyBank);
- $notes = '' === $notes ? null : $notes;
+ $notes = $this->piggyRepos->getNoteText($piggyBank);
+ $notes = '' === $notes ? null : $notes;
$objectGroupId = null;
$objectGroupOrder = null;
$objectGroupTitle = null;
/** @var null|ObjectGroup $objectGroup */
- $objectGroup = $piggyBank->objectGroups->first();
+ $objectGroup = $piggyBank->objectGroups->first();
if (null !== $objectGroup) {
$objectGroupId = $objectGroup->id;
$objectGroupOrder = $objectGroup->order;
@@ -80,31 +77,33 @@ class PiggyBankTransformer extends AbstractTransformer
}
// get currently saved amount:
- $currentAmount = app('steam')->bcround($this->piggyRepos->getCurrentAmount($piggyBank), $currency->decimal_places);
+ $currency = $piggyBank->transactionCurrency;
+ $currentAmount = app('steam')->bcround($this->piggyRepos->getCurrentAmount($piggyBank), $currency->decimal_places);
// Amounts, depending on 0.0 state of target amount
- $percentage = null;
- $targetAmount = $piggyBank->target_amount;
- $leftToSave = null;
- $savePerMonth = null;
+ $percentage = null;
+ $targetAmount = $piggyBank->target_amount;
+ $leftToSave = null;
+ $savePerMonth = null;
if (0 !== bccomp($targetAmount, '0')) { // target amount is not 0.00
$leftToSave = bcsub($piggyBank->target_amount, $currentAmount);
- $percentage = (int)bcmul(bcdiv($currentAmount, $targetAmount), '100');
+ $percentage = (int) bcmul(bcdiv($currentAmount, $targetAmount), '100');
$targetAmount = app('steam')->bcround($targetAmount, $currency->decimal_places);
$leftToSave = app('steam')->bcround($leftToSave, $currency->decimal_places);
$savePerMonth = app('steam')->bcround($this->piggyRepos->getSuggestedMonthlyAmount($piggyBank), $currency->decimal_places);
}
- $startDate = $piggyBank->start_date?->format('Y-m-d');
- $targetDate = $piggyBank->target_date?->format('Y-m-d');
+ $startDate = $piggyBank->start_date?->format('Y-m-d');
+ $targetDate = $piggyBank->target_date?->format('Y-m-d');
return [
- 'id' => (string)$piggyBank->id,
+ 'id' => (string) $piggyBank->id,
'created_at' => $piggyBank->created_at->toAtomString(),
'updated_at' => $piggyBank->updated_at->toAtomString(),
- 'account_id' => (string)$piggyBank->account_id,
- 'account_name' => $piggyBank->account->name,
+ 'accounts' => $this->renderAccounts($piggyBank),
+ //'account_id' => (string)$piggyBank->account_id,
+ //'account_name' => $piggyBank->account->name,
'name' => $piggyBank->name,
- 'currency_id' => (string)$currency->id,
+ 'currency_id' => (string) $currency->id,
'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places,
@@ -118,15 +117,28 @@ class PiggyBankTransformer extends AbstractTransformer
'order' => $piggyBank->order,
'active' => true,
'notes' => $notes,
- 'object_group_id' => null !== $objectGroupId ? (string)$objectGroupId : null,
+ 'object_group_id' => null !== $objectGroupId ? (string) $objectGroupId : null,
'object_group_order' => $objectGroupOrder,
'object_group_title' => $objectGroupTitle,
'links' => [
[
'rel' => 'self',
- 'uri' => '/piggy_banks/'.$piggyBank->id,
+ 'uri' => '/piggy_banks/' . $piggyBank->id,
],
],
];
}
+
+ private function renderAccounts(PiggyBank $piggyBank): array
+ {
+ $return = [];
+ foreach ($piggyBank->accounts as $account) {
+ $return[] = [
+ 'id' => $account->id,
+ 'name' => $account->name,
+ // TODO add balance, add left to save.
+ ];
+ }
+ return $return;
+ }
}
diff --git a/app/Transformers/V2/PiggyBankTransformer.php b/app/Transformers/V2/PiggyBankTransformer.php
index 30ebe367a7..8dfb88b69c 100644
--- a/app/Transformers/V2/PiggyBankTransformer.php
+++ b/app/Transformers/V2/PiggyBankTransformer.php
@@ -115,6 +115,7 @@ class PiggyBankTransformer extends AbstractTransformer
// grab repetitions (for current amount):
$repetitions = PiggyBankRepetition::whereIn('piggy_bank_id', $piggyBanks)->get();
+ throw new FireflyException('[d] Piggy bank repetitions are EOL.');
/** @var PiggyBankRepetition $repetition */
foreach ($repetitions as $repetition) {
diff --git a/app/User.php b/app/User.php
index deb0b896ab..3e44cb1e43 100644
--- a/app/User.php
+++ b/app/User.php
@@ -332,14 +332,6 @@ class User extends Authenticatable
return $this->hasMany(ObjectGroup::class);
}
- /**
- * Link to piggy banks.
- */
- public function piggyBanks(): HasManyThrough
- {
- return $this->hasManyThrough(PiggyBank::class, Account::class);
- }
-
/**
* Link to preferences.
*/
From 4819b5ac5d08e6461d522f47a5f4ec049fbd2237 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Wed, 4 Dec 2024 06:38:47 +0100
Subject: [PATCH 010/122] More code for multi account piggy banks.
---
app/Factory/PiggyBankFactory.php | 15 +-
.../Controllers/PiggyBank/IndexController.php | 159 ++++++++++++------
app/Models/PiggyBank.php | 2 +-
.../PiggyBank/PiggyBankRepository.php | 10 +-
.../PiggyBankRepositoryInterface.php | 5 +-
app/Transformers/PiggyBankTransformer.php | 3 +-
6 files changed, 131 insertions(+), 63 deletions(-)
diff --git a/app/Factory/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php
index df9b54bc46..7f9def7600 100644
--- a/app/Factory/PiggyBankFactory.php
+++ b/app/Factory/PiggyBankFactory.php
@@ -169,9 +169,20 @@ class PiggyBankFactory
}
- private function resetOrder(): void
+ public function resetOrder(): void
{
- $set = $this->user->piggyBanks()->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']);
+ // TODO duplicate code
+ $set = PiggyBank
+ ::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
+ ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
+ ->where('accounts.user_id', $this->user->id)
+ ->with(
+ [
+ 'account',
+ 'objectGroups',
+ ]
+ )
+ ->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']);
$current = 1;
foreach ($set as $piggyBank) {
if ($piggyBank->order !== $current) {
diff --git a/app/Http/Controllers/PiggyBank/IndexController.php b/app/Http/Controllers/PiggyBank/IndexController.php
index 9c08ebdf25..eca160f505 100644
--- a/app/Http/Controllers/PiggyBank/IndexController.php
+++ b/app/Http/Controllers/PiggyBank/IndexController.php
@@ -36,6 +36,7 @@ use FireflyIII\Transformers\PiggyBankTransformer;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
+use Illuminate\Support\Collection;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\ParameterBag;
@@ -57,7 +58,7 @@ class IndexController extends Controller
$this->middleware(
function ($request, $next) {
- app('view')->share('title', (string)trans('firefly.piggyBanks'));
+ app('view')->share('title', (string) trans('firefly.piggyBanks'));
app('view')->share('mainTitleIcon', 'fa-bullseye');
$this->piggyRepos = app(PiggyBankRepositoryInterface::class);
@@ -79,63 +80,26 @@ class IndexController extends Controller
public function index()
{
$this->cleanupObjectGroups();
- //$this->piggyRepos->resetOrder();
- $collection = $this->piggyRepos->getPiggyBanks();
- $accounts = [];
+ $this->piggyRepos->resetOrder();
+ $collection = $this->piggyRepos->getPiggyBanks();
/** @var Carbon $end */
- $end = session('end', today(config('app.timezone'))->endOfMonth());
+ $end = session('end', today(config('app.timezone'))->endOfMonth());
// transform piggies using the transformer:
- $parameters = new ParameterBag();
+ $parameters = new ParameterBag();
$parameters->set('end', $end);
- // make piggy bank groups:
- $piggyBanks = [];
-
- /** @var PiggyBankTransformer $transformer */
- $transformer = app(PiggyBankTransformer::class);
- $transformer->setParameters(new ParameterBag());
/** @var AccountTransformer $accountTransformer */
$accountTransformer = app(AccountTransformer::class);
$accountTransformer->setParameters($parameters);
- /** @var PiggyBank $piggy */
- foreach ($collection as $piggy) {
- $array = $transformer->transform($piggy);
- $groupOrder = (int)$array['object_group_order'];
- // make group array if necessary:
- $piggyBanks[$groupOrder] ??= [
- 'object_group_id' => $array['object_group_id'] ?? 0,
- 'object_group_title' => $array['object_group_title'] ?? trans('firefly.default_group_title_name'),
- 'piggy_banks' => [],
- ];
-
- $account = $accountTransformer->transform($piggy->account);
- $accountId = (int)$account['id'];
- $array['attachments'] = $this->piggyRepos->getAttachments($piggy);
- if (!array_key_exists($accountId, $accounts)) {
- // create new:
- $accounts[$accountId] = $account;
-
- // add some interesting details:
- $accounts[$accountId]['left'] = $accounts[$accountId]['current_balance'];
- $accounts[$accountId]['saved'] = 0;
- $accounts[$accountId]['target'] = 0;
- $accounts[$accountId]['to_save'] = 0;
- }
-
- // calculate new interesting fields:
- $accounts[$accountId]['left'] -= $array['current_amount'];
- $accounts[$accountId]['saved'] += $array['current_amount'];
- $accounts[$accountId]['target'] += $array['target_amount'];
- $accounts[$accountId]['to_save'] += ($array['target_amount'] - $array['current_amount']);
- $array['account_name'] = $account['name'];
- $piggyBanks[$groupOrder]['piggy_banks'][] = $array;
- }
- // do a bunch of summaries.
- $piggyBanks = $this->makeSums($piggyBanks);
+ // data
+ $piggyBanks = $this->groupPiggyBanks($collection);
+ $accounts = $this->collectAccounts($collection);
+ $accounts = $this->mergeAccountsAndPiggies($piggyBanks, $accounts);
+ $piggyBanks = $this->makeSums($piggyBanks);
ksort($piggyBanks);
@@ -148,7 +112,7 @@ class IndexController extends Controller
foreach ($piggyBanks as $groupOrder => $group) {
$groupId = $group['object_group_id'];
foreach ($group['piggy_banks'] as $piggy) {
- $currencyId = $piggy['currency_id'];
+ $currencyId = $piggy['currency_id'];
$sums[$groupId][$currencyId] ??= [
'target' => '0',
'saved' => '0',
@@ -163,10 +127,10 @@ class IndexController extends Controller
// current_amount
// left_to_save
// save_per_month
- $sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string)$piggy['target_amount']);
- $sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string)$piggy['current_amount']);
- $sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string)$piggy['left_to_save']);
- $sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string)$piggy['save_per_month']);
+ $sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string) $piggy['target_amount']);
+ $sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string) $piggy['current_amount']);
+ $sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string) $piggy['left_to_save']);
+ $sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string) $piggy['save_per_month']);
}
}
foreach ($piggyBanks as $groupOrder => $group) {
@@ -182,8 +146,8 @@ class IndexController extends Controller
*/
public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse
{
- $objectGroupTitle = (string)$request->get('objectGroupTitle');
- $newOrder = (int)$request->get('order');
+ $objectGroupTitle = (string) $request->get('objectGroupTitle');
+ $newOrder = (int) $request->get('order');
$this->piggyRepos->setOrder($piggyBank, $newOrder);
if ('' !== $objectGroupTitle) {
$this->piggyRepos->setObjectGroup($piggyBank, $objectGroupTitle);
@@ -194,4 +158,91 @@ class IndexController extends Controller
return response()->json(['data' => 'OK']);
}
+
+ private function groupPiggyBanks(Collection $collection): array
+ {
+ /** @var PiggyBankTransformer $transformer */
+ $transformer = app(PiggyBankTransformer::class);
+ $transformer->setParameters(new ParameterBag());
+ $piggyBanks = [];
+ /** @var PiggyBank $piggy */
+ foreach ($collection as $piggy) {
+ $array = $transformer->transform($piggy);
+ $groupOrder = (int) $array['object_group_order'];
+ $piggyBanks[$groupOrder] ??= [
+ 'object_group_id' => $array['object_group_id'] ?? 0,
+ 'object_group_title' => $array['object_group_title'] ?? trans('firefly.default_group_title_name'),
+ 'piggy_banks' => [],
+ ];
+ $array['attachments'] = $this->piggyRepos->getAttachments($piggy);
+
+ // sum the total amount for the index.
+ $piggyBanks[$groupOrder]['piggy_banks'][] = $array;
+ }
+ return $piggyBanks;
+ }
+
+ private function collectAccounts(Collection $collection): array
+ {
+ /** @var Carbon $end */
+ $end = session('end', today(config('app.timezone'))->endOfMonth());
+
+ // transform piggies using the transformer:
+ $parameters = new ParameterBag();
+ $parameters->set('end', $end);
+
+ /** @var AccountTransformer $accountTransformer */
+ $accountTransformer = app(AccountTransformer::class);
+ $accountTransformer->setParameters($parameters);
+
+ $return = [];
+ /** @var PiggyBank $piggy */
+ foreach ($collection as $piggy) {
+ $accounts = $piggy->accounts;
+ /** @var Account $account */
+ foreach ($accounts as $account) {
+ $array = $accountTransformer->transform($account);
+ $accountId = (int) $array['id'];
+ if (!array_key_exists($accountId, $return)) {
+ $return[$accountId] = $array;
+
+ // add some interesting details:
+ $return[$accountId]['left'] = $return[$accountId]['current_balance'];
+ $return[$accountId]['saved'] = '0';
+ $return[$accountId]['target'] = '0';
+ $return[$accountId]['to_save'] = '0';
+ }
+
+ // calculate new interesting fields:
+// $return[$accountId]['left'] -= $array['current_amount'];
+// $return[$accountId]['saved'] += $array['current_amount'];
+// $return[$accountId]['target'] += $array['target_amount'];
+// $return[$accountId]['to_save'] += ($array['target_amount'] - $array['current_amount']);
+// $return['account_name'] = $account['name'];
+
+ }
+ }
+ return $return;
+ }
+
+ private function mergeAccountsAndPiggies(array $piggyBanks, array $accounts): array
+ {
+ /** @var array $piggyBank */
+ foreach ($piggyBanks as $group) {
+ foreach ($group['piggy_banks'] as $piggyBank) {
+ // loop all accounts in this piggy bank subtract the current amount from "left to save" in the $accounts array.
+ /** @var array $piggyAccount */
+ foreach ($piggyBank['accounts'] as $piggyAccount) {
+ $accountId = $piggyAccount['id'];
+ if (array_key_exists($accountId, $accounts)) {
+ $accounts[$accountId]['left'] = bcsub($accounts[$accountId]['left'], $piggyAccount['current_amount']);
+ $accounts[$accountId]['saved'] = bcadd($accounts[$accountId]['saved'], $piggyAccount['current_amount']);
+ $accounts[$accountId]['target'] = bcadd($accounts[$accountId]['target'], $piggyBank['target_amount']);
+ $accounts[$accountId]['to_save'] = bcadd($accounts[$accountId]['to_save'], bcsub($piggyBank['target_amount'], $piggyAccount['current_amount']));
+ }
+ }
+ }
+ }
+ return $accounts;
+ }
}
diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php
index d5a936cf31..fa797977fc 100644
--- a/app/Models/PiggyBank.php
+++ b/app/Models/PiggyBank.php
@@ -116,7 +116,7 @@ class PiggyBank extends Model
public function accounts(): BelongsToMany
{
- return $this->belongsToMany(Account::class);
+ return $this->belongsToMany(Account::class)->withPivot('current_amount');
}
public function piggyBankRepetitions(): HasMany
diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php
index ce32ca3269..cf73589b94 100644
--- a/app/Repositories/PiggyBank/PiggyBankRepository.php
+++ b/app/Repositories/PiggyBank/PiggyBankRepository.php
@@ -25,6 +25,7 @@ namespace FireflyIII\Repositories\PiggyBank;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
+use FireflyIII\Factory\PiggyBankFactory;
use FireflyIII\Models\Attachment;
use FireflyIII\Models\Note;
use FireflyIII\Models\PiggyBank;
@@ -285,7 +286,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
'objectGroups',
]
)
- ->orderBy('piggy_banks.order', 'ASC')->get();
+ ->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']);
}
/**
@@ -352,4 +353,11 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
{
throw new FireflyException('TODO Not implemented');
}
+
+ #[\Override] public function resetOrder(): void
+ {
+ $factory = new PiggyBankFactory();
+ $factory->setUser($this->user);
+ $factory->resetOrder();
+ }
}
diff --git a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php
index dfe534f4cf..b2c13d5764 100644
--- a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php
+++ b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php
@@ -113,10 +113,7 @@ interface PiggyBankRepositoryInterface
public function removeObjectGroup(PiggyBank $piggyBank): PiggyBank;
-// /**
-// * Correct order of piggies in case of issues.
-// */
-// public function resetOrder(): void;
+ public function resetOrder(): void;
/**
* Search for piggy banks.
diff --git a/app/Transformers/PiggyBankTransformer.php b/app/Transformers/PiggyBankTransformer.php
index 701c816257..ae15958fbe 100644
--- a/app/Transformers/PiggyBankTransformer.php
+++ b/app/Transformers/PiggyBankTransformer.php
@@ -132,10 +132,11 @@ class PiggyBankTransformer extends AbstractTransformer
private function renderAccounts(PiggyBank $piggyBank): array
{
$return = [];
- foreach ($piggyBank->accounts as $account) {
+ foreach ($piggyBank->accounts()->get() as $account) {
$return[] = [
'id' => $account->id,
'name' => $account->name,
+ 'current_amount' => $account->pivot->current_amount,
// TODO add balance, add left to save.
];
}
From ea4be9dd0cc4927e1551df9c729779af414a6702 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Fri, 6 Dec 2024 08:10:31 +0100
Subject: [PATCH 011/122] Expand forms and improve validation for multi-account
piggy banks
---
.../Models/PiggyBank/StoreRequest.php | 49 ++++++++++++++++---
app/Factory/PiggyBankFactory.php | 16 +++---
.../PiggyBank/CreateController.php | 5 +-
app/Http/Requests/PiggyBankStoreRequest.php | 29 +++++++----
app/Models/AccountType.php | 26 +++++-----
.../PiggyBank/ModifiesPiggyBanks.php | 4 +-
.../PiggyBank/PiggyBankRepository.php | 4 +-
.../Support/RecurringTransactionTrait.php | 6 +--
app/Support/Form/AccountForm.php | 18 ++++++-
app/Support/Form/FormSupport.php | 19 +++++++
config/twigbridge.php | 1 +
resources/lang/en_US/firefly.php | 1 +
resources/lang/en_US/form.php | 7 +--
resources/lang/en_US/validation.php | 2 +
resources/views/form/multi-select.twig | 10 ++++
resources/views/piggy-banks/create.twig | 9 ++--
16 files changed, 149 insertions(+), 57 deletions(-)
create mode 100644 resources/views/form/multi-select.twig
diff --git a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php
index d73abc7b8c..2566cfe8ba 100644
--- a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php
+++ b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php
@@ -24,8 +24,11 @@ declare(strict_types=1);
namespace FireflyIII\Api\V1\Requests\Models\PiggyBank;
+use FireflyIII\Exceptions\FireflyException;
+use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Rules\IsValidPositiveAmount;
+use FireflyIII\Rules\IsValidZeroOrMoreAmount;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
use Illuminate\Foundation\Http\FormRequest;
@@ -73,27 +76,30 @@ class StoreRequest extends FormRequest
'accounts' => 'required',
'accounts.*' => 'array|required',
'accounts.*.account_id' => 'required|numeric|belongsToUser:accounts,id',
- 'accounts.*.current_amount' => ['numeric', new IsValidPositiveAmount()],
+ 'accounts.*.current_amount' => ['numeric', new IsValidZeroOrMoreAmount()],
'object_group_id' => 'numeric|belongsToUser:object_groups,id',
'object_group_title' => ['min:1', 'max:255'],
- 'target_amount' => ['required', new IsValidPositiveAmount()],
+ 'target_amount' => ['required', new IsValidZeroOrMoreAmount()],
'start_date' => 'date|nullable',
- 'transaction_currency_id' => 'exists:transaction_currencies,id',
- 'transaction_currency_code' => 'exists:transaction_currencies,code',
+ 'transaction_currency_id' => 'exists:transaction_currencies,id|required_without:transaction_currency_code',
+ 'transaction_currency_code' => 'exists:transaction_currencies,code|required_without:transaction_currency_id',
'target_date' => 'date|nullable|after:start_date',
'notes' => 'max:65000',
];
}
/**
- * Can only store money on liabilities and asset accouns.
+ * Can only store money on liabilities and asset accounts.
*/
public function withValidator(Validator $validator): void
{
$validator->after(
function (Validator $validator): void {
// validate start before end only if both are there.
- $data = $validator->getData();
+ $data = $validator->getData();
+ $currency = $this->getCurrencyFromData($data);
+ $targetAmount = (string) ($data['target_amount'] ?? '0');
+ $currentAmount = '0';
if (array_key_exists('accounts', $data) && is_array($data['accounts'])) {
$repository = app(AccountRepositoryInterface::class);
$types = config('firefly.piggy_bank_account_types');
@@ -101,6 +107,13 @@ class StoreRequest extends FormRequest
$accountId = (int) ($array['account_id'] ?? 0);
$account = $repository->find($accountId);
if (null !== $account) {
+ // check currency here.
+ $accountCurrency = $repository->getAccountCurrency($account);
+ $isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency');
+ $currentAmount = bcadd($currentAmount, (string)($array['current_amount'] ?? '0'));
+ if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) {
+ $validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_currency'));
+ }
$type = $account->accountType->type;
if (!in_array($type, $types, true)) {
$validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_type'));
@@ -108,6 +121,9 @@ class StoreRequest extends FormRequest
}
}
}
+ if(bccomp($targetAmount, $currentAmount) === -1 && bccomp($targetAmount, '0') === 1) {
+ $validator->errors()->add('target_amount', trans('validation.current_amount_too_much'));
+ }
}
);
if ($validator->fails()) {
@@ -126,10 +142,27 @@ class StoreRequest extends FormRequest
continue;
}
$return[] = [
- 'account_id' => $this->integerFromValue((string)($entry['account_id'] ?? '0')),
- 'current_amount' => $this->clearString($entry['current_amount'] ?? '0'),
+ 'account_id' => $this->integerFromValue((string) ($entry['account_id'] ?? '0')),
+ 'current_amount' => $this->clearString((string) ($entry['current_amount'] ?? '0')),
];
}
return $return;
}
+
+ private function getCurrencyFromData(array $data): TransactionCurrency
+ {
+ if (array_key_exists('transaction_currency_code', $data) && '' !== (string) $data['transaction_currency_code']) {
+ $currency = TransactionCurrency::whereCode($data['transaction_currency_code'])->first();
+ if (null !== $currency) {
+ return $currency;
+ }
+ }
+ if (array_key_exists('transaction_currency_id', $data) && '' !== (string) $data['transaction_currency_id']) {
+ $currency = TransactionCurrency::find((int) $data['transaction_currency_id']);
+ if (null !== $currency) {
+ return $currency;
+ }
+ }
+ throw new FireflyException('Unexpected empty currency.');
+ }
}
diff --git a/app/Factory/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php
index 7f9def7600..cd41ee1deb 100644
--- a/app/Factory/PiggyBankFactory.php
+++ b/app/Factory/PiggyBankFactory.php
@@ -37,7 +37,11 @@ use Illuminate\Database\QueryException;
*/
class PiggyBankFactory
{
- private User $user;
+ public User $user {
+ set(User $value) {
+ $this->user = $value;
+ }
+ }
private CurrencyRepositoryInterface $currencyRepository;
private AccountRepositoryInterface $accountRepository;
private PiggyBankRepositoryInterface $piggyBankRepository;
@@ -138,11 +142,6 @@ class PiggyBankFactory
return $this->user->piggyBanks()->where('piggy_banks.name', $name)->first();
}
- public function setUser(User $user): void
- {
- $this->user = $user;
- }
-
private function getCurrency(array $data): TransactionCurrency {
// currency:
$defaultCurrency = app('amount')->getDefaultCurrency();
@@ -197,7 +196,8 @@ class PiggyBankFactory
private function getMaxOrder(): int
{
- return (int)$this->user->piggyBanks()->max('piggy_banks.order');
+ return (int) $this->piggyBankRepository->getPiggyBanks()->max('order');
+
}
private function linkToAccountIds(PiggyBank $piggyBank, array $accounts): void {
@@ -207,7 +207,7 @@ class PiggyBankFactory
if(null === $account) {
continue;
}
- $piggyBank->accounts()->syncWithoutDetaching([$account->id, ['current_amount' => $info['current_amount'] ?? '0']]);
+ $piggyBank->accounts()->syncWithoutDetaching([$account->id => ['current_amount' => $info['current_amount'] ?? '0']]);
}
}
}
diff --git a/app/Http/Controllers/PiggyBank/CreateController.php b/app/Http/Controllers/PiggyBank/CreateController.php
index 92aac833d9..a0626b5c3b 100644
--- a/app/Http/Controllers/PiggyBank/CreateController.php
+++ b/app/Http/Controllers/PiggyBank/CreateController.php
@@ -92,10 +92,11 @@ class CreateController extends Controller
public function store(PiggyBankStoreRequest $request)
{
$data = $request->getPiggyBankData();
- if (null === $data['startdate']) {
- $data['startdate'] = today(config('app.timezone'));
+ if (null === $data['start_date']) {
+ $data['start_date'] = today(config('app.timezone'));
}
$piggyBank = $this->piggyRepos->store($data);
+ var_dump($data);exit;
session()->flash('success', (string)trans('firefly.stored_piggy_bank', ['name' => $piggyBank->name]));
app('preferences')->mark();
diff --git a/app/Http/Requests/PiggyBankStoreRequest.php b/app/Http/Requests/PiggyBankStoreRequest.php
index 94087fedb8..467cfe607e 100644
--- a/app/Http/Requests/PiggyBankStoreRequest.php
+++ b/app/Http/Requests/PiggyBankStoreRequest.php
@@ -43,15 +43,21 @@ class PiggyBankStoreRequest extends FormRequest
*/
public function getPiggyBankData(): array
{
- return [
+ $data = [
'name' => $this->convertString('name'),
- 'startdate' => $this->getCarbonDate('startdate'),
- 'account_id' => $this->convertInteger('account_id'),
- 'targetamount' => $this->convertString('targetamount'),
- 'targetdate' => $this->getCarbonDate('targetdate'),
+ 'start_date' => $this->getCarbonDate('start_date'),
+ //'account_id' => $this->convertInteger('account_id'),
+ 'accounts' => $this->get('accounts'),
+ 'target_amount' => $this->convertString('target_amount'),
+ 'target_date' => $this->getCarbonDate('target_date'),
'notes' => $this->stringWithNewlines('notes'),
'object_group_title' => $this->convertString('object_group'),
];
+ if(!is_array($data['accounts'])) {
+ $data['accounts'] = [];
+ }
+
+ return $data;
}
/**
@@ -61,10 +67,11 @@ class PiggyBankStoreRequest extends FormRequest
{
return [
'name' => 'required|min:1|max:255|uniquePiggyBankForUser',
- 'account_id' => 'required|belongsToUser:accounts',
- 'targetamount' => ['nullable', new IsValidPositiveAmount()],
- 'startdate' => 'date',
- 'targetdate' => 'date|nullable',
+ 'accounts' => 'required|array',
+ 'accounts.*' => 'required|belongsToUser:accounts',
+ 'target_amount' => ['nullable', new IsValidPositiveAmount()],
+ 'start_date' => 'date',
+ 'target_date' => 'date|nullable',
'order' => 'integer|min:1',
'object_group' => 'min:0|max:255',
'notes' => 'min:1|max:32768|nullable',
@@ -73,6 +80,10 @@ class PiggyBankStoreRequest extends FormRequest
public function withValidator(Validator $validator): void
{
+ // need to have more than one account.
+ // accounts need to have the same currency or be multi-currency(?).
+
+
if ($validator->fails()) {
Log::channel('audit')->error(sprintf('Validation errors in %s', __CLASS__), $validator->errors()->toArray());
}
diff --git a/app/Models/AccountType.php b/app/Models/AccountType.php
index 0ef77adcc2..c8bc76b399 100644
--- a/app/Models/AccountType.php
+++ b/app/Models/AccountType.php
@@ -35,46 +35,46 @@ class AccountType extends Model
{
use ReturnsIntegerIdTrait;
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string ASSET = 'Asset account';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string BENEFICIARY = 'Beneficiary account';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string CASH = 'Cash account';
#[\Deprecated] /** @deprecated */
public const string CREDITCARD = 'Credit card';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string DEBT = 'Debt';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string DEFAULT = 'Default account';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string EXPENSE = 'Expense account';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string IMPORT = 'Import account';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string INITIAL_BALANCE = 'Initial balance account';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string LIABILITY_CREDIT = 'Liability credit account';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string LOAN = 'Loan';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string MORTGAGE = 'Mortgage';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string RECONCILIATION = 'Reconciliation account';
- #[\Deprecated]
+ #[\Deprecated] /** @deprecated */
public const string REVENUE = 'Revenue account';
protected $casts
diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
index 09169ef898..f37bc9e1a2 100644
--- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
+++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
@@ -182,8 +182,8 @@ trait ModifiesPiggyBanks
*/
public function store(array $data): PiggyBank
{
- $factory = new PiggyBankFactory();
- $factory->setUser($this->user);
+ $factory = new PiggyBankFactory();
+ $factory->user = $this->user;
return $factory->store($data);
}
diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php
index cf73589b94..bd8c78de52 100644
--- a/app/Repositories/PiggyBank/PiggyBankRepository.php
+++ b/app/Repositories/PiggyBank/PiggyBankRepository.php
@@ -356,8 +356,8 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
#[\Override] public function resetOrder(): void
{
- $factory = new PiggyBankFactory();
- $factory->setUser($this->user);
+ $factory = new PiggyBankFactory();
+ $factory->user = $this->user;
$factory->resetOrder();
}
}
diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.php
index 438563c98b..1ca7f701c2 100644
--- a/app/Services/Internal/Support/RecurringTransactionTrait.php
+++ b/app/Services/Internal/Support/RecurringTransactionTrait.php
@@ -283,9 +283,9 @@ trait RecurringTransactionTrait
protected function updatePiggyBank(RecurrenceTransaction $transaction, int $piggyId): void
{
/** @var PiggyBankFactory $factory */
- $factory = app(PiggyBankFactory::class);
- $factory->setUser($transaction->recurrence->user);
- $piggyBank = $factory->find($piggyId, null);
+ $factory = app(PiggyBankFactory::class);
+ $factory->user = $transaction->recurrence->user;
+ $piggyBank = $factory->find($piggyId, null);
if (null !== $piggyBank) {
/** @var null|RecurrenceMeta $entry */
$entry = $transaction->recurrenceTransactionMeta()->where('name', 'piggy_bank_id')->first();
diff --git a/app/Support/Form/AccountForm.php b/app/Support/Form/AccountForm.php
index b7bc140a79..8034bf93e6 100644
--- a/app/Support/Form/AccountForm.php
+++ b/app/Support/Form/AccountForm.php
@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Form;
+use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
@@ -141,12 +142,25 @@ class AccountForm
*/
public function assetAccountList(string $name, $value = null, ?array $options = null): string
{
- $types = [AccountType::ASSET, AccountType::DEFAULT];
+ $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value];
$grouped = $this->getAccountsGrouped($types);
return $this->select($name, $grouped, $value, $options);
}
+ /**
+ * Basic list of asset accounts.
+ *
+ * @param mixed $value
+ */
+ public function assetLiabilityMultiAccountList(string $name, $value = null, ?array $options = null): string
+ {
+ $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value,AccountTypeEnum::LOAN->value];
+ $grouped = $this->getAccountsGrouped($types);
+
+ return $this->multiSelect($name, $grouped, $value, $options);
+ }
+
/**
* Same list but all liabilities as well.
*
@@ -154,7 +168,7 @@ class AccountForm
*/
public function longAccountList(string $name, $value = null, ?array $options = null): string
{
- $types = [AccountType::ASSET, AccountType::DEFAULT, AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
+ $types = [AccountType::ASSET, AccountType::DEFAULT, AccountType::MORTGAGE, AccountType::DEBT, AccountType::LOAN];
$grouped = $this->getAccountsGrouped($types);
return $this->select($name, $grouped, $value, $options);
diff --git a/app/Support/Form/FormSupport.php b/app/Support/Form/FormSupport.php
index f91931cd60..09c8de4910 100644
--- a/app/Support/Form/FormSupport.php
+++ b/app/Support/Form/FormSupport.php
@@ -56,6 +56,25 @@ trait FormSupport
return $html;
}
+ public function multiSelect(string $name, ?array $list = null, $selected = null, ?array $options = null): string
+ {
+ $list ??= [];
+ $label = $this->label($name, $options);
+ $options = $this->expandOptionArray($name, $label, $options);
+ $classes = $this->getHolderClasses($name);
+ $selected = $this->fillFieldValue($name, $selected);
+ unset($options['autocomplete'], $options['placeholder']);
+
+ try {
+ $html = view('form.multi-select', compact('classes', 'name', 'label', 'selected', 'options', 'list'))->render();
+ } catch (\Throwable $e) {
+ app('log')->debug(sprintf('Could not render multi-select(): %s', $e->getMessage()));
+ $html = 'Could not render multi-select.';
+ }
+
+ return $html;
+ }
+
protected function label(string $name, ?array $options = null): string
{
$options ??= [];
diff --git a/config/twigbridge.php b/config/twigbridge.php
index da8d491d82..60d1e1023d 100644
--- a/config/twigbridge.php
+++ b/config/twigbridge.php
@@ -197,6 +197,7 @@ return [
'assetAccountCheckList',
'assetAccountList',
'longAccountList',
+ 'assetLiabilityMultiAccountList',
],
],
'CurrencyForm' => [
diff --git a/resources/lang/en_US/firefly.php b/resources/lang/en_US/firefly.php
index aa395cd3da..1f6c37af8e 100644
--- a/resources/lang/en_US/firefly.php
+++ b/resources/lang/en_US/firefly.php
@@ -2197,6 +2197,7 @@ return [
'amount' => 'Amount',
'overview' => 'Overview',
'saveOnAccount' => 'Save on account',
+ 'saveOnAccounts' => 'Save on account(s)',
'unknown' => 'Unknown',
'monthly' => 'Monthly',
'profile' => 'Profile',
diff --git a/resources/lang/en_US/form.php b/resources/lang/en_US/form.php
index 5e6ab8d583..a83bbd764e 100644
--- a/resources/lang/en_US/form.php
+++ b/resources/lang/en_US/form.php
@@ -69,6 +69,7 @@ return [
// Ignore this comment
'targetamount' => 'Target amount',
+ 'target_amount' => 'Target amount',
'account_role' => 'Account role',
'opening_balance_date' => 'Opening balance date',
'cc_type' => 'Credit card payment plan',
@@ -106,7 +107,9 @@ return [
'deletePermanently' => 'Delete permanently',
'cancel' => 'Cancel',
'targetdate' => 'Target date',
+ 'target_date' => 'Target date',
'startdate' => 'Start date',
+ 'start_date' => 'Start date',
'tag' => 'Tag',
'under' => 'Under',
'symbol' => 'Symbol',
@@ -116,7 +119,6 @@ return [
'creditCardNumber' => 'Credit card number',
'has_headers' => 'Headers',
'date_format' => 'Date format',
- 'specifix' => 'Bank- or file specific fixes',
'attachments[]' => 'Attachments',
'title' => 'Title',
'notes' => 'Notes',
@@ -125,8 +127,7 @@ return [
'size' => 'Size',
'trigger' => 'Trigger',
'stop_processing' => 'Stop processing',
- 'start_date' => 'Start of range',
- 'end_date' => 'End of range',
+ 'end_date' => 'End date',
'enddate' => 'End date',
'move_rules_before_delete' => 'Rule group',
'start' => 'Start of range',
diff --git a/resources/lang/en_US/validation.php b/resources/lang/en_US/validation.php
index 9f6dc2fe54..587db8cb29 100644
--- a/resources/lang/en_US/validation.php
+++ b/resources/lang/en_US/validation.php
@@ -26,6 +26,8 @@ declare(strict_types=1);
return [
'invalid_account_type' => 'A piggy bank can only be linked to asset accounts and liabilities',
+ 'invalid_account_currency' => 'This account does not use the currency you have selected',
+ 'current_amount_too_much' => 'The combined amount in "current_amount" cannot exceed the "target_amount".',
'filter_must_be_in' => 'Filter ":filter" must be one of: :values',
'filter_not_string' => 'Filter ":filter" is expected to be a string of text',
'bad_api_filter' => 'This API endpoint does not support ":filter" as a filter.',
diff --git a/resources/views/form/multi-select.twig b/resources/views/form/multi-select.twig
new file mode 100644
index 0000000000..b27359e41e
--- /dev/null
+++ b/resources/views/form/multi-select.twig
@@ -0,0 +1,10 @@
+
+
+
+
+ {{ Html.select(name~"[]", list, selected).id(options.id).class('form-control').attribute('multiple').attribute('autocomplete','off').attribute('spellcheck','false').attribute('placeholder', options.placeholder) }}
+ {% include 'form.help' %}
+ {% include 'form.feedback' %}
+
+
+
diff --git a/resources/views/piggy-banks/create.twig b/resources/views/piggy-banks/create.twig
index f25dd211a8..84662207a4 100644
--- a/resources/views/piggy-banks/create.twig
+++ b/resources/views/piggy-banks/create.twig
@@ -8,7 +8,6 @@
- {{ __('firefly.bills_to_pay') }}
+ {{ __('firefly.bills_to_pay') }}
TODO No subscriptions are waiting to be paid
From 7c8445707e79e040d48523117ddac018e30a24c3 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Thu, 26 Dec 2024 14:12:05 +0100
Subject: [PATCH 108/122] Add moar debug.
---
app/Http/Controllers/Chart/AccountController.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php
index d4f95e0334..f2a3c6ea23 100644
--- a/app/Http/Controllers/Chart/AccountController.php
+++ b/app/Http/Controllers/Chart/AccountController.php
@@ -417,7 +417,7 @@ class AccountController extends Controller
*/
public function period(Account $account, Carbon $start, Carbon $end): JsonResponse
{
- Log::debug('Now in period()');
+ Log::debug(sprintf('Now in period("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d')));
$chartData = [];
$cache = new CacheProperties();
$cache->addProperty('chart.account.period');
From a3ff73903aceb9d4e9a96fe5d3f8f408faadbb83 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Fri, 27 Dec 2024 05:44:03 +0100
Subject: [PATCH 109/122] Fix bad error message.
---
app/Jobs/DownloadExchangeRates.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/app/Jobs/DownloadExchangeRates.php b/app/Jobs/DownloadExchangeRates.php
index 17bf251f1d..5ba8d7f998 100644
--- a/app/Jobs/DownloadExchangeRates.php
+++ b/app/Jobs/DownloadExchangeRates.php
@@ -102,7 +102,7 @@ class DownloadExchangeRates implements ShouldQueue
try {
$res = $client->get($url);
} catch (ConnectException|RequestException $e) {
- app('log')->warning(sprintf('Trying to grab "%s" resulted in error "%d".', $url, $e->getMessage()));
+ app('log')->warning(sprintf('Trying to grab "%s" resulted in error "%s".', $url, $e->getMessage()));
return;
}
From 2314ce800484908c4691f212b04b971806c5657a Mon Sep 17 00:00:00 2001
From: James Cole
Date: Fri, 27 Dec 2024 06:48:58 +0100
Subject: [PATCH 110/122] Refactor and renam commands.
---
.../ConvertsDatesToUTC.php} | 23 +++++++-
.../Commands/Correction/CorrectDatabase.php | 10 +++-
.../CorrectsGroupInformation.php} | 8 +--
.../CorrectsTimezoneInformation.php} | 21 ++++++-
.../CreatesGroupMemberships.php} | 8 +--
.../RestoresOAuthKeys.php} | 10 ++--
...ptyObjects.php => ReportsEmptyObjects.php} | 4 +-
...portIntegrity.php => ReportsIntegrity.php} | 10 ++--
.../{ReportSum.php => ReportsSums.php} | 5 +-
...ier.php => AddsTransactionIdentifiers.php} | 4 +-
...base.php => RemovesDatabaseDecryption.php} | 7 +--
...Balance.php => RepairsAccountBalances.php} | 7 +--
...ences.php => RepairsPostgresSequences.php} | 7 +--
...ions.php => UpgradeTransferCurrencies.php} | 6 +-
...cies.php => UpgradesAccountCurrencies.php} | 4 +-
...ntMeta.php => UpgradesAccountMetaData.php} | 7 +--
...ttachments.php => UpgradesAttachments.php} | 4 +-
...teToRules.php => UpgradesBillsToRules.php} | 7 +--
...ods.php => UpgradesBudgetLimitPeriods.php} | 7 +--
...tCurrency.php => UpgradesBudgetLimits.php} | 7 +--
....php => UpgradesCreditCardLiabilities.php} | 7 +--
...es.php => UpgradesCurrencyPreferences.php} | 6 +-
...gradeDatabase.php => UpgradesDatabase.php} | 56 ++++++++-----------
...urnals.php => UpgradesJournalMetaData.php} | 9 +--
...rnalNotes.php => UpgradesJournalNotes.php} | 7 +--
...iabilities.php => UpgradesLiabilities.php} | 7 +--
...Eight.php => UpgradesLiabilitiesEight.php} | 30 +---------
...yBanks.php => UpgradesMultiPiggyBanks.php} | 6 +-
...eta.php => UpgradesRecurrenceMetaData.php} | 4 +-
...nceType.php => UpgradesRecurrenceType.php} | 4 +-
...uleActions.php => UpgradesRuleActions.php} | 4 +-
...Locations.php => UpgradesTagLocations.php} | 4 +-
...grateToGroups.php => UpgradesToGroups.php} | 11 +---
...=> UpgradesVariousCurrencyInformation.php} | 8 +--
.../Authentication/RemoteUserProvider.php | 2 +-
resources/lang/en_US/firefly.php | 1 +
resources/views/currencies/index.twig | 5 +-
37 files changed, 153 insertions(+), 184 deletions(-)
rename app/Console/Commands/{Integrity/ConvertDatesToUTC.php => Correction/ConvertsDatesToUTC.php} (79%)
rename app/Console/Commands/{Integrity/UpdateGroupInformation.php => Correction/CorrectsGroupInformation.php} (95%)
rename app/Console/Commands/{Integrity/AddTimezonesToDates.php => Correction/CorrectsTimezoneInformation.php} (82%)
rename app/Console/Commands/{Integrity/CreateGroupMemberships.php => Correction/CreatesGroupMemberships.php} (94%)
rename app/Console/Commands/{Integrity/RestoreOAuthKeys.php => Correction/RestoresOAuthKeys.php} (93%)
rename app/Console/Commands/Integrity/{ReportEmptyObjects.php => ReportsEmptyObjects.php} (98%)
rename app/Console/Commands/Integrity/{ReportIntegrity.php => ReportsIntegrity.php} (85%)
rename app/Console/Commands/Integrity/{ReportSum.php => ReportsSums.php} (96%)
rename app/Console/Commands/Upgrade/{TransactionIdentifier.php => AddsTransactionIdentifiers.php} (98%)
rename app/Console/Commands/Upgrade/{DecryptDatabase.php => RemovesDatabaseDecryption.php} (97%)
rename app/Console/Commands/Upgrade/{CorrectAccountBalance.php => RepairsAccountBalances.php} (91%)
rename app/Console/Commands/Upgrade/{FixPostgresSequences.php => RepairsPostgresSequences.php} (96%)
rename app/Console/Commands/Upgrade/{TransferCurrenciesCorrections.php => UpgradeTransferCurrencies.php} (99%)
rename app/Console/Commands/Upgrade/{AccountCurrencies.php => UpgradesAccountCurrencies.php} (98%)
rename app/Console/Commands/Upgrade/{RenameAccountMeta.php => UpgradesAccountMetaData.php} (93%)
rename app/Console/Commands/Upgrade/{MigrateAttachments.php => UpgradesAttachments.php} (95%)
rename app/Console/Commands/Upgrade/{MigrateToRules.php => UpgradesBillsToRules.php} (98%)
rename app/Console/Commands/Upgrade/{AppendBudgetLimitPeriods.php => UpgradesBudgetLimitPeriods.php} (96%)
rename app/Console/Commands/Upgrade/{BudgetLimitCurrency.php => UpgradesBudgetLimits.php} (94%)
rename app/Console/Commands/Upgrade/{CCLiabilities.php => UpgradesCreditCardLiabilities.php} (96%)
rename app/Console/Commands/Upgrade/{UpgradeCurrencyPreferences.php => UpgradesCurrencyPreferences.php} (95%)
rename app/Console/Commands/Upgrade/{UpgradeDatabase.php => UpgradesDatabase.php} (59%)
rename app/Console/Commands/Upgrade/{BackToJournals.php => UpgradesJournalMetaData.php} (96%)
rename app/Console/Commands/Upgrade/{MigrateJournalNotes.php => UpgradesJournalNotes.php} (93%)
rename app/Console/Commands/Upgrade/{UpgradeLiabilities.php => UpgradesLiabilities.php} (96%)
rename app/Console/Commands/Upgrade/{UpgradeLiabilitiesEight.php => UpgradesLiabilitiesEight.php} (85%)
rename app/Console/Commands/Upgrade/{UpgradeMultiPiggyBanks.php => UpgradesMultiPiggyBanks.php} (93%)
rename app/Console/Commands/Upgrade/{MigrateRecurrenceMeta.php => UpgradesRecurrenceMetaData.php} (95%)
rename app/Console/Commands/Upgrade/{MigrateRecurrenceType.php => UpgradesRecurrenceType.php} (91%)
rename app/Console/Commands/Upgrade/{MigrateRuleActions.php => UpgradesRuleActions.php} (97%)
rename app/Console/Commands/Upgrade/{MigrateTagLocations.php => UpgradesTagLocations.php} (94%)
rename app/Console/Commands/Upgrade/{MigrateToGroups.php => UpgradesToGroups.php} (98%)
rename app/Console/Commands/Upgrade/{OtherCurrenciesCorrections.php => UpgradesVariousCurrencyInformation.php} (97%)
diff --git a/app/Console/Commands/Integrity/ConvertDatesToUTC.php b/app/Console/Commands/Correction/ConvertsDatesToUTC.php
similarity index 79%
rename from app/Console/Commands/Integrity/ConvertDatesToUTC.php
rename to app/Console/Commands/Correction/ConvertsDatesToUTC.php
index 454ee8a033..d2a59c8666 100644
--- a/app/Console/Commands/Integrity/ConvertDatesToUTC.php
+++ b/app/Console/Commands/Correction/ConvertsDatesToUTC.php
@@ -1,4 +1,23 @@
friendlyWarning('Please do not use this command.');
+ return 0;
/**
* @var string $model
* @var array $fields
diff --git a/app/Console/Commands/Correction/CorrectDatabase.php b/app/Console/Commands/Correction/CorrectDatabase.php
index d3eadc0ee7..a0bc6607a3 100644
--- a/app/Console/Commands/Correction/CorrectDatabase.php
+++ b/app/Console/Commands/Correction/CorrectDatabase.php
@@ -34,7 +34,7 @@ class CorrectDatabase extends Command
{
use ShowsFriendlyMessages;
- protected $description = 'Will correct the integrity of your database, if necessary.';
+ protected $description = 'Will validate and correct the integrity of your database, if necessary.';
protected $signature = 'firefly-iii:correct-database';
/**
@@ -49,6 +49,14 @@ class CorrectDatabase extends Command
return 1;
}
$commands = [
+
+ // also just in case, some integrity commands:
+ // 'upgrade:restore-oauth-keys',
+ // 'upgrade:add-timezones-to-dates',
+ // 'upgrade:create-group-memberships',
+ // 'upgrade:upgrade-group-information',
+ // 'upgrade:610-currency-preferences',
+ // 'upgrade:620-piggy-banks',
'firefly-iii:fix-piggies',
'firefly-iii:create-link-types',
'firefly-iii:create-access-tokens',
diff --git a/app/Console/Commands/Integrity/UpdateGroupInformation.php b/app/Console/Commands/Correction/CorrectsGroupInformation.php
similarity index 95%
rename from app/Console/Commands/Integrity/UpdateGroupInformation.php
rename to app/Console/Commands/Correction/CorrectsGroupInformation.php
index 3be6c7ee0d..acdb3b4338 100644
--- a/app/Console/Commands/Integrity/UpdateGroupInformation.php
+++ b/app/Console/Commands/Correction/CorrectsGroupInformation.php
@@ -1,8 +1,8 @@
.
+ * along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
-namespace FireflyIII\Console\Commands\Integrity;
+namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\Account;
diff --git a/app/Console/Commands/Integrity/AddTimezonesToDates.php b/app/Console/Commands/Correction/CorrectsTimezoneInformation.php
similarity index 82%
rename from app/Console/Commands/Integrity/AddTimezonesToDates.php
rename to app/Console/Commands/Correction/CorrectsTimezoneInformation.php
index cc8be30011..d17451e89a 100644
--- a/app/Console/Commands/Integrity/AddTimezonesToDates.php
+++ b/app/Console/Commands/Correction/CorrectsTimezoneInformation.php
@@ -1,4 +1,23 @@
.
+ * along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
-namespace FireflyIII\Console\Commands\Integrity;
+namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Enums\UserRoleEnum;
diff --git a/app/Console/Commands/Integrity/RestoreOAuthKeys.php b/app/Console/Commands/Correction/RestoresOAuthKeys.php
similarity index 93%
rename from app/Console/Commands/Integrity/RestoreOAuthKeys.php
rename to app/Console/Commands/Correction/RestoresOAuthKeys.php
index b84a7eec14..d216702818 100644
--- a/app/Console/Commands/Integrity/RestoreOAuthKeys.php
+++ b/app/Console/Commands/Correction/RestoresOAuthKeys.php
@@ -1,8 +1,8 @@
.
+ * along with this program. If not, see https://www.gnu.org/licenses/.
*/
declare(strict_types=1);
-namespace FireflyIII\Console\Commands\Integrity;
+namespace FireflyIII\Console\Commands\Correction;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Support\System\OAuthKeys;
diff --git a/app/Console/Commands/Integrity/ReportEmptyObjects.php b/app/Console/Commands/Integrity/ReportsEmptyObjects.php
similarity index 98%
rename from app/Console/Commands/Integrity/ReportEmptyObjects.php
rename to app/Console/Commands/Integrity/ReportsEmptyObjects.php
index 811398d673..882df65b5d 100644
--- a/app/Console/Commands/Integrity/ReportEmptyObjects.php
+++ b/app/Console/Commands/Integrity/ReportsEmptyObjects.php
@@ -34,13 +34,13 @@ use Illuminate\Console\Command;
/**
* Class ReportEmptyObjects
*/
-class ReportEmptyObjects extends Command
+class ReportsEmptyObjects extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Reports on empty database objects.';
- protected $signature = 'firefly-iii:report-empty-objects';
+ protected $signature = 'integrity:empty-objects';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Integrity/ReportIntegrity.php b/app/Console/Commands/Integrity/ReportsIntegrity.php
similarity index 85%
rename from app/Console/Commands/Integrity/ReportIntegrity.php
rename to app/Console/Commands/Integrity/ReportsIntegrity.php
index 3dc698a2d3..59405ecef6 100644
--- a/app/Console/Commands/Integrity/ReportIntegrity.php
+++ b/app/Console/Commands/Integrity/ReportsIntegrity.php
@@ -30,7 +30,7 @@ use Illuminate\Console\Command;
/**
* Class ReportIntegrity
*/
-class ReportIntegrity extends Command
+class ReportsIntegrity extends Command
{
use ShowsFriendlyMessages;
@@ -48,11 +48,9 @@ class ReportIntegrity extends Command
return 1;
}
$commands = [
- 'firefly-iii:add-timezones-to-dates',
- 'firefly-iii:create-group-memberships',
- 'firefly-iii:report-empty-objects',
- 'firefly-iii:report-sum',
- 'firefly-iii:upgrade-group-information',
+ //'firefly-iii:add-timezones-to-dates',
+ 'integrity:empty-objects',
+ 'integrity:total-sums',
];
foreach ($commands as $command) {
$this->friendlyLine(sprintf('Now executing %s', $command));
diff --git a/app/Console/Commands/Integrity/ReportSum.php b/app/Console/Commands/Integrity/ReportsSums.php
similarity index 96%
rename from app/Console/Commands/Integrity/ReportSum.php
rename to app/Console/Commands/Integrity/ReportsSums.php
index d348468aba..82c763093d 100644
--- a/app/Console/Commands/Integrity/ReportSum.php
+++ b/app/Console/Commands/Integrity/ReportsSums.php
@@ -32,12 +32,13 @@ use Illuminate\Console\Command;
/**
* Class ReportSkeleton
*/
-class ReportSum extends Command
+class ReportsSums extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Report on the total sum of transactions. Must be 0.';
- protected $signature = 'firefly-iii:report-sum';
+ protected $signature = 'integrity:total-sums';
+
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/TransactionIdentifier.php b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php
similarity index 98%
rename from app/Console/Commands/Upgrade/TransactionIdentifier.php
rename to app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php
index da2848ef4f..0099b11e5d 100644
--- a/app/Console/Commands/Upgrade/TransactionIdentifier.php
+++ b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php
@@ -35,13 +35,13 @@ use Illuminate\Database\QueryException;
/**
* Class TransactionIdentifier
*/
-class TransactionIdentifier extends Command
+class AddsTransactionIdentifiers extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_transaction_identifier';
protected $description = 'Fixes transaction identifiers.';
- protected $signature = 'firefly-iii:transaction-identifiers {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-transaction-identifiers {--F|force : Force the execution of this command.}';
private JournalCLIRepositoryInterface $cliRepository;
private int $count;
diff --git a/app/Console/Commands/Upgrade/DecryptDatabase.php b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php
similarity index 97%
rename from app/Console/Commands/Upgrade/DecryptDatabase.php
rename to app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php
index a7ec4f2efa..a8eab8c9a7 100644
--- a/app/Console/Commands/Upgrade/DecryptDatabase.php
+++ b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php
@@ -30,15 +30,12 @@ use FireflyIII\Models\Preference;
use Illuminate\Console\Command;
use Illuminate\Contracts\Encryption\DecryptException;
-/**
- * Class DecryptDatabase
- */
-class DecryptDatabase extends Command
+class RemovesDatabaseDecryption extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Decrypts the database.';
- protected $signature = 'firefly-iii:decrypt-all';
+ protected $signature = 'upgrade:480-decrypt-all';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/CorrectAccountBalance.php b/app/Console/Commands/Upgrade/RepairsAccountBalances.php
similarity index 91%
rename from app/Console/Commands/Upgrade/CorrectAccountBalance.php
rename to app/Console/Commands/Upgrade/RepairsAccountBalances.php
index a28ea60737..670b20995c 100644
--- a/app/Console/Commands/Upgrade/CorrectAccountBalance.php
+++ b/app/Console/Commands/Upgrade/RepairsAccountBalances.php
@@ -28,16 +28,13 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Support\Models\AccountBalanceCalculator;
use Illuminate\Console\Command;
-/**
- * Class CorrectionSkeleton
- */
-class CorrectAccountBalance extends Command
+class RepairsAccountBalances extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '610_correct_balances';
protected $description = 'Recalculate all account balance amounts';
- protected $signature = 'firefly-iii:correct-account-balance {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:610-account-balances {--F|force : Force the execution of this command.}';
public function handle(): int
{
diff --git a/app/Console/Commands/Upgrade/FixPostgresSequences.php b/app/Console/Commands/Upgrade/RepairsPostgresSequences.php
similarity index 96%
rename from app/Console/Commands/Upgrade/FixPostgresSequences.php
rename to app/Console/Commands/Upgrade/RepairsPostgresSequences.php
index 01f667f490..7d64be8637 100644
--- a/app/Console/Commands/Upgrade/FixPostgresSequences.php
+++ b/app/Console/Commands/Upgrade/RepairsPostgresSequences.php
@@ -27,16 +27,13 @@ namespace FireflyIII\Console\Commands\Upgrade;
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
-/**
- * Class FixPostgresSequences
- */
-class FixPostgresSequences extends Command
+class RepairsPostgresSequences extends Command
{
use ShowsFriendlyMessages;
protected $description = 'Fixes issues with PostgreSQL sequences.';
- protected $signature = 'firefly-iii:fix-pgsql-sequences';
+ protected $signature = 'upgrade:600-pgsql-sequences';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php b/app/Console/Commands/Upgrade/UpgradeTransferCurrencies.php
similarity index 99%
rename from app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php
rename to app/Console/Commands/Upgrade/UpgradeTransferCurrencies.php
index ea6e4cb8ca..4057a7f863 100644
--- a/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php
+++ b/app/Console/Commands/Upgrade/UpgradeTransferCurrencies.php
@@ -35,15 +35,15 @@ use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface;
use Illuminate\Console\Command;
/**
- * Class TransferCurrenciesCorrections
+ * Class UpgradeTransferCurrencies
*/
-class TransferCurrenciesCorrections extends Command
+class UpgradeTransferCurrencies extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_transfer_currencies';
protected $description = 'Updates transfer currency information.';
- protected $signature = 'firefly-iii:transfer-currencies {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-transfer-currencies {--F|force : Force the execution of this command.}';
private array $accountCurrencies;
private AccountRepositoryInterface $accountRepos;
private JournalCLIRepositoryInterface $cliRepos;
diff --git a/app/Console/Commands/Upgrade/AccountCurrencies.php b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php
similarity index 98%
rename from app/Console/Commands/Upgrade/AccountCurrencies.php
rename to app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php
index bc4a0780c0..b50fa0c150 100644
--- a/app/Console/Commands/Upgrade/AccountCurrencies.php
+++ b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php
@@ -39,14 +39,14 @@ use Illuminate\Console\Command;
/**
* Class AccountCurrencies
*/
-class AccountCurrencies extends Command
+class UpgradesAccountCurrencies extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_account_currencies';
protected $description = 'Give all accounts proper currency info.';
- protected $signature = 'firefly-iii:account-currencies {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-account-currencies {--F|force : Force the execution of this command.}';
private AccountRepositoryInterface $accountRepos;
private int $count;
private UserRepositoryInterface $userRepos;
diff --git a/app/Console/Commands/Upgrade/RenameAccountMeta.php b/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php
similarity index 93%
rename from app/Console/Commands/Upgrade/RenameAccountMeta.php
rename to app/Console/Commands/Upgrade/UpgradesAccountMetaData.php
index aba059a38c..8ccbfd63de 100644
--- a/app/Console/Commands/Upgrade/RenameAccountMeta.php
+++ b/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php
@@ -29,10 +29,7 @@ use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\AccountMeta;
use Illuminate\Console\Command;
-/**
- * Class RenameAccountMeta
- */
-class RenameAccountMeta extends Command
+class UpgradesAccountMetaData extends Command
{
use ShowsFriendlyMessages;
@@ -40,7 +37,7 @@ class RenameAccountMeta extends Command
protected $description = 'Rename account meta-data to new format.';
- protected $signature = 'firefly-iii:rename-account-meta {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-account-meta {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/MigrateAttachments.php b/app/Console/Commands/Upgrade/UpgradesAttachments.php
similarity index 95%
rename from app/Console/Commands/Upgrade/MigrateAttachments.php
rename to app/Console/Commands/Upgrade/UpgradesAttachments.php
index cb517059fc..aa2e310733 100644
--- a/app/Console/Commands/Upgrade/MigrateAttachments.php
+++ b/app/Console/Commands/Upgrade/UpgradesAttachments.php
@@ -33,7 +33,7 @@ use Illuminate\Console\Command;
/**
* Class MigrateAttachments
*/
-class MigrateAttachments extends Command
+class UpgradesAttachments extends Command
{
use ShowsFriendlyMessages;
@@ -41,7 +41,7 @@ class MigrateAttachments extends Command
protected $description = 'Migrates attachment meta-data.';
- protected $signature = 'firefly-iii:migrate-attachments {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-attachments {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/MigrateToRules.php b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php
similarity index 98%
rename from app/Console/Commands/Upgrade/MigrateToRules.php
rename to app/Console/Commands/Upgrade/UpgradesBillsToRules.php
index d2fed1a94d..de70c8e761 100644
--- a/app/Console/Commands/Upgrade/MigrateToRules.php
+++ b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php
@@ -36,10 +36,7 @@ use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
use Illuminate\Console\Command;
-/**
- * Class MigrateToRules
- */
-class MigrateToRules extends Command
+class UpgradesBillsToRules extends Command
{
use ShowsFriendlyMessages;
@@ -47,7 +44,7 @@ class MigrateToRules extends Command
protected $description = 'Migrate bills to rules.';
- protected $signature = 'firefly-iii:bills-to-rules {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-bills-to-rules {--F|force : Force the execution of this command.}';
private BillRepositoryInterface $billRepository;
private int $count;
private RuleGroupRepositoryInterface $ruleGroupRepository;
diff --git a/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php b/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php
similarity index 96%
rename from app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php
rename to app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php
index 83a0d11548..a43f05682d 100644
--- a/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php
+++ b/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php
@@ -28,10 +28,7 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\BudgetLimit;
use Illuminate\Console\Command;
-/**
- * Class AppendBudgetLimitPeriods
- */
-class AppendBudgetLimitPeriods extends Command
+class UpgradesBudgetLimitPeriods extends Command
{
use ShowsFriendlyMessages;
@@ -39,7 +36,7 @@ class AppendBudgetLimitPeriods extends Command
protected $description = 'Append budget limits with their (estimated) timeframe.';
- protected $signature = 'firefly-iii:budget-limit-periods {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:550-budget-limit-periods {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/BudgetLimitCurrency.php b/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php
similarity index 94%
rename from app/Console/Commands/Upgrade/BudgetLimitCurrency.php
rename to app/Console/Commands/Upgrade/UpgradesBudgetLimits.php
index a00cf81e0d..98b4020d78 100644
--- a/app/Console/Commands/Upgrade/BudgetLimitCurrency.php
+++ b/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php
@@ -31,10 +31,7 @@ use FireflyIII\Models\BudgetLimit;
use FireflyIII\User;
use Illuminate\Console\Command;
-/**
- * Class BudgetLimitCurrency
- */
-class BudgetLimitCurrency extends Command
+class UpgradesBudgetLimits extends Command
{
use ShowsFriendlyMessages;
@@ -42,7 +39,7 @@ class BudgetLimitCurrency extends Command
protected $description = 'Give budget limits a currency';
- protected $signature = 'firefly-iii:bl-currency {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-budget-limit-currencies {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/CCLiabilities.php b/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php
similarity index 96%
rename from app/Console/Commands/Upgrade/CCLiabilities.php
rename to app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php
index f2211fb59a..33c8acfa90 100644
--- a/app/Console/Commands/Upgrade/CCLiabilities.php
+++ b/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php
@@ -31,16 +31,13 @@ use FireflyIII\Models\AccountType;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
-/**
- * Class CCLiabilities
- */
-class CCLiabilities extends Command
+class UpgradesCreditCardLiabilities extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_cc_liabilities';
protected $description = 'Convert old credit card liabilities.';
- protected $signature = 'firefly-iii:cc-liabilities {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-cc-liabilities {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/UpgradeCurrencyPreferences.php b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php
similarity index 95%
rename from app/Console/Commands/Upgrade/UpgradeCurrencyPreferences.php
rename to app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php
index 1e7cd051dc..927b9e1845 100644
--- a/app/Console/Commands/Upgrade/UpgradeCurrencyPreferences.php
+++ b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php
@@ -33,9 +33,9 @@ use Illuminate\Console\Command;
use Illuminate\Support\Collection;
/**
- * Class UpgradeCurrencyPreferences
+ * Class UpgradesCurrencyPreferences
*/
-class UpgradeCurrencyPreferences extends Command
+class UpgradesCurrencyPreferences extends Command
{
use ShowsFriendlyMessages;
@@ -43,7 +43,7 @@ class UpgradeCurrencyPreferences extends Command
protected $description = 'Upgrade user currency preferences';
- protected $signature = 'firefly-iii:upgrade-currency-preferences {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:610-currency-preferences {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/UpgradeDatabase.php b/app/Console/Commands/Upgrade/UpgradesDatabase.php
similarity index 59%
rename from app/Console/Commands/Upgrade/UpgradeDatabase.php
rename to app/Console/Commands/Upgrade/UpgradesDatabase.php
index 3b27f72ebd..10fdde02ea 100644
--- a/app/Console/Commands/Upgrade/UpgradeDatabase.php
+++ b/app/Console/Commands/Upgrade/UpgradesDatabase.php
@@ -29,10 +29,7 @@ set_time_limit(0);
use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use Illuminate\Console\Command;
-/**
- * Class UpgradeDatabase
- */
-class UpgradeDatabase extends Command
+class UpgradesDatabase extends Command
{
use ShowsFriendlyMessages;
@@ -46,33 +43,26 @@ class UpgradeDatabase extends Command
{
$this->callInitialCommands();
$commands = [
- 'firefly-iii:transaction-identifiers',
- 'firefly-iii:migrate-to-groups',
- 'firefly-iii:account-currencies',
- 'firefly-iii:transfer-currencies',
- 'firefly-iii:other-currencies',
- 'firefly-iii:migrate-notes',
- 'firefly-iii:migrate-attachments',
- 'firefly-iii:bills-to-rules',
- 'firefly-iii:bl-currency',
- 'firefly-iii:cc-liabilities',
- 'firefly-iii:back-to-journals',
- 'firefly-iii:rename-account-meta',
- 'firefly-iii:migrate-recurrence-meta',
- 'firefly-iii:migrate-tag-locations',
- 'firefly-iii:migrate-recurrence-type',
- 'firefly-iii:upgrade-liabilities',
- 'firefly-iii:liabilities-600',
- 'firefly-iii:budget-limit-periods',
- 'firefly-iii:migrate-rule-actions',
- 'firefly-iii:restore-oauth-keys',
- 'firefly-iii:correct-account-balance',
- // also just in case, some integrity commands:
- 'firefly-iii:add-timezones-to-dates',
- 'firefly-iii:create-group-memberships',
- 'firefly-iii:upgrade-group-information',
- 'firefly-iii:upgrade-currency-preferences',
- 'firefly-iii:upgrade-multi-piggies',
+ 'upgrade:480-transaction-identifiers',
+ 'upgrade:480-migrate-to-groups',
+ 'upgrade:480-account-currencies',
+ 'upgrade:480-transfer-currencies',
+ 'upgrade:480-currency-information',
+ 'upgrade:480-notes',
+ 'upgrade:480-attachments',
+ 'upgrade:480-bills-to-rules',
+ 'upgrade:480-budget-limit-currencies',
+ 'upgrade:480-cc-liabilities',
+ 'upgrade:480-journal-meta-data',
+ 'upgrade:480-account-meta',
+ 'upgrade:481-recurrence-meta',
+ 'upgrade:500-tag-locations',
+ 'upgrade:550-recurrence-type',
+ 'upgrade:560-liabilities',
+ 'upgrade:600-liabilities',
+ 'upgrade:550-budget-limit-periods',
+ 'upgrade:600-rule-actions',
+ 'upgrade:610-account-balance',
'firefly-iii:correct-database',
];
$args = [];
@@ -94,7 +84,7 @@ class UpgradeDatabase extends Command
private function callInitialCommands(): void
{
$this->call('migrate', ['--seed' => true, '--force' => true, '--no-interaction' => true]);
- $this->call('firefly-iii:fix-pgsql-sequences');
- $this->call('firefly-iii:decrypt-all');
+ $this->call('upgrade:600-pgsql-sequences');
+ $this->call('upgrade:480-decrypt-all');
}
}
diff --git a/app/Console/Commands/Upgrade/BackToJournals.php b/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php
similarity index 96%
rename from app/Console/Commands/Upgrade/BackToJournals.php
rename to app/Console/Commands/Upgrade/UpgradesJournalMetaData.php
index 31f72f2c74..325de12feb 100644
--- a/app/Console/Commands/Upgrade/BackToJournals.php
+++ b/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php
@@ -32,10 +32,7 @@ use FireflyIII\Models\TransactionJournal;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
-/**
- * Class BackToJournals
- */
-class BackToJournals extends Command
+class UpgradesJournalMetaData extends Command
{
use ShowsFriendlyMessages;
@@ -43,7 +40,7 @@ class BackToJournals extends Command
protected $description = 'Move meta data back to journals, not individual transactions.';
- protected $signature = 'firefly-iii:back-to-journals {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-journal-meta-data {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
@@ -71,7 +68,7 @@ class BackToJournals extends Command
private function isMigrated(): bool
{
- $configVar = app('fireflyconfig')->get(MigrateToGroups::CONFIG_NAME, false);
+ $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
return (bool) $configVar->data;
}
diff --git a/app/Console/Commands/Upgrade/MigrateJournalNotes.php b/app/Console/Commands/Upgrade/UpgradesJournalNotes.php
similarity index 93%
rename from app/Console/Commands/Upgrade/MigrateJournalNotes.php
rename to app/Console/Commands/Upgrade/UpgradesJournalNotes.php
index 2434ba4d10..e638b4144b 100644
--- a/app/Console/Commands/Upgrade/MigrateJournalNotes.php
+++ b/app/Console/Commands/Upgrade/UpgradesJournalNotes.php
@@ -29,10 +29,7 @@ use FireflyIII\Models\Note;
use FireflyIII\Models\TransactionJournalMeta;
use Illuminate\Console\Command;
-/**
- * Class MigrateJournalNotes
- */
-class MigrateJournalNotes extends Command
+class UpgradesJournalNotes extends Command
{
use ShowsFriendlyMessages;
@@ -40,7 +37,7 @@ class MigrateJournalNotes extends Command
protected $description = 'Migrate notes for transaction journals.';
- protected $signature = 'firefly-iii:migrate-notes {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-notes {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/UpgradeLiabilities.php b/app/Console/Commands/Upgrade/UpgradesLiabilities.php
similarity index 96%
rename from app/Console/Commands/Upgrade/UpgradeLiabilities.php
rename to app/Console/Commands/Upgrade/UpgradesLiabilities.php
index 66902b171c..c75ccc6a99 100644
--- a/app/Console/Commands/Upgrade/UpgradeLiabilities.php
+++ b/app/Console/Commands/Upgrade/UpgradesLiabilities.php
@@ -34,16 +34,13 @@ use FireflyIII\Services\Internal\Support\CreditRecalculateService;
use FireflyIII\User;
use Illuminate\Console\Command;
-/**
- * Class UpgradeLiabilities
- */
-class UpgradeLiabilities extends Command
+class UpgradesLiabilities extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '560_upgrade_liabilities';
protected $description = 'Upgrade liabilities to new 5.6.0 structure.';
- protected $signature = 'firefly-iii:upgrade-liabilities {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:560-liabilities {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/UpgradeLiabilitiesEight.php b/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php
similarity index 85%
rename from app/Console/Commands/Upgrade/UpgradeLiabilitiesEight.php
rename to app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php
index 1422e77363..a28fb86324 100644
--- a/app/Console/Commands/Upgrade/UpgradeLiabilitiesEight.php
+++ b/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php
@@ -35,16 +35,13 @@ use FireflyIII\Services\Internal\Support\CreditRecalculateService;
use FireflyIII\User;
use Illuminate\Console\Command;
-/**
- * Class UpgradeLiabilitiesEight
- */
-class UpgradeLiabilitiesEight extends Command
+class UpgradesLiabilitiesEight extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '600_upgrade_liabilities';
protected $description = 'Upgrade liabilities to new 6.0.0 structure.';
- protected $signature = 'firefly-iii:liabilities-600 {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:600-liabilities {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
@@ -201,32 +198,9 @@ class UpgradeLiabilitiesEight extends Command
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
- // $delete = false;
- // /** @var Transaction $source */
- // $source = $journal->transactions()->where('amount', '<', 0)->first();
- // /** @var Transaction $dest */
- // $dest = $journal->transactions()->where('amount', '>', 0)->first();
-
- /**
- * // if source is this liability and destination is expense, remove transaction.
- * // if source is revenue and destination is liability, remove transaction.
- * if ($source->account_id === $account->id && $dest->account->accountType->type === AccountType::EXPENSE) {
- * $delete = true;
- * }
- * if ($dest->account_id === $account->id && $source->account->accountType->type === AccountType::REVENUE) {
- * $delete = true;
- * }
- *
- * // overruled. No transaction will be deleted, ever.
- * // code is kept in place, so I can revisit my reasoning.
- * $delete = false;
- */
-
- // if ($delete) {
$service = app(TransactionGroupDestroyService::class);
$service->destroy($journal->transactionGroup);
++$count;
- // }
}
return $count;
diff --git a/app/Console/Commands/Upgrade/UpgradeMultiPiggyBanks.php b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php
similarity index 93%
rename from app/Console/Commands/Upgrade/UpgradeMultiPiggyBanks.php
rename to app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php
index 6914bc0919..9284ca913a 100644
--- a/app/Console/Commands/Upgrade/UpgradeMultiPiggyBanks.php
+++ b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php
@@ -30,15 +30,15 @@ use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
-class UpgradeMultiPiggyBanks extends Command
+class UpgradesMultiPiggyBanks extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '620_make_multi_piggies';
- protected $description = 'Upgrade piggybanks so they can use multiple accounts.';
+ protected $description = 'Upgrade piggy banks so they can use multiple accounts.';
- protected $signature = 'firefly-iii:upgrade-multi-piggies {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:620-piggy-banks {--F|force : Force the execution of this command.}';
private AccountRepositoryInterface $accountRepository;
private PiggyBankRepositoryInterface $repository;
diff --git a/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php
similarity index 95%
rename from app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php
rename to app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php
index 5b79a96f3c..e2e04cf3cd 100644
--- a/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php
+++ b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php
@@ -33,7 +33,7 @@ use Illuminate\Console\Command;
/**
* Class MigrateRecurrenceMeta
*/
-class MigrateRecurrenceMeta extends Command
+class UpgradesRecurrenceMetaData extends Command
{
use ShowsFriendlyMessages;
@@ -41,7 +41,7 @@ class MigrateRecurrenceMeta extends Command
protected $description = 'Migrate recurrence meta data';
- protected $signature = 'firefly-iii:migrate-recurrence-meta {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:481-recurrence-meta {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/MigrateRecurrenceType.php b/app/Console/Commands/Upgrade/UpgradesRecurrenceType.php
similarity index 91%
rename from app/Console/Commands/Upgrade/MigrateRecurrenceType.php
rename to app/Console/Commands/Upgrade/UpgradesRecurrenceType.php
index d8cf398141..802e303f94 100644
--- a/app/Console/Commands/Upgrade/MigrateRecurrenceType.php
+++ b/app/Console/Commands/Upgrade/UpgradesRecurrenceType.php
@@ -30,7 +30,7 @@ use Illuminate\Console\Command;
/**
* Class MigrateRecurrenceType
*/
-class MigrateRecurrenceType extends Command
+class UpgradesRecurrenceType extends Command
{
use ShowsFriendlyMessages;
@@ -38,7 +38,7 @@ class MigrateRecurrenceType extends Command
protected $description = 'Migrate transaction type of recurring transaction.';
- protected $signature = 'firefly-iii:migrate-recurrence-type {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:550-recurrence-type {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/MigrateRuleActions.php b/app/Console/Commands/Upgrade/UpgradesRuleActions.php
similarity index 97%
rename from app/Console/Commands/Upgrade/MigrateRuleActions.php
rename to app/Console/Commands/Upgrade/UpgradesRuleActions.php
index f0c825b40f..c6341238ae 100644
--- a/app/Console/Commands/Upgrade/MigrateRuleActions.php
+++ b/app/Console/Commands/Upgrade/UpgradesRuleActions.php
@@ -27,7 +27,7 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages;
use FireflyIII\Models\RuleAction;
use Illuminate\Console\Command;
-class MigrateRuleActions extends Command
+class UpgradesRuleActions extends Command
{
use ShowsFriendlyMessages;
@@ -35,7 +35,7 @@ class MigrateRuleActions extends Command
protected $description = 'Migrate rule actions away from expression engine';
- protected $signature = 'firefly-iii:migrate-rule-actions {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:600-rule-actions {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/MigrateTagLocations.php b/app/Console/Commands/Upgrade/UpgradesTagLocations.php
similarity index 94%
rename from app/Console/Commands/Upgrade/MigrateTagLocations.php
rename to app/Console/Commands/Upgrade/UpgradesTagLocations.php
index 7284622067..d0a297c20c 100644
--- a/app/Console/Commands/Upgrade/MigrateTagLocations.php
+++ b/app/Console/Commands/Upgrade/UpgradesTagLocations.php
@@ -32,7 +32,7 @@ use Illuminate\Console\Command;
/**
* Class MigrateTagLocations
*/
-class MigrateTagLocations extends Command
+class UpgradesTagLocations extends Command
{
use ShowsFriendlyMessages;
@@ -40,7 +40,7 @@ class MigrateTagLocations extends Command
protected $description = 'Migrate tag locations.';
- protected $signature = 'firefly-iii:migrate-tag-locations {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:500-tag-locations {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
diff --git a/app/Console/Commands/Upgrade/MigrateToGroups.php b/app/Console/Commands/Upgrade/UpgradesToGroups.php
similarity index 98%
rename from app/Console/Commands/Upgrade/MigrateToGroups.php
rename to app/Console/Commands/Upgrade/UpgradesToGroups.php
index c9b475217a..c0c7cf3e10 100644
--- a/app/Console/Commands/Upgrade/MigrateToGroups.php
+++ b/app/Console/Commands/Upgrade/UpgradesToGroups.php
@@ -36,20 +36,13 @@ use FireflyIII\Services\Internal\Destroy\JournalDestroyService;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
-/**
- * This command will take split transactions and migrate them to "transaction groups".
- *
- * It will only run once, but can be forced to run again.
- *
- * Class MigrateToGroups
- */
-class MigrateToGroups extends Command
+class UpgradesToGroups extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_migrated_to_groups';
protected $description = 'Migrates a pre-4.7.8 transaction structure to the 4.7.8+ transaction structure.';
- protected $signature = 'firefly-iii:migrate-to-groups {--F|force : Force the migration, even if it fired before.}';
+ protected $signature = 'upgrade:480-migrate-to-groups {--F|force : Force the migration, even if it fired before.}';
private JournalCLIRepositoryInterface $cliRepository;
private int $count;
private TransactionGroupFactory $groupFactory;
diff --git a/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php
similarity index 97%
rename from app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php
rename to app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php
index 0f4a601054..4e7398915f 100644
--- a/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php
+++ b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php
@@ -36,16 +36,14 @@ use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use Illuminate\Console\Command;
-/**
- * Class OtherCurrenciesCorrections
- */
-class OtherCurrenciesCorrections extends Command
+
+class UpgradesVariousCurrencyInformation extends Command
{
use ShowsFriendlyMessages;
public const string CONFIG_NAME = '480_other_currencies';
protected $description = 'Update all journal currency information.';
- protected $signature = 'firefly-iii:other-currencies {--F|force : Force the execution of this command.}';
+ protected $signature = 'upgrade:480-currency-information {--F|force : Force the execution of this command.}';
private array $accountCurrencies;
private AccountRepositoryInterface $accountRepos;
private JournalCLIRepositoryInterface $cliRepos;
diff --git a/app/Support/Authentication/RemoteUserProvider.php b/app/Support/Authentication/RemoteUserProvider.php
index a218dd5bfe..548b6bab15 100644
--- a/app/Support/Authentication/RemoteUserProvider.php
+++ b/app/Support/Authentication/RemoteUserProvider.php
@@ -24,7 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Authentication;
-use FireflyIII\Console\Commands\Integrity\CreateGroupMemberships;
+use FireflyIII\Console\Commands\Correction\CreateGroupMemberships;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Role;
use FireflyIII\User;
diff --git a/resources/lang/en_US/firefly.php b/resources/lang/en_US/firefly.php
index 313229c2d8..403811e6eb 100644
--- a/resources/lang/en_US/firefly.php
+++ b/resources/lang/en_US/firefly.php
@@ -1766,6 +1766,7 @@ return [
'updated_currency' => 'Currency :name updated',
'ask_site_owner' => 'Please ask :owner to add, remove or edit currencies.',
'currencies_intro' => 'Firefly III supports various currencies which you can set and enable here.',
+ 'currencies_switch_default' => 'If you have a large database, switching from one default currency to another may take a moment.',
'make_default_currency' => 'Make default',
'default_currency' => 'default',
'currency_is_disabled' => 'Disabled',
diff --git a/resources/views/currencies/index.twig b/resources/views/currencies/index.twig
index 93b30071d9..9da52a312b 100644
--- a/resources/views/currencies/index.twig
+++ b/resources/views/currencies/index.twig
@@ -13,11 +13,10 @@
{{ 'create_currency'|_ }}
-
+
{{ 'currencies_intro'|_ }}
-
-
{{ 'currencies_default_disabled'|_ }}
+ {{ 'currencies_switch_default'|_ }}
{% if currencies|length > 0 %}
@@ -125,7 +128,13 @@
data-id="{{ budget.id }}">{{ trans('firefly.available_between', {start: budget.start_date.isoFormat(monthAndDayFormat), end: budget.end_date.isoFormat(monthAndDayFormat) }) }}
:
{{ formatAmountBySymbol(budget.amount, budget.transaction_currency.symbol, budget.transaction_currency.decimal_places, true) }}
+ data-value="{{ budget.amount }}">
+ {{ formatAmountBySymbol(budget.amount, budget.transaction_currency.symbol, budget.transaction_currency.decimal_places, true) }}
+ {% if(convertToNative and 0 != budget.native_amount) %}
+ ({{ formatAmountBySymbol(budget.native_amount, defaultCurrency.symbol, defaultCurrency.decimal_places, true) }})
+ {% endif %}
+
+
diff --git a/resources/views/budgets/show.twig b/resources/views/budgets/show.twig
index ca1dbd4995..d0ec49a61f 100644
--- a/resources/views/budgets/show.twig
+++ b/resources/views/budgets/show.twig
@@ -158,12 +158,19 @@
{{ 'amount'|_ }} |
{{ formatAmountBySymbol(limit.amount, limit.transactionCurrency.symbol, limit.transactionCurrency.decimal_places) }}
+ {% if convertToNative and 0 != limit.native_amount %}
+ ({{ formatAmountBySymbol(limit.native_amount, defaultCurrency.symbol, defaultCurrency.decimal_places) }})
+ {% endif %}
|
{{ 'spent'|_ }} |
- {{ formatAmountBySymbol(limit.spent, limit.transactionCurrency.symbol, limit.transactionCurrency.decimal_places) }}
+ {% if convertToNative %}
+ {{ formatAmountBySymbol(limit.spent, defaultCurrency.symbol, defaultCurrency.decimal_places) }}
+ {% else %}
+ {{ formatAmountBySymbol(limit.spent, limit.transactionCurrency.symbol, limit.transactionCurrency.decimal_places) }}
+ {% endif %}
|
{% if limit.spent > 0 %}
From 68b446db1841f82e135dc11de13aae160c8e20b6 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Fri, 27 Dec 2024 19:46:40 +0100
Subject: [PATCH 121/122] Final changes.
---
.../Controllers/Chart/CategoryController.php | 80 +++++-----
app/Http/Controllers/DebugController.php | 4 +
.../Category/OperationsRepository.php | 151 +++++++++++-------
.../Category/WholePeriodChartGenerator.php | 5 +-
4 files changed, 142 insertions(+), 98 deletions(-)
diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php
index 3a2e51a999..91bd8b24e3 100644
--- a/app/Http/Controllers/Chart/CategoryController.php
+++ b/app/Http/Controllers/Chart/CategoryController.php
@@ -70,24 +70,27 @@ class CategoryController extends Controller
public function all(Category $category): JsonResponse
{
// cache results:
- $cache = new CacheProperties();
+ $cache = new CacheProperties();
$cache->addProperty('chart.category.all');
$cache->addProperty($category->id);
+ $cache->addProperty($this->convertToNative);
if ($cache->has()) {
- return response()->json($cache->get());
+ // return response()->json($cache->get());
}
/** @var CategoryRepositoryInterface $repository */
- $repository = app(CategoryRepositoryInterface::class);
- $start = $repository->firstUseDate($category) ?? $this->getDate();
- $range = app('navigation')->getViewRange(false);
- $start = app('navigation')->startOfPeriod($start, $range);
- $end = $this->getDate();
+ $repository = app(CategoryRepositoryInterface::class);
+ $start = $repository->firstUseDate($category) ?? $this->getDate();
+ $range = app('navigation')->getViewRange(false);
+ $start = app('navigation')->startOfPeriod($start, $range);
+ $end = $this->getDate();
/** @var WholePeriodChartGenerator $chartGenerator */
- $chartGenerator = app(WholePeriodChartGenerator::class);
- $chartData = $chartGenerator->generate($category, $start, $end);
- $data = $this->generator->multiSet($chartData);
+ $chartGenerator = app(WholePeriodChartGenerator::class);
+ $chartGenerator->convertToNative = $this->convertToNative;
+
+ $chartData = $chartGenerator->generate($category, $start, $end);
+ $data = $this->generator->multiSet($chartData);
$cache->store($data);
return response()->json($data);
@@ -104,10 +107,10 @@ class CategoryController extends Controller
*/
public function frontPage(): JsonResponse
{
- $start = session('start', today(config('app.timezone'))->startOfMonth());
- $end = session('end', today(config('app.timezone'))->endOfMonth());
+ $start = session('start', today(config('app.timezone'))->startOfMonth());
+ $end = session('end', today(config('app.timezone'))->endOfMonth());
// chart properties for cache:
- $cache = new CacheProperties();
+ $cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($this->convertToNative);
@@ -136,10 +139,11 @@ class CategoryController extends Controller
$cache->addProperty('chart.category.period');
$cache->addProperty($accounts->pluck('id')->toArray());
$cache->addProperty($category);
+ $cache->addProperty($this->convertToNative);
if ($cache->has()) {
- return response()->json($cache->get());
+ // return response()->json($cache->get());
}
- $data = $this->reportPeriodChart($accounts, $start, $end, $category);
+ $data = $this->reportPeriodChart($accounts, $start, $end, $category);
$cache->store($data);
@@ -160,8 +164,8 @@ class CategoryController extends Controller
$noCatRepository = app(NoCategoryRepositoryInterface::class);
// this gives us all currencies
- $expenses = $noCatRepository->listExpenses($start, $end, $accounts);
- $income = $noCatRepository->listIncome($start, $end, $accounts);
+ $expenses = $noCatRepository->listExpenses($start, $end, $accounts);
+ $income = $noCatRepository->listIncome($start, $end, $accounts);
}
if (null !== $category) {
@@ -169,9 +173,9 @@ class CategoryController extends Controller
$opsRepository = app(OperationsRepositoryInterface::class);
$categoryId = $category->id;
// this gives us all currencies
- $collection = new Collection([$category]);
- $expenses = $opsRepository->listExpenses($start, $end, $accounts, $collection);
- $income = $opsRepository->listIncome($start, $end, $accounts, $collection);
+ $collection = new Collection([$category]);
+ $expenses = $opsRepository->listExpenses($start, $end, $accounts, $collection);
+ $income = $opsRepository->listIncome($start, $end, $accounts, $collection);
}
$currencies = array_unique(array_merge(array_keys($income), array_keys($expenses)));
$periods = app('navigation')->listOfPeriods($start, $end);
@@ -185,19 +189,19 @@ class CategoryController extends Controller
$inKey = sprintf('%d-in', $currencyId);
$chartData[$outKey]
= [
- 'label' => sprintf('%s (%s)', (string) trans('firefly.spent'), $currencyInfo['currency_name']),
- 'entries' => [],
- 'type' => 'bar',
- 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
- ];
+ 'label' => sprintf('%s (%s)', (string) trans('firefly.spent'), $currencyInfo['currency_name']),
+ 'entries' => [],
+ 'type' => 'bar',
+ 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
+ ];
$chartData[$inKey]
- = [
- 'label' => sprintf('%s (%s)', (string) trans('firefly.earned'), $currencyInfo['currency_name']),
- 'entries' => [],
- 'type' => 'bar',
- 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
- ];
+ = [
+ 'label' => sprintf('%s (%s)', (string) trans('firefly.earned'), $currencyInfo['currency_name']),
+ 'entries' => [],
+ 'type' => 'bar',
+ 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
+ ];
// loop empty periods:
foreach (array_keys($periods) as $period) {
$label = $periods[$period];
@@ -205,7 +209,7 @@ class CategoryController extends Controller
$chartData[$inKey]['entries'][$label] = '0';
}
// loop income and expenses for this category.:
- $outSet = $expenses[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
+ $outSet = $expenses[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
foreach ($outSet['transaction_journals'] as $journal) {
$amount = app('steam')->positive($journal['amount']);
$date = $journal['date']->isoFormat($format);
@@ -214,7 +218,7 @@ class CategoryController extends Controller
$chartData[$outKey]['entries'][$date] = bcadd($amount, $chartData[$outKey]['entries'][$date]);
}
- $inSet = $income[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
+ $inSet = $income[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
foreach ($inSet['transaction_journals'] as $journal) {
$amount = app('steam')->positive($journal['amount']);
$date = $journal['date']->isoFormat($format);
@@ -240,7 +244,7 @@ class CategoryController extends Controller
if ($cache->has()) {
return response()->json($cache->get());
}
- $data = $this->reportPeriodChart($accounts, $start, $end, null);
+ $data = $this->reportPeriodChart($accounts, $start, $end, null);
$cache->store($data);
@@ -255,14 +259,14 @@ class CategoryController extends Controller
*/
public function specificPeriod(Category $category, Carbon $date): JsonResponse
{
- $range = app('navigation')->getViewRange(false);
- $start = app('navigation')->startOfPeriod($date, $range);
- $end = session()->get('end');
+ $range = app('navigation')->getViewRange(false);
+ $start = app('navigation')->startOfPeriod($date, $range);
+ $end = session()->get('end');
if ($end < $start) {
[$end, $start] = [$start, $end];
}
- $cache = new CacheProperties();
+ $cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($category->id);
diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php
index e08bbe706f..510a4ca910 100644
--- a/app/Http/Controllers/DebugController.php
+++ b/app/Http/Controllers/DebugController.php
@@ -76,6 +76,10 @@ class DebugController extends Controller
|| 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;
diff --git a/app/Repositories/Category/OperationsRepository.php b/app/Repositories/Category/OperationsRepository.php
index 5f62bf2433..6741f3ffa8 100644
--- a/app/Repositories/Category/OperationsRepository.php
+++ b/app/Repositories/Category/OperationsRepository.php
@@ -63,13 +63,13 @@ class OperationsRepository implements OperationsRepositoryInterface
$collector->setCategories($this->getCategories());
}
$collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation();
- $journals = $collector->getExtractedJournals();
- $array = [];
+ $journals = $collector->getExtractedJournals();
+ $array = [];
foreach ($journals as $journal) {
- $currencyId = (int) $journal['currency_id'];
- $categoryId = (int) $journal['category_id'];
- $categoryName = (string) $journal['category_name'];
+ $currencyId = (int) $journal['currency_id'];
+ $categoryId = (int) $journal['category_id'];
+ $categoryName = (string) $journal['category_name'];
// catch "no category" entries.
if (0 === $categoryId) {
@@ -77,7 +77,7 @@ class OperationsRepository implements OperationsRepositoryInterface
}
// info about the currency:
- $array[$currencyId] ??= [
+ $array[$currencyId] ??= [
'categories' => [],
'currency_id' => (string) $currencyId,
'currency_name' => $journal['currency_name'],
@@ -112,7 +112,7 @@ class OperationsRepository implements OperationsRepositoryInterface
return $array;
}
- public function setUser(null|Authenticatable|User $user): void
+ public function setUser(null | Authenticatable | User $user): void
{
if ($user instanceof User) {
$this->user = $user;
@@ -147,13 +147,13 @@ class OperationsRepository implements OperationsRepositoryInterface
$collector->setCategories($this->getCategories());
}
$collector->withCategoryInformation()->withAccountInformation();
- $journals = $collector->getExtractedJournals();
- $array = [];
+ $journals = $collector->getExtractedJournals();
+ $array = [];
foreach ($journals as $journal) {
- $currencyId = (int) $journal['currency_id'];
- $categoryId = (int) $journal['category_id'];
- $categoryName = (string) $journal['category_name'];
+ $currencyId = (int) $journal['currency_id'];
+ $categoryId = (int) $journal['category_id'];
+ $categoryName = (string) $journal['category_name'];
// catch "no category" entries.
if (0 === $categoryId) {
@@ -161,7 +161,7 @@ class OperationsRepository implements OperationsRepositoryInterface
}
// info about the currency:
- $array[$currencyId] ??= [
+ $array[$currencyId] ??= [
'categories' => [],
'currency_id' => (string) $currencyId,
'currency_name' => $journal['currency_name'],
@@ -200,8 +200,7 @@ class OperationsRepository implements OperationsRepositoryInterface
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::TRANSFER])
- ->setDestinationAccounts($accounts)->excludeSourceAccounts($accounts)
- ;
+ ->setDestinationAccounts($accounts)->excludeSourceAccounts($accounts);
if (null !== $categories && $categories->count() > 0) {
$collector->setCategories($categories);
}
@@ -209,13 +208,13 @@ class OperationsRepository implements OperationsRepositoryInterface
$collector->setCategories($this->getCategories());
}
$collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation();
- $journals = $collector->getExtractedJournals();
- $array = [];
+ $journals = $collector->getExtractedJournals();
+ $array = [];
foreach ($journals as $journal) {
- $currencyId = (int) $journal['currency_id'];
- $categoryId = (int) $journal['category_id'];
- $categoryName = (string) $journal['category_name'];
+ $currencyId = (int) $journal['currency_id'];
+ $categoryId = (int) $journal['category_id'];
+ $categoryName = (string) $journal['category_name'];
// catch "no category" entries.
if (0 === $categoryId) {
@@ -223,7 +222,7 @@ class OperationsRepository implements OperationsRepositoryInterface
}
// info about the currency:
- $array[$currencyId] ??= [
+ $array[$currencyId] ??= [
'categories' => [],
'currency_id' => (string) $currencyId,
'currency_name' => $journal['currency_name'],
@@ -263,8 +262,7 @@ class OperationsRepository implements OperationsRepositoryInterface
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::TRANSFER])
- ->setSourceAccounts($accounts)->excludeDestinationAccounts($accounts)
- ;
+ ->setSourceAccounts($accounts)->excludeDestinationAccounts($accounts);
if (null !== $categories && $categories->count() > 0) {
$collector->setCategories($categories);
}
@@ -272,13 +270,13 @@ class OperationsRepository implements OperationsRepositoryInterface
$collector->setCategories($this->getCategories());
}
$collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation();
- $journals = $collector->getExtractedJournals();
- $array = [];
+ $journals = $collector->getExtractedJournals();
+ $array = [];
foreach ($journals as $journal) {
- $currencyId = (int) $journal['currency_id'];
- $categoryId = (int) $journal['category_id'];
- $categoryName = (string) $journal['category_name'];
+ $currencyId = (int) $journal['currency_id'];
+ $categoryId = (int) $journal['category_id'];
+ $categoryName = (string) $journal['category_name'];
// catch "no category" entries.
if (0 === $categoryId) {
@@ -286,7 +284,7 @@ class OperationsRepository implements OperationsRepositoryInterface
}
// info about the currency:
- $array[$currencyId] ??= [
+ $array[$currencyId] ??= [
'categories' => [],
'currency_id' => (string) $currencyId,
'currency_name' => $journal['currency_name'],
@@ -327,7 +325,7 @@ class OperationsRepository implements OperationsRepositoryInterface
public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
{
/** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
+ $collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
// default currency information for native stuff.
@@ -341,29 +339,35 @@ class OperationsRepository implements OperationsRepositoryInterface
}
$collector->setCategories($categories);
$collector->withCategoryInformation();
- $journals = $collector->getExtractedJournals();
- $array = [];
+ $journals = $collector->getExtractedJournals();
+ $array = [];
Log::debug(sprintf('Collected %d journals', count($journals)));
foreach ($journals as $journal) {
// Almost the same as in \FireflyIII\Repositories\Budget\OperationsRepository::sumExpenses
- $amount = '0';
- $currencyId = (int) $journal['currency_id'];
- $currencyName = $journal['currency_name'];
- $currencySymbol = $journal['currency_symbol'];
- $currencyCode = $journal['currency_code'];
- $currencyDecimalPlaces = $journal['currency_decimal_places'];
+ $amount = '0';
+ $currencyId = (int) $journal['currency_id'];
+ $currencyName = $journal['currency_name'];
+ $currencySymbol = $journal['currency_symbol'];
+ $currencyCode = $journal['currency_code'];
+ $currencyDecimalPlaces = $journal['currency_decimal_places'];
if ($convertToNative) {
- $useNative = $default->id !== (int) $journal['currency_id'];
- $amount = Amount::getAmountFromJournal($journal);
- if ($useNative) {
+ $amount = Amount::getAmountFromJournal($journal);
+ if ($default->id !== (int) $journal['currency_id'] && $default->id !== (int) $journal['foreign_currency_id']) {
$currencyId = $default->id;
$currencyName = $default->name;
$currencySymbol = $default->symbol;
$currencyCode = $default->code;
$currencyDecimalPlaces = $default->decimal_places;
}
+ if ($default->id !== (int) $journal['currency_id'] && $default->id === (int) $journal['foreign_currency_id']) {
+ $currencyId = $journal['foreign_currency_id'];
+ $currencyName = $journal['foreign_currency_name'];
+ $currencySymbol = $journal['foreign_currency_symbol'];
+ $currencyCode = $journal['foreign_currency_code'];
+ $currencyDecimalPlaces = $journal['foreign_currency_decimal_places'];
+ }
Log::debug(sprintf('[a] Add amount %s %s', $currencyCode, $amount));
}
if (!$convertToNative) {
@@ -372,8 +376,7 @@ class OperationsRepository implements OperationsRepositoryInterface
$amount = $journal['amount'];
}
-
- $array[$currencyId] ??= [
+ $array[$currencyId] ??= [
'sum' => '0',
'currency_id' => (string) $currencyId,
'currency_name' => $currencyName,
@@ -395,8 +398,7 @@ class OperationsRepository implements OperationsRepositoryInterface
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)
- ->setTypes([TransactionType::DEPOSIT])
- ;
+ ->setTypes([TransactionTypeEnum::DEPOSIT->value]);
if (null !== $accounts && $accounts->count() > 0) {
$collector->setAccounts($accounts);
@@ -405,20 +407,52 @@ class OperationsRepository implements OperationsRepositoryInterface
$categories = $this->getCategories();
}
$collector->setCategories($categories);
- $journals = $collector->getExtractedJournals();
- $array = [];
+ $journals = $collector->getExtractedJournals();
+ $convertToNative = app('preferences')->get('convert_to_native', false)->data;
+ $default = app('amount')->getDefaultCurrency();
+ $array = [];
foreach ($journals as $journal) {
- $currencyId = (int) $journal['currency_id'];
- $array[$currencyId] ??= [
+ // Almost the same as in \FireflyIII\Repositories\Budget\OperationsRepository::sumExpenses
+ $amount = '0';
+ $currencyId = (int) $journal['currency_id'];
+ $currencyName = $journal['currency_name'];
+ $currencySymbol = $journal['currency_symbol'];
+ $currencyCode = $journal['currency_code'];
+ $currencyDecimalPlaces = $journal['currency_decimal_places'];
+ if ($convertToNative) {
+ $amount = Amount::getAmountFromJournal($journal);
+ if ($default->id !== (int) $journal['currency_id'] && $default->id !== (int) $journal['foreign_currency_id']) {
+ $currencyId = $default->id;
+ $currencyName = $default->name;
+ $currencySymbol = $default->symbol;
+ $currencyCode = $default->code;
+ $currencyDecimalPlaces = $default->decimal_places;
+ }
+ if ($default->id !== (int) $journal['currency_id'] && $default->id === (int) $journal['foreign_currency_id']) {
+ $currencyId = $journal['foreign_currency_id'];
+ $currencyName = $journal['foreign_currency_name'];
+ $currencySymbol = $journal['foreign_currency_symbol'];
+ $currencyCode = $journal['foreign_currency_code'];
+ $currencyDecimalPlaces = $journal['foreign_currency_decimal_places'];
+ }
+ Log::debug(sprintf('[a] Add amount %s %s', $currencyCode, $amount));
+ }
+ if (!$convertToNative) {
+ // ignore the amount in foreign currency.
+ Log::debug(sprintf('[b] Add amount %s %s', $currencyCode, $journal['amount']));
+ $amount = $journal['amount'];
+ }
+
+ $array[$currencyId] ??= [
'sum' => '0',
'currency_id' => (string) $currencyId,
- 'currency_name' => $journal['currency_name'],
- 'currency_symbol' => $journal['currency_symbol'],
- 'currency_code' => $journal['currency_code'],
- 'currency_decimal_places' => $journal['currency_decimal_places'],
+ 'currency_name' => $currencyName,
+ 'currency_symbol' => $currencySymbol,
+ 'currency_code' => $currencyCode,
+ 'currency_decimal_places' => $currencyDecimalPlaces,
];
- $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->positive($journal['amount']));
+ $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->positive($amount));
}
return $array;
@@ -432,8 +466,7 @@ class OperationsRepository implements OperationsRepositoryInterface
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user)->setRange($start, $end)
- ->setTypes([TransactionType::TRANSFER])
- ;
+ ->setTypes([TransactionType::TRANSFER]);
if (null !== $accounts && $accounts->count() > 0) {
$collector->setAccounts($accounts);
@@ -442,12 +475,12 @@ class OperationsRepository implements OperationsRepositoryInterface
$categories = $this->getCategories();
}
$collector->setCategories($categories);
- $journals = $collector->getExtractedJournals();
- $array = [];
+ $journals = $collector->getExtractedJournals();
+ $array = [];
foreach ($journals as $journal) {
$currencyId = (int) $journal['currency_id'];
- $array[$currencyId] ??= [
+ $array[$currencyId] ??= [
'sum' => '0',
'currency_id' => (string) $currencyId,
'currency_name' => $journal['currency_name'],
diff --git a/app/Support/Chart/Category/WholePeriodChartGenerator.php b/app/Support/Chart/Category/WholePeriodChartGenerator.php
index 1a562aa370..2b2e39b182 100644
--- a/app/Support/Chart/Category/WholePeriodChartGenerator.php
+++ b/app/Support/Chart/Category/WholePeriodChartGenerator.php
@@ -25,6 +25,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Chart\Category;
use Carbon\Carbon;
+use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Category;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
@@ -36,6 +37,8 @@ use Illuminate\Support\Collection;
*/
class WholePeriodChartGenerator
{
+ public bool $convertToNative;
+
public function generate(Category $category, Carbon $start, Carbon $end): array
{
$collection = new Collection([$category]);
@@ -46,7 +49,7 @@ class WholePeriodChartGenerator
/** @var AccountRepositoryInterface $accountRepository */
$accountRepository = app(AccountRepositoryInterface::class);
- $types = [AccountType::DEFAULT, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE];
+ $types = [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
$accounts = $accountRepository->getAccountsByType($types);
$step = $this->calculateStep($start, $end);
$chartData = [];
From f191086adb366cea64ebad7b372410e0edf6a4c2 Mon Sep 17 00:00:00 2001
From: James Cole
Date: Fri, 27 Dec 2024 19:47:35 +0100
Subject: [PATCH 122/122] Enable cache again.
---
app/Helpers/Report/NetWorth.php | 2 +-
app/Http/Controllers/Chart/AccountController.php | 2 +-
app/Http/Controllers/Chart/BillController.php | 2 +-
app/Http/Controllers/Chart/BudgetController.php | 6 +++---
app/Http/Controllers/Chart/CategoryController.php | 6 +++---
app/Http/Controllers/Chart/ReportController.php | 2 +-
app/Support/Http/Controllers/AugumentData.php | 2 +-
app/Support/Http/Controllers/ChartGeneration.php | 2 +-
app/Support/Http/Controllers/PeriodOverview.php | 2 +-
app/Support/Steam.php | 2 +-
10 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/app/Helpers/Report/NetWorth.php b/app/Helpers/Report/NetWorth.php
index 2b5c17c944..6fc0c3a0c1 100644
--- a/app/Helpers/Report/NetWorth.php
+++ b/app/Helpers/Report/NetWorth.php
@@ -74,7 +74,7 @@ class NetWorth implements NetWorthInterface
$cache->addProperty('net-worth-by-accounts');
$cache->addProperty($ids);
if ($cache->has()) {
- // return $cache->get();
+ return $cache->get();
}
Log::debug(sprintf('Now in byAccounts("%s", "%s")', $ids, $date->format('Y-m-d H:i:s')));
$default = Amount::getDefaultCurrency();
diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php
index f2a3c6ea23..c3ffe5f1d2 100644
--- a/app/Http/Controllers/Chart/AccountController.php
+++ b/app/Http/Controllers/Chart/AccountController.php
@@ -426,7 +426,7 @@ class AccountController extends Controller
$cache->addProperty($this->convertToNative);
$cache->addProperty($account->id);
if ($cache->has()) {
- // return response()->json($cache->get());
+ return response()->json($cache->get());
}
// collect and filter balances for the entire period.
diff --git a/app/Http/Controllers/Chart/BillController.php b/app/Http/Controllers/Chart/BillController.php
index 529a1170c8..e4cf002336 100644
--- a/app/Http/Controllers/Chart/BillController.php
+++ b/app/Http/Controllers/Chart/BillController.php
@@ -111,7 +111,7 @@ class BillController extends Controller
$cache->addProperty($bill->id);
$cache->addProperty($this->convertToNative);
if ($cache->has()) {
- // return response()->json($cache->get());
+ return response()->json($cache->get());
}
$locale = app('steam')->getLocale();
diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php
index b06bdf2bfb..f830264167 100644
--- a/app/Http/Controllers/Chart/BudgetController.php
+++ b/app/Http/Controllers/Chart/BudgetController.php
@@ -221,7 +221,7 @@ class BudgetController extends Controller
$cache->addProperty($end);
if ($cache->has()) {
- // return response()->json($cache->get());
+ return response()->json($cache->get());
}
$collector->setRange($start, $end);
$collector->setBudget($budget);
@@ -385,7 +385,7 @@ class BudgetController extends Controller
$cache->addProperty($end);
if ($cache->has()) {
- // return response()->json($cache->get());
+ return response()->json($cache->get());
}
$collector->setRange($start, $end);
$collector->setTypes([TransactionType::WITHDRAWAL])->setBudget($budget)->withAccountInformation();
@@ -457,7 +457,7 @@ class BudgetController extends Controller
$cache->addProperty($this->convertToNative);
$cache->addProperty('chart.budget.frontpage');
if ($cache->has()) {
- // return response()->json($cache->get());
+ return response()->json($cache->get());
}
Log::debug('Regenerate frontpage chart from scratch.');
$chartGenerator = app(FrontpageChartGenerator::class);
diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php
index 91bd8b24e3..c48b8cf3ff 100644
--- a/app/Http/Controllers/Chart/CategoryController.php
+++ b/app/Http/Controllers/Chart/CategoryController.php
@@ -75,7 +75,7 @@ class CategoryController extends Controller
$cache->addProperty($category->id);
$cache->addProperty($this->convertToNative);
if ($cache->has()) {
- // return response()->json($cache->get());
+ return response()->json($cache->get());
}
/** @var CategoryRepositoryInterface $repository */
@@ -116,7 +116,7 @@ class CategoryController extends Controller
$cache->addProperty($this->convertToNative);
$cache->addProperty('chart.category.frontpage');
if ($cache->has()) {
- // return response()->json($cache->get());
+ return response()->json($cache->get());
}
$frontpageGenerator = new FrontpageChartGenerator($start, $end);
@@ -141,7 +141,7 @@ class CategoryController extends Controller
$cache->addProperty($category);
$cache->addProperty($this->convertToNative);
if ($cache->has()) {
- // return response()->json($cache->get());
+ return response()->json($cache->get());
}
$data = $this->reportPeriodChart($accounts, $start, $end, $category);
diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php
index 7c5db3052e..d538ebbd97 100644
--- a/app/Http/Controllers/Chart/ReportController.php
+++ b/app/Http/Controllers/Chart/ReportController.php
@@ -145,7 +145,7 @@ class ReportController extends Controller
$cache->addProperty($accounts);
$cache->addProperty($end);
if ($cache->has()) {
- // return response()->json($cache->get());
+ return response()->json($cache->get());
}
Log::debug('Going to do operations for accounts ', $accounts->pluck('id')->toArray());
diff --git a/app/Support/Http/Controllers/AugumentData.php b/app/Support/Http/Controllers/AugumentData.php
index 574cad84c5..e3c39ea4b2 100644
--- a/app/Support/Http/Controllers/AugumentData.php
+++ b/app/Support/Http/Controllers/AugumentData.php
@@ -183,7 +183,7 @@ trait AugumentData
$cache->addProperty('get-limits');
if ($cache->has()) {
- // return $cache->get();
+ return $cache->get();
}
$set = $blRepository->getBudgetLimits($budget, $start, $end);
diff --git a/app/Support/Http/Controllers/ChartGeneration.php b/app/Support/Http/Controllers/ChartGeneration.php
index e66a202364..3fea9eada1 100644
--- a/app/Support/Http/Controllers/ChartGeneration.php
+++ b/app/Support/Http/Controllers/ChartGeneration.php
@@ -54,7 +54,7 @@ trait ChartGeneration
$cache->addProperty($accounts);
$cache->addProperty($convertToNative);
if ($cache->has()) {
- // return $cache->get();
+ return $cache->get();
}
app('log')->debug('Regenerate chart.account.account-balance-chart from scratch.');
$locale = app('steam')->getLocale();
diff --git a/app/Support/Http/Controllers/PeriodOverview.php b/app/Support/Http/Controllers/PeriodOverview.php
index e1df4293c3..925438b375 100644
--- a/app/Support/Http/Controllers/PeriodOverview.php
+++ b/app/Support/Http/Controllers/PeriodOverview.php
@@ -333,7 +333,7 @@ trait PeriodOverview
$cache->addProperty('no-budget-period-entries');
if ($cache->has()) {
- // return $cache->get();
+ return $cache->get();
}
/** @var array $dates */
diff --git a/app/Support/Steam.php b/app/Support/Steam.php
index 7d5ca78599..0201aefba0 100644
--- a/app/Support/Steam.php
+++ b/app/Support/Steam.php
@@ -84,7 +84,7 @@ class Steam
$cache->addProperty($start);
$cache->addProperty($end);
if ($cache->has()) {
- // return $cache->get();
+ return $cache->get();
}
$balances = [];