Skip to content

Firefly III: a personal finances manager

🤖 Auto commit for release 'develop' on 2026-02-06

JC52de9926db86d
diff --git a/app/Api/V1/Controllers/Chart/BudgetController.php b/app/Api/V1/Controllers/Chart/BudgetController.php
index 07fd41b6b5..7f9670e56b 100644
--- a/app/Api/V1/Controllers/Chart/BudgetController.php
+++ b/app/Api/V1/Controllers/Chart/BudgetController.php
@@ -104,6 +104,48 @@ class BudgetController extends Controller
return response()->json($this->clean($data));
}
+ private function filterLimit(int $currencyId, Collection $limits): ?BudgetLimit
+ {
+ $amount = '0';
+ $limit = null;
+ $converter = new ExchangeRateConverter();
+
+ /** @var BudgetLimit $current */
+ foreach ($limits as $current) {
+ if ($this->convertToPrimary) {
+ if ($current->transaction_currency_id === $this->primaryCurrency->id) {
+ // simply add it.
+ $amount = bcadd($amount, (string) $current->amount);
+ Log::debug(sprintf('Set amount in limit to %s', $amount));
+ }
+ if ($current->transaction_currency_id !== $this->primaryCurrency->id) {
+ // convert and then add it.
+ $converted = $converter->convert($current->transactionCurrency, $this->primaryCurrency, $current->start_date, $current->amount);
+ $amount = bcadd($amount, $converted);
+ Log::debug(sprintf(
+ 'Budgeted in limit #%d: %s %s, converted to %s %s',
+ $current->id,
+ $current->transactionCurrency->code,
+ $current->amount,
+ $this->primaryCurrency->code,
+ $converted
+ ));
+ Log::debug(sprintf('Set amount in limit to %s', $amount));
+ }
+ }
+ if ($current->transaction_currency_id === $currencyId) {
+ $limit = $current;
+ }
+ }
+ if (null !== $limit && $this->convertToPrimary) {
+ // convert and add all amounts.
+ $limit->amount = Steam::positive($amount);
+ Log::debug(sprintf('Final amount in limit with converted amount %s', $limit->amount));
+ }
+
+ return $limit;
+ }
+
/**
* @throws FireflyException
*/
@@ -250,46 +292,4 @@ class BudgetController extends Controller
return $return;
}
-
- private function filterLimit(int $currencyId, Collection $limits): ?BudgetLimit
- {
- $amount = '0';
- $limit = null;
- $converter = new ExchangeRateConverter();
-
- /** @var BudgetLimit $current */
- foreach ($limits as $current) {
- if ($this->convertToPrimary) {
- if ($current->transaction_currency_id === $this->primaryCurrency->id) {
- // simply add it.
- $amount = bcadd($amount, (string) $current->amount);
- Log::debug(sprintf('Set amount in limit to %s', $amount));
- }
- if ($current->transaction_currency_id !== $this->primaryCurrency->id) {
- // convert and then add it.
- $converted = $converter->convert($current->transactionCurrency, $this->primaryCurrency, $current->start_date, $current->amount);
- $amount = bcadd($amount, $converted);
- Log::debug(sprintf(
- 'Budgeted in limit #%d: %s %s, converted to %s %s',
- $current->id,
- $current->transactionCurrency->code,
- $current->amount,
- $this->primaryCurrency->code,
- $converted
- ));
- Log::debug(sprintf('Set amount in limit to %s', $amount));
- }
- }
- if ($current->transaction_currency_id === $currencyId) {
- $limit = $current;
- }
- }
- if (null !== $limit && $this->convertToPrimary) {
- // convert and add all amounts.
- $limit->amount = Steam::positive($amount);
- Log::debug(sprintf('Final amount in limit with converted amount %s', $limit->amount));
- }
-
- return $limit;
- }
}
diff --git a/app/Api/V1/Controllers/Controller.php b/app/Api/V1/Controllers/Controller.php
index eab84c1be8..28fd0308df 100644
--- a/app/Api/V1/Controllers/Controller.php
+++ b/app/Api/V1/Controllers/Controller.php
@@ -98,6 +98,77 @@ abstract class Controller extends BaseController
});
}
+ /**
+ * Method to help build URL's.
+ */
+ final protected function buildParams(): string
+ {
+ $return = '?';
+ $params = [];
+ foreach ($this->parameters as $key => $value) {
+ if ('page' === $key) {
+ continue;
+ }
+ if ($value instanceof Carbon) {
+ $params[$key] = $value->format('Y-m-d');
+
+ continue;
+ }
+ $params[$key] = $value;
+ }
+
+ return $return.http_build_query($params);
+ }
+
+ final protected function getManager(): Manager
+ {
+ // create some objects:
+ $manager = new Manager();
+ $baseUrl = request()->getSchemeAndHttpHost().'/api/v1';
+ $manager->setSerializer(new JsonApiSerializer($baseUrl));
+
+ return $manager;
+ }
+
+ final protected function jsonApiList(string $key, LengthAwarePaginator $paginator, AbstractTransformer $transformer): array
+ {
+ $manager = new Manager();
+ $baseUrl = sprintf('%s/api/v1/', request()->getSchemeAndHttpHost());
+
+ // TODO add stuff to path?
+
+ $manager->setSerializer(new JsonApiSerializer($baseUrl));
+
+ $objects = $paginator->getCollection();
+
+ // the transformer, at this point, needs to collect information that ALL items in the collection
+ // require, like meta-data and stuff like that, and save it for later.
+ // $objects = $transformer->collectMetaData($objects);
+ $paginator->setCollection($objects);
+
+ $resource = new FractalCollection($objects, $transformer, $key);
+ $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
+
+ return $manager->createData($resource)->toArray();
+ }
+
+ /**
+ * Returns a JSON API object and returns it.
+ *
+ * @param array<int, mixed>|Model $object
+ */
+ final protected function jsonApiObject(string $key, array|Model $object, AbstractTransformer $transformer): array
+ {
+ // create some objects:
+ $manager = new Manager();
+ $baseUrl = sprintf('%s/api/v1', request()->getSchemeAndHttpHost());
+ $manager->setSerializer(new JsonApiSerializer($baseUrl));
+
+ $resource = new Item($object, $transformer, $key);
+
+ return $manager->createData($resource)->toArray();
+ }
+
#[Deprecated(message: <<<'TXT'
use Request classes
Method to grab all parameters from the URL
@@ -170,75 +241,4 @@ abstract class Controller extends BaseController
// return $this->getSortParameters($bag);
}
-
- /**
- * Method to help build URL's.
- */
- final protected function buildParams(): string
- {
- $return = '?';
- $params = [];
- foreach ($this->parameters as $key => $value) {
- if ('page' === $key) {
- continue;
- }
- if ($value instanceof Carbon) {
- $params[$key] = $value->format('Y-m-d');
-
- continue;
- }
- $params[$key] = $value;
- }
-
- return $return.http_build_query($params);
- }
-
- final protected function getManager(): Manager
- {
- // create some objects:
- $manager = new Manager();
- $baseUrl = request()->getSchemeAndHttpHost().'/api/v1';
- $manager->setSerializer(new JsonApiSerializer($baseUrl));
-
- return $manager;
- }
-
- final protected function jsonApiList(string $key, LengthAwarePaginator $paginator, AbstractTransformer $transformer): array
- {
- $manager = new Manager();
- $baseUrl = sprintf('%s/api/v1/', request()->getSchemeAndHttpHost());
-
- // TODO add stuff to path?
-
- $manager->setSerializer(new JsonApiSerializer($baseUrl));
-
- $objects = $paginator->getCollection();
-
- // the transformer, at this point, needs to collect information that ALL items in the collection
- // require, like meta-data and stuff like that, and save it for later.
- // $objects = $transformer->collectMetaData($objects);
- $paginator->setCollection($objects);
-
- $resource = new FractalCollection($objects, $transformer, $key);
- $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
-
- return $manager->createData($resource)->toArray();
- }
-
- /**
- * Returns a JSON API object and returns it.
- *
- * @param array<int, mixed>|Model $object
- */
- final protected function jsonApiObject(string $key, array|Model $object, AbstractTransformer $transformer): array
- {
- // create some objects:
- $manager = new Manager();
- $baseUrl = sprintf('%s/api/v1', request()->getSchemeAndHttpHost());
- $manager->setSerializer(new JsonApiSerializer($baseUrl));
-
- $resource = new Item($object, $transformer, $key);
-
- return $manager->createData($resource)->toArray();
- }
}
diff --git a/app/Api/V1/Controllers/Data/DestroyController.php b/app/Api/V1/Controllers/Data/DestroyController.php
index ab519becbe..3426201b4a 100644
--- a/app/Api/V1/Controllers/Data/DestroyController.php
+++ b/app/Api/V1/Controllers/Data/DestroyController.php
@@ -137,6 +137,41 @@ class DestroyController extends Controller
return response()->json([], 204);
}
+ /**
+ * @param array<int, string> $types
+ */
+ private function destroyAccounts(array $types): void
+ {
+ /** @var AccountRepositoryInterface $repository */
+ $repository = app(AccountRepositoryInterface::class);
+ $collection = $repository->getAccountsByType($types);
+ $service = app(AccountDestroyService::class);
+
+ /** @var Account $account */
+ foreach ($collection as $account) {
+ $count = $account->transactions()->count();
+ if ($this->unused && 0 === $count) {
+ Log::info(sprintf('Deleted unused account #%d "%s"', $account->id, $account->name));
+ Log::channel('audit')->info(sprintf('Deleted unused account #%d "%s"', $account->id, $account->name));
+ $service->destroy($account, null);
+
+ continue;
+ }
+ if (false === $this->unused) {
+ Log::info(sprintf('Deleting account #%d "%s"', $account->id, $account->name));
+ Log::channel('audit')->warning(sprintf('Deleted account #%d "%s"', $account->id, $account->name));
+ $service->destroy($account, null);
+ }
+ }
+ }
+
+ private function destroyBills(): void
+ {
+ /** @var BillRepositoryInterface $repository */
+ $repository = app(BillRepositoryInterface::class);
+ $repository->destroyAll();
+ }
+
private function destroyBudgets(): void
{
/** @var AvailableBudgetRepositoryInterface $abRepository */
@@ -152,24 +187,24 @@ class DestroyController extends Controller
$budgetRepository->destroyAll();
}
- private function destroyBills(): void
+ private function destroyCategories(): void
{
- /** @var BillRepositoryInterface $repository */
- $repository = app(BillRepositoryInterface::class);
- $repository->destroyAll();
+ /** @var CategoryRepositoryInterface $categoryRepos */
+ $categoryRepos = app(CategoryRepositoryInterface::class);
+ $categoryRepos->destroyAll();
}
- private function destroyPiggyBanks(): void
+ private function destroyObjectGroups(): void
{
- /** @var PiggyBankRepositoryInterface $repository */
- $repository = app(PiggyBankRepositoryInterface::class);
- $repository->destroyAll();
+ /** @var ObjectGroupRepositoryInterface $repository */
+ $repository = app(ObjectGroupRepositoryInterface::class);
+ $repository->deleteAll();
}
- private function destroyRules(): void
+ private function destroyPiggyBanks(): void
{
- /** @var RuleGroupRepositoryInterface $repository */
- $repository = app(RuleGroupRepositoryInterface::class);
+ /** @var PiggyBankRepositoryInterface $repository */
+ $repository = app(PiggyBankRepositoryInterface::class);
$repository->destroyAll();
}
@@ -180,11 +215,11 @@ class DestroyController extends Controller
$repository->destroyAll();
}
- private function destroyCategories(): void
+ private function destroyRules(): void
{
- /** @var CategoryRepositoryInterface $categoryRepos */
- $categoryRepos = app(CategoryRepositoryInterface::class);
- $categoryRepos->destroyAll();
+ /** @var RuleGroupRepositoryInterface $repository */
+ $repository = app(RuleGroupRepositoryInterface::class);
+ $repository->destroyAll();
}
private function destroyTags(): void
@@ -194,41 +229,6 @@ class DestroyController extends Controller
$tagRepository->destroyAll();
}
- private function destroyObjectGroups(): void
- {
- /** @var ObjectGroupRepositoryInterface $repository */
- $repository = app(ObjectGroupRepositoryInterface::class);
- $repository->deleteAll();
- }
-
- /**
- * @param array<int, string> $types
- */
- private function destroyAccounts(array $types): void
- {
- /** @var AccountRepositoryInterface $repository */
- $repository = app(AccountRepositoryInterface::class);
- $collection = $repository->getAccountsByType($types);
- $service = app(AccountDestroyService::class);
-
- /** @var Account $account */
- foreach ($collection as $account) {
- $count = $account->transactions()->count();
- if ($this->unused && 0 === $count) {
- Log::info(sprintf('Deleted unused account #%d "%s"', $account->id, $account->name));
- Log::channel('audit')->info(sprintf('Deleted unused account #%d "%s"', $account->id, $account->name));
- $service->destroy($account, null);
-
- continue;
- }
- if (false === $this->unused) {
- Log::info(sprintf('Deleting account #%d "%s"', $account->id, $account->name));
- Log::channel('audit')->warning(sprintf('Deleted account #%d "%s"', $account->id, $account->name));
- $service->destroy($account, null);
- }
- }
- }
-
/**
* @param array<int, string> $types
*/
diff --git a/app/Api/V1/Controllers/Data/Export/ExportController.php b/app/Api/V1/Controllers/Data/Export/ExportController.php
index 295cfff4d8..43e055e976 100644
--- a/app/Api/V1/Controllers/Data/Export/ExportController.php
+++ b/app/Api/V1/Controllers/Data/Export/ExportController.php
@@ -72,33 +72,6 @@ class ExportController extends Controller
return $this->returnExport('accounts');
}
- /**
- * @throws FireflyException
- * @throws DatetimeException
- */
- private function returnExport(string $key): LaravelResponse
- {
- $date = date('Y-m-d-H-i-s');
- $fileName = sprintf('%s-export-%s.csv', $date, $key);
- $data = $this->exporter->export();
-
- /** @var LaravelResponse $response */
- $response = response($data[$key]);
- $response
- ->header('Content-Description', 'File Transfer')
- ->header('Content-Type', 'application/octet-stream')
- ->header('Content-Disposition', 'attachment; filename='.$fileName)
- ->header('Content-Transfer-Encoding', 'binary')
- ->header('Connection', 'Keep-Alive')
- ->header('Expires', '0')
- ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
- ->header('Pragma', 'public')
- ->header('Content-Length', (string) strlen((string) $data[$key]))
- ;
-
- return $response;
- }
-
/**
* @throws DatetimeException
* @throws FireflyException
@@ -204,4 +177,31 @@ class ExportController extends Controller
return $this->returnExport('transactions');
}
+
+ /**
+ * @throws FireflyException
+ * @throws DatetimeException
+ */
+ private function returnExport(string $key): LaravelResponse
+ {
+ $date = date('Y-m-d-H-i-s');
+ $fileName = sprintf('%s-export-%s.csv', $date, $key);
+ $data = $this->exporter->export();
+
+ /** @var LaravelResponse $response */
+ $response = response($data[$key]);
+ $response
+ ->header('Content-Description', 'File Transfer')
+ ->header('Content-Type', 'application/octet-stream')
+ ->header('Content-Disposition', 'attachment; filename='.$fileName)
+ ->header('Content-Transfer-Encoding', 'binary')
+ ->header('Connection', 'Keep-Alive')
+ ->header('Expires', '0')
+ ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
+ ->header('Pragma', 'public')
+ ->header('Content-Length', (string) strlen((string) $data[$key]))
+ ;
+
+ return $response;
+ }
}
diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php
index 116f7f913f..e6f185b633 100644
--- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php
+++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php
@@ -63,13 +63,6 @@ class DestroyController extends Controller
return response()->json([], 204);
}
- public function destroySingleById(CurrencyExchangeRate $exchangeRate): JsonResponse
- {
- $this->repository->deleteRate($exchangeRate);
-
- return response()->json([], 204);
- }
-
public function destroySingleByDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): JsonResponse
{
$exchangeRate = $this->repository->getSpecificRateOnDate($from, $to, $date);
@@ -82,4 +75,11 @@ class DestroyController extends Controller
return response()->json([], 204);
}
+
+ public function destroySingleById(CurrencyExchangeRate $exchangeRate): JsonResponse
+ {
+ $this->repository->deleteRate($exchangeRate);
+
+ return response()->json([], 204);
+ }
}
diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php
index 11cf33a539..157ad52eec 100644
--- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php
+++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php
@@ -75,14 +75,6 @@ class ShowController extends Controller
return response()->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer))->header('Content-Type', self::CONTENT_TYPE);
}
- public function showSingleById(CurrencyExchangeRate $exchangeRate): JsonResponse
- {
- $transformer = new ExchangeRateTransformer();
- $transformer->setParameters($this->parameters);
-
- return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE);
- }
-
public function showSingleByDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): JsonResponse
{
$transformer = new ExchangeRateTransformer();
@@ -95,4 +87,12 @@ class ShowController extends Controller
return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE);
}
+
+ public function showSingleById(CurrencyExchangeRate $exchangeRate): JsonResponse
+ {
+ $transformer = new ExchangeRateTransformer();
+ $transformer->setParameters($this->parameters);
+
+ return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE);
+ }
}
diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php
index 039437e83a..c601e62384 100644
--- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php
+++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php
@@ -61,6 +61,30 @@ class StoreController extends Controller
});
}
+ public function store(StoreRequest $request): JsonResponse
+ {
+ $date = $request->getDate();
+ $rate = $request->getRate();
+ $from = $request->getFromCurrency();
+ $to = $request->getToCurrency();
+
+ // already has rate?
+ $object = $this->repository->getSpecificRateOnDate($from, $to, $date);
+ if ($object instanceof CurrencyExchangeRate) {
+ // just update it, no matter.
+ $rate = $this->repository->updateExchangeRate($object, $rate, $date);
+ }
+ if (!$object instanceof CurrencyExchangeRate) {
+ // store new
+ $rate = $this->repository->storeExchangeRate($from, $to, $rate, $date);
+ }
+
+ $transformer = new ExchangeRateTransformer();
+ $transformer->setParameters($this->parameters);
+
+ return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $rate, $transformer))->header('Content-Type', self::CONTENT_TYPE);
+ }
+
public function storeByCurrencies(StoreByCurrenciesRequest $request, TransactionCurrency $from, TransactionCurrency $to): JsonResponse
{
$data = $request->getAll();
@@ -114,28 +138,4 @@ class StoreController extends Controller
return response()->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer))->header('Content-Type', self::CONTENT_TYPE);
}
-
- public function store(StoreRequest $request): JsonResponse
- {
- $date = $request->getDate();
- $rate = $request->getRate();
- $from = $request->getFromCurrency();
- $to = $request->getToCurrency();
-
- // already has rate?
- $object = $this->repository->getSpecificRateOnDate($from, $to, $date);
- if ($object instanceof CurrencyExchangeRate) {
- // just update it, no matter.
- $rate = $this->repository->updateExchangeRate($object, $rate, $date);
- }
- if (!$object instanceof CurrencyExchangeRate) {
- // store new
- $rate = $this->repository->storeExchangeRate($from, $to, $rate, $date);
- }
-
- $transformer = new ExchangeRateTransformer();
- $transformer->setParameters($this->parameters);
-
- return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $rate, $transformer))->header('Content-Type', self::CONTENT_TYPE);
- }
}
diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php
index 71e0edfc01..f70a21a797 100644
--- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php
+++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php
@@ -57,28 +57,28 @@ class UpdateController extends Controller
});
}
- public function updateById(UpdateRequest $request, CurrencyExchangeRate $exchangeRate): JsonResponse
+ public function updateByDate(UpdateRequest $request, TransactionCurrency $from, TransactionCurrency $to, Carbon $date): JsonResponse
{
+ $exchangeRate = $this->repository->getSpecificRateOnDate($from, $to, $date);
+ if (!$exchangeRate instanceof CurrencyExchangeRate) {
+ throw new NotFoundHttpException();
+ }
$date = $request->getDate();
$rate = $request->getRate();
$exchangeRate = $this->repository->updateExchangeRate($exchangeRate, $rate, $date);
+
$transformer = new ExchangeRateTransformer();
- $transformer->setParameters($this->parameters);
return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE);
}
- public function updateByDate(UpdateRequest $request, TransactionCurrency $from, TransactionCurrency $to, Carbon $date): JsonResponse
+ public function updateById(UpdateRequest $request, CurrencyExchangeRate $exchangeRate): JsonResponse
{
- $exchangeRate = $this->repository->getSpecificRateOnDate($from, $to, $date);
- if (!$exchangeRate instanceof CurrencyExchangeRate) {
- throw new NotFoundHttpException();
- }
$date = $request->getDate();
$rate = $request->getRate();
$exchangeRate = $this->repository->updateExchangeRate($exchangeRate, $rate, $date);
-
$transformer = new ExchangeRateTransformer();
+ $transformer->setParameters($this->parameters);
return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE);
}
diff --git a/app/Api/V1/Controllers/Models/Transaction/DestroyController.php b/app/Api/V1/Controllers/Models/Transaction/DestroyController.php
index 56834a8afe..6557b0397a 100644
--- a/app/Api/V1/Controllers/Models/Transaction/DestroyController.php
+++ b/app/Api/V1/Controllers/Models/Transaction/DestroyController.php
@@ -50,9 +50,9 @@ class DestroyController extends Controller
parent::__construct();
$this->middleware(function ($request, $next) {
/** @var User $admin */
- $admin = auth()->user();
+ $admin = auth()->user();
- $this->repository = app(JournalRepositoryInterface::class);
+ $this->repository = app(JournalRepositoryInterface::class);
$this->repository->setUser($admin);
$this->groupRepository = app(TransactionGroupRepository::class);
diff --git a/app/Api/V1/Controllers/Models/Transaction/ShowController.php b/app/Api/V1/Controllers/Models/Transaction/ShowController.php
index 4f4bcd43df..e59e796404 100644
--- a/app/Api/V1/Controllers/Models/Transaction/ShowController.php
+++ b/app/Api/V1/Controllers/Models/Transaction/ShowController.php
@@ -99,17 +99,6 @@ class ShowController 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)#/transactions/getTransactionByJournal
- *
- * Show a single transaction, by transaction journal.
- */
- public function showJournal(TransactionJournal $transactionJournal): JsonResponse
- {
- return $this->show($transactionJournal->transactionGroup);
- }
-
/**
* This endpoint is documented at:
* https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/transactions/getTransaction
@@ -151,4 +140,15 @@ class ShowController 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)#/transactions/getTransactionByJournal
+ *
+ * Show a single transaction, by transaction journal.
+ */
+ public function showJournal(TransactionJournal $transactionJournal): JsonResponse
+ {
+ return $this->show($transactionJournal->transactionGroup);
+ }
}
diff --git a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php
index 0f27f121e0..f5f1768280 100644
--- a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php
+++ b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php
@@ -93,7 +93,7 @@ class UpdateController extends Controller
$flags->fireWebhooks = $fireWebhooks;
$flags->recalculateCredit = $runRecalculations;
event(new UpdatedSingleTransactionGroup($flags, $objects));
- event(new WebhookMessagesRequestSending());
+ event(new WebhookMessagesRequestSending());
/** @var User $admin */
$admin = auth()->user();
diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php
index 3bef404524..113ee5b0ab 100644
--- a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php
+++ b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php
@@ -97,16 +97,20 @@ class UpdateController extends Controller
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
- public function makePrimary(TransactionCurrency $currency): JsonResponse
+ /**
+ * This endpoint is documented at:
+ * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/currencies/enableCurrency
+ *
+ * Enable a currency.
+ */
+ public function enable(TransactionCurrency $currency): JsonResponse
{
- /** @var User $user */
- $user = auth()->user();
$this->repository->enable($currency);
- $this->repository->makePrimary($currency);
+ $manager = $this->getManager();
- Preferences::mark();
+ /** @var User $user */
+ $user = auth()->user();
- $manager = $this->getManager();
$currency->refreshForUser($user);
/** @var CurrencyTransformer $transformer */
@@ -118,20 +122,16 @@ class UpdateController 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)#/currencies/enableCurrency
- *
- * Enable a currency.
- */
- public function enable(TransactionCurrency $currency): JsonResponse
+ public function makePrimary(TransactionCurrency $currency): JsonResponse
{
- $this->repository->enable($currency);
- $manager = $this->getManager();
-
/** @var User $user */
$user = auth()->user();
+ $this->repository->enable($currency);
+ $this->repository->makePrimary($currency);
+
+ Preferences::mark();
+ $manager = $this->getManager();
$currency->refreshForUser($user);
/** @var CurrencyTransformer $transformer */
diff --git a/app/Api/V1/Controllers/Summary/BasicController.php b/app/Api/V1/Controllers/Summary/BasicController.php
index d7b2a9b550..a18e9537ba 100644
--- a/app/Api/V1/Controllers/Summary/BasicController.php
+++ b/app/Api/V1/Controllers/Summary/BasicController.php
@@ -112,6 +112,19 @@ class BasicController extends Controller
return response()->json($return);
}
+ /**
+ * Check if date is outside session range.
+ */
+ protected function notInDateRange(Carbon $date, Carbon $start, Carbon $end): bool
+ { // Validate a preference
+ if ($start->greaterThanOrEqualTo($date) && $end->greaterThanOrEqualTo($date)) {
+ return true;
+ }
+
+ // start and end in the past? use $end
+ return $start->lessThanOrEqualTo($date) && $end->lessThanOrEqualTo($date);
+ }
+
private function getBalanceInformation(Carbon $start, Carbon $end): array
{
Log::debug('getBalanceInformation');
@@ -312,145 +325,6 @@ class BasicController extends Controller
return $return;
}
- private function getSubscriptionInformation(Carbon $start, Carbon $end): array
- {
- Log::debug(sprintf('Now in getBillInformation("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d-')));
- /*
- * Since both this method and the chart use the exact same data, we can suffice
- * with calling the one method in the bill repository that will get this amount.
- */
- $paidAmount = $this->billRepository->sumPaidInRange($start, $end);
- $unpaidAmount = $this->billRepository->sumUnpaidInRange($start, $end);
- $currencies = [$this->primaryCurrency->id => $this->primaryCurrency];
-
- if ($this->convertToPrimary) {
- $converter = new ExchangeRateConverter();
- $newPaidAmount = [[
- 'id' => $this->primaryCurrency->id,
- 'name' => $this->primaryCurrency->name,
- 'symbol' => $this->primaryCurrency->symbol,
- 'code' => $this->primaryCurrency->code,
- 'decimal_places' => $this->primaryCurrency->decimal_places,
- 'sum' => '0',
- ]];
-
- $newUnpaidAmount = [[
- 'id' => $this->primaryCurrency->id,
- 'name' => $this->primaryCurrency->name,
- 'symbol' => $this->primaryCurrency->symbol,
- 'code' => $this->primaryCurrency->code,
- 'decimal_places' => $this->primaryCurrency->decimal_places,
- 'sum' => '0',
- ]];
- foreach ([$paidAmount, $unpaidAmount] as $index => $array) {
- foreach ($array as $item) {
- $currencyId = (int) $item['id'];
- if (0 === $index) {
- // paid amount
- if ($currencyId === $this->primaryCurrency->id) {
- $newPaidAmount[0]['sum'] = bcadd($newPaidAmount[0]['sum'], (string) $item['sum']);
-
- continue;
- }
- $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId);
- $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']);
- $newPaidAmount[0]['sum'] = bcadd($newPaidAmount[0]['sum'], $convertedAmount);
-
- continue;
- }
- // unpaid amount
- if ($currencyId === $this->primaryCurrency->id) {
- $newUnpaidAmount[0]['sum'] = bcadd($newUnpaidAmount[0]['sum'], (string) $item['sum']);
-
- continue;
- }
- $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId);
- $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']);
- $newUnpaidAmount[0]['sum'] = bcadd($newUnpaidAmount[0]['sum'], $convertedAmount);
- }
- }
- $paidAmount = $newPaidAmount;
- $unpaidAmount = $newUnpaidAmount;
- }
-
- // var_dump($paidAmount);
- // var_dump($unpaidAmount);
- // exit;
-
- $return = [];
-
- /**
- * @var array $info
- */
- foreach ($paidAmount as $info) {
- $amount = bcmul((string) $info['sum'], '-1');
- $return[] = [
- 'key' => sprintf('bills-paid-in-%s', $info['code']),
- 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $info['symbol']]),
- 'monetary_value' => $amount,
- 'currency_id' => (string) $info['id'],
- 'currency_code' => $info['code'],
- 'currency_symbol' => $info['symbol'],
- 'currency_decimal_places' => $info['decimal_places'],
- 'value_parsed' => Amount::formatFlat($info['symbol'], $info['decimal_places'], $amount, false),
- 'local_icon' => 'check',
- 'sub_title' => '',
- ];
- }
-
- /**
- * @var array $info
- */
- foreach ($unpaidAmount as $info) {
- $amount = bcmul((string) $info['sum'], '-1');
- $return[] = [
- 'key' => sprintf('bills-unpaid-in-%s', $info['code']),
- 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $info['symbol']]),
- 'monetary_value' => $amount,
- 'currency_id' => (string) $info['id'],
- 'currency_code' => $info['code'],
- 'currency_symbol' => $info['symbol'],
- 'currency_decimal_places' => $info['decimal_places'],
- 'value_parsed' => Amount::formatFlat($info['symbol'], $info['decimal_places'], $amount, false),
- 'local_icon' => 'calendar-o',
- 'sub_title' => '',
- ];
- }
- Log::debug(sprintf('Done with getBillInformation("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d-')));
-
- if (0 === count($return)) {
- $currency = $this->primaryCurrency;
- unset($info, $amount);
-
- $return[] = [
- 'key' => sprintf('bills-paid-in-%s', $currency->code),
- 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $currency->symbol]),
- 'monetary_value' => '0',
- 'currency_id' => (string) $currency->id,
- 'currency_code' => $currency->code,
- 'currency_symbol' => $currency->symbol,
- 'currency_decimal_places' => $currency->decimal_places,
- 'value_parsed' => Amount::formatFlat($currency->symbol, $currency->decimal_places, '0', false),
- 'local_icon' => 'check',
- 'sub_title' => '',
- ];
- $return[] = [
- 'key' => sprintf('bills-unpaid-in-%s', $currency->code),
- 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $currency->symbol]),
- 'monetary_value' => '0',
- 'currency_id' => (string) $currency->id,
- 'currency_code' => $currency->code,
- 'currency_symbol' => $currency->symbol,
- 'currency_decimal_places' => $currency->decimal_places,
- 'value_parsed' => Amount::formatFlat($currency->symbol, $currency->decimal_places, '0', false),
- 'local_icon' => 'calendar-o',
- 'sub_title' => '',
- ];
- }
-
- return $return;
- }
-
/**
* @throws Exception
*/
@@ -650,16 +524,142 @@ class BasicController extends Controller
return $return;
}
- /**
- * Check if date is outside session range.
- */
- protected function notInDateRange(Carbon $date, Carbon $start, Carbon $end): bool
- { // Validate a preference
- if ($start->greaterThanOrEqualTo($date) && $end->greaterThanOrEqualTo($date)) {
- return true;
+ private function getSubscriptionInformation(Carbon $start, Carbon $end): array
+ {
+ Log::debug(sprintf('Now in getBillInformation("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d-')));
+ /*
+ * Since both this method and the chart use the exact same data, we can suffice
+ * with calling the one method in the bill repository that will get this amount.
+ */
+ $paidAmount = $this->billRepository->sumPaidInRange($start, $end);
+ $unpaidAmount = $this->billRepository->sumUnpaidInRange($start, $end);
+ $currencies = [$this->primaryCurrency->id => $this->primaryCurrency];
+
+ if ($this->convertToPrimary) {
+ $converter = new ExchangeRateConverter();
+ $newPaidAmount = [[
+ 'id' => $this->primaryCurrency->id,
+ 'name' => $this->primaryCurrency->name,
+ 'symbol' => $this->primaryCurrency->symbol,
+ 'code' => $this->primaryCurrency->code,
+ 'decimal_places' => $this->primaryCurrency->decimal_places,
+ 'sum' => '0',
+ ]];
+
+ $newUnpaidAmount = [[
+ 'id' => $this->primaryCurrency->id,
+ 'name' => $this->primaryCurrency->name,
+ 'symbol' => $this->primaryCurrency->symbol,
+ 'code' => $this->primaryCurrency->code,
+ 'decimal_places' => $this->primaryCurrency->decimal_places,
+ 'sum' => '0',
+ ]];
+ foreach ([$paidAmount, $unpaidAmount] as $index => $array) {
+ foreach ($array as $item) {
+ $currencyId = (int) $item['id'];
+ if (0 === $index) {
+ // paid amount
+ if ($currencyId === $this->primaryCurrency->id) {
+ $newPaidAmount[0]['sum'] = bcadd($newPaidAmount[0]['sum'], (string) $item['sum']);
+
+ continue;
+ }
+ $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId);
+ $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']);
+ $newPaidAmount[0]['sum'] = bcadd($newPaidAmount[0]['sum'], $convertedAmount);
+
+ continue;
+ }
+ // unpaid amount
+ if ($currencyId === $this->primaryCurrency->id) {
+ $newUnpaidAmount[0]['sum'] = bcadd($newUnpaidAmount[0]['sum'], (string) $item['sum']);
+
+ continue;
+ }
+ $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId);
+ $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']);
+ $newUnpaidAmount[0]['sum'] = bcadd($newUnpaidAmount[0]['sum'], $convertedAmount);
+ }
+ }
+ $paidAmount = $newPaidAmount;
+ $unpaidAmount = $newUnpaidAmount;
}
- // start and end in the past? use $end
- return $start->lessThanOrEqualTo($date) && $end->lessThanOrEqualTo($date);
+ // var_dump($paidAmount);
+ // var_dump($unpaidAmount);
+ // exit;
+
+ $return = [];
+
+ /**
+ * @var array $info
+ */
+ foreach ($paidAmount as $info) {
+ $amount = bcmul((string) $info['sum'], '-1');
+ $return[] = [
+ 'key' => sprintf('bills-paid-in-%s', $info['code']),
+ 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $info['symbol']]),
+ 'monetary_value' => $amount,
+ 'currency_id' => (string) $info['id'],
+ 'currency_code' => $info['code'],
+ 'currency_symbol' => $info['symbol'],
+ 'currency_decimal_places' => $info['decimal_places'],
+ 'value_parsed' => Amount::formatFlat($info['symbol'], $info['decimal_places'], $amount, false),
+ 'local_icon' => 'check',
+ 'sub_title' => '',
+ ];
+ }
+
+ /**
+ * @var array $info
+ */
+ foreach ($unpaidAmount as $info) {
+ $amount = bcmul((string) $info['sum'], '-1');
+ $return[] = [
+ 'key' => sprintf('bills-unpaid-in-%s', $info['code']),
+ 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $info['symbol']]),
+ 'monetary_value' => $amount,
+ 'currency_id' => (string) $info['id'],
+ 'currency_code' => $info['code'],
+ 'currency_symbol' => $info['symbol'],
+ 'currency_decimal_places' => $info['decimal_places'],
+ 'value_parsed' => Amount::formatFlat($info['symbol'], $info['decimal_places'], $amount, false),
+ 'local_icon' => 'calendar-o',
+ 'sub_title' => '',
+ ];
+ }
+ Log::debug(sprintf('Done with getBillInformation("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d-')));
+
+ if (0 === count($return)) {
+ $currency = $this->primaryCurrency;
+ unset($info, $amount);
+
+ $return[] = [
+ 'key' => sprintf('bills-paid-in-%s', $currency->code),
+ 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $currency->symbol]),
+ 'monetary_value' => '0',
+ 'currency_id' => (string) $currency->id,
+ 'currency_code' => $currency->code,
+ 'currency_symbol' => $currency->symbol,
+ 'currency_decimal_places' => $currency->decimal_places,
+ 'value_parsed' => Amount::formatFlat($currency->symbol, $currency->decimal_places, '0', false),
+ 'local_icon' => 'check',
+ 'sub_title' => '',
+ ];
+ $return[] = [
+ 'key' => sprintf('bills-unpaid-in-%s', $currency->code),
+ 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $currency->symbol]),
+ 'monetary_value' => '0',
+ 'currency_id' => (string) $currency->id,
+ 'currency_code' => $currency->code,
+ 'currency_symbol' => $currency->symbol,
+ 'currency_decimal_places' => $currency->decimal_places,
+ 'value_parsed' => Amount::formatFlat($currency->symbol, $currency->decimal_places, '0', false),
+ 'local_icon' => 'calendar-o',
+ 'sub_title' => '',
+ ];
+ }
+
+ return $return;
}
}
diff --git a/app/Api/V1/Controllers/System/ConfigurationController.php b/app/Api/V1/Controllers/System/ConfigurationController.php
index 65cef0479e..4d6d84d968 100644
--- a/app/Api/V1/Controllers/System/ConfigurationController.php
+++ b/app/Api/V1/Controllers/System/ConfigurationController.php
@@ -86,37 +86,6 @@ class ConfigurationController extends Controller
return response()->api($return);
}
- /**
- * Get all config values.
- *
- * @throws FireflyException
- */
- private function getDynamicConfiguration(): array
- {
- $isDemoSite = FireflyConfig::get('is_demo_site');
- $updateCheck = FireflyConfig::get('permission_update_check');
- $lastCheck = FireflyConfig::get('last_update_check');
- $singleUser = FireflyConfig::get('single_user_mode');
-
- return [
- 'is_demo_site' => $isDemoSite?->data,
- 'permission_update_check' => null === $updateCheck ? null : (int) $updateCheck->data,
- 'last_update_check' => null === $lastCheck ? null : (int) $lastCheck->data,
- 'single_user_mode' => $singleUser?->data,
- ];
- }
-
- private function getStaticConfiguration(): array
- {
- $list = EitherConfigKey::$static;
- $return = [];
- foreach ($list as $key) {
- $return[$key] = config($key);
- }
-
- return $return;
- }
-
/**
* This endpoint is documented at:
* https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/configuration/getSingleConfiguration
@@ -170,6 +139,37 @@ class ConfigurationController extends Controller
return response()->api(['data' => $data])->header('Content-Type', self::CONTENT_TYPE);
}
+ /**
+ * Get all config values.
+ *
+ * @throws FireflyException
+ */
+ private function getDynamicConfiguration(): array
+ {
+ $isDemoSite = FireflyConfig::get('is_demo_site');
+ $updateCheck = FireflyConfig::get('permission_update_check');
+ $lastCheck = FireflyConfig::get('last_update_check');
+ $singleUser = FireflyConfig::get('single_user_mode');
+
+ return [
+ 'is_demo_site' => $isDemoSite?->data,
+ 'permission_update_check' => null === $updateCheck ? null : (int) $updateCheck->data,
+ 'last_update_check' => null === $lastCheck ? null : (int) $lastCheck->data,
+ 'single_user_mode' => $singleUser?->data,
+ ];
+ }
+
+ private function getStaticConfiguration(): array
+ {
+ $list = EitherConfigKey::$static;
+ $return = [];
+ foreach ($list as $key) {
+ $return[$key] = config($key);
+ }
+
+ return $return;
+ }
+
private function getWebhookConfiguration(string $configKey): array
{
switch ($configKey) {
diff --git a/app/Api/V1/Controllers/System/UserController.php b/app/Api/V1/Controllers/System/UserController.php
index ab7a0f5eb8..5f066ca141 100644
--- a/app/Api/V1/Controllers/System/UserController.php
+++ b/app/Api/V1/Controllers/System/UserController.php
@@ -58,8 +58,6 @@ class UserController extends Controller
});
}
- public function finishBatch(): JsonResponse {}
-
/**
* This endpoint is documented at:
* https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/users/deleteUser
@@ -85,6 +83,8 @@ class UserController extends Controller
throw new FireflyException('200025: No access to function.');
}
+ public function finishBatch(): JsonResponse {}
+
/**
* This endpoint is documented at:
* https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/users/listUser
diff --git a/app/Api/V1/Requests/AggregateFormRequest.php b/app/Api/V1/Requests/AggregateFormRequest.php
index 192981a2a8..f4e9671b1b 100644
--- a/app/Api/V1/Requests/AggregateFormRequest.php
+++ b/app/Api/V1/Requests/AggregateFormRequest.php
@@ -37,9 +37,6 @@ abstract class AggregateFormRequest extends ApiRequest
*/
protected array $requests = [];
- /** @return array<array|string> */
- abstract protected function getRequests(): array;
-
#[Override]
public function initialize(
array $query = [],
@@ -101,4 +98,7 @@ abstract class AggregateFormRequest extends ApiRequest
}
}
}
+
+ /** @return array<array|string> */
+ abstract protected function getRequests(): array;
}
diff --git a/app/Api/V1/Requests/Insight/GenericRequest.php b/app/Api/V1/Requests/Insight/GenericRequest.php
index a60defe4da..435bb4a60c 100644
--- a/app/Api/V1/Requests/Insight/GenericRequest.php
+++ b/app/Api/V1/Requests/Insight/GenericRequest.php
@@ -79,25 +79,6 @@ class GenericRequest extends FormRequest
return $return;
}
- private function parseAccounts(): void
- {
- if (0 !== $this->accounts->count()) {
- return;
- }
- $repository = app(AccountRepositoryInterface::class);
- $repository->setUser(auth()->user());
- $array = $this->get('accounts');
- if (is_array($array)) {
- foreach ($array as $accountId) {
- $accountId = (int) $accountId;
- $account = $repository->find($accountId);
- if (null !== $account) {
- $this->accounts->push($account);
- }
- }
- }
- }
-
public function getBills(): Collection
{
$this->parseBills();
@@ -105,25 +86,6 @@ class GenericRequest extends FormRequest
return $this->bills;
}
- private function parseBills(): void
- {
- if (0 !== $this->bills->count()) {
- return;
- }
- $repository = app(BillRepositoryInterface::class);
- $repository->setUser(auth()->user());
- $array = $this->get('bills');
- if (is_array($array)) {
- foreach ($array as $billId) {
- $billId = (int) $billId;
- $bill = $repository->find($billId);
- if (null !== $bill) {
- $this->bills->push($bill);
- }
- }
- }
- }
-
public function getBudgets(): Collection
{
$this->parseBudgets();
@@ -131,25 +93,6 @@ class GenericRequest extends FormRequest
return $this->budgets;
}
- private function parseBudgets(): void
- {
- if (0 !== $this->budgets->count()) {
- return;
- }
- $repository = app(BudgetRepositoryInterface::class);
- $repository->setUser(auth()->user());
- $array = $this->get('budgets');
- if (is_array($array)) {
- foreach ($array as $budgetId) {
- $budgetId = (int) $budgetId;
- $budget = $repository->find($budgetId);
- if (null !== $budget) {
- $this->budgets->push($budget);
- }
- }
- }
- }
-
public function getCategories(): Collection
{
$this->parseCategories();
@@ -157,25 +100,6 @@ class GenericRequest extends FormRequest
return $this->categories;
}
- private function parseCategories(): void
- {
- if (0 !== $this->categories->count()) {
- return;
- }
- $repository = app(CategoryRepositoryInterface::class);
- $repository->setUser(auth()->user());
- $array = $this->get('categories');
- if (is_array($array)) {
- foreach ($array as $categoryId) {
- $categoryId = (int) $categoryId;
- $category = $repository->find($categoryId);
- if (null !== $category) {
- $this->categories->push($category);
- }
- }
- }
- }
-
public function getEnd(): Carbon
{
$date = $this->getCarbonDate('end');
@@ -231,6 +155,97 @@ class GenericRequest extends FormRequest
return $this->tags;
}
+ /**
+ * The rules that the incoming request must be matched against.
+ */
+ public function rules(): array
+ {
+ // this is cheating, but it works to initialize the collections.
+ $this->accounts = new Collection();
+ $this->budgets = new Collection();
+ $this->categories = new Collection();
+ $this->bills = new Collection();
+ $this->tags = new Collection();
+
+ return ['start' => 'required|date', 'end' => 'required|date|after_or_equal:start'];
+ }
+
+ private function parseAccounts(): void
+ {
+ if (0 !== $this->accounts->count()) {
+ return;
+ }
+ $repository = app(AccountRepositoryInterface::class);
+ $repository->setUser(auth()->user());
+ $array = $this->get('accounts');
+ if (is_array($array)) {
+ foreach ($array as $accountId) {
+ $accountId = (int) $accountId;
+ $account = $repository->find($accountId);
+ if (null !== $account) {
+ $this->accounts->push($account);
+ }
+ }
+ }
+ }
+
+ private function parseBills(): void
+ {
+ if (0 !== $this->bills->count()) {
+ return;
+ }
+ $repository = app(BillRepositoryInterface::class);
+ $repository->setUser(auth()->user());
+ $array = $this->get('bills');
+ if (is_array($array)) {
+ foreach ($array as $billId) {
+ $billId = (int) $billId;
+ $bill = $repository->find($billId);
+ if (null !== $bill) {
+ $this->bills->push($bill);
+ }
+ }
+ }
+ }
+
+ private function parseBudgets(): void
+ {
+ if (0 !== $this->budgets->count()) {
+ return;
+ }
+ $repository = app(BudgetRepositoryInterface::class);
+ $repository->setUser(auth()->user());
+ $array = $this->get('budgets');
+ if (is_array($array)) {
+ foreach ($array as $budgetId) {
+ $budgetId = (int) $budgetId;
+ $budget = $repository->find($budgetId);
+ if (null !== $budget) {
+ $this->budgets->push($budget);
+ }
+ }
+ }
+ }
+
+ private function parseCategories(): void
+ {
+ if (0 !== $this->categories->count()) {
+ return;
+ }
+ $repository = app(CategoryRepositoryInterface::class);
+ $repository->setUser(auth()->user());
+ $array = $this->get('categories');
+ if (is_array($array)) {
+ foreach ($array as $categoryId) {
+ $categoryId = (int) $categoryId;
+ $category = $repository->find($categoryId);
+ if (null !== $category) {
+ $this->categories->push($category);
+ }
+ }
+ }
+ }
+
private function parseTags(): void
{
if (0 !== $this->tags->count()) {
@@ -249,19 +264,4 @@ class GenericRequest extends FormRequest
}
}
}
-
- /**
- * The rules that the incoming request must be matched against.
- */
- public function rules(): array
- {
- // this is cheating, but it works to initialize the collections.
- $this->accounts = new Collection();
- $this->budgets = new Collection();
- $this->categories = new Collection();
- $this->bills = new Collection();
- $this->tags = new Collection();
-
- return ['start' => 'required|date', 'end' => 'required|date|after_or_equal:start'];
- }
}
diff --git a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php
index 3552bf01a8..8038ab71e1 100644
--- a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php
+++ b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php
@@ -70,65 +70,6 @@ class StoreRequest extends FormRequest
return ['recurrence' => $recurrence, 'transactions' => $this->getTransactionData(), 'repetitions' => $this->getRepetitionData()];
}
- /**
- * Returns the transaction data as it is found in the submitted data. It's a complex method according to code
- * standards, but it just has a lot of ??-statements because of the fields that may or may not exist.
- */
- private function getTransactionData(): array
- {
- $return = [];
-
- // transaction data:
- /** @var null|array $transactions */
- $transactions = $this->get('transactions');
- if (null === $transactions) {
- return [];
- }
-
- /** @var array $transaction */
- foreach ($transactions as $transaction) {
- $return[] = $this->getSingleTransactionData($transaction);
- }
-
- return $return;
- }
-
- /**
- * Returns the repetition data as it is found in the submitted data.
- */
- private function getRepetitionData(): array
- {
- $return = [];
-
- // repetition data:
- /** @var null|array $repetitions */
- $repetitions = $this->get('repetitions');
- if (null === $repetitions) {
- return [];
- }
-
- /** @var array $repetition */
- foreach ($repetitions as $repetition) {
- $current = [];
- if (array_key_exists('type', $repetition)) {
- $current['type'] = $repetition['type'];
- }
- if (array_key_exists('moment', $repetition)) {
- $current['moment'] = $repetition['moment'];
- }
- if (array_key_exists('skip', $repetition)) {
- $current['skip'] = (int) $repetition['skip'];
- }
- if (array_key_exists('weekend', $repetition)) {
- $current['weekend'] = (int) $repetition['weekend'];
- }
-
- $return[] = $current;
- }
-
- return $return;
- }
-
/**
* The rules that the incoming request must be matched against.
*/
@@ -190,4 +131,63 @@ class StoreRequest extends FormRequest
Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray());
}
}
+
+ /**
+ * Returns the repetition data as it is found in the submitted data.
+ */
+ private function getRepetitionData(): array
+ {
+ $return = [];
+
+ // repetition data:
+ /** @var null|array $repetitions */
+ $repetitions = $this->get('repetitions');
+ if (null === $repetitions) {
+ return [];
+ }
+
+ /** @var array $repetition */
+ foreach ($repetitions as $repetition) {
+ $current = [];
+ if (array_key_exists('type', $repetition)) {
+ $current['type'] = $repetition['type'];
+ }
+ if (array_key_exists('moment', $repetition)) {
+ $current['moment'] = $repetition['moment'];
+ }
+ if (array_key_exists('skip', $repetition)) {
+ $current['skip'] = (int) $repetition['skip'];
+ }
+ if (array_key_exists('weekend', $repetition)) {
+ $current['weekend'] = (int) $repetition['weekend'];
+ }
+
+ $return[] = $current;
+ }
+
+ return $return;
+ }
+
+ /**
+ * Returns the transaction data as it is found in the submitted data. It's a complex method according to code
+ * standards, but it just has a lot of ??-statements because of the fields that may or may not exist.
+ */
+ private function getTransactionData(): array
+ {
+ $return = [];
+
+ // transaction data:
+ /** @var null|array $transactions */
+ $transactions = $this->get('transactions');
+ if (null === $transactions) {
+ return [];
+ }
+
+ /** @var array $transaction */
+ foreach ($transactions as $transaction) {
+ $return[] = $this->getSingleTransactionData($transaction);
+ }
+
+ return $return;
+ }
}
diff --git a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php
index fded74916b..e1440b477d 100644
--- a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php
+++ b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php
@@ -77,70 +77,6 @@ class UpdateRequest extends FormRequest
return $return;
}
- /**
- * Returns the repetition data as it is found in the submitted data.
- */
- private function getRepetitionData(): ?array
- {
- $return = [];
-
- // repetition data:
- /** @var null|array $repetitions */
- $repetitions = $this->get('repetitions');
- if (null === $repetitions) {
- return null;
- }
-
- /** @var array $repetition */
- foreach ($repetitions as $repetition) {
- $current = [];
- if (array_key_exists('type', $repetition)) {
- $current['type'] = $repetition['type'];
- }
-
- if (array_key_exists('moment', $repetition)) {
- $current['moment'] = (string) $repetition['moment'];
- }
-
- if (array_key_exists('skip', $repetition)) {
- $current['skip'] = (int) $repetition['skip'];
- }
-
- if (array_key_exists('weekend', $repetition)) {
- $current['weekend'] = (int) $repetition['weekend'];
- }
- $return[] = $current;
- }
- if (0 === count($return)) {
- return null;
- }
-
- return $return;
- }
-
- /**
- * Returns the transaction data as it is found in the submitted data. It's a complex method according to code
- * standards, but it just has a lot of ??-statements because of the fields that may or may not exist.
- */
- private function getTransactionData(): array
- {
- $return = [];
-
- // transaction data:
- /** @var null|array $transactions */
- $transactions = $this->get('transactions');
- if (null === $transactions) {
- return [];
- }
-
- /** @var array $transaction */
- foreach ($transactions as $transaction) {
- $return[] = $this->getSingleTransactionData($transaction);
- }
-
- return $return;
- }
-
/**
* The rules that the incoming request must be matched against.
*/
@@ -207,4 +143,68 @@ class UpdateRequest extends FormRequest
Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray());
}
}
+
+ /**
+ * Returns the repetition data as it is found in the submitted data.
+ */
+ private function getRepetitionData(): ?array
+ {
+ $return = [];
+
+ // repetition data:
+ /** @var null|array $repetitions */
+ $repetitions = $this->get('repetitions');
+ if (null === $repetitions) {
+ return null;
+ }
+
+ /** @var array $repetition */
+ foreach ($repetitions as $repetition) {
+ $current = [];
+ if (array_key_exists('type', $repetition)) {
+ $current['type'] = $repetition['type'];
+ }
+
+ if (array_key_exists('moment', $repetition)) {
+ $current['moment'] = (string) $repetition['moment'];
+ }
+
+ if (array_key_exists('skip', $repetition)) {
+ $current['skip'] = (int) $repetition['skip'];
+ }
+
+ if (array_key_exists('weekend', $repetition)) {
+ $current['weekend'] = (int) $repetition['weekend'];
+ }
+ $return[] = $current;
+ }
+ if (0 === count($return)) {
+ return null;
+ }
+
+ return $return;
+ }
+
+ /**
+ * Returns the transaction data as it is found in the submitted data. It's a complex method according to code
+ * standards, but it just has a lot of ??-statements because of the fields that may or may not exist.
+ */
+ private function getTransactionData(): array
+ {
+ $return = [];
+
+ // transaction data:
+ /** @var null|array $transactions */
+ $transactions = $this->get('transactions');
+ if (null === $transactions) {
+ return [];
+ }
+
+ /** @var array $transaction */
+ foreach ($transactions as $transaction) {
+ $return[] = $this->getSingleTransactionData($transaction);
+ }
+
+ return $return;
+ }
}
diff --git a/app/Api/V1/Requests/Models/Rule/StoreRequest.php b/app/Api/V1/Requests/Models/Rule/StoreRequest.php
index 9bfbd7fd7b..a5d05ebdbf 100644
--- a/app/Api/V1/Requests/Models/Rule/StoreRequest.php
+++ b/app/Api/V1/Requests/Models/Rule/StoreRequest.php
@@ -65,43 +65,6 @@ class StoreRequest extends FormRequest
return $data;
}
- private function getRuleTriggers(): array
- {
- $triggers = $this->get('triggers');
- $return = [];
- if (is_array($triggers)) {
- foreach ($triggers as $trigger) {
- $return[] = [
- 'type' => $trigger['type'] ?? '',
- 'value' => $trigger['value'] ?? null,
- 'prohibited' => $this->convertBoolean((string) ($trigger['prohibited'] ?? 'false')),
- 'active' => $this->convertBoolean((string) ($trigger['active'] ?? 'true')),
- 'stop_processing' => $this->convertBoolean((string) ($trigger['stop_processing'] ?? 'false')),
- ];
- }
- }
-
- return $return;
- }
-
- private function getRuleActions(): array
- {
- $actions = $this->get('actions');
- $return = [];
- if (is_array($actions)) {
- foreach ($actions as $action) {
- $return[] = [
- 'type' => $action['type'],
- 'value' => $action['value'],
- 'active' => $this->convertBoolean((string) ($action['active'] ?? 'true')),
- 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')),
- ];
- }
- }
-
- return $return;
- }
-
/**
* The rules that the incoming request must be matched against.
*/
@@ -150,19 +113,6 @@ class StoreRequest extends FormRequest
}
}
- /**
- * Adds an error to the validator when there are no triggers in the array of data.
- */
- protected function atLeastOneTrigger(Validator $validator): void
- {
- $data = $validator->getData();
- $triggers = $data['triggers'] ?? [];
- // need at least one trigger
- if (!is_countable($triggers) || 0 === count($triggers)) {
- $validator->errors()->add('title', (string) trans('validation.at_least_one_trigger'));
- }
- }
-
/**
* Adds an error to the validator when there are no repetitions in the array of data.
*/
@@ -177,22 +127,22 @@ class StoreRequest extends FormRequest
}
/**
- * Adds an error to the validator when there are no ACTIVE triggers in the array of data.
+ * Adds an error to the validator when there are no ACTIVE actions in the array of data.
*/
- protected function atLeastOneActiveTrigger(Validator $validator): void
+ protected function atLeastOneActiveAction(Validator $validator): void
{
$data = $validator->getData();
- /** @var null|array|int|string $triggers */
- $triggers = $data['triggers'] ?? [];
+ /** @var null|array|int|string $actions */
+ $actions = $data['actions'] ?? [];
// need at least one trigger
- if (!is_countable($triggers) || 0 === count($triggers)) {
+ if (!is_countable($actions) || 0 === count($actions)) {
return;
}
$allInactive = true;
$inactiveIndex = 0;
- foreach ($triggers as $index => $trigger) {
- $active = array_key_exists('active', $trigger) ? $trigger['active'] : true; // assume true
+ foreach ($actions as $index => $action) {
+ $active = array_key_exists('active', $action) ? $action['active'] : true; // assume true
if (true === $active) {
$allInactive = false;
}
@@ -201,27 +151,27 @@ class StoreRequest extends FormRequest
}
}
if ($allInactive) {
- $validator->errors()->add(sprintf('triggers.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_trigger'));
+ $validator->errors()->add(sprintf('actions.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_action'));
}
}
/**
- * Adds an error to the validator when there are no ACTIVE actions in the array of data.
+ * Adds an error to the validator when there are no ACTIVE triggers in the array of data.
*/
- protected function atLeastOneActiveAction(Validator $validator): void
+ protected function atLeastOneActiveTrigger(Validator $validator): void
{
$data = $validator->getData();
- /** @var null|array|int|string $actions */
- $actions = $data['actions'] ?? [];
+ /** @var null|array|int|string $triggers */
+ $triggers = $data['triggers'] ?? [];
// need at least one trigger
- if (!is_countable($actions) || 0 === count($actions)) {
+ if (!is_countable($triggers) || 0 === count($triggers)) {
return;
}
$allInactive = true;
$inactiveIndex = 0;
- foreach ($actions as $index => $action) {
- $active = array_key_exists('active', $action) ? $action['active'] : true; // assume true
+ foreach ($triggers as $index => $trigger) {
+ $active = array_key_exists('active', $trigger) ? $trigger['active'] : true; // assume true
if (true === $active) {
$allInactive = false;
}
@@ -230,7 +180,57 @@ class StoreRequest extends FormRequest
}
}
if ($allInactive) {
- $validator->errors()->add(sprintf('actions.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_action'));
+ $validator->errors()->add(sprintf('triggers.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_trigger'));
+ }
+ }
+
+ /**
+ * Adds an error to the validator when there are no triggers in the array of data.
+ */
+ protected function atLeastOneTrigger(Validator $validator): void
+ {
+ $data = $validator->getData();
+ $triggers = $data['triggers'] ?? [];
+ // need at least one trigger
+ if (!is_countable($triggers) || 0 === count($triggers)) {
+ $validator->errors()->add('title', (string) trans('validation.at_least_one_trigger'));
+ }
+ }
+
+ private function getRuleActions(): array
+ {
+ $actions = $this->get('actions');
+ $return = [];
+ if (is_array($actions)) {
+ foreach ($actions as $action) {
+ $return[] = [
+ 'type' => $action['type'],
+ 'value' => $action['value'],
+ 'active' => $this->convertBoolean((string) ($action['active'] ?? 'true')),
+ 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')),
+ ];
+ }
}
+
+ return $return;
+ }
+
+ private function getRuleTriggers(): array
+ {
+ $triggers = $this->get('triggers');
+ $return = [];
+ if (is_array($triggers)) {
+ foreach ($triggers as $trigger) {
+ $return[] = [
+ 'type' => $trigger['type'] ?? '',
+ 'value' => $trigger['value'] ?? null,
+ 'prohibited' => $this->convertBoolean((string) ($trigger['prohibited'] ?? 'false')),
+ 'active' => $this->convertBoolean((string) ($trigger['active'] ?? 'true')),
+ 'stop_processing' => $this->convertBoolean((string) ($trigger['stop_processing'] ?? 'false')),
+ ];
+ }
+ }
+
+ return $return;
}
}
diff --git a/app/Api/V1/Requests/Models/Rule/TestRequest.php b/app/Api/V1/Requests/Models/Rule/TestRequest.php
index efc60b79fa..5af6a03419 100644
--- a/app/Api/V1/Requests/Models/Rule/TestRequest.php
+++ b/app/Api/V1/Requests/Models/Rule/TestRequest.php
@@ -42,9 +42,19 @@ class TestRequest extends FormRequest
return ['page' => $this->getPage(), 'start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()];
}
- private function getPage(): int
+ public function rules(): array
{
- return 0 === (int) $this->query('page') ? 1 : (int) $this->query('page');
+ return [
+ 'start' => 'date|after:1970-01-02|before:2038-01-17',
+ 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17',
+ 'accounts' => '',
+ 'accounts.*' => 'required|exists:accounts,id|belongsToUser:accounts',
+ ];
+ }
+
+ private function getAccounts(): array
+ {
+ return $this->get('accounts') ?? [];
}
private function getDate(string $field): ?Carbon
@@ -58,18 +68,8 @@ class TestRequest extends FormRequest
return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($value, 0, 10));
}
- private function getAccounts(): array
- {
- return $this->get('accounts') ?? [];
- }
-
- public function rules(): array
+ private function getPage(): int
{
- return [
- 'start' => 'date|after:1970-01-02|before:2038-01-17',
- 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17',
- 'accounts' => '',
- 'accounts.*' => 'required|exists:accounts,id|belongsToUser:accounts',
- ];
+ return 0 === (int) $this->query('page') ? 1 : (int) $this->query('page');
}
}
diff --git a/app/Api/V1/Requests/Models/Rule/TriggerRequest.php b/app/Api/V1/Requests/Models/Rule/TriggerRequest.php
index 44951621e2..589ba95045 100644
--- a/app/Api/V1/Requests/Models/Rule/TriggerRequest.php
+++ b/app/Api/V1/Requests/Models/Rule/TriggerRequest.php
@@ -42,15 +42,14 @@ class TriggerRequest extends FormRequest
return ['start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()];
}
- private function getDate(string $field): ?Carbon
+ public function rules(): array
{
- $value = $this->query($field);
- if (is_array($value)) {
- return null;
- }
- $value = (string) $value;
-
- return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($value, 0, 10));
+ return [
+ 'start' => 'date|after:1970-01-02|before:2038-01-17',
+ 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17',
+ 'accounts' => '',
+ 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts',
+ ];
}
private function getAccounts(): array
@@ -58,13 +57,14 @@ class TriggerRequest extends FormRequest
return $this->get('accounts') ?? [];
}
- public function rules(): array
+ private function getDate(string $field): ?Carbon
{
- return [
- 'start' => 'date|after:1970-01-02|before:2038-01-17',
- 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17',
- 'accounts' => '',
- 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts',
- ];
+ $value = $this->query($field);
+ if (is_array($value)) {
+ return null;
+ }
+ $value = (string) $value;
+
+ return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($value, 0, 10));
}
}
diff --git a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php
index cec238f65e..48e3474feb 100644
--- a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php
+++ b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php
@@ -72,52 +72,6 @@ class UpdateRequest extends FormRequest
return $return;
}
- private function getRuleTriggers(): ?array
- {
- if (!$this->has('triggers')) {
- return null;
- }
- $triggers = $this->get('triggers');
- $return = [];
- if (is_array($triggers)) {
- foreach ($triggers as $trigger) {
- $active = array_key_exists('active', $trigger) ? $trigger['active'] : true;
- $prohibited = array_key_exists('prohibited', $trigger) ? $trigger['prohibited'] : false;
- $stopProcessing = array_key_exists('stop_processing', $trigger) ? $trigger['stop_processing'] : false;
- $return[] = [
- 'type' => $trigger['type'],
- 'value' => $trigger['value'],
- 'prohibited' => $prohibited,
- 'active' => $active,
- 'stop_processing' => $stopProcessing,
- ];
- }
- }
-
- return $return;
- }
-
- private function getRuleActions(): ?array
- {
- if (!$this->has('actions')) {
- return null;
- }
- $actions = $this->get('actions');
- $return = [];
- if (is_array($actions)) {
- foreach ($actions as $action) {
- $return[] = [
- 'type' => $action['type'],
- 'value' => $action['value'],
- 'active' => $this->convertBoolean((string) ($action['active'] ?? 'false')),
- 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')),
- ];
- }
- }
-
- return $return;
- }
-
/**
* The rules that the incoming request must be matched against.
*/
@@ -170,6 +124,19 @@ class UpdateRequest extends FormRequest
}
}
+ /**
+ * Adds an error to the validator when there are no repetitions in the array of data.
+ */
+ protected function atLeastOneAction(Validator $validator): void
+ {
+ $data = $validator->getData();
+ $actions = $data['actions'] ?? null;
+ // need at least one action
+ if (is_array($actions) && 0 === count($actions)) {
+ $validator->errors()->add('title', (string) trans('validation.at_least_one_action'));
+ }
+ }
+
/**
* Adds an error to the validator when there are no repetitions in the array of data.
*/
@@ -186,18 +153,19 @@ class UpdateRequest extends FormRequest
/**
* Adds an error to the validator when there are no repetitions in the array of data.
*/
- protected function atLeastOneValidTrigger(Validator $validator): void
+ protected function atLeastOneValidAction(Validator $validator): void
{
$data = $validator->getData();
- $triggers = $data['triggers'] ?? [];
+ $actions = $data['actions'] ?? [];
$allInactive = true;
$inactiveIndex = 0;
- // need at least one trigger
- if (is_array($triggers) && 0 === count($triggers)) {
+ // need at least one action
+ if (is_array($actions) && 0 === count($actions)) {
return;
}
- foreach ($triggers as $index => $trigger) {
- $active = array_key_exists('active', $trigger) ? $trigger['active'] : true; // assume true
+
+ foreach ($actions as $index => $action) {
+ $active = array_key_exists('active', $action) ? $action['active'] : true; // assume true
if (true === $active) {
$allInactive = false;
}
@@ -206,39 +174,25 @@ class UpdateRequest extends FormRequest
}
}
if ($allInactive) {
- $validator->errors()->add(sprintf('triggers.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_trigger'));
- }
- }
-
- /**
- * Adds an error to the validator when there are no repetitions in the array of data.
- */
- protected function atLeastOneAction(Validator $validator): void
- {
- $data = $validator->getData();
- $actions = $data['actions'] ?? null;
- // need at least one action
- if (is_array($actions) && 0 === count($actions)) {
- $validator->errors()->add('title', (string) trans('validation.at_least_one_action'));
+ $validator->errors()->add(sprintf('actions.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_action'));
}
}
/**
* Adds an error to the validator when there are no repetitions in the array of data.
*/
- protected function atLeastOneValidAction(Validator $validator): void
+ protected function atLeastOneValidTrigger(Validator $validator): void
{
$data = $validator->getData();
- $actions = $data['actions'] ?? [];
+ $triggers = $data['triggers'] ?? [];
$allInactive = true;
$inactiveIndex = 0;
- // need at least one action
- if (is_array($actions) && 0 === count($actions)) {
+ // need at least one trigger
+ if (is_array($triggers) && 0 === count($triggers)) {
return;
}
-
- foreach ($actions as $index => $action) {
- $active = array_key_exists('active', $action) ? $action['active'] : true; // assume true
+ foreach ($triggers as $index => $trigger) {
+ $active = array_key_exists('active', $trigger) ? $trigger['active'] : true; // assume true
if (true === $active) {
$allInactive = false;
}
@@ -247,7 +201,53 @@ class UpdateRequest extends FormRequest
}
}
if ($allInactive) {
- $validator->errors()->add(sprintf('actions.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_action'));
+ $validator->errors()->add(sprintf('triggers.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_trigger'));
+ }
+ }
+
+ private function getRuleActions(): ?array
+ {
+ if (!$this->has('actions')) {
+ return null;
+ }
+ $actions = $this->get('actions');
+ $return = [];
+ if (is_array($actions)) {
+ foreach ($actions as $action) {
+ $return[] = [
+ 'type' => $action['type'],
+ 'value' => $action['value'],
+ 'active' => $this->convertBoolean((string) ($action['active'] ?? 'false')),
+ 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')),
+ ];
+ }
+ }
+
+ return $return;
+ }
+
+ private function getRuleTriggers(): ?array
+ {
+ if (!$this->has('triggers')) {
+ return null;
}
+ $triggers = $this->get('triggers');
+ $return = [];
+ if (is_array($triggers)) {
+ foreach ($triggers as $trigger) {
+ $active = array_key_exists('active', $trigger) ? $trigger['active'] : true;
+ $prohibited = array_key_exists('prohibited', $trigger) ? $trigger['prohibited'] : false;
+ $stopProcessing = array_key_exists('stop_processing', $trigger) ? $trigger['stop_processing'] : false;
+ $return[] = [
+ 'type' => $trigger['type'],
+ 'value' => $trigger['value'],
+ 'prohibited' => $prohibited,
+ 'active' => $active,
+ 'stop_processing' => $stopProcessing,
+ ];
+ }
+ }
+
+ return $return;
}
}
diff --git a/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php b/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php
index aeee9b9297..f4b43ddfbc 100644
--- a/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php
+++ b/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php
@@ -42,15 +42,14 @@ class TestRequest extends FormRequest
return ['start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()];
}
- private function getDate(string $field): ?Carbon
+ public function rules(): array
{
- $value = $this->query($field);
- if (is_array($value)) {
- return null;
- }
- $value = (string) $value;
-
- return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($value, 0, 10));
+ return [
+ 'start' => 'date|after:1970-01-02|before:2038-01-17',
+ 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17',
+ 'accounts' => '',
+ 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts',
+ ];
}
private function getAccounts(): array
@@ -58,13 +57,14 @@ class TestRequest extends FormRequest
return $this->get('accounts') ?? [];
}
- public function rules(): array
+ private function getDate(string $field): ?Carbon
{
- return [
- 'start' => 'date|after:1970-01-02|before:2038-01-17',
- 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17',
- 'accounts' => '',
- 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts',
- ];
+ $value = $this->query($field);
+ if (is_array($value)) {
+ return null;
+ }
+ $value = (string) $value;
+
+ return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($value, 0, 10));
}
}
diff --git a/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php b/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php
index 09b24e9071..fbb6f9c071 100644
--- a/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php
+++ b/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php
@@ -42,15 +42,9 @@ class TriggerRequest extends FormRequest
return ['start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()];
}
- private function getDate(string $field): ?Carbon
+ public function rules(): array
{
- $value = $this->query($field);
- if (is_array($value)) {
- return null;
- }
- $value = (string) $value;
-
- return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($value, 0, 10));
+ return ['start' => 'date|after:1970-01-02|before:2038-01-17', 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17'];
}
private function getAccounts(): array
@@ -62,8 +56,14 @@ class TriggerRequest extends FormRequest
return $this->get('accounts');
}
- public function rules(): array
+ private function getDate(string $field): ?Carbon
{
- return ['start' => 'date|after:1970-01-02|before:2038-01-17', 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17'];
+ $value = $this->query($field);
+ if (is_array($value)) {
+ return null;
+ }
+ $value = (string) $value;
+
+ return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($value, 0, 10));
}
}
diff --git a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php
index 6f7c7ec02c..a6acd226bf 100644
--- a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php
+++ b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php
@@ -73,106 +73,6 @@ class StoreRequest extends FormRequest
// TODO include location and ability to process it.
}
- /**
- * Get transaction data.
- */
- private function getTransactionData(): array
- {
- $return = [];
-
- /**
- * @var array $transaction
- */
- foreach ($this->get('transactions') as $transaction) {
- $object = new NullArrayObject($transaction);
- $return[] = [
- 'type' => $this->clearString($object['type']),
- 'date' => $this->dateFromValue($object['date']),
- 'order' => $this->integerFromValue((string) $object['order']),
-
- 'currency_id' => $this->integerFromValue((string) $object['currency_id']),
- 'currency_code' => $this->clearString((string) $object['currency_code']),
-
- // location
- 'latitude' => $this->floatFromValue((string) $object['latitude']),
- 'longitude' => $this->floatFromValue((string) $object['longitude']),
- 'zoom_level' => $this->integerFromValue((string) $object['zoom_level']),
-
- // foreign currency info:
- 'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']),
- 'foreign_currency_code' => $this->clearString((string) $object['foreign_currency_code']),
-
- // amount and foreign amount. Cannot be 0.
- 'amount' => $this->clearString((string) $object['amount']),
- 'foreign_amount' => $this->clearString((string) $object['foreign_amount']),
-
- // description.
- 'description' => $this->clearString($object['description']),
-
- // source of transaction. If everything is null, assume cash account.
- 'source_id' => $this->integerFromValue((string) $object['source_id']),
- 'source_name' => $this->clearString((string) $object['source_name']),
- 'source_iban' => $this->clearIban((string) $object['source_iban']),
- 'source_number' => $this->clearString((string) $object['source_number']),
- 'source_bic' => $this->clearString((string) $object['source_bic']),
-
- // destination of transaction. If everything is null, assume cash account.
- 'destination_id' => $this->integerFromValue((string) $object['destination_id']),
- 'destination_name' => $this->clearString((string) $object['destination_name']),
- 'destination_iban' => $this->clearIban((string) $object['destination_iban']),
- 'destination_number' => $this->clearString((string) $object['destination_number']),
- 'destination_bic' => $this->clearString((string) $object['destination_bic']),
-
- // budget info
- 'budget_id' => $this->integerFromValue((string) $object['budget_id']),
- 'budget_name' => $this->clearString((string) $object['budget_name']),
-
- // category info
- 'category_id' => $this->integerFromValue((string) $object['category_id']),
- 'category_name' => $this->clearString((string) $object['category_name']),
-
- // journal bill reference. Optional. Will only work for withdrawals
- 'bill_id' => $this->integerFromValue((string) $object['bill_id']),
- 'bill_name' => $this->clearString((string) $object['bill_name']),
-
- // piggy bank reference. Optional. Will only work for transfers
- 'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']),
- 'piggy_bank_name' => $this->clearString((string) $object['piggy_bank_name']),
-
- // some other interesting properties
- 'reconciled' => $this->convertBoolean((string) $object['reconciled']),
- 'notes' => $this->clearStringKeepNewlines((string) $object['notes']),
- 'tags' => $this->arrayFromValue($object['tags']),
-
- // all custom fields:
- 'internal_reference' => $this->clearString((string) $object['internal_reference']),
- 'external_id' => $this->clearString((string) $object['external_id']),
- 'original_source' => sprintf('ff3-v%s', config('firefly.version')),
- 'recurrence_id' => $this->integerFromValue($object['recurrence_id']),
- 'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id']),
- 'external_url' => $this->clearString((string) $object['external_url']),
-
- 'sepa_cc' => $this->clearString((string) $object['sepa_cc']),
- 'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op']),
- 'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id']),
- 'sepa_db' => $this->clearString((string) $object['sepa_db']),
- 'sepa_country' => $this->clearString((string) $object['sepa_country']),
- 'sepa_ep' => $this->clearString((string) $object['sepa_ep']),
- 'sepa_ci' => $this->clearString((string) $object['sepa_ci']),
- 'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id']),
- // custom date fields. Must be Carbon objects. Presence is optional.
- 'interest_date' => $this->dateFromValue($object['interest_date']),
- 'book_date' => $this->dateFromValue($object['book_date']),
- 'process_date' => $this->dateFromValue($object['process_date']),
- 'due_date' => $this->dateFromValue($object['due_date']),
- 'payment_date' => $this->dateFromValue($object['payment_date']),
- 'invoice_date' => $this->dateFromValue($object['invoice_date']),
- ];
- }
-
- return $return;
- }
-
/**
* The rules that the incoming request must be matched against.
*/
@@ -305,4 +205,104 @@ class StoreRequest extends FormRequest
Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray());
}
}
+
+ /**
+ * Get transaction data.
+ */
+ private function getTransactionData(): array
+ {
+ $return = [];
+
+ /**
+ * @var array $transaction
+ */
+ foreach ($this->get('transactions') as $transaction) {
+ $object = new NullArrayObject($transaction);
+ $return[] = [
+ 'type' => $this->clearString($object['type']),
+ 'date' => $this->dateFromValue($object['date']),
+ 'order' => $this->integerFromValue((string) $object['order']),
+
+ 'currency_id' => $this->integerFromValue((string) $object['currency_id']),
+ 'currency_code' => $this->clearString((string) $object['currency_code']),
+
+ // location
+ 'latitude' => $this->floatFromValue((string) $object['latitude']),
+ 'longitude' => $this->floatFromValue((string) $object['longitude']),
+ 'zoom_level' => $this->integerFromValue((string) $object['zoom_level']),
+
+ // foreign currency info:
+ 'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']),
+ 'foreign_currency_code' => $this->clearString((string) $object['foreign_currency_code']),
+
+ // amount and foreign amount. Cannot be 0.
+ 'amount' => $this->clearString((string) $object['amount']),
+ 'foreign_amount' => $this->clearString((string) $object['foreign_amount']),
+
+ // description.
+ 'description' => $this->clearString($object['description']),
+
+ // source of transaction. If everything is null, assume cash account.
+ 'source_id' => $this->integerFromValue((string) $object['source_id']),
+ 'source_name' => $this->clearString((string) $object['source_name']),
+ 'source_iban' => $this->clearIban((string) $object['source_iban']),
+ 'source_number' => $this->clearString((string) $object['source_number']),
+ 'source_bic' => $this->clearString((string) $object['source_bic']),
+
+ // destination of transaction. If everything is null, assume cash account.
+ 'destination_id' => $this->integerFromValue((string) $object['destination_id']),
+ 'destination_name' => $this->clearString((string) $object['destination_name']),
+ 'destination_iban' => $this->clearIban((string) $object['destination_iban']),
+ 'destination_number' => $this->clearString((string) $object['destination_number']),
+ 'destination_bic' => $this->clearString((string) $object['destination_bic']),
+
+ // budget info
+ 'budget_id' => $this->integerFromValue((string) $object['budget_id']),
+ 'budget_name' => $this->clearString((string) $object['budget_name']),
+
+ // category info
+ 'category_id' => $this->integerFromValue((string) $object['category_id']),
+ 'category_name' => $this->clearString((string) $object['category_name']),
+
+ // journal bill reference. Optional. Will only work for withdrawals
+ 'bill_id' => $this->integerFromValue((string) $object['bill_id']),
+ 'bill_name' => $this->clearString((string) $object['bill_name']),
+
+ // piggy bank reference. Optional. Will only work for transfers
+ 'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']),
+ 'piggy_bank_name' => $this->clearString((string) $object['piggy_bank_name']),
+
+ // some other interesting properties
+ 'reconciled' => $this->convertBoolean((string) $object['reconciled']),
+ 'notes' => $this->clearStringKeepNewlines((string) $object['notes']),
+ 'tags' => $this->arrayFromValue($object['tags']),
+
+ // all custom fields:
+ 'internal_reference' => $this->clearString((string) $object['internal_reference']),
+ 'external_id' => $this->clearString((string) $object['external_id']),
+ 'original_source' => sprintf('ff3-v%s', config('firefly.version')),
+ 'recurrence_id' => $this->integerFromValue($object['recurrence_id']),
+ 'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id']),
+ 'external_url' => $this->clearString((string) $object['external_url']),
+
+ 'sepa_cc' => $this->clearString((string) $object['sepa_cc']),
+ 'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op']),
+ 'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id']),
+ 'sepa_db' => $this->clearString((string) $object['sepa_db']),
+ 'sepa_country' => $this->clearString((string) $object['sepa_country']),
+ 'sepa_ep' => $this->clearString((string) $object['sepa_ep']),
+ 'sepa_ci' => $this->clearString((string) $object['sepa_ci']),
+ 'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id']),
+ // custom date fields. Must be Carbon objects. Presence is optional.
+ 'interest_date' => $this->dateFromValue($object['interest_date']),
+ 'book_date' => $this->dateFromValue($object['book_date']),
+ 'process_date' => $this->dateFromValue($object['process_date']),
+ 'due_date' => $this->dateFromValue($object['due_date']),
+ 'payment_date' => $this->dateFromValue($object['payment_date']),
+ 'invoice_date' => $this->dateFromValue($object['invoice_date']),
+ ];
+ }
+
+ return $return;
+ }
}
diff --git a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php
index 2c4ac8ac57..de60f42d69 100644
--- a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php
+++ b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php
@@ -133,158 +133,6 @@ class UpdateRequest extends FormRequest
return $data;
}
- /**
- * Get transaction data.
- *
- * @throws FireflyException
- */
- private function getTransactionData(): array
- {
- Log::debug(sprintf('Now in %s', __METHOD__));
- $return = [];
-
- /** @var null|array $transactions */
- $transactions = $this->get('transactions');
-
- if (!is_countable($transactions)) {
- return $return;
- }
-
- /** @var null|array $transaction */
- foreach ($transactions as $transaction) {
- if (!is_array($transaction)) {
- throw new FireflyException('Invalid data submitted: transaction is not array.');
- }
- // default response is to update nothing in the transaction:
- $current = [];
- $current = $this->getIntegerData($current, $transaction);
- $current = $this->getStringData($current, $transaction);
- $current = $this->getNlStringData($current, $transaction);
- $current = $this->getDateData($current, $transaction);
- $current = $this->getBooleanData($current, $transaction);
- $current = $this->getArrayData($current, $transaction);
- $current = $this->getFloatData($current, $transaction);
- $return[] = $current;
- }
-
- return $return;
- }
-
- /**
- * For each field, add it to the array if a reference is present in the request:
- *
- * @param array<string, string> $current
- * @param array<string, mixed> $transaction
- */
- private function getIntegerData(array $current, array $transaction): array
- {
- foreach ($this->integerFields as $fieldName) {
- if (array_key_exists($fieldName, $transaction)) {
- $current[$fieldName] = $this->integerFromValue((string) $transaction[$fieldName]);
- }
- }
-
- return $current;
- }
-
- /**
- * @param array<string, string> $current
- * @param array<string, mixed> $transaction
- */
- private function getStringData(array $current, array $transaction): array
- {
- foreach ($this->stringFields as $fieldName) {
- if (array_key_exists($fieldName, $transaction)) {
- $current[$fieldName] = $this->clearString((string) $transaction[$fieldName]);
- }
- }
-
- return $current;
- }
-
- /**
- * @param array<string, string> $current
- * @param array<string, mixed> $transaction
- */
- private function getNlStringData(array $current, array $transaction): array
- {
- foreach ($this->textareaFields as $fieldName) {
- if (array_key_exists($fieldName, $transaction)) {
- $current[$fieldName] = $this->clearStringKeepNewlines((string) $transaction[$fieldName]); // keep newlines
- }
- }
-
- return $current;
- }
-
- /**
- * @param array<string, string> $current
- * @param array<string, mixed> $transaction
- */
- private function getDateData(array $current, array $transaction): array
- {
- foreach ($this->dateFields as $fieldName) {
- Log::debug(sprintf('Now at date field %s', $fieldName));
- if (array_key_exists($fieldName, $transaction)) {
- Log::debug(sprintf('New value: "%s"', $transaction[$fieldName]));
- $current[$fieldName] = $this->dateFromValue((string) $transaction[$fieldName]);
- }
- }
-
- return $current;
- }
-
- /**
- * @param array<string, string> $current
- * @param array<string, mixed> $transaction
- */
- private function getBooleanData(array $current, array $transaction): array
- {
- foreach ($this->booleanFields as $fieldName) {
- if (array_key_exists($fieldName, $transaction)) {
- $current[$fieldName] = $this->convertBoolean((string) $transaction[$fieldName]);
- }
- }
-
- return $current;
- }
-
- /**
- * @param array<string, string> $current
- * @param array<string, mixed> $transaction
- */
- private function getArrayData(array $current, array $transaction): array
- {
- foreach ($this->arrayFields as $fieldName) {
- if (array_key_exists($fieldName, $transaction)) {
- $current[$fieldName] = $this->arrayFromValue($transaction[$fieldName]);
- }
- }
-
- return $current;
- }
-
- /**
- * @param array<string, string> $current
- * @param array<string, mixed> $transaction
- */
- private function getFloatData(array $current, array $transaction): array
- {
- foreach ($this->floatFields as $fieldName) {
- if (array_key_exists($fieldName, $transaction)) {
- $value = $transaction[$fieldName];
- if (is_float($value)) {
- $current[$fieldName] = sprintf('%.12f', $value);
- }
- if (!is_float($value)) {
- $current[$fieldName] = (string) $value;
- }
- }
- }
-
- return $current;
- }
-
/**
* The rules that the incoming request must be matched against.
*/
@@ -406,4 +254,156 @@ class UpdateRequest extends FormRequest
Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray());
}
}
+
+ /**
+ * @param array<string, string> $current
+ * @param array<string, mixed> $transaction
+ */
+ private function getArrayData(array $current, array $transaction): array
+ {
+ foreach ($this->arrayFields as $fieldName) {
+ if (array_key_exists($fieldName, $transaction)) {
+ $current[$fieldName] = $this->arrayFromValue($transaction[$fieldName]);
+ }
+ }
+
+ return $current;
+ }
+
+ /**
+ * @param array<string, string> $current
+ * @param array<string, mixed> $transaction
+ */
+ private function getBooleanData(array $current, array $transaction): array
+ {
+ foreach ($this->booleanFields as $fieldName) {
+ if (array_key_exists($fieldName, $transaction)) {
+ $current[$fieldName] = $this->convertBoolean((string) $transaction[$fieldName]);
+ }
+ }
+
+ return $current;
+ }
+
+ /**
+ * @param array<string, string> $current
+ * @param array<string, mixed> $transaction
+ */
+ private function getDateData(array $current, array $transaction): array
+ {
+ foreach ($this->dateFields as $fieldName) {
+ Log::debug(sprintf('Now at date field %s', $fieldName));
+ if (array_key_exists($fieldName, $transaction)) {
+ Log::debug(sprintf('New value: "%s"', $transaction[$fieldName]));
+ $current[$fieldName] = $this->dateFromValue((string) $transaction[$fieldName]);
+ }
+ }
+
+ return $current;
+ }
+
+ /**
+ * @param array<string, string> $current
+ * @param array<string, mixed> $transaction
+ */
+ private function getFloatData(array $current, array $transaction): array
+ {
+ foreach ($this->floatFields as $fieldName) {
+ if (array_key_exists($fieldName, $transaction)) {
+ $value = $transaction[$fieldName];
+ if (is_float($value)) {
+ $current[$fieldName] = sprintf('%.12f', $value);
+ }
+ if (!is_float($value)) {
+ $current[$fieldName] = (string) $value;
+ }
+ }
+ }
+
+ return $current;
+ }
+
+ /**
+ * For each field, add it to the array if a reference is present in the request:
+ *
+ * @param array<string, string> $current
+ * @param array<string, mixed> $transaction
+ */
+ private function getIntegerData(array $current, array $transaction): array
+ {
+ foreach ($this->integerFields as $fieldName) {
+ if (array_key_exists($fieldName, $transaction)) {
+ $current[$fieldName] = $this->integerFromValue((string) $transaction[$fieldName]);
+ }
+ }
+
+ return $current;
+ }
+
+ /**
+ * @param array<string, string> $current
+ * @param array<string, mixed> $transaction
+ */
+ private function getNlStringData(array $current, array $transaction): array
+ {
+ foreach ($this->textareaFields as $fieldName) {
+ if (array_key_exists($fieldName, $transaction)) {
+ $current[$fieldName] = $this->clearStringKeepNewlines((string) $transaction[$fieldName]); // keep newlines
+ }
+ }
+
+ return $current;
+ }
+
+ /**
+ * @param array<string, string> $current
+ * @param array<string, mixed> $transaction
+ */
+ private function getStringData(array $current, array $transaction): array
+ {
+ foreach ($this->stringFields as $fieldName) {
+ if (array_key_exists($fieldName, $transaction)) {
+ $current[$fieldName] = $this->clearString((string) $transaction[$fieldName]);
+ }
+ }
+
+ return $current;
+ }
+
+ /**
+ * Get transaction data.
+ *
+ * @throws FireflyException
+ */
+ private function getTransactionData(): array
+ {
+ Log::debug(sprintf('Now in %s', __METHOD__));
+ $return = [];
+
+ /** @var null|array $transactions */
+ $transactions = $this->get('transactions');
+
+ if (!is_countable($transactions)) {
+ return $return;
+ }
+
+ /** @var null|array $transaction */
+ foreach ($transactions as $transaction) {
+ if (!is_array($transaction)) {
+ throw new FireflyException('Invalid data submitted: transaction is not array.');
+ }
+ // default response is to update nothing in the transaction:
+ $current = [];
+ $current = $this->getIntegerData($current, $transaction);
+ $current = $this->getStringData($current, $transaction);
+ $current = $this->getNlStringData($current, $transaction);
+ $current = $this->getDateData($current, $transaction);
+ $current = $this->getBooleanData($current, $transaction);
+ $current = $this->getArrayData($current, $transaction);
+ $current = $this->getFloatData($current, $transaction);
+ $return[] = $current;
+ }
+
+ return $return;
+ }
}
diff --git a/app/Console/Commands/Correction/ConvertsDatesToUTC.php b/app/Console/Commands/Correction/ConvertsDatesToUTC.php
index 742b0bd18d..145f9117f6 100644
--- a/app/Console/Commands/Correction/ConvertsDatesToUTC.php
+++ b/app/Console/Commands/Correction/ConvertsDatesToUTC.php
@@ -62,14 +62,6 @@ class ConvertsDatesToUTC extends Command
return Command::SUCCESS;
}
- private function ConvertModeltoUTC(string $model, array $fields): void
- {
- /** @var string $field */
- foreach ($fields as $field) {
- $this->convertFieldtoUTC($model, $field);
- }
- }
-
private function convertFieldtoUTC(string $model, string $field): void
{
$this->info(sprintf('Converting %s.%s to UTC', $model, $field));
@@ -98,4 +90,12 @@ class ConvertsDatesToUTC extends Command
$item->save();
});
}
+
+ private function ConvertModeltoUTC(string $model, array $fields): void
+ {
+ /** @var string $field */
+ foreach ($fields as $field) {
+ $this->convertFieldtoUTC($model, $field);
+ }
+ }
}
diff --git a/app/Console/Commands/Correction/CorrectsAccountTypes.php b/app/Console/Commands/Correction/CorrectsAccountTypes.php
index 4366cc184b..0bd3a59877 100644
--- a/app/Console/Commands/Correction/CorrectsAccountTypes.php
+++ b/app/Console/Commands/Correction/CorrectsAccountTypes.php
@@ -123,56 +123,17 @@ class CorrectsAccountTypes extends Command
return 0;
}
- private function stupidLaravel(): void
- {
- $this->count = 0;
- }
-
- private function inspectJournal(TransactionJournal $journal): void
- {
- Log::debug(sprintf('Now inspecting journal #%d', $journal->id));
- $transactions = $journal->transactions()->count();
- if (2 !== $transactions) {
- Log::debug(sprintf('Journal has %d transactions, so can\'t fix.', $transactions));
- $this->friendlyError(sprintf('Cannot inspect transaction journal #%d because it has %d transaction(s) instead of 2.', $journal->id, $transactions));
-
- return;
- }
- $type = $journal->transactionType->type;
- $sourceTransaction = $this->getSourceTransaction($journal);
- $destTransaction = $this->getDestinationTransaction($journal);
- $sourceAccount = $sourceTransaction->account;
- $sourceAccountType = $sourceAccount->accountType->type;
- $destAccount = $destTransaction->account;
- $destAccountType = $destAccount->accountType->type;
-
- if (!array_key_exists($type, $this->expected)) {
- Log::info(sprintf('No source/destination info for transaction type %s.', $type));
- $this->friendlyError(sprintf('No source/destination info for transaction type %s.', $type));
-
- return;
- }
- if (!array_key_exists($sourceAccountType, $this->expected[$type])) {
- Log::debug(sprintf('[a] Going to fix journal #%d', $journal->id));
- $this->fixJournal($journal, $type, $sourceTransaction, $destTransaction);
-
- return;
- }
- $expectedTypes = $this->expected[$type][$sourceAccountType];
- if (!in_array($destAccountType, $expectedTypes, true)) {
- Log::debug(sprintf('[b] Going to fix journal #%d', $journal->id));
- $this->fixJournal($journal, $type, $sourceTransaction, $destTransaction);
- }
- }
-
- private function getSourceTransaction(TransactionJournal $journal): Transaction
+ private function canCreateDestination(array $validDestinations): bool
{
- return $journal->transactions->firstWhere('amount', '<', 0);
+ return in_array(AccountTypeEnum::EXPENSE->value, $validDestinations, true);
}
- private function getDestinationTransaction(TransactionJournal $journal): Transaction
+ /**
+ * Can only create revenue accounts out of the blue.
+ */
+ private function canCreateSource(array $validSources): bool
{
- return $journal->transactions->firstWhere('amount', '>', 0);
+ return in_array(AccountTypeEnum::REVENUE->value, $validSources, true);
}
private function fixJournal(TransactionJournal $journal, string $transactionType, Transaction $source, Transaction $dest): void
@@ -266,41 +227,121 @@ class CorrectsAccountTypes extends Command
}
}
- private function shouldBeTransfer(string $transactionType, string $sourceType, string $destinationType): bool
+ private function getDestinationTransaction(TransactionJournal $journal): Transaction
{
- return
- TransactionTypeEnum::TRANSFER->value === $transactionType
- && AccountTypeEnum::ASSET->value === $sourceType
- && $this->isLiability($destinationType);
+ return $journal->transactions->firstWhere('amount', '>', 0);
}
- private function isLiability(string $destinationType): bool
+ private function getSourceTransaction(TransactionJournal $journal): Transaction
{
- return
- AccountTypeEnum::LOAN->value === $destinationType
- || AccountTypeEnum::DEBT->value === $destinationType
- || AccountTypeEnum::MORTGAGE->value === $destinationType;
+ return $journal->transactions->firstWhere('amount', '<', 0);
}
- private function makeTransfer(TransactionJournal $journal): void
+ private function giveNewDestinationAccount(TransactionJournal $journal, Account $newDestination): void
{
- // from an asset to a liability should be a withdrawal:
- $withdrawal = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first();
- $journal->transactionType()->associate($withdrawal);
- $journal->save();
- $message = sprintf('Converted transaction #%d from a transfer to a withdrawal.', $journal->id);
+ $destTransaction = $this->getDestinationTransaction($journal);
+ $oldDest = $destTransaction->account;
+ $destTransaction->account_id = $newDestination->id;
+ $destTransaction->save();
+ $message = sprintf(
+ 'Transaction journal #%d, destination account changed from #%d ("%s") to #%d ("%s").',
+ $journal->id,
+ $oldDest->id,
+ $oldDest->name,
+ $newDestination->id,
+ $newDestination->name
+ );
$this->friendlyInfo($message);
+ $journal->refresh();
Log::debug($message);
- // check it again:
+ }
+
+ private function giveNewExpense(TransactionJournal $journal, Transaction $destination): void
+ {
+ Log::debug(sprintf('An account of type "%s" could be a valid destination.', AccountTypeEnum::EXPENSE->value));
+ $this->factory->setUser($journal->user);
+ $name = $destination->account->name;
+ $newDestination = $this->factory->findOrCreate($name, AccountTypeEnum::EXPENSE->value);
+ $destination->account()->associate($newDestination);
+ $destination->save();
+ $this->friendlyPositive(sprintf(
+ 'Firefly III gave transaction #%d a new destination %s: #%d ("%s").',
+ $journal->transaction_group_id,
+ AccountTypeEnum::EXPENSE->value,
+ $newDestination->id,
+ $newDestination->name
+ ));
+ Log::debug(sprintf('Associated account #%d with transaction #%d', $newDestination->id, $destination->id));
$this->inspectJournal($journal);
}
- private function shouldBeDeposit(string $transactionType, string $sourceType, string $destinationType): bool
+ private function giveNewRevenue(TransactionJournal $journal, Transaction $source): void
+ {
+ Log::debug(sprintf('An account of type "%s" could be a valid source.', AccountTypeEnum::REVENUE->value));
+ $this->factory->setUser($journal->user);
+ $name = $source->account->name;
+ $newSource = $this->factory->findOrCreate($name, AccountTypeEnum::REVENUE->value);
+ $source->account()->associate($newSource);
+ $source->save();
+ $this->friendlyPositive(sprintf(
+ 'Firefly III gave transaction #%d a new source %s: #%d ("%s").',
+ $journal->transaction_group_id,
+ AccountTypeEnum::REVENUE->value,
+ $newSource->id,
+ $newSource->name
+ ));
+ Log::debug(sprintf('Associated account #%d with transaction #%d', $newSource->id, $source->id));
+ $this->inspectJournal($journal);
+ }
+
+ private function hasValidAccountType(array $validTypes, string $accountType): bool
+ {
+ return in_array($accountType, $validTypes, true);
+ }
+
+ private function inspectJournal(TransactionJournal $journal): void
+ {
+ Log::debug(sprintf('Now inspecting journal #%d', $journal->id));
+ $transactions = $journal->transactions()->count();
+ if (2 !== $transactions) {
+ Log::debug(sprintf('Journal has %d transactions, so can\'t fix.', $transactions));
+ $this->friendlyError(sprintf('Cannot inspect transaction journal #%d because it has %d transaction(s) instead of 2.', $journal->id, $transactions));
+
+ return;
+ }
+ $type = $journal->transactionType->type;
+ $sourceTransaction = $this->getSourceTransaction($journal);
+ $destTransaction = $this->getDestinationTransaction($journal);
+ $sourceAccount = $sourceTransaction->account;
+ $sourceAccountType = $sourceAccount->accountType->type;
+ $destAccount = $destTransaction->account;
+ $destAccountType = $destAccount->accountType->type;
+
+ if (!array_key_exists($type, $this->expected)) {
+ Log::info(sprintf('No source/destination info for transaction type %s.', $type));
+ $this->friendlyError(sprintf('No source/destination info for transaction type %s.', $type));
+
+ return;
+ }
+ if (!array_key_exists($sourceAccountType, $this->expected[$type])) {
+ Log::debug(sprintf('[a] Going to fix journal #%d', $journal->id));
+ $this->fixJournal($journal, $type, $sourceTransaction, $destTransaction);
+
+ return;
+ }
+ $expectedTypes = $this->expected[$type][$sourceAccountType];
+ if (!in_array($destAccountType, $expectedTypes, true)) {
+ Log::debug(sprintf('[b] Going to fix journal #%d', $journal->id));
+ $this->fixJournal($journal, $type, $sourceTransaction, $destTransaction);
+ }
+ }
+
+ private function isLiability(string $destinationType): bool
{
return
- TransactionTypeEnum::TRANSFER->value === $transactionType
- && $this->isLiability($sourceType)
- && AccountTypeEnum::ASSET->value === $destinationType;
+ AccountTypeEnum::LOAN->value === $destinationType
+ || AccountTypeEnum::DEBT->value === $destinationType
+ || AccountTypeEnum::MORTGAGE->value === $destinationType;
}
private function makeDeposit(TransactionJournal $journal): void
@@ -316,14 +357,6 @@ class CorrectsAccountTypes extends Command
$this->inspectJournal($journal);
}
- private function shouldGoToExpenseAccount(string $transactionType, string $sourceType, string $destinationType): bool
- {
- return
- TransactionTypeEnum::WITHDRAWAL->value === $transactionType
- && AccountTypeEnum::ASSET->value === $sourceType
- && AccountTypeEnum::REVENUE->value === $destinationType;
- }
-
private function makeExpenseDestination(TransactionJournal $journal, Transaction $destination): void
{
// withdrawals with a revenue account as destination instead of an expense account.
@@ -345,14 +378,6 @@ class CorrectsAccountTypes extends Command
$this->inspectJournal($journal);
}
- private function shouldComeFromRevenueAccount(string $transactionType, string $sourceType, string $destinationType): bool
- {
- return
- TransactionTypeEnum::DEPOSIT->value === $transactionType
- && AccountTypeEnum::EXPENSE->value === $sourceType
- && AccountTypeEnum::ASSET->value === $destinationType;
- }
-
private function makeRevenueSource(TransactionJournal $journal, Transaction $source): void
{
// deposits with an expense account as source instead of a revenue account.
@@ -375,78 +400,53 @@ class CorrectsAccountTypes extends Command
$this->inspectJournal($journal);
}
- /**
- * Can only create revenue accounts out of the blue.
- */
- private function canCreateSource(array $validSources): bool
+ private function makeTransfer(TransactionJournal $journal): void
{
- return in_array(AccountTypeEnum::REVENUE->value, $validSources, true);
+ // from an asset to a liability should be a withdrawal:
+ $withdrawal = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first();
+ $journal->transactionType()->associate($withdrawal);
+ $journal->save();
+ $message = sprintf('Converted transaction #%d from a transfer to a withdrawal.', $journal->id);
+ $this->friendlyInfo($message);
+ Log::debug($message);
+ // check it again:
+ $this->inspectJournal($journal);
}
- private function hasValidAccountType(array $validTypes, string $accountType): bool
+ private function shouldBeDeposit(string $transactionType, string $sourceType, string $destinationType): bool
{
- return in_array($accountType, $validTypes, true);
+ return
+ TransactionTypeEnum::TRANSFER->value === $transactionType
+ && $this->isLiability($sourceType)
+ && AccountTypeEnum::ASSET->value === $destinationType;
}
- private function giveNewRevenue(TransactionJournal $journal, Transaction $source): void
+ private function shouldBeTransfer(string $transactionType, string $sourceType, string $destinationType): bool
{
- Log::debug(sprintf('An account of type "%s" could be a valid source.', AccountTypeEnum::REVENUE->value));
- $this->factory->setUser($journal->user);
- $name = $source->account->name;
- $newSource = $this->factory->findOrCreate($name, AccountTypeEnum::REVENUE->value);
- $source->account()->associate($newSource);
- $source->save();
- $this->friendlyPositive(sprintf(
- 'Firefly III gave transaction #%d a new source %s: #%d ("%s").',
- $journal->transaction_group_id,
- AccountTypeEnum::REVENUE->value,
- $newSource->id,
- $newSource->name
- ));
- Log::debug(sprintf('Associated account #%d with transaction #%d', $newSource->id, $source->id));
- $this->inspectJournal($journal);
+ return
+ TransactionTypeEnum::TRANSFER->value === $transactionType
+ && AccountTypeEnum::ASSET->value === $sourceType
+ && $this->isLiability($destinationType);
}
- private function canCreateDestination(array $validDestinations): bool
+ private function shouldComeFromRevenueAccount(string $transactionType, string $sourceType, string $destinationType): bool
{
- return in_array(AccountTypeEnum::EXPENSE->value, $validDestinations, true);
+ return
+ TransactionTypeEnum::DEPOSIT->value === $transactionType
+ && AccountTypeEnum::EXPENSE->value === $sourceType
+ && AccountTypeEnum::ASSET->value === $destinationType;
}
- private function giveNewExpense(TransactionJournal $journal, Transaction $destination): void
+ private function shouldGoToExpenseAccount(string $transactionType, string $sourceType, string $destinationType): bool
{
- Log::debug(sprintf('An account of type "%s" could be a valid destination.', AccountTypeEnum::EXPENSE->value));
- $this->factory->setUser($journal->user);
- $name = $destination->account->name;
- $newDestination = $this->factory->findOrCreate($name, AccountTypeEnum::EXPENSE->value);
- $destination->account()->associate($newDestination);
- $destination->save();
- $this->friendlyPositive(sprintf(
- 'Firefly III gave transaction #%d a new destination %s: #%d ("%s").',
- $journal->transaction_group_id,
- AccountTypeEnum::EXPENSE->value,
- $newDestination->id,
- $newDestination->name
- ));
- Log::debug(sprintf('Associated account #%d with transaction #%d', $newDestination->id, $destination->id));
- $this->inspectJournal($journal);
+ return
+ TransactionTypeEnum::WITHDRAWAL->value === $transactionType
+ && AccountTypeEnum::ASSET->value === $sourceType
+ && AccountTypeEnum::REVENUE->value === $destinationType;
}
- private function giveNewDestinationAccount(TransactionJournal $journal, Account $newDestination): void
+ private function stupidLaravel(): void
{
- $destTransaction = $this->getDestinationTransaction($journal);
- $oldDest = $destTransaction->account;
- $destTransaction->account_id = $newDestination->id;
- $destTransaction->save();
- $message = sprintf(
- 'Transaction journal #%d, destination account changed from #%d ("%s") to #%d ("%s").',
- $journal->id,
- $oldDest->id,
- $oldDest->name,
- $newDestination->id,
- $newDestination->name
- );
- $this->friendlyInfo($message);
- $journal->refresh();
- Log::debug($message);
+ $this->count = 0;
}
}
diff --git a/app/Console/Commands/Correction/CorrectsAmounts.php b/app/Console/Commands/Correction/CorrectsAmounts.php
index 9f8dfdd441..cfe775380e 100644
--- a/app/Console/Commands/Correction/CorrectsAmounts.php
+++ b/app/Console/Commands/Correction/CorrectsAmounts.php
@@ -253,27 +253,6 @@ class CorrectsAmounts extends Command
$this->friendlyInfo(sprintf('Corrected %d recurring transaction amount(s).', $count));
}
- /**
- * Foreach loop is unavoidable here.
- */
- private function fixRuleTriggers(): void
- {
- $set = RuleTrigger::whereIn('trigger_type', ['amount_less', 'amount_more', 'amount_is'])->get();
- $fixed = 0;
-
- /** @var RuleTrigger $item */
- foreach ($set as $item) {
- $result = $this->fixRuleTrigger($item);
- if ($result) {
- ++$fixed;
- }
- }
- if (0 === $fixed) {
- return;
- }
- $this->friendlyInfo(sprintf('Corrected %d rule trigger amount(s).', $fixed));
- }
-
private function fixRuleTrigger(RuleTrigger $item): bool
{
try {
@@ -301,6 +280,27 @@ class CorrectsAmounts extends Command
return false;
}
+ /**
+ * Foreach loop is unavoidable here.
+ */
+ private function fixRuleTriggers(): void
+ {
+ $set = RuleTrigger::whereIn('trigger_type', ['amount_less', 'amount_more', 'amount_is'])->get();
+ $fixed = 0;
+
+ /** @var RuleTrigger $item */
+ foreach ($set as $item) {
+ $result = $this->fixRuleTrigger($item);
+ if ($result) {
+ ++$fixed;
+ }
+ }
+ if (0 === $fixed) {
+ return;
+ }
+ $this->friendlyInfo(sprintf('Corrected %d rule trigger amount(s).', $fixed));
+ }
+
private function validateJournal(TransactionJournal $journal): bool
{
$countSource = $journal->transactions()->where('amount', '<', 0)->count();
diff --git a/app/Console/Commands/Correction/CorrectsGroupAccounts.php b/app/Console/Commands/Correction/CorrectsGroupAccounts.php
index 97e1d0c066..0b8b20de6f 100644
--- a/app/Console/Commands/Correction/CorrectsGroupAccounts.php
+++ b/app/Console/Commands/Correction/CorrectsGroupAccounts.php
@@ -66,6 +66,7 @@ class CorrectsGroupAccounts extends Command
}
event(new UpdatedSingleTransactionGroup($flags, $objects));
event(new WebhookMessagesRequestSending());
+
return 0;
}
}
diff --git a/app/Console/Commands/Correction/CorrectsIbans.php b/app/Console/Commands/Correction/CorrectsIbans.php
index 7ac2b0f73c..5749665e45 100644
--- a/app/Console/Commands/Correction/CorrectsIbans.php
+++ b/app/Console/Commands/Correction/CorrectsIbans.php
@@ -51,33 +51,6 @@ class CorrectsIbans extends Command
return 0;
}
- private function filterIbans(Collection $accounts): void
- {
- /** @var Account $account */
- foreach ($accounts as $account) {
- $iban = (string) $account->iban;
- $newIban = Steam::filterSpaces($iban);
- if ('' !== $iban && $iban !== $newIban) {
- $account->iban = $newIban;
- $account->save();
- $this->friendlyInfo(sprintf('Removed spaces from IBAN of account #%d', $account->id));
- ++$this->count;
- }
- // same for account number:
- $accountNumber = $account->accountMeta->where('name', 'account_number')->first();
- if (null !== $accountNumber) {
- $number = (string) $accountNumber->value;
- $newNumber = Steam::filterSpaces($number);
- if ('' !== $number && $number !== $newNumber) {
- $accountNumber->value = $newNumber;
- $accountNumber->save();
- $this->friendlyInfo(sprintf('Removed spaces from account number of account #%d', $account->id));
- ++$this->count;
- }
- }
- }
- }
-
private function countAndCorrectIbans(Collection $accounts): void
{
$set = [];
@@ -119,4 +92,31 @@ class CorrectsIbans extends Command
}
}
}
+
+ private function filterIbans(Collection $accounts): void
+ {
+ /** @var Account $account */
+ foreach ($accounts as $account) {
+ $iban = (string) $account->iban;
+ $newIban = Steam::filterSpaces($iban);
+ if ('' !== $iban && $iban !== $newIban) {
+ $account->iban = $newIban;
+ $account->save();
+ $this->friendlyInfo(sprintf('Removed spaces from IBAN of account #%d', $account->id));
+ ++$this->count;
+ }
+ // same for account number:
+ $accountNumber = $account->accountMeta->where('name', 'account_number')->first();
+ if (null !== $accountNumber) {
+ $number = (string) $accountNumber->value;
+ $newNumber = Steam::filterSpaces($number);
+ if ('' !== $number && $number !== $newNumber) {
+ $accountNumber->value = $newNumber;
+ $accountNumber->save();
+ $this->friendlyInfo(sprintf('Removed spaces from account number of account #%d', $account->id));
+ ++$this->count;
+ }
+ }
+ }
+ }
}
diff --git a/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php b/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php
index 6c2162f69f..2574a2891c 100644
--- a/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php
+++ b/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php
@@ -69,7 +69,7 @@ class CorrectsInvertedBudgetLimits extends Command
$budgetLimit->saveQuietly();
}
- if($set->count() > 0) {
+ if ($set->count() > 0) {
// FIXME here be a available budget event.
}
diff --git a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php
index 2120b3021b..7160a488ba 100644
--- a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php
+++ b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php
@@ -65,16 +65,6 @@ class CorrectsOpeningBalanceCurrencies extends Command
return 0;
}
- private function getJournals(): Collection
- {
- /** @var Collection */
- return TransactionJournal::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
- ->whereNull('transaction_journals.deleted_at')
- ->where('transaction_types.type', TransactionTypeEnum::OPENING_BALANCE->value)
- ->get(['transaction_journals.*'])
- ;
- }
-
private function correctJournal(TransactionJournal $journal): int
{
// get the asset account for this opening balance:
@@ -107,6 +97,25 @@ class CorrectsOpeningBalanceCurrencies extends Command
return null;
}
+ private function getCurrency(Account $account): TransactionCurrency
+ {
+ /** @var AccountRepositoryInterface $repos */
+ $repos = app(AccountRepositoryInterface::class);
+ $repos->setUser($account->user);
+
+ return $repos->getAccountCurrency($account) ?? Amount::getPrimaryCurrencyByUserGroup($account->userGroup);
+ }
+
+ private function getJournals(): Collection
+ {
+ /** @var Collection */
+ return TransactionJournal::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
+ ->whereNull('transaction_journals.deleted_at')
+ ->where('transaction_types.type', TransactionTypeEnum::OPENING_BALANCE->value)
+ ->get(['transaction_journals.*'])
+ ;
+ }
+
private function setCorrectCurrency(Account $account, TransactionJournal $journal): int
{
$currency = $this->getCurrency($account);
@@ -128,13 +137,4 @@ class CorrectsOpeningBalanceCurrencies extends Command
return $count;
}
-
- private function getCurrency(Account $account): TransactionCurrency
- {
- /** @var AccountRepositoryInterface $repos */
- $repos = app(AccountRepositoryInterface::class);
- $repos->setUser($account->user);
-
- return $repos->getAccountCurrency($account) ?? Amount::getPrimaryCurrencyByUserGroup($account->userGroup);
- }
}
diff --git a/app/Console/Commands/Correction/CorrectsRecurringTransactions.php b/app/Console/Commands/Correction/CorrectsRecurringTransactions.php
index e043cafdab..afbd042833 100644
--- a/app/Console/Commands/Correction/CorrectsRecurringTransactions.php
+++ b/app/Console/Commands/Correction/CorrectsRecurringTransactions.php
@@ -54,17 +54,6 @@ class CorrectsRecurringTransactions extends Command
return 0;
}
- /**
- * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
- * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
- * be called from the handle method instead of using the constructor to initialize the command.
- */
- private function stupidLaravel(): void
- {
- $this->recurringRepos = app(RecurringRepositoryInterface::class);
- $this->userRepos = app(UserRepositoryInterface::class);
- }
-
private function correctTransactions(): void
{
$users = $this->userRepos->all();
@@ -75,17 +64,6 @@ class CorrectsRecurringTransactions extends Command
}
}
- private function processUser(User $user): void
- {
- $this->recurringRepos->setUser($user);
- $recurrences = $this->recurringRepos->get();
-
- /** @var Recurrence $recurrence */
- foreach ($recurrences as $recurrence) {
- $this->processRecurrence($recurrence);
- }
- }
-
private function processRecurrence(Recurrence $recurrence): void
{
/** @var RecurrenceTransaction $transaction */
@@ -115,4 +93,26 @@ class CorrectsRecurringTransactions extends Command
}
}
}
+
+ private function processUser(User $user): void
+ {
+ $this->recurringRepos->setUser($user);
+ $recurrences = $this->recurringRepos->get();
+
+ /** @var Recurrence $recurrence */
+ foreach ($recurrences as $recurrence) {
+ $this->processRecurrence($recurrence);
+ }
+ }
+
+ /**
+ * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
+ * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
+ * be called from the handle method instead of using the constructor to initialize the command.
+ */
+ private function stupidLaravel(): void
+ {
+ $this->recurringRepos = app(RecurringRepositoryInterface::class);
+ $this->userRepos = app(UserRepositoryInterface::class);
+ }
}
diff --git a/app/Console/Commands/Correction/CorrectsTransactionTypes.php b/app/Console/Commands/Correction/CorrectsTransactionTypes.php
index 4510cd0587..c50a2c0b97 100644
--- a/app/Console/Commands/Correction/CorrectsTransactionTypes.php
+++ b/app/Console/Commands/Correction/CorrectsTransactionTypes.php
@@ -67,6 +67,15 @@ class CorrectsTransactionTypes extends Command
return 0;
}
+ private function changeJournal(TransactionJournal $journal, string $expectedType): void
+ {
+ $type = TransactionType::whereType($expectedType)->first();
+ if (null !== $type) {
+ $journal->transaction_type_id = $type->id;
+ $journal->save();
+ }
+ }
+
/**
* Collect all transaction journals.
*/
@@ -108,14 +117,14 @@ class CorrectsTransactionTypes extends Command
/**
* @throws FireflyException
*/
- private function getSourceAccount(TransactionJournal $journal): Account
+ private function getDestinationAccount(TransactionJournal $journal): Account
{
- $collection = $journal->transactions->filter(static fn (Transaction $transaction): bool => $transaction->amount < 0);
+ $collection = $journal->transactions->filter(static fn (Transaction $transaction): bool => $transaction->amount > 0);
if (0 === $collection->count()) {
- throw new FireflyException(sprintf('300001: Journal #%d has no source transaction.', $journal->id));
+ throw new FireflyException(sprintf('300004: Journal #%d has no destination transaction.', $journal->id));
}
if (1 !== $collection->count()) {
- throw new FireflyException(sprintf('300002: Journal #%d has multiple source transactions.', $journal->id));
+ throw new FireflyException(sprintf('300005: Journal #%d has multiple destination transactions.', $journal->id));
}
/** @var Transaction $transaction */
@@ -124,7 +133,7 @@ class CorrectsTransactionTypes extends Command
/** @var null|Account $account */
$account = $transaction->account;
if (null === $account) {
- throw new FireflyException(sprintf('300003: Journal #%d, transaction #%d has no source account.', $journal->id, $transaction->id));
+ throw new FireflyException(sprintf('300006: Journal #%d, transaction #%d has no destination account.', $journal->id, $transaction->id));
}
return $account;
@@ -133,14 +142,14 @@ class CorrectsTransactionTypes extends Command
/**
* @throws FireflyException
*/
- private function getDestinationAccount(TransactionJournal $journal): Account
+ private function getSourceAccount(TransactionJournal $journal): Account
{
- $collection = $journal->transactions->filter(static fn (Transaction $transaction): bool => $transaction->amount > 0);
+ $collection = $journal->transactions->filter(static fn (Transaction $transaction): bool => $transaction->amount < 0);
if (0 === $collection->count()) {
- throw new FireflyException(sprintf('300004: Journal #%d has no destination transaction.', $journal->id));
+ throw new FireflyException(sprintf('300001: Journal #%d has no source transaction.', $journal->id));
}
if (1 !== $collection->count()) {
- throw new FireflyException(sprintf('300005: Journal #%d has multiple destination transactions.', $journal->id));
+ throw new FireflyException(sprintf('300002: Journal #%d has multiple source transactions.', $journal->id));
}
/** @var Transaction $transaction */
@@ -149,18 +158,9 @@ class CorrectsTransactionTypes extends Command
/** @var null|Account $account */
$account = $transaction->account;
if (null === $account) {
- throw new FireflyException(sprintf('300006: Journal #%d, transaction #%d has no destination account.', $journal->id, $transaction->id));
+ throw new FireflyException(sprintf('300003: Journal #%d, transaction #%d has no source account.', $journal->id, $transaction->id));
}
return $account;
}
-
- private function changeJournal(TransactionJournal $journal, string $expectedType): void
- {
- $type = TransactionType::whereType($expectedType)->first();
- if (null !== $type) {
- $journal->transaction_type_id = $type->id;
- $journal->save();
- }
- }
}
diff --git a/app/Console/Commands/Correction/CorrectsUnevenAmount.php b/app/Console/Commands/Correction/CorrectsUnevenAmount.php
index cf9cc2bd8c..25a0971182 100644
--- a/app/Console/Commands/Correction/CorrectsUnevenAmount.php
+++ b/app/Console/Commands/Correction/CorrectsUnevenAmount.php
@@ -70,6 +70,120 @@ class CorrectsUnevenAmount extends Command
return 0;
}
+ private function convertOldStyleTransactions(): void
+ {
+ /** @var AccountRepositoryInterface $repository */
+ $repository = app(AccountRepositoryInterface::class);
+ Log::debug('convertOldStyleTransactions()');
+ $count = 0;
+ $transactions = Transaction::distinct()
+ ->leftJoin('transaction_journals', 'transaction_journals.id', 'transactions.transaction_journal_id')
+ ->leftJoin('transaction_types', 'transaction_types.id', 'transaction_journals.transaction_type_id')
+ ->leftJoin('accounts', 'accounts.id', 'transactions.account_id')
+ ->leftJoin('account_types', 'account_types.id', 'accounts.account_type_id')
+ ->whereNot('transaction_types.type', TransactionTypeEnum::TRANSFER->value)
+ ->whereNotNull('foreign_currency_id')
+ ->whereNotNull('foreign_amount')
+ ->whereIn('account_types.type', [
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::LOAN->value,
+ ])
+ ->get(['transactions.transaction_journal_id'])
+ ;
+
+ /** @var Transaction $transaction */
+ foreach ($transactions as $transaction) {
+ /** @var null|TransactionJournal $journal */
+ $journal = TransactionJournal::find($transaction->transaction_journal_id);
+ $repository->setUser($journal->user);
+ if (null === $journal) {
+ Log::debug('Found no journal, continue.');
+
+ continue;
+ }
+ if (!$this->isBetweenAssetAndLiability($journal)) {
+ // Log::debug('Not between asset and liability, continue.');
+
+ continue;
+ }
+ $source = $journal->transactions()->where('amount', '<', 0)->first();
+ $destination = $journal->transactions()->where('amount', '>', 0)->first();
+ $sourceAccount = $source->account;
+ $destAccount = $destination->account;
+ $sourceCurrency = $repository->getAccountCurrency($sourceAccount);
+ $destCurrency = $repository->getAccountCurrency($destAccount);
+ if (null === $source || null === $destination) {
+ Log::debug('Either transaction is NULL, continue.');
+
+ continue;
+ }
+ if (
+ 0 === bccomp((string) $source->amount, (string) $source->foreign_amount)
+ && 0 === bccomp((string) $source->foreign_amount, (string) $source->amount)
+ ) {
+ Log::debug('Already fixed, continue.');
+
+ continue;
+ }
+ // source transaction. Switch info when does not match.
+ if ((int) $source->transaction_currency_id !== (int) $sourceCurrency->id) {
+ Log::debug(sprintf('Ready to swap data in transaction #%d.', $source->id));
+ // swap amounts.
+ $amount = $source->amount;
+ $currency = $source->transaction_currency_id;
+ $source->amount = $source->foreign_amount;
+ $source->transaction_currency_id = $source->foreign_currency_id;
+ $source->foreign_amount = $amount;
+ $source->foreign_currency_id = $currency;
+ $source->saveQuietly();
+ $source->refresh();
+ // Log::debug(sprintf('source->amount = %s', $source->amount));
+ // Log::debug(sprintf('source->transaction_currency_id = %s', $source->transaction_currency_id));
+ // Log::debug(sprintf('source->foreign_amount = %s', $source->foreign_amount));
+ // Log::debug(sprintf('source->foreign_currency_id = %s', $source->foreign_currency_id));
+ ++$count;
+ }
+ // same but for destination
+ if ((int) $destination->transaction_currency_id !== (int) $destCurrency->id) {
+ ++$count;
+ Log::debug(sprintf('Ready to swap data in transaction #%d.', $destination->id));
+ // swap amounts.
+ $amount = $destination->amount;
+ $currency = $destination->transaction_currency_id;
+ $destination->amount = $destination->foreign_amount;
+ $destination->transaction_currency_id = $destination->foreign_currency_id;
+ $destination->foreign_amount = $amount;
+ $destination->foreign_currency_id = $currency;
+ $destination->balance_dirty = true;
+ $destination->saveQuietly();
+ $destination->refresh();
+
+ // Log::debug(sprintf('destination->amount = %s', $destination->amount));
+ // Log::debug(sprintf('destination->transaction_currency_id = %s', $destination->transaction_currency_id));
+ // Log::debug(sprintf('destination->foreign_amount = %s', $destination->foreign_amount));
+ // Log::debug(sprintf('destination->foreign_currency_id = %s', $destination->foreign_currency_id));
+ }
+
+ // // only fix the destination transaction
+ // $destination->foreign_currency_id = $source->transaction_currency_id;
+ // $destination->foreign_amount = \FireflyIII\Support\Facades\Steam::positive($source->amount);
+ // $destination->transaction_currency_id = $source->foreign_currency_id;
+ // $destination->amount = \FireflyIII\Support\Facades\Steam::positive($source->foreign_amount);
+ // $destination->balance_dirty = true;
+ // $source->balance_dirty = true;
+ // $destination->save();
+ // $source->save();
+ // $this->friendlyWarning(sprintf('Corrected foreign amounts of transaction #%d.', $journal->id));
+ }
+ if (0 === $count) {
+ return;
+ }
+
+ $this->friendlyPositive(sprintf('Fixed %d journal(s) with unbalanced amounts.', $count));
+ }
+
private function convertOldStyleTransfers(): void
{
Log::debug('convertOldStyleTransfers()');
@@ -131,47 +245,6 @@ class CorrectsUnevenAmount extends Command
$this->friendlyPositive(sprintf('Fixed %d transfer(s) with unbalanced amounts.', $count));
}
- private function fixUnevenAmounts(): void
- {
- Log::debug('fixUnevenAmounts()');
- $journals = DB::table('transactions')
- ->groupBy('transaction_journal_id')
- ->whereNull('deleted_at')
- ->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')])
- ;
-
- /** @var stdClass $entry */
- foreach ($journals as $entry) {
- $sum = (string) $entry->the_sum;
- $sum = Steam::floatalize($sum);
- if (
- !is_numeric($sum)
- || '' === $sum // @phpstan-ignore-line
- || str_contains($sum, 'e')
- || str_contains($sum, ',')
- ) {
- $message = sprintf('Journal #%d has an invalid sum ("%s"). No sure what to do.', $entry->transaction_journal_id, $entry->the_sum);
- $this->friendlyWarning($message);
- Log::warning($message);
- ++$this->count;
-
- continue;
- }
- $res = -1;
-
- try {
- $res = bccomp($sum, '0');
- } catch (ValueError $e) {
- $this->friendlyError(sprintf('Could not bccomp("%s", "0").', $sum));
- Log::error($e->getMessage());
- Log::error($e->getTraceAsString());
- }
- if (0 !== $res) {
- $this->fixJournal((int) $entry->transaction_journal_id);
- }
- }
- }
-
private function fixJournal(int $param): void
{
// one of the transactions is bad.
@@ -236,59 +309,45 @@ class CorrectsUnevenAmount extends Command
++$this->count;
}
- private function isForeignCurrencyTransfer(TransactionJournal $journal): bool
- {
- if (TransactionTypeEnum::TRANSFER->value !== $journal->transactionType->type) {
- return false;
- }
-
- /** @var Transaction $destination */
- $destination = $journal->transactions()->where('amount', '>', 0)->first();
-
- /** @var Transaction $source */
- $source = $journal->transactions()->where('amount', '<', 0)->first();
-
- // safety catch on NULL should not be necessary, we just had that catch.
- // source amount = dest foreign amount
- // source currency = dest foreign currency
- // dest amount = source foreign currency
- // dest currency = source foreign currency
- // Log::debug(sprintf('[a] %s', bccomp(\FireflyIII\Support\Facades\Steam::positive($source->amount), \FireflyIII\Support\Facades\Steam::positive($destination->foreign_amount))));
- // Log::debug(sprintf('[b] %s', bccomp(\FireflyIII\Support\Facades\Steam::positive($destination->amount), \FireflyIII\Support\Facades\Steam::positive($source->foreign_amount))));
- // Log::debug(sprintf('[c] %s', var_export($source->transaction_currency_id === $destination->foreign_currency_id,true)));
- // Log::debug(sprintf('[d] %s', var_export((int) $destination->transaction_currency_id ===(int) $source->foreign_currency_id, true)));
- return
- 0 === bccomp(Steam::positive($source->amount), Steam::positive($destination->foreign_amount))
- && $source->transaction_currency_id === $destination->foreign_currency_id
- && 0 === bccomp(Steam::positive($destination->amount), Steam::positive($source->foreign_amount))
- && (int) $destination->transaction_currency_id === (int) $source->foreign_currency_id;
- }
-
- private function matchCurrencies(): void
+ private function fixUnevenAmounts(): void
{
- $journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', 'transactions.transaction_journal_id')->where(
- 'transactions.transaction_currency_id',
- '!=',
- DB::raw('transaction_journals.transaction_currency_id')
- )->get(['transaction_journals.*']);
-
- $count = 0;
+ Log::debug('fixUnevenAmounts()');
+ $journals = DB::table('transactions')
+ ->groupBy('transaction_journal_id')
+ ->whereNull('deleted_at')
+ ->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')])
+ ;
- /** @var TransactionJournal $journal */
- foreach ($journals as $journal) {
- if (!$this->isForeignCurrencyTransfer($journal) && !$this->isBetweenAssetAndLiability($journal)) {
- Transaction::where('transaction_journal_id', $journal->id)->update(['transaction_currency_id' => $journal->transaction_currency_id]);
- ++$count;
+ /** @var stdClass $entry */
+ foreach ($journals as $entry) {
+ $sum = (string) $entry->the_sum;
+ $sum = Steam::floatalize($sum);
+ if (
+ !is_numeric($sum)
+ || '' === $sum // @phpstan-ignore-line
+ || str_contains($sum, 'e')
+ || str_contains($sum, ',')
+ ) {
+ $message = sprintf('Journal #%d has an invalid sum ("%s"). No sure what to do.', $entry->transaction_journal_id, $entry->the_sum);
+ $this->friendlyWarning($message);
+ Log::warning($message);
+ ++$this->count;
continue;
}
- Log::debug(sprintf('Can skip foreign currency transfer or transaction between asset and liability #%d.', $journal->id));
- }
- if (0 === $count) {
- return;
- }
+ $res = -1;
- $this->friendlyPositive(sprintf('Fixed %d journal(s) with mismatched currencies.', $journals->count()));
+ try {
+ $res = bccomp($sum, '0');
+ } catch (ValueError $e) {
+ $this->friendlyError(sprintf('Could not bccomp("%s", "0").', $sum));
+ Log::error($e->getMessage());
+ Log::error($e->getTraceAsString());
+ }
+ if (0 !== $res) {
+ $this->fixJournal((int) $entry->transaction_journal_id);
+ }
+ }
}
private function isBetweenAssetAndLiability(TransactionJournal $journal): bool
@@ -335,117 +394,58 @@ class CorrectsUnevenAmount extends Command
return false;
}
- private function convertOldStyleTransactions(): void
+ private function isForeignCurrencyTransfer(TransactionJournal $journal): bool
{
- /** @var AccountRepositoryInterface $repository */
- $repository = app(AccountRepositoryInterface::class);
- Log::debug('convertOldStyleTransactions()');
- $count = 0;
- $transactions = Transaction::distinct()
- ->leftJoin('transaction_journals', 'transaction_journals.id', 'transactions.transaction_journal_id')
- ->leftJoin('transaction_types', 'transaction_types.id', 'transaction_journals.transaction_type_id')
- ->leftJoin('accounts', 'accounts.id', 'transactions.account_id')
- ->leftJoin('account_types', 'account_types.id', 'accounts.account_type_id')
- ->whereNot('transaction_types.type', TransactionTypeEnum::TRANSFER->value)
- ->whereNotNull('foreign_currency_id')
- ->whereNotNull('foreign_amount')
- ->whereIn('account_types.type', [
- AccountTypeEnum::ASSET->value,
- AccountTypeEnum::DEBT->value,
- AccountTypeEnum::MORTGAGE->value,
- AccountTypeEnum::LOAN->value,
- ])
- ->get(['transactions.transaction_journal_id'])
- ;
+ if (TransactionTypeEnum::TRANSFER->value !== $journal->transactionType->type) {
+ return false;
+ }
- /** @var Transaction $transaction */
- foreach ($transactions as $transaction) {
- /** @var null|TransactionJournal $journal */
- $journal = TransactionJournal::find($transaction->transaction_journal_id);
- $repository->setUser($journal->user);
- if (null === $journal) {
- Log::debug('Found no journal, continue.');
+ /** @var Transaction $destination */
+ $destination = $journal->transactions()->where('amount', '>', 0)->first();
- continue;
- }
- if (!$this->isBetweenAssetAndLiability($journal)) {
- // Log::debug('Not between asset and liability, continue.');
+ /** @var Transaction $source */
+ $source = $journal->transactions()->where('amount', '<', 0)->first();
- continue;
- }
- $source = $journal->transactions()->where('amount', '<', 0)->first();
- $destination = $journal->transactions()->where('amount', '>', 0)->first();
- $sourceAccount = $source->account;
- $destAccount = $destination->account;
- $sourceCurrency = $repository->getAccountCurrency($sourceAccount);
- $destCurrency = $repository->getAccountCurrency($destAccount);
- if (null === $source || null === $destination) {
- Log::debug('Either transaction is NULL, continue.');
+ // safety catch on NULL should not be necessary, we just had that catch.
+ // source amount = dest foreign amount
+ // source currency = dest foreign currency
+ // dest amount = source foreign currency
+ // dest currency = source foreign currency
+ // Log::debug(sprintf('[a] %s', bccomp(\FireflyIII\Support\Facades\Steam::positive($source->amount), \FireflyIII\Support\Facades\Steam::positive($destination->foreign_amount))));
+ // Log::debug(sprintf('[b] %s', bccomp(\FireflyIII\Support\Facades\Steam::positive($destination->amount), \FireflyIII\Support\Facades\Steam::positive($source->foreign_amount))));
+ // Log::debug(sprintf('[c] %s', var_export($source->transaction_currency_id === $destination->foreign_currency_id,true)));
+ // Log::debug(sprintf('[d] %s', var_export((int) $destination->transaction_currency_id ===(int) $source->foreign_currency_id, true)));
+ return
+ 0 === bccomp(Steam::positive($source->amount), Steam::positive($destination->foreign_amount))
+ && $source->transaction_currency_id === $destination->foreign_currency_id
+ && 0 === bccomp(Steam::positive($destination->amount), Steam::positive($source->foreign_amount))
+ && (int) $destination->transaction_currency_id === (int) $source->foreign_currency_id;
+ }
- continue;
- }
- if (
- 0 === bccomp((string) $source->amount, (string) $source->foreign_amount)
- && 0 === bccomp((string) $source->foreign_amount, (string) $source->amount)
- ) {
- Log::debug('Already fixed, continue.');
+ private function matchCurrencies(): void
+ {
+ $journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', 'transactions.transaction_journal_id')->where(
+ 'transactions.transaction_currency_id',
+ '!=',
+ DB::raw('transaction_journals.transaction_currency_id')
+ )->get(['transaction_journals.*']);
- continue;
- }
- // source transaction. Switch info when does not match.
- if ((int) $source->transaction_currency_id !== (int) $sourceCurrency->id) {
- Log::debug(sprintf('Ready to swap data in transaction #%d.', $source->id));
- // swap amounts.
- $amount = $source->amount;
- $currency = $source->transaction_currency_id;
- $source->amount = $source->foreign_amount;
- $source->transaction_currency_id = $source->foreign_currency_id;
- $source->foreign_amount = $amount;
- $source->foreign_currency_id = $currency;
- $source->saveQuietly();
- $source->refresh();
- // Log::debug(sprintf('source->amount = %s', $source->amount));
- // Log::debug(sprintf('source->transaction_currency_id = %s', $source->transaction_currency_id));
- // Log::debug(sprintf('source->foreign_amount = %s', $source->foreign_amount));
- // Log::debug(sprintf('source->foreign_currency_id = %s', $source->foreign_currency_id));
- ++$count;
- }
- // same but for destination
- if ((int) $destination->transaction_currency_id !== (int) $destCurrency->id) {
+ $count = 0;
+
+ /** @var TransactionJournal $journal */
+ foreach ($journals as $journal) {
+ if (!$this->isForeignCurrencyTransfer($journal) && !$this->isBetweenAssetAndLiability($journal)) {
+ Transaction::where('transaction_journal_id', $journal->id)->update(['transaction_currency_id' => $journal->transaction_currency_id]);
++$count;
- Log::debug(sprintf('Ready to swap data in transaction #%d.', $destination->id));
- // swap amounts.
- $amount = $destination->amount;
- $currency = $destination->transaction_currency_id;
- $destination->amount = $destination->foreign_amount;
- $destination->transaction_currency_id = $destination->foreign_currency_id;
- $destination->foreign_amount = $amount;
- $destination->foreign_currency_id = $currency;
- $destination->balance_dirty = true;
- $destination->saveQuietly();
- $destination->refresh();
- // Log::debug(sprintf('destination->amount = %s', $destination->amount));
- // Log::debug(sprintf('destination->transaction_currency_id = %s', $destination->transaction_currency_id));
- // Log::debug(sprintf('destination->foreign_amount = %s', $destination->foreign_amount));
- // Log::debug(sprintf('destination->foreign_currency_id = %s', $destination->foreign_currency_id));
+ continue;
}
-
- // // only fix the destination transaction
- // $destination->foreign_currency_id = $source->transaction_currency_id;
- // $destination->foreign_amount = \FireflyIII\Support\Facades\Steam::positive($source->amount);
- // $destination->transaction_currency_id = $source->foreign_currency_id;
- // $destination->amount = \FireflyIII\Support\Facades\Steam::positive($source->foreign_amount);
- // $destination->balance_dirty = true;
- // $source->balance_dirty = true;
- // $destination->save();
- // $source->save();
- // $this->friendlyWarning(sprintf('Corrected foreign amounts of transaction #%d.', $journal->id));
+ Log::debug(sprintf('Can skip foreign currency transfer or transaction between asset and liability #%d.', $journal->id));
}
if (0 === $count) {
return;
}
- $this->friendlyPositive(sprintf('Fixed %d journal(s) with unbalanced amounts.', $count));
+ $this->friendlyPositive(sprintf('Fixed %d journal(s) with mismatched currencies.', $journals->count()));
}
}
diff --git a/app/Console/Commands/Correction/CreatesGroupMemberships.php b/app/Console/Commands/Correction/CreatesGroupMemberships.php
index bf35bcfdef..fc9481745d 100644
--- a/app/Console/Commands/Correction/CreatesGroupMemberships.php
+++ b/app/Console/Commands/Correction/CreatesGroupMemberships.php
@@ -42,31 +42,6 @@ class CreatesGroupMemberships extends Command
protected $description = 'Update group memberships';
protected $signature = 'correction:create-group-memberships';
- /**
- * Execute the console command.
- *
- * @throws FireflyException
- */
- public function handle(): int
- {
- $this->createGroupMemberships();
-
- return 0;
- }
-
- /**
- * @throws FireflyException
- */
- private function createGroupMemberships(): void
- {
- $users = User::get();
-
- /** @var User $user */
- foreach ($users as $user) {
- self::createGroupMembership($user);
- }
- }
-
/**
* TODO move to helper.
*
@@ -98,4 +73,29 @@ class CreatesGroupMemberships extends Command
$user->save();
}
}
+
+ /**
+ * Execute the console command.
+ *
+ * @throws FireflyException
+ */
+ public function handle(): int
+ {
+ $this->createGroupMemberships();
+
+ return 0;
+ }
+
+ /**
+ * @throws FireflyException
+ */
+ private function createGroupMemberships(): void
+ {
+ $users = User::get();
+
+ /** @var User $user */
+ foreach ($users as $user) {
+ self::createGroupMembership($user);
+ }
+ }
}
diff --git a/app/Console/Commands/Correction/RemovesEmptyJournals.php b/app/Console/Commands/Correction/RemovesEmptyJournals.php
index 12c6efd5db..1dc3517d58 100644
--- a/app/Console/Commands/Correction/RemovesEmptyJournals.php
+++ b/app/Console/Commands/Correction/RemovesEmptyJournals.php
@@ -51,6 +51,30 @@ class RemovesEmptyJournals extends Command
return 0;
}
+ private function deleteEmptyJournals(): void
+ {
+ $count = 0;
+ $set = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
+ ->groupBy('transaction_journals.id')
+ ->whereNull('transactions.transaction_journal_id')
+ ->get(['transaction_journals.id'])
+ ;
+
+ foreach ($set as $entry) {
+ try {
+ /** @var null|TransactionJournal $journal */
+ $journal = TransactionJournal::find($entry->id);
+ $journal?->delete();
+ } catch (QueryException $e) {
+ Log::info(sprintf('Could not delete entry: %s', $e->getMessage()));
+ Log::error($e->getTraceAsString());
+ }
+
+ $this->friendlyInfo(sprintf('Deleted empty transaction journal #%d', $entry->id));
+ ++$count;
+ }
+ }
+
/**
* Delete transactions and their journals if they have an uneven number of transactions.
*/
@@ -85,28 +109,4 @@ class RemovesEmptyJournals extends Command
}
}
}
-
- private function deleteEmptyJournals(): void
- {
- $count = 0;
- $set = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
- ->groupBy('transaction_journals.id')
- ->whereNull('transactions.transaction_journal_id')
- ->get(['transaction_journals.id'])
- ;
-
- foreach ($set as $entry) {
- try {
- /** @var null|TransactionJournal $journal */
- $journal = TransactionJournal::find($entry->id);
- $journal?->delete();
- } catch (QueryException $e) {
- Log::info(sprintf('Could not delete entry: %s', $e->getMessage()));
- Log::error($e->getTraceAsString());
- }
-
- $this->friendlyInfo(sprintf('Deleted empty transaction journal #%d', $entry->id));
- ++$count;
- }
- }
}
diff --git a/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php b/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php
index a0e6b86413..b8710df663 100644
--- a/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php
+++ b/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php
@@ -95,11 +95,19 @@ class RemovesLinksToDeletedObjects extends Command
$this->friendlyNeutral('Validated links to deleted objects.');
}
- private function cleanupTags(array $tags): void
+ private function cleanupBudgets(array $budgets): void
{
- $count = DB::table('tag_transaction_journal')->whereIn('tag_id', $tags)->delete();
+ $count = DB::table('budget_transaction_journal')->whereIn('budget_id', $budgets)->delete();
if ($count > 0) {
- $this->friendlyInfo(sprintf('Removed %d old relationship(s) categories transactions and tags.', $count));
+ $this->friendlyInfo(sprintf('Removed %d old relationship(s) between budgets and transactions.', $count));
+ }
+ }
+
+ private function cleanupCategories(array $categories): void
+ {
+ $count = DB::table('category_transaction_journal')->whereIn('category_id', $categories)->delete();
+ if ($count > 0) {
+ $this->friendlyInfo(sprintf('Removed %d old relationship(s) categories categories and transactions.', $count));
}
}
@@ -127,19 +135,11 @@ class RemovesLinksToDeletedObjects extends Command
}
}
- private function cleanupBudgets(array $budgets): void
- {
- $count = DB::table('budget_transaction_journal')->whereIn('budget_id', $budgets)->delete();
- if ($count > 0) {
- $this->friendlyInfo(sprintf('Removed %d old relationship(s) between budgets and transactions.', $count));
- }
- }
-
- private function cleanupCategories(array $categories): void
+ private function cleanupTags(array $tags): void
{
- $count = DB::table('category_transaction_journal')->whereIn('category_id', $categories)->delete();
+ $count = DB::table('tag_transaction_journal')->whereIn('tag_id', $tags)->delete();
if ($count > 0) {
- $this->friendlyInfo(sprintf('Removed %d old relationship(s) categories categories and transactions.', $count));
+ $this->friendlyInfo(sprintf('Removed %d old relationship(s) categories transactions and tags.', $count));
}
}
}
diff --git a/app/Console/Commands/Correction/RemovesOrphanedTransactions.php b/app/Console/Commands/Correction/RemovesOrphanedTransactions.php
index 7f005aeedc..7ca6ef47e4 100644
--- a/app/Console/Commands/Correction/RemovesOrphanedTransactions.php
+++ b/app/Console/Commands/Correction/RemovesOrphanedTransactions.php
@@ -56,6 +56,27 @@ class RemovesOrphanedTransactions extends Command
return 0;
}
+ private function deleteFromOrphanedAccounts(): void
+ {
+ $set = Transaction::leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id')->whereNotNull('accounts.deleted_at')->get(['transactions.*']);
+ $count = 0;
+
+ /** @var Transaction $transaction */
+ foreach ($set as $transaction) {
+ // delete journals
+ /** @var null|TransactionJournal $journal */
+ $journal = TransactionJournal::find($transaction->transaction_journal_id);
+ $journal?->delete();
+ Transaction::where('transaction_journal_id', $transaction->transaction_journal_id)->delete();
+ $this->friendlyWarning(sprintf(
+ 'Deleted transaction journal #%d because account #%d was already deleted.',
+ $transaction->transaction_journal_id,
+ $transaction->account_id
+ ));
+ ++$count;
+ }
+ }
+
private function deleteOrphanedJournals(): void
{
$set = TransactionJournal::leftJoin('transaction_groups', 'transaction_journals.transaction_group_id', 'transaction_groups.id')
@@ -111,25 +132,4 @@ class RemovesOrphanedTransactions extends Command
}
}
}
-
- private function deleteFromOrphanedAccounts(): void
- {
- $set = Transaction::leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id')->whereNotNull('accounts.deleted_at')->get(['transactions.*']);
- $count = 0;
-
- /** @var Transaction $transaction */
- foreach ($set as $transaction) {
- // delete journals
- /** @var null|TransactionJournal $journal */
- $journal = TransactionJournal::find($transaction->transaction_journal_id);
- $journal?->delete();
- Transaction::where('transaction_journal_id', $transaction->transaction_journal_id)->delete();
- $this->friendlyWarning(sprintf(
- 'Deleted transaction journal #%d because account #%d was already deleted.',
- $transaction->transaction_journal_id,
- $transaction->account_id
- ));
- ++$count;
- }
- }
}
diff --git a/app/Console/Commands/Correction/RestoresOAuthKeys.php b/app/Console/Commands/Correction/RestoresOAuthKeys.php
index 8d23a405f2..3d2c856555 100644
--- a/app/Console/Commands/Correction/RestoresOAuthKeys.php
+++ b/app/Console/Commands/Correction/RestoresOAuthKeys.php
@@ -48,6 +48,26 @@ class RestoresOAuthKeys extends Command
return 0;
}
+ private function generateKeys(): void
+ {
+ OAuthKeys::generateKeys();
+ }
+
+ private function keysInDatabase(): bool
+ {
+ return OAuthKeys::keysInDatabase();
+ }
+
+ private function keysOnDrive(): bool
+ {
+ return OAuthKeys::hasKeyFiles();
+ }
+
+ private function restoreKeysFromDB(): bool
+ {
+ return OAuthKeys::restoreKeysFromDB();
+ }
+
private function restoreOAuthKeys(): void
{
if (!$this->keysInDatabase() && !$this->keysOnDrive()) {
@@ -76,28 +96,8 @@ class RestoresOAuthKeys extends Command
}
}
- private function keysInDatabase(): bool
- {
- return OAuthKeys::keysInDatabase();
- }
-
- private function keysOnDrive(): bool
- {
- return OAuthKeys::hasKeyFiles();
- }
-
- private function generateKeys(): void
- {
- OAuthKeys::generateKeys();
- }
-
private function storeKeysInDB(): void
{
OAuthKeys::storeKeysInDB();
}
-
- private function restoreKeysFromDB(): bool
- {
- return OAuthKeys::restoreKeysFromDB();
- }
}
diff --git a/app/Console/Commands/Correction/TriggersCreditCalculation.php b/app/Console/Commands/Correction/TriggersCreditCalculation.php
index f99b762cd6..07c9d66984 100644
--- a/app/Console/Commands/Correction/TriggersCreditCalculation.php
+++ b/app/Console/Commands/Correction/TriggersCreditCalculation.php
@@ -43,6 +43,14 @@ class TriggersCreditCalculation extends Command
return 0;
}
+ private function processAccount(Account $account): void
+ {
+ /** @var CreditRecalculateService $object */
+ $object = app(CreditRecalculateService::class);
+ $object->setAccount($account);
+ $object->recalculate();
+ }
+
private function processAccounts(): void
{
$accounts = Account::leftJoin('account_types', 'accounts.account_type_id', 'account_types.id')->whereIn(
@@ -53,12 +61,4 @@ class TriggersCreditCalculation extends Command
$this->processAccount($account);
}
}
-
- private function processAccount(Account $account): void
- {
- /** @var CreditRecalculateService $object */
- $object = app(CreditRecalculateService::class);
- $object->setAccount($account);
- $object->recalculate();
- }
}
diff --git a/app/Console/Commands/Export/ExportsData.php b/app/Console/Commands/Export/ExportsData.php
index 2a9b55292c..736ae1f882 100644
--- a/app/Console/Commands/Export/ExportsData.php
+++ b/app/Console/Commands/Export/ExportsData.php
@@ -134,45 +134,55 @@ class ExportsData extends Command
}
/**
- * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
- * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
- * be called from the handle method instead of using the constructor to initialize the command.
+ * @throws FireflyException
+ * @throws FilesystemException
*/
- private function stupidLaravel(): void
+ private function exportData(array $options, array $data): void
{
- $this->journalRepository = app(JournalRepositoryInterface::class);
- $this->accountRepository = app(AccountRepositoryInterface::class);
+ $date = Carbon::now()->format('Y_m_d');
+ foreach ($data as $key => $content) {
+ $file = sprintf('%s%s_%s.csv', $options['directory'], $date, $key);
+ if (false === $options['force'] && file_exists($file)) {
+ throw new FireflyException(sprintf('File "%s" exists already. Use --force to overwrite.', $file));
+ }
+ if (true === $options['force'] && file_exists($file)) {
+ $this->friendlyWarning(sprintf('File "%s" exists already but will be replaced.', $file));
+ }
+ // continue to write to file.
+ file_put_contents($file, $content);
+ $this->friendlyPositive(sprintf('Wrote %s-export to file "%s".', $key, $file));
+ }
}
/**
* @throws FireflyException
- * @throws Exception
*/
- private function parseOptions(): array
+ private function getAccountsParameter(): Collection
{
- $start = $this->getDateParameter('start');
- $end = $this->getDateParameter('end');
- $accounts = $this->getAccountsParameter();
- $export = $this->getExportDirectory();
+ $final = new Collection();
+ $accounts = new Collection();
+ $accountList = (string) $this->option('accounts');
+ $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
+ if ('' !== $accountList) {
+ $accountIds = explode(',', $accountList);
+ $accounts = $this->accountRepository->getAccountsById($accountIds);
+ }
+ if ('' === $accountList) {
+ $accounts = $this->accountRepository->getAccountsByType($types);
+ }
- return [
- 'export' => [
- 'transactions' => $this->option('export-transactions'),
- 'accounts' => $this->option('export-accounts'),
- 'budgets' => $this->option('export-budgets'),
- 'categories' => $this->option('export-categories'),
- 'tags' => $this->option('export-tags'),
- 'recurring' => $this->option('export-recurring'),
- 'rules' => $this->option('export-rules'),
- 'bills' => $this->option('export-subscriptions'),
- 'piggies' => $this->option('export-piggies'),
- ],
- 'start' => $start,
- 'end' => $end,
- 'accounts' => $accounts,
- 'directory' => $export,
- 'force' => $this->option('force'),
- ];
+ // filter accounts,
+ /** @var Account $account */
+ foreach ($accounts as $account) {
+ if (in_array($account->accountType->type, $types, true)) {
+ $final->push($account);
+ }
+ }
+ if (0 === $final->count()) {
+ throw new FireflyException('300007: Ended up with zero valid accounts to export from.');
+ }
+
+ return $final;
}
/**
@@ -228,37 +238,6 @@ class ExportsData extends Command
return $date;
}
- /**
- * @throws FireflyException
- */
- private function getAccountsParameter(): Collection
- {
- $final = new Collection();
- $accounts = new Collection();
- $accountList = (string) $this->option('accounts');
- $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
- if ('' !== $accountList) {
- $accountIds = explode(',', $accountList);
- $accounts = $this->accountRepository->getAccountsById($accountIds);
- }
- if ('' === $accountList) {
- $accounts = $this->accountRepository->getAccountsByType($types);
- }
-
- // filter accounts,
- /** @var Account $account */
- foreach ($accounts as $account) {
- if (in_array($account->accountType->type, $types, true)) {
- $final->push($account);
- }
- }
- if (0 === $final->count()) {
- throw new FireflyException('300007: Ended up with zero valid accounts to export from.');
- }
-
- return $final;
- }
-
/**
* @throws FireflyException
*/
@@ -277,22 +256,43 @@ class ExportsData extends Command
/**
* @throws FireflyException
- * @throws FilesystemException
+ * @throws Exception
*/
- private function exportData(array $options, array $data): void
+ private function parseOptions(): array
{
- $date = Carbon::now()->format('Y_m_d');
- foreach ($data as $key => $content) {
- $file = sprintf('%s%s_%s.csv', $options['directory'], $date, $key);
- if (false === $options['force'] && file_exists($file)) {
- throw new FireflyException(sprintf('File "%s" exists already. Use --force to overwrite.', $file));
- }
- if (true === $options['force'] && file_exists($file)) {
- $this->friendlyWarning(sprintf('File "%s" exists already but will be replaced.', $file));
- }
- // continue to write to file.
- file_put_contents($file, $content);
- $this->friendlyPositive(sprintf('Wrote %s-export to file "%s".', $key, $file));
- }
+ $start = $this->getDateParameter('start');
+ $end = $this->getDateParameter('end');
+ $accounts = $this->getAccountsParameter();
+ $export = $this->getExportDirectory();
+
+ return [
+ 'export' => [
+ 'transactions' => $this->option('export-transactions'),
+ 'accounts' => $this->option('export-accounts'),
+ 'budgets' => $this->option('export-budgets'),
+ 'categories' => $this->option('export-categories'),
+ 'tags' => $this->option('export-tags'),
+ 'recurring' => $this->option('export-recurring'),
+ 'rules' => $this->option('export-rules'),
+ 'bills' => $this->option('export-subscriptions'),
+ 'piggies' => $this->option('export-piggies'),
+ ],
+ 'start' => $start,
+ 'end' => $end,
+ 'accounts' => $accounts,
+ 'directory' => $export,
+ 'force' => $this->option('force'),
+ ];
+ }
+
+ /**
+ * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
+ * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
+ * be called from the handle method instead of using the constructor to initialize the command.
+ */
+ private function stupidLaravel(): void
+ {
+ $this->journalRepository = app(JournalRepositoryInterface::class);
+ $this->accountRepository = app(AccountRepositoryInterface::class);
}
}
diff --git a/app/Console/Commands/Integrity/ReportsEmptyObjects.php b/app/Console/Commands/Integrity/ReportsEmptyObjects.php
index b234d646c7..2dda07a5e2 100644
--- a/app/Console/Commands/Integrity/ReportsEmptyObjects.php
+++ b/app/Console/Commands/Integrity/ReportsEmptyObjects.php
@@ -54,6 +54,45 @@ class ReportsEmptyObjects extends Command
return 0;
}
+ /**
+ * Reports on accounts with no transactions.
+ */
+ private function reportAccounts(): void
+ {
+ $set = Account::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id')
+ ->leftJoin('users', 'accounts.user_id', '=', 'users.id')
+ ->groupBy(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email'])
+ ->whereNull('transactions.account_id')
+ ->get(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email'])
+ ;
+
+ /** @var stdClass $entry */
+ foreach ($set as $entry) {
+ $line = 'User #%d (%s) has account #%d ("%s") which has no transactions.';
+ $line = sprintf($line, $entry->user_id, $entry->email, $entry->id, $entry->name);
+ $this->friendlyWarning($line);
+ }
+ }
+
+ /**
+ * Reports on budgets with no budget limits (which makes them pointless).
+ */
+ private function reportBudgetLimits(): void
+ {
+ $set = Budget::leftJoin('budget_limits', 'budget_limits.budget_id', '=', 'budgets.id')
+ ->leftJoin('users', 'budgets.user_id', '=', 'users.id')
+ ->groupBy(['budgets.id', 'budgets.name', 'budgets.encrypted', 'budgets.user_id', 'users.email'])
+ ->whereNull('budget_limits.id')
+ ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'budgets.encrypted', 'users.email'])
+ ;
+
+ /** @var Budget $entry */
+ foreach ($set as $entry) {
+ $line = sprintf('User #%d (%s) has budget #%d ("%s") which has no budget limits.', $entry->user_id, $entry->email, $entry->id, $entry->name);
+ $this->friendlyWarning($line);
+ }
+ }
+
/**
* Report on budgets with no transactions or journals.
*/
@@ -110,43 +149,4 @@ class ReportsEmptyObjects extends Command
$this->friendlyWarning($line);
}
}
-
- /**
- * Reports on accounts with no transactions.
- */
- private function reportAccounts(): void
- {
- $set = Account::leftJoin('transactions', 'transactions.account_id', '=', 'accounts.id')
- ->leftJoin('users', 'accounts.user_id', '=', 'users.id')
- ->groupBy(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email'])
- ->whereNull('transactions.account_id')
- ->get(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email'])
- ;
-
- /** @var stdClass $entry */
- foreach ($set as $entry) {
- $line = 'User #%d (%s) has account #%d ("%s") which has no transactions.';
- $line = sprintf($line, $entry->user_id, $entry->email, $entry->id, $entry->name);
- $this->friendlyWarning($line);
- }
- }
-
- /**
- * Reports on budgets with no budget limits (which makes them pointless).
- */
- private function reportBudgetLimits(): void
- {
- $set = Budget::leftJoin('budget_limits', 'budget_limits.budget_id', '=', 'budgets.id')
- ->leftJoin('users', 'budgets.user_id', '=', 'users.id')
- ->groupBy(['budgets.id', 'budgets.name', 'budgets.encrypted', 'budgets.user_id', 'users.email'])
- ->whereNull('budget_limits.id')
- ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'budgets.encrypted', 'users.email'])
- ;
-
- /** @var Budget $entry */
- foreach ($set as $entry) {
- $line = sprintf('User #%d (%s) has budget #%d ("%s") which has no budget limits.', $entry->user_id, $entry->email, $entry->id, $entry->name);
- $this->friendlyWarning($line);
- }
- }
}
diff --git a/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php b/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php
index 820250d252..d77b8ff2a6 100644
--- a/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php
+++ b/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php
@@ -55,6 +55,20 @@ class ValidatesEnvironmentVariables extends Command
return Command::SUCCESS;
}
+ private function validateGuard(): bool
+ {
+ $guard = config('auth.defaults.guard');
+ if ('web' !== $guard && 'remote_user_guard' !== $guard) {
+ $this->friendlyError(sprintf('AUTHENTICATION_GUARD "%s" is not a valid guard for Firefly III.', $guard));
+ $this->friendlyError('Please check your .env file and make sure you use a valid setting.');
+ $this->friendlyError('Valid guards are: web, remote_user_guard');
+
+ return false;
+ }
+
+ return true;
+ }
+
private function validateLanguage(): bool
{
$language = config('firefly.default_language');
@@ -80,20 +94,6 @@ class ValidatesEnvironmentVariables extends Command
return true;
}
- private function validateGuard(): bool
- {
- $guard = config('auth.defaults.guard');
- if ('web' !== $guard && 'remote_user_guard' !== $guard) {
- $this->friendlyError(sprintf('AUTHENTICATION_GUARD "%s" is not a valid guard for Firefly III.', $guard));
- $this->friendlyError('Please check your .env file and make sure you use a valid setting.');
- $this->friendlyError('Valid guards are: web, remote_user_guard');
-
- return false;
- }
-
- return true;
- }
-
private function validateStaticToken(): bool
{
$token = (string) config('firefly.static_cron_token');
diff --git a/app/Console/Commands/ShowsFriendlyMessages.php b/app/Console/Commands/ShowsFriendlyMessages.php
index 1046218d0f..c530226cac 100644
--- a/app/Console/Commands/ShowsFriendlyMessages.php
+++ b/app/Console/Commands/ShowsFriendlyMessages.php
@@ -39,14 +39,14 @@ trait ShowsFriendlyMessages
$this->friendlyNeutral($message);
}
- public function friendlyNeutral(string $message): void
+ public function friendlyLine(string $message): void
{
- $this->line(sprintf(' [i] %s', trim($message)));
+ $this->line(sprintf(' %s', trim($message)));
}
- public function friendlyLine(string $message): void
+ public function friendlyNeutral(string $message): void
{
- $this->line(sprintf(' %s', trim($message)));
+ $this->line(sprintf(' [i] %s', trim($message)));
}
public function friendlyPositive(string $message): void
diff --git a/app/Console/Commands/System/ForcesDecimalSize.php b/app/Console/Commands/System/ForcesDecimalSize.php
index bbd3b6637e..ab0be39b74 100644
--- a/app/Console/Commands/System/ForcesDecimalSize.php
+++ b/app/Console/Commands/System/ForcesDecimalSize.php
@@ -112,19 +112,53 @@ class ForcesDecimalSize extends Command
return 0;
}
- private function determineDatabaseType(): void
+ /**
+ * This method loops over all accounts and validates the amounts.
+ */
+ private function correctAccountAmounts(TransactionCurrency $currency, array $fields): void
{
- // switch stuff based on database connection:
- $this->operator = 'REGEXP';
- $this->regularExpression = '\'\\\.[\\\d]{%d}[1-9]+\'';
- $this->cast = 'CHAR';
- if ('pgsql' === config('database.default')) {
- $this->operator = 'SIMILAR TO';
- $this->regularExpression = '\'%%\.[\d]{%d}[1-9]+%%\'';
- $this->cast = 'TEXT';
+ $operator = $this->operator;
+ $cast = $this->cast;
+ $regularExpression = $this->regularExpression;
+
+ /** @var Builder $query */
+ $query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
+ ->where('account_meta.name', 'currency_id')
+ ->where('account_meta.data', json_encode((string) $currency->id))
+ ;
+ $query->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void {
+ foreach ($fields as $field) {
+ $q->orWhere(
+ DB::raw(sprintf('CAST(accounts.%s AS %s)', $field, $cast)),
+ $operator,
+ DB::raw(sprintf($regularExpression, $currency->decimal_places))
+ );
+ }
+ });
+ $result = $query->get(['accounts.*']);
+ if (0 === $result->count()) {
+ $this->friendlyPositive(sprintf('All accounts in %s are OK', $currency->code));
+
+ return;
}
- if ('sqlite' === config('database.default')) {
- $this->regularExpression = '"\.[\d]{%d}[1-9]+"';
+
+ /** @var Account $account */
+ foreach ($result as $account) {
+ /** @var string $field */
+ foreach ($fields as $field) {
+ $value = $account->{$field};
+ if (null === $value) {
+ continue;
+ }
+ // fix $field by rounding it down correctly.
+ $pow = 10 ** $currency->decimal_places;
+ $correct = bcdiv((string) round($value * $pow), (string) $pow, 12);
+ $this->friendlyInfo(sprintf('Account #%d has %s with value "%s", this has been corrected to "%s".', $account->id, $field, $value, $correct));
+
+ /** @var null|Account $updateAccount */
+ $updateAccount = Account::find($account->id);
+ $updateAccount?->update([$field => $correct]);
+ }
}
}
@@ -231,99 +265,101 @@ class ForcesDecimalSize extends Command
}
/**
- * This method loops over all accounts and validates the amounts.
+ * This method fixes all auto budgets in currency $currency.
*/
- private function correctAccountAmounts(TransactionCurrency $currency, array $fields): void
+ private function correctGeneric(TransactionCurrency $currency, string $table): void
{
+ $class = $this->classes[$table];
+ $fields = $this->tables[$table];
$operator = $this->operator;
$cast = $this->cast;
$regularExpression = $this->regularExpression;
/** @var Builder $query */
- $query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
- ->where('account_meta.name', 'currency_id')
- ->where('account_meta.data', json_encode((string) $currency->id))
+ $query = $class::where('transaction_currency_id', $currency->id)
+ ->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void {
+ /** @var string $field */
+ foreach ($fields as $field) {
+ $q->orWhere(DB::raw(sprintf('CAST(%s AS %s)', $field, $cast)), $operator, DB::raw(sprintf($regularExpression, $currency->decimal_places)));
+ }
+ })
;
- $query->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void {
- foreach ($fields as $field) {
- $q->orWhere(
- DB::raw(sprintf('CAST(accounts.%s AS %s)', $field, $cast)),
- $operator,
- DB::raw(sprintf($regularExpression, $currency->decimal_places))
- );
- }
- });
- $result = $query->get(['accounts.*']);
+
+ $result = $query->get();
if (0 === $result->count()) {
- $this->friendlyPositive(sprintf('All accounts in %s are OK', $currency->code));
+ $this->friendlyPositive(sprintf('All %s in %s are OK', $table, $currency->code));
return;
}
- /** @var Account $account */
- foreach ($result as $account) {
+ /** @var Model $item */
+ foreach ($result as $item) {
/** @var string $field */
foreach ($fields as $field) {
- $value = $account->{$field};
- if (null === $value) {
+ $value = $item->{$field};
+ if (null === $value || '' === $value) {
continue;
}
// fix $field by rounding it down correctly.
- $pow = 10 ** $currency->decimal_places;
- $correct = bcdiv((string) round($value * $pow), (string) $pow, 12);
- $this->friendlyInfo(sprintf('Account #%d has %s with value "%s", this has been corrected to "%s".', $account->id, $field, $value, $correct));
+ $pow = 10 ** $currency->decimal_places;
+ $correct = bcdiv((string) round($value * $pow), (string) $pow, 12);
+ $this->friendlyWarning(sprintf('%s #%d has %s with value "%s", this has been corrected to "%s".', $table, $item->id, $field, $value, $correct));
- /** @var null|Account $updateAccount */
- $updateAccount = Account::find($account->id);
- $updateAccount?->update([$field => $correct]);
+ /** @var null|Model $model */
+ $model = $class::find($item->id);
+ $model?->update([$field => $correct]);
}
}
}
/**
- * This method fixes all auto budgets in currency $currency.
+ * This method fixes all piggy banks in currency $currency.
*/
- private function correctGeneric(TransactionCurrency $currency, string $table): void
+ private function correctPiggyAmounts(TransactionCurrency $currency, array $fields): void
{
- $class = $this->classes[$table];
- $fields = $this->tables[$table];
$operator = $this->operator;
$cast = $this->cast;
$regularExpression = $this->regularExpression;
/** @var Builder $query */
- $query = $class::where('transaction_currency_id', $currency->id)
+ $query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
+ ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
+ ->where('account_meta.name', 'currency_id')
+ ->where('account_meta.data', json_encode((string) $currency->id))
->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void {
- /** @var string $field */
foreach ($fields as $field) {
- $q->orWhere(DB::raw(sprintf('CAST(%s AS %s)', $field, $cast)), $operator, DB::raw(sprintf($regularExpression, $currency->decimal_places)));
+ $q->orWhere(
+ DB::raw(sprintf('CAST(piggy_banks.%s AS %s)', $field, $cast)),
+ $operator,
+ DB::raw(sprintf($regularExpression, $currency->decimal_places))
+ );
}
})
;
- $result = $query->get();
+ $result = $query->get(['piggy_banks.*']);
if (0 === $result->count()) {
- $this->friendlyPositive(sprintf('All %s in %s are OK', $table, $currency->code));
+ $this->friendlyPositive(sprintf('All piggy banks in %s are OK', $currency->code));
return;
}
- /** @var Model $item */
+ /** @var PiggyBank $item */
foreach ($result as $item) {
/** @var string $field */
foreach ($fields as $field) {
- $value = $item->{$field};
- if (null === $value || '' === $value) {
+ $value = $item->{$field};
+ if (null === $value) {
continue;
}
// fix $field by rounding it down correctly.
- $pow = 10 ** $currency->decimal_places;
- $correct = bcdiv((string) round($value * $pow), (string) $pow, 12);
- $this->friendlyWarning(sprintf('%s #%d has %s with value "%s", this has been corrected to "%s".', $table, $item->id, $field, $value, $correct));
+ $pow = 10 ** $currency->decimal_places;
+ $correct = bcdiv((string) round($value * $pow), (string) $pow, 12);
+ $this->friendlyWarning(sprintf('Piggy bank #%d has %s with value "%s", this has been corrected to "%s".', $item->id, $field, $value, $correct));
- /** @var null|Model $model */
- $model = $class::find($item->id);
- $model?->update([$field => $correct]);
+ /** @var null|PiggyBank $piggyBank */
+ $piggyBank = PiggyBank::find($item->id);
+ $piggyBank?->update([$field => $correct]);
}
}
}
@@ -447,58 +483,6 @@ class ForcesDecimalSize extends Command
}
}
- /**
- * This method fixes all piggy banks in currency $currency.
- */
- private function correctPiggyAmounts(TransactionCurrency $currency, array $fields): void
- {
- $operator = $this->operator;
- $cast = $this->cast;
- $regularExpression = $this->regularExpression;
-
- /** @var Builder $query */
- $query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id')
- ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id')
- ->where('account_meta.name', 'currency_id')
- ->where('account_meta.data', json_encode((string) $currency->id))
- ->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void {
- foreach ($fields as $field) {
- $q->orWhere(
- DB::raw(sprintf('CAST(piggy_banks.%s AS %s)', $field, $cast)),
- $operator,
- DB::raw(sprintf($regularExpression, $currency->decimal_places))
- );
- }
- })
- ;
-
- $result = $query->get(['piggy_banks.*']);
- if (0 === $result->count()) {
- $this->friendlyPositive(sprintf('All piggy banks in %s are OK', $currency->code));
-
- return;
- }
-
- /** @var PiggyBank $item */
- foreach ($result as $item) {
- /** @var string $field */
- foreach ($fields as $field) {
- $value = $item->{$field};
- if (null === $value) {
- continue;
- }
- // fix $field by rounding it down correctly.
- $pow = 10 ** $currency->decimal_places;
- $correct = bcdiv((string) round($value * $pow), (string) $pow, 12);
- $this->friendlyWarning(sprintf('Piggy bank #%d has %s with value "%s", this has been corrected to "%s".', $item->id, $field, $value, $correct));
-
- /** @var null|PiggyBank $piggyBank */
- $piggyBank = PiggyBank::find($item->id);
- $piggyBank?->update([$field => $correct]);
- }
- }
- }
-
/**
* This method fixes all transactions in currency $currency.
*/
@@ -570,6 +554,22 @@ class ForcesDecimalSize extends Command
}
}
+ private function determineDatabaseType(): void
+ {
+ // switch stuff based on database connection:
+ $this->operator = 'REGEXP';
+ $this->regularExpression = '\'\\\.[\\\d]{%d}[1-9]+\'';
+ $this->cast = 'CHAR';
+ if ('pgsql' === config('database.default')) {
+ $this->operator = 'SIMILAR TO';
+ $this->regularExpression = '\'%%\.[\d]{%d}[1-9]+%%\'';
+ $this->cast = 'TEXT';
+ }
+ if ('sqlite' === config('database.default')) {
+ $this->regularExpression = '"\.[\d]{%d}[1-9]+"';
+ }
+ }
+
private function updateDecimals(): void
{
$this->friendlyInfo('Going to force the size of DECIMAL columns. Please hold.');
diff --git a/app/Console/Commands/System/OutputsInstructions.php b/app/Console/Commands/System/OutputsInstructions.php
index 8f8c47317a..ad6bc7444b 100644
--- a/app/Console/Commands/System/OutputsInstructions.php
+++ b/app/Console/Commands/System/OutputsInstructions.php
@@ -56,14 +56,43 @@ class OutputsInstructions extends Command
}
/**
- * Render upgrade instructions.
+ * Show a nice box.
*/
- private function updateInstructions(): void
+ private function boxed(string $text): void
+ {
+ $parts = explode("\n", wordwrap($text));
+ foreach ($parts as $string) {
+ $this->line('| '.sprintf('%-77s', $string).'|');
+ }
+ }
+
+ /**
+ * Show a nice info box.
+ */
+ private function boxedInfo(string $text): void
+ {
+ $parts = explode("\n", wordwrap($text));
+ foreach ($parts as $string) {
+ $this->info('| '.sprintf('%-77s', $string).'|');
+ }
+ }
+
+ private function donationText(): void
+ {
+ $this->boxed('Did you know you can support the development of Firefly III?');
+ $this->boxed('You can donate in many ways, like GitHub Sponsors or Patreon.');
+ $this->boxed('For more information, please visit https://bit.ly/donate-to-Firefly-III');
+ }
+
+ /**
+ * Render instructions.
+ */
+ private function installInstructions(): void
{
$version = (string) config('firefly.version');
/** @var array $config */
- $config = config('upgrade.text.upgrade');
+ $config = config('upgrade.text.install');
$text = '';
/** @var string $compare */
@@ -80,20 +109,18 @@ class OutputsInstructions extends Command
}
$prefix = 'v';
- if (str_starts_with($version, 'develop') || str_starts_with($version, 'branch')) {
+ if (str_starts_with($version, 'develop')) {
$prefix = '';
}
$this->newLine();
$this->showLogo();
$this->newLine();
- $this->newLine();
$this->showLine();
-
$this->boxed('');
if ('' === $text) {
- $this->boxed(sprintf('Thank you for updating to Firefly III, %s%s', $prefix, $version));
- $this->boxedInfo('There are no extra upgrade instructions.');
+ $this->boxed(sprintf('Thank you for installing Firefly III, %s%s!', $prefix, $version));
+ $this->boxedInfo('There are no extra installation instructions.');
$this->boxed('Firefly III should be ready for use.');
$this->boxed('');
$this->donationText();
@@ -103,7 +130,7 @@ class OutputsInstructions extends Command
return;
}
- $this->boxed(sprintf('Thank you for updating to Firefly III, %s%s!', $prefix, $version));
+ $this->boxed(sprintf('Thank you for installing Firefly III, %s%s!', $prefix, $version));
$this->boxedInfo($text);
$this->boxed('');
$this->donationText();
@@ -111,6 +138,14 @@ class OutputsInstructions extends Command
$this->showLine();
}
+ /**
+ * Show a line.
+ */
+ private function showLine(): void
+ {
+ $this->line(sprintf('+%s+', str_repeat('-', 78)));
+ }
+
/**
* The logo takes up 8 lines of code. So 8 colors can be used.
*/
@@ -151,52 +186,47 @@ class OutputsInstructions extends Command
$this->someQuote();
}
- /**
- * Show a line.
- */
- private function showLine(): void
+ private function someQuote(): void
{
- $this->line(sprintf('+%s+', str_repeat('-', 78)));
- }
+ $lines = [
+ '"Forgive yourself for not being at peace."',
+ '"Doesn\'t look like anything to me."',
+ '"Be proud of what you make."',
+ '"Be there or forever wonder."',
+ '"A year from now you will wish you had started today."',
+ '🇺🇦 Слава Україні!',
+ '🇺🇦 Slava Ukraini!',
+ ];
- /**
- * Show a nice box.
- */
- private function boxed(string $text): void
- {
- $parts = explode("\n", wordwrap($text));
- foreach ($parts as $string) {
- $this->line('| '.sprintf('%-77s', $string).'|');
- }
- }
+ // fuck the Russian aggression in Ukraine.
- /**
- * Show a nice info box.
- */
- private function boxedInfo(string $text): void
- {
- $parts = explode("\n", wordwrap($text));
- foreach ($parts as $string) {
- $this->info('| '.sprintf('%-77s', $string).'|');
+ // There is no point even trying to be neutral, because you can’t. When I say you can’t be neutral on
+ // a moving train, it means the world is already moving in certain directions. Children are going
+ // hungry, wars are taking place. In a situation like that, to be neutral or to try to be neutral,
+ // to stand aside, not to take a stand, not to participate, is to collaborate with whatever is
+ // going on, to allow that to happen.
+
+ if ('ru_RU' === config('firefly.default_language')) {
+ $lines = ['🇺🇦 Слава Україні!', '🇺🇦 Slava Ukraini!'];
}
- }
- private function donationText(): void
- {
- $this->boxed('Did you know you can support the development of Firefly III?');
- $this->boxed('You can donate in many ways, like GitHub Sponsors or Patreon.');
- $this->boxed('For more information, please visit https://bit.ly/donate-to-Firefly-III');
+ try {
+ $random = random_int(0, count($lines) - 1);
+ } catch (RandomException) {
+ $random = 0;
+ }
+ $this->line(sprintf(' %s', $lines[$random]));
}
/**
- * Render instructions.
+ * Render upgrade instructions.
*/
- private function installInstructions(): void
+ private function updateInstructions(): void
{
$version = (string) config('firefly.version');
/** @var array $config */
- $config = config('upgrade.text.install');
+ $config = config('upgrade.text.upgrade');
$text = '';
/** @var string $compare */
@@ -213,18 +243,20 @@ class OutputsInstructions extends Command
}
$prefix = 'v';
- if (str_starts_with($version, 'develop')) {
+ if (str_starts_with($version, 'develop') || str_starts_with($version, 'branch')) {
$prefix = '';
}
$this->newLine();
$this->showLogo();
$this->newLine();
+ $this->newLine();
$this->showLine();
+
$this->boxed('');
if ('' === $text) {
- $this->boxed(sprintf('Thank you for installing Firefly III, %s%s!', $prefix, $version));
- $this->boxedInfo('There are no extra installation instructions.');
+ $this->boxed(sprintf('Thank you for updating to Firefly III, %s%s', $prefix, $version));
+ $this->boxedInfo('There are no extra upgrade instructions.');
$this->boxed('Firefly III should be ready for use.');
$this->boxed('');
$this->donationText();
@@ -234,43 +266,11 @@ class OutputsInstructions extends Command
return;
}
- $this->boxed(sprintf('Thank you for installing Firefly III, %s%s!', $prefix, $version));
+ $this->boxed(sprintf('Thank you for updating to Firefly III, %s%s!', $prefix, $version));
$this->boxedInfo($text);
$this->boxed('');
$this->donationText();
$this->boxed('');
$this->showLine();
}
-
- private function someQuote(): void
- {
- $lines = [
- '"Forgive yourself for not being at peace."',
- '"Doesn\'t look like anything to me."',
- '"Be proud of what you make."',
- '"Be there or forever wonder."',
- '"A year from now you will wish you had started today."',
- '🇺🇦 Слава Україні!',
- '🇺🇦 Slava Ukraini!',
- ];
-
- // fuck the Russian aggression in Ukraine.
-
- // There is no point even trying to be neutral, because you can’t. When I say you can’t be neutral on
- // a moving train, it means the world is already moving in certain directions. Children are going
- // hungry, wars are taking place. In a situation like that, to be neutral or to try to be neutral,
- // to stand aside, not to take a stand, not to participate, is to collaborate with whatever is
- // going on, to allow that to happen.
-
- if ('ru_RU' === config('firefly.default_language')) {
- $lines = ['🇺🇦 Слава Україні!', '🇺🇦 Slava Ukraini!'];
- }
-
- try {
- $random = random_int(0, count($lines) - 1);
- } catch (RandomException) {
- $random = 0;
- }
- $this->line(sprintf(' %s', $lines[$random]));
- }
}
diff --git a/app/Console/Commands/Tools/ApplyRules.php b/app/Console/Commands/Tools/ApplyRules.php
index 5685ec6593..4f487c0cc2 100644
--- a/app/Console/Commands/Tools/ApplyRules.php
+++ b/app/Console/Commands/Tools/ApplyRules.php
@@ -140,6 +140,44 @@ class ApplyRules extends Command
return 0;
}
+ private function getRulesToApply(): Collection
+ {
+ Log::debug('getRulesToApply()');
+ $rulesToApply = new Collection();
+
+ /** @var RuleGroup $group */
+ foreach ($this->groups as $group) {
+ Log::debug(sprintf('Scanning rule group #%d', $group->id));
+ $rules = $this->ruleGroupRepository->getActiveStoreRules($group);
+
+ /** @var Rule $rule */
+ foreach ($rules as $rule) {
+ // if in rule selection, or group in selection or all rules, it's included.
+ $test = $this->includeRule($rule, $group);
+ if ($test) {
+ Log::debug(sprintf('Will include rule #%d "%s"', $rule->id, $rule->title));
+ $rulesToApply->push($rule);
+ }
+ if (!$test) {
+ Log::debug(sprintf('Will not include rule #%d', $rule->id));
+ }
+ }
+ }
+ Log::debug(sprintf('Found %d rules to apply.', $rulesToApply->count()));
+
+ return $rulesToApply;
+ }
+
+ private function grabAllRules(): void
+ {
+ $this->groups = $this->ruleGroupRepository->getActiveGroups();
+ }
+
+ private function includeRule(Rule $rule, RuleGroup $group): bool
+ {
+ return in_array((int) $group->id, $this->ruleGroupSelection, true) || in_array((int) $rule->id, $this->ruleSelection, true) || $this->allRules;
+ }
+
/**
* Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
* executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
@@ -234,6 +272,47 @@ class ApplyRules extends Command
return true;
}
+ /**
+ * @throws FireflyException
+ */
+ private function verifyInputDates(): void
+ {
+ // parse start date.
+ $inputStart = today(config('app.timezone'))->startOfMonth();
+ $startString = $this->option('start_date');
+ if (null === $startString) {
+ /** @var JournalRepositoryInterface $repository */
+ $repository = app(JournalRepositoryInterface::class);
+ $repository->setUser($this->getUser());
+ $first = $repository->firstNull();
+ if (null !== $first) {
+ $inputStart = $first->date;
+ }
+ }
+ if (null !== $startString && '' !== $startString) {
+ $inputStart = Carbon::createFromFormat('Y-m-d', $startString);
+ }
+
+ // parse end date
+ $inputEnd = today(config('app.timezone'));
+ $endString = $this->option('end_date');
+ if (null !== $endString && '' !== $endString) {
+ $inputEnd = Carbon::createFromFormat('Y-m-d', $endString);
+ }
+ if (!$inputEnd instanceof Carbon || null === $inputStart) {
+ Log::error('Could not parse start or end date in verifyInputDate().');
+
+ return;
+ }
+
+ if ($inputStart > $inputEnd) {
+ [$inputEnd, $inputStart] = [$inputStart, $inputEnd];
+ }
+
+ $this->startDate = $inputStart;
+ $this->endDate = $inputEnd;
+ }
+
private function verifyInputRuleGroups(): bool
{
$ruleGroupString = $this->option('rule_groups');
@@ -302,83 +381,4 @@ class ApplyRules extends Command
return true;
}
-
- /**
- * @throws FireflyException
- */
- private function verifyInputDates(): void
- {
- // parse start date.
- $inputStart = today(config('app.timezone'))->startOfMonth();
- $startString = $this->option('start_date');
- if (null === $startString) {
- /** @var JournalRepositoryInterface $repository */
- $repository = app(JournalRepositoryInterface::class);
- $repository->setUser($this->getUser());
- $first = $repository->firstNull();
- if (null !== $first) {
- $inputStart = $first->date;
- }
- }
- if (null !== $startString && '' !== $startString) {
- $inputStart = Carbon::createFromFormat('Y-m-d', $startString);
- }
-
- // parse end date
- $inputEnd = today(config('app.timezone'));
- $endString = $this->option('end_date');
- if (null !== $endString && '' !== $endString) {
- $inputEnd = Carbon::createFromFormat('Y-m-d', $endString);
- }
- if (!$inputEnd instanceof Carbon || null === $inputStart) {
- Log::error('Could not parse start or end date in verifyInputDate().');
-
- return;
- }
-
- if ($inputStart > $inputEnd) {
- [$inputEnd, $inputStart] = [$inputStart, $inputEnd];
- }
-
- $this->startDate = $inputStart;
- $this->endDate = $inputEnd;
- }
-
- private function grabAllRules(): void
- {
- $this->groups = $this->ruleGroupRepository->getActiveGroups();
- }
-
- private function getRulesToApply(): Collection
- {
- Log::debug('getRulesToApply()');
- $rulesToApply = new Collection();
-
- /** @var RuleGroup $group */
- foreach ($this->groups as $group) {
- Log::debug(sprintf('Scanning rule group #%d', $group->id));
- $rules = $this->ruleGroupRepository->getActiveStoreRules($group);
-
- /** @var Rule $rule */
- foreach ($rules as $rule) {
- // if in rule selection, or group in selection or all rules, it's included.
- $test = $this->includeRule($rule, $group);
- if ($test) {
- Log::debug(sprintf('Will include rule #%d "%s"', $rule->id, $rule->title));
- $rulesToApply->push($rule);
- }
- if (!$test) {
- Log::debug(sprintf('Will not include rule #%d', $rule->id));
- }
- }
- }
- Log::debug(sprintf('Found %d rules to apply.', $rulesToApply->count()));
-
- return $rulesToApply;
- }
-
- private function includeRule(Rule $rule, RuleGroup $group): bool
- {
- return in_array((int) $group->id, $this->ruleGroupSelection, true) || in_array((int) $rule->id, $this->ruleSelection, true) || $this->allRules;
- }
}
diff --git a/app/Console/Commands/Tools/Cron.php b/app/Console/Commands/Tools/Cron.php
index 184b6eed5d..0588491877 100644
--- a/app/Console/Commands/Tools/Cron.php
+++ b/app/Console/Commands/Tools/Cron.php
@@ -142,26 +142,25 @@ class Cron extends Command
return 0;
}
- private function exchangeRatesCronJob(bool $force, ?Carbon $date): void
+ private function autoBudgetCronJob(bool $force, ?Carbon $date): void
{
- Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__));
- $exchangeRates = new ExchangeRatesCronjob();
- $exchangeRates->setForce($force);
+ $autoBudget = new AutoBudgetCronjob();
+ $autoBudget->setForce($force);
// set date in cron job:
if ($date instanceof Carbon) {
- $exchangeRates->setDate($date);
+ $autoBudget->setDate($date);
}
- $exchangeRates->fire();
+ $autoBudget->fire();
- if ($exchangeRates->jobErrored) {
- $this->friendlyError(sprintf('Error in "exchange rates" cron: %s', $exchangeRates->message));
+ if ($autoBudget->jobErrored) {
+ $this->friendlyError(sprintf('Error in "create auto budgets" cron: %s', $autoBudget->message));
}
- if ($exchangeRates->jobFired) {
- $this->friendlyInfo(sprintf('"Exchange rates" cron fired: %s', $exchangeRates->message));
+ if ($autoBudget->jobFired) {
+ $this->friendlyInfo(sprintf('"Create auto budgets" cron fired: %s', $autoBudget->message));
}
- if ($exchangeRates->jobSucceeded) {
- $this->friendlyPositive(sprintf('"Exchange rates" cron ran with success: %s', $exchangeRates->message));
+ if ($autoBudget->jobSucceeded) {
+ $this->friendlyPositive(sprintf('"Create auto budgets" cron ran with success: %s', $autoBudget->message));
}
}
@@ -182,6 +181,29 @@ class Cron extends Command
}
}
+ private function exchangeRatesCronJob(bool $force, ?Carbon $date): void
+ {
+ Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__));
+ $exchangeRates = new ExchangeRatesCronjob();
+ $exchangeRates->setForce($force);
+ // set date in cron job:
+ if ($date instanceof Carbon) {
+ $exchangeRates->setDate($date);
+ }
+
+ $exchangeRates->fire();
+
+ if ($exchangeRates->jobErrored) {
+ $this->friendlyError(sprintf('Error in "exchange rates" cron: %s', $exchangeRates->message));
+ }
+ if ($exchangeRates->jobFired) {
+ $this->friendlyInfo(sprintf('"Exchange rates" cron fired: %s', $exchangeRates->message));
+ }
+ if ($exchangeRates->jobSucceeded) {
+ $this->friendlyPositive(sprintf('"Exchange rates" cron ran with success: %s', $exchangeRates->message));
+ }
+ }
+
/**
* @throws FireflyException
*/
@@ -207,28 +229,6 @@ class Cron extends Command
}
}
- private function autoBudgetCronJob(bool $force, ?Carbon $date): void
- {
- $autoBudget = new AutoBudgetCronjob();
- $autoBudget->setForce($force);
- // set date in cron job:
- if ($date instanceof Carbon) {
- $autoBudget->setDate($date);
- }
-
- $autoBudget->fire();
-
- if ($autoBudget->jobErrored) {
- $this->friendlyError(sprintf('Error in "create auto budgets" cron: %s', $autoBudget->message));
- }
- if ($autoBudget->jobFired) {
- $this->friendlyInfo(sprintf('"Create auto budgets" cron fired: %s', $autoBudget->message));
- }
- if ($autoBudget->jobSucceeded) {
- $this->friendlyPositive(sprintf('"Create auto budgets" cron ran with success: %s', $autoBudget->message));
- }
- }
-
/**
* @throws FireflyException
*/
diff --git a/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php
index cab149c144..6676dc04a9 100644
--- a/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php
+++ b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php
@@ -86,6 +86,44 @@ class AddsTransactionIdentifiers extends Command
return 0;
}
+ private function findOpposing(Transaction $transaction, array $exclude): ?Transaction
+ {
+ // find opposing:
+ $amount = bcmul($transaction->amount, '-1');
+
+ try {
+ /** @var Transaction $opposing */
+ $opposing = Transaction::where('transaction_journal_id', $transaction->transaction_journal_id)
+ ->where('amount', $amount)
+ ->where('identifier', '=', 0)
+ ->whereNotIn('id', $exclude)
+ ->first()
+ ;
+ } catch (QueryException $e) {
+ Log::error($e->getMessage());
+ $this->friendlyError('Firefly III could not find the "identifier" field in the "transactions" table.');
+ $this->friendlyError(sprintf('This field is required for Firefly III version %s to run.', config('firefly.version')));
+ $this->friendlyError('Please run "php artisan migrate --force" to add this field to the table.');
+ $this->friendlyError('Then, run "php artisan firefly:upgrade-database" to try again.');
+
+ return null;
+ }
+
+ return $opposing;
+ }
+
+ private function isExecuted(): bool
+ {
+ $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
+
+ return (bool) $configVar?->data;
+ }
+
+ private function markAsExecuted(): void
+ {
+ FireflyConfig::set(self::CONFIG_NAME, true);
+ }
+
/**
* Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
* executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
@@ -97,13 +135,6 @@ class AddsTransactionIdentifiers extends Command
$this->count = 0;
}
- private function isExecuted(): bool
- {
- $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
-
- return (bool) $configVar?->data;
- }
-
/**
* Grab all positive transactions from this journal that are not deleted. for each one, grab the negative opposing
* one which has 0 as an identifier and give it the same identifier.
@@ -130,35 +161,4 @@ class AddsTransactionIdentifiers extends Command
++$identifier;
}
}
-
- private function findOpposing(Transaction $transaction, array $exclude): ?Transaction
- {
- // find opposing:
- $amount = bcmul($transaction->amount, '-1');
-
- try {
- /** @var Transaction $opposing */
- $opposing = Transaction::where('transaction_journal_id', $transaction->transaction_journal_id)
- ->where('amount', $amount)
- ->where('identifier', '=', 0)
- ->whereNotIn('id', $exclude)
- ->first()
- ;
- } catch (QueryException $e) {
- Log::error($e->getMessage());
- $this->friendlyError('Firefly III could not find the "identifier" field in the "transactions" table.');
- $this->friendlyError(sprintf('This field is required for Firefly III version %s to run.', config('firefly.version')));
- $this->friendlyError('Please run "php artisan migrate --force" to add this field to the table.');
- $this->friendlyError('Then, run "php artisan firefly:upgrade-database" to try again.');
-
- return null;
- }
-
- return $opposing;
- }
-
- private function markAsExecuted(): void
- {
- FireflyConfig::set(self::CONFIG_NAME, true);
- }
}
diff --git a/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php
index b410c1fb8f..80eecc91a2 100644
--- a/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php
+++ b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php
@@ -75,41 +75,36 @@ class RemovesDatabaseDecryption extends Command
return 0;
}
- private function decryptTable(string $table, array $fields): void
+ private function decryptField(string $table, string $field): void
{
- if ($this->isDecrypted($table)) {
- return;
- }
- foreach ($fields as $field) {
- $this->decryptField($table, $field);
+ $rows = DB::table($table)->get(['id', $field]);
+
+ /** @var stdClass $row */
+ foreach ($rows as $row) {
+ $this->decryptRow($table, $field, $row);
}
- $this->friendlyPositive(sprintf('Decrypted the data in table "%s".', $table));
- // mark as decrypted:
- $configName = sprintf('is_decrypted_%s', $table);
- FireflyConfig::set($configName, true);
}
- private function isDecrypted(string $table): bool
+ private function decryptPreferencesRow(int $id, string $value): void
{
- $configName = sprintf('is_decrypted_%s', $table);
- $configVar = null;
-
+ // try to json_decrypt the value.
try {
- $configVar = FireflyConfig::get($configName, false);
- } catch (FireflyException $e) {
- Log::error($e->getMessage());
- }
-
- return (bool) $configVar?->data;
- }
+ $newValue = json_decode($value, true, 512, JSON_THROW_ON_ERROR) ?? $value;
+ } catch (JsonException $e) {
+ $message = sprintf('Could not JSON decode preference row #%d: %s. This does not have to be a problem.', $id, $e->getMessage());
+ $this->friendlyError($message);
+ Log::warning($message);
+ Log::warning($value);
+ Log::warning($e->getTraceAsString());
- private function decryptField(string $table, string $field): void
- {
- $rows = DB::table($table)->get(['id', $field]);
+ return;
+ }
- /** @var stdClass $row */
- foreach ($rows as $row) {
- $this->decryptRow($table, $field, $row);
+ /** @var null|Preference $object */
+ $object = Preference::find($id);
+ if (null !== $object) {
+ $object->data = $newValue;
+ $object->save();
}
}
@@ -143,6 +138,34 @@ class RemovesDatabaseDecryption extends Command
}
}
+ private function decryptTable(string $table, array $fields): void
+ {
+ if ($this->isDecrypted($table)) {
+ return;
+ }
+ foreach ($fields as $field) {
+ $this->decryptField($table, $field);
+ }
+ $this->friendlyPositive(sprintf('Decrypted the data in table "%s".', $table));
+ // mark as decrypted:
+ $configName = sprintf('is_decrypted_%s', $table);
+ FireflyConfig::set($configName, true);
+ }
+
+ private function isDecrypted(string $table): bool
+ {
+ $configName = sprintf('is_decrypted_%s', $table);
+ $configVar = null;
+
+ try {
+ $configVar = FireflyConfig::get($configName, false);
+ } catch (FireflyException $e) {
+ Log::error($e->getMessage());
+ }
+
+ return (bool) $configVar?->data;
+ }
+
/**
* Tries to decrypt data. Will only throw an exception when the MAC is invalid.
*
@@ -164,27 +187,4 @@ class RemovesDatabaseDecryption extends Command
return $value;
}
-
- private function decryptPreferencesRow(int $id, string $value): void
- {
- // try to json_decrypt the value.
- try {
- $newValue = json_decode($value, true, 512, JSON_THROW_ON_ERROR) ?? $value;
- } catch (JsonException $e) {
- $message = sprintf('Could not JSON decode preference row #%d: %s. This does not have to be a problem.', $id, $e->getMessage());
- $this->friendlyError($message);
- Log::warning($message);
- Log::warning($value);
- Log::warning($e->getTraceAsString());
-
- return;
- }
-
- /** @var null|Preference $object */
- $object = Preference::find($id);
- if (null !== $object) {
- $object->data = $newValue;
- $object->save();
- }
- }
}
diff --git a/app/Console/Commands/Upgrade/RepairsAccountBalances.php b/app/Console/Commands/Upgrade/RepairsAccountBalances.php
index 8651ccac38..9ed16a14c1 100644
--- a/app/Console/Commands/Upgrade/RepairsAccountBalances.php
+++ b/app/Console/Commands/Upgrade/RepairsAccountBalances.php
@@ -58,6 +58,11 @@ class RepairsAccountBalances extends Command
return 0;
}
+ private function correctBalanceAmounts(): void
+ {
+ AccountBalanceCalculator::recalculateAll(false);
+ }
+
private function isExecuted(): bool
{
$configVar = FireflyConfig::get(self::CONFIG_NAME, false);
@@ -69,9 +74,4 @@ class RepairsAccountBalances extends Command
{
FireflyConfig::set(self::CONFIG_NAME, true);
}
-
- private function correctBalanceAmounts(): void
- {
- AccountBalanceCalculator::recalculateAll(false);
- }
}
diff --git a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php
index dfed8b1d1c..cd33ccd94c 100644
--- a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php
+++ b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php
@@ -73,18 +73,6 @@ class UpgradesAccountCurrencies extends Command
return 0;
}
- /**
- * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
- * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
- * be called from the handle method instead of using the constructor to initialize the command.
- */
- private function stupidLaravel(): void
- {
- $this->accountRepos = app(AccountRepositoryInterface::class);
- $this->userRepos = app(UserRepositoryInterface::class);
- $this->count = 0;
- }
-
private function isExecuted(): bool
{
$configVar = FireflyConfig::get(self::CONFIG_NAME, false);
@@ -92,26 +80,21 @@ class UpgradesAccountCurrencies extends Command
return (bool) $configVar?->data;
}
- private function updateAccountCurrencies(): void
+ private function markAsExecuted(): void
{
- $users = $this->userRepos->all();
- foreach ($users as $user) {
- $this->updateCurrenciesForUser($user);
- }
+ FireflyConfig::set(self::CONFIG_NAME, true);
}
- private function updateCurrenciesForUser(User $user): void
+ /**
+ * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
+ * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
+ * be called from the handle method instead of using the constructor to initialize the command.
+ */
+ private function stupidLaravel(): void
{
- $this->accountRepos->setUser($user);
- $accounts = $this->accountRepos->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value]);
-
- // get user's currency preference:
- $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($user->userGroup);
-
- /** @var Account $account */
- foreach ($accounts as $account) {
- $this->updateAccount($account, $primaryCurrency);
- }
+ $this->accountRepos = app(AccountRepositoryInterface::class);
+ $this->userRepos = app(UserRepositoryInterface::class);
+ $this->count = 0;
}
private function updateAccount(Account $account, TransactionCurrency $currency): void
@@ -153,8 +136,25 @@ class UpgradesAccountCurrencies extends Command
}
}
- private function markAsExecuted(): void
+ private function updateAccountCurrencies(): void
{
- FireflyConfig::set(self::CONFIG_NAME, true);
+ $users = $this->userRepos->all();
+ foreach ($users as $user) {
+ $this->updateCurrenciesForUser($user);
+ }
+ }
+
+ private function updateCurrenciesForUser(User $user): void
+ {
+ $this->accountRepos->setUser($user);
+ $accounts = $this->accountRepos->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value]);
+
+ // get user's currency preference:
+ $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($user->userGroup);
+
+ /** @var Account $account */
+ foreach ($accounts as $account) {
+ $this->updateAccount($account, $primaryCurrency);
+ }
}
}
diff --git a/app/Console/Commands/Upgrade/UpgradesBillsToRules.php b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php
index 22dd1a67ec..3ed92b79ee 100644
--- a/app/Console/Commands/Upgrade/UpgradesBillsToRules.php
+++ b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php
@@ -84,20 +84,6 @@ class UpgradesBillsToRules extends Command
return 0;
}
- /**
- * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
- * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
- * be called from the handle method instead of using the constructor to initialize the command.
- */
- private function stupidLaravel(): void
- {
- $this->count = 0;
- $this->userRepository = app(UserRepositoryInterface::class);
- $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class);
- $this->billRepository = app(BillRepositoryInterface::class);
- $this->ruleRepository = app(RuleRepositoryInterface::class);
- }
-
private function isExecuted(): bool
{
$configVar = FireflyConfig::get(self::CONFIG_NAME, false);
@@ -105,34 +91,9 @@ class UpgradesBillsToRules extends Command
return (bool) $configVar?->data;
}
- /**
- * Migrate bills to new rule structure for a specific user.
- */
- private function migrateUser(User $user): void
+ private function markAsExecuted(): void
{
- $this->ruleGroupRepository->setUser($user);
- $this->billRepository->setUser($user);
- $this->ruleRepository->setUser($user);
-
- /** @var Preference $lang */
- $lang = Preferences::getForUser($user, 'language', 'en_US');
- $language = null !== $lang->data && !is_array($lang->data) ? (string) $lang->data : 'en_US';
- $groupTitle = (string) trans('firefly.rulegroup_for_bills_title', [], $language);
- $ruleGroup = $this->ruleGroupRepository->findByTitle($groupTitle);
-
- if (!$ruleGroup instanceof RuleGroup) {
- $ruleGroup = $this->ruleGroupRepository->store([
- 'title' => (string) trans('firefly.rulegroup_for_bills_title', [], $language),
- 'description' => (string) trans('firefly.rulegroup_for_bills_description', [], $language),
- 'active' => true,
- ]);
- }
- $bills = $this->billRepository->getBills();
-
- /** @var Bill $bill */
- foreach ($bills as $bill) {
- $this->migrateBill($ruleGroup, $bill, $lang);
- }
+ FireflyConfig::set(self::CONFIG_NAME, true);
}
private function migrateBill(RuleGroup $ruleGroup, Bill $bill, Preference $language): void
@@ -183,8 +144,47 @@ class UpgradesBillsToRules extends Command
++$this->count;
}
- private function markAsExecuted(): void
+ /**
+ * Migrate bills to new rule structure for a specific user.
+ */
+ private function migrateUser(User $user): void
{
- FireflyConfig::set(self::CONFIG_NAME, true);
+ $this->ruleGroupRepository->setUser($user);
+ $this->billRepository->setUser($user);
+ $this->ruleRepository->setUser($user);
+
+ /** @var Preference $lang */
+ $lang = Preferences::getForUser($user, 'language', 'en_US');
+ $language = null !== $lang->data && !is_array($lang->data) ? (string) $lang->data : 'en_US';
+ $groupTitle = (string) trans('firefly.rulegroup_for_bills_title', [], $language);
+ $ruleGroup = $this->ruleGroupRepository->findByTitle($groupTitle);
+
+ if (!$ruleGroup instanceof RuleGroup) {
+ $ruleGroup = $this->ruleGroupRepository->store([
+ 'title' => (string) trans('firefly.rulegroup_for_bills_title', [], $language),
+ 'description' => (string) trans('firefly.rulegroup_for_bills_description', [], $language),
+ 'active' => true,
+ ]);
+ }
+ $bills = $this->billRepository->getBills();
+
+ /** @var Bill $bill */
+ foreach ($bills as $bill) {
+ $this->migrateBill($ruleGroup, $bill, $lang);
+ }
+ }
+
+ /**
+ * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
+ * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
+ * be called from the handle method instead of using the constructor to initialize the command.
+ */
+ private function stupidLaravel(): void
+ {
+ $this->count = 0;
+ $this->userRepository = app(UserRepositoryInterface::class);
+ $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class);
+ $this->billRepository = app(BillRepositoryInterface::class);
+ $this->ruleRepository = app(RuleRepositoryInterface::class);
}
}
diff --git a/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php b/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php
index 589fa26f0f..a318f8ed55 100644
--- a/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php
+++ b/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php
@@ -57,23 +57,6 @@ class UpgradesBudgetLimitPeriods extends Command
return 0;
}
- private function isExecuted(): bool
- {
- $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
-
- return (bool) $configVar->data;
- }
-
- private function theresNoLimit(): void
- {
- $limits = BudgetLimit::whereNull('period')->get();
-
- /** @var BudgetLimit $limit */
- foreach ($limits as $limit) {
- $this->fixLimit($limit);
- }
- }
-
private function fixLimit(BudgetLimit $limit): void
{
$period = $this->getLimitPeriod($limit);
@@ -155,8 +138,25 @@ class UpgradesBudgetLimitPeriods extends Command
return null;
}
+ private function isExecuted(): bool
+ {
+ $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
+
+ return (bool) $configVar->data;
+ }
+
private function markAsExecuted(): void
{
FireflyConfig::set(self::CONFIG_NAME, true);
}
+
+ private function theresNoLimit(): void
+ {
+ $limits = BudgetLimit::whereNull('period')->get();
+
+ /** @var BudgetLimit $limit */
+ foreach ($limits as $limit) {
+ $this->fixLimit($limit);
+ }
+ }
}
diff --git a/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php
index 4a6affcd3d..6b77443bc6 100644
--- a/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php
+++ b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php
@@ -64,6 +64,24 @@ class UpgradesCurrencyPreferences extends Command
return 0;
}
+ private function getPreference(User $user): string
+ {
+ $preference = Preference::where('user_id', $user->id)
+ ->where('name', 'currencyPreference')
+ ->first(['id', 'user_id', 'name', 'data', 'updated_at', 'created_at'])
+ ;
+
+ if (null === $preference) {
+ return 'EUR';
+ }
+
+ if (null !== $preference->data && !is_array($preference->data)) {
+ return (string) $preference->data;
+ }
+
+ return 'EUR';
+ }
+
private function isExecuted(): bool
{
$configVar = FireflyConfig::get(self::CONFIG_NAME, false);
@@ -71,6 +89,11 @@ class UpgradesCurrencyPreferences extends Command
return (bool) $configVar?->data;
}
+ private function markAsExecuted(): void
+ {
+ FireflyConfig::set(self::CONFIG_NAME, true);
+ }
+
private function runUpgrade(): void
{
$groups = UserGroup::get();
@@ -126,27 +149,4 @@ class UpgradesCurrencyPreferences extends Command
$user->currencies()->updateExistingPivot($primaryCurrency->id, ['user_default' => true]);
$user->userGroup->currencies()->updateExistingPivot($primaryCurrency->id, ['group_default' => true]);
}
-
- private function getPreference(User $user): string
- {
- $preference = Preference::where('user_id', $user->id)
- ->where('name', 'currencyPreference')
- ->first(['id', 'user_id', 'name', 'data', 'updated_at', 'created_at'])
- ;
-
- if (null === $preference) {
- return 'EUR';
- }
-
- if (null !== $preference->data && !is_array($preference->data)) {
- return (string) $preference->data;
- }
-
- return 'EUR';
- }
-
- private function markAsExecuted(): void
- {
- FireflyConfig::set(self::CONFIG_NAME, true);
- }
}
diff --git a/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php b/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php
index 96696feb35..4fe68a395c 100644
--- a/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php
+++ b/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php
@@ -68,11 +68,48 @@ class UpgradesJournalMetaData extends Command
return 0;
}
- private function isMigrated(): bool
+ private function getIdsForBudgets(): array
{
- $configVar = FireflyConfig::get(UpgradesToGroups::CONFIG_NAME, false);
+ $transactions = DB::table('budget_transaction')
+ ->distinct()
+ ->pluck('transaction_id')
+ ->toArray()
+ ;
+ $array = [];
+ $chunks = array_chunk($transactions, 500);
- return (bool) $configVar->data;
+ foreach ($chunks as $chunk) {
+ $set = DB::table('transactions')
+ ->whereIn('transactions.id', $chunk)
+ ->pluck('transaction_journal_id')
+ ->toArray()
+ ;
+ $array = array_merge($array, $set);
+ }
+
+ return $array;
+ }
+
+ private function getIdsForCategories(): array
+ {
+ $transactions = DB::table('category_transaction')
+ ->distinct()
+ ->pluck('transaction_id')
+ ->toArray()
+ ;
+ $array = [];
+ $chunks = array_chunk($transactions, 500);
+
+ foreach ($chunks as $chunk) {
+ $set = DB::table('transactions')
+ ->whereIn('transactions.id', $chunk)
+ ->pluck('transaction_journal_id')
+ ->toArray()
+ ;
+ $array = array_merge($array, $set);
+ }
+
+ return $array;
}
private function isExecuted(): bool
@@ -82,6 +119,18 @@ class UpgradesJournalMetaData extends Command
return (bool) $configVar->data;
}
+ private function isMigrated(): bool
+ {
+ $configVar = FireflyConfig::get(UpgradesToGroups::CONFIG_NAME, false);
+
+ return (bool) $configVar->data;
+ }
+
+ private function markAsExecuted(): void
+ {
+ FireflyConfig::set(self::CONFIG_NAME, true);
+ }
+
private function migrateAll(): void
{
$this->migrateBudgets();
@@ -108,28 +157,6 @@ class UpgradesJournalMetaData extends Command
}
}
- private function getIdsForBudgets(): array
- {
- $transactions = DB::table('budget_transaction')
- ->distinct()
- ->pluck('transaction_id')
- ->toArray()
- ;
- $array = [];
- $chunks = array_chunk($transactions, 500);
-
- foreach ($chunks as $chunk) {
- $set = DB::table('transactions')
- ->whereIn('transactions.id', $chunk)
- ->pluck('transaction_journal_id')
- ->toArray()
- ;
- $array = array_merge($array, $set);
- }
-
- return $array;
- }
-
private function migrateBudgetsForJournal(TransactionJournal $journal): void
{
// grab category from first transaction
@@ -179,28 +206,6 @@ class UpgradesJournalMetaData extends Command
}
}
- private function getIdsForCategories(): array
- {
- $transactions = DB::table('category_transaction')
- ->distinct()
- ->pluck('transaction_id')
- ->toArray()
- ;
- $array = [];
- $chunks = array_chunk($transactions, 500);
-
- foreach ($chunks as $chunk) {
- $set = DB::table('transactions')
- ->whereIn('transactions.id', $chunk)
- ->pluck('transaction_journal_id')
- ->toArray()
- ;
- $array = array_merge($array, $set);
- }
-
- return $array;
- }
-
private function migrateCategoriesForJournal(TransactionJournal $journal): void
{
// grab category from first transaction
@@ -229,9 +234,4 @@ class UpgradesJournalMetaData extends Command
$journal->categories()->sync([$category->id]);
}
}
-
- private function markAsExecuted(): void
- {
- FireflyConfig::set(self::CONFIG_NAME, true);
- }
}
diff --git a/app/Console/Commands/Upgrade/UpgradesLiabilities.php b/app/Console/Commands/Upgrade/UpgradesLiabilities.php
index 0ead19729b..56cab26b41 100644
--- a/app/Console/Commands/Upgrade/UpgradesLiabilities.php
+++ b/app/Console/Commands/Upgrade/UpgradesLiabilities.php
@@ -61,6 +61,36 @@ class UpgradesLiabilities extends Command
return 0;
}
+ private function correctOpeningBalance(Account $account, TransactionJournal $openingBalance): void
+ {
+ $source = $this->getSourceTransaction($openingBalance);
+ $destination = $this->getDestinationTransaction($openingBalance);
+ if (!$source instanceof Transaction || !$destination instanceof Transaction) {
+ return;
+ }
+ // source MUST be the liability.
+ if ($destination->account_id === $account->id) {
+ // so if not, switch things around:
+ $sourceAccountId = $source->account_id;
+ $source->account_id = $destination->account_id;
+ $destination->account_id = $sourceAccountId;
+ $source->save();
+ $destination->save();
+ }
+ }
+
+ private function getDestinationTransaction(TransactionJournal $journal): ?Transaction
+ {
+ /** @var null|Transaction */
+ return $journal->transactions()->where('amount', '>', 0)->first();
+ }
+
+ private function getSourceTransaction(TransactionJournal $journal): ?Transaction
+ {
+ /** @var null|Transaction */
+ return $journal->transactions()->where('amount', '<', 0)->first();
+ }
+
private function isExecuted(): bool
{
$configVar = FireflyConfig::get(self::CONFIG_NAME, false);
@@ -68,14 +98,9 @@ class UpgradesLiabilities extends Command
return (bool) $configVar?->data;
}
- private function upgradeLiabilities(): void
+ private function markAsExecuted(): void
{
- $users = User::get();
-
- /** @var User $user */
- foreach ($users as $user) {
- $this->upgradeForUser($user);
- }
+ FireflyConfig::set(self::CONFIG_NAME, true);
}
private function upgradeForUser(User $user): void
@@ -96,6 +121,16 @@ class UpgradesLiabilities extends Command
}
}
+ private function upgradeLiabilities(): void
+ {
+ $users = User::get();
+
+ /** @var User $user */
+ foreach ($users as $user) {
+ $this->upgradeForUser($user);
+ }
+ }
+
private function upgradeLiability(Account $account): void
{
/** @var AccountRepositoryInterface $repository */
@@ -117,39 +152,4 @@ class UpgradesLiabilities extends Command
$factory->crud($account, 'liability_direction', 'debit');
}
}
-
- private function correctOpeningBalance(Account $account, TransactionJournal $openingBalance): void
- {
- $source = $this->getSourceTransaction($openingBalance);
- $destination = $this->getDestinationTransaction($openingBalance);
- if (!$source instanceof Transaction || !$destination instanceof Transaction) {
- return;
- }
- // source MUST be the liability.
- if ($destination->account_id === $account->id) {
- // so if not, switch things around:
- $sourceAccountId = $source->account_id;
- $source->account_id = $destination->account_id;
- $destination->account_id = $sourceAccountId;
- $source->save();
- $destination->save();
- }
- }
-
- private function getSourceTransaction(TransactionJournal $journal): ?Transaction
- {
- /** @var null|Transaction */
- return $journal->transactions()->where('amount', '<', 0)->first();
- }
-
- private function getDestinationTransaction(TransactionJournal $journal): ?Transaction
- {
- /** @var null|Transaction */
- return $journal->transactions()->where('amount', '>', 0)->first();
- }
-
- private function markAsExecuted(): void
- {
- FireflyConfig::set(self::CONFIG_NAME, true);
- }
}
diff --git a/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php b/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php
index 7efa427a11..5882d08e44 100644
--- a/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php
+++ b/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php
@@ -63,59 +63,40 @@ class UpgradesLiabilitiesEight extends Command
return 0;
}
- private function isExecuted(): bool
- {
- $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
-
- return (bool) $configVar?->data;
- }
-
- private function upgradeLiabilities(): void
- {
- $users = User::get();
-
- /** @var User $user */
- foreach ($users as $user) {
- $this->upgradeForUser($user);
- }
- }
-
- private function upgradeForUser(User $user): void
+ private function deleteCreditTransaction(Account $account): void
{
- $accounts = $user
- ->accounts()
- ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
- ->whereIn('account_types.type', config('firefly.valid_liabilities'))
- ->get(['accounts.*'])
+ $liabilityType = TransactionType::whereType(TransactionTypeEnum::LIABILITY_CREDIT->value)->first();
+ $liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
+ ->where('transactions.account_id', $account->id)
+ ->where('transaction_journals.transaction_type_id', $liabilityType->id)
+ ->first(['transaction_journals.*'])
;
-
- /** @var Account $account */
- foreach ($accounts as $account) {
- $this->upgradeLiability($account);
- $service = app(CreditRecalculateService::class);
- $service->setAccount($account);
- $service->recalculate();
+ if (null !== $liabilityJournal && null !== $liabilityJournal->transactionGroup) {
+ $group = $liabilityJournal->transactionGroup;
+ $service = new TransactionGroupDestroyService();
+ $service->destroy($group);
}
}
- private function upgradeLiability(Account $account): void
+ private function deleteTransactions(Account $account): int
{
- /** @var AccountRepositoryInterface $repository */
- $repository = app(AccountRepositoryInterface::class);
- $repository->setUser($account->user);
+ $count = 0;
+ $journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')->where(
+ 'transactions.account_id',
+ $account->id
+ )->get(['transaction_journals.*']);
- $direction = $repository->getMetaValue($account, 'liability_direction');
- if ('credit' === $direction && $this->hasBadOpening($account)) {
- $this->deleteCreditTransaction($account);
- $this->reverseOpeningBalance($account);
- $this->friendlyInfo(sprintf('Corrected opening balance for liability #%d ("%s")', $account->id, $account->name));
- }
- if ('credit' === $direction) {
- $count = $this->deleteTransactions($account);
- if ($count > 0) {
- $this->friendlyInfo(sprintf('Removed %d old format transaction(s) for liability #%d ("%s")', $count, $account->id, $account->name));
+ $service = app(TransactionGroupDestroyService::class);
+
+ /** @var TransactionJournal $journal */
+ foreach ($journals as $journal) {
+ if (null !== $journal->transactionGroup) {
+ $service->destroy($journal->transactionGroup);
+ ++$count;
}
}
+
+ return $count;
}
private function hasBadOpening(Account $account): bool
@@ -142,19 +123,16 @@ class UpgradesLiabilitiesEight extends Command
return (bool) $openingJournal->date->isSameDay($liabilityJournal->date);
}
- private function deleteCreditTransaction(Account $account): void
+ private function isExecuted(): bool
{
- $liabilityType = TransactionType::whereType(TransactionTypeEnum::LIABILITY_CREDIT->value)->first();
- $liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
- ->where('transactions.account_id', $account->id)
- ->where('transaction_journals.transaction_type_id', $liabilityType->id)
- ->first(['transaction_journals.*'])
- ;
- if (null !== $liabilityJournal && null !== $liabilityJournal->transactionGroup) {
- $group = $liabilityJournal->transactionGroup;
- $service = new TransactionGroupDestroyService();
- $service->destroy($group);
- }
+ $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
+
+ return (bool) $configVar?->data;
+ }
+
+ private function markAsExecuted(): void
+ {
+ FireflyConfig::set(self::CONFIG_NAME, true);
}
private function reverseOpeningBalance(Account $account): void
@@ -186,29 +164,51 @@ class UpgradesLiabilitiesEight extends Command
Log::warning('Did not find opening balance.');
}
- private function deleteTransactions(Account $account): int
+ private function upgradeForUser(User $user): void
{
- $count = 0;
- $journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')->where(
- 'transactions.account_id',
- $account->id
- )->get(['transaction_journals.*']);
-
- $service = app(TransactionGroupDestroyService::class);
+ $accounts = $user
+ ->accounts()
+ ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
+ ->whereIn('account_types.type', config('firefly.valid_liabilities'))
+ ->get(['accounts.*'])
+ ;
- /** @var TransactionJournal $journal */
- foreach ($journals as $journal) {
- if (null !== $journal->transactionGroup) {
- $service->destroy($journal->transactionGroup);
- ++$count;
- }
+ /** @var Account $account */
+ foreach ($accounts as $account) {
+ $this->upgradeLiability($account);
+ $service = app(CreditRecalculateService::class);
+ $service->setAccount($account);
+ $service->recalculate();
}
+ }
- return $count;
+ private function upgradeLiabilities(): void
+ {
+ $users = User::get();
+
+ /** @var User $user */
+ foreach ($users as $user) {
+ $this->upgradeForUser($user);
+ }
}
- private function markAsExecuted(): void
+ private function upgradeLiability(Account $account): void
{
- FireflyConfig::set(self::CONFIG_NAME, true);
+ /** @var AccountRepositoryInterface $repository */
+ $repository = app(AccountRepositoryInterface::class);
+ $repository->setUser($account->user);
+
+ $direction = $repository->getMetaValue($account, 'liability_direction');
+ if ('credit' === $direction && $this->hasBadOpening($account)) {
+ $this->deleteCreditTransaction($account);
+ $this->reverseOpeningBalance($account);
+ $this->friendlyInfo(sprintf('Corrected opening balance for liability #%d ("%s")', $account->id, $account->name));
+ }
+ if ('credit' === $direction) {
+ $count = $this->deleteTransactions($account);
+ if ($count > 0) {
+ $this->friendlyInfo(sprintf('Removed %d old format transaction(s) for liability #%d ("%s")', $count, $account->id, $account->name));
+ }
+ }
}
}
diff --git a/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php
index 60ee70b36c..53488e5acc 100644
--- a/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php
+++ b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php
@@ -70,17 +70,9 @@ class UpgradesMultiPiggyBanks extends Command
return (bool) $configVar?->data;
}
- private function upgradePiggyBanks(): void
+ private function markAsExecuted(): 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);
- }
+ FireflyConfig::set(self::CONFIG_NAME, true);
}
private function upgradePiggyBank(PiggyBank $piggyBank): void
@@ -109,8 +101,16 @@ class UpgradesMultiPiggyBanks extends Command
$piggyBank->piggyBankRepetitions()->delete();
}
- private function markAsExecuted(): void
+ private function upgradePiggyBanks(): void
{
- FireflyConfig::set(self::CONFIG_NAME, true);
+ $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);
+ }
}
}
diff --git a/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php
index c000d3b646..f08ccc97b1 100644
--- a/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php
+++ b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php
@@ -71,18 +71,9 @@ class UpgradesRecurrenceMetaData extends Command
return (bool) $configVar?->data;
}
- private function migrateMetaData(): int
+ private function markAsExecuted(): void
{
- $count = 0;
- // get all recurrence meta data:
- $collection = RecurrenceMeta::with('recurrence')->get();
-
- /** @var RecurrenceMeta $meta */
- foreach ($collection as $meta) {
- $count += $this->migrateEntry($meta);
- }
-
- return $count;
+ FireflyConfig::set(self::CONFIG_NAME, true);
}
private function migrateEntry(RecurrenceMeta $meta): int
@@ -109,8 +100,17 @@ class UpgradesRecurrenceMetaData extends Command
return 1;
}
- private function markAsExecuted(): void
+ private function migrateMetaData(): int
{
- FireflyConfig::set(self::CONFIG_NAME, true);
+ $count = 0;
+ // get all recurrence meta data:
+ $collection = RecurrenceMeta::with('recurrence')->get();
+
+ /** @var RecurrenceMeta $meta */
+ foreach ($collection as $meta) {
+ $count += $this->migrateEntry($meta);
+ }
+
+ return $count;
}
}
diff --git a/app/Console/Commands/Upgrade/UpgradesRuleActions.php b/app/Console/Commands/Upgrade/UpgradesRuleActions.php
index 0e74393759..20664ce64d 100644
--- a/app/Console/Commands/Upgrade/UpgradesRuleActions.php
+++ b/app/Console/Commands/Upgrade/UpgradesRuleActions.php
@@ -68,6 +68,11 @@ class UpgradesRuleActions extends Command
return (bool) $configVar?->data;
}
+ private function markAsExecuted(): void
+ {
+ FireflyConfig::set(self::CONFIG_NAME, true);
+ }
+
private function replaceEqualSign(): void
{
$count = 0;
@@ -179,9 +184,4 @@ class UpgradesRuleActions extends Command
}
}
}
-
- private function markAsExecuted(): void
- {
- FireflyConfig::set(self::CONFIG_NAME, true);
- }
}
diff --git a/app/Console/Commands/Upgrade/UpgradesTagLocations.php b/app/Console/Commands/Upgrade/UpgradesTagLocations.php
index 45a5b9e0a5..3590268f95 100644
--- a/app/Console/Commands/Upgrade/UpgradesTagLocations.php
+++ b/app/Console/Commands/Upgrade/UpgradesTagLocations.php
@@ -56,28 +56,21 @@ class UpgradesTagLocations extends Command
return 0;
}
- private function isExecuted(): bool
+ private function hasLocationDetails(Tag $tag): bool
{
- $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
-
- return (bool) $configVar?->data;
+ return !in_array(null, [$tag->latitude, $tag->longitude, $tag->zoomLevel], true);
}
- private function migrateTagLocations(): void
+ private function isExecuted(): bool
{
- $tags = Tag::get();
+ $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
- /** @var Tag $tag */
- foreach ($tags as $tag) {
- if ($this->hasLocationDetails($tag)) {
- $this->migrateLocationDetails($tag);
- }
- }
+ return (bool) $configVar?->data;
}
- private function hasLocationDetails(Tag $tag): bool
+ private function markAsExecuted(): void
{
- return !in_array(null, [$tag->latitude, $tag->longitude, $tag->zoomLevel], true);
+ FireflyConfig::set(self::CONFIG_NAME, true);
}
private function migrateLocationDetails(Tag $tag): void
@@ -95,8 +88,15 @@ class UpgradesTagLocations extends Command
$tag->save();
}
- private function markAsExecuted(): void
+ private function migrateTagLocations(): void
{
- FireflyConfig::set(self::CONFIG_NAME, true);
+ $tags = Tag::get();
+
+ /** @var Tag $tag */
+ foreach ($tags as $tag) {
+ if ($this->hasLocationDetails($tag)) {
+ $this->migrateLocationDetails($tag);
+ }
+ }
}
}
diff --git a/app/Console/Commands/Upgrade/UpgradesToGroups.php b/app/Console/Commands/Upgrade/UpgradesToGroups.php
index 1b2a1acccf..0981af55b4 100644
--- a/app/Console/Commands/Upgrade/UpgradesToGroups.php
+++ b/app/Console/Commands/Upgrade/UpgradesToGroups.php
@@ -83,100 +83,18 @@ class UpgradesToGroups extends Command
return 0;
}
- /**
- * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
- * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
- * be called from the handle method instead of using the constructor to initialize the command.
- */
- private function stupidLaravel(): void
- {
- $this->count = 0;
- $this->journalRepository = app(JournalRepositoryInterface::class);
- $this->service = app(JournalDestroyService::class);
- $this->groupFactory = app(TransactionGroupFactory::class);
- $this->cliRepository = app(JournalCLIRepositoryInterface::class);
- }
-
- private function isMigrated(): bool
- {
- $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
-
- return (bool) $configVar?->data;
- }
-
- /**
- * @throws Exception
- */
- private function makeGroupsFromSplitJournals(): void
- {
- $splitJournals = $this->cliRepository->getSplitJournals();
- if ($splitJournals->count() > 0) {
- $this->friendlyLine(sprintf('Going to convert %d split transaction(s). Please hold..', $splitJournals->count()));
-
- /** @var TransactionJournal $journal */
- foreach ($splitJournals as $journal) {
- $this->makeMultiGroup($journal);
- }
- }
- }
-
- /**
- * @throws Exception
- */
- private function makeMultiGroup(TransactionJournal $journal): void
+ private function findOpposingTransaction(TransactionJournal $journal, Transaction $transaction): ?Transaction
{
- // double check transaction count.
- if ($journal->transactions->count() <= 2) {
- Log::debug(sprintf('Will not try to convert journal #%d because it has 2 or fewer transactions.', $journal->id));
-
- return;
- }
- Log::debug(sprintf('Will now try to convert journal #%d', $journal->id));
-
- $this->journalRepository->setUser($journal->user);
- $this->groupFactory->setUser($journal->user);
- $this->cliRepository->setUser($journal->user);
-
- $data = [
- // mandatory fields.
- 'group_title' => $journal->description,
- 'transactions' => [],
- ];
- $destTransactions = $this->getDestinationTransactions($journal);
-
- Log::debug(sprintf('Will use %d positive transactions to create a new group.', $destTransactions->count()));
-
- /** @var Transaction $transaction */
- foreach ($destTransactions as $transaction) {
- $data['transactions'][] = $this->generateTransaction($journal, $transaction);
- }
- Log::debug(sprintf('Now calling transaction journal factory (%d transactions in array)', count($data['transactions'])));
- $group = $this->groupFactory->create($data);
- Log::debug('Done calling transaction journal factory');
-
- // delete the old transaction journal.
- $this->service->destroy($journal);
-
- ++$this->count;
+ $set = $journal->transactions->filter(static function (Transaction $subject) use ($transaction): bool {
+ $amount = ((float) $transaction->amount * -1) === (float) $subject->amount; // intentional float
+ $identifier = $transaction->identifier === $subject->identifier;
+ Log::debug(sprintf('Amount the same? %s', var_export($amount, true)));
+ Log::debug(sprintf('ID the same? %s', var_export($identifier, true)));
- // report on result:
- Log::debug(sprintf(
- 'Migrated journal #%d into group #%d with these journals: #%s',
- $journal->id,
- $group->id,
- implode(', #', $group->transactionJournals->pluck('id')->toArray())
- ));
- $this->friendlyInfo(sprintf(
- 'Migrated journal #%d into group #%d with these journals: #%s',
- $journal->id,
- $group->id,
- implode(', #', $group->transactionJournals->pluck('id')->toArray())
- ));
- }
+ return $amount && $identifier;
+ });
- private function getDestinationTransactions(TransactionJournal $journal): Collection
- {
- return $journal->transactions->filter(static fn (Transaction $transaction): bool => $transaction->amount > 0);
+ return $set->first();
}
/**
@@ -268,18 +186,9 @@ class UpgradesToGroups extends Command
];
}
- private function findOpposingTransaction(TransactionJournal $journal, Transaction $transaction): ?Transaction
+ private function getDestinationTransactions(TransactionJournal $journal): Collection
{
- $set = $journal->transactions->filter(static function (Transaction $subject) use ($transaction): bool {
- $amount = ((float) $transaction->amount * -1) === (float) $subject->amount; // intentional float
- $identifier = $transaction->identifier === $subject->identifier;
- Log::debug(sprintf('Amount the same? %s', var_export($amount, true)));
- Log::debug(sprintf('ID the same? %s', var_export($identifier, true)));
-
- return $amount && $identifier;
- });
-
- return $set->first();
+ return $journal->transactions->filter(static fn (Transaction $transaction): bool => $transaction->amount > 0);
}
private function getTransactionBudget(Transaction $left, Transaction $right): ?int
@@ -336,6 +245,25 @@ class UpgradesToGroups extends Command
return null;
}
+ private function giveGroup(array $array): void
+ {
+ $groupId = DB::table('transaction_groups')->insertGetId([
+ 'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
+ 'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
+ 'title' => null,
+ 'user_id' => $array['user_id'],
+ ]);
+ DB::table('transaction_journals')->where('id', $array['id'])->update(['transaction_group_id' => $groupId]);
+ ++$this->count;
+ }
+
+ private function isMigrated(): bool
+ {
+ $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
+
+ return (bool) $configVar?->data;
+ }
+
/**
* Gives all journals without a group a group.
*/
@@ -354,20 +282,92 @@ class UpgradesToGroups extends Command
}
}
- private function giveGroup(array $array): void
+ /**
+ * @throws Exception
+ */
+ private function makeGroupsFromSplitJournals(): void
{
- $groupId = DB::table('transaction_groups')->insertGetId([
- 'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
- 'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
- 'title' => null,
- 'user_id' => $array['user_id'],
- ]);
- DB::table('transaction_journals')->where('id', $array['id'])->update(['transaction_group_id' => $groupId]);
+ $splitJournals = $this->cliRepository->getSplitJournals();
+ if ($splitJournals->count() > 0) {
+ $this->friendlyLine(sprintf('Going to convert %d split transaction(s). Please hold..', $splitJournals->count()));
+
+ /** @var TransactionJournal $journal */
+ foreach ($splitJournals as $journal) {
+ $this->makeMultiGroup($journal);
+ }
+ }
+ }
+
+ /**
+ * @throws Exception
+ */
+ private function makeMultiGroup(TransactionJournal $journal): void
+ {
+ // double check transaction count.
+ if ($journal->transactions->count() <= 2) {
+ Log::debug(sprintf('Will not try to convert journal #%d because it has 2 or fewer transactions.', $journal->id));
+
+ return;
+ }
+ Log::debug(sprintf('Will now try to convert journal #%d', $journal->id));
+
+ $this->journalRepository->setUser($journal->user);
+ $this->groupFactory->setUser($journal->user);
+ $this->cliRepository->setUser($journal->user);
+
+ $data = [
+ // mandatory fields.
+ 'group_title' => $journal->description,
+ 'transactions' => [],
+ ];
+ $destTransactions = $this->getDestinationTransactions($journal);
+
+ Log::debug(sprintf('Will use %d positive transactions to create a new group.', $destTransactions->count()));
+
+ /** @var Transaction $transaction */
+ foreach ($destTransactions as $transaction) {
+ $data['transactions'][] = $this->generateTransaction($journal, $transaction);
+ }
+ Log::debug(sprintf('Now calling transaction journal factory (%d transactions in array)', count($data['transactions'])));
+ $group = $this->groupFactory->create($data);
+ Log::debug('Done calling transaction journal factory');
+
+ // delete the old transaction journal.
+ $this->service->destroy($journal);
+
++$this->count;
+
+ // report on result:
+ Log::debug(sprintf(
+ 'Migrated journal #%d into group #%d with these journals: #%s',
+ $journal->id,
+ $group->id,
+ implode(', #', $group->transactionJournals->pluck('id')->toArray())
+ ));
+ $this->friendlyInfo(sprintf(
+ 'Migrated journal #%d into group #%d with these journals: #%s',
+ $journal->id,
+ $group->id,
+ implode(', #', $group->transactionJournals->pluck('id')->toArray())
+ ));
}
private function markAsMigrated(): void
{
FireflyConfig::set(self::CONFIG_NAME, true);
}
+
+ /**
+ * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
+ * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
+ * be called from the handle method instead of using the constructor to initialize the command.
+ */
+ private function stupidLaravel(): void
+ {
+ $this->count = 0;
+ $this->journalRepository = app(JournalRepositoryInterface::class);
+ $this->service = app(JournalDestroyService::class);
+ $this->groupFactory = app(TransactionGroupFactory::class);
+ $this->cliRepository = app(JournalCLIRepositoryInterface::class);
+ }
}
diff --git a/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php b/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php
index 5c15db8467..b299859ae3 100644
--- a/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php
+++ b/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php
@@ -79,137 +79,192 @@ class UpgradesTransferCurrencies extends Command
}
/**
- * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
- * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
- * be called from the handle method instead of using the constructor to initialize the command.
+ * The destination transaction must have the correct currency. If not, it will be set by
+ * taking it from the destination account's preference.
*/
- private function stupidLaravel(): void
+ private function fixDestinationUnmatchedCurrency(): void
{
- $this->count = 0;
- $this->accountRepos = app(AccountRepositoryInterface::class);
- $this->cliRepos = app(JournalCLIRepositoryInterface::class);
- $this->accountCurrencies = [];
- $this->resetInformation();
+ if (
+ $this->destinationCurrency instanceof TransactionCurrency
+ && null === $this->destinationTransaction->foreign_amount
+ && (int) $this->destinationTransaction->transaction_currency_id !== $this->destinationCurrency->id
+ ) {
+ $message = sprintf(
+ 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.',
+ $this->destinationTransaction->id,
+ $this->destinationTransaction->transaction_currency_id,
+ $this->destinationAccount->id,
+ $this->destinationTransaction->amount
+ );
+ $this->friendlyWarning($message);
+ ++$this->count;
+ $this->destinationTransaction->transaction_currency_id = $this->destinationCurrency->id;
+ $this->destinationTransaction->save();
+ }
}
/**
- * Reset all the class fields for the current transfer.
+ * The destination transaction must have a currency. If not, it will be added by
+ * taking it from the destination account's preference.
*/
- private function resetInformation(): void
- {
- $this->sourceTransaction = null;
- $this->sourceAccount = null;
- $this->sourceCurrency = null;
- $this->destinationTransaction = null;
- $this->destinationAccount = null;
- $this->destinationCurrency = null;
- }
-
- private function isExecuted(): bool
+ private function fixDestNoCurrency(): void
{
- $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
-
- return (bool) $configVar?->data;
+ if (null === $this->destinationTransaction->transaction_currency_id && $this->destinationCurrency instanceof TransactionCurrency) {
+ $this->destinationTransaction->transaction_currency_id = $this->destinationCurrency->id;
+ $message = sprintf(
+ 'Transaction #%d has no currency setting, now set to %s.',
+ $this->destinationTransaction->id,
+ $this->destinationCurrency->code
+ );
+ $this->friendlyInfo($message);
+ ++$this->count;
+ $this->destinationTransaction->save();
+ }
}
/**
- * This routine verifies that transfers have the correct currency settings for the accounts they are linked to.
- * For transfers, this is can be a destructive routine since we FORCE them into a currency setting whether they
- * like it or not. Previous routines MUST have set the currency setting for both accounts for this to work.
- *
- * Both source and destination must match the respective currency preference. So FF3 must verify ALL
- * transactions.
+ * If the foreign amount of the destination transaction is null, but that of the other isn't, use this piece of code
+ * to restore it.
*/
- private function startUpdateRoutine(): void
+ private function fixDestNullForeignAmount(): void
{
- $set = $this->cliRepos->getAllJournals([TransactionTypeEnum::TRANSFER->value]);
-
- /** @var TransactionJournal $journal */
- foreach ($set as $journal) {
- $this->updateTransferCurrency($journal);
+ if (null === $this->destinationTransaction->foreign_amount && null !== $this->sourceTransaction->foreign_amount) {
+ $this->destinationTransaction->foreign_amount = bcmul($this->sourceTransaction->foreign_amount, '-1');
+ $this->destinationTransaction->save();
+ ++$this->count;
+ $this->friendlyInfo(sprintf(
+ 'Restored foreign amount of destination transaction #%d to %s',
+ $this->destinationTransaction->id,
+ $this->destinationTransaction->foreign_amount
+ ));
}
}
- private function updateTransferCurrency(TransactionJournal $transfer): void
+ /**
+ * If the destination account currency is the same as the source currency,
+ * both foreign_amount and foreign_currency_id fields must be NULL
+ * for both transactions (because foreign currency info would not make sense)
+ */
+ private function fixInvalidForeignCurrency(): void
{
- $this->resetInformation();
-
- if ($this->isSplitJournal($transfer)) {
- $this->friendlyWarning(sprintf('Transaction journal #%d is a split journal. Cannot continue.', $transfer->id));
-
- return;
- }
-
- $this->getSourceInformation($transfer);
- $this->getDestinationInformation($transfer);
-
- // unexpectedly, either one is null:
+ if ($this->destinationCurrency->id === $this->sourceCurrency->id) {
+ // update both transactions to match:
+ $this->sourceTransaction->foreign_amount = null;
+ $this->sourceTransaction->foreign_currency_id = null;
- if ($this->isEmptyTransactions()) {
- $this->friendlyError(sprintf('Source or destination information for transaction journal #%d is null. Cannot fix this one.', $transfer->id));
+ $this->destinationTransaction->foreign_amount = null;
+ $this->destinationTransaction->foreign_currency_id = null;
- return;
+ $this->sourceTransaction->save();
+ $this->destinationTransaction->save();
}
+ }
- // both accounts must have currency preference:
+ /**
+ * If destination account currency is different from source account currency,
+ * then both transactions must get the source account's currency as normal currency
+ * and the opposing account's currency as foreign currency.
+ */
+ private function fixMismatchedForeignCurrency(): void
+ {
+ if ($this->sourceCurrency->id !== $this->destinationCurrency->id) {
+ $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id;
+ $this->sourceTransaction->foreign_currency_id = $this->destinationCurrency->id;
+ $this->destinationTransaction->transaction_currency_id = $this->sourceCurrency->id;
+ $this->destinationTransaction->foreign_currency_id = $this->destinationCurrency->id;
- if ($this->isNoCurrencyPresent()) {
- $this->friendlyError(sprintf(
- 'Source or destination accounts for transaction journal #%d have no currency information. Cannot fix this one.',
- $transfer->id
+ $this->sourceTransaction->save();
+ $this->destinationTransaction->save();
+ ++$this->count;
+ $this->friendlyInfo(sprintf(
+ 'Verified foreign currency ID of transaction #%d and #%d',
+ $this->sourceTransaction->id,
+ $this->destinationTransaction->id
));
-
- return;
}
+ }
- // fix source transaction having no currency.
- $this->fixSourceNoCurrency();
-
- // fix source transaction having bad currency.
- $this->fixSourceUnmatchedCurrency();
-
- // fix destination transaction having no currency.
- $this->fixDestNoCurrency();
-
- // fix destination transaction having bad currency.
- $this->fixDestinationUnmatchedCurrency();
-
- // remove foreign currency information if not necessary.
- $this->fixInvalidForeignCurrency();
- // correct foreign currency info if necessary.
- $this->fixMismatchedForeignCurrency();
-
- // restore missing foreign currency amount.
- $this->fixSourceNullForeignAmount();
-
- $this->fixDestNullForeignAmount();
-
- // fix journal itself:
- $this->fixTransactionJournalCurrency($transfer);
+ /**
+ * The source transaction must have a currency. If not, it will be added by
+ * taking it from the source account's preference.
+ */
+ private function fixSourceNoCurrency(): void
+ {
+ if (null === $this->sourceTransaction->transaction_currency_id && $this->sourceCurrency instanceof TransactionCurrency) {
+ $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id;
+ $message = sprintf(
+ 'Transaction #%d has no currency setting, now set to %s.',
+ $this->sourceTransaction->id,
+ $this->sourceCurrency->code
+ );
+ $this->friendlyInfo($message);
+ ++$this->count;
+ $this->sourceTransaction->save();
+ }
}
/**
- * Is this a split transaction journal?
+ * If the foreign amount of the source transaction is null, but that of the other isn't, use this piece of code
+ * to restore it.
*/
- private function isSplitJournal(TransactionJournal $transfer): bool
+ private function fixSourceNullForeignAmount(): void
{
- return $transfer->transactions->count() > 2;
+ if (null === $this->sourceTransaction->foreign_amount && null !== $this->destinationTransaction->foreign_amount) {
+ $this->sourceTransaction->foreign_amount = bcmul($this->destinationTransaction->foreign_amount, '-1');
+ $this->sourceTransaction->save();
+ ++$this->count;
+ $this->friendlyInfo(sprintf(
+ 'Restored foreign amount of source transaction #%d to %s',
+ $this->sourceTransaction->id,
+ $this->sourceTransaction->foreign_amount
+ ));
+ }
}
/**
- * Extract source transaction, source account + source account currency from the journal.
+ * The source transaction must have the correct currency. If not, it will be set by
+ * taking it from the source account's preference.
*/
- private function getSourceInformation(TransactionJournal $journal): void
+ private function fixSourceUnmatchedCurrency(): void
{
- $this->sourceTransaction = $this->getSourceTransaction($journal);
- $this->sourceAccount = $this->sourceTransaction?->account;
- $this->sourceCurrency = $this->sourceAccount instanceof Account ? $this->getCurrency($this->sourceAccount) : null;
+ if (
+ $this->sourceCurrency instanceof TransactionCurrency
+ && null === $this->sourceTransaction->foreign_amount
+ && (int) $this->sourceTransaction->transaction_currency_id !== $this->sourceCurrency->id
+ ) {
+ $message = sprintf(
+ 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.',
+ $this->sourceTransaction->id,
+ $this->sourceTransaction->transaction_currency_id,
+ $this->sourceAccount->id,
+ $this->sourceTransaction->amount
+ );
+ $this->friendlyWarning($message);
+ ++$this->count;
+ $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id;
+ $this->sourceTransaction->save();
+ }
}
- private function getSourceTransaction(TransactionJournal $transfer): ?Transaction
+ /**
+ * This method makes sure that the transaction journal uses the currency given in the source transaction.
+ */
+ private function fixTransactionJournalCurrency(TransactionJournal $journal): void
{
- /** @var null|Transaction */
- return $transfer->transactions()->where('amount', '<', 0)->first();
+ if ((int) $journal->transaction_currency_id !== $this->sourceCurrency->id) {
+ $oldCurrencyCode = $journal->transactionCurrency->code ?? '(nothing)';
+ $journal->transaction_currency_id = $this->sourceCurrency->id;
+ $message = sprintf(
+ 'Transfer #%d ("%s") has been updated to use %s instead of %s.',
+ $journal->id,
+ $journal->description,
+ $this->sourceCurrency->code,
+ $oldCurrencyCode
+ );
+ ++$this->count;
+ $this->friendlyInfo($message);
+ $journal->save();
+ }
}
private function getCurrency(Account $account): ?TransactionCurrency
@@ -248,6 +303,22 @@ class UpgradesTransferCurrencies extends Command
return $transfer->transactions()->where('amount', '>', 0)->first();
}
+ /**
+ * Extract source transaction, source account + source account currency from the journal.
+ */
+ private function getSourceInformation(TransactionJournal $journal): void
+ {
+ $this->sourceTransaction = $this->getSourceTransaction($journal);
+ $this->sourceAccount = $this->sourceTransaction?->account;
+ $this->sourceCurrency = $this->sourceAccount instanceof Account ? $this->getCurrency($this->sourceAccount) : null;
+ }
+
+ private function getSourceTransaction(TransactionJournal $transfer): ?Transaction
+ {
+ /** @var null|Transaction */
+ return $transfer->transactions()->where('amount', '<', 0)->first();
+ }
+
/**
* Is either the source or destination transaction NULL?
*/
@@ -260,6 +331,13 @@ class UpgradesTransferCurrencies extends Command
|| !$this->destinationAccount instanceof Account;
}
+ private function isExecuted(): bool
+ {
+ $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
+
+ return (bool) $configVar?->data;
+ }
+
private function isNoCurrencyPresent(): bool
{
// source account must have a currency preference.
@@ -288,196 +366,118 @@ class UpgradesTransferCurrencies extends Command
}
/**
- * The source transaction must have a currency. If not, it will be added by
- * taking it from the source account's preference.
+ * Is this a split transaction journal?
*/
- private function fixSourceNoCurrency(): void
+ private function isSplitJournal(TransactionJournal $transfer): bool
{
- if (null === $this->sourceTransaction->transaction_currency_id && $this->sourceCurrency instanceof TransactionCurrency) {
- $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id;
- $message = sprintf(
- 'Transaction #%d has no currency setting, now set to %s.',
- $this->sourceTransaction->id,
- $this->sourceCurrency->code
- );
- $this->friendlyInfo($message);
- ++$this->count;
- $this->sourceTransaction->save();
- }
+ return $transfer->transactions->count() > 2;
}
- /**
- * The source transaction must have the correct currency. If not, it will be set by
- * taking it from the source account's preference.
- */
- private function fixSourceUnmatchedCurrency(): void
+ private function markAsExecuted(): void
{
- if (
- $this->sourceCurrency instanceof TransactionCurrency
- && null === $this->sourceTransaction->foreign_amount
- && (int) $this->sourceTransaction->transaction_currency_id !== $this->sourceCurrency->id
- ) {
- $message = sprintf(
- 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.',
- $this->sourceTransaction->id,
- $this->sourceTransaction->transaction_currency_id,
- $this->sourceAccount->id,
- $this->sourceTransaction->amount
- );
- $this->friendlyWarning($message);
- ++$this->count;
- $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id;
- $this->sourceTransaction->save();
- }
+ FireflyConfig::set(self::CONFIG_NAME, true);
}
/**
- * The destination transaction must have a currency. If not, it will be added by
- * taking it from the destination account's preference.
+ * Reset all the class fields for the current transfer.
*/
- private function fixDestNoCurrency(): void
+ private function resetInformation(): void
{
- if (null === $this->destinationTransaction->transaction_currency_id && $this->destinationCurrency instanceof TransactionCurrency) {
- $this->destinationTransaction->transaction_currency_id = $this->destinationCurrency->id;
- $message = sprintf(
- 'Transaction #%d has no currency setting, now set to %s.',
- $this->destinationTransaction->id,
- $this->destinationCurrency->code
- );
- $this->friendlyInfo($message);
- ++$this->count;
- $this->destinationTransaction->save();
- }
+ $this->sourceTransaction = null;
+ $this->sourceAccount = null;
+ $this->sourceCurrency = null;
+ $this->destinationTransaction = null;
+ $this->destinationAccount = null;
+ $this->destinationCurrency = null;
}
/**
- * The destination transaction must have the correct currency. If not, it will be set by
- * taking it from the destination account's preference.
+ * This routine verifies that transfers have the correct currency settings for the accounts they are linked to.
+ * For transfers, this is can be a destructive routine since we FORCE them into a currency setting whether they
+ * like it or not. Previous routines MUST have set the currency setting for both accounts for this to work.
+ *
+ * Both source and destination must match the respective currency preference. So FF3 must verify ALL
+ * transactions.
*/
- private function fixDestinationUnmatchedCurrency(): void
+ private function startUpdateRoutine(): void
{
- if (
- $this->destinationCurrency instanceof TransactionCurrency
- && null === $this->destinationTransaction->foreign_amount
- && (int) $this->destinationTransaction->transaction_currency_id !== $this->destinationCurrency->id
- ) {
- $message = sprintf(
- 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.',
- $this->destinationTransaction->id,
- $this->destinationTransaction->transaction_currency_id,
- $this->destinationAccount->id,
- $this->destinationTransaction->amount
- );
- $this->friendlyWarning($message);
- ++$this->count;
- $this->destinationTransaction->transaction_currency_id = $this->destinationCurrency->id;
- $this->destinationTransaction->save();
+ $set = $this->cliRepos->getAllJournals([TransactionTypeEnum::TRANSFER->value]);
+
+ /** @var TransactionJournal $journal */
+ foreach ($set as $journal) {
+ $this->updateTransferCurrency($journal);
}
}
/**
- * If the destination account currency is the same as the source currency,
- * both foreign_amount and foreign_currency_id fields must be NULL
- * for both transactions (because foreign currency info would not make sense)
+ * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
+ * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
+ * be called from the handle method instead of using the constructor to initialize the command.
*/
- private function fixInvalidForeignCurrency(): void
+ private function stupidLaravel(): void
{
- if ($this->destinationCurrency->id === $this->sourceCurrency->id) {
- // update both transactions to match:
- $this->sourceTransaction->foreign_amount = null;
- $this->sourceTransaction->foreign_currency_id = null;
-
- $this->destinationTransaction->foreign_amount = null;
- $this->destinationTransaction->foreign_currency_id = null;
-
- $this->sourceTransaction->save();
- $this->destinationTransaction->save();
- }
+ $this->count = 0;
+ $this->accountRepos = app(AccountRepositoryInterface::class);
+ $this->cliRepos = app(JournalCLIRepositoryInterface::class);
+ $this->accountCurrencies = [];
+ $this->resetInformation();
}
- /**
- * If destination account currency is different from source account currency,
- * then both transactions must get the source account's currency as normal currency
- * and the opposing account's currency as foreign currency.
- */
- private function fixMismatchedForeignCurrency(): void
+ private function updateTransferCurrency(TransactionJournal $transfer): void
{
- if ($this->sourceCurrency->id !== $this->destinationCurrency->id) {
- $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id;
- $this->sourceTransaction->foreign_currency_id = $this->destinationCurrency->id;
- $this->destinationTransaction->transaction_currency_id = $this->sourceCurrency->id;
- $this->destinationTransaction->foreign_currency_id = $this->destinationCurrency->id;
+ $this->resetInformation();
- $this->sourceTransaction->save();
- $this->destinationTransaction->save();
- ++$this->count;
- $this->friendlyInfo(sprintf(
- 'Verified foreign currency ID of transaction #%d and #%d',
- $this->sourceTransaction->id,
- $this->destinationTransaction->id
- ));
+ if ($this->isSplitJournal($transfer)) {
+ $this->friendlyWarning(sprintf('Transaction journal #%d is a split journal. Cannot continue.', $transfer->id));
+
+ return;
}
- }
- /**
- * If the foreign amount of the source transaction is null, but that of the other isn't, use this piece of code
- * to restore it.
- */
- private function fixSourceNullForeignAmount(): void
- {
- if (null === $this->sourceTransaction->foreign_amount && null !== $this->destinationTransaction->foreign_amount) {
- $this->sourceTransaction->foreign_amount = bcmul($this->destinationTransaction->foreign_amount, '-1');
- $this->sourceTransaction->save();
- ++$this->count;
- $this->friendlyInfo(sprintf(
- 'Restored foreign amount of source transaction #%d to %s',
- $this->sourceTransaction->id,
- $this->sourceTransaction->foreign_amount
- ));
+ $this->getSourceInformation($transfer);
+ $this->getDestinationInformation($transfer);
+
+ // unexpectedly, either one is null:
+
+ if ($this->isEmptyTransactions()) {
+ $this->friendlyError(sprintf('Source or destination information for transaction journal #%d is null. Cannot fix this one.', $transfer->id));
+
+ return;
}
- }
- /**
- * If the foreign amount of the destination transaction is null, but that of the other isn't, use this piece of code
- * to restore it.
- */
- private function fixDestNullForeignAmount(): void
- {
- if (null === $this->destinationTransaction->foreign_amount && null !== $this->sourceTransaction->foreign_amount) {
- $this->destinationTransaction->foreign_amount = bcmul($this->sourceTransaction->foreign_amount, '-1');
- $this->destinationTransaction->save();
- ++$this->count;
- $this->friendlyInfo(sprintf(
- 'Restored foreign amount of destination transaction #%d to %s',
- $this->destinationTransaction->id,
- $this->destinationTransaction->foreign_amount
+ // both accounts must have currency preference:
+
+ if ($this->isNoCurrencyPresent()) {
+ $this->friendlyError(sprintf(
+ 'Source or destination accounts for transaction journal #%d have no currency information. Cannot fix this one.',
+ $transfer->id
));
- }
- }
- /**
- * This method makes sure that the transaction journal uses the currency given in the source transaction.
- */
- private function fixTransactionJournalCurrency(TransactionJournal $journal): void
- {
- if ((int) $journal->transaction_currency_id !== $this->sourceCurrency->id) {
- $oldCurrencyCode = $journal->transactionCurrency->code ?? '(nothing)';
- $journal->transaction_currency_id = $this->sourceCurrency->id;
- $message = sprintf(
- 'Transfer #%d ("%s") has been updated to use %s instead of %s.',
- $journal->id,
- $journal->description,
- $this->sourceCurrency->code,
- $oldCurrencyCode
- );
- ++$this->count;
- $this->friendlyInfo($message);
- $journal->save();
+ return;
}
- }
- private function markAsExecuted(): void
- {
- FireflyConfig::set(self::CONFIG_NAME, true);
+ // fix source transaction having no currency.
+ $this->fixSourceNoCurrency();
+
+ // fix source transaction having bad currency.
+ $this->fixSourceUnmatchedCurrency();
+
+ // fix destination transaction having no currency.
+ $this->fixDestNoCurrency();
+
+ // fix destination transaction having bad currency.
+ $this->fixDestinationUnmatchedCurrency();
+
+ // remove foreign currency information if not necessary.
+ $this->fixInvalidForeignCurrency();
+ // correct foreign currency info if necessary.
+ $this->fixMismatchedForeignCurrency();
+
+ // restore missing foreign currency amount.
+ $this->fixSourceNullForeignAmount();
+
+ $this->fixDestNullForeignAmount();
+
+ // fix journal itself:
+ $this->fixTransactionJournalCurrency($transfer);
}
}
diff --git a/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php
index 58439f0d71..1b886447a0 100644
--- a/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php
+++ b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php
@@ -72,97 +72,24 @@ class UpgradesVariousCurrencyInformation extends Command
return 0;
}
- /**
- * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
- * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
- * be called from the handle method instead of using the constructor to initialize the command.
- */
- private function stupidLaravel(): void
- {
- $this->count = 0;
- $this->accountCurrencies = [];
- $this->accountRepos = app(AccountRepositoryInterface::class);
- $this->journalRepos = app(JournalRepositoryInterface::class);
- $this->cliRepos = app(JournalCLIRepositoryInterface::class);
- }
-
- private function isExecuted(): bool
- {
- $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
-
- return (bool) $configVar?->data;
- }
-
- /**
- * This routine verifies that withdrawals, deposits and opening balances have the correct currency settings for
- * the accounts they are linked to.
- * Both source and destination must match the respective currency preference of the related asset account.
- * So FF3 must verify all transactions.
- */
- private function updateOtherJournalsCurrencies(): void
+ private function getCurrency(Account $account): ?TransactionCurrency
{
- $set = $this->cliRepos->getAllJournals([
- TransactionTypeEnum::WITHDRAWAL->value,
- TransactionTypeEnum::DEPOSIT->value,
- TransactionTypeEnum::OPENING_BALANCE->value,
- TransactionTypeEnum::RECONCILIATION->value,
- ]);
-
- /** @var TransactionJournal $journal */
- foreach ($set as $journal) {
- $this->updateJournalCurrency($journal);
+ $accountId = $account->id;
+ if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) {
+ return null;
}
- }
-
- private function updateJournalCurrency(TransactionJournal $journal): void
- {
- $this->accountRepos->setUser($journal->user);
- $this->journalRepos->setUser($journal->user);
- $this->cliRepos->setUser($journal->user);
-
- $leadTransaction = $this->getLeadTransaction($journal);
-
- if (!$leadTransaction instanceof Transaction) {
- $this->friendlyError(sprintf('Could not reliably determine which transaction is in the lead for transaction journal #%d.', $journal->id));
-
- return;
+ if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) {
+ return $this->accountCurrencies[$accountId];
}
-
- $account = $leadTransaction->account;
- $currency = $this->getCurrency($account);
- $isMultiCurrency = $this->isMultiCurrency($account);
+ $currency = $this->accountRepos->getAccountCurrency($account);
if (!$currency instanceof TransactionCurrency) {
- $this->friendlyError(sprintf(
- 'Account #%d ("%s") has no currency preference, so transaction journal #%d can\'t be corrected',
- $account->id,
- $account->name,
- $journal->id
- ));
- ++$this->count;
+ $this->accountCurrencies[$accountId] = 0;
- return;
+ return null;
}
- // fix each transaction:
- $journal->transactions->each(static function (Transaction $transaction) use ($currency, $isMultiCurrency): void {
- if (null === $transaction->transaction_currency_id) {
- $transaction->transaction_currency_id = $currency->id;
- $transaction->save();
- }
+ $this->accountCurrencies[$accountId] = $currency;
- // when mismatch in transaction:
- if ($transaction->transaction_currency_id !== $currency->id && !$isMultiCurrency) {
- $transaction->foreign_currency_id = $transaction->transaction_currency_id;
- $transaction->foreign_amount = $transaction->amount;
- $transaction->transaction_currency_id = $currency->id;
- $transaction->save();
- }
- });
- // also update the journal, of course:
- if (!$isMultiCurrency) {
- $journal->transaction_currency_id = $currency->id;
- }
- ++$this->count;
- $journal->save();
+ return $currency;
}
/**
@@ -216,24 +143,11 @@ class UpgradesVariousCurrencyInformation extends Command
return $lead;
}
- private function getCurrency(Account $account): ?TransactionCurrency
+ private function isExecuted(): bool
{
- $accountId = $account->id;
- if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) {
- return null;
- }
- if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) {
- return $this->accountCurrencies[$accountId];
- }
- $currency = $this->accountRepos->getAccountCurrency($account);
- if (!$currency instanceof TransactionCurrency) {
- $this->accountCurrencies[$accountId] = 0;
-
- return null;
- }
- $this->accountCurrencies[$accountId] = $currency;
+ $configVar = FireflyConfig::get(self::CONFIG_NAME, false);
- return $currency;
+ return (bool) $configVar?->data;
}
private function isMultiCurrency(Account $account): bool
@@ -250,4 +164,90 @@ class UpgradesVariousCurrencyInformation extends Command
{
FireflyConfig::set(self::CONFIG_NAME, true);
}
+
+ /**
+ * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is
+ * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should
+ * be called from the handle method instead of using the constructor to initialize the command.
+ */
+ private function stupidLaravel(): void
+ {
+ $this->count = 0;
+ $this->accountCurrencies = [];
+ $this->accountRepos = app(AccountRepositoryInterface::class);
+ $this->journalRepos = app(JournalRepositoryInterface::class);
+ $this->cliRepos = app(JournalCLIRepositoryInterface::class);
+ }
+
+ private function updateJournalCurrency(TransactionJournal $journal): void
+ {
+ $this->accountRepos->setUser($journal->user);
+ $this->journalRepos->setUser($journal->user);
+ $this->cliRepos->setUser($journal->user);
+
+ $leadTransaction = $this->getLeadTransaction($journal);
+
+ if (!$leadTransaction instanceof Transaction) {
+ $this->friendlyError(sprintf('Could not reliably determine which transaction is in the lead for transaction journal #%d.', $journal->id));
+
+ return;
+ }
+
+ $account = $leadTransaction->account;
+ $currency = $this->getCurrency($account);
+ $isMultiCurrency = $this->isMultiCurrency($account);
+ if (!$currency instanceof TransactionCurrency) {
+ $this->friendlyError(sprintf(
+ 'Account #%d ("%s") has no currency preference, so transaction journal #%d can\'t be corrected',
+ $account->id,
+ $account->name,
+ $journal->id
+ ));
+ ++$this->count;
+
+ return;
+ }
+ // fix each transaction:
+ $journal->transactions->each(static function (Transaction $transaction) use ($currency, $isMultiCurrency): void {
+ if (null === $transaction->transaction_currency_id) {
+ $transaction->transaction_currency_id = $currency->id;
+ $transaction->save();
+ }
+
+ // when mismatch in transaction:
+ if ($transaction->transaction_currency_id !== $currency->id && !$isMultiCurrency) {
+ $transaction->foreign_currency_id = $transaction->transaction_currency_id;
+ $transaction->foreign_amount = $transaction->amount;
+ $transaction->transaction_currency_id = $currency->id;
+ $transaction->save();
+ }
+ });
+ // also update the journal, of course:
+ if (!$isMultiCurrency) {
+ $journal->transaction_currency_id = $currency->id;
+ }
+ ++$this->count;
+ $journal->save();
+ }
+
+ /**
+ * This routine verifies that withdrawals, deposits and opening balances have the correct currency settings for
+ * the accounts they are linked to.
+ * Both source and destination must match the respective currency preference of the related asset account.
+ * So FF3 must verify all transactions.
+ */
+ private function updateOtherJournalsCurrencies(): void
+ {
+ $set = $this->cliRepos->getAllJournals([
+ TransactionTypeEnum::WITHDRAWAL->value,
+ TransactionTypeEnum::DEPOSIT->value,
+ TransactionTypeEnum::OPENING_BALANCE->value,
+ TransactionTypeEnum::RECONCILIATION->value,
+ ]);
+
+ /** @var TransactionJournal $journal */
+ foreach ($set as $journal) {
+ $this->updateJournalCurrency($journal);
+ }
+ }
}
diff --git a/app/Console/Commands/Upgrade/UpgradesWebhooks.php b/app/Console/Commands/Upgrade/UpgradesWebhooks.php
index 1249e8d425..93c19d25ee 100644
--- a/app/Console/Commands/Upgrade/UpgradesWebhooks.php
+++ b/app/Console/Commands/Upgrade/UpgradesWebhooks.php
@@ -69,18 +69,9 @@ class UpgradesWebhooks extends Command
return (bool) $configVar?->data;
}
- private function upgradeWebhooks(): void
+ private function markAsExecuted(): void
{
- $set = Webhook::where('delivery', '>', 1)
- ->orWhere('trigger', '>', 1)
- ->orWhere('response', '>', 1)
- ->get()
- ;
-
- /** @var Webhook $webhook */
- foreach ($set as $webhook) {
- $this->upgradeWebhook($webhook);
- }
+ FireflyConfig::set(self::CONFIG_NAME, true);
}
private function upgradeWebhook(Webhook $webhook): void
@@ -111,8 +102,17 @@ class UpgradesWebhooks extends Command
$this->friendlyPositive(sprintf('Webhook #%d upgraded.', $webhook->id));
}
- private function markAsExecuted(): void
+ private function upgradeWebhooks(): void
{
- FireflyConfig::set(self::CONFIG_NAME, true);
+ $set = Webhook::where('delivery', '>', 1)
+ ->orWhere('trigger', '>', 1)
+ ->orWhere('response', '>', 1)
+ ->get()
+ ;
+
+ /** @var Webhook $webhook */
+ foreach ($set as $webhook) {
+ $this->upgradeWebhook($webhook);
+ }
}
}
diff --git a/app/Console/Commands/VerifiesAccessToken.php b/app/Console/Commands/VerifiesAccessToken.php
index 3726eb6a36..147dd83476 100644
--- a/app/Console/Commands/VerifiesAccessToken.php
+++ b/app/Console/Commands/VerifiesAccessToken.php
@@ -37,6 +37,15 @@ use Illuminate\Support\Facades\Log;
*/
trait VerifiesAccessToken
{
+ /**
+ * Abstract method to make sure trait knows about method "option".
+ *
+ * @param null|string $key
+ *
+ * @return mixed
+ */
+ abstract public function option($key = null);
+
/**
* @throws FireflyException
*/
@@ -54,15 +63,6 @@ trait VerifiesAccessToken
return $user;
}
- /**
- * Abstract method to make sure trait knows about method "option".
- *
- * @param null|string $key
- *
- * @return mixed
- */
- abstract public function option($key = null);
-
/**
* Returns false when given token does not match given user token.
*/
diff --git a/app/Events/Model/Budget/CreatedBudget.php b/app/Events/Model/Budget/CreatedBudget.php
index af7d187af6..44382bdf84 100644
--- a/app/Events/Model/Budget/CreatedBudget.php
+++ b/app/Events/Model/Budget/CreatedBudget.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* CreatedBudget.php
* Copyright (c) 2026 [email protected]
@@ -29,6 +32,8 @@ class CreatedBudget extends Event
{
use SerializesModels;
- public function __construct(public Budget $budget, public bool $createWebhookMessages) {}
-
+ public function __construct(
+ public Budget $budget,
+ public bool $createWebhookMessages
+ ) {}
}
diff --git a/app/Events/Model/Budget/DestroyedBudget.php b/app/Events/Model/Budget/DestroyedBudget.php
index e581bb3462..bf76737f80 100644
--- a/app/Events/Model/Budget/DestroyedBudget.php
+++ b/app/Events/Model/Budget/DestroyedBudget.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* DestroyedBudget.php
* Copyright (c) 2026 [email protected]
@@ -22,15 +25,15 @@
namespace FireflyIII\Events\Model\Budget;
use FireflyIII\Events\Event;
-use FireflyIII\Models\Budget;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class DestroyedBudget extends Event
{
- public function __construct() {
- Log::debug('Created event DestroyedBudget');
- }
use SerializesModels;
+ public function __construct()
+ {
+ Log::debug('Created event DestroyedBudget');
+ }
}
diff --git a/app/Events/Model/Budget/DestroyingBudget.php b/app/Events/Model/Budget/DestroyingBudget.php
index 494619b5f2..46ed0f4800 100644
--- a/app/Events/Model/Budget/DestroyingBudget.php
+++ b/app/Events/Model/Budget/DestroyingBudget.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* DestroyingBudget.php
* Copyright (c) 2026 [email protected]
@@ -28,10 +31,11 @@ use Illuminate\Support\Facades\Log;
class DestroyingBudget extends Event
{
- public function __construct(public Budget $budget)
- {
+ use SerializesModels;
+
+ public function __construct(
+ public Budget $budget
+ ) {
Log::debug(sprintf('Created event DestroyingBudget(#%d)', $budget->id));
}
-
- use SerializesModels;
}
diff --git a/app/Events/Model/Budget/UpdatedBudget.php b/app/Events/Model/Budget/UpdatedBudget.php
index bb2ee6d785..9d676765ee 100644
--- a/app/Events/Model/Budget/UpdatedBudget.php
+++ b/app/Events/Model/Budget/UpdatedBudget.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* UpdatedBudget.php
* Copyright (c) 2026 [email protected]
@@ -29,6 +32,8 @@ class UpdatedBudget extends Event
{
use SerializesModels;
- public function __construct(public Budget $budget, public bool $createWebhookMessages) {}
-
+ public function __construct(
+ public Budget $budget,
+ public bool $createWebhookMessages
+ ) {}
}
diff --git a/app/Events/Model/BudgetLimit/CreatedBudgetLimit.php b/app/Events/Model/BudgetLimit/CreatedBudgetLimit.php
index acde1656e4..85b1ac5669 100644
--- a/app/Events/Model/BudgetLimit/CreatedBudgetLimit.php
+++ b/app/Events/Model/BudgetLimit/CreatedBudgetLimit.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* CreatedBudgetLimit.php
* Copyright (c) 2026 [email protected]
@@ -29,6 +32,8 @@ class CreatedBudgetLimit extends Event
{
use SerializesModels;
- public function __construct(public BudgetLimit $budgetLimit, public bool $createWebhookMessages) {}
-
+ public function __construct(
+ public BudgetLimit $budgetLimit,
+ public bool $createWebhookMessages
+ ) {}
}
diff --git a/app/Events/Model/BudgetLimit/DestroyedBudgetLimit.php b/app/Events/Model/BudgetLimit/DestroyedBudgetLimit.php
index 9b976f4986..5e09deda1b 100644
--- a/app/Events/Model/BudgetLimit/DestroyedBudgetLimit.php
+++ b/app/Events/Model/BudgetLimit/DestroyedBudgetLimit.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* DestroyedBudgetLimit.php
* Copyright (c) 2026 [email protected]
@@ -31,6 +34,11 @@ class DestroyedBudgetLimit extends Event
{
use SerializesModels;
- public function __construct(public User $user, public Budget $budget, public Carbon $start, public Carbon $end, public bool $createWebhookMessages) {}
-
+ public function __construct(
+ public User $user,
+ public Budget $budget,
+ public Carbon $start,
+ public Carbon $end,
+ public bool $createWebhookMessages
+ ) {}
}
diff --git a/app/Events/Model/BudgetLimit/UpdatedBudgetLimit.php b/app/Events/Model/BudgetLimit/UpdatedBudgetLimit.php
index 7a973de487..3a0e3b84c4 100644
--- a/app/Events/Model/BudgetLimit/UpdatedBudgetLimit.php
+++ b/app/Events/Model/BudgetLimit/UpdatedBudgetLimit.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* UpdatedBudgetLimit.php
* Copyright (c) 2026 [email protected]
@@ -29,5 +32,8 @@ class UpdatedBudgetLimit extends Event
{
use SerializesModels;
- public function __construct(public BudgetLimit $budgetLimit, public bool $createWebhookMessages) {}
+ public function __construct(
+ public BudgetLimit $budgetLimit,
+ public bool $createWebhookMessages
+ ) {}
}
diff --git a/app/Exceptions/GracefulNotFoundHandler.php b/app/Exceptions/GracefulNotFoundHandler.php
index 1b53d0456d..c5794b2925 100644
--- a/app/Exceptions/GracefulNotFoundHandler.php
+++ b/app/Exceptions/GracefulNotFoundHandler.php
@@ -181,46 +181,6 @@ class GracefulNotFoundHandler extends ExceptionHandler
return redirect(route('accounts.index', [$shortType]));
}
- /**
- * @return Response
- *
- * @throws Throwable
- */
- private function handleGroup(Request $request, Throwable $exception)
- {
- Log::debug('404 page is probably a deleted group. Redirect to overview of group types.');
-
- /** @var User $user */
- $user = auth()->user();
- $route = $request->route();
- $param = $route->parameter('transactionGroup');
- $groupId = is_object($param) ? 0 : (int) $param;
-
- /** @var null|TransactionGroup $group */
- $group = $user->transactionGroups()->withTrashed()->find($groupId);
- if (null === $group) {
- Log::error(sprintf('Could not find group %d, so give big fat error.', $groupId));
-
- return parent::render($request, $exception);
- }
-
- /** @var null|TransactionJournal $journal */
- $journal = $group->transactionJournals()->withTrashed()->first();
- if (null === $journal) {
- Log::error(sprintf('Could not find journal for group %d, so give big fat error.', $groupId));
-
- return parent::render($request, $exception);
- }
- $type = $journal->transactionType->type;
- $request->session()->reflash();
-
- if (TransactionTypeEnum::RECONCILIATION->value === $type) {
- return redirect(route('accounts.index', ['asset']));
- }
-
- return redirect(route('transactions.index', [strtolower((string) $type)]));
- }
-
/**
* @return Response
*
@@ -265,4 +225,44 @@ class GracefulNotFoundHandler extends ExceptionHandler
return parent::render($request, $exception);
}
+
+ /**
+ * @return Response
+ *
+ * @throws Throwable
+ */
+ private function handleGroup(Request $request, Throwable $exception)
+ {
+ Log::debug('404 page is probably a deleted group. Redirect to overview of group types.');
+
+ /** @var User $user */
+ $user = auth()->user();
+ $route = $request->route();
+ $param = $route->parameter('transactionGroup');
+ $groupId = is_object($param) ? 0 : (int) $param;
+
+ /** @var null|TransactionGroup $group */
+ $group = $user->transactionGroups()->withTrashed()->find($groupId);
+ if (null === $group) {
+ Log::error(sprintf('Could not find group %d, so give big fat error.', $groupId));
+
+ return parent::render($request, $exception);
+ }
+
+ /** @var null|TransactionJournal $journal */
+ $journal = $group->transactionJournals()->withTrashed()->first();
+ if (null === $journal) {
+ Log::error(sprintf('Could not find journal for group %d, so give big fat error.', $groupId));
+
+ return parent::render($request, $exception);
+ }
+ $type = $journal->transactionType->type;
+ $request->session()->reflash();
+
+ if (TransactionTypeEnum::RECONCILIATION->value === $type) {
+ return redirect(route('accounts.index', ['asset']));
+ }
+
+ return redirect(route('transactions.index', [strtolower((string) $type)]));
+ }
}
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php
index 7813b96e35..f541f86978 100644
--- a/app/Exceptions/Handler.php
+++ b/app/Exceptions/Handler.php
@@ -260,11 +260,6 @@ class Handler extends ExceptionHandler
parent::report($e);
}
- private function shouldntReportLocal(Throwable $e): bool
- {
- return null !== Arr::first($this->dontReport, static fn ($type): bool => $e instanceof $type);
- }
-
/**
* Convert a validation exception into a response.
*
@@ -298,4 +293,9 @@ class Handler extends ExceptionHandler
return null !== $previousHost && $previousHost === $safeHost ? $previous : $safe;
}
+
+ private function shouldntReportLocal(Throwable $e): bool
+ {
+ return null !== Arr::first($this->dontReport, static fn ($type): bool => $e instanceof $type);
+ }
}
diff --git a/app/Factory/AccountFactory.php b/app/Factory/AccountFactory.php
index 0b61b7389c..43fe4109ac 100644
--- a/app/Factory/AccountFactory.php
+++ b/app/Factory/AccountFactory.php
@@ -67,6 +67,43 @@ class AccountFactory
$this->validFields = config('firefly.valid_account_fields');
}
+ /**
+ * @throws FireflyException
+ */
+ public function create(array $data): Account
+ {
+ Log::debug('Now in AccountFactory::create()');
+ $type = $this->getAccountType($data);
+ $data['iban'] = $this->filterIban($data['iban'] ?? null);
+
+ // account may exist already:
+ $return = $this->find($data['name'], $type->type);
+
+ if ($return instanceof Account) {
+ return $return;
+ }
+
+ $return = $this->createAccount($type, $data);
+
+ event(new CreatedNewAccount($return));
+
+ return $return;
+ }
+
+ public function find(string $accountName, string $accountType): ?Account
+ {
+ Log::debug(sprintf('Now in AccountFactory::find("%s", "%s")', $accountName, $accountType));
+ $type = AccountType::whereType($accountType)->first();
+
+ /** @var null|Account */
+ return $this->user
+ ->accounts()
+ ->where('account_type_id', $type->id)
+ ->where('name', $accountName)
+ ->first()
+ ;
+ }
+
/**
* @throws FireflyException
*/
@@ -104,27 +141,10 @@ class AccountFactory
return $return;
}
- /**
- * @throws FireflyException
- */
- public function create(array $data): Account
+ public function setUser(User $user): void
{
- Log::debug('Now in AccountFactory::create()');
- $type = $this->getAccountType($data);
- $data['iban'] = $this->filterIban($data['iban'] ?? null);
-
- // account may exist already:
- $return = $this->find($data['name'], $type->type);
-
- if ($return instanceof Account) {
- return $return;
- }
-
- $return = $this->createAccount($type, $data);
-
- event(new CreatedNewAccount($return));
-
- return $return;
+ $this->user = $user;
+ $this->accountRepository->setUser($user);
}
/**
@@ -160,18 +180,28 @@ class AccountFactory
return $result;
}
- public function find(string $accountName, string $accountType): ?Account
+ /**
+ * @throws FireflyException
+ */
+ private function cleanMetaDataArray(Account $account, array $data): array
{
- Log::debug(sprintf('Now in AccountFactory::find("%s", "%s")', $accountName, $accountType));
- $type = AccountType::whereType($accountType)->first();
+ $currencyId = array_key_exists('currency_id', $data) ? (int) $data['currency_id'] : 0;
+ $currencyCode = array_key_exists('currency_code', $data) ? (string) $data['currency_code'] : '';
+ $accountRole = array_key_exists('account_role', $data) ? (string) $data['account_role'] : null;
+ $currency = $this->getCurrency($currencyId, $currencyCode);
- /** @var null|Account */
- return $this->user
- ->accounts()
- ->where('account_type_id', $type->id)
- ->where('name', $accountName)
- ->first()
- ;
+ // only asset account may have a role:
+ if (AccountTypeEnum::ASSET->value !== $account->accountType->type) {
+ $accountRole = '';
+ }
+ // only liability may have direction:
+ if (array_key_exists('liability_direction', $data) && !in_array($account->accountType->type, config('firefly.valid_liabilities'), true)) {
+ $data['liability_direction'] = null;
+ }
+ $data['account_role'] = $accountRole;
+ $data['currency_id'] = $currency->id;
+
+ return $data;
}
/**
@@ -245,25 +275,27 @@ class AccountFactory
/**
* @throws FireflyException
*/
- private function cleanMetaDataArray(Account $account, array $data): array
+ private function storeCreditLiability(Account $account, array $data): void
{
- $currencyId = array_key_exists('currency_id', $data) ? (int) $data['currency_id'] : 0;
- $currencyCode = array_key_exists('currency_code', $data) ? (string) $data['currency_code'] : '';
- $accountRole = array_key_exists('account_role', $data) ? (string) $data['account_role'] : null;
- $currency = $this->getCurrency($currencyId, $currencyCode);
-
- // only asset account may have a role:
- if (AccountTypeEnum::ASSET->value !== $account->accountType->type) {
- $accountRole = '';
- }
- // only liability may have direction:
- if (array_key_exists('liability_direction', $data) && !in_array($account->accountType->type, config('firefly.valid_liabilities'), true)) {
- $data['liability_direction'] = null;
+ Log::debug('storeCreditLiability');
+ $account->refresh();
+ $accountType = $account->accountType->type;
+ $direction = $this->accountRepository->getMetaValue($account, 'liability_direction');
+ $valid = config('firefly.valid_liabilities');
+ if (in_array($accountType, $valid, true)) {
+ Log::debug('Is a liability with credit ("i am owed") direction.');
+ if ($this->validOBData($data)) {
+ Log::debug('Has valid CL data.');
+ $openingBalance = $data['opening_balance'];
+ $openingBalanceDate = $data['opening_balance_date'];
+ // store credit transaction.
+ $this->updateCreditTransaction($account, $direction, $openingBalance, $openingBalanceDate);
+ }
+ if (!$this->validOBData($data)) {
+ Log::debug('Does NOT have valid CL data, deletr any CL transaction.');
+ $this->deleteCreditTransaction($account);
+ }
}
- $data['account_role'] = $accountRole;
- $data['currency_id'] = $currency->id;
-
- return $data;
}
private function storeMetaData(Account $account, array $data): void
@@ -324,32 +356,6 @@ class AccountFactory
}
}
- /**
- * @throws FireflyException
- */
- private function storeCreditLiability(Account $account, array $data): void
- {
- Log::debug('storeCreditLiability');
- $account->refresh();
- $accountType = $account->accountType->type;
- $direction = $this->accountRepository->getMetaValue($account, 'liability_direction');
- $valid = config('firefly.valid_liabilities');
- if (in_array($accountType, $valid, true)) {
- Log::debug('Is a liability with credit ("i am owed") direction.');
- if ($this->validOBData($data)) {
- Log::debug('Has valid CL data.');
- $openingBalance = $data['opening_balance'];
- $openingBalanceDate = $data['opening_balance_date'];
- // store credit transaction.
- $this->updateCreditTransaction($account, $direction, $openingBalance, $openingBalanceDate);
- }
- if (!$this->validOBData($data)) {
- Log::debug('Does NOT have valid CL data, deletr any CL transaction.');
- $this->deleteCreditTransaction($account);
- }
- }
- }
-
/**
* @throws FireflyException
*/
@@ -370,10 +376,4 @@ class AccountFactory
$updateService->setUser($account->user);
$updateService->update($account, ['order' => $order]);
}
-
- public function setUser(User $user): void
- {
- $this->user = $user;
- $this->accountRepository->setUser($user);
- }
}
diff --git a/app/Factory/AccountMetaFactory.php b/app/Factory/AccountMetaFactory.php
index d2b8d7a80f..b8f7b3e8ff 100644
--- a/app/Factory/AccountMetaFactory.php
+++ b/app/Factory/AccountMetaFactory.php
@@ -33,6 +33,11 @@ use FireflyIII\Support\Facades\Steam;
*/
class AccountMetaFactory
{
+ public function create(array $data): ?AccountMeta
+ {
+ return AccountMeta::create($data);
+ }
+
/**
* Create update or delete meta data.
*/
@@ -63,9 +68,4 @@ class AccountMetaFactory
return $entry;
}
-
- public function create(array $data): ?AccountMeta
- {
- return AccountMeta::create($data);
- }
}
diff --git a/app/Factory/CategoryFactory.php b/app/Factory/CategoryFactory.php
index a5ddb51b9d..847728d2f3 100644
--- a/app/Factory/CategoryFactory.php
+++ b/app/Factory/CategoryFactory.php
@@ -36,6 +36,16 @@ class CategoryFactory
{
private User $user;
+ public function findByName(string $name): ?Category
+ {
+ /** @var null|Category */
+ return $this->user
+ ->categories()
+ ->where('name', $name)
+ ->first()
+ ;
+ }
+
/**
* @throws FireflyException
*/
@@ -77,16 +87,6 @@ class CategoryFactory
return null;
}
- public function findByName(string $name): ?Category
- {
- /** @var null|Category */
- return $this->user
- ->categories()
- ->where('name', $name)
- ->first()
- ;
- }
-
public function setUser(User $user): void
{
$this->user = $user;
diff --git a/app/Factory/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php
index 62ac992de6..209c7aad27 100644
--- a/app/Factory/PiggyBankFactory.php
+++ b/app/Factory/PiggyBankFactory.php
@@ -59,93 +59,6 @@ class PiggyBankFactory
$this->piggyBankRepository = app(PiggyBankRepositoryInterface::class);
}
- public function setUser(User $user): void
- {
- $this->user = $user;
- $this->currencyRepository->setUser($user);
- $this->accountRepository->setUser($user);
- $this->piggyBankRepository->setUser($user);
- }
-
- /**
- * Store a piggy bank or come back with an exception.
- */
- public function store(array $data): PiggyBank
- {
- $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::createQuietly($piggyBankData);
- } catch (QueryException $e) {
- 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 ($objectGroup instanceof ObjectGroup) {
- $piggyBank->objectGroups()->sync([$objectGroup->id]);
- }
- }
- // try also with ID
- $objectGroupId = (int) ($data['object_group_id'] ?? 0);
- if (0 !== $objectGroupId) {
- $objectGroup = $this->findObjectGroupById($objectGroupId);
- if ($objectGroup instanceof ObjectGroup) {
- $piggyBank->objectGroups()->sync([$objectGroup->id]);
- }
- }
- Log::debug('Touch piggy bank');
- $piggyBank->encrypted = false;
- $piggyBank->save();
- $piggyBank->touch();
-
- return $piggyBank;
- }
-
- private function getCurrency(array $data): TransactionCurrency
- {
- // currency:
- $primaryCurrency = Amount::getPrimaryCurrency();
- $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 ??= $primaryCurrency;
-
- return $currency;
- }
-
public function find(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank
{
$piggyBankId = (int) $piggyBankId;
@@ -188,45 +101,6 @@ class PiggyBankFactory
;
}
- 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->saveQuietly();
-
- return $piggyBank;
- }
-
- public function resetOrder(): void
- {
- // 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(['objectGroups'])
- ->orderBy('piggy_banks.order', 'ASC')
- ->get(['piggy_banks.*'])
- ;
- $current = 1;
- foreach ($set as $piggyBank) {
- if ($piggyBank->order !== $current) {
- 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->piggyBankRepository->getPiggyBanks()->max('order');
- }
-
public function linkToAccountIds(PiggyBank $piggyBank, array $accounts): void
{
Log::debug(sprintf('Linking piggy bank #%d to %d accounts.', $piggyBank->id, count($accounts)), $accounts);
@@ -316,4 +190,130 @@ class PiggyBankFactory
Log::warning('No accounts to link to piggy bank, will not change whatever is there now.');
}
}
+
+ public function resetOrder(): void
+ {
+ // 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(['objectGroups'])
+ ->orderBy('piggy_banks.order', 'ASC')
+ ->get(['piggy_banks.*'])
+ ;
+ $current = 1;
+ foreach ($set as $piggyBank) {
+ if ($piggyBank->order !== $current) {
+ 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 setUser(User $user): void
+ {
+ $this->user = $user;
+ $this->currencyRepository->setUser($user);
+ $this->accountRepository->setUser($user);
+ $this->piggyBankRepository->setUser($user);
+ }
+
+ /**
+ * Store a piggy bank or come back with an exception.
+ */
+ public function store(array $data): PiggyBank
+ {
+ $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::createQuietly($piggyBankData);
+ } catch (QueryException $e) {
+ 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 ($objectGroup instanceof ObjectGroup) {
+ $piggyBank->objectGroups()->sync([$objectGroup->id]);
+ }
+ }
+ // try also with ID
+ $objectGroupId = (int) ($data['object_group_id'] ?? 0);
+ if (0 !== $objectGroupId) {
+ $objectGroup = $this->findObjectGroupById($objectGroupId);
+ if ($objectGroup instanceof ObjectGroup) {
+ $piggyBank->objectGroups()->sync([$objectGroup->id]);
+ }
+ }
+ Log::debug('Touch piggy bank');
+ $piggyBank->encrypted = false;
+ $piggyBank->save();
+ $piggyBank->touch();
+
+ return $piggyBank;
+ }
+
+ private function getCurrency(array $data): TransactionCurrency
+ {
+ // currency:
+ $primaryCurrency = Amount::getPrimaryCurrency();
+ $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 ??= $primaryCurrency;
+
+ return $currency;
+ }
+
+ private function getMaxOrder(): int
+ {
+ return (int) $this->piggyBankRepository->getPiggyBanks()->max('order');
+ }
+
+ 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->saveQuietly();
+
+ return $piggyBank;
+ }
}
diff --git a/app/Factory/TagFactory.php b/app/Factory/TagFactory.php
index 5e2c44de64..c4988089eb 100644
--- a/app/Factory/TagFactory.php
+++ b/app/Factory/TagFactory.php
@@ -38,6 +38,38 @@ class TagFactory
private User $user;
private UserGroup $userGroup;
+ public function create(array $data): ?Tag
+ {
+ $zoomLevel = 0 === (int) $data['zoom_level'] ? null : (int) $data['zoom_level'];
+ $latitude = 0.0 === (float) $data['latitude'] ? null : (float) $data['latitude']; // intentional float
+ $longitude = 0.0 === (float) $data['longitude'] ? null : (float) $data['longitude']; // intentional float
+ $array = [
+ 'user_id' => $this->user->id,
+ 'user_group_id' => $this->userGroup->id,
+ 'tag' => trim((string) $data['tag']),
+ 'tag_mode' => 'nothing',
+ 'date' => $data['date'],
+ 'description' => $data['description'],
+ 'latitude' => null,
+ 'longitude' => null,
+ 'zoomLevel' => null,
+ ];
+
+ /** @var null|Tag $tag */
+ $tag = Tag::create($array);
+ if (!in_array(null, [$tag, $latitude, $longitude], true)) {
+ // create location object.
+ $location = new Location();
+ $location->latitude = $latitude;
+ $location->longitude = $longitude;
+ $location->zoom_level = $zoomLevel;
+ $location->locatable()->associate($tag);
+ $location->save();
+ }
+
+ return $tag;
+ }
+
public function findOrCreate(string $tag): ?Tag
{
$tag = trim($tag);
@@ -72,38 +104,6 @@ class TagFactory
return $newTag;
}
- public function create(array $data): ?Tag
- {
- $zoomLevel = 0 === (int) $data['zoom_level'] ? null : (int) $data['zoom_level'];
- $latitude = 0.0 === (float) $data['latitude'] ? null : (float) $data['latitude']; // intentional float
- $longitude = 0.0 === (float) $data['longitude'] ? null : (float) $data['longitude']; // intentional float
- $array = [
- 'user_id' => $this->user->id,
- 'user_group_id' => $this->userGroup->id,
- 'tag' => trim((string) $data['tag']),
- 'tag_mode' => 'nothing',
- 'date' => $data['date'],
- 'description' => $data['description'],
- 'latitude' => null,
- 'longitude' => null,
- 'zoomLevel' => null,
- ];
-
- /** @var null|Tag $tag */
- $tag = Tag::create($array);
- if (!in_array(null, [$tag, $latitude, $longitude], true)) {
- // create location object.
- $location = new Location();
- $location->latitude = $latitude;
- $location->longitude = $longitude;
- $location->zoom_level = $zoomLevel;
- $location->locatable()->associate($tag);
- $location->save();
- }
-
- return $tag;
- }
-
public function setUser(User $user): void
{
$this->user = $user;
diff --git a/app/Factory/TransactionFactory.php b/app/Factory/TransactionFactory.php
index 2ea36c7a84..aa65c11ba7 100644
--- a/app/Factory/TransactionFactory.php
+++ b/app/Factory/TransactionFactory.php
@@ -65,6 +65,56 @@ class TransactionFactory
return $this->create(Steam::negative($amount), $foreignAmount);
}
+ /**
+ * Create transaction with positive amount (for destination accounts).
+ *
+ * @throws FireflyException
+ */
+ public function createPositive(string $amount, ?string $foreignAmount): Transaction
+ {
+ if ('' === $foreignAmount) {
+ $foreignAmount = null;
+ }
+ if (null !== $foreignAmount) {
+ $foreignAmount = Steam::positive($foreignAmount);
+ }
+
+ return $this->create(Steam::positive($amount), $foreignAmount);
+ }
+
+ public function setAccount(Account $account): void
+ {
+ $this->account = $account;
+ }
+
+ public function setAccountInformation(array $accountInformation): void
+ {
+ $this->accountInformation = $accountInformation;
+ }
+
+ public function setCurrency(TransactionCurrency $currency): void
+ {
+ $this->currency = $currency;
+ }
+
+ /**
+ * @param null|TransactionCurrency $foreignCurrency |null
+ */
+ public function setForeignCurrency(?TransactionCurrency $foreignCurrency): void
+ {
+ $this->foreignCurrency = $foreignCurrency;
+ }
+
+ public function setJournal(TransactionJournal $journal): void
+ {
+ $this->journal = $journal;
+ }
+
+ public function setReconciled(bool $reconciled): void
+ {
+ $this->reconciled = $reconciled;
+ }
+
/**
* @throws FireflyException
*/
@@ -156,54 +206,4 @@ class TransactionFactory
$service = app(AccountUpdateService::class);
$service->update($this->account, ['iban' => $this->accountInformation['iban']]);
}
-
- /**
- * Create transaction with positive amount (for destination accounts).
- *
- * @throws FireflyException
- */
- public function createPositive(string $amount, ?string $foreignAmount): Transaction
- {
- if ('' === $foreignAmount) {
- $foreignAmount = null;
- }
- if (null !== $foreignAmount) {
- $foreignAmount = Steam::positive($foreignAmount);
- }
-
- return $this->create(Steam::positive($amount), $foreignAmount);
- }
-
- public function setAccount(Account $account): void
- {
- $this->account = $account;
- }
-
- public function setAccountInformation(array $accountInformation): void
- {
- $this->accountInformation = $accountInformation;
- }
-
- public function setCurrency(TransactionCurrency $currency): void
- {
- $this->currency = $currency;
- }
-
- /**
- * @param null|TransactionCurrency $foreignCurrency |null
- */
- public function setForeignCurrency(?TransactionCurrency $foreignCurrency): void
- {
- $this->foreignCurrency = $foreignCurrency;
- }
-
- public function setJournal(TransactionJournal $journal): void
- {
- $this->journal = $journal;
- }
-
- public function setReconciled(bool $reconciled): void
- {
- $this->reconciled = $reconciled;
- }
}
diff --git a/app/Factory/TransactionJournalFactory.php b/app/Factory/TransactionJournalFactory.php
index 0648ea7127..b14a6dc06b 100644
--- a/app/Factory/TransactionJournalFactory.php
+++ b/app/Factory/TransactionJournalFactory.php
@@ -150,6 +150,74 @@ class TransactionJournalFactory
return $collection;
}
+ public function setErrorOnHash(bool $errorOnHash): void
+ {
+ $this->errorOnHash = $errorOnHash;
+ if ($errorOnHash) {
+ Log::info('Will trigger duplication alert for this journal.');
+ }
+ }
+
+ /**
+ * Set the user.
+ */
+ public function setUser(User $user): void
+ {
+ $this->user = $user;
+ $this->userGroup = $user->userGroup;
+ $this->currencyRepository->setUser($this->user);
+ $this->tagFactory->setUser($user);
+ $this->billRepository->setUser($this->user);
+ $this->budgetRepository->setUser($this->user);
+ $this->categoryRepository->setUser($this->user);
+ $this->piggyRepository->setUser($this->user);
+ $this->accountRepository->setUser($this->user);
+ }
+
+ public function setUserGroup(UserGroup $userGroup): void
+ {
+ $this->userGroup = $userGroup;
+ $this->currencyRepository->setUserGroup($userGroup);
+ $this->tagFactory->setUserGroup($userGroup);
+ $this->billRepository->setUserGroup($userGroup);
+ $this->budgetRepository->setUserGroup($userGroup);
+ $this->categoryRepository->setUserGroup($userGroup);
+ $this->piggyRepository->setUserGroup($userGroup);
+ $this->accountRepository->setUserGroup($userGroup);
+ }
+
+ protected function storeMeta(TransactionJournal $journal, array $data, string $field): void
+ {
+ $set = ['journal' => $journal, 'name' => $field, 'data' => (string) ($data[$field] ?? '')];
+ if (array_key_exists($field, $data) && $data[$field] instanceof Carbon) {
+ $data[$field]->setTimezone(config('app.timezone'));
+ Log::debug(sprintf('%s Date: %s (%s)', $field, $data[$field], $data[$field]->timezone->getName()));
+ $set['data'] = $data[$field]->format('Y-m-d H:i:s');
+ }
+
+ Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data']));
+
+ /** @var TransactionJournalMetaFactory $factory */
+ $factory = app(TransactionJournalMetaFactory::class);
+ $factory->updateOrCreate($set);
+ }
+
+ /**
+ * Set foreign currency to NULL if it's the same as the normal currency:
+ */
+ private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency
+ {
+ Log::debug(sprintf('Now in compareCurrencies("%s", "%s")', $currency?->code, $foreignCurrency?->code));
+ if (!$currency instanceof TransactionCurrency) {
+ return null;
+ }
+ if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id === $currency->id) {
+ return null;
+ }
+
+ return $foreignCurrency;
+ }
+
/**
* TODO typeOverrule: the account validator may have another opinion on the transaction type. not sure what to do
* with this.
@@ -341,22 +409,6 @@ class TransactionJournalFactory
return $journal;
}
- private function hashArray(NullArrayObject $row): string
- {
- unset($row['import_hash_v2'], $row['original_source']);
-
- try {
- $json = json_encode($row, JSON_THROW_ON_ERROR);
- } catch (JsonException $e) {
- Log::error(sprintf('Could not encode dataRow: %s', $e->getMessage()));
- $json = microtime();
- }
- $hash = hash('sha256', $json);
- Log::debug(sprintf('The hash is: %s', $hash), $row->getArrayCopy());
-
- return $hash;
- }
-
/**
* If this transaction already exists, throw an error.
*
@@ -392,87 +444,40 @@ class TransactionJournalFactory
}
/**
- * @throws FireflyException
+ * Force the deletion of an entire set of transaction journals and their meta object in case of
+ * an error creating a group.
*/
- private function validateAccounts(NullArrayObject $data): void
+ private function forceDeleteOnError(Collection $collection): void
{
- Log::debug(sprintf('Now in %s', __METHOD__));
- $transactionType = $data['type'] ?? 'invalid';
- $this->accountValidator->setUser($this->user);
- $this->accountValidator->setTransactionType($transactionType);
-
- // validate source account.
- $array = [
- 'id' => null !== $data['source_id'] ? (int) $data['source_id'] : null,
- 'name' => null !== $data['source_name'] ? (string) $data['source_name'] : null,
- 'iban' => null !== $data['source_iban'] ? (string) $data['source_iban'] : null,
- 'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null,
- ];
- $validSource = $this->accountValidator->validateSource($array);
-
- // do something with result:
- if (false === $validSource) {
- throw new FireflyException(sprintf('Source: %s', $this->accountValidator->sourceError));
- }
- Log::debug('Source seems valid.');
-
- // validate destination account
- $array = [
- 'id' => null !== $data['destination_id'] ? (int) $data['destination_id'] : null,
- 'name' => null !== $data['destination_name'] ? (string) $data['destination_name'] : null,
- 'iban' => null !== $data['destination_iban'] ? (string) $data['destination_iban'] : null,
- 'number' => null !== $data['destination_number'] ? (string) $data['destination_number'] : null,
- ];
+ Log::debug(sprintf('forceDeleteOnError on collection size %d item(s)', $collection->count()));
+ $service = app(JournalDestroyService::class);
- $validDestination = $this->accountValidator->validateDestination($array);
- // do something with result:
- if (false === $validDestination) {
- throw new FireflyException(sprintf('Destination: %s', $this->accountValidator->destError));
+ /** @var TransactionJournal $journal */
+ foreach ($collection as $journal) {
+ Log::debug(sprintf('forceDeleteOnError on journal #%d', $journal->id));
+ $service->destroy($journal);
}
}
- /**
- * Set the user.
- */
- public function setUser(User $user): void
+ private function forceTrDelete(Transaction $transaction): void
{
- $this->user = $user;
- $this->userGroup = $user->userGroup;
- $this->currencyRepository->setUser($this->user);
- $this->tagFactory->setUser($user);
- $this->billRepository->setUser($this->user);
- $this->budgetRepository->setUser($this->user);
- $this->categoryRepository->setUser($this->user);
- $this->piggyRepository->setUser($this->user);
- $this->accountRepository->setUser($this->user);
+ $transaction->delete();
}
- private function reconciliationSanityCheck(?Account $sourceAccount, ?Account $destinationAccount): array
+ private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency
{
- Log::debug(sprintf('Now in %s', __METHOD__));
- if ($sourceAccount instanceof Account && $destinationAccount instanceof Account) {
- Log::debug('Both accounts exist, simply return them.');
-
- return [$sourceAccount, $destinationAccount];
- }
- if (!$destinationAccount instanceof Account) {
- Log::debug('Destination account is NULL, source account is not.');
- $account = $this->accountRepository->getReconciliation($sourceAccount);
- Log::debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type));
-
- return [$sourceAccount, $account];
- }
-
- if (!$sourceAccount instanceof Account) { // @phpstan-ignore-line
- Log::debug('Source account is NULL, destination account is not.');
- $account = $this->accountRepository->getReconciliation($destinationAccount);
- Log::debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type));
+ Log::debug(sprintf('Now in getCurrency(#%d, "%s")', $currency?->id, $account->name));
- return [$account, $destinationAccount];
+ /** @var null|TransactionCurrency $preference */
+ $preference = $this->accountRepository->getAccountCurrency($account);
+ if (null === $preference && !$currency instanceof TransactionCurrency) {
+ // return user's default:
+ return Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
}
- Log::debug('Unused fallback'); // @phpstan-ignore-line
+ $result = $preference ?? $currency;
+ Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name));
- return [$sourceAccount, $destinationAccount];
+ return $result;
}
/**
@@ -496,36 +501,11 @@ class TransactionJournalFactory
};
}
- private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency
- {
- Log::debug(sprintf('Now in getCurrency(#%d, "%s")', $currency?->id, $account->name));
-
- /** @var null|TransactionCurrency $preference */
- $preference = $this->accountRepository->getAccountCurrency($account);
- if (null === $preference && !$currency instanceof TransactionCurrency) {
- // return user's default:
- return Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
- }
- $result = $preference ?? $currency;
- Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name));
-
- return $result;
- }
-
- /**
- * Set foreign currency to NULL if it's the same as the normal currency:
- */
- private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency
+ private function getDescription(string $description): string
{
- Log::debug(sprintf('Now in compareCurrencies("%s", "%s")', $currency?->code, $foreignCurrency?->code));
- if (!$currency instanceof TransactionCurrency) {
- return null;
- }
- if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id === $currency->id) {
- return null;
- }
+ $description = '' === $description ? '(empty description)' : $description;
- return $foreignCurrency;
+ return substr($description, 0, 1024);
}
/**
@@ -541,73 +521,69 @@ class TransactionJournalFactory
return $foreignCurrency;
}
- private function getDescription(string $description): string
- {
- $description = '' === $description ? '(empty description)' : $description;
-
- return substr($description, 0, 1024);
- }
-
- /**
- * Force the deletion of an entire set of transaction journals and their meta object in case of
- * an error creating a group.
- */
- private function forceDeleteOnError(Collection $collection): void
+ private function hashArray(NullArrayObject $row): string
{
- Log::debug(sprintf('forceDeleteOnError on collection size %d item(s)', $collection->count()));
- $service = app(JournalDestroyService::class);
+ unset($row['import_hash_v2'], $row['original_source']);
- /** @var TransactionJournal $journal */
- foreach ($collection as $journal) {
- Log::debug(sprintf('forceDeleteOnError on journal #%d', $journal->id));
- $service->destroy($journal);
+ try {
+ $json = json_encode($row, JSON_THROW_ON_ERROR);
+ } catch (JsonException $e) {
+ Log::error(sprintf('Could not encode dataRow: %s', $e->getMessage()));
+ $json = microtime();
}
- }
+ $hash = hash('sha256', $json);
+ Log::debug(sprintf('The hash is: %s', $hash), $row->getArrayCopy());
- private function forceTrDelete(Transaction $transaction): void
- {
- $transaction->delete();
+ return $hash;
}
- /**
- * Link a piggy bank to this journal.
- */
- private function storePiggyEvent(TransactionJournal $journal, NullArrayObject $data): void
+ private function isBetweenAssetAndLiability(Account $source, Account $destination): bool
{
- Log::debug('Will now store piggy event.');
+ $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
- $piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']);
+ // source is liability, destination is asset
+ if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) {
+ Log::debug('Source is a liability account, destination is an asset account, return TRUE.');
- if ($piggyBank instanceof PiggyBank) {
- $this->piggyEventFactory->create($journal, $piggyBank);
- Log::debug('Create piggy event.');
+ return true;
+ }
+ // source is asset, destination is liability
+ if (in_array($destination->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $source->accountType->type) {
+ Log::debug('Destination is a liability account, source is an asset account, return TRUE.');
- return;
+ return true;
}
- Log::debug('Create no piggy event');
+ Log::debug('Not between asset and liability, return FALSE');
+
+ return false;
}
- private function storeMetaFields(TransactionJournal $journal, NullArrayObject $transaction): void
+ private function reconciliationSanityCheck(?Account $sourceAccount, ?Account $destinationAccount): array
{
- foreach ($this->fields as $field) {
- $this->storeMeta($journal, $transaction->getArrayCopy(), $field);
+ Log::debug(sprintf('Now in %s', __METHOD__));
+ if ($sourceAccount instanceof Account && $destinationAccount instanceof Account) {
+ Log::debug('Both accounts exist, simply return them.');
+
+ return [$sourceAccount, $destinationAccount];
}
- }
+ if (!$destinationAccount instanceof Account) {
+ Log::debug('Destination account is NULL, source account is not.');
+ $account = $this->accountRepository->getReconciliation($sourceAccount);
+ Log::debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type));
- protected function storeMeta(TransactionJournal $journal, array $data, string $field): void
- {
- $set = ['journal' => $journal, 'name' => $field, 'data' => (string) ($data[$field] ?? '')];
- if (array_key_exists($field, $data) && $data[$field] instanceof Carbon) {
- $data[$field]->setTimezone(config('app.timezone'));
- Log::debug(sprintf('%s Date: %s (%s)', $field, $data[$field], $data[$field]->timezone->getName()));
- $set['data'] = $data[$field]->format('Y-m-d H:i:s');
+ return [$sourceAccount, $account];
}
- Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data']));
+ if (!$sourceAccount instanceof Account) { // @phpstan-ignore-line
+ Log::debug('Source account is NULL, destination account is not.');
+ $account = $this->accountRepository->getReconciliation($destinationAccount);
+ Log::debug(sprintf('Will return account #%d ("%s") of type "%s"', $account->id, $account->name, $account->accountType->type));
- /** @var TransactionJournalMetaFactory $factory */
- $factory = app(TransactionJournalMetaFactory::class);
- $factory->updateOrCreate($set);
+ return [$account, $destinationAccount];
+ }
+ Log::debug('Unused fallback'); // @phpstan-ignore-line
+
+ return [$sourceAccount, $destinationAccount];
}
private function storeLocation(TransactionJournal $journal, NullArrayObject $data): void
@@ -622,44 +598,68 @@ class TransactionJournalFactory
}
}
- public function setErrorOnHash(bool $errorOnHash): void
+ private function storeMetaFields(TransactionJournal $journal, NullArrayObject $transaction): void
{
- $this->errorOnHash = $errorOnHash;
- if ($errorOnHash) {
- Log::info('Will trigger duplication alert for this journal.');
+ foreach ($this->fields as $field) {
+ $this->storeMeta($journal, $transaction->getArrayCopy(), $field);
}
}
- public function setUserGroup(UserGroup $userGroup): void
+ /**
+ * Link a piggy bank to this journal.
+ */
+ private function storePiggyEvent(TransactionJournal $journal, NullArrayObject $data): void
{
- $this->userGroup = $userGroup;
- $this->currencyRepository->setUserGroup($userGroup);
- $this->tagFactory->setUserGroup($userGroup);
- $this->billRepository->setUserGroup($userGroup);
- $this->budgetRepository->setUserGroup($userGroup);
- $this->categoryRepository->setUserGroup($userGroup);
- $this->piggyRepository->setUserGroup($userGroup);
- $this->accountRepository->setUserGroup($userGroup);
+ Log::debug('Will now store piggy event.');
+
+ $piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']);
+
+ if ($piggyBank instanceof PiggyBank) {
+ $this->piggyEventFactory->create($journal, $piggyBank);
+ Log::debug('Create piggy event.');
+
+ return;
+ }
+ Log::debug('Create no piggy event');
}
- private function isBetweenAssetAndLiability(Account $source, Account $destination): bool
+ /**
+ * @throws FireflyException
+ */
+ private function validateAccounts(NullArrayObject $data): void
{
- $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
+ Log::debug(sprintf('Now in %s', __METHOD__));
+ $transactionType = $data['type'] ?? 'invalid';
+ $this->accountValidator->setUser($this->user);
+ $this->accountValidator->setTransactionType($transactionType);
- // source is liability, destination is asset
- if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) {
- Log::debug('Source is a liability account, destination is an asset account, return TRUE.');
+ // validate source account.
+ $array = [
+ 'id' => null !== $data['source_id'] ? (int) $data['source_id'] : null,
+ 'name' => null !== $data['source_name'] ? (string) $data['source_name'] : null,
+ 'iban' => null !== $data['source_iban'] ? (string) $data['source_iban'] : null,
+ 'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null,
+ ];
+ $validSource = $this->accountValidator->validateSource($array);
- return true;
+ // do something with result:
+ if (false === $validSource) {
+ throw new FireflyException(sprintf('Source: %s', $this->accountValidator->sourceError));
}
- // source is asset, destination is liability
- if (in_array($destination->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $source->accountType->type) {
- Log::debug('Destination is a liability account, source is an asset account, return TRUE.');
+ Log::debug('Source seems valid.');
- return true;
- }
- Log::debug('Not between asset and liability, return FALSE');
+ // validate destination account
+ $array = [
+ 'id' => null !== $data['destination_id'] ? (int) $data['destination_id'] : null,
+ 'name' => null !== $data['destination_name'] ? (string) $data['destination_name'] : null,
+ 'iban' => null !== $data['destination_iban'] ? (string) $data['destination_iban'] : null,
+ 'number' => null !== $data['destination_number'] ? (string) $data['destination_number'] : null,
+ ];
- return false;
+ $validDestination = $this->accountValidator->validateDestination($array);
+ // do something with result:
+ if (false === $validDestination) {
+ throw new FireflyException(sprintf('Destination: %s', $this->accountValidator->destError));
+ }
}
}
diff --git a/app/Generator/Report/Account/MonthReportGenerator.php b/app/Generator/Report/Account/MonthReportGenerator.php
index b186742802..5c2c4ae6ca 100644
--- a/app/Generator/Report/Account/MonthReportGenerator.php
+++ b/app/Generator/Report/Account/MonthReportGenerator.php
@@ -75,14 +75,6 @@ class MonthReportGenerator implements ReportGeneratorInterface
return $result;
}
- /**
- * Return the preferred period.
- */
- protected function preferredPeriod(): string
- {
- return 'day';
- }
-
/**
* Set accounts.
*/
@@ -146,4 +138,12 @@ class MonthReportGenerator implements ReportGeneratorInterface
{
return $this;
}
+
+ /**
+ * Return the preferred period.
+ */
+ protected function preferredPeriod(): string
+ {
+ return 'day';
+ }
}
diff --git a/app/Generator/Report/Budget/MonthReportGenerator.php b/app/Generator/Report/Budget/MonthReportGenerator.php
index 865a07ad32..65dcf1d64b 100644
--- a/app/Generator/Report/Budget/MonthReportGenerator.php
+++ b/app/Generator/Report/Budget/MonthReportGenerator.php
@@ -73,6 +73,26 @@ class MonthReportGenerator implements ReportGeneratorInterface
return $result;
}
+ /**
+ * Set the involved accounts.
+ */
+ public function setAccounts(Collection $accounts): ReportGeneratorInterface
+ {
+ $this->accounts = $accounts;
+
+ return $this;
+ }
+
+ /**
+ * Set the involved budgets.
+ */
+ public function setBudgets(Collection $budgets): ReportGeneratorInterface
+ {
+ $this->budgets = $budgets;
+
+ return $this;
+ }
+
/**
* Unused category setter.
*/
@@ -144,24 +164,4 @@ class MonthReportGenerator implements ReportGeneratorInterface
return $journals;
}
-
- /**
- * Set the involved budgets.
- */
- public function setBudgets(Collection $budgets): ReportGeneratorInterface
- {
- $this->budgets = $budgets;
-
- return $this;
- }
-
- /**
- * Set the involved accounts.
- */
- public function setAccounts(Collection $accounts): ReportGeneratorInterface
- {
- $this->accounts = $accounts;
-
- return $this;
- }
}
diff --git a/app/Generator/Report/Category/MonthReportGenerator.php b/app/Generator/Report/Category/MonthReportGenerator.php
index d4079bbd47..61d4827295 100644
--- a/app/Generator/Report/Category/MonthReportGenerator.php
+++ b/app/Generator/Report/Category/MonthReportGenerator.php
@@ -74,6 +74,16 @@ class MonthReportGenerator implements ReportGeneratorInterface
}
}
+ /**
+ * Set the involved accounts.
+ */
+ public function setAccounts(Collection $accounts): ReportGeneratorInterface
+ {
+ $this->accounts = $accounts;
+
+ return $this;
+ }
+
/**
* Empty budget setter.
*/
@@ -82,6 +92,16 @@ class MonthReportGenerator implements ReportGeneratorInterface
return $this;
}
+ /**
+ * Set the categories involved in this report.
+ */
+ public function setCategories(Collection $categories): ReportGeneratorInterface
+ {
+ $this->categories = $categories;
+
+ return $this;
+ }
+
/**
* Set the end date for this report.
*/
@@ -145,26 +165,6 @@ class MonthReportGenerator implements ReportGeneratorInterface
return $transactions;
}
- /**
- * Set the categories involved in this report.
- */
- public function setCategories(Collection $categories): ReportGeneratorInterface
- {
- $this->categories = $categories;
-
- return $this;
- }
-
- /**
- * Set the involved accounts.
- */
- public function setAccounts(Collection $accounts): ReportGeneratorInterface
- {
- $this->accounts = $accounts;
-
- return $this;
- }
-
/**
* Get the income for this report.
*/
diff --git a/app/Generator/Webhook/StandardMessageGenerator.php b/app/Generator/Webhook/StandardMessageGenerator.php
index 9737d20b57..b180e5f40b 100644
--- a/app/Generator/Webhook/StandardMessageGenerator.php
+++ b/app/Generator/Webhook/StandardMessageGenerator.php
@@ -84,43 +84,44 @@ class StandardMessageGenerator implements MessageGeneratorInterface
$this->run();
}
- private function getWebhooks(): Collection
+ public function getVersion(): int
{
- return $this->user
- ->webhooks()
- ->leftJoin('webhook_webhook_trigger', 'webhook_webhook_trigger.webhook_id', 'webhooks.id')
- ->leftJoin('webhook_triggers', 'webhook_webhook_trigger.webhook_trigger_id', 'webhook_triggers.id')
- ->where('active', true)
- ->whereIn('webhook_triggers.title', [$this->trigger->name, WebhookTrigger::ANY->name])
- ->get(['webhooks.*'])
- ;
+ return $this->version;
}
- /**
- * @throws FireflyException
- */
- private function run(): void
+ public function setObjects(Collection $objects): void
{
- Log::debug('Now in StandardMessageGenerator::run');
+ $this->objects = $objects;
+ }
- /** @var Webhook $webhook */
- foreach ($this->webhooks as $webhook) {
- $this->runWebhook($webhook);
- }
- Log::debug('Done with StandardMessageGenerator::run');
+ public function setTrigger(WebhookTrigger $trigger): void
+ {
+ $this->trigger = $trigger;
}
- /**
- * @throws FireflyException
- */
- private function runWebhook(Webhook $webhook): void
+ public function setUser(User $user): void
{
- Log::debug(sprintf('Now in runWebhook(#%d)', $webhook->id));
+ $this->user = $user;
+ }
- /** @var Model $object */
- foreach ($this->objects as $object) {
- $this->generateMessage($webhook, $object);
+ public function setWebhooks(Collection $webhooks): void
+ {
+ $this->webhooks = $webhooks;
+ }
+
+ private function collectAccounts(TransactionGroup $transactionGroup): Collection
+ {
+ $accounts = new Collection();
+
+ /** @var TransactionJournal $journal */
+ foreach ($transactionGroup->transactionJournals as $journal) {
+ /** @var Transaction $transaction */
+ foreach ($journal->transactions as $transaction) {
+ $accounts->push($transaction->account);
+ }
}
+
+ return $accounts->unique();
}
/**
@@ -258,46 +259,6 @@ class StandardMessageGenerator implements MessageGeneratorInterface
$factory->create($webhook, $basicMessage);
}
- public function getVersion(): int
- {
- return $this->version;
- }
-
- private function collectAccounts(TransactionGroup $transactionGroup): Collection
- {
- $accounts = new Collection();
-
- /** @var TransactionJournal $journal */
- foreach ($transactionGroup->transactionJournals as $journal) {
- /** @var Transaction $transaction */
- foreach ($journal->transactions as $transaction) {
- $accounts->push($transaction->account);
- }
- }
-
- return $accounts->unique();
- }
-
- public function setObjects(Collection $objects): void
- {
- $this->objects = $objects;
- }
-
- public function setTrigger(WebhookTrigger $trigger): void
- {
- $this->trigger = $trigger;
- }
-
- public function setUser(User $user): void
- {
- $this->user = $user;
- }
-
- public function setWebhooks(Collection $webhooks): void
- {
- $this->webhooks = $webhooks;
- }
-
private function getRelevantResponse(WebhookResponseModel $response, string $class): string
{
// return none if none.
@@ -343,4 +304,43 @@ class StandardMessageGenerator implements MessageGeneratorInterface
return array_unique($return);
}
+
+ private function getWebhooks(): Collection
+ {
+ return $this->user
+ ->webhooks()
+ ->leftJoin('webhook_webhook_trigger', 'webhook_webhook_trigger.webhook_id', 'webhooks.id')
+ ->leftJoin('webhook_triggers', 'webhook_webhook_trigger.webhook_trigger_id', 'webhook_triggers.id')
+ ->where('active', true)
+ ->whereIn('webhook_triggers.title', [$this->trigger->name, WebhookTrigger::ANY->name])
+ ->get(['webhooks.*'])
+ ;
+ }
+
+ /**
+ * @throws FireflyException
+ */
+ private function run(): void
+ {
+ Log::debug('Now in StandardMessageGenerator::run');
+
+ /** @var Webhook $webhook */
+ foreach ($this->webhooks as $webhook) {
+ $this->runWebhook($webhook);
+ }
+ Log::debug('Done with StandardMessageGenerator::run');
+ }
+
+ /**
+ * @throws FireflyException
+ */
+ private function runWebhook(Webhook $webhook): void
+ {
+ Log::debug(sprintf('Now in runWebhook(#%d)', $webhook->id));
+
+ /** @var Model $object */
+ foreach ($this->objects as $object) {
+ $this->generateMessage($webhook, $object);
+ }
+ }
}
diff --git a/app/Handlers/Observer/BillObserver.php b/app/Handlers/Observer/BillObserver.php
index ec2cddb509..1a8c3cf29d 100644
--- a/app/Handlers/Observer/BillObserver.php
+++ b/app/Handlers/Observer/BillObserver.php
@@ -25,9 +25,7 @@ namespace FireflyIII\Handlers\Observer;
use FireflyIII\Handlers\ExchangeRate\ConversionParameters;
use FireflyIII\Handlers\ExchangeRate\ConvertsAmountToPrimaryAmount;
-use FireflyIII\Models\Attachment;
use FireflyIII\Models\Bill;
-use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface;
/**
* Class BillObserver
diff --git a/app/Helpers/Attachments/AttachmentHelper.php b/app/Helpers/Attachments/AttachmentHelper.php
index 1e84e2b457..a3f545ea89 100644
--- a/app/Helpers/Attachments/AttachmentHelper.php
+++ b/app/Helpers/Attachments/AttachmentHelper.php
@@ -219,6 +219,33 @@ class AttachmentHelper implements AttachmentHelperInterface
return true;
}
+ /**
+ * Check if a model already has this file attached.
+ */
+ protected function hasFile(UploadedFile $file, Model $model): bool
+ {
+ $md5 = md5_file($file->getRealPath());
+ $name = $file->getClientOriginalName();
+ $class = $model::class;
+ $count = 0;
+ // ignore lines about polymorphic calls.
+ if ($model instanceof PiggyBank) {
+ $count = $model->account->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
+ }
+ if (!$model instanceof PiggyBank) {
+ $count = $model->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
+ }
+ $result = false;
+ if ($count > 0) {
+ $msg = (string) trans('validation.file_already_attached', ['name' => $name]);
+ $this->errors->add('attachments', $msg);
+ Log::error($msg);
+ $result = true;
+ }
+
+ return $result;
+ }
+
/**
* Process the upload of a file.
*
@@ -341,31 +368,4 @@ class AttachmentHelper implements AttachmentHelperInterface
return $result;
}
-
- /**
- * Check if a model already has this file attached.
- */
- protected function hasFile(UploadedFile $file, Model $model): bool
- {
- $md5 = md5_file($file->getRealPath());
- $name = $file->getClientOriginalName();
- $class = $model::class;
- $count = 0;
- // ignore lines about polymorphic calls.
- if ($model instanceof PiggyBank) {
- $count = $model->account->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
- }
- if (!$model instanceof PiggyBank) {
- $count = $model->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count();
- }
- $result = false;
- if ($count > 0) {
- $msg = (string) trans('validation.file_already_attached', ['name' => $name]);
- $this->errors->add('attachments', $msg);
- Log::error($msg);
- $result = true;
- }
-
- return $result;
- }
}
diff --git a/app/Helpers/Collector/Extensions/AttachmentCollection.php b/app/Helpers/Collector/Extensions/AttachmentCollection.php
index 09ebe86911..c518199364 100644
--- a/app/Helpers/Collector/Extensions/AttachmentCollection.php
+++ b/app/Helpers/Collector/Extensions/AttachmentCollection.php
@@ -66,51 +66,6 @@ trait AttachmentCollection
return $this;
}
- /**
- * Has attachments
- */
- public function hasAttachments(): GroupCollectorInterface
- {
- Log::debug('Add filter on attachment ID.');
- $this->joinAttachmentTables();
- $this->query->whereNotNull('attachments.attachable_id');
- $this->query->whereNull('attachments.deleted_at');
-
- return $this;
- }
-
- /**
- * Join table to get attachment information.
- */
- private function joinAttachmentTables(): void
- {
- if (false === $this->hasJoinedAttTables) {
- // join some extra tables:
- $this->hasJoinedAttTables = true;
- $this->query
- ->leftJoin('attachments', 'attachments.attachable_id', '=', 'transaction_journals.id')
- ->where(static function (EloquentBuilder $q1): void { // @phpstan-ignore-line
- $q1->where('attachments.attachable_type', TransactionJournal::class);
- // $q1->where('attachments.uploaded', true);
- // $q1->whereNull('attachments.deleted_at');
- $q1->orWhereNull('attachments.attachable_type');
- })
- ;
- }
- }
-
- public function withAttachmentInformation(): GroupCollectorInterface
- {
- $this->fields[] = 'attachments.id as attachment_id';
- $this->fields[] = 'attachments.filename as attachment_filename';
- $this->fields[] = 'attachments.title as attachment_title';
- $this->fields[] = 'attachments.deleted_at as attachment_deleted_at';
- $this->fields[] = 'attachments.uploaded as attachment_uploaded';
- $this->joinAttachmentTables();
-
- return $this;
- }
-
public function attachmentNameDoesNotContain(string $name): GroupCollectorInterface
{
$this->hasAttachments();
@@ -498,6 +453,19 @@ trait AttachmentCollection
return $this;
}
+ /**
+ * Has attachments
+ */
+ public function hasAttachments(): GroupCollectorInterface
+ {
+ Log::debug('Add filter on attachment ID.');
+ $this->joinAttachmentTables();
+ $this->query->whereNotNull('attachments.attachable_id');
+ $this->query->whereNull('attachments.deleted_at');
+
+ return $this;
+ }
+
/**
* Has attachments
*/
@@ -517,4 +485,36 @@ trait AttachmentCollection
return $this;
}
+
+ public function withAttachmentInformation(): GroupCollectorInterface
+ {
+ $this->fields[] = 'attachments.id as attachment_id';
+ $this->fields[] = 'attachments.filename as attachment_filename';
+ $this->fields[] = 'attachments.title as attachment_title';
+ $this->fields[] = 'attachments.deleted_at as attachment_deleted_at';
+ $this->fields[] = 'attachments.uploaded as attachment_uploaded';
+ $this->joinAttachmentTables();
+
+ return $this;
+ }
+
+ /**
+ * Join table to get attachment information.
+ */
+ private function joinAttachmentTables(): void
+ {
+ if (false === $this->hasJoinedAttTables) {
+ // join some extra tables:
+ $this->hasJoinedAttTables = true;
+ $this->query
+ ->leftJoin('attachments', 'attachments.attachable_id', '=', 'transaction_journals.id')
+ ->where(static function (EloquentBuilder $q1): void { // @phpstan-ignore-line
+ $q1->where('attachments.attachable_type', TransactionJournal::class);
+ // $q1->where('attachments.uploaded', true);
+ // $q1->whereNull('attachments.deleted_at');
+ $q1->orWhereNull('attachments.attachable_type');
+ })
+ ;
+ }
+ }
}
diff --git a/app/Helpers/Collector/Extensions/MetaCollection.php b/app/Helpers/Collector/Extensions/MetaCollection.php
index 8610061b3f..c69cbe079f 100644
--- a/app/Helpers/Collector/Extensions/MetaCollection.php
+++ b/app/Helpers/Collector/Extensions/MetaCollection.php
@@ -54,23 +54,6 @@ trait MetaCollection
return $this;
}
- /**
- * Will include bill name + ID, if any.
- */
- public function withBillInformation(): GroupCollectorInterface
- {
- if (false === $this->hasBillInformation) {
- // join bill table
- $this->query->leftJoin('bills', 'bills.id', '=', 'transaction_journals.bill_id');
- // add fields
- $this->fields[] = 'bills.id as bill_id';
- $this->fields[] = 'bills.name as bill_name';
- $this->hasBillInformation = true;
- }
-
- return $this;
- }
-
/**
* Exclude a specific budget.
*/
@@ -86,25 +69,6 @@ trait MetaCollection
return $this;
}
- /**
- * Will include budget ID + name, if any.
- */
- public function withBudgetInformation(): GroupCollectorInterface
- {
- if (false === $this->hasBudgetInformation) {
- // join link table
- $this->query->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
- // join cat table
- $this->query->leftJoin('budgets', 'budget_transaction_journal.budget_id', '=', 'budgets.id');
- // add fields
- $this->fields[] = 'budgets.id as budget_id';
- $this->fields[] = 'budgets.name as budget_name';
- $this->hasBudgetInformation = true;
- }
-
- return $this;
- }
-
public function excludeBudgets(Collection $budgets): GroupCollectorInterface
{
if ($budgets->count() > 0) {
@@ -131,25 +95,6 @@ trait MetaCollection
return $this;
}
- /**
- * Will include category ID + name, if any.
- */
- public function withCategoryInformation(): GroupCollectorInterface
- {
- if (false === $this->hasCatInformation) {
- // join link table
- $this->query->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
- // join cat table
- $this->query->leftJoin('categories', 'category_transaction_journal.category_id', '=', 'categories.id');
- // add fields
- $this->fields[] = 'categories.id as category_id';
- $this->fields[] = 'categories.name as category_name';
- $this->hasCatInformation = true;
- }
-
- return $this;
- }
-
/**
* Exclude a specific category.
*/
@@ -175,19 +120,6 @@ trait MetaCollection
return $this;
}
- /**
- * Join table to get tag information.
- */
- protected function joinMetaDataTables(): void
- {
- if (false === $this->hasJoinedMetaTables) {
- $this->hasJoinedMetaTables = true;
- $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
- $this->fields[] = 'journal_meta.name as meta_name';
- $this->fields[] = 'journal_meta.data as meta_data';
- }
- }
-
public function excludeExternalUrl(string $url): GroupCollectorInterface
{
$this->joinMetaDataTables();
@@ -371,34 +303,6 @@ trait MetaCollection
return $this;
}
- public function withTagInformation(): GroupCollectorInterface
- {
- $this->fields[] = 'tags.id as tag_id';
- $this->fields[] = 'tags.tag as tag_name';
- $this->fields[] = 'tags.date as tag_date';
- $this->fields[] = 'tags.description as tag_description';
- $this->fields[] = 'tags.latitude as tag_latitude';
- $this->fields[] = 'tags.longitude as tag_longitude';
- $this->fields[] = 'tags.zoomLevel as tag_zoom_level';
-
- $this->joinTagTables();
-
- return $this;
- }
-
- /**
- * Join table to get tag information.
- */
- protected function joinTagTables(): void
- {
- if (false === $this->hasJoinedTagTables) {
- // join some extra tables:
- $this->hasJoinedTagTables = true;
- $this->query->leftJoin('tag_transaction_journal', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
- $this->query->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id');
- }
- }
-
public function internalReferenceContains(string $internalReference): GroupCollectorInterface
{
$internalReference = json_encode($internalReference);
@@ -487,23 +391,6 @@ trait MetaCollection
return $this;
}
- public function withNotes(): GroupCollectorInterface
- {
- if (false === $this->hasNotesInformation) {
- // join bill table
- $this->query->leftJoin('notes', static function (JoinClause $join): void {
- $join->on('notes.noteable_id', '=', 'transaction_journals.id');
- $join->where('notes.noteable_type', '=', TransactionJournal::class);
- $join->whereNull('notes.deleted_at');
- });
- // add fields
- $this->fields[] = 'notes.text as notes';
- $this->hasNotesInformation = true;
- }
-
- return $this;
- }
-
public function notesDoNotContain(string $value): GroupCollectorInterface
{
$this->withNotes();
@@ -850,6 +737,23 @@ trait MetaCollection
return $this;
}
+ /**
+ * Will include bill name + ID, if any.
+ */
+ public function withBillInformation(): GroupCollectorInterface
+ {
+ if (false === $this->hasBillInformation) {
+ // join bill table
+ $this->query->leftJoin('bills', 'bills.id', '=', 'transaction_journals.bill_id');
+ // add fields
+ $this->fields[] = 'bills.id as bill_id';
+ $this->fields[] = 'bills.name as bill_name';
+ $this->hasBillInformation = true;
+ }
+
+ return $this;
+ }
+
/**
* Limit results to a transactions without a budget..
*/
@@ -861,6 +765,25 @@ trait MetaCollection
return $this;
}
+ /**
+ * Will include budget ID + name, if any.
+ */
+ public function withBudgetInformation(): GroupCollectorInterface
+ {
+ if (false === $this->hasBudgetInformation) {
+ // join link table
+ $this->query->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
+ // join cat table
+ $this->query->leftJoin('budgets', 'budget_transaction_journal.budget_id', '=', 'budgets.id');
+ // add fields
+ $this->fields[] = 'budgets.id as budget_id';
+ $this->fields[] = 'budgets.name as budget_name';
+ $this->hasBudgetInformation = true;
+ }
+
+ return $this;
+ }
+
/**
* Limit results to a transactions without a category.
*/
@@ -872,6 +795,25 @@ trait MetaCollection
return $this;
}
+ /**
+ * Will include category ID + name, if any.
+ */
+ public function withCategoryInformation(): GroupCollectorInterface
+ {
+ if (false === $this->hasCatInformation) {
+ // join link table
+ $this->query->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
+ // join cat table
+ $this->query->leftJoin('categories', 'category_transaction_journal.category_id', '=', 'categories.id');
+ // add fields
+ $this->fields[] = 'categories.id as category_id';
+ $this->fields[] = 'categories.name as category_name';
+ $this->hasCatInformation = true;
+ }
+
+ return $this;
+ }
+
public function withExternalId(): GroupCollectorInterface
{
$this->joinMetaDataTables();
@@ -892,6 +834,23 @@ trait MetaCollection
return $this;
}
+ public function withNotes(): GroupCollectorInterface
+ {
+ if (false === $this->hasNotesInformation) {
+ // join bill table
+ $this->query->leftJoin('notes', static function (JoinClause $join): void {
+ $join->on('notes.noteable_id', '=', 'transaction_journals.id');
+ $join->where('notes.noteable_type', '=', TransactionJournal::class);
+ $join->whereNull('notes.deleted_at');
+ });
+ // add fields
+ $this->fields[] = 'notes.text as notes';
+ $this->hasNotesInformation = true;
+ }
+
+ return $this;
+ }
+
/**
* Limit results to a transactions without a bill.
*/
@@ -989,4 +948,45 @@ trait MetaCollection
return $this;
}
+
+ public function withTagInformation(): GroupCollectorInterface
+ {
+ $this->fields[] = 'tags.id as tag_id';
+ $this->fields[] = 'tags.tag as tag_name';
+ $this->fields[] = 'tags.date as tag_date';
+ $this->fields[] = 'tags.description as tag_description';
+ $this->fields[] = 'tags.latitude as tag_latitude';
+ $this->fields[] = 'tags.longitude as tag_longitude';
+ $this->fields[] = 'tags.zoomLevel as tag_zoom_level';
+
+ $this->joinTagTables();
+
+ return $this;
+ }
+
+ /**
+ * Join table to get tag information.
+ */
+ protected function joinMetaDataTables(): void
+ {
+ if (false === $this->hasJoinedMetaTables) {
+ $this->hasJoinedMetaTables = true;
+ $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id');
+ $this->fields[] = 'journal_meta.name as meta_name';
+ $this->fields[] = 'journal_meta.data as meta_data';
+ }
+ }
+
+ /**
+ * Join table to get tag information.
+ */
+ protected function joinTagTables(): void
+ {
+ if (false === $this->hasJoinedTagTables) {
+ // join some extra tables:
+ $this->hasJoinedTagTables = true;
+ $this->query->leftJoin('tag_transaction_journal', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
+ $this->query->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id');
+ }
+ }
}
diff --git a/app/Helpers/Collector/Extensions/TimeCollection.php b/app/Helpers/Collector/Extensions/TimeCollection.php
index e6f3b3857b..d2786ec3be 100644
--- a/app/Helpers/Collector/Extensions/TimeCollection.php
+++ b/app/Helpers/Collector/Extensions/TimeCollection.php
@@ -88,15 +88,6 @@ trait TimeCollection
return $this;
}
- public function withMetaDate(string $field): GroupCollectorInterface
- {
- $this->joinMetaDataTables();
- $this->query->where('journal_meta.name', '=', $field);
- $this->query->whereNotNull('journal_meta.data');
-
- return $this;
- }
-
public function excludeObjectRange(Carbon $start, Carbon $end, string $field): GroupCollectorInterface
{
$after = $start->format('Y-m-d 00:00:00');
@@ -620,6 +611,15 @@ trait TimeCollection
return $this;
}
+ public function withMetaDate(string $field): GroupCollectorInterface
+ {
+ $this->joinMetaDataTables();
+ $this->query->where('journal_meta.name', '=', $field);
+ $this->query->whereNotNull('journal_meta.data');
+
+ return $this;
+ }
+
public function yearAfter(string $year): GroupCollectorInterface
{
$this->query->whereYear('transaction_journals.date', '>=', $year);
diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php
index a96a010d30..d5c69df1d3 100644
--- a/app/Helpers/Collector/GroupCollector.php
+++ b/app/Helpers/Collector/GroupCollector.php
@@ -469,346 +469,222 @@ class GroupCollector implements GroupCollectorInterface
return $collection;
}
- private function getCollectedGroupIds(): array
- {
- return $this->query
- ->get(['transaction_journals.transaction_group_id'])
- ->pluck('transaction_group_id')
- ->toArray()
- ;
- }
-
/**
- * @throws FireflyException
+ * Same as getGroups but everything is in a paginator.
*/
- private function parseArray(Collection $collection): Collection
+ public function getPaginatedGroups(): LengthAwarePaginator
{
- $groups = [];
+ Log::debug('Now in getPaginatedGroups()');
+ $set = $this->getGroups();
+ if (0 === $this->limit) {
+ $this->setLimit(50);
+ }
+ if (null !== $this->startRow && null !== $this->endRow) {
+ /** @var int $total */
+ $total = $this->endRow - $this->startRow;
- /** @var TransactionJournal $augumentedJournal */
- foreach ($collection as $augumentedJournal) {
- $groupId = (int) $augumentedJournal->transaction_group_id;
+ return new LengthAwarePaginator($set, $this->total, $total, 1);
+ }
+ $limit = $this->limit ?? 1;
- if (!array_key_exists($groupId, $groups)) {
- // make new array
- $parsedGroup = $this->parseAugmentedJournal($augumentedJournal);
- $groupArray = [
- 'id' => (int) $augumentedJournal->transaction_group_id,
- 'user_id' => $augumentedJournal->user_id,
- 'user_group_id' => $augumentedJournal->user_group_id,
- // Field transaction_group_title was added by the query.
- 'title' => $augumentedJournal->transaction_group_title,
- 'created_at' => new Carbon($augumentedJournal->group_created_at, config('app.timezone')),
- 'updated_at' => new Carbon($augumentedJournal->group_updated_at, config('app.timezone')),
- 'transaction_type' => $parsedGroup['transaction_type_type'],
- 'count' => 1,
- 'sums' => [],
- 'transactions' => [],
- ];
- // Field transaction_journal_id was added by the query.
- $journalId = (int) $augumentedJournal->transaction_journal_id;
- $groupArray['transactions'][$journalId] = $parsedGroup;
- $groups[$groupId] = $groupArray;
+ return new LengthAwarePaginator($set, $this->total, $limit, $this->page);
+ }
- continue;
- }
- // or parse the rest.
- // Field transaction_journal_id was added by the query.
- $journalId = (int) $augumentedJournal->transaction_journal_id;
- if (array_key_exists($journalId, $groups[$groupId]['transactions'])) {
- // append data to existing group + journal (for multiple tags or multiple attachments)
- $groups[$groupId]['transactions'][$journalId] = $this->mergeTags($groups[$groupId]['transactions'][$journalId], $augumentedJournal);
- $groups[$groupId]['transactions'][$journalId] = $this->mergeAttachments($groups[$groupId]['transactions'][$journalId], $augumentedJournal);
- }
+ public function isNotReconciled(): GroupCollectorInterface
+ {
+ $this->query->where('source.reconciled', 0)->where('destination.reconciled', 0);
- if (!array_key_exists($journalId, $groups[$groupId]['transactions'])) {
- // create second, third, fourth split:
- ++$groups[$groupId]['count'];
- $groups[$groupId]['transactions'][$journalId] = $this->parseAugmentedJournal($augumentedJournal);
- }
- }
- $groups = $this->parseSums($groups);
+ return $this;
+ }
- return new Collection()->push(...$groups);
+ public function isReconciled(): GroupCollectorInterface
+ {
+ $this->query->where('source.reconciled', 1)->where('destination.reconciled', 1);
+
+ return $this;
}
/**
- * @throws FireflyException
- * @throws JsonException
+ * Limit results to a specific currency, either foreign or normal one.
*/
- private function parseAugmentedJournal(TransactionJournal $augumentedJournal): array
+ public function setCurrency(TransactionCurrency $currency): GroupCollectorInterface
{
- $result = $augumentedJournal->toArray();
- $result['tags'] = [];
- $result['attachments'] = [];
- $result['interest_date'] = null;
- $result['payment_date'] = null;
- $result['invoice_date'] = null;
- $result['book_date'] = null;
- $result['due_date'] = null;
- $result['process_date'] = null;
+ $this->query->where(static function (EloquentBuilder $q) use ($currency): void {
+ $q->where('source.transaction_currency_id', $currency->id);
+ $q->orWhere('source.foreign_currency_id', $currency->id);
+ });
- try {
- $result['date'] = new Carbon($result['date'], 'UTC');
- $result['created_at'] = new Carbon($result['created_at'], 'UTC');
- $result['updated_at'] = new Carbon($result['updated_at'], 'UTC');
+ return $this;
+ }
- // this is going to happen a lot:
- $result['date']->setTimezone(config('app.timezone'));
- $result['created_at']->setTimezone(config('app.timezone'));
- $result['updated_at']->setTimezone(config('app.timezone'));
- } catch (Exception $e) { // intentional generic exception
- Log::error($e->getMessage());
+ public function setEndRow(int $endRow): self
+ {
+ $this->endRow = $endRow;
- throw new FireflyException($e->getMessage(), 0, $e);
- }
+ return $this;
+ }
- // try to process meta date value (if present)
- $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date'];
- if (array_key_exists('meta_name', $result) && in_array($result['meta_name'], $dates, true)) {
- $name = $result['meta_name'];
- if (array_key_exists('meta_data', $result) && '' !== (string) $result['meta_data']) {
- $result[$name] = Carbon::createFromFormat('!Y-m-d', substr((string) json_decode((string) $result['meta_data']), 0, 10));
- }
- }
+ public function setExpandGroupSearch(bool $expandGroupSearch): GroupCollectorInterface
+ {
+ $this->expandGroupSearch = $expandGroupSearch;
- // convert values to integers:
- $result = $this->convertToInteger($result);
+ return $this;
+ }
- // convert to boolean
- $result = $this->convertToBoolean($result);
+ public function setForeignCurrency(TransactionCurrency $currency): GroupCollectorInterface
+ {
+ $this->query->where('source.foreign_currency_id', $currency->id);
- // convert back to strings because SQLite is dumb like that.
- $result = $this->convertToStrings($result);
+ return $this;
+ }
- $result['reconciled'] = 1 === (int) $result['reconciled'];
- if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well.
- $tagId = (int) $augumentedJournal['tag_id'];
- $tagDate = null;
+ /**
+ * Limit the result to a set of specific transaction groups.
+ */
+ public function setIds(array $groupIds): GroupCollectorInterface
+ {
+ $this->query->whereIn('transaction_groups.id', $groupIds);
- try {
- $tagDate = Carbon::parse($augumentedJournal['tag_date']);
- } catch (InvalidFormatException $e) {
- Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
- }
+ return $this;
+ }
- $result['tags'][$tagId] = [
- 'id' => (int) $result['tag_id'],
- 'name' => $result['tag_name'],
- 'date' => $tagDate,
- 'description' => $result['tag_description'],
- ];
- }
+ /**
+ * Limit the result to a set of specific journals.
+ */
+ public function setJournalIds(array $journalIds): GroupCollectorInterface
+ {
+ if (0 !== count($journalIds)) {
+ // make all integers.
+ $integerIDs = array_map(intval(...), $journalIds);
+ Log::debug(sprintf('GroupCollector: setJournalIds: %s', implode(', ', $integerIDs)));
- // also merge attachments:
- if (array_key_exists('attachment_id', $result) && null !== $result['attachment_id']) {
- $uploaded = 1 === (int) $result['attachment_uploaded'];
- $attachmentId = (int) $augumentedJournal['attachment_id'];
- $deleted = null !== $result['attachment_deleted_at'];
- if (0 !== $attachmentId && $uploaded && !$deleted) {
- $result['attachments'][$attachmentId] = [
- 'id' => $attachmentId,
- 'filename' => $augumentedJournal['attachment_filename'],
- 'title' => $augumentedJournal['attachment_title'],
- ];
- }
+ $this->query->whereIn('transaction_journals.id', $integerIDs);
}
- // unset various fields:
- unset(
- $result['tag_id'],
- $result['meta_data'],
- $result['meta_name'],
- $result['tag_name'],
- $result['tag_date'],
- $result['tag_description'],
- $result['tag_latitude'],
- $result['tag_longitude'],
- $result['tag_zoom_level'],
- $result['attachment_filename'],
- $result['attachment_id']
- );
- return $result;
+ return $this;
}
/**
- * Convert a selected set of fields to arrays.
+ * Limit the number of returned entries.
*/
- private function convertToInteger(array $array): array
+ public function setLimit(int $limit): GroupCollectorInterface
{
- foreach ($this->integerFields as $field) {
- $array[$field] = array_key_exists($field, $array) && null !== $array[$field] ? (int) $array[$field] : null;
- }
+ $this->limit = $limit;
+ // Log::debug(sprintf('GroupCollector: The limit is now %d', $limit));
- return $array;
+ return $this;
}
- private function convertToBoolean(array $array): array
+ /**
+ * Limit results to a specific currency, only normal one.
+ */
+ public function setNormalCurrency(TransactionCurrency $currency): GroupCollectorInterface
{
- foreach ($this->booleanFields as $field) {
- $array[$field] = array_key_exists($field, $array) ? (bool) $array[$field] : null;
- }
+ $this->query->where('source.transaction_currency_id', $currency->id);
- return $array;
+ return $this;
}
- private function convertToStrings(array $array): array
+ /**
+ * Set the page to get.
+ */
+ public function setPage(int $page): GroupCollectorInterface
{
- foreach ($this->stringFields as $field) {
- $array[$field] = array_key_exists($field, $array) && null !== $array[$field] ? (string) $array[$field] : null;
- }
+ $page = 0 === $page ? 1 : $page;
+ $this->page = $page;
+ // Log::debug(sprintf('GroupCollector: page is now %d', $page));
- return $array;
+ return $this;
}
- private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array
+ /**
+ * Search for words in descriptions.
+ */
+ public function setSearchWords(array $array): GroupCollectorInterface
{
- $newArray = $newJournal->toArray();
- if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well.
- $tagId = (int) $newJournal['tag_id'];
-
- $tagDate = null;
-
- try {
- $tagDate = Carbon::parse($newArray['tag_date']);
- } catch (InvalidFormatException $e) {
- Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
- }
+ if (0 === count($array)) {
+ Log::debug('No words in array');
- $existingJournal['tags'][$tagId] = [
- 'id' => (int) $newArray['tag_id'],
- 'name' => $newArray['tag_name'],
- 'date' => $tagDate,
- 'description' => $newArray['tag_description'],
- ];
+ return $this;
}
+ Log::debug(sprintf('%d word(s) in array', count($array)));
+ $this->query->where(static function (EloquentBuilder $q) use ($array): void {
+ $q->where(static function (EloquentBuilder $q1) use ($array): void {
+ foreach ($array as $word) {
+ $keyword = sprintf('%%%s%%', $word);
+ $q1->whereLike('transaction_journals.description', $keyword);
+ }
+ });
+ $q->orWhere(static function (EloquentBuilder $q2) use ($array): void {
+ foreach ($array as $word) {
+ $keyword = sprintf('%%%s%%', $word);
+ $q2->whereLike('transaction_groups.title', $keyword);
+ }
+ });
+ });
- return $existingJournal;
+ return $this;
}
- private function mergeAttachments(array $existingJournal, TransactionJournal $newJournal): array
+ #[Override]
+ public function setSorting(array $instructions): GroupCollectorInterface
{
- $newArray = $newJournal->toArray();
- if (array_key_exists('attachment_id', $newArray)) {
- $attachmentId = (int) $newJournal['attachment_id'];
-
- $existingJournal['attachments'][$attachmentId] = ['id' => $attachmentId];
- }
+ $this->sorting = $instructions;
- return $existingJournal;
+ return $this;
}
- private function parseSums(array $groups): array
+ public function setStartRow(int $startRow): self
{
- /**
- * @var int $groudId
- * @var array $group
- */
- foreach ($groups as $groudId => $group) {
- /** @var array $transaction */
- foreach ($group['transactions'] as $transaction) {
- $currencyId = (int) $transaction['currency_id'];
- if (null === $transaction['amount']) {
- throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId));
- }
- $pcAmount = (string) ('' === $transaction['pc_amount'] ? '0' : $transaction['pc_amount']);
- $pcForeignAmount = (string) ('' === $transaction['pc_foreign_amount'] ? '0' : $transaction['pc_foreign_amount']);
- $foreignAmount = (string) ('' === $transaction['foreign_amount'] ? '0' : $transaction['foreign_amount']);
-
- // set default:
- if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
- $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;
- $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code'];
- $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol'];
- $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['currency_decimal_places'];
- $groups[$groudId]['sums'][$currencyId]['amount'] = '0';
- $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0';
- }
- $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']);
- $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['pc_amount'], $pcAmount);
-
- if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) {
- $currencyId = (int) $transaction['foreign_currency_id'];
-
- // set default:
- if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
- $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;
- $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code'];
- $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol'];
- $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['foreign_currency_decimal_places'];
- $groups[$groudId]['sums'][$currencyId]['amount'] = '0';
- $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0';
- }
- $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $foreignAmount);
- $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $pcForeignAmount);
- }
- }
- }
+ $this->startRow = $startRow;
- return $groups;
+ return $this;
}
- private function postFilterCollection(Collection $collection): Collection
+ /**
+ * Limit the search to one specific transaction group.
+ */
+ public function setTransactionGroup(TransactionGroup $transactionGroup): GroupCollectorInterface
{
- $currentCollection = $collection;
- $countFilters = count($this->postFilters);
- if (0 === $countFilters) {
- return $currentCollection;
- }
- Log::debug(sprintf(
- 'GroupCollector: postFilterCollection has %d filter(s) and %d transaction(s).',
- count($this->postFilters),
- count($currentCollection)
- ));
-
- if (0 === $currentCollection->count()) {
- Log::debug('Found nothing anyway, return empty collection.');
-
- return $currentCollection;
- }
+ $this->query->where('transaction_groups.id', $transactionGroup->id);
- /**
- * @var Closure $function
- */
- foreach ($this->postFilters as $function) {
- Log::debug('Applying filter...');
- $nextCollection = new Collection();
+ return $this;
+ }
- // loop everything in the current collection
- // and save it (or not) in the new collection.
- // that new collection is the next current collection
- /**
- * @var array $item
- */
- foreach ($currentCollection as $item) {
- $result = $function($item);
- if (false === $result) {
- // skip other filters, continue to next item.
- Log::debug('Result is false');
+ /**
+ * Limit the included transaction types.
+ */
+ public function setTypes(array $types): GroupCollectorInterface
+ {
+ $this->query->whereIn('transaction_types.type', $types);
- continue;
- }
- // if the result is a bool, use the unedited results.
- if (true === $result) {
- Log::debug('Result is true');
- $nextCollection->push($item);
+ return $this;
+ }
- continue;
- }
- // if the result is an array, the filter has changed what's being returned.
- if (is_array($result)) {
- Log::debug('Result is array');
- $nextCollection->push($result);
+ /**
+ * Set the user object and start the query.
+ */
+ public function setUser(User $user): GroupCollectorInterface
+ {
+ if (!$this->user instanceof User) {
+ $this->user = $user;
+ $this->startQuery();
+ }
- continue;
- }
- Log::debug('Result is something else!');
- }
- $currentCollection = $nextCollection;
- Log::debug(sprintf('GroupCollector: postFilterCollection has %d transaction(s) left.', count($currentCollection)));
+ return $this;
+ }
+
+ /**
+ * Set the user object and start the query.
+ */
+ public function setUserGroup(UserGroup $userGroup): GroupCollectorInterface
+ {
+ if (!$this->userGroup instanceof UserGroup) {
+ $this->userGroup = $userGroup;
+ $this->startQueryForGroup();
}
- return $currentCollection;
+ return $this;
}
#[Override]
@@ -841,208 +717,364 @@ class GroupCollector implements GroupCollectorInterface
}
/**
- * Same as getGroups but everything is in a paginator.
+ * Automatically include all stuff required to make API calls work.
*/
- public function getPaginatedGroups(): LengthAwarePaginator
+ public function withAPIInformation(): GroupCollectorInterface
{
- Log::debug('Now in getPaginatedGroups()');
- $set = $this->getGroups();
- if (0 === $this->limit) {
- $this->setLimit(50);
- }
- if (null !== $this->startRow && null !== $this->endRow) {
- /** @var int $total */
- $total = $this->endRow - $this->startRow;
+ // include source + destination account name and type.
+ $this
+ ->withAccountInformation()
+ // include category ID + name (if any)
+ ->withCategoryInformation()
+ // include budget ID + name (if any)
+ ->withBudgetInformation()
+ // include bill ID + name (if any)
+ ->withBillInformation()
+ ;
- return new LengthAwarePaginator($set, $this->total, $total, 1);
+ return $this;
+ }
+
+ private function convertToBoolean(array $array): array
+ {
+ foreach ($this->booleanFields as $field) {
+ $array[$field] = array_key_exists($field, $array) ? (bool) $array[$field] : null;
}
- $limit = $this->limit ?? 1;
- return new LengthAwarePaginator($set, $this->total, $limit, $this->page);
+ return $array;
}
/**
- * Limit the number of returned entries.
+ * Convert a selected set of fields to arrays.
*/
- public function setLimit(int $limit): GroupCollectorInterface
+ private function convertToInteger(array $array): array
{
- $this->limit = $limit;
- // Log::debug(sprintf('GroupCollector: The limit is now %d', $limit));
+ foreach ($this->integerFields as $field) {
+ $array[$field] = array_key_exists($field, $array) && null !== $array[$field] ? (int) $array[$field] : null;
+ }
- return $this;
+ return $array;
}
- public function isNotReconciled(): GroupCollectorInterface
+ private function convertToStrings(array $array): array
{
- $this->query->where('source.reconciled', 0)->where('destination.reconciled', 0);
+ foreach ($this->stringFields as $field) {
+ $array[$field] = array_key_exists($field, $array) && null !== $array[$field] ? (string) $array[$field] : null;
+ }
- return $this;
+ return $array;
}
- public function isReconciled(): GroupCollectorInterface
+ private function getCollectedGroupIds(): array
{
- $this->query->where('source.reconciled', 1)->where('destination.reconciled', 1);
-
- return $this;
+ return $this->query
+ ->get(['transaction_journals.transaction_group_id'])
+ ->pluck('transaction_group_id')
+ ->toArray()
+ ;
}
- /**
- * Limit results to a specific currency, either foreign or normal one.
- */
- public function setCurrency(TransactionCurrency $currency): GroupCollectorInterface
+ private function mergeAttachments(array $existingJournal, TransactionJournal $newJournal): array
{
- $this->query->where(static function (EloquentBuilder $q) use ($currency): void {
- $q->where('source.transaction_currency_id', $currency->id);
- $q->orWhere('source.foreign_currency_id', $currency->id);
- });
-
- return $this;
- }
+ $newArray = $newJournal->toArray();
+ if (array_key_exists('attachment_id', $newArray)) {
+ $attachmentId = (int) $newJournal['attachment_id'];
- public function setEndRow(int $endRow): self
- {
- $this->endRow = $endRow;
+ $existingJournal['attachments'][$attachmentId] = ['id' => $attachmentId];
+ }
- return $this;
+ return $existingJournal;
}
- public function setExpandGroupSearch(bool $expandGroupSearch): GroupCollectorInterface
+ private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array
{
- $this->expandGroupSearch = $expandGroupSearch;
+ $newArray = $newJournal->toArray();
+ if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well.
+ $tagId = (int) $newJournal['tag_id'];
- return $this;
- }
+ $tagDate = null;
- public function setForeignCurrency(TransactionCurrency $currency): GroupCollectorInterface
- {
- $this->query->where('source.foreign_currency_id', $currency->id);
+ try {
+ $tagDate = Carbon::parse($newArray['tag_date']);
+ } catch (InvalidFormatException $e) {
+ Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
+ }
- return $this;
+ $existingJournal['tags'][$tagId] = [
+ 'id' => (int) $newArray['tag_id'],
+ 'name' => $newArray['tag_name'],
+ 'date' => $tagDate,
+ 'description' => $newArray['tag_description'],
+ ];
+ }
+
+ return $existingJournal;
}
/**
- * Limit the result to a set of specific transaction groups.
+ * @throws FireflyException
*/
- public function setIds(array $groupIds): GroupCollectorInterface
+ private function parseArray(Collection $collection): Collection
{
- $this->query->whereIn('transaction_groups.id', $groupIds);
+ $groups = [];
- return $this;
+ /** @var TransactionJournal $augumentedJournal */
+ foreach ($collection as $augumentedJournal) {
+ $groupId = (int) $augumentedJournal->transaction_group_id;
+
+ if (!array_key_exists($groupId, $groups)) {
+ // make new array
+ $parsedGroup = $this->parseAugmentedJournal($augumentedJournal);
+ $groupArray = [
+ 'id' => (int) $augumentedJournal->transaction_group_id,
+ 'user_id' => $augumentedJournal->user_id,
+ 'user_group_id' => $augumentedJournal->user_group_id,
+ // Field transaction_group_title was added by the query.
+ 'title' => $augumentedJournal->transaction_group_title,
+ 'created_at' => new Carbon($augumentedJournal->group_created_at, config('app.timezone')),
+ 'updated_at' => new Carbon($augumentedJournal->group_updated_at, config('app.timezone')),
+ 'transaction_type' => $parsedGroup['transaction_type_type'],
+ 'count' => 1,
+ 'sums' => [],
+ 'transactions' => [],
+ ];
+ // Field transaction_journal_id was added by the query.
+ $journalId = (int) $augumentedJournal->transaction_journal_id;
+ $groupArray['transactions'][$journalId] = $parsedGroup;
+ $groups[$groupId] = $groupArray;
+
+ continue;
+ }
+ // or parse the rest.
+ // Field transaction_journal_id was added by the query.
+ $journalId = (int) $augumentedJournal->transaction_journal_id;
+ if (array_key_exists($journalId, $groups[$groupId]['transactions'])) {
+ // append data to existing group + journal (for multiple tags or multiple attachments)
+ $groups[$groupId]['transactions'][$journalId] = $this->mergeTags($groups[$groupId]['transactions'][$journalId], $augumentedJournal);
+ $groups[$groupId]['transactions'][$journalId] = $this->mergeAttachments($groups[$groupId]['transactions'][$journalId], $augumentedJournal);
+ }
+
+ if (!array_key_exists($journalId, $groups[$groupId]['transactions'])) {
+ // create second, third, fourth split:
+ ++$groups[$groupId]['count'];
+ $groups[$groupId]['transactions'][$journalId] = $this->parseAugmentedJournal($augumentedJournal);
+ }
+ }
+ $groups = $this->parseSums($groups);
+
+ return new Collection()->push(...$groups);
}
/**
- * Limit the result to a set of specific journals.
+ * @throws FireflyException
+ * @throws JsonException
*/
- public function setJournalIds(array $journalIds): GroupCollectorInterface
+ private function parseAugmentedJournal(TransactionJournal $augumentedJournal): array
{
- if (0 !== count($journalIds)) {
- // make all integers.
- $integerIDs = array_map(intval(...), $journalIds);
- Log::debug(sprintf('GroupCollector: setJournalIds: %s', implode(', ', $integerIDs)));
+ $result = $augumentedJournal->toArray();
+ $result['tags'] = [];
+ $result['attachments'] = [];
+ $result['interest_date'] = null;
+ $result['payment_date'] = null;
+ $result['invoice_date'] = null;
+ $result['book_date'] = null;
+ $result['due_date'] = null;
+ $result['process_date'] = null;
+
+ try {
+ $result['date'] = new Carbon($result['date'], 'UTC');
+ $result['created_at'] = new Carbon($result['created_at'], 'UTC');
+ $result['updated_at'] = new Carbon($result['updated_at'], 'UTC');
+
+ // this is going to happen a lot:
+ $result['date']->setTimezone(config('app.timezone'));
+ $result['created_at']->setTimezone(config('app.timezone'));
+ $result['updated_at']->setTimezone(config('app.timezone'));
+ } catch (Exception $e) { // intentional generic exception
+ Log::error($e->getMessage());
+
+ throw new FireflyException($e->getMessage(), 0, $e);
+ }
+
+ // try to process meta date value (if present)
+ $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date'];
+ if (array_key_exists('meta_name', $result) && in_array($result['meta_name'], $dates, true)) {
+ $name = $result['meta_name'];
+ if (array_key_exists('meta_data', $result) && '' !== (string) $result['meta_data']) {
+ $result[$name] = Carbon::createFromFormat('!Y-m-d', substr((string) json_decode((string) $result['meta_data']), 0, 10));
+ }
+ }
+
+ // convert values to integers:
+ $result = $this->convertToInteger($result);
- $this->query->whereIn('transaction_journals.id', $integerIDs);
- }
+ // convert to boolean
+ $result = $this->convertToBoolean($result);
- return $this;
- }
+ // convert back to strings because SQLite is dumb like that.
+ $result = $this->convertToStrings($result);
- /**
- * Limit results to a specific currency, only normal one.
- */
- public function setNormalCurrency(TransactionCurrency $currency): GroupCollectorInterface
- {
- $this->query->where('source.transaction_currency_id', $currency->id);
+ $result['reconciled'] = 1 === (int) $result['reconciled'];
+ if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well.
+ $tagId = (int) $augumentedJournal['tag_id'];
+ $tagDate = null;
- return $this;
- }
+ try {
+ $tagDate = Carbon::parse($augumentedJournal['tag_date']);
+ } catch (InvalidFormatException $e) {
+ Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
+ }
- /**
- * Set the page to get.
- */
- public function setPage(int $page): GroupCollectorInterface
- {
- $page = 0 === $page ? 1 : $page;
- $this->page = $page;
- // Log::debug(sprintf('GroupCollector: page is now %d', $page));
+ $result['tags'][$tagId] = [
+ 'id' => (int) $result['tag_id'],
+ 'name' => $result['tag_name'],
+ 'date' => $tagDate,
+ 'description' => $result['tag_description'],
+ ];
+ }
- return $this;
+ // also merge attachments:
+ if (array_key_exists('attachment_id', $result) && null !== $result['attachment_id']) {
+ $uploaded = 1 === (int) $result['attachment_uploaded'];
+ $attachmentId = (int) $augumentedJournal['attachment_id'];
+ $deleted = null !== $result['attachment_deleted_at'];
+ if (0 !== $attachmentId && $uploaded && !$deleted) {
+ $result['attachments'][$attachmentId] = [
+ 'id' => $attachmentId,
+ 'filename' => $augumentedJournal['attachment_filename'],
+ 'title' => $augumentedJournal['attachment_title'],
+ ];
+ }
+ }
+ // unset various fields:
+ unset(
+ $result['tag_id'],
+ $result['meta_data'],
+ $result['meta_name'],
+ $result['tag_name'],
+ $result['tag_date'],
+ $result['tag_description'],
+ $result['tag_latitude'],
+ $result['tag_longitude'],
+ $result['tag_zoom_level'],
+ $result['attachment_filename'],
+ $result['attachment_id']
+ );
+
+ return $result;
}
- /**
- * Search for words in descriptions.
- */
- public function setSearchWords(array $array): GroupCollectorInterface
+ private function parseSums(array $groups): array
{
- if (0 === count($array)) {
- Log::debug('No words in array');
-
- return $this;
- }
- Log::debug(sprintf('%d word(s) in array', count($array)));
- $this->query->where(static function (EloquentBuilder $q) use ($array): void {
- $q->where(static function (EloquentBuilder $q1) use ($array): void {
- foreach ($array as $word) {
- $keyword = sprintf('%%%s%%', $word);
- $q1->whereLike('transaction_journals.description', $keyword);
+ /**
+ * @var int $groudId
+ * @var array $group
+ */
+ foreach ($groups as $groudId => $group) {
+ /** @var array $transaction */
+ foreach ($group['transactions'] as $transaction) {
+ $currencyId = (int) $transaction['currency_id'];
+ if (null === $transaction['amount']) {
+ throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId));
}
- });
- $q->orWhere(static function (EloquentBuilder $q2) use ($array): void {
- foreach ($array as $word) {
- $keyword = sprintf('%%%s%%', $word);
- $q2->whereLike('transaction_groups.title', $keyword);
+ $pcAmount = (string) ('' === $transaction['pc_amount'] ? '0' : $transaction['pc_amount']);
+ $pcForeignAmount = (string) ('' === $transaction['pc_foreign_amount'] ? '0' : $transaction['pc_foreign_amount']);
+ $foreignAmount = (string) ('' === $transaction['foreign_amount'] ? '0' : $transaction['foreign_amount']);
+
+ // set default:
+ if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
+ $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;
+ $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code'];
+ $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol'];
+ $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['currency_decimal_places'];
+ $groups[$groudId]['sums'][$currencyId]['amount'] = '0';
+ $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0';
}
- });
- });
+ $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']);
+ $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['pc_amount'], $pcAmount);
- return $this;
- }
+ if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) {
+ $currencyId = (int) $transaction['foreign_currency_id'];
- #[Override]
- public function setSorting(array $instructions): GroupCollectorInterface
- {
- $this->sorting = $instructions;
+ // set default:
+ if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) {
+ $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId;
+ $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code'];
+ $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol'];
+ $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['foreign_currency_decimal_places'];
+ $groups[$groudId]['sums'][$currencyId]['amount'] = '0';
+ $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0';
+ }
+ $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $foreignAmount);
+ $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $pcForeignAmount);
+ }
+ }
+ }
- return $this;
+ return $groups;
}
- public function setStartRow(int $startRow): self
+ private function postFilterCollection(Collection $collection): Collection
{
- $this->startRow = $startRow;
+ $currentCollection = $collection;
+ $countFilters = count($this->postFilters);
+ if (0 === $countFilters) {
+ return $currentCollection;
+ }
+ Log::debug(sprintf(
+ 'GroupCollector: postFilterCollection has %d filter(s) and %d transaction(s).',
+ count($this->postFilters),
+ count($currentCollection)
+ ));
- return $this;
- }
+ if (0 === $currentCollection->count()) {
+ Log::debug('Found nothing anyway, return empty collection.');
- /**
- * Limit the search to one specific transaction group.
- */
- public function setTransactionGroup(TransactionGroup $transactionGroup): GroupCollectorInterface
- {
- $this->query->where('transaction_groups.id', $transactionGroup->id);
+ return $currentCollection;
+ }
- return $this;
- }
+ /**
+ * @var Closure $function
+ */
+ foreach ($this->postFilters as $function) {
+ Log::debug('Applying filter...');
+ $nextCollection = new Collection();
- /**
- * Limit the included transaction types.
- */
- public function setTypes(array $types): GroupCollectorInterface
- {
- $this->query->whereIn('transaction_types.type', $types);
+ // loop everything in the current collection
+ // and save it (or not) in the new collection.
+ // that new collection is the next current collection
+ /**
+ * @var array $item
+ */
+ foreach ($currentCollection as $item) {
+ $result = $function($item);
+ if (false === $result) {
+ // skip other filters, continue to next item.
+ Log::debug('Result is false');
- return $this;
- }
+ continue;
+ }
+ // if the result is a bool, use the unedited results.
+ if (true === $result) {
+ Log::debug('Result is true');
+ $nextCollection->push($item);
- /**
- * Set the user object and start the query.
- */
- public function setUser(User $user): GroupCollectorInterface
- {
- if (!$this->user instanceof User) {
- $this->user = $user;
- $this->startQuery();
+ continue;
+ }
+ // if the result is an array, the filter has changed what's being returned.
+ if (is_array($result)) {
+ Log::debug('Result is array');
+ $nextCollection->push($result);
+
+ continue;
+ }
+ Log::debug('Result is something else!');
+ }
+ $currentCollection = $nextCollection;
+ Log::debug(sprintf('GroupCollector: postFilterCollection has %d transaction(s) left.', count($currentCollection)));
}
- return $this;
+ return $currentCollection;
}
/**
@@ -1081,19 +1113,6 @@ class GroupCollector implements GroupCollectorInterface
;
}
- /**
- * Set the user object and start the query.
- */
- public function setUserGroup(UserGroup $userGroup): GroupCollectorInterface
- {
- if (!$this->userGroup instanceof UserGroup) {
- $this->userGroup = $userGroup;
- $this->startQueryForGroup();
- }
-
- return $this;
- }
-
/**
* Build the query.
*/
@@ -1123,26 +1142,6 @@ class GroupCollector implements GroupCollectorInterface
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC')
->orderBy('transaction_journals.description', 'DESC')
- ->orderBy('source.amount', 'DESC')
- ;
- }
-
- /**
- * Automatically include all stuff required to make API calls work.
- */
- public function withAPIInformation(): GroupCollectorInterface
- {
- // include source + destination account name and type.
- $this
- ->withAccountInformation()
- // include category ID + name (if any)
- ->withCategoryInformation()
- // include budget ID + name (if any)
- ->withBudgetInformation()
- // include bill ID + name (if any)
- ->withBillInformation()
- ;
-
- return $this;
+ ->orderBy('source.amount', 'DESC');
}
}
diff --git a/app/Helpers/Collector/GroupCollectorInterface.php b/app/Helpers/Collector/GroupCollectorInterface.php
index 8dab806e8c..afb457764f 100644
--- a/app/Helpers/Collector/GroupCollectorInterface.php
+++ b/app/Helpers/Collector/GroupCollectorInterface.php
@@ -628,11 +628,6 @@ interface GroupCollectorInterface
*/
public function sortCollection(Collection $collection): Collection;
- /**
- * Automatically include all stuff required to make API calls work.
- */
- public function withAPIInformation(): self;
-
/**
* Will include the source and destination account names and types.
*/
@@ -643,6 +638,11 @@ interface GroupCollectorInterface
*/
public function withAnyNotes(): self;
+ /**
+ * Automatically include all stuff required to make API calls work.
+ */
+ public function withAPIInformation(): self;
+
/**
* Add basic info on attachments of transactions.
*/
@@ -698,11 +698,6 @@ interface GroupCollectorInterface
*/
public function withNotes(): self;
- /**
- * Add tag info.
- */
- public function withTagInformation(): self;
-
/**
* Limit results to a transactions without a bill.
*/
@@ -732,6 +727,11 @@ interface GroupCollectorInterface
public function withoutTags(): self;
+ /**
+ * Add tag info.
+ */
+ public function withTagInformation(): self;
+
public function yearAfter(string $year): self;
public function yearBefore(string $year): self;
diff --git a/app/Http/Controllers/Account/IndexController.php b/app/Http/Controllers/Account/IndexController.php
index c529d61377..682c24f91c 100644
--- a/app/Http/Controllers/Account/IndexController.php
+++ b/app/Http/Controllers/Account/IndexController.php
@@ -123,16 +123,6 @@ class IndexController extends Controller
]);
}
- private function subtract(array $startBalances, array $endBalances): array
- {
- $result = [];
- foreach ($endBalances as $key => $value) {
- $result[$key] = bcsub((string) $value, $startBalances[$key] ?? '0');
- }
-
- return $result;
- }
-
/**
* Show list of accounts.
*
@@ -214,4 +204,14 @@ class IndexController extends Controller
'accounts' => $accounts,
]);
}
+
+ private function subtract(array $startBalances, array $endBalances): array
+ {
+ $result = [];
+ foreach ($endBalances as $key => $value) {
+ $result[$key] = bcsub((string) $value, $startBalances[$key] ?? '0');
+ }
+
+ return $result;
+ }
}
diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php
index 1b11a93b1e..4b654abe56 100644
--- a/app/Http/Controllers/Auth/ForgotPasswordController.php
+++ b/app/Http/Controllers/Auth/ForgotPasswordController.php
@@ -104,29 +104,6 @@ class ForgotPasswordController extends Controller
return back()->with('status', trans($response));
}
- /**
- * @throws FireflyException
- */
- private function validateHost(): void
- {
- try {
- $configuredHost = parse_url((string) config('app.url'), PHP_URL_HOST);
- } catch (UrlException $e) {
- throw new FireflyException('Please set a valid and correct Firefly III URL in the APP_URL environment variable.', 0, $e);
- }
- if (!is_string($configuredHost)) {
- throw new FireflyException('Please set a valid and correct Firefly III URL in the APP_URL environment variable.');
- }
- $host = request()->host();
- if ($configuredHost !== $host) {
- Log::error(sprintf('Host header is "%s", APP_URL is "%s".', $host, $configuredHost));
-
- throw new FireflyException(
- 'The Host-header does not match the host in the APP_URL environment variable. Please make sure these match. See also: https://bit.ly/FF3-host-header'
- );
- }
- }
-
/**
* Show form for email recovery.
*
@@ -155,4 +132,27 @@ class ForgotPasswordController extends Controller
return view('auth.passwords.email')->with(['allowRegistration' => $allowRegistration, 'pageTitle' => $pageTitle]);
}
+
+ /**
+ * @throws FireflyException
+ */
+ private function validateHost(): void
+ {
+ try {
+ $configuredHost = parse_url((string) config('app.url'), PHP_URL_HOST);
+ } catch (UrlException $e) {
+ throw new FireflyException('Please set a valid and correct Firefly III URL in the APP_URL environment variable.', 0, $e);
+ }
+ if (!is_string($configuredHost)) {
+ throw new FireflyException('Please set a valid and correct Firefly III URL in the APP_URL environment variable.');
+ }
+ $host = request()->host();
+ if ($configuredHost !== $host) {
+ Log::error(sprintf('Host header is "%s", APP_URL is "%s".', $host, $configuredHost));
+
+ throw new FireflyException(
+ 'The Host-header does not match the host in the APP_URL environment variable. Please make sure these match. See also: https://bit.ly/FF3-host-header'
+ );
+ }
+ }
}
diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php
index 4800c78008..8fd8b4b540 100644
--- a/app/Http/Controllers/Auth/LoginController.php
+++ b/app/Http/Controllers/Auth/LoginController.php
@@ -150,29 +150,6 @@ class LoginController extends Controller
return response()->json();
}
- /**
- * Get the login username to be used by the controller.
- */
- public function username(): string
- {
- return $this->username;
- }
-
- /**
- * Get the failed login response instance.
- *
- * @SuppressWarnings("PHPMD.UnusedFormalParameter")
- *
- * @throws ValidationException
- */
- protected function sendFailedLoginResponse(Request $request): void
- {
- $exception = ValidationException::withMessages([$this->username() => [trans('auth.failed')]]);
- $exception->redirectTo = route('login');
-
- throw $exception;
- }
-
/**
* Log the user out of the application.
*/
@@ -257,6 +234,29 @@ class LoginController extends Controller
]);
}
+ /**
+ * Get the login username to be used by the controller.
+ */
+ public function username(): string
+ {
+ return $this->username;
+ }
+
+ /**
+ * Get the failed login response instance.
+ *
+ * @SuppressWarnings("PHPMD.UnusedFormalParameter")
+ *
+ * @throws ValidationException
+ */
+ protected function sendFailedLoginResponse(Request $request): void
+ {
+ $exception = ValidationException::withMessages([$this->username() => [trans('auth.failed')]]);
+ $exception->redirectTo = route('login');
+
+ throw $exception;
+ }
+
/**
* Send the response after the user was authenticated.
*
diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php
index 0de21cb311..54c9fb3273 100644
--- a/app/Http/Controllers/Auth/RegisterController.php
+++ b/app/Http/Controllers/Auth/RegisterController.php
@@ -113,31 +113,6 @@ class RegisterController extends Controller
return redirect($this->redirectPath());
}
- /**
- * @throws FireflyException
- */
- protected function allowedToRegister(): bool
- {
- // is allowed to register?
- $allowRegistration = true;
-
- try {
- $singleUserMode = FireflyConfig::get('single_user_mode', config('firefly.configuration.single_user_mode'))->data;
- } catch (ContainerExceptionInterface|NotFoundExceptionInterface) {
- $singleUserMode = true;
- }
- $userCount = User::count();
- $guard = config('auth.defaults.guard');
- if (true === $singleUserMode && $userCount > 0 && 'web' === $guard) {
- $allowRegistration = false;
- }
- if ('web' !== $guard) {
- return false;
- }
-
- return $allowRegistration;
- }
-
/**
* Show the application registration form if the invitation code is valid.
*
@@ -197,4 +172,29 @@ class RegisterController extends Controller
return view('auth.register', ['isDemoSite' => $isDemoSite, 'email' => $email, 'pageTitle' => $pageTitle]);
}
+
+ /**
+ * @throws FireflyException
+ */
+ protected function allowedToRegister(): bool
+ {
+ // is allowed to register?
+ $allowRegistration = true;
+
+ try {
+ $singleUserMode = FireflyConfig::get('single_user_mode', config('firefly.configuration.single_user_mode'))->data;
+ } catch (ContainerExceptionInterface|NotFoundExceptionInterface) {
+ $singleUserMode = true;
+ }
+ $userCount = User::count();
+ $guard = config('auth.defaults.guard');
+ if (true === $singleUserMode && $userCount > 0 && 'web' === $guard) {
+ $allowRegistration = false;
+ }
+ if ('web' !== $guard) {
+ return false;
+ }
+
+ return $allowRegistration;
+ }
}
diff --git a/app/Http/Controllers/Auth/TwoFactorController.php b/app/Http/Controllers/Auth/TwoFactorController.php
index f8919f52c6..9db3704962 100644
--- a/app/Http/Controllers/Auth/TwoFactorController.php
+++ b/app/Http/Controllers/Auth/TwoFactorController.php
@@ -126,22 +126,23 @@ class TwoFactorController extends Controller
return redirect(route('home'));
}
- /**
- * Each MFA history has a timestamp and a code, saving the MFA entries for 5 minutes. So if the
- * submitted MFA code has been submitted in the last 5 minutes, it won't work despite being valid.
- */
- private function inMFAHistory(string $mfaCode, array $mfaHistory): bool
+ private function addToMFAFailureCounter(): void
{
- $now = Carbon::now()->getTimestamp();
- foreach ($mfaHistory as $entry) {
- $time = $entry['time'];
- $code = $entry['code'];
- if ($code === $mfaCode && ($now - $time) <= 300) {
- return true;
- }
- }
+ $preference = (int) Preferences::get('mfa_failure_count', 0)->data;
+ ++$preference;
+ Log::channel('audit')->info(sprintf('MFA failure count is set to %d.', $preference));
+ Preferences::set('mfa_failure_count', $preference);
+ }
- return false;
+ private function addToMFAHistory(string $mfaCode): void
+ {
+ /** @var array $mfaHistory */
+ $mfaHistory = Preferences::get('mfa_history', [])->data;
+ $entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode];
+ $mfaHistory[] = $entry;
+
+ Preferences::set('mfa_history', $mfaHistory);
+ $this->filterMFAHistory();
}
/**
@@ -163,14 +164,6 @@ class TwoFactorController extends Controller
Preferences::set('mfa_history', $newHistory);
}
- private function addToMFAFailureCounter(): void
- {
- $preference = (int) Preferences::get('mfa_failure_count', 0)->data;
- ++$preference;
- Log::channel('audit')->info(sprintf('MFA failure count is set to %d.', $preference));
- Preferences::set('mfa_failure_count', $preference);
- }
-
private function getMFAFailureCounter(): int
{
$value = (int) Preferences::get('mfa_failure_count', 0)->data;
@@ -179,21 +172,22 @@ class TwoFactorController extends Controller
return $value;
}
- private function addToMFAHistory(string $mfaCode): void
+ /**
+ * Each MFA history has a timestamp and a code, saving the MFA entries for 5 minutes. So if the
+ * submitted MFA code has been submitted in the last 5 minutes, it won't work despite being valid.
+ */
+ private function inMFAHistory(string $mfaCode, array $mfaHistory): bool
{
- /** @var array $mfaHistory */
- $mfaHistory = Preferences::get('mfa_history', [])->data;
- $entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode];
- $mfaHistory[] = $entry;
-
- Preferences::set('mfa_history', $mfaHistory);
- $this->filterMFAHistory();
- }
+ $now = Carbon::now()->getTimestamp();
+ foreach ($mfaHistory as $entry) {
+ $time = $entry['time'];
+ $code = $entry['code'];
+ if ($code === $mfaCode && ($now - $time) <= 300) {
+ return true;
+ }
+ }
- private function resetMFAFailureCounter(): void
- {
- Preferences::set('mfa_failure_count', 0);
- Log::channel('audit')->info('MFA failure count is set to zero.');
+ return false;
}
/**
@@ -235,4 +229,10 @@ class TwoFactorController extends Controller
Preferences::set('mfa_recovery', $newList);
}
+
+ private function resetMFAFailureCounter(): void
+ {
+ Preferences::set('mfa_failure_count', 0);
+ Log::channel('audit')->info('MFA failure count is set to zero.');
+ }
}
diff --git a/app/Http/Controllers/Bill/IndexController.php b/app/Http/Controllers/Bill/IndexController.php
index bc7f56c3ef..f01954990e 100644
--- a/app/Http/Controllers/Bill/IndexController.php
+++ b/app/Http/Controllers/Bill/IndexController.php
@@ -136,6 +136,58 @@ class IndexController extends Controller
return view('bills.index', ['bills' => $bills, 'sums' => $sums, 'total' => $total, 'totals' => $totals, 'today' => $today]);
}
+ /**
+ * Set the order of a bill.
+ */
+ public function setOrder(Request $request, Bill $bill): JsonResponse
+ {
+ $objectGroupTitle = (string) $request->get('objectGroupTitle');
+ $newOrder = (int) $request->get('order');
+ $this->repository->setOrder($bill, $newOrder);
+ if ('' !== $objectGroupTitle) {
+ $this->repository->setObjectGroup($bill, $objectGroupTitle);
+ }
+ if ('' === $objectGroupTitle) {
+ $this->repository->removeObjectGroup($bill);
+ }
+
+ return response()->json(['data' => 'OK']);
+ }
+
+ private function amountPerPeriod(array $bill, string $range): string
+ {
+ $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2');
+
+ Log::debug(sprintf('Amount per period for bill #%d "%s"', $bill['id'], $bill['name']));
+ Log::debug(sprintf('Average is %s', $avg));
+ // calculate amount per year:
+ $multiplies = ['yearly' => '1', 'half-year' => '2', 'quarterly' => '4', 'monthly' => '12', 'weekly' => '52.17', 'daily' => '365.24'];
+ $yearAmount = bcmul($avg, bcdiv($multiplies[$bill['repeat_freq']], (string) ($bill['skip'] + 1)));
+ Log::debug(sprintf('Amount per year is %s (%s * %s / %s)', $yearAmount, $avg, $multiplies[$bill['repeat_freq']], (string) ($bill['skip'] + 1)));
+
+ // per period:
+ $division = [
+ '1Y' => '1',
+ '6M' => '2',
+ '3M' => '4',
+ '1M' => '12',
+ '1W' => '52.16',
+ '1D' => '365.24',
+ 'YTD' => '1',
+ 'QTD' => '4',
+ 'MTD' => '12',
+ 'last7' => '52.16',
+ 'last30' => '12',
+ 'last90' => '4',
+ 'last365' => '1',
+ ];
+ $perPeriod = bcdiv($yearAmount, $division[$range]);
+
+ Log::debug(sprintf('Amount per %s is %s (%s / %s)', $range, $perPeriod, $yearAmount, $division[$range]));
+
+ return $perPeriod;
+ }
+
private function getSums(array $bills): array
{
Log::debug(sprintf('now in getSums(count:%d)', count($bills)));
@@ -220,40 +272,6 @@ class IndexController extends Controller
return $sums;
}
- private function amountPerPeriod(array $bill, string $range): string
- {
- $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2');
-
- Log::debug(sprintf('Amount per period for bill #%d "%s"', $bill['id'], $bill['name']));
- Log::debug(sprintf('Average is %s', $avg));
- // calculate amount per year:
- $multiplies = ['yearly' => '1', 'half-year' => '2', 'quarterly' => '4', 'monthly' => '12', 'weekly' => '52.17', 'daily' => '365.24'];
- $yearAmount = bcmul($avg, bcdiv($multiplies[$bill['repeat_freq']], (string) ($bill['skip'] + 1)));
- Log::debug(sprintf('Amount per year is %s (%s * %s / %s)', $yearAmount, $avg, $multiplies[$bill['repeat_freq']], (string) ($bill['skip'] + 1)));
-
- // per period:
- $division = [
- '1Y' => '1',
- '6M' => '2',
- '3M' => '4',
- '1M' => '12',
- '1W' => '52.16',
- '1D' => '365.24',
- 'YTD' => '1',
- 'QTD' => '4',
- 'MTD' => '12',
- 'last7' => '52.16',
- 'last30' => '12',
- 'last90' => '4',
- 'last365' => '1',
- ];
- $perPeriod = bcdiv($yearAmount, $division[$range]);
-
- Log::debug(sprintf('Amount per %s is %s (%s / %s)', $range, $perPeriod, $yearAmount, $division[$range]));
-
- return $perPeriod;
- }
-
private function getTotals(array $sums): array
{
$totals = [];
@@ -287,22 +305,4 @@ class IndexController extends Controller
return $totals;
}
-
- /**
- * Set the order of a bill.
- */
- public function setOrder(Request $request, Bill $bill): JsonResponse
- {
- $objectGroupTitle = (string) $request->get('objectGroupTitle');
- $newOrder = (int) $request->get('order');
- $this->repository->setOrder($bill, $newOrder);
- if ('' !== $objectGroupTitle) {
- $this->repository->setObjectGroup($bill, $objectGroupTitle);
- }
- if ('' === $objectGroupTitle) {
- $this->repository->removeObjectGroup($bill);
- }
-
- return response()->json(['data' => 'OK']);
- }
}
diff --git a/app/Http/Controllers/Budget/BudgetLimitController.php b/app/Http/Controllers/Budget/BudgetLimitController.php
index c37d802934..8eebf7795c 100644
--- a/app/Http/Controllers/Budget/BudgetLimitController.php
+++ b/app/Http/Controllers/Budget/BudgetLimitController.php
@@ -97,7 +97,7 @@ class BudgetLimitController extends Controller
return true;
});
- return view('budgets.budget-limits.create', ['start' => $start, 'end' => $end, 'currencies' => $currencies, 'budget' => $budget]);
+ return view('budgets.budget-limits.create', ['start' => $start, 'end' => $end, 'currencies' => $currencies, 'budget' => $budget]);
}
public function delete(BudgetLimit $budgetLimit): Redirector|RedirectResponse
diff --git a/app/Http/Controllers/Budget/IndexController.php b/app/Http/Controllers/Budget/IndexController.php
index 7dc441075a..ef43c56848 100644
--- a/app/Http/Controllers/Budget/IndexController.php
+++ b/app/Http/Controllers/Budget/IndexController.php
@@ -158,6 +158,24 @@ final class IndexController extends Controller
]);
}
+ public function reorder(Request $request, BudgetRepositoryInterface $repository): JsonResponse
+ {
+ $this->abRepository->cleanup();
+ $budgetIds = $request->get('budgetIds');
+
+ foreach ($budgetIds as $index => $budgetId) {
+ $budgetId = (int) $budgetId;
+ $budget = $repository->find($budgetId);
+ if ($budget instanceof Budget) {
+ Log::debug(sprintf('Set budget #%d ("%s") to position %d', $budget->id, $budget->name, $index + 1));
+ $repository->setBudgetOrder($budget, $index + 1);
+ }
+ }
+ Preferences::mark();
+
+ return response()->json(['OK']);
+ }
+
private function getAllAvailableBudgets(Carbon $start, Carbon $end): array
{
Log::debug(sprintf('Start of getAllAvailableBudgets("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
@@ -305,22 +323,4 @@ final class IndexController extends Controller
return $sums;
}
-
- public function reorder(Request $request, BudgetRepositoryInterface $repository): JsonResponse
- {
- $this->abRepository->cleanup();
- $budgetIds = $request->get('budgetIds');
-
- foreach ($budgetIds as $index => $budgetId) {
- $budgetId = (int) $budgetId;
- $budget = $repository->find($budgetId);
- if ($budget instanceof Budget) {
- Log::debug(sprintf('Set budget #%d ("%s") to position %d', $budget->id, $budget->name, $index + 1));
- $repository->setBudgetOrder($budget, $index + 1);
- }
- }
- Preferences::mark();
-
- return response()->json(['OK']);
- }
}
diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php
index 5d829c325b..b4416758fa 100644
--- a/app/Http/Controllers/Chart/AccountController.php
+++ b/app/Http/Controllers/Chart/AccountController.php
@@ -204,17 +204,6 @@ class AccountController extends Controller
return response()->json($data);
}
- /**
- * Expenses per budget for all time, as shown on account overview.
- */
- public function expenseBudgetAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
- {
- $start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
- $end = today(config('app.timezone'));
-
- return $this->expenseBudget($account, $start, $end);
- }
-
/**
* Expenses per budget, as shown on account overview.
*/
@@ -293,14 +282,14 @@ class AccountController extends Controller
}
/**
- * Expenses grouped by category for account.
+ * Expenses per budget for all time, as shown on account overview.
*/
- public function expenseCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
+ public function expenseBudgetAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
$end = today(config('app.timezone'));
- return $this->expenseCategory($account, $start, $end);
+ return $this->expenseBudget($account, $start, $end);
}
/**
@@ -375,6 +364,17 @@ class AccountController extends Controller
return response()->json($data);
}
+ /**
+ * Expenses grouped by category for account.
+ */
+ public function expenseCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
+ {
+ $start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
+ $end = today(config('app.timezone'));
+
+ return $this->expenseCategory($account, $start, $end);
+ }
+
/**
* Shows the balances for all the user's frontpage accounts.
*
@@ -401,17 +401,6 @@ class AccountController extends Controller
return response()->json($this->accountBalanceChart($accounts, $start, $end));
}
- /**
- * Shows the income grouped by category for an account, in all time.
- */
- public function incomeCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
- {
- $start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
- $end = today(config('app.timezone'));
-
- return $this->incomeCategory($account, $start, $end);
- }
-
/**
* Shows all income per account for each category.
*/
@@ -485,6 +474,17 @@ class AccountController extends Controller
return response()->json($data);
}
+ /**
+ * Shows the income grouped by category for an account, in all time.
+ */
+ public function incomeCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
+ {
+ $start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
+ $end = today(config('app.timezone'));
+
+ return $this->incomeCategory($account, $start, $end);
+ }
+
/**
* Shows overview of account during a single period.
*
@@ -617,15 +617,6 @@ class AccountController extends Controller
return response()->json($data);
}
- private function updateChartKeys(array $array, array $balances): array
- {
- foreach (array_keys($balances) as $key) {
- $array[$key] ??= ['key' => $key];
- }
-
- return $array;
- }
-
/**
* Shows the balances for a given set of dates and accounts.
*
@@ -762,4 +753,13 @@ class AccountController extends Controller
return response()->json($data);
}
+
+ private function updateChartKeys(array $array, array $balances): array
+ {
+ foreach (array_keys($balances) as $key) {
+ $array[$key] ??= ['key' => $key];
+ }
+
+ return $array;
+ }
}
diff --git a/app/Http/Controllers/Chart/BudgetReportController.php b/app/Http/Controllers/Chart/BudgetReportController.php
index 0b7f03a42c..f133c55053 100644
--- a/app/Http/Controllers/Chart/BudgetReportController.php
+++ b/app/Http/Controllers/Chart/BudgetReportController.php
@@ -196,23 +196,6 @@ class BudgetReportController extends Controller
return response()->json($data);
}
- private function makeEntries(Carbon $start, Carbon $end): array
- {
- $return = [];
- $format = Navigation::preferredCarbonLocalizedFormat($start, $end);
- $preferredRange = Navigation::preferredRangeFormat($start, $end);
- $currentStart = clone $start;
- while ($currentStart <= $end) {
- $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
- $key = $currentStart->isoFormat($format);
- $return[$key] = '0';
- $currentStart = clone $currentEnd;
- $currentStart->addDay()->startOfDay();
- }
-
- return $return;
- }
-
/**
* Chart that groups expenses by the account.
*/
@@ -242,4 +225,21 @@ class BudgetReportController extends Controller
return response()->json($data);
}
+
+ private function makeEntries(Carbon $start, Carbon $end): array
+ {
+ $return = [];
+ $format = Navigation::preferredCarbonLocalizedFormat($start, $end);
+ $preferredRange = Navigation::preferredRangeFormat($start, $end);
+ $currentStart = clone $start;
+ while ($currentStart <= $end) {
+ $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
+ $key = $currentStart->isoFormat($format);
+ $return[$key] = '0';
+ $currentStart = clone $currentEnd;
+ $currentStart->addDay()->startOfDay();
+ }
+
+ return $return;
+ }
}
diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php
index a6024980fa..518159f6fc 100644
--- a/app/Http/Controllers/Chart/CategoryController.php
+++ b/app/Http/Controllers/Chart/CategoryController.php
@@ -97,11 +97,6 @@ class CategoryController extends Controller
return response()->json($data);
}
- private function getDate(): Carbon
- {
- return today(config('app.timezone'));
- }
-
/**
* Shows the category chart on the front page.
* TODO test method for category refactor.
@@ -151,6 +146,67 @@ class CategoryController extends Controller
return response()->json($data);
}
+ /**
+ * Chart for period for transactions without a category.
+ * TODO test me.
+ */
+ public function reportPeriodNoCategory(Collection $accounts, Carbon $start, Carbon $end): JsonResponse
+ {
+ $cache = new CacheProperties();
+ $cache->addProperty($start);
+ $cache->addProperty($end);
+ $cache->addProperty('chart.category.period.no-cat');
+ $cache->addProperty($accounts->pluck('id')->toArray());
+ if ($cache->has()) {
+ return response()->json($cache->get());
+ }
+ $data = $this->reportPeriodChart($accounts, $start, $end, null);
+
+ $cache->store($data);
+
+ return response()->json($data);
+ }
+
+ /**
+ * Chart for a specific period.
+ * TODO test me, for category refactor.
+ *
+ * @throws ContainerExceptionInterface
+ * @throws NotFoundExceptionInterface
+ */
+ public function specificPeriod(Category $category, Carbon $date): JsonResponse
+ {
+ $range = Navigation::getViewRange(false);
+ $start = Navigation::startOfPeriod($date, $range);
+ $end = session()->get('end');
+ if ($end < $start) {
+ [$end, $start] = [$start, $end];
+ }
+
+ $cache = new CacheProperties();
+ $cache->addProperty($start);
+ $cache->addProperty($end);
+ $cache->addProperty($category->id);
+ $cache->addProperty('chart.category.period-chart');
+ if ($cache->has()) {
+ return response()->json($cache->get());
+ }
+
+ /** @var WholePeriodChartGenerator $chartGenerator */
+ $chartGenerator = app(WholePeriodChartGenerator::class);
+ $chartData = $chartGenerator->generate($category, $start, $end);
+ $data = $this->generator->multiSet($chartData);
+
+ $cache->store($data);
+
+ return response()->json($data);
+ }
+
+ private function getDate(): Carbon
+ {
+ return today(config('app.timezone'));
+ }
+
/**
* Generate report chart for either with or without category.
*/
@@ -227,60 +283,4 @@ class CategoryController extends Controller
return $this->generator->multiSet($chartData);
}
-
- /**
- * Chart for period for transactions without a category.
- * TODO test me.
- */
- public function reportPeriodNoCategory(Collection $accounts, Carbon $start, Carbon $end): JsonResponse
- {
- $cache = new CacheProperties();
- $cache->addProperty($start);
- $cache->addProperty($end);
- $cache->addProperty('chart.category.period.no-cat');
- $cache->addProperty($accounts->pluck('id')->toArray());
- if ($cache->has()) {
- return response()->json($cache->get());
- }
- $data = $this->reportPeriodChart($accounts, $start, $end, null);
-
- $cache->store($data);
-
- return response()->json($data);
- }
-
- /**
- * Chart for a specific period.
- * TODO test me, for category refactor.
- *
- * @throws ContainerExceptionInterface
- * @throws NotFoundExceptionInterface
- */
- public function specificPeriod(Category $category, Carbon $date): JsonResponse
- {
- $range = Navigation::getViewRange(false);
- $start = Navigation::startOfPeriod($date, $range);
- $end = session()->get('end');
- if ($end < $start) {
- [$end, $start] = [$start, $end];
- }
-
- $cache = new CacheProperties();
- $cache->addProperty($start);
- $cache->addProperty($end);
- $cache->addProperty($category->id);
- $cache->addProperty('chart.category.period-chart');
- if ($cache->has()) {
- return response()->json($cache->get());
- }
-
- /** @var WholePeriodChartGenerator $chartGenerator */
- $chartGenerator = app(WholePeriodChartGenerator::class);
- $chartData = $chartGenerator->generate($category, $start, $end);
- $data = $this->generator->multiSet($chartData);
-
- $cache->store($data);
-
- return response()->json($data);
- }
}
diff --git a/app/Http/Controllers/Chart/CategoryReportController.php b/app/Http/Controllers/Chart/CategoryReportController.php
index 49d865794d..0c61d6642e 100644
--- a/app/Http/Controllers/Chart/CategoryReportController.php
+++ b/app/Http/Controllers/Chart/CategoryReportController.php
@@ -268,26 +268,6 @@ class CategoryReportController extends Controller
return response()->json($data);
}
- /**
- * TODO duplicate function
- */
- private function makeEntries(Carbon $start, Carbon $end): array
- {
- $return = [];
- $format = Navigation::preferredCarbonLocalizedFormat($start, $end);
- $preferredRange = Navigation::preferredRangeFormat($start, $end);
- $currentStart = clone $start;
- while ($currentStart <= $end) {
- $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
- $key = $currentStart->isoFormat($format);
- $return[$key] = '0';
- $currentStart = clone $currentEnd;
- $currentStart->addDay()->startOfDay();
- }
-
- return $return;
- }
-
public function sourceExpense(Collection $accounts, Collection $categories, Carbon $start, Carbon $end): JsonResponse
{
$result = [];
@@ -343,4 +323,24 @@ class CategoryReportController extends Controller
return response()->json($data);
}
+
+ /**
+ * TODO duplicate function
+ */
+ private function makeEntries(Carbon $start, Carbon $end): array
+ {
+ $return = [];
+ $format = Navigation::preferredCarbonLocalizedFormat($start, $end);
+ $preferredRange = Navigation::preferredRangeFormat($start, $end);
+ $currentStart = clone $start;
+ while ($currentStart <= $end) {
+ $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
+ $key = $currentStart->isoFormat($format);
+ $return[$key] = '0';
+ $currentStart = clone $currentEnd;
+ $currentStart->addDay()->startOfDay();
+ }
+
+ return $return;
+ }
}
diff --git a/app/Http/Controllers/Chart/DoubleReportController.php b/app/Http/Controllers/Chart/DoubleReportController.php
index 8b002eb9b1..675c09ea51 100644
--- a/app/Http/Controllers/Chart/DoubleReportController.php
+++ b/app/Http/Controllers/Chart/DoubleReportController.php
@@ -213,44 +213,6 @@ class DoubleReportController extends Controller
return response()->json($data);
}
- /**
- * TODO duplicate function
- */
- private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
- {
- /** @var Account $account */
- foreach ($accounts as $account) {
- if ($account->name === $name && $account->id !== $id) {
- return $account->name;
- }
- if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
- return $account->iban;
- }
- }
-
- return $name;
- }
-
- /**
- * TODO duplicate function
- */
- private function makeEntries(Carbon $start, Carbon $end): array
- {
- $return = [];
- $format = Navigation::preferredCarbonLocalizedFormat($start, $end);
- $preferredRange = Navigation::preferredRangeFormat($start, $end);
- $currentStart = clone $start;
- while ($currentStart <= $end) {
- $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
- $key = $currentStart->isoFormat($format);
- $return[$key] = '0';
- $currentStart = clone $currentEnd;
- $currentStart->addDay()->startOfDay();
- }
-
- return $return;
- }
-
public function tagExpense(Collection $accounts, Collection $others, Carbon $start, Carbon $end): JsonResponse
{
$result = [];
@@ -356,4 +318,42 @@ class DoubleReportController extends Controller
return response()->json($data);
}
+
+ /**
+ * TODO duplicate function
+ */
+ private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
+ {
+ /** @var Account $account */
+ foreach ($accounts as $account) {
+ if ($account->name === $name && $account->id !== $id) {
+ return $account->name;
+ }
+ if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
+ return $account->iban;
+ }
+ }
+
+ return $name;
+ }
+
+ /**
+ * TODO duplicate function
+ */
+ private function makeEntries(Carbon $start, Carbon $end): array
+ {
+ $return = [];
+ $format = Navigation::preferredCarbonLocalizedFormat($start, $end);
+ $preferredRange = Navigation::preferredRangeFormat($start, $end);
+ $currentStart = clone $start;
+ while ($currentStart <= $end) {
+ $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
+ $key = $currentStart->isoFormat($format);
+ $return[$key] = '0';
+ $currentStart = clone $currentEnd;
+ $currentStart->addDay()->startOfDay();
+ }
+
+ return $return;
+ }
}
diff --git a/app/Http/Controllers/Chart/TagReportController.php b/app/Http/Controllers/Chart/TagReportController.php
index 2f068f2dc6..5c85c417a6 100644
--- a/app/Http/Controllers/Chart/TagReportController.php
+++ b/app/Http/Controllers/Chart/TagReportController.php
@@ -274,26 +274,6 @@ class TagReportController extends Controller
return response()->json($data);
}
- /**
- * TODO duplicate function
- */
- private function makeEntries(Carbon $start, Carbon $end): array
- {
- $return = [];
- $format = Navigation::preferredCarbonLocalizedFormat($start, $end);
- $preferredRange = Navigation::preferredRangeFormat($start, $end);
- $currentStart = clone $start;
- while ($currentStart <= $end) {
- $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
- $key = $currentStart->isoFormat($format);
- $return[$key] = '0';
- $currentStart = clone $currentEnd;
- $currentStart->addDay()->startOfDay();
- }
-
- return $return;
- }
-
public function sourceExpense(Collection $accounts, Collection $tags, Carbon $start, Carbon $end): JsonResponse
{
$result = [];
@@ -401,4 +381,24 @@ class TagReportController extends Controller
return response()->json($data);
}
+
+ /**
+ * TODO duplicate function
+ */
+ private function makeEntries(Carbon $start, Carbon $end): array
+ {
+ $return = [];
+ $format = Navigation::preferredCarbonLocalizedFormat($start, $end);
+ $preferredRange = Navigation::preferredRangeFormat($start, $end);
+ $currentStart = clone $start;
+ while ($currentStart <= $end) {
+ $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
+ $key = $currentStart->isoFormat($format);
+ $return[$key] = '0';
+ $currentStart = clone $currentEnd;
+ $currentStart->addDay()->startOfDay();
+ }
+
+ return $return;
+ }
}
diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php
index 0e15119815..f4d7ae994a 100644
--- a/app/Http/Controllers/DebugController.php
+++ b/app/Http/Controllers/DebugController.php
@@ -75,6 +75,11 @@ class DebugController extends Controller
$this->middleware(IsDemoUser::class)->except(['displayError']);
}
+ public function apiTest(): View
+ {
+ return view('test.api-test');
+ }
+
/**
* Show all possible errors.
*
@@ -162,200 +167,6 @@ class DebugController extends Controller
return view('debug', ['table' => $table, 'now' => $now, 'logContent' => $logContent]);
}
- public function apiTest(): View
- {
- return view('test.api-test');
- }
-
- private function generateTable(): string
- {
- // system information:
- $system = $this->getSystemInformation();
- $docker = $this->getBuildInfo();
- $app = $this->getAppInfo();
- $user = $this->getUserInfo();
-
- return (string) view('partials.debug-table', ['system' => $system, 'docker' => $docker, 'app' => $app, 'user' => $user]);
- }
-
- private function getSystemInformation(): array
- {
- $maxFileSize = Steam::phpBytes(ini_get('upload_max_filesize'));
- $maxPostSize = Steam::phpBytes(ini_get('post_max_size'));
- $drivers = DB::availableDrivers();
- $currentDriver = DB::getDriverName();
-
- return [
- 'php_version' => PHP_VERSION,
- 'php_os' => PHP_OS,
- 'build_time' => config('firefly.build_time'),
- 'build_time_nice' => Carbon::parse(config('firefly.build_time'), 'Europe/Amsterdam')->setTimezone('Europe/Amsterdam')->format('Y-m-d H:i:s e'),
- 'uname' => php_uname('m'),
- 'interface' => PHP_SAPI,
- 'bits' => PHP_INT_SIZE * 8,
- 'bcscale' => bcscale(),
- 'display_errors' => ini_get('display_errors'),
- 'error_reporting' => $this->errorReporting((int) ini_get('error_reporting')),
- 'upload_size' => min($maxFileSize, $maxPostSize),
- 'all_drivers' => $drivers,
- 'current_driver' => $currentDriver,
- ];
- }
-
- private function getBuildInfo(): array
- {
- $return = [
- 'is_docker' => env('IS_DOCKER', false), // @phpstan-ignore-line
- 'build' => '(unknown)',
- 'build_date' => '(unknown)',
- 'base_build' => '(unknown)',
- 'base_build_date' => '(unknown)',
- ];
-
- try {
- if (file_exists('/var/www/counter-main.txt')) {
- $return['build'] = trim(file_get_contents('/var/www/counter-main.txt'));
- Log::debug(sprintf('build is now "%s"', $return['build']));
- }
- } catch (Exception $e) {
- Log::debug('Could not check build counter, but thats ok.');
- Log::warning($e->getMessage());
- }
-
- try {
- if (file_exists('/var/www/build-date-main.txt')) {
- $return['build_date'] = trim(file_get_contents('/var/www/build-date-main.txt'));
- }
- } catch (Exception $e) {
- Log::debug('Could not check build date, but thats ok.');
- Log::warning($e->getMessage());
- }
- if ('' !== (string) env('BASE_IMAGE_BUILD')) { // @phpstan-ignore-line
- $return['base_build'] = env('BASE_IMAGE_BUILD'); // @phpstan-ignore-line
- }
- if ('' !== (string) env('BASE_IMAGE_DATE')) { // @phpstan-ignore-line
- $return['base_build_date'] = env('BASE_IMAGE_DATE'); // @phpstan-ignore-line
- }
-
- return $return;
- }
-
- private function getAppInfo(): array
- {
- $userGuard = config('auth.defaults.guard');
-
- $config = FireflyConfig::get('last_rt_job', 0);
- $lastTime = (int) $config->data;
- $lastCronjob = 'never';
- $lastCronjobAgo = 'never';
- if ($lastTime > 0) {
- $carbon = Carbon::createFromTimestamp($lastTime);
- $lastCronjob = $carbon->format('Y-m-d H:i:s');
- $lastCronjobAgo = $carbon->locale('en')->diffForHumans(); // @phpstan-ignore-line
- }
-
- return [
- 'debug' => var_export(config('app.debug'), true),
- 'audit_log_channel' => envNonEmpty('AUDIT_LOG_CHANNEL', '(empty)'),
- 'default_language' => (string) config('firefly.default_language'),
- 'default_locale' => (string) config('firefly.default_locale'),
- 'remote_header' => 'remote_user_guard' === $userGuard ? config('auth.guard_header') : 'N/A',
- 'remote_mail_header' => 'remote_user_guard' === $userGuard ? config('auth.guard_email') : 'N/A',
- 'stateful_domains' => implode(', ', config('sanctum.stateful')),
-
- // the dates for the cron job are based on the recurring cron job's times.
- // any of the cron jobs will do, they always run at the same time.
- // but this job is the oldest, so the biggest chance it ran once
-
- 'last_cronjob' => $lastCronjob,
- 'last_cronjob_ago' => $lastCronjobAgo,
- ];
- }
-
- private function getUserInfo(): array
- {
- $userFlags = $this->getUserFlags();
-
- // user info
- $userAgent = request()->header('user-agent');
-
- // set languages, see what happens:
- $original = setlocale(LC_ALL, '0');
- $localeAttempts = [];
- $parts = Steam::getLocaleArray(Steam::getLocale());
- foreach ($parts as $code) {
- $code = trim($code);
- Log::debug(sprintf('Trying to set %s', $code));
- $result = setlocale(LC_ALL, $code);
- $localeAttempts[$code] = $result === $code;
- }
- setlocale(LC_ALL, (string) $original);
-
- return [
- 'user_id' => auth()->user()->id,
- 'user_count' => User::count(),
- 'user_flags' => $userFlags,
- 'user_agent' => $userAgent,
- 'primary' => Amount::getPrimaryCurrency(),
- 'convert_to_primary' => Amount::convertToPrimary(),
- 'locale_attempts' => $localeAttempts,
- 'locale' => Steam::getLocale(),
- 'language' => Steam::getLanguage(),
- 'view_range' => Preferences::get('viewRange', '1M')->data,
- ];
- }
-
- private function getUserFlags(): string
- {
- $flags = [];
-
- /** @var User $user */
- $user = auth()->user();
-
- // has liabilities
- if ($user->accounts()->accountTypeIn([AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value])->count() > 0) {
- $flags[] = '<span title="Has liabilities">:credit_card:</span>';
- }
-
- // has piggies
- $repository = app(PiggyBankRepositoryInterface::class);
- $repository->setUser($user);
-
- if ($repository->getPiggyBanks()->count() > 0) {
- $flags[] = '<span title="Has piggy banks">:pig:</span>';
- }
-
- // has stored reconciliations
- $type = TransactionType::whereType(TransactionTypeEnum::RECONCILIATION->value)->first();
- if ($user->transactionJournals()->where('transaction_type_id', $type->id)->count() > 0) {
- $flags[] = '<span title="Has reconciled">:ledger:</span>';
- }
-
- // has used importer?
-
- // has rules
- if ($user->rules()->count() > 0) {
- $flags[] = '<span title="Has rules">:wrench:</span>';
- }
-
- // has recurring transactions
- if ($user->recurrences()->count() > 0) {
- $flags[] = '<span title="Has recurring transactions">:clock130:</span>';
- }
-
- // has groups
- if ($user->objectGroups()->count() > 0) {
- $flags[] = '<span title="Has object groups">:bookmark_tabs:</span>';
- }
-
- // uses bills
- if ($user->bills()->count() > 0) {
- $flags[] = '<span title="Has subscriptions">:email:</span>';
- }
-
- return implode(' ', $flags);
- }
-
public function routes(Request $request): never
{
if (!auth()->user()->hasRole('owner')) {
@@ -456,6 +267,100 @@ class DebugController extends Controller
exit;
}
+ /**
+ * Flash all types of messages.
+ */
+ public function testFlash(Request $request): Redirector|RedirectResponse
+ {
+ $request->session()->flash('success', 'This is a success message.');
+ $request->session()->flash('info', 'This is an info message.');
+ $request->session()->flash('warning', 'This is a warning.');
+ $request->session()->flash('error', 'This is an error!');
+
+ return redirect(route('home'));
+ }
+
+ private function generateTable(): string
+ {
+ // system information:
+ $system = $this->getSystemInformation();
+ $docker = $this->getBuildInfo();
+ $app = $this->getAppInfo();
+ $user = $this->getUserInfo();
+
+ return (string) view('partials.debug-table', ['system' => $system, 'docker' => $docker, 'app' => $app, 'user' => $user]);
+ }
+
+ private function getAppInfo(): array
+ {
+ $userGuard = config('auth.defaults.guard');
+
+ $config = FireflyConfig::get('last_rt_job', 0);
+ $lastTime = (int) $config->data;
+ $lastCronjob = 'never';
+ $lastCronjobAgo = 'never';
+ if ($lastTime > 0) {
+ $carbon = Carbon::createFromTimestamp($lastTime);
+ $lastCronjob = $carbon->format('Y-m-d H:i:s');
+ $lastCronjobAgo = $carbon->locale('en')->diffForHumans(); // @phpstan-ignore-line
+ }
+
+ return [
+ 'debug' => var_export(config('app.debug'), true),
+ 'audit_log_channel' => envNonEmpty('AUDIT_LOG_CHANNEL', '(empty)'),
+ 'default_language' => (string) config('firefly.default_language'),
+ 'default_locale' => (string) config('firefly.default_locale'),
+ 'remote_header' => 'remote_user_guard' === $userGuard ? config('auth.guard_header') : 'N/A',
+ 'remote_mail_header' => 'remote_user_guard' === $userGuard ? config('auth.guard_email') : 'N/A',
+ 'stateful_domains' => implode(', ', config('sanctum.stateful')),
+
+ // the dates for the cron job are based on the recurring cron job's times.
+ // any of the cron jobs will do, they always run at the same time.
+ // but this job is the oldest, so the biggest chance it ran once
+
+ 'last_cronjob' => $lastCronjob,
+ 'last_cronjob_ago' => $lastCronjobAgo,
+ ];
+ }
+
+ private function getBuildInfo(): array
+ {
+ $return = [
+ 'is_docker' => env('IS_DOCKER', false), // @phpstan-ignore-line
+ 'build' => '(unknown)',
+ 'build_date' => '(unknown)',
+ 'base_build' => '(unknown)',
+ 'base_build_date' => '(unknown)',
+ ];
+
+ try {
+ if (file_exists('/var/www/counter-main.txt')) {
+ $return['build'] = trim(file_get_contents('/var/www/counter-main.txt'));
+ Log::debug(sprintf('build is now "%s"', $return['build']));
+ }
+ } catch (Exception $e) {
+ Log::debug('Could not check build counter, but thats ok.');
+ Log::warning($e->getMessage());
+ }
+
+ try {
+ if (file_exists('/var/www/build-date-main.txt')) {
+ $return['build_date'] = trim(file_get_contents('/var/www/build-date-main.txt'));
+ }
+ } catch (Exception $e) {
+ Log::debug('Could not check build date, but thats ok.');
+ Log::warning($e->getMessage());
+ }
+ if ('' !== (string) env('BASE_IMAGE_BUILD')) { // @phpstan-ignore-line
+ $return['base_build'] = env('BASE_IMAGE_BUILD'); // @phpstan-ignore-line
+ }
+ if ('' !== (string) env('BASE_IMAGE_DATE')) { // @phpstan-ignore-line
+ $return['base_build_date'] = env('BASE_IMAGE_DATE'); // @phpstan-ignore-line
+ }
+
+ return $return;
+ }
+
private function getParameter(string $name): string
{
switch ($name) {
@@ -552,16 +457,111 @@ class DebugController extends Controller
}
}
- /**
- * Flash all types of messages.
- */
- public function testFlash(Request $request): Redirector|RedirectResponse
+ private function getSystemInformation(): array
{
- $request->session()->flash('success', 'This is a success message.');
- $request->session()->flash('info', 'This is an info message.');
- $request->session()->flash('warning', 'This is a warning.');
- $request->session()->flash('error', 'This is an error!');
+ $maxFileSize = Steam::phpBytes(ini_get('upload_max_filesize'));
+ $maxPostSize = Steam::phpBytes(ini_get('post_max_size'));
+ $drivers = DB::availableDrivers();
+ $currentDriver = DB::getDriverName();
- return redirect(route('home'));
+ return [
+ 'php_version' => PHP_VERSION,
+ 'php_os' => PHP_OS,
+ 'build_time' => config('firefly.build_time'),
+ 'build_time_nice' => Carbon::parse(config('firefly.build_time'), 'Europe/Amsterdam')->setTimezone('Europe/Amsterdam')->format('Y-m-d H:i:s e'),
+ 'uname' => php_uname('m'),
+ 'interface' => PHP_SAPI,
+ 'bits' => PHP_INT_SIZE * 8,
+ 'bcscale' => bcscale(),
+ 'display_errors' => ini_get('display_errors'),
+ 'error_reporting' => $this->errorReporting((int) ini_get('error_reporting')),
+ 'upload_size' => min($maxFileSize, $maxPostSize),
+ 'all_drivers' => $drivers,
+ 'current_driver' => $currentDriver,
+ ];
+ }
+
+ private function getUserFlags(): string
+ {
+ $flags = [];
+
+ /** @var User $user */
+ $user = auth()->user();
+
+ // has liabilities
+ if ($user->accounts()->accountTypeIn([AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value])->count() > 0) {
+ $flags[] = '<span title="Has liabilities">:credit_card:</span>';
+ }
+
+ // has piggies
+ $repository = app(PiggyBankRepositoryInterface::class);
+ $repository->setUser($user);
+
+ if ($repository->getPiggyBanks()->count() > 0) {
+ $flags[] = '<span title="Has piggy banks">:pig:</span>';
+ }
+
+ // has stored reconciliations
+ $type = TransactionType::whereType(TransactionTypeEnum::RECONCILIATION->value)->first();
+ if ($user->transactionJournals()->where('transaction_type_id', $type->id)->count() > 0) {
+ $flags[] = '<span title="Has reconciled">:ledger:</span>';
+ }
+
+ // has used importer?
+
+ // has rules
+ if ($user->rules()->count() > 0) {
+ $flags[] = '<span title="Has rules">:wrench:</span>';
+ }
+
+ // has recurring transactions
+ if ($user->recurrences()->count() > 0) {
+ $flags[] = '<span title="Has recurring transactions">:clock130:</span>';
+ }
+
+ // has groups
+ if ($user->objectGroups()->count() > 0) {
+ $flags[] = '<span title="Has object groups">:bookmark_tabs:</span>';
+ }
+
+ // uses bills
+ if ($user->bills()->count() > 0) {
+ $flags[] = '<span title="Has subscriptions">:email:</span>';
+ }
+
+ return implode(' ', $flags);
+ }
+
+ private function getUserInfo(): array
+ {
+ $userFlags = $this->getUserFlags();
+
+ // user info
+ $userAgent = request()->header('user-agent');
+
+ // set languages, see what happens:
+ $original = setlocale(LC_ALL, '0');
+ $localeAttempts = [];
+ $parts = Steam::getLocaleArray(Steam::getLocale());
+ foreach ($parts as $code) {
+ $code = trim($code);
+ Log::debug(sprintf('Trying to set %s', $code));
+ $result = setlocale(LC_ALL, $code);
+ $localeAttempts[$code] = $result === $code;
+ }
+ setlocale(LC_ALL, (string) $original);
+
+ return [
+ 'user_id' => auth()->user()->id,
+ 'user_count' => User::count(),
+ 'user_flags' => $userFlags,
+ 'user_agent' => $userAgent,
+ 'primary' => Amount::getPrimaryCurrency(),
+ 'convert_to_primary' => Amount::convertToPrimary(),
+ 'locale_attempts' => $localeAttempts,
+ 'locale' => Steam::getLocale(),
+ 'language' => Steam::getLanguage(),
+ 'view_range' => Preferences::get('viewRange', '1M')->data,
+ ];
}
}
diff --git a/app/Http/Controllers/Json/ReconcileController.php b/app/Http/Controllers/Json/ReconcileController.php
index 5268a6e7dd..14d2ce460b 100644
--- a/app/Http/Controllers/Json/ReconcileController.php
+++ b/app/Http/Controllers/Json/ReconcileController.php
@@ -162,37 +162,6 @@ class ReconcileController extends Controller
return response()->json($return);
}
- private function processJournal(Account $account, TransactionCurrency $currency, array $journal, string $amount): string
- {
- $toAdd = '0';
- Log::debug(sprintf('User submitted %s #%d: "%s"', $journal['transaction_type_type'], $journal['transaction_journal_id'], $journal['description']));
-
- // not much magic below we need to cover using tests.
-
- if ($account->id === $journal['source_account_id']) {
- if ($currency->id === $journal['currency_id']) {
- $toAdd = $journal['amount'];
- }
- if (null !== $journal['foreign_currency_id'] && $journal['foreign_currency_id'] === $currency->id) {
- $toAdd = $journal['foreign_amount'];
- }
- }
- if ($account->id === $journal['destination_account_id']) {
- if ($currency->id === $journal['currency_id']) {
- $toAdd = bcmul((string) $journal['amount'], '-1');
- }
- if (null !== $journal['foreign_currency_id'] && $journal['foreign_currency_id'] === $currency->id) {
- $toAdd = bcmul((string) $journal['foreign_amount'], '-1');
- }
- }
-
- Log::debug(sprintf('Going to add %s to %s', $toAdd, $amount));
- $amount = bcadd($amount, (string) $toAdd);
- Log::debug(sprintf('Result is %s', $amount));
-
- return $amount;
- }
-
/**
* Returns a list of transactions in a modal.
*
@@ -278,6 +247,37 @@ class ReconcileController extends Controller
return response()->json(['html' => $html, 'startBalance' => $startBalance, 'endBalance' => $endBalance]);
}
+ private function processJournal(Account $account, TransactionCurrency $currency, array $journal, string $amount): string
+ {
+ $toAdd = '0';
+ Log::debug(sprintf('User submitted %s #%d: "%s"', $journal['transaction_type_type'], $journal['transaction_journal_id'], $journal['description']));
+
+ // not much magic below we need to cover using tests.
+
+ if ($account->id === $journal['source_account_id']) {
+ if ($currency->id === $journal['currency_id']) {
+ $toAdd = $journal['amount'];
+ }
+ if (null !== $journal['foreign_currency_id'] && $journal['foreign_currency_id'] === $currency->id) {
+ $toAdd = $journal['foreign_amount'];
+ }
+ }
+ if ($account->id === $journal['destination_account_id']) {
+ if ($currency->id === $journal['currency_id']) {
+ $toAdd = bcmul((string) $journal['amount'], '-1');
+ }
+ if (null !== $journal['foreign_currency_id'] && $journal['foreign_currency_id'] === $currency->id) {
+ $toAdd = bcmul((string) $journal['foreign_amount'], '-1');
+ }
+ }
+
+ Log::debug(sprintf('Going to add %s to %s', $toAdd, $amount));
+ $amount = bcadd($amount, (string) $toAdd);
+ Log::debug(sprintf('Result is %s', $amount));
+
+ return $amount;
+ }
+
/**
* "fix" amounts to make it easier on the reconciliation overview:
*/
diff --git a/app/Http/Controllers/PiggyBank/EditController.php b/app/Http/Controllers/PiggyBank/EditController.php
index 4d80f1e53a..1b20650cd8 100644
--- a/app/Http/Controllers/PiggyBank/EditController.php
+++ b/app/Http/Controllers/PiggyBank/EditController.php
@@ -63,14 +63,6 @@ class EditController extends Controller
});
}
- public function resetHistory(PiggyBank $piggyBank): RedirectResponse
- {
- $this->piggyRepos->resetHistory($piggyBank);
- session()->flash('success', (string) trans('firefly.piggy_history_reset'));
-
- return redirect(route('piggy-banks.show', [$piggyBank->id]));
- }
-
/**
* Edit a piggy bank.
*
@@ -117,6 +109,14 @@ class EditController extends Controller
]);
}
+ public function resetHistory(PiggyBank $piggyBank): RedirectResponse
+ {
+ $this->piggyRepos->resetHistory($piggyBank);
+ session()->flash('success', (string) trans('firefly.piggy_history_reset'));
+
+ return redirect(route('piggy-banks.show', [$piggyBank->id]));
+ }
+
/**
* Update a piggy bank.
*/
diff --git a/app/Http/Controllers/PiggyBank/IndexController.php b/app/Http/Controllers/PiggyBank/IndexController.php
index 0c12201142..53637e1f20 100644
--- a/app/Http/Controllers/PiggyBank/IndexController.php
+++ b/app/Http/Controllers/PiggyBank/IndexController.php
@@ -102,36 +102,22 @@ class IndexController extends Controller
return view('piggy-banks.index', ['piggyBanks' => $piggyBanks, 'accounts' => $accounts]);
}
- private function groupPiggyBanks(Collection $collection): array
+ /**
+ * Set the order of a piggy bank.
+ */
+ public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse
{
- /** @var PiggyBankTransformer $transformer */
- $transformer = app(PiggyBankTransformer::class);
- $transformer->setParameters(new ParameterBag());
- $piggyBanks = [];
-
- // enrich
- /** @var User $admin */
- $admin = auth()->user();
- $enrichment = new PiggyBankEnrichment();
- $enrichment->setUser($admin);
- $collection = $enrichment->enrich($collection);
-
- /** @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;
+ $objectGroupTitle = (string) $request->get('objectGroupTitle');
+ $newOrder = (int) $request->get('order');
+ $this->piggyRepos->setOrder($piggyBank, $newOrder);
+ if ('' !== $objectGroupTitle) {
+ $this->piggyRepos->setObjectGroup($piggyBank, $objectGroupTitle);
+ }
+ if ('' === $objectGroupTitle) {
+ $this->piggyRepos->removeObjectGroup($piggyBank);
}
- return $piggyBanks;
+ return response()->json(['data' => 'OK']);
}
private function collectAccounts(Collection $collection): array
@@ -178,30 +164,36 @@ class IndexController extends Controller
return $return;
}
- private function mergeAccountsAndPiggies(array $piggyBanks, array $accounts): array
+ private function groupPiggyBanks(Collection $collection): array
{
- /** @var array $group */
- foreach ($piggyBanks as $group) {
- /** @var array $piggyBank */
- 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['account_id'];
- if (array_key_exists($accountId, $accounts)) {
- $accounts[$accountId]['left'] = bcsub((string) $accounts[$accountId]['left'], (string) $piggyAccount['current_amount']);
- $accounts[$accountId]['saved'] = bcadd((string) $accounts[$accountId]['saved'], (string) $piggyAccount['current_amount']);
- $accounts[$accountId]['target'] = bcadd((string) $accounts[$accountId]['target'], (string) $piggyBank['target_amount']);
- $accounts[$accountId]['to_save'] = bcadd((string) $accounts[$accountId]['to_save'], bcsub(
- (string) $piggyBank['target_amount'],
- (string) $piggyAccount['current_amount']
- ));
- }
- }
- }
+ /** @var PiggyBankTransformer $transformer */
+ $transformer = app(PiggyBankTransformer::class);
+ $transformer->setParameters(new ParameterBag());
+ $piggyBanks = [];
+
+ // enrich
+ /** @var User $admin */
+ $admin = auth()->user();
+ $enrichment = new PiggyBankEnrichment();
+ $enrichment->setUser($admin);
+ $collection = $enrichment->enrich($collection);
+
+ /** @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 $accounts;
+ return $piggyBanks;
}
private function makeSums(array $piggyBanks): array
@@ -239,21 +231,29 @@ class IndexController extends Controller
return $piggyBanks;
}
- /**
- * Set the order of a piggy bank.
- */
- public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse
+ private function mergeAccountsAndPiggies(array $piggyBanks, array $accounts): array
{
- $objectGroupTitle = (string) $request->get('objectGroupTitle');
- $newOrder = (int) $request->get('order');
- $this->piggyRepos->setOrder($piggyBank, $newOrder);
- if ('' !== $objectGroupTitle) {
- $this->piggyRepos->setObjectGroup($piggyBank, $objectGroupTitle);
- }
- if ('' === $objectGroupTitle) {
- $this->piggyRepos->removeObjectGroup($piggyBank);
+ /** @var array $group */
+ foreach ($piggyBanks as $group) {
+ /** @var array $piggyBank */
+ 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['account_id'];
+ if (array_key_exists($accountId, $accounts)) {
+ $accounts[$accountId]['left'] = bcsub((string) $accounts[$accountId]['left'], (string) $piggyAccount['current_amount']);
+ $accounts[$accountId]['saved'] = bcadd((string) $accounts[$accountId]['saved'], (string) $piggyAccount['current_amount']);
+ $accounts[$accountId]['target'] = bcadd((string) $accounts[$accountId]['target'], (string) $piggyBank['target_amount']);
+ $accounts[$accountId]['to_save'] = bcadd((string) $accounts[$accountId]['to_save'], bcsub(
+ (string) $piggyBank['target_amount'],
+ (string) $piggyAccount['current_amount']
+ ));
+ }
+ }
+ }
}
- return response()->json(['data' => 'OK']);
+ return $accounts;
}
}
diff --git a/app/Http/Controllers/Profile/MfaController.php b/app/Http/Controllers/Profile/MfaController.php
index b5a71e0adc..ac491d3a63 100644
--- a/app/Http/Controllers/Profile/MfaController.php
+++ b/app/Http/Controllers/Profile/MfaController.php
@@ -274,6 +274,21 @@ class MfaController extends Controller
return redirect(route('profile.mfa.backup-codes'));
}
+ public function index(): Factory|RedirectResponse|View
+ {
+ if (!$this->internalAuth) {
+ request()->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
+
+ return redirect(route('profile.index'));
+ }
+
+ $subTitle = (string) trans('firefly.mfa_index_title');
+ $subTitleIcon = 'fa-calculator';
+ $enabledMFA = null !== auth()->user()->mfa_secret;
+
+ return view('profile.mfa.index')->with(['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'enabledMFA' => $enabledMFA]);
+ }
+
/**
* TODO duplicate code.
*
@@ -309,19 +324,4 @@ class MfaController extends Controller
}
Preferences::set('mfa_history', $newHistory);
}
-
- public function index(): Factory|RedirectResponse|View
- {
- if (!$this->internalAuth) {
- request()->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
-
- return redirect(route('profile.index'));
- }
-
- $subTitle = (string) trans('firefly.mfa_index_title');
- $subTitleIcon = 'fa-calculator';
- $enabledMFA = null !== auth()->user()->mfa_secret;
-
- return view('profile.mfa.index')->with(['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'enabledMFA' => $enabledMFA]);
- }
}
diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php
index 9bea42d046..4271ca5efe 100644
--- a/app/Http/Controllers/ProfileController.php
+++ b/app/Http/Controllers/ProfileController.php
@@ -85,6 +85,45 @@ class ProfileController extends Controller
$this->middleware(IsDemoUser::class)->except(['index']);
}
+ /**
+ * Change your email address.
+ */
+ public function changeEmail(Request $request): Factory|RedirectResponse|View
+ {
+ if (!$this->internalAuth) {
+ $request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
+
+ return redirect(route('profile.index'));
+ }
+
+ $title = auth()->user()->email;
+ $email = auth()->user()->email;
+ $subTitle = (string) trans('firefly.change_your_email');
+ $subTitleIcon = 'fa-envelope';
+
+ return view('profile.change-email', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'email' => $email]);
+ }
+
+ /**
+ * Change your password.
+ *
+ * @return Factory|Redirector|RedirectResponse|View
+ */
+ public function changePassword(Request $request): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse
+ {
+ if (!$this->internalAuth) {
+ $request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
+
+ return redirect(route('profile.index'));
+ }
+
+ $title = auth()->user()->email;
+ $subTitle = (string) trans('firefly.change_your_password');
+ $subTitleIcon = 'fa-key';
+
+ return view('profile.change-password', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]);
+ }
+
/**
* Screen to confirm email change.
*
@@ -242,25 +281,6 @@ class ProfileController extends Controller
return redirect(route('index'));
}
- /**
- * Change your email address.
- */
- public function changeEmail(Request $request): Factory|RedirectResponse|View
- {
- if (!$this->internalAuth) {
- $request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
-
- return redirect(route('profile.index'));
- }
-
- $title = auth()->user()->email;
- $email = auth()->user()->email;
- $subTitle = (string) trans('firefly.change_your_email');
- $subTitleIcon = 'fa-envelope';
-
- return view('profile.change-email', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'email' => $email]);
- }
-
/**
* Submit change password form.
*/
@@ -293,26 +313,6 @@ class ProfileController extends Controller
return redirect(route('profile.index'));
}
- /**
- * Change your password.
- *
- * @return Factory|Redirector|RedirectResponse|View
- */
- public function changePassword(Request $request): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse
- {
- if (!$this->internalAuth) {
- $request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
-
- return redirect(route('profile.index'));
- }
-
- $title = auth()->user()->email;
- $subTitle = (string) trans('firefly.change_your_password');
- $subTitleIcon = 'fa-key';
-
- return view('profile.change-password', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]);
- }
-
/**
* Submit delete account.
*/
diff --git a/app/Http/Controllers/Report/DoubleController.php b/app/Http/Controllers/Report/DoubleController.php
index 073f7fb41b..8cc6d652b6 100644
--- a/app/Http/Controllers/Report/DoubleController.php
+++ b/app/Http/Controllers/Report/DoubleController.php
@@ -278,24 +278,6 @@ class DoubleController extends Controller
return view('reports.double.partials.accounts', ['sums' => $sums, 'report' => $report]);
}
- /**
- * TODO this method is duplicated.
- */
- private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
- {
- /** @var Account $account */
- foreach ($accounts as $account) {
- if ($account->name === $name && $account->id !== $id) {
- return $account->name;
- }
- if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
- return $account->iban;
- }
- }
-
- return $name;
- }
-
/**
* @return Factory|View
*/
@@ -486,4 +468,22 @@ class DoubleController extends Controller
return $result;
}
+
+ /**
+ * TODO this method is duplicated.
+ */
+ private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
+ {
+ /** @var Account $account */
+ foreach ($accounts as $account) {
+ if ($account->name === $name && $account->id !== $id) {
+ return $account->name;
+ }
+ if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
+ return $account->iban;
+ }
+ }
+
+ return $name;
+ }
}
diff --git a/app/Http/Controllers/Rule/EditController.php b/app/Http/Controllers/Rule/EditController.php
index 2f0ce2402c..d06faa9e6e 100644
--- a/app/Http/Controllers/Rule/EditController.php
+++ b/app/Http/Controllers/Rule/EditController.php
@@ -151,6 +151,34 @@ class EditController extends Controller
]);
}
+ /**
+ * Update the rule.
+ *
+ * @return Redirector|RedirectResponse
+ */
+ public function update(RuleFormRequest $request, Rule $rule)
+ {
+ $data = $request->getRuleData();
+
+ $this->ruleRepos->update($rule, $data);
+
+ session()->flash('success', (string) trans('firefly.updated_rule', ['title' => $rule->title]));
+ Preferences::mark();
+ $redirect = redirect($this->getPreviousUrl('rules.edit.url'));
+
+ if (true === $data['run_after_form']) {
+ return redirect(route('rules.select-transactions', [$rule->id]));
+ }
+
+ if (1 === (int) $request->get('return_to_edit')) {
+ session()->put('rules.edit.fromUpdate', true);
+
+ $redirect = redirect(route('rules.edit', [$rule->id]))->withInput(['return_to_edit' => 1]);
+ }
+
+ return $redirect;
+ }
+
/**
* @throws FireflyException
*/
@@ -189,32 +217,4 @@ class EditController extends Controller
return $renderedEntries;
}
-
- /**
- * Update the rule.
- *
- * @return Redirector|RedirectResponse
- */
- public function update(RuleFormRequest $request, Rule $rule)
- {
- $data = $request->getRuleData();
-
- $this->ruleRepos->update($rule, $data);
-
- session()->flash('success', (string) trans('firefly.updated_rule', ['title' => $rule->title]));
- Preferences::mark();
- $redirect = redirect($this->getPreviousUrl('rules.edit.url'));
-
- if (true === $data['run_after_form']) {
- return redirect(route('rules.select-transactions', [$rule->id]));
- }
-
- if (1 === (int) $request->get('return_to_edit')) {
- session()->put('rules.edit.fromUpdate', true);
-
- $redirect = redirect(route('rules.edit', [$rule->id]))->withInput(['return_to_edit' => 1]);
- }
-
- return $redirect;
- }
}
diff --git a/app/Http/Controllers/System/InstallController.php b/app/Http/Controllers/System/InstallController.php
index defcb6b4a4..da5f92a183 100644
--- a/app/Http/Controllers/System/InstallController.php
+++ b/app/Http/Controllers/System/InstallController.php
@@ -89,6 +89,23 @@ class InstallController extends Controller
return view('install.index');
}
+ /**
+ * Create specific RSA keys.
+ */
+ public function keys(): void
+ {
+ $key = RSA::createKey(4096);
+
+ [$publicKey, $privateKey] = [Passport::keyPath('oauth-public.key'), Passport::keyPath('oauth-private.key')];
+
+ if (file_exists($publicKey) || file_exists($privateKey)) {
+ return;
+ }
+
+ file_put_contents($publicKey, (string) $key->getPublicKey());
+ file_put_contents($privateKey, $key->toString('PKCS1'));
+ }
+
public function runCommand(Request $request): JsonResponse
{
$requestIndex = (int) $request->get('index');
@@ -149,21 +166,4 @@ class InstallController extends Controller
return true;
}
-
- /**
- * Create specific RSA keys.
- */
- public function keys(): void
- {
- $key = RSA::createKey(4096);
-
- [$publicKey, $privateKey] = [Passport::keyPath('oauth-public.key'), Passport::keyPath('oauth-private.key')];
-
- if (file_exists($publicKey) || file_exists($privateKey)) {
- return;
- }
-
- file_put_contents($publicKey, (string) $key->getPublicKey());
- file_put_contents($privateKey, $key->toString('PKCS1'));
- }
}
diff --git a/app/Http/Controllers/TagController.php b/app/Http/Controllers/TagController.php
index 6bc8cd7c80..a42c75c44b 100644
--- a/app/Http/Controllers/TagController.php
+++ b/app/Http/Controllers/TagController.php
@@ -113,6 +113,20 @@ class TagController extends Controller
return view('tags.delete', ['tag' => $tag, 'subTitle' => $subTitle]);
}
+ /**
+ * Destroy a tag.
+ */
+ public function destroy(Tag $tag): RedirectResponse
+ {
+ $tagName = $tag->tag;
+ $this->repository->destroy($tag);
+
+ session()->flash('success', (string) trans('firefly.deleted_tag', ['tag' => $tagName]));
+ Preferences::mark();
+
+ return redirect($this->getPreviousUrl('tags.delete.url'));
+ }
+
/**
* Edit a tag.
*
@@ -198,20 +212,6 @@ class TagController extends Controller
return redirect(route('tags.index'));
}
- /**
- * Destroy a tag.
- */
- public function destroy(Tag $tag): RedirectResponse
- {
- $tagName = $tag->tag;
- $this->repository->destroy($tag);
-
- session()->flash('success', (string) trans('firefly.deleted_tag', ['tag' => $tagName]));
- Preferences::mark();
-
- return redirect($this->getPreviousUrl('tags.delete.url'));
- }
-
/**
* Show a single tag.
*
diff --git a/app/Http/Controllers/Transaction/BulkController.php b/app/Http/Controllers/Transaction/BulkController.php
index 19625e2dec..8a0e955fd1 100644
--- a/app/Http/Controllers/Transaction/BulkController.php
+++ b/app/Http/Controllers/Transaction/BulkController.php
@@ -129,7 +129,6 @@ class BulkController extends Controller
event(new UpdatedSingleTransactionGroup($flags, $objects));
event(new WebhookMessagesRequestSending());
-
Preferences::mark();
$request->session()->flash('success', trans_choice('firefly.mass_edited_transactions_success', $count));
@@ -148,6 +147,17 @@ class BulkController extends Controller
return true;
}
+ private function updateJournalCategory(TransactionJournal $journal, bool $ignoreUpdate, string $category): bool
+ {
+ if ($ignoreUpdate) {
+ return false;
+ }
+ Log::debug(sprintf('Set budget to %s', $category));
+ $this->repository->updateCategory($journal, $category);
+
+ return true;
+ }
+
private function updateJournalTags(TransactionJournal $journal, string $action, array $tags): bool
{
if ('do_replace' === $action) {
@@ -162,15 +172,4 @@ class BulkController extends Controller
return true;
}
-
- private function updateJournalCategory(TransactionJournal $journal, bool $ignoreUpdate, string $category): bool
- {
- if ($ignoreUpdate) {
- return false;
- }
- Log::debug(sprintf('Set budget to %s', $category));
- $this->repository->updateCategory($journal, $category);
-
- return true;
- }
}
diff --git a/app/Http/Controllers/Transaction/ConvertController.php b/app/Http/Controllers/Transaction/ConvertController.php
index fea68500b2..67a988fffa 100644
--- a/app/Http/Controllers/Transaction/ConvertController.php
+++ b/app/Http/Controllers/Transaction/ConvertController.php
@@ -138,149 +138,6 @@ class ConvertController extends Controller
]);
}
- private function getValidDepositSources(): array
- {
- // make repositories
- $liabilityTypes = [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value];
- $accountList = $this->accountRepository->getActiveAccountsByType([
- AccountTypeEnum::REVENUE->value,
- AccountTypeEnum::CASH->value,
- AccountTypeEnum::LOAN->value,
- AccountTypeEnum::DEBT->value,
- AccountTypeEnum::MORTGAGE->value,
- ]);
- $grouped = [];
-
- // group accounts:
- /** @var Account $account */
- foreach ($accountList as $account) {
- $role = (string) $this->accountRepository->getMetaValue($account, 'account_role');
- $name = $account->name;
- if ('' === $role) {
- $role = 'no_account_type';
- }
-
- // maybe it's a liability thing:
- if (in_array($account->accountType->type, $liabilityTypes, true)) {
- $role = 'l_'.$account->accountType->type;
- }
- if (AccountTypeEnum::CASH->value === $account->accountType->type) {
- $role = 'cash_account';
- $name = sprintf('(%s)', trans('firefly.cash'));
- }
- if (AccountTypeEnum::REVENUE->value === $account->accountType->type) {
- $role = 'revenue_account';
- }
-
- $key = (string) trans('firefly.opt_group_'.$role);
- $grouped[$key][$account->id] = $name;
- }
-
- return $grouped;
- }
-
- private function getValidWithdrawalDests(): array
- {
- // make repositories
- $liabilityTypes = [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value];
- $accountList = $this->accountRepository->getActiveAccountsByType([
- AccountTypeEnum::EXPENSE->value,
- AccountTypeEnum::CASH->value,
- AccountTypeEnum::LOAN->value,
- AccountTypeEnum::DEBT->value,
- AccountTypeEnum::MORTGAGE->value,
- ]);
- $grouped = [];
-
- // group accounts:
- /** @var Account $account */
- foreach ($accountList as $account) {
- $role = (string) $this->accountRepository->getMetaValue($account, 'account_role');
- $name = $account->name;
- if ('' === $role) {
- $role = 'no_account_type';
- }
-
- // maybe it's a liability thing:
- if (in_array($account->accountType->type, $liabilityTypes, true)) {
- $role = 'l_'.$account->accountType->type;
- }
- if (AccountTypeEnum::CASH->value === $account->accountType->type) {
- $role = 'cash_account';
- $name = sprintf('(%s)', trans('firefly.cash'));
- }
- if (AccountTypeEnum::EXPENSE->value === $account->accountType->type) {
- $role = 'expense_account';
- }
-
- $key = (string) trans('firefly.opt_group_'.$role);
- $grouped[$key][$account->id] = $name;
- }
-
- return $grouped;
- }
-
- /**
- * @throws Exception
- */
- private function getLiabilities(): array
- {
- // make repositories
- $accountList = $this->accountRepository->getActiveAccountsByType([
- AccountTypeEnum::LOAN->value,
- AccountTypeEnum::DEBT->value,
- AccountTypeEnum::MORTGAGE->value,
- ]);
- $grouped = [];
-
- // group accounts:
- /** @var Account $account */
- foreach ($accountList as $account) {
- $date = today()->endOfDay();
- Log::debug(sprintf('getLiabilities: Call finalAccountBalance with date/time "%s"', $date->toIso8601String()));
- // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized.
- // $balance = Steam::finalAccountBalance($account, $date)['balance'];
- $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0';
- $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency;
- $role = sprintf('l_%s', $account->accountType->type);
- $key = (string) trans(sprintf('firefly.opt_group_%s', $role));
- $grouped[$key][$account->id] = sprintf('%s (%s)', $account->name, Amount::formatAnything($currency, $balance, false));
- }
-
- return $grouped;
- }
-
- /**
- * @throws Exception
- */
- private function getAssetAccounts(): array
- {
- // make repositories
- $accountList = $this->accountRepository->getActiveAccountsByType([AccountTypeEnum::ASSET->value]);
- $grouped = [];
-
- // group accounts:
- /** @var Account $account */
- foreach ($accountList as $account) {
- $date = today()->endOfDay();
- Log::debug(sprintf('getAssetAccounts: Call finalAccountBalance with date/time "%s"', $date->toIso8601String()));
- // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized.
- // $balance = Steam::finalAccountBalance($account, $date)['balance'];
- $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0';
-
- $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency;
- $role = (string) $this->accountRepository->getMetaValue($account, 'account_role');
- if ('' === $role) {
- $role = 'no_account_type';
- }
-
- $key = (string) trans(sprintf('firefly.opt_group_%s', $role));
- $grouped[$key][$account->id] = sprintf('%s (%s)', $account->name, Amount::formatAnything($currency, $balance, false));
- }
-
- return $grouped;
- }
-
/**
* Do the conversion.
*
@@ -313,7 +170,6 @@ class ConvertController extends Controller
event(new UpdatedSingleTransactionGroup($flags, $objects));
event(new WebhookMessagesRequestSending());
-
return redirect(route('transactions.show', [$group->id]));
}
@@ -404,4 +260,147 @@ class ConvertController extends Controller
return $journal;
}
+
+ /**
+ * @throws Exception
+ */
+ private function getAssetAccounts(): array
+ {
+ // make repositories
+ $accountList = $this->accountRepository->getActiveAccountsByType([AccountTypeEnum::ASSET->value]);
+ $grouped = [];
+
+ // group accounts:
+ /** @var Account $account */
+ foreach ($accountList as $account) {
+ $date = today()->endOfDay();
+ Log::debug(sprintf('getAssetAccounts: Call finalAccountBalance with date/time "%s"', $date->toIso8601String()));
+ // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized.
+ // $balance = Steam::finalAccountBalance($account, $date)['balance'];
+ $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0';
+
+ $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency;
+ $role = (string) $this->accountRepository->getMetaValue($account, 'account_role');
+ if ('' === $role) {
+ $role = 'no_account_type';
+ }
+
+ $key = (string) trans(sprintf('firefly.opt_group_%s', $role));
+ $grouped[$key][$account->id] = sprintf('%s (%s)', $account->name, Amount::formatAnything($currency, $balance, false));
+ }
+
+ return $grouped;
+ }
+
+ /**
+ * @throws Exception
+ */
+ private function getLiabilities(): array
+ {
+ // make repositories
+ $accountList = $this->accountRepository->getActiveAccountsByType([
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value,
+ ]);
+ $grouped = [];
+
+ // group accounts:
+ /** @var Account $account */
+ foreach ($accountList as $account) {
+ $date = today()->endOfDay();
+ Log::debug(sprintf('getLiabilities: Call finalAccountBalance with date/time "%s"', $date->toIso8601String()));
+ // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized.
+ // $balance = Steam::finalAccountBalance($account, $date)['balance'];
+ $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0';
+ $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency;
+ $role = sprintf('l_%s', $account->accountType->type);
+ $key = (string) trans(sprintf('firefly.opt_group_%s', $role));
+ $grouped[$key][$account->id] = sprintf('%s (%s)', $account->name, Amount::formatAnything($currency, $balance, false));
+ }
+
+ return $grouped;
+ }
+
+ private function getValidDepositSources(): array
+ {
+ // make repositories
+ $liabilityTypes = [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value];
+ $accountList = $this->accountRepository->getActiveAccountsByType([
+ AccountTypeEnum::REVENUE->value,
+ AccountTypeEnum::CASH->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value,
+ ]);
+ $grouped = [];
+
+ // group accounts:
+ /** @var Account $account */
+ foreach ($accountList as $account) {
+ $role = (string) $this->accountRepository->getMetaValue($account, 'account_role');
+ $name = $account->name;
+ if ('' === $role) {
+ $role = 'no_account_type';
+ }
+
+ // maybe it's a liability thing:
+ if (in_array($account->accountType->type, $liabilityTypes, true)) {
+ $role = 'l_'.$account->accountType->type;
+ }
+ if (AccountTypeEnum::CASH->value === $account->accountType->type) {
+ $role = 'cash_account';
+ $name = sprintf('(%s)', trans('firefly.cash'));
+ }
+ if (AccountTypeEnum::REVENUE->value === $account->accountType->type) {
+ $role = 'revenue_account';
+ }
+
+ $key = (string) trans('firefly.opt_group_'.$role);
+ $grouped[$key][$account->id] = $name;
+ }
+
+ return $grouped;
+ }
+
+ private function getValidWithdrawalDests(): array
+ {
+ // make repositories
+ $liabilityTypes = [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value];
+ $accountList = $this->accountRepository->getActiveAccountsByType([
+ AccountTypeEnum::EXPENSE->value,
+ AccountTypeEnum::CASH->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value,
+ AccountTypeEnum::MORTGAGE->value,
+ ]);
+ $grouped = [];
+
+ // group accounts:
+ /** @var Account $account */
+ foreach ($accountList as $account) {
+ $role = (string) $this->accountRepository->getMetaValue($account, 'account_role');
+ $name = $account->name;
+ if ('' === $role) {
+ $role = 'no_account_type';
+ }
+
+ // maybe it's a liability thing:
+ if (in_array($account->accountType->type, $liabilityTypes, true)) {
+ $role = 'l_'.$account->accountType->type;
+ }
+ if (AccountTypeEnum::CASH->value === $account->accountType->type) {
+ $role = 'cash_account';
+ $name = sprintf('(%s)', trans('firefly.cash'));
+ }
+ if (AccountTypeEnum::EXPENSE->value === $account->accountType->type) {
+ $role = 'expense_account';
+ }
+
+ $key = (string) trans('firefly.opt_group_'.$role);
+ $grouped[$key][$account->id] = $name;
+ }
+
+ return $grouped;
+ }
}
diff --git a/app/Http/Controllers/Transaction/DeleteController.php b/app/Http/Controllers/Transaction/DeleteController.php
index 076f66aaba..2ef1397d7d 100644
--- a/app/Http/Controllers/Transaction/DeleteController.php
+++ b/app/Http/Controllers/Transaction/DeleteController.php
@@ -52,7 +52,7 @@ class DeleteController extends Controller
// translations:
$this->middleware(function ($request, $next) {
- app('view')->share('title', (string)trans('firefly.transactions'));
+ app('view')->share('title', (string) trans('firefly.transactions'));
app('view')->share('mainTitleIcon', 'fa-exchange');
$this->repository = app(TransactionGroupRepositoryInterface::class);
@@ -64,7 +64,7 @@ class DeleteController extends Controller
/**
* Shows the form that allows a user to delete a transaction journal.
*/
- public function delete(TransactionGroup $group): Factory | Redirector | RedirectResponse | View
+ public function delete(TransactionGroup $group): Factory|Redirector|RedirectResponse|View
{
if (!$this->isEditableGroup($group)) {
return $this->redirectGroupToAccount($group);
@@ -72,12 +72,12 @@ class DeleteController extends Controller
Log::debug(sprintf('Start of delete view for group #%d', $group->id));
- $journal = $group->transactionJournals->first();
+ $journal = $group->transactionJournals->first();
if (null === $journal) {
throw new NotFoundHttpException();
}
$objectType = strtolower($journal->transaction_type_type ?? $journal->transactionType->type);
- $subTitle = (string)trans('firefly.delete_' . $objectType, ['description' => $group->title ?? $journal->description]);
+ $subTitle = (string) trans('firefly.delete_'.$objectType, ['description' => $group->title ?? $journal->description]);
$previous = Steam::getSafePreviousUrl();
// put previous url in session
Log::debug('Will try to remember previous URL');
@@ -95,19 +95,19 @@ class DeleteController extends Controller
/**
* Actually destroys the journal.
*/
- public function destroy(TransactionGroup $group): Redirector | RedirectResponse
+ public function destroy(TransactionGroup $group): Redirector|RedirectResponse
{
Log::debug(sprintf('Now in %s(#%d).', __METHOD__, $group->id));
if (!$this->isEditableGroup($group)) {
return $this->redirectGroupToAccount($group);
}
- $journal = $group->transactionJournals->first();
+ $journal = $group->transactionJournals->first();
if (null === $journal) {
throw new NotFoundHttpException();
}
$objectType = strtolower($journal->transaction_type_type ?? $journal->transactionType->type);
- session()->flash('success', (string)trans('firefly.deleted_' . strtolower($objectType), ['description' => $group->title ?? $journal->description]));
+ session()->flash('success', (string) trans('firefly.deleted_'.strtolower($objectType), ['description' => $group->title ?? $journal->description]));
$this->repository->destroy($group);
Preferences::mark();
diff --git a/app/Http/Controllers/Transaction/MassController.php b/app/Http/Controllers/Transaction/MassController.php
index 4d06375894..61cda0cd88 100644
--- a/app/Http/Controllers/Transaction/MassController.php
+++ b/app/Http/Controllers/Transaction/MassController.php
@@ -192,43 +192,6 @@ class MassController extends Controller
return redirect($this->getPreviousUrl('transactions.mass-edit.url'));
}
- /**
- * @throws FireflyException
- */
- private function updateJournal(int $journalId, MassEditJournalRequest $request): void
- {
- $journal = $this->repository->find($journalId);
- if (!$journal instanceof TransactionJournal) {
- throw new FireflyException(sprintf('Trying to edit non-existent or deleted journal #%d', $journalId));
- }
- $service = app(JournalUpdateService::class);
- // for each field, call the update service.
- $service->setTransactionJournal($journal);
-
- $data = [
- 'date' => $this->getDateFromRequest($request, $journal->id, 'date'),
- 'description' => $this->getStringFromRequest($request, $journal->id, 'description'),
- 'source_id' => $this->getIntFromRequest($request, $journal->id, 'source_id'),
- 'source_name' => $this->getStringFromRequest($request, $journal->id, 'source_name'),
- 'destination_id' => $this->getIntFromRequest($request, $journal->id, 'destination_id'),
- 'destination_name' => $this->getStringFromRequest($request, $journal->id, 'destination_name'),
- 'budget_id' => $this->getIntFromRequest($request, $journal->id, 'budget_id'),
- 'category_name' => $this->getStringFromRequest($request, $journal->id, 'category'),
- 'amount' => $this->getStringFromRequest($request, $journal->id, 'amount'),
- 'foreign_amount' => $this->getStringFromRequest($request, $journal->id, 'foreign_amount'),
- ];
- Log::debug(sprintf('Will update journal #%d with data.', $journal->id), $data);
-
- // call service to update.
- $service->setData($data);
- $service->update();
- $flags = new TransactionGroupEventFlags();
- $objects = TransactionGroupEventObjects::collectFromTransactionGroup($journal->transactionGroup);
- event(new UpdatedSingleTransactionGroup($flags, $objects));
- event(new WebhookMessagesRequestSending());
-
- }
-
private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): ?Carbon
{
$value = $request->get($key);
@@ -251,7 +214,7 @@ class MassController extends Controller
return $carbon;
}
- private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?string
+ private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?int
{
$value = $request->get($string);
if (!is_array($value)) {
@@ -261,10 +224,10 @@ class MassController extends Controller
return null;
}
- return (string) $value[$journalId];
+ return (int) $value[$journalId];
}
- private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?int
+ private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?string
{
$value = $request->get($string);
if (!is_array($value)) {
@@ -274,6 +237,42 @@ class MassController extends Controller
return null;
}
- return (int) $value[$journalId];
+ return (string) $value[$journalId];
+ }
+
+ /**
+ * @throws FireflyException
+ */
+ private function updateJournal(int $journalId, MassEditJournalRequest $request): void
+ {
+ $journal = $this->repository->find($journalId);
+ if (!$journal instanceof TransactionJournal) {
+ throw new FireflyException(sprintf('Trying to edit non-existent or deleted journal #%d', $journalId));
+ }
+ $service = app(JournalUpdateService::class);
+ // for each field, call the update service.
+ $service->setTransactionJournal($journal);
+
+ $data = [
+ 'date' => $this->getDateFromRequest($request, $journal->id, 'date'),
+ 'description' => $this->getStringFromRequest($request, $journal->id, 'description'),
+ 'source_id' => $this->getIntFromRequest($request, $journal->id, 'source_id'),
+ 'source_name' => $this->getStringFromRequest($request, $journal->id, 'source_name'),
+ 'destination_id' => $this->getIntFromRequest($request, $journal->id, 'destination_id'),
+ 'destination_name' => $this->getStringFromRequest($request, $journal->id, 'destination_name'),
+ 'budget_id' => $this->getIntFromRequest($request, $journal->id, 'budget_id'),
+ 'category_name' => $this->getStringFromRequest($request, $journal->id, 'category'),
+ 'amount' => $this->getStringFromRequest($request, $journal->id, 'amount'),
+ 'foreign_amount' => $this->getStringFromRequest($request, $journal->id, 'foreign_amount'),
+ ];
+ Log::debug(sprintf('Will update journal #%d with data.', $journal->id), $data);
+
+ // call service to update.
+ $service->setData($data);
+ $service->update();
+ $flags = new TransactionGroupEventFlags();
+ $objects = TransactionGroupEventObjects::collectFromTransactionGroup($journal->transactionGroup);
+ event(new UpdatedSingleTransactionGroup($flags, $objects));
+ event(new WebhookMessagesRequestSending());
}
}
diff --git a/app/Http/Controllers/Transaction/ShowController.php b/app/Http/Controllers/Transaction/ShowController.php
index 459c514923..c834f492a4 100644
--- a/app/Http/Controllers/Transaction/ShowController.php
+++ b/app/Http/Controllers/Transaction/ShowController.php
@@ -163,6 +163,31 @@ class ShowController extends Controller
]);
}
+ private function getAccounts(array $group): array
+ {
+ $accounts = ['source' => [], 'destination' => []];
+
+ foreach ($group['transactions'] as $transaction) {
+ $accounts['source'][] = [
+ 'type' => $transaction['source_account_type'],
+ 'id' => $transaction['source_account_id'],
+ 'name' => $transaction['source_account_name'],
+ 'iban' => $transaction['source_account_iban'],
+ ];
+ $accounts['destination'][] = [
+ 'type' => $transaction['destination_account_type'],
+ 'id' => $transaction['destination_account_id'],
+ 'name' => $transaction['destination_account_name'],
+ 'iban' => $transaction['destination_account_iban'],
+ ];
+ }
+
+ $accounts['source'] = array_unique($accounts['source'], SORT_REGULAR);
+ $accounts['destination'] = array_unique($accounts['destination'], SORT_REGULAR);
+
+ return $accounts;
+ }
+
private function getAmounts(array $group): array
{
$amounts = [];
@@ -202,29 +227,4 @@ class ShowController extends Controller
return $amounts;
}
-
- private function getAccounts(array $group): array
- {
- $accounts = ['source' => [], 'destination' => []];
-
- foreach ($group['transactions'] as $transaction) {
- $accounts['source'][] = [
- 'type' => $transaction['source_account_type'],
- 'id' => $transaction['source_account_id'],
- 'name' => $transaction['source_account_name'],
- 'iban' => $transaction['source_account_iban'],
- ];
- $accounts['destination'][] = [
- 'type' => $transaction['destination_account_type'],
- 'id' => $transaction['destination_account_id'],
- 'name' => $transaction['destination_account_name'],
- 'iban' => $transaction['destination_account_iban'],
- ];
- }
-
- $accounts['source'] = array_unique($accounts['source'], SORT_REGULAR);
- $accounts['destination'] = array_unique($accounts['destination'], SORT_REGULAR);
-
- return $accounts;
- }
}
diff --git a/app/Http/Middleware/Installer.php b/app/Http/Middleware/Installer.php
index 852c523c4c..dd5ef803df 100644
--- a/app/Http/Middleware/Installer.php
+++ b/app/Http/Middleware/Installer.php
@@ -78,6 +78,22 @@ class Installer
return $next($request);
}
+ /**
+ * Is access denied error.
+ */
+ protected function isAccessDenied(string $message): bool
+ {
+ return false !== stripos($message, 'Access denied');
+ }
+
+ /**
+ * Is no tables exist error.
+ */
+ protected function noTablesExist(string $message): bool
+ {
+ return false !== stripos($message, 'Base table or view not found');
+ }
+
/**
* Check if the tables are created and accounted for.
*
@@ -113,20 +129,4 @@ class Installer
return false;
}
-
- /**
- * Is access denied error.
- */
- protected function isAccessDenied(string $message): bool
- {
- return false !== stripos($message, 'Access denied');
- }
-
- /**
- * Is no tables exist error.
- */
- protected function noTablesExist(string $message): bool
- {
- return false !== stripos($message, 'Base table or view not found');
- }
}
diff --git a/app/Http/Middleware/InterestingMessage.php b/app/Http/Middleware/InterestingMessage.php
index a2a7bf8d2e..854c403f3f 100644
--- a/app/Http/Middleware/InterestingMessage.php
+++ b/app/Http/Middleware/InterestingMessage.php
@@ -82,10 +82,31 @@ class InterestingMessage
return $next($request);
}
- private function testing(): bool
+ private function accountMessage(Request $request): bool
{
- // ignore middleware in test environment.
- return 'testing' === config('app.env') || !auth()->check();
+ // get parameters from request.
+ $accountId = $request->get('account_id');
+ $message = $request->get('message');
+
+ return null !== $accountId && null !== $message;
+ }
+
+ private function billMessage(Request $request): bool
+ {
+ // get parameters from request.
+ $billId = $request->get('bill_id');
+ $message = $request->get('message');
+
+ return null !== $billId && null !== $message;
+ }
+
+ private function currencyMessage(Request $request): bool
+ {
+ // get parameters from request.
+ $code = $request->get('code');
+ $message = $request->get('message');
+
+ return null !== $code && null !== $message;
}
private function groupMessage(Request $request): bool
@@ -97,6 +118,85 @@ class InterestingMessage
return null !== $transactionGroupId && null !== $message;
}
+ private function handleAccountMessage(Request $request): void
+ {
+ // get parameters from request.
+ $accountId = $request->get('account_id');
+ $message = $request->get('message');
+
+ /** @var User $user */
+ $user = auth()->user();
+
+ /** @var null|Account $account */
+ $account = $user->accounts()->withTrashed()->find($accountId);
+
+ if (null === $account) {
+ return;
+ }
+ if ('deleted' === $message) {
+ session()->flash('success', (string) trans('firefly.account_deleted', ['name' => $account->name]));
+ }
+ if ('created' === $message) {
+ session()->flash('success', (string) trans('firefly.stored_new_account', ['name' => $account->name]));
+ }
+ if ('updated' === $message) {
+ session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name]));
+ }
+ }
+
+ private function handleBillMessage(Request $request): void
+ {
+ // get parameters from request.
+ $billId = $request->get('bill_id');
+ $message = $request->get('message');
+
+ /** @var null|Bill $bill */
+ $bill = auth()->user()->bills()->withTrashed()->find($billId);
+
+ if (null === $bill) {
+ return;
+ }
+ if ('deleted' === $message) {
+ session()->flash('success', (string) trans('firefly.deleted_bill', ['name' => $bill->name]));
+ }
+ if ('created' === $message) {
+ session()->flash('success', (string) trans('firefly.stored_new_bill', ['name' => $bill->name]));
+ }
+ }
+
+ private function handleCurrencyMessage(Request $request): void
+ {
+ // params:
+ // get parameters from request.
+ $code = (string) $request->get('code');
+ $message = (string) $request->get('message');
+
+ try {
+ $currency = Amount::getTransactionCurrencyByCode($code);
+ } catch (FireflyException) {
+ return;
+ }
+
+ if ('enabled' === $message) {
+ session()->flash('success', (string) trans('firefly.currency_is_now_enabled', ['name' => $currency->name]));
+ }
+ if ('enable_failed' === $message) {
+ session()->flash('error', (string) trans('firefly.could_not_enable_currency', ['name' => $currency->name]));
+ }
+ if ('disabled' === $message) {
+ session()->flash('success', (string) trans('firefly.currency_is_now_disabled', ['name' => $currency->name]));
+ }
+ if ('disable_failed' === $message) {
+ session()->flash('error', (string) trans('firefly.could_not_disable_currency', ['name' => $currency->name]));
+ }
+ if ('default' === $message) {
+ session()->flash('success', (string) trans('firefly.new_default_currency', ['name' => $currency->name]));
+ }
+ if ('default_failed' === $message) {
+ session()->flash('error', (string) trans('firefly.default_currency_failed', ['name' => $currency->name]));
+ }
+ }
+
private function handleGroupMessage(Request $request): void
{
// get parameters from request.
@@ -135,15 +235,6 @@ class InterestingMessage
}
}
- private function userGroupMessage(Request $request): bool
- {
- // get parameters from request.
- $transactionGroupId = $request->get('user_group_id');
- $message = $request->get('message');
-
- return null !== $transactionGroupId && null !== $message;
- }
-
private function handleUserGroupMessage(Request $request): void
{
// get parameters from request.
@@ -181,79 +272,6 @@ class InterestingMessage
}
}
- private function accountMessage(Request $request): bool
- {
- // get parameters from request.
- $accountId = $request->get('account_id');
- $message = $request->get('message');
-
- return null !== $accountId && null !== $message;
- }
-
- private function handleAccountMessage(Request $request): void
- {
- // get parameters from request.
- $accountId = $request->get('account_id');
- $message = $request->get('message');
-
- /** @var User $user */
- $user = auth()->user();
-
- /** @var null|Account $account */
- $account = $user->accounts()->withTrashed()->find($accountId);
-
- if (null === $account) {
- return;
- }
- if ('deleted' === $message) {
- session()->flash('success', (string) trans('firefly.account_deleted', ['name' => $account->name]));
- }
- if ('created' === $message) {
- session()->flash('success', (string) trans('firefly.stored_new_account', ['name' => $account->name]));
- }
- if ('updated' === $message) {
- session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name]));
- }
- }
-
- private function billMessage(Request $request): bool
- {
- // get parameters from request.
- $billId = $request->get('bill_id');
- $message = $request->get('message');
-
- return null !== $billId && null !== $message;
- }
-
- private function handleBillMessage(Request $request): void
- {
- // get parameters from request.
- $billId = $request->get('bill_id');
- $message = $request->get('message');
-
- /** @var null|Bill $bill */
- $bill = auth()->user()->bills()->withTrashed()->find($billId);
-
- if (null === $bill) {
- return;
- }
- if ('deleted' === $message) {
- session()->flash('success', (string) trans('firefly.deleted_bill', ['name' => $bill->name]));
- }
- if ('created' === $message) {
- session()->flash('success', (string) trans('firefly.stored_new_bill', ['name' => $bill->name]));
- }
- }
-
- private function webhookMessage(Request $request): bool
- {
- // get parameters from request.
- $webhookId = $request->get('webhook_id');
- $message = $request->get('message');
-
- return null !== $webhookId && null !== $message;
- }
-
private function handleWebhookMessage(Request $request): void
{
// get parameters from request.
@@ -277,45 +295,27 @@ class InterestingMessage
}
}
- private function currencyMessage(Request $request): bool
+ private function testing(): bool
+ {
+ // ignore middleware in test environment.
+ return 'testing' === config('app.env') || !auth()->check();
+ }
+
+ private function userGroupMessage(Request $request): bool
{
// get parameters from request.
- $code = $request->get('code');
- $message = $request->get('message');
+ $transactionGroupId = $request->get('user_group_id');
+ $message = $request->get('message');
- return null !== $code && null !== $message;
+ return null !== $transactionGroupId && null !== $message;
}
- private function handleCurrencyMessage(Request $request): void
+ private function webhookMessage(Request $request): bool
{
- // params:
// get parameters from request.
- $code = (string) $request->get('code');
- $message = (string) $request->get('message');
-
- try {
- $currency = Amount::getTransactionCurrencyByCode($code);
- } catch (FireflyException) {
- return;
- }
+ $webhookId = $request->get('webhook_id');
+ $message = $request->get('message');
- if ('enabled' === $message) {
- session()->flash('success', (string) trans('firefly.currency_is_now_enabled', ['name' => $currency->name]));
- }
- if ('enable_failed' === $message) {
- session()->flash('error', (string) trans('firefly.could_not_enable_currency', ['name' => $currency->name]));
- }
- if ('disabled' === $message) {
- session()->flash('success', (string) trans('firefly.currency_is_now_disabled', ['name' => $currency->name]));
- }
- if ('disable_failed' === $message) {
- session()->flash('error', (string) trans('firefly.could_not_disable_currency', ['name' => $currency->name]));
- }
- if ('default' === $message) {
- session()->flash('success', (string) trans('firefly.new_default_currency', ['name' => $currency->name]));
- }
- if ('default_failed' === $message) {
- session()->flash('error', (string) trans('firefly.default_currency_failed', ['name' => $currency->name]));
- }
+ return null !== $webhookId && null !== $message;
}
}
diff --git a/app/Http/Middleware/Range.php b/app/Http/Middleware/Range.php
index cfad4e219b..94b2f34789 100644
--- a/app/Http/Middleware/Range.php
+++ b/app/Http/Middleware/Range.php
@@ -65,37 +65,17 @@ class Range
}
/**
- * Set the range for the current view.
+ * Configure the list length.
*/
- private function setRange(): void
+ private function configureList(): void
{
- // ignore preference. set the range to be the current month:
- if (!app('session')->has('start') && !app('session')->has('end')) {
- Log::debug('setRange: Session has no start or end.');
- $viewRange = Preferences::get('viewRange', '1M')->data;
- if (is_array($viewRange)) {
- $viewRange = '1M';
- }
-
- $today = today(config('app.timezone'));
- $start = Navigation::updateStartDate((string) $viewRange, $today);
- $end = Navigation::updateEndDate((string) $viewRange, $start);
-
- app('session')->put('start', $start);
- app('session')->put('end', $end);
- }
- if (!app('session')->has('first')) {
- Log::debug('setRange: Session has no "first".');
-
- /** @var JournalRepositoryInterface $repository */
- $repository = app(JournalRepositoryInterface::class);
- $journal = $repository->firstNull();
- $first = today(config('app.timezone'))->startOfYear();
+ $pref = Preferences::get('list-length', config('firefly.list_length', 10))->data;
+ app('view')->share('listLength', $pref);
- if (null !== $journal) {
- $first = $journal->date ?? $first;
- }
- app('session')->put('first', $first);
+ // share security message:
+ if (FireflyConfig::has('upgrade_security_message') && FireflyConfig::has('upgrade_security_level')) {
+ app('view')->share('upgrade_security_message', FireflyConfig::get('upgrade_security_message')->data);
+ app('view')->share('upgrade_security_level', FireflyConfig::get('upgrade_security_level')->data);
}
}
@@ -136,17 +116,37 @@ class Range
}
/**
- * Configure the list length.
+ * Set the range for the current view.
*/
- private function configureList(): void
+ private function setRange(): void
{
- $pref = Preferences::get('list-length', config('firefly.list_length', 10))->data;
- app('view')->share('listLength', $pref);
+ // ignore preference. set the range to be the current month:
+ if (!app('session')->has('start') && !app('session')->has('end')) {
+ Log::debug('setRange: Session has no start or end.');
+ $viewRange = Preferences::get('viewRange', '1M')->data;
+ if (is_array($viewRange)) {
+ $viewRange = '1M';
+ }
- // share security message:
- if (FireflyConfig::has('upgrade_security_message') && FireflyConfig::has('upgrade_security_level')) {
- app('view')->share('upgrade_security_message', FireflyConfig::get('upgrade_security_message')->data);
- app('view')->share('upgrade_security_level', FireflyConfig::get('upgrade_security_level')->data);
+ $today = today(config('app.timezone'));
+ $start = Navigation::updateStartDate((string) $viewRange, $today);
+ $end = Navigation::updateEndDate((string) $viewRange, $start);
+
+ app('session')->put('start', $start);
+ app('session')->put('end', $end);
+ }
+ if (!app('session')->has('first')) {
+ Log::debug('setRange: Session has no "first".');
+
+ /** @var JournalRepositoryInterface $repository */
+ $repository = app(JournalRepositoryInterface::class);
+ $journal = $repository->firstNull();
+ $first = today(config('app.timezone'))->startOfYear();
+
+ if (null !== $journal) {
+ $first = $journal->date ?? $first;
+ }
+ app('session')->put('first', $first);
}
}
}
diff --git a/app/Http/Requests/RecurrenceFormRequest.php b/app/Http/Requests/RecurrenceFormRequest.php
index 7670bd4cea..415dcd9b69 100644
--- a/app/Http/Requests/RecurrenceFormRequest.php
+++ b/app/Http/Requests/RecurrenceFormRequest.php
@@ -147,35 +147,6 @@ class RecurrenceFormRequest extends FormRequest
return $return;
}
- /**
- * Parses repetition data.
- */
- private function parseRepetitionData(): array
- {
- $value = $this->convertString('repetition_type');
- $return = ['type' => '', 'moment' => ''];
-
- if ('daily' === $value) {
- $return['type'] = $value;
- }
- // monthly,17
- // ndom,3,7
- if (in_array(substr($value, 0, 6), ['yearly', 'weekly'], true)) {
- $return['type'] = substr($value, 0, 6);
- $return['moment'] = substr($value, 7);
- }
- if (str_starts_with($value, 'monthly')) {
- $return['type'] = substr($value, 0, 7);
- $return['moment'] = substr($value, 8);
- }
- if (str_starts_with($value, 'ndom')) {
- $return['type'] = substr($value, 0, 4);
- $return['moment'] = substr($value, 5);
- }
-
- return $return;
- }
-
/**
* The rules for this request.
*/
@@ -262,20 +233,6 @@ class RecurrenceFormRequest extends FormRequest
return $rules;
}
- /**
- * Configure the validator instance with special rules for after the basic validation rules.
- */
- public function withValidator(Validator $validator): void
- {
- $validator->after(function (Validator $validator): void {
- // validate all account info
- $this->validateAccountInformation($validator);
- });
- if ($validator->fails()) {
- Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray());
- }
- }
-
/**
* Validates the given account information. Switches on given transaction type.
*
@@ -340,4 +297,47 @@ class RecurrenceFormRequest extends FormRequest
$validator->errors()->add('withdrawal_destination_id', $message);
}
}
+
+ /**
+ * Configure the validator instance with special rules for after the basic validation rules.
+ */
+ public function withValidator(Validator $validator): void
+ {
+ $validator->after(function (Validator $validator): void {
+ // validate all account info
+ $this->validateAccountInformation($validator);
+ });
+ if ($validator->fails()) {
+ Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray());
+ }
+ }
+
+ /**
+ * Parses repetition data.
+ */
+ private function parseRepetitionData(): array
+ {
+ $value = $this->convertString('repetition_type');
+ $return = ['type' => '', 'moment' => ''];
+
+ if ('daily' === $value) {
+ $return['type'] = $value;
+ }
+ // monthly,17
+ // ndom,3,7
+ if (in_array(substr($value, 0, 6), ['yearly', 'weekly'], true)) {
+ $return['type'] = substr($value, 0, 6);
+ $return['moment'] = substr($value, 7);
+ }
+ if (str_starts_with($value, 'monthly')) {
+ $return['type'] = substr($value, 0, 7);
+ $return['moment'] = substr($value, 8);
+ }
+ if (str_starts_with($value, 'ndom')) {
+ $return['type'] = substr($value, 0, 4);
+ $return['moment'] = substr($value, 5);
+ }
+
+ return $return;
+ }
}
diff --git a/app/Http/Requests/RuleFormRequest.php b/app/Http/Requests/RuleFormRequest.php
index c44fb52243..feb46c2197 100644
--- a/app/Http/Requests/RuleFormRequest.php
+++ b/app/Http/Requests/RuleFormRequest.php
@@ -41,47 +41,6 @@ class RuleFormRequest extends FormRequest
use ConvertsDataTypes;
use GetRuleConfiguration;
- /**
- * Get all data for controller.
- */
- public function getRuleData(): array
- {
- return [
- 'title' => $this->convertString('title'),
- 'rule_group_id' => $this->convertInteger('rule_group_id'),
- 'active' => $this->boolean('active'),
- 'trigger' => $this->convertString('trigger'),
- 'description' => $this->stringWithNewlines('description'),
- 'stop_processing' => $this->boolean('stop_processing'),
- 'strict' => $this->boolean('strict'),
- 'run_after_form' => $this->boolean('run_after_form'),
- 'triggers' => $this->getRuleTriggerData(),
- 'actions' => $this->getRuleActionData(),
- ];
- }
-
- private function getRuleTriggerData(): array
- {
- $return = [];
- $triggerData = $this->get('triggers');
- if (is_array($triggerData)) {
- foreach ($triggerData as $trigger) {
- $stopProcessing = $trigger['stop_processing'] ?? '0';
- $prohibited = $trigger['prohibited'] ?? '0';
- $set = [
- 'type' => $trigger['type'] ?? 'invalid',
- 'value' => $trigger['value'] ?? '',
- 'stop_processing' => 1 === (int) $stopProcessing,
- 'prohibited' => 1 === (int) $prohibited,
- ];
- $set = self::replaceAmountTrigger($set);
- $return[] = $set;
- }
- }
-
- return $return;
- }
-
public static function replaceAmountTrigger(array $array): array
{
// do some sneaky search and replace.
@@ -107,22 +66,23 @@ class RuleFormRequest extends FormRequest
return $array;
}
- private function getRuleActionData(): array
+ /**
+ * Get all data for controller.
+ */
+ public function getRuleData(): array
{
- $return = [];
- $actionData = $this->get('actions');
- if (is_array($actionData)) {
- foreach ($actionData as $action) {
- $stopProcessing = $action['stop_processing'] ?? '0';
- $return[] = [
- 'type' => $action['type'] ?? 'invalid',
- 'value' => $action['value'] ?? '',
- 'stop_processing' => 1 === (int) $stopProcessing,
- ];
- }
- }
-
- return $return;
+ return [
+ 'title' => $this->convertString('title'),
+ 'rule_group_id' => $this->convertInteger('rule_group_id'),
+ 'active' => $this->boolean('active'),
+ 'trigger' => $this->convertString('trigger'),
+ 'description' => $this->stringWithNewlines('description'),
+ 'stop_processing' => $this->boolean('stop_processing'),
+ 'strict' => $this->boolean('strict'),
+ 'run_after_form' => $this->boolean('run_after_form'),
+ 'triggers' => $this->getRuleTriggerData(),
+ 'actions' => $this->getRuleActionData(),
+ ];
}
/**
@@ -170,4 +130,44 @@ class RuleFormRequest extends FormRequest
Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray());
}
}
+
+ private function getRuleActionData(): array
+ {
+ $return = [];
+ $actionData = $this->get('actions');
+ if (is_array($actionData)) {
+ foreach ($actionData as $action) {
+ $stopProcessing = $action['stop_processing'] ?? '0';
+ $return[] = [
+ 'type' => $action['type'] ?? 'invalid',
+ 'value' => $action['value'] ?? '',
+ 'stop_processing' => 1 === (int) $stopProcessing,
+ ];
+ }
+ }
+
+ return $return;
+ }
+
+ private function getRuleTriggerData(): array
+ {
+ $return = [];
+ $triggerData = $this->get('triggers');
+ if (is_array($triggerData)) {
+ foreach ($triggerData as $trigger) {
+ $stopProcessing = $trigger['stop_processing'] ?? '0';
+ $prohibited = $trigger['prohibited'] ?? '0';
+ $set = [
+ 'type' => $trigger['type'] ?? 'invalid',
+ 'value' => $trigger['value'] ?? '',
+ 'stop_processing' => 1 === (int) $stopProcessing,
+ 'prohibited' => 1 === (int) $prohibited,
+ ];
+ $set = self::replaceAmountTrigger($set);
+ $return[] = $set;
+ }
+ }
+
+ return $return;
+ }
}
diff --git a/app/Jobs/CreateAutoBudgetLimits.php b/app/Jobs/CreateAutoBudgetLimits.php
index 34c9fddae4..26824023cc 100644
--- a/app/Jobs/CreateAutoBudgetLimits.php
+++ b/app/Jobs/CreateAutoBudgetLimits.php
@@ -59,7 +59,7 @@ class CreateAutoBudgetLimits implements ShouldQueue
public function __construct(?Carbon $date)
{
if ($date instanceof Carbon) {
- $newDate = clone $date;
+ $newDate = clone $date;
$newDate->startOfDay();
$this->date = $newDate;
Log::debug(sprintf('Created new CreateAutoBudgetLimits("%s")', $this->date->format('Y-m-d')));
@@ -81,127 +81,81 @@ class CreateAutoBudgetLimits implements ShouldQueue
}
}
- /**
- * @throws FireflyException
- */
- private function handleAutoBudget(AutoBudget $autoBudget): void
+ public function setDate(Carbon $date): void
{
- if (null === $autoBudget->budget) {
- Log::info(sprintf('Auto budget #%d is associated with a deleted budget.', $autoBudget->id));
- $autoBudget->delete();
-
- return;
- }
- if (false === $autoBudget->budget->active) {
- Log::info(sprintf('Auto budget #%d is associated with an inactive budget.', $autoBudget->id));
+ $newDate = clone $date;
+ $newDate->startOfDay();
+ $this->date = $newDate;
+ }
- return;
- }
- if (!$this->isMagicDay($autoBudget)) {
- Log::info(sprintf(
- 'Today (%s) is not a magic day for %s auto-budget #%d (part of budget #%d "%s")',
- $this->date->format('Y-m-d'),
- $autoBudget->period,
- $autoBudget->id,
- $autoBudget->budget->id,
- $autoBudget->budget->name
- ));
- Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
+ private function createAdjustedLimit(AutoBudget $autoBudget): void
+ {
+ Log::debug(sprintf('Will now manage rollover for auto budget #%d', $autoBudget->id));
+ // current period:
+ $start = Navigation::startOfPeriod($this->date, $autoBudget->period);
+ $end = Navigation::endOfPeriod($start, $autoBudget->period);
- return;
- }
- Log::info(sprintf(
- 'Today (%s) is a magic day for %s auto-budget #%d (part of budget #%d "%s")',
- $this->date->format('Y-m-d'),
- $autoBudget->period,
- $autoBudget->id,
- $autoBudget->budget->id,
- $autoBudget->budget->name
- ));
+ // which means previous period:
+ $previousStart = Navigation::subtractPeriod($start, $autoBudget->period);
+ $previousEnd = Navigation::endOfPeriod($previousStart, $autoBudget->period);
- // get date range for budget limit, based on range in auto-budget
- $start = Navigation::startOfPeriod($this->date, $autoBudget->period);
- $end = Navigation::endOfPeriod($start, $autoBudget->period);
+ Log::debug(sprintf(
+ 'Current period is %s-%s, so previous period is %s-%s',
+ $start->format('Y-m-d'),
+ $end->format('Y-m-d'),
+ $previousStart->format('Y-m-d'),
+ $previousEnd->format('Y-m-d')
+ ));
- // find budget limit:
- $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $start, $end);
+ // has budget limit in previous period?
+ $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd);
- if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_RESET->value === (int)$autoBudget->auto_budget_type) {
- // that's easy: create one.
- // do nothing else.
+ if (!$budgetLimit instanceof BudgetLimit) {
+ Log::debug('No budget limit exists in previous period, so create one.');
+ // if not, create standard amount, and we're done.
$this->createBudgetLimit($autoBudget, $start, $end);
- Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
-
- return;
- }
-
- if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_ROLLOVER->value === (int)$autoBudget->auto_budget_type) {
- // budget limit exists already,
- $this->createRollover($autoBudget);
- Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
-
- return;
- }
- if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_ADJUSTED->value === (int)$autoBudget->auto_budget_type) {
- // budget limit exists already,
- $this->createAdjustedLimit($autoBudget);
- Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
return;
}
- Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
- }
+ Log::debug('Budget limit exists for previous period.');
- /**
- * @throws FireflyException
- */
- private function isMagicDay(AutoBudget $autoBudget): bool
- {
- if ('daily' === $autoBudget->period) {
- return true;
- }
+ // if has one, calculate expenses and use that as a base.
+ $repository = app(OperationsRepositoryInterface::class);
+ $repository->setUser($autoBudget->budget->user);
+ $spent = $repository->sumExpenses(
+ $previousStart,
+ $previousEnd,
+ null,
+ new Collection()->push($autoBudget->budget),
+ $autoBudget->transactionCurrency
+ );
+ $currencyId = $autoBudget->transaction_currency_id;
+ $spentAmount = $spent[$currencyId]['sum'] ?? '0';
+ Log::debug(sprintf('Spent in previous budget period (%s-%s) is %s', $previousStart->format('Y-m-d'), $previousEnd->format('Y-m-d'), $spentAmount));
- if ('weekly' === $autoBudget->period) {
- return $this->date->isMonday();
- }
+ // what you spent in previous period PLUS the amount for the current period,
+ // if that is more than zero, that's the amount that will be set.
- if ('monthly' === $autoBudget->period) {
- return 1 === $this->date->day;
- }
- if ('quarterly' === $autoBudget->period) {
- $format = 'm-d';
- $value = $this->date->format($format);
+ $budgetAvailable = bcadd(bcadd($budgetLimit->amount, $autoBudget->amount), $spentAmount);
+ $totalAmount = $autoBudget->amount;
+ Log::debug(sprintf('Total amount available for current budget period is %s', $budgetAvailable));
- return in_array($value, ['01-01', '04-01', '07-01', '10-01'], true);
+ if (-1 !== bccomp($budgetAvailable, $totalAmount)) {
+ Log::info(sprintf('There is no overspending, no need to adjust. Budget limit amount will be %s.', $budgetAvailable));
+ // create budget limit:
+ $this->createBudgetLimit($autoBudget, $start, $end, $budgetAvailable);
}
- if ('half_year' === $autoBudget->period) {
- $format = 'm-d';
- $value = $this->date->format($format);
-
- return in_array($value, ['01-01', '07-01'], true);
+ if (1 !== bccomp($budgetAvailable, $totalAmount) && 1 === bccomp($budgetAvailable, '0')) {
+ Log::info(sprintf('There was overspending, so the new amount will be %s.', $budgetAvailable));
+ // create budget limit:
+ $this->createBudgetLimit($autoBudget, $start, $end, $budgetAvailable);
}
- if ('yearly' === $autoBudget->period) {
- $format = 'm-d';
- $value = $this->date->format($format);
-
- return '01-01' === $value;
+ if (1 !== bccomp($budgetAvailable, $totalAmount) && -1 === bccomp($budgetAvailable, '0')) {
+ Log::info('There was overspending, but so much even this period cant fix that. Reset it to 1.');
+ // create budget limit:
+ $this->createBudgetLimit($autoBudget, $start, $end, '1');
}
-
- throw new FireflyException(sprintf('isMagicDay() can\'t handle period "%s"', $autoBudget->period));
- }
-
- private function findBudgetLimit(Budget $budget, Carbon $start, Carbon $end): ?BudgetLimit
- {
- Log::debug(sprintf(
- 'Going to find a budget limit for budget #%d ("%s") between %s and %s',
- $budget->id,
- $budget->name,
- $start->format('Y-m-d'),
- $end->format('Y-m-d')
- ));
-
- /** @var null|BudgetLimit */
- return $budget->budgetlimits()->where('start_date', $start->format('Y-m-d'))->where('end_date', $end->format('Y-m-d'))->first();
+ Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
}
private function createBudgetLimit(AutoBudget $autoBudget, Carbon $start, Carbon $end, ?string $amount = null): void
@@ -210,22 +164,20 @@ class CreateAutoBudgetLimits implements ShouldQueue
if (null !== $amount) {
Log::debug(sprintf('Amount is overruled and will be set to %s', $amount));
}
+
/** @var BudgetLimitRepositoryInterface $repository */
- $repository = app(BudgetLimitRepositoryInterface::class);
+ $repository = app(BudgetLimitRepositoryInterface::class);
$repository->setUserGroup($autoBudget->budget->user->userGroup);
- $budgetLimit = $repository->store(
- [
- 'currency_id' => $autoBudget->transaction_currency_id,
- 'budget_id' => $autoBudget->budget->id,
- 'start_date' => clone $start,
- 'end_date' => clone $end,
- 'amount' => $amount ?? $autoBudget->amount,
- 'period' => $autoBudget->period,
- 'generated' => true,
-
- ]
- );
+ $budgetLimit = $repository->store([
+ 'currency_id' => $autoBudget->transaction_currency_id,
+ 'budget_id' => $autoBudget->budget->id,
+ 'start_date' => clone $start,
+ 'end_date' => clone $end,
+ 'amount' => $amount ?? $autoBudget->amount,
+ 'period' => $autoBudget->period,
+ 'generated' => true,
+ ]);
Log::debug(sprintf('Created budget limit #%d.', $budgetLimit->id));
}
@@ -236,23 +188,23 @@ class CreateAutoBudgetLimits implements ShouldQueue
{
Log::debug(sprintf('Will now manage rollover for auto budget #%d', $autoBudget->id));
// current period:
- $start = Navigation::startOfPeriod($this->date, $autoBudget->period);
- $end = Navigation::endOfPeriod($start, $autoBudget->period);
+ $start = Navigation::startOfPeriod($this->date, $autoBudget->period);
+ $end = Navigation::endOfPeriod($start, $autoBudget->period);
// which means previous period:
$previousStart = Navigation::subtractPeriod($start, $autoBudget->period);
$previousEnd = Navigation::endOfPeriod($previousStart, $autoBudget->period);
Log::debug(sprintf(
- 'Current period is %s-%s, so previous period is %s-%s',
- $start->format('Y-m-d'),
- $end->format('Y-m-d'),
- $previousStart->format('Y-m-d'),
- $previousEnd->format('Y-m-d')
- ));
+ 'Current period is %s-%s, so previous period is %s-%s',
+ $start->format('Y-m-d'),
+ $end->format('Y-m-d'),
+ $previousStart->format('Y-m-d'),
+ $previousEnd->format('Y-m-d')
+ ));
// has budget limit in previous period?
- $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd);
+ $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd);
if (!$budgetLimit instanceof BudgetLimit) {
Log::debug('No budget limit exists in previous period, so create one.');
@@ -264,23 +216,23 @@ class CreateAutoBudgetLimits implements ShouldQueue
}
Log::debug('Budget limit exists for previous period.');
// if has one, calculate expenses and use that as a base.
- $repository = app(OperationsRepositoryInterface::class);
+ $repository = app(OperationsRepositoryInterface::class);
$repository->setUser($autoBudget->budget->user);
- $spent = $repository->sumExpenses(
+ $spent = $repository->sumExpenses(
$previousStart,
$previousEnd,
null,
new Collection()->push($autoBudget->budget),
$autoBudget->transactionCurrency
);
- $currencyId = $autoBudget->transaction_currency_id;
- $spentAmount = $spent[$currencyId]['sum'] ?? '0';
+ $currencyId = $autoBudget->transaction_currency_id;
+ $spentAmount = $spent[$currencyId]['sum'] ?? '0';
Log::debug(sprintf('Spent in previous budget period (%s-%s) is %s', $previousStart->format('Y-m-d'), $previousEnd->format('Y-m-d'), $spentAmount));
// if you spent more in previous budget period, than whatever you had previous budget period, the amount resets
// previous budget limit + spent
- $budgetLeft = bcadd($budgetLimit->amount, $spentAmount);
- $totalAmount = $autoBudget->amount;
+ $budgetLeft = bcadd($budgetLimit->amount, $spentAmount);
+ $totalAmount = $autoBudget->amount;
Log::debug(sprintf('Total amount left for previous budget period is %s', $budgetLeft));
if (-1 !== bccomp('0', $budgetLeft)) {
@@ -296,80 +248,126 @@ class CreateAutoBudgetLimits implements ShouldQueue
Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
}
- private function createAdjustedLimit(AutoBudget $autoBudget): void
+ private function findBudgetLimit(Budget $budget, Carbon $start, Carbon $end): ?BudgetLimit
{
- Log::debug(sprintf('Will now manage rollover for auto budget #%d', $autoBudget->id));
- // current period:
- $start = Navigation::startOfPeriod($this->date, $autoBudget->period);
- $end = Navigation::endOfPeriod($start, $autoBudget->period);
+ Log::debug(sprintf(
+ 'Going to find a budget limit for budget #%d ("%s") between %s and %s',
+ $budget->id,
+ $budget->name,
+ $start->format('Y-m-d'),
+ $end->format('Y-m-d')
+ ));
- // which means previous period:
- $previousStart = Navigation::subtractPeriod($start, $autoBudget->period);
- $previousEnd = Navigation::endOfPeriod($previousStart, $autoBudget->period);
+ /** @var null|BudgetLimit */
+ return $budget->budgetlimits()->where('start_date', $start->format('Y-m-d'))->where('end_date', $end->format('Y-m-d'))->first();
+ }
- Log::debug(sprintf(
- 'Current period is %s-%s, so previous period is %s-%s',
- $start->format('Y-m-d'),
- $end->format('Y-m-d'),
- $previousStart->format('Y-m-d'),
- $previousEnd->format('Y-m-d')
- ));
+ /**
+ * @throws FireflyException
+ */
+ private function handleAutoBudget(AutoBudget $autoBudget): void
+ {
+ if (null === $autoBudget->budget) {
+ Log::info(sprintf('Auto budget #%d is associated with a deleted budget.', $autoBudget->id));
+ $autoBudget->delete();
- // has budget limit in previous period?
- $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd);
+ return;
+ }
+ if (false === $autoBudget->budget->active) {
+ Log::info(sprintf('Auto budget #%d is associated with an inactive budget.', $autoBudget->id));
- if (!$budgetLimit instanceof BudgetLimit) {
- Log::debug('No budget limit exists in previous period, so create one.');
- // if not, create standard amount, and we're done.
- $this->createBudgetLimit($autoBudget, $start, $end);
+ return;
+ }
+ if (!$this->isMagicDay($autoBudget)) {
+ Log::info(sprintf(
+ 'Today (%s) is not a magic day for %s auto-budget #%d (part of budget #%d "%s")',
+ $this->date->format('Y-m-d'),
+ $autoBudget->period,
+ $autoBudget->id,
+ $autoBudget->budget->id,
+ $autoBudget->budget->name
+ ));
+ Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
return;
}
- Log::debug('Budget limit exists for previous period.');
+ Log::info(sprintf(
+ 'Today (%s) is a magic day for %s auto-budget #%d (part of budget #%d "%s")',
+ $this->date->format('Y-m-d'),
+ $autoBudget->period,
+ $autoBudget->id,
+ $autoBudget->budget->id,
+ $autoBudget->budget->name
+ ));
- // if has one, calculate expenses and use that as a base.
- $repository = app(OperationsRepositoryInterface::class);
- $repository->setUser($autoBudget->budget->user);
- $spent = $repository->sumExpenses(
- $previousStart,
- $previousEnd,
- null,
- new Collection()->push($autoBudget->budget),
- $autoBudget->transactionCurrency
- );
- $currencyId = $autoBudget->transaction_currency_id;
- $spentAmount = $spent[$currencyId]['sum'] ?? '0';
- Log::debug(sprintf('Spent in previous budget period (%s-%s) is %s', $previousStart->format('Y-m-d'), $previousEnd->format('Y-m-d'), $spentAmount));
+ // get date range for budget limit, based on range in auto-budget
+ $start = Navigation::startOfPeriod($this->date, $autoBudget->period);
+ $end = Navigation::endOfPeriod($start, $autoBudget->period);
- // what you spent in previous period PLUS the amount for the current period,
- // if that is more than zero, that's the amount that will be set.
+ // find budget limit:
+ $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $start, $end);
- $budgetAvailable = bcadd(bcadd($budgetLimit->amount, $autoBudget->amount), $spentAmount);
- $totalAmount = $autoBudget->amount;
- Log::debug(sprintf('Total amount available for current budget period is %s', $budgetAvailable));
+ if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_RESET->value === (int) $autoBudget->auto_budget_type) {
+ // that's easy: create one.
+ // do nothing else.
+ $this->createBudgetLimit($autoBudget, $start, $end);
+ Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
- if (-1 !== bccomp($budgetAvailable, $totalAmount)) {
- Log::info(sprintf('There is no overspending, no need to adjust. Budget limit amount will be %s.', $budgetAvailable));
- // create budget limit:
- $this->createBudgetLimit($autoBudget, $start, $end, $budgetAvailable);
+ return;
}
- if (1 !== bccomp($budgetAvailable, $totalAmount) && 1 === bccomp($budgetAvailable, '0')) {
- Log::info(sprintf('There was overspending, so the new amount will be %s.', $budgetAvailable));
- // create budget limit:
- $this->createBudgetLimit($autoBudget, $start, $end, $budgetAvailable);
+
+ if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_ROLLOVER->value === (int) $autoBudget->auto_budget_type) {
+ // budget limit exists already,
+ $this->createRollover($autoBudget);
+ Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
+
+ return;
}
- if (1 !== bccomp($budgetAvailable, $totalAmount) && -1 === bccomp($budgetAvailable, '0')) {
- Log::info('There was overspending, but so much even this period cant fix that. Reset it to 1.');
- // create budget limit:
- $this->createBudgetLimit($autoBudget, $start, $end, '1');
+ if (!$budgetLimit instanceof BudgetLimit && AutoBudgetType::AUTO_BUDGET_ADJUSTED->value === (int) $autoBudget->auto_budget_type) {
+ // budget limit exists already,
+ $this->createAdjustedLimit($autoBudget);
+ Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
+
+ return;
}
Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id));
}
- public function setDate(Carbon $date): void
+ /**
+ * @throws FireflyException
+ */
+ private function isMagicDay(AutoBudget $autoBudget): bool
{
- $newDate = clone $date;
- $newDate->startOfDay();
- $this->date = $newDate;
+ if ('daily' === $autoBudget->period) {
+ return true;
+ }
+
+ if ('weekly' === $autoBudget->period) {
+ return $this->date->isMonday();
+ }
+
+ if ('monthly' === $autoBudget->period) {
+ return 1 === $this->date->day;
+ }
+ if ('quarterly' === $autoBudget->period) {
+ $format = 'm-d';
+ $value = $this->date->format($format);
+
+ return in_array($value, ['01-01', '04-01', '07-01', '10-01'], true);
+ }
+ if ('half_year' === $autoBudget->period) {
+ $format = 'm-d';
+ $value = $this->date->format($format);
+
+ return in_array($value, ['01-01', '07-01'], true);
+ }
+ if ('yearly' === $autoBudget->period) {
+ $format = 'm-d';
+ $value = $this->date->format($format);
+
+ return '01-01' === $value;
+ }
+
+ throw new FireflyException(sprintf('isMagicDay() can\'t handle period "%s"', $autoBudget->period));
}
}
diff --git a/app/Jobs/CreateRecurringTransactions.php b/app/Jobs/CreateRecurringTransactions.php
index a8a770aa24..8e77695306 100644
--- a/app/Jobs/CreateRecurringTransactions.php
+++ b/app/Jobs/CreateRecurringTransactions.php
@@ -153,66 +153,22 @@ class CreateRecurringTransactions implements ShouldQueue
Preferences::mark();
}
- private function filterRecurrences(Collection $recurrences): Collection
+ public function setDate(Carbon $date): void
{
- return $recurrences->filter($this->validRecurrence(...));
+ $newDate = clone $date;
+ $newDate->startOfDay();
+ Log::debug(sprintf('Overruled date to "%s', $newDate->format('Y-m-d H:i:s')));
+ $this->date = $newDate;
}
- /**
- * Is the info in the recurrence valid?
- */
- private function validRecurrence(Recurrence $recurrence): bool
+ public function setForce(bool $force): void
{
- Log::debug(sprintf('Now filtering recurrence #%d, owned by user #%d', $recurrence->id, $recurrence->user_id));
- // is not active.
- if (!$this->active($recurrence)) {
- Log::info(sprintf('Recurrence #%d is not active. Skipped.', $recurrence->id));
-
- return false;
- }
-
- // has repeated X times.
- $journalCount = $this->repository->getJournalCount($recurrence);
- if (0 !== $recurrence->repetitions && $journalCount >= $recurrence->repetitions && false === $this->force) {
- Log::info(sprintf('Recurrence #%d has run %d times, so will run no longer.', $recurrence->id, $journalCount));
-
- return false;
- }
- Log::debug(sprintf('Recurrence #%d has run %d times, max is %d times.', $recurrence->id, $journalCount, $recurrence->repetitions));
-
- // is no longer running
- if ($this->repeatUntilHasPassed($recurrence)) {
- Log::info(sprintf(
- 'Recurrence #%d was set to run until %s, and today\'s date is %s. Skipped.',
- $recurrence->id,
- $recurrence->repeat_until->format('Y-m-d'),
- $this->date->format('Y-m-d')
- ));
-
- return false;
- }
-
- // first_date is in the future
- if ($this->hasNotStartedYet($recurrence)) {
- Log::info(sprintf(
- 'Recurrence #%d is set to run on %s, and today\'s date is %s. Skipped.',
- $recurrence->id,
- $recurrence->first_date->format('Y-m-d H:i:s'),
- $this->date->format('Y-m-d H:i:s')
- ));
-
- return false;
- }
-
- // already fired today (with success):
- if (false === $this->force && $this->hasFiredToday($recurrence)) {
- Log::info(sprintf('Recurrence #%d has already fired today. Skipped.', $recurrence->id));
-
- return false;
- }
- Log::debug('Will be included.');
+ $this->force = $force;
+ }
- return true;
+ public function setRecurrences(Collection $recurrences): void
+ {
+ $this->recurrences = $recurrences;
}
/**
@@ -223,25 +179,9 @@ class CreateRecurringTransactions implements ShouldQueue
return $recurrence->active;
}
- /**
- * Return true if the $repeat_until date is in the past.
- */
- private function repeatUntilHasPassed(Recurrence $recurrence): bool
- {
- // date has passed
- return null !== $recurrence->repeat_until && $recurrence->repeat_until->lt($this->date);
- }
-
- /**
- * Has the recurrence started yet?
- */
- private function hasNotStartedYet(Recurrence $recurrence): bool
+ private function filterRecurrences(Collection $recurrences): Collection
{
- $startDate = $this->getStartDate($recurrence);
- Log::debug(sprintf('Start date is %s', $startDate->toW3cString()));
- Log::debug(sprintf('Ask date is %s', $this->date->toW3cString()));
-
- return $startDate->gt($this->date);
+ return $recurrences->filter($this->validRecurrence(...));
}
/**
@@ -258,67 +198,60 @@ class CreateRecurringTransactions implements ShouldQueue
}
/**
- * Has the recurrence fired today.
- */
- private function hasFiredToday(Recurrence $recurrence): bool
- {
- return null !== $recurrence->latest_date && $recurrence->latest_date->eq($this->date);
- }
-
- /**
- * Separate method that will loop all repetitions and do something with it. Will return
- * all created transaction journals.
- *
- * @throws DuplicateTransactionException
- * @throws FireflyException
+ * Get transaction information from a recurring transaction.
*/
- private function handleRepetitions(Recurrence $recurrence): Collection
+ private function getTransactionData(Recurrence $recurrence, RecurrenceRepetition $repetition, Carbon $date): array
{
- $collection = new Collection();
-
- /** @var RecurrenceRepetition $repetition */
- foreach ($recurrence->recurrenceRepetitions as $repetition) {
- Log::debug(sprintf(
- 'Now repeating %s with value "%s", skips every %d time(s)',
- $repetition->repetition_type,
- $repetition->repetition_moment,
- $repetition->repetition_skip
- ));
-
- // start looping from $startDate to today perhaps we have a hit?
- // add two days to $this->date, so we always include the weekend.
- $includeWeekend = clone $this->date;
- $includeWeekend->addDays(2);
- $occurrences = $this->repository->getOccurrencesInRange($repetition, $recurrence->first_date, $includeWeekend);
-
- unset($includeWeekend);
-
- $result = $this->handleOccurrences($recurrence, $repetition, $occurrences);
- $collection = $collection->merge($result);
- }
-
- return $collection;
- }
+ // total transactions expected for this recurrence:
+ $total = $this->repository->totalTransactions($recurrence, $repetition);
+ $count = $this->repository->getJournalCount($recurrence) + 1;
+ $transactions = $recurrence->recurrenceTransactions()->get();
- /**
- * Check if the occurrences should be executed.
- *
- * @throws DuplicateTransactionException
- * @throws FireflyException
- */
- private function handleOccurrences(Recurrence $recurrence, RecurrenceRepetition $repetition, array $occurrences): Collection
- {
- $collection = new Collection();
+ $transactions->first();
+ $return = [];
- /** @var Carbon $date */
- foreach ($occurrences as $date) {
- $result = $this->handleOccurrence($recurrence, $repetition, $date);
- if ($result instanceof TransactionGroup) {
- $collection->push($result);
- }
+ /** @var RecurrenceTransaction $transaction */
+ foreach ($transactions as $index => $transaction) {
+ $single = [
+ 'type' => null === $transaction?->transactionType?->type
+ ? strtolower((string) $recurrence->transactionType->type)
+ : strtolower($transaction->transactionType->type), // @phpstan-ignore-line
+ 'date' => $date,
+ 'user' => $recurrence->user,
+ 'user_group' => $recurrence->user->userGroup,
+ 'currency_id' => $transaction->transaction_currency_id,
+ 'currency_code' => null,
+ 'description' => $transaction->description,
+ 'amount' => $transaction->amount,
+ 'budget_id' => $this->repository->getBudget($transaction),
+ 'budget_name' => null,
+ 'category_id' => $this->repository->getCategoryId($transaction),
+ 'category_name' => $this->repository->getCategoryName($transaction),
+ 'source_id' => $transaction->source_id,
+ 'source_name' => null,
+ 'destination_id' => $transaction->destination_id,
+ 'destination_name' => null,
+ 'foreign_currency_id' => $transaction->foreign_currency_id,
+ 'foreign_currency_code' => null,
+ 'foreign_amount' => $transaction->foreign_amount,
+ 'reconciled' => false,
+ 'identifier' => $index,
+ 'recurrence_id' => $recurrence->id,
+ 'order' => $index,
+ 'notes' => (string) trans('firefly.created_from_recurrence', ['id' => $recurrence->id, 'title' => $recurrence->title]),
+ 'tags' => $this->repository->getTags($transaction),
+ 'piggy_bank_id' => $this->repository->getPiggyBank($transaction),
+ 'piggy_bank_name' => null,
+ 'bill_id' => $this->repository->getBillId($transaction),
+ 'bill_name' => null,
+ 'recurrence_total' => $total,
+ 'recurrence_count' => $count,
+ 'recurrence_date' => $date,
+ ];
+ $return[] = $single;
}
- return $collection;
+ return $return;
}
/**
@@ -389,77 +322,144 @@ class CreateRecurringTransactions implements ShouldQueue
}
/**
- * Get transaction information from a recurring transaction.
+ * Check if the occurrences should be executed.
+ *
+ * @throws DuplicateTransactionException
+ * @throws FireflyException
*/
- private function getTransactionData(Recurrence $recurrence, RecurrenceRepetition $repetition, Carbon $date): array
+ private function handleOccurrences(Recurrence $recurrence, RecurrenceRepetition $repetition, array $occurrences): Collection
{
- // total transactions expected for this recurrence:
- $total = $this->repository->totalTransactions($recurrence, $repetition);
- $count = $this->repository->getJournalCount($recurrence) + 1;
- $transactions = $recurrence->recurrenceTransactions()->get();
+ $collection = new Collection();
- $transactions->first();
- $return = [];
+ /** @var Carbon $date */
+ foreach ($occurrences as $date) {
+ $result = $this->handleOccurrence($recurrence, $repetition, $date);
+ if ($result instanceof TransactionGroup) {
+ $collection->push($result);
+ }
+ }
- /** @var RecurrenceTransaction $transaction */
- foreach ($transactions as $index => $transaction) {
- $single = [
- 'type' => null === $transaction?->transactionType?->type
- ? strtolower((string) $recurrence->transactionType->type)
- : strtolower($transaction->transactionType->type), // @phpstan-ignore-line
- 'date' => $date,
- 'user' => $recurrence->user,
- 'user_group' => $recurrence->user->userGroup,
- 'currency_id' => $transaction->transaction_currency_id,
- 'currency_code' => null,
- 'description' => $transaction->description,
- 'amount' => $transaction->amount,
- 'budget_id' => $this->repository->getBudget($transaction),
- 'budget_name' => null,
- 'category_id' => $this->repository->getCategoryId($transaction),
- 'category_name' => $this->repository->getCategoryName($transaction),
- 'source_id' => $transaction->source_id,
- 'source_name' => null,
- 'destination_id' => $transaction->destination_id,
- 'destination_name' => null,
- 'foreign_currency_id' => $transaction->foreign_currency_id,
- 'foreign_currency_code' => null,
- 'foreign_amount' => $transaction->foreign_amount,
- 'reconciled' => false,
- 'identifier' => $index,
- 'recurrence_id' => $recurrence->id,
- 'order' => $index,
- 'notes' => (string) trans('firefly.created_from_recurrence', ['id' => $recurrence->id, 'title' => $recurrence->title]),
- 'tags' => $this->repository->getTags($transaction),
- 'piggy_bank_id' => $this->repository->getPiggyBank($transaction),
- 'piggy_bank_name' => null,
- 'bill_id' => $this->repository->getBillId($transaction),
- 'bill_name' => null,
- 'recurrence_total' => $total,
- 'recurrence_count' => $count,
- 'recurrence_date' => $date,
- ];
- $return[] = $single;
+ return $collection;
+ }
+
+ /**
+ * Separate method that will loop all repetitions and do something with it. Will return
+ * all created transaction journals.
+ *
+ * @throws DuplicateTransactionException
+ * @throws FireflyException
+ */
+ private function handleRepetitions(Recurrence $recurrence): Collection
+ {
+ $collection = new Collection();
+
+ /** @var RecurrenceRepetition $repetition */
+ foreach ($recurrence->recurrenceRepetitions as $repetition) {
+ Log::debug(sprintf(
+ 'Now repeating %s with value "%s", skips every %d time(s)',
+ $repetition->repetition_type,
+ $repetition->repetition_moment,
+ $repetition->repetition_skip
+ ));
+
+ // start looping from $startDate to today perhaps we have a hit?
+ // add two days to $this->date, so we always include the weekend.
+ $includeWeekend = clone $this->date;
+ $includeWeekend->addDays(2);
+ $occurrences = $this->repository->getOccurrencesInRange($repetition, $recurrence->first_date, $includeWeekend);
+
+ unset($includeWeekend);
+
+ $result = $this->handleOccurrences($recurrence, $repetition, $occurrences);
+ $collection = $collection->merge($result);
}
- return $return;
+ return $collection;
}
- public function setDate(Carbon $date): void
+ /**
+ * Has the recurrence fired today.
+ */
+ private function hasFiredToday(Recurrence $recurrence): bool
{
- $newDate = clone $date;
- $newDate->startOfDay();
- Log::debug(sprintf('Overruled date to "%s', $newDate->format('Y-m-d H:i:s')));
- $this->date = $newDate;
+ return null !== $recurrence->latest_date && $recurrence->latest_date->eq($this->date);
}
- public function setForce(bool $force): void
+ /**
+ * Has the recurrence started yet?
+ */
+ private function hasNotStartedYet(Recurrence $recurrence): bool
{
- $this->force = $force;
+ $startDate = $this->getStartDate($recurrence);
+ Log::debug(sprintf('Start date is %s', $startDate->toW3cString()));
+ Log::debug(sprintf('Ask date is %s', $this->date->toW3cString()));
+
+ return $startDate->gt($this->date);
}
- public function setRecurrences(Collection $recurrences): void
+ /**
+ * Return true if the $repeat_until date is in the past.
+ */
+ private function repeatUntilHasPassed(Recurrence $recurrence): bool
{
- $this->recurrences = $recurrences;
+ // date has passed
+ return null !== $recurrence->repeat_until && $recurrence->repeat_until->lt($this->date);
+ }
+
+ /**
+ * Is the info in the recurrence valid?
+ */
+ private function validRecurrence(Recurrence $recurrence): bool
+ {
+ Log::debug(sprintf('Now filtering recurrence #%d, owned by user #%d', $recurrence->id, $recurrence->user_id));
+ // is not active.
+ if (!$this->active($recurrence)) {
+ Log::info(sprintf('Recurrence #%d is not active. Skipped.', $recurrence->id));
+
+ return false;
+ }
+
+ // has repeated X times.
+ $journalCount = $this->repository->getJournalCount($recurrence);
+ if (0 !== $recurrence->repetitions && $journalCount >= $recurrence->repetitions && false === $this->force) {
+ Log::info(sprintf('Recurrence #%d has run %d times, so will run no longer.', $recurrence->id, $journalCount));
+
+ return false;
+ }
+ Log::debug(sprintf('Recurrence #%d has run %d times, max is %d times.', $recurrence->id, $journalCount, $recurrence->repetitions));
+
+ // is no longer running
+ if ($this->repeatUntilHasPassed($recurrence)) {
+ Log::info(sprintf(
+ 'Recurrence #%d was set to run until %s, and today\'s date is %s. Skipped.',
+ $recurrence->id,
+ $recurrence->repeat_until->format('Y-m-d'),
+ $this->date->format('Y-m-d')
+ ));
+
+ return false;
+ }
+
+ // first_date is in the future
+ if ($this->hasNotStartedYet($recurrence)) {
+ Log::info(sprintf(
+ 'Recurrence #%d is set to run on %s, and today\'s date is %s. Skipped.',
+ $recurrence->id,
+ $recurrence->first_date->format('Y-m-d H:i:s'),
+ $this->date->format('Y-m-d H:i:s')
+ ));
+
+ return false;
+ }
+
+ // already fired today (with success):
+ if (false === $this->force && $this->hasFiredToday($recurrence)) {
+ Log::info(sprintf('Recurrence #%d has already fired today. Skipped.', $recurrence->id));
+
+ return false;
+ }
+ Log::debug('Will be included.');
+
+ return true;
}
}
diff --git a/app/Jobs/DownloadExchangeRates.php b/app/Jobs/DownloadExchangeRates.php
index 5cb878d298..f940ba426b 100644
--- a/app/Jobs/DownloadExchangeRates.php
+++ b/app/Jobs/DownloadExchangeRates.php
@@ -93,6 +93,13 @@ class DownloadExchangeRates implements ShouldQueue
}
}
+ public function setDate(Carbon $date): void
+ {
+ $newDate = clone $date;
+ $newDate->startOfDay();
+ $this->date = $newDate;
+ }
+
/**
* @throws GuzzleException
* @throws JsonException
@@ -131,20 +138,6 @@ class DownloadExchangeRates implements ShouldQueue
$this->saveRates($currency, $date, $json['rates']);
}
- private function saveRates(TransactionCurrency $currency, Carbon $date, array $rates): void
- {
- foreach ($rates as $code => $rate) {
- $to = $this->getCurrency($code);
- if (!$to instanceof TransactionCurrency) {
- Log::debug(sprintf('Currency %s is not in use, do not save rate.', $code));
-
- continue;
- }
- Log::debug(sprintf('Currency %s is in use.', $code));
- $this->saveRate($currency, $to, $date, $rate);
- }
- }
-
private function getCurrency(string $code): ?TransactionCurrency
{
// if we have it already, don't bother searching for it again.
@@ -185,10 +178,17 @@ class DownloadExchangeRates implements ShouldQueue
}
}
- public function setDate(Carbon $date): void
+ private function saveRates(TransactionCurrency $currency, Carbon $date, array $rates): void
{
- $newDate = clone $date;
- $newDate->startOfDay();
- $this->date = $newDate;
+ foreach ($rates as $code => $rate) {
+ $to = $this->getCurrency($code);
+ if (!$to instanceof TransactionCurrency) {
+ Log::debug(sprintf('Currency %s is not in use, do not save rate.', $code));
+
+ continue;
+ }
+ Log::debug(sprintf('Currency %s is in use.', $code));
+ $this->saveRate($currency, $to, $date, $rate);
+ }
}
}
diff --git a/app/Jobs/WarnAboutBills.php b/app/Jobs/WarnAboutBills.php
index 46a48c7afc..595bcd22f9 100644
--- a/app/Jobs/WarnAboutBills.php
+++ b/app/Jobs/WarnAboutBills.php
@@ -102,49 +102,6 @@ class WarnAboutBills implements ShouldQueue
Log::debug('Done with handle()');
}
- private function hasDateFields(Bill $bill): bool
- {
- if (false === $bill->active) {
- Log::debug('Bill is not active.');
-
- return false;
- }
- if (null === $bill->end_date && null === $bill->extension_date) {
- Log::debug('Bill has no date fields.');
-
- return false;
- }
-
- return true;
- }
-
- private function needsWarning(Bill $bill, string $field): bool
- {
- if (null === $bill->{$field}) {
- return false;
- }
- $diff = $this->getDiff($bill, $field);
- $list = config('firefly.bill_reminder_periods');
- Log::debug(sprintf('Difference in days for field "%s" ("%s") is %d day(s)', $field, $bill->{$field}->format('Y-m-d'), $diff));
-
- return in_array($diff, $list, true);
- }
-
- private function getDiff(Bill $bill, string $field): int
- {
- $today = clone $this->date;
- $carbon = clone $bill->{$field};
-
- return (int) $today->diffInDays($carbon);
- }
-
- private function sendWarning(Bill $bill, string $field): void
- {
- $diff = $this->getDiff($bill, $field);
- Log::debug('Will now send warning!');
- event(new SubscriptionNeedsExtensionOrRenewal($bill, $field, $diff));
- }
-
public function setDate(Carbon $date): void
{
$newDate = clone $date;
@@ -174,6 +131,30 @@ class WarnAboutBills implements ShouldQueue
return ['pay_dates' => $single->meta['pay_dates'] ?? [], 'paid_dates' => $single->meta['paid_dates'] ?? []];
}
+ private function getDiff(Bill $bill, string $field): int
+ {
+ $today = clone $this->date;
+ $carbon = clone $bill->{$field};
+
+ return (int) $today->diffInDays($carbon);
+ }
+
+ private function hasDateFields(Bill $bill): bool
+ {
+ if (false === $bill->active) {
+ Log::debug('Bill is not active.');
+
+ return false;
+ }
+ if (null === $bill->end_date && null === $bill->extension_date) {
+ Log::debug('Bill has no date fields.');
+
+ return false;
+ }
+
+ return true;
+ }
+
private function needsOverdueAlert(array $dates): bool
{
$count = count($dates['pay_dates']) - count($dates['paid_dates']);
@@ -190,6 +171,18 @@ class WarnAboutBills implements ShouldQueue
return $diff >= 6; // FIXME hard coded value.
}
+ private function needsWarning(Bill $bill, string $field): bool
+ {
+ if (null === $bill->{$field}) {
+ return false;
+ }
+ $diff = $this->getDiff($bill, $field);
+ $list = config('firefly.bill_reminder_periods');
+ Log::debug(sprintf('Difference in days for field "%s" ("%s") is %d day(s)', $field, $bill->{$field}->format('Y-m-d'), $diff));
+
+ return in_array($diff, $list, true);
+ }
+
private function sendOverdueAlerts(User $user, array $overdue): void
{
if (count($overdue) > 0) {
@@ -197,4 +190,11 @@ class WarnAboutBills implements ShouldQueue
event(new SubscriptionsAreOverdueForPayment($user, $overdue));
}
}
+
+ private function sendWarning(Bill $bill, string $field): void
+ {
+ $diff = $this->getDiff($bill, $field);
+ Log::debug('Will now send warning!');
+ event(new SubscriptionNeedsExtensionOrRenewal($bill, $field, $diff));
+ }
}
diff --git a/app/Listeners/Model/Budget/ProcessesBudgets.php b/app/Listeners/Model/Budget/ProcessesBudgets.php
index 8497485bd1..68ec95bd87 100644
--- a/app/Listeners/Model/Budget/ProcessesBudgets.php
+++ b/app/Listeners/Model/Budget/ProcessesBudgets.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* ProcessesBudgets.php
* Copyright (c) 2026 [email protected]
@@ -32,7 +35,7 @@ use Illuminate\Support\Facades\Log;
class ProcessesBudgets implements ShouldQueue
{
- public function handle(DestroyingBudget | CreatedBudget | UpdatedBudget $event): void
+ public function handle(CreatedBudget|DestroyingBudget|UpdatedBudget $event): void
{
Log::debug(sprintf('Will now handle %s', get_class($event)));
$trigger = WebhookTrigger::STORE_BUDGET;
@@ -43,13 +46,11 @@ class ProcessesBudgets implements ShouldQueue
$trigger = WebhookTrigger::UPDATE_BUDGET;
}
-
/** @var MessageGeneratorInterface $engine */
- $engine = app(MessageGeneratorInterface::class);
+ $engine = app(MessageGeneratorInterface::class);
$engine->setUser($event->budget->user);
$engine->setObjects(new Collection()->push($event->budget));
$engine->setTrigger($trigger);
$engine->generateMessages();
}
-
}
diff --git a/app/Listeners/Model/BudgetLimit/ProcessesBudgetLimits.php b/app/Listeners/Model/BudgetLimit/ProcessesBudgetLimits.php
index 542f76c7a7..e450f9a27e 100644
--- a/app/Listeners/Model/BudgetLimit/ProcessesBudgetLimits.php
+++ b/app/Listeners/Model/BudgetLimit/ProcessesBudgetLimits.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* RecalculatesAvailableBudgets.php
* Copyright (c) 2026 [email protected]
@@ -35,10 +38,8 @@ use Illuminate\Support\Collection;
class ProcessesBudgetLimits implements ShouldQueue
{
-
- public function handle(DestroyedBudgetLimit | CreatedBudgetLimit | UpdatedBudgetLimit $event): void
+ public function handle(CreatedBudgetLimit|DestroyedBudgetLimit|UpdatedBudgetLimit $event): void
{
-
if ($event instanceof DestroyedBudgetLimit && null !== $event->user) {
// need to recalculate all available budgets for this user.
$calculator = new AvailableBudgetCalculator();
diff --git a/app/Listeners/Model/TransactionGroup/SupportsGroupProcessingTrait.php b/app/Listeners/Model/TransactionGroup/SupportsGroupProcessingTrait.php
index 0594389bdc..595b67b07b 100644
--- a/app/Listeners/Model/TransactionGroup/SupportsGroupProcessingTrait.php
+++ b/app/Listeners/Model/TransactionGroup/SupportsGroupProcessingTrait.php
@@ -26,37 +26,52 @@ use Illuminate\Support\Facades\Log;
trait SupportsGroupProcessingTrait
{
- private function recalculateCredit(Collection $accounts): void
+ protected function processRules(Collection $set, string $type): void
{
- Log::debug(sprintf('Will now recalculateCredit for %d account(s)', $accounts->count()));
+ Log::debug(sprintf('Will now processRules("%s") for %d journal(s)', $type, $set->count()));
+ $array = $set->pluck('id')->toArray();
- /** @var CreditRecalculateService $object */
- $object = app(CreditRecalculateService::class);
- $object->setAccounts($accounts);
- $object->recalculate();
- Log::debug(sprintf('Done with recalculateCredit for %d account(s)', $accounts->count()));
+ /** @var TransactionJournal $first */
+ $first = $set->first();
+ $journalIds = implode(',', $array);
+ $user = $first->user;
+ Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds));
+
+ // collect rules:
+ $ruleGroupRepository = app(RuleGroupRepositoryInterface::class);
+ $ruleGroupRepository->setUser($user);
+
+ // add the groups to the rule engine.
+ // it should run the rules in the group and cancel the group if necessary.
+ Log::debug(sprintf('Fire processRules with ALL %s rule groups.', $type));
+ $groups = $ruleGroupRepository->getRuleGroupsWithRules($type);
+
+ // create and fire rule engine.
+ $newRuleEngine = app(RuleEngineInterface::class);
+ $newRuleEngine->setUser($user);
+ $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]);
+ $newRuleEngine->setRuleGroups($groups);
+ $newRuleEngine->fire();
+ Log::debug(sprintf('Done with processRules("%s") for %d journal(s)', $type, $set->count()));
}
- private function createWebhookMessages(Collection $groups, WebhookTrigger $trigger): void
+ protected function recalculateRunningBalance(TransactionGroupEventObjects $objects): void
{
- Log::debug(sprintf('Will now create webhook messages for %d group(s)', $groups->count()));
-
- /** @var TransactionGroup $first */
- $first = $groups->first();
- $user = $first->user;
+ Log::debug('Now in recalculateRunningBalance');
+ if (false === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data) {
+ Log::debug('Running balance is disabled.');
- /** @var MessageGeneratorInterface $engine */
- $engine = app(MessageGeneratorInterface::class);
- $engine->setUser($user);
+ return;
+ }
+ // find the earliest date in the set, based on date and _internal_previous_date
+ $earliest = $objects->transactionJournals->pluck('date')->sort()->first();
+ $fromInternalDate = $this->getFromInternalDate($objects->transactionJournals->pluck('id')->toArray());
+ $earliest = $fromInternalDate->lt($earliest) ? $fromInternalDate : $earliest;
+ Log::debug(sprintf('Found earliest date: %s', $earliest->toW3cString()));
- // tell the generator which trigger it should look for
- $engine->setTrigger($trigger);
- // tell the generator which objects to process
- $engine->setObjects($groups);
- // tell the generator to generate the messages
- $engine->generateMessages();
+ Log::debug('Found accounts to process', $objects->accounts->pluck('id')->toArray());
- Log::debug(sprintf('Done with create webhook messages for %d group(s)', $groups->count()));
+ AccountBalanceCalculator::optimizedCalculation($objects->accounts, $earliest);
}
protected function removePeriodStatistics(TransactionGroupEventObjects $objects): void
@@ -103,52 +118,26 @@ trait SupportsGroupProcessingTrait
return $collection;
}
- protected function processRules(Collection $set, string $type): void
+ private function createWebhookMessages(Collection $groups, WebhookTrigger $trigger): void
{
- Log::debug(sprintf('Will now processRules("%s") for %d journal(s)', $type, $set->count()));
- $array = $set->pluck('id')->toArray();
-
- /** @var TransactionJournal $first */
- $first = $set->first();
- $journalIds = implode(',', $array);
- $user = $first->user;
- Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds));
-
- // collect rules:
- $ruleGroupRepository = app(RuleGroupRepositoryInterface::class);
- $ruleGroupRepository->setUser($user);
-
- // add the groups to the rule engine.
- // it should run the rules in the group and cancel the group if necessary.
- Log::debug(sprintf('Fire processRules with ALL %s rule groups.', $type));
- $groups = $ruleGroupRepository->getRuleGroupsWithRules($type);
-
- // create and fire rule engine.
- $newRuleEngine = app(RuleEngineInterface::class);
- $newRuleEngine->setUser($user);
- $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]);
- $newRuleEngine->setRuleGroups($groups);
- $newRuleEngine->fire();
- Log::debug(sprintf('Done with processRules("%s") for %d journal(s)', $type, $set->count()));
- }
+ Log::debug(sprintf('Will now create webhook messages for %d group(s)', $groups->count()));
- protected function recalculateRunningBalance(TransactionGroupEventObjects $objects): void
- {
- Log::debug('Now in recalculateRunningBalance');
- if (false === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data) {
- Log::debug('Running balance is disabled.');
+ /** @var TransactionGroup $first */
+ $first = $groups->first();
+ $user = $first->user;
- return;
- }
- // find the earliest date in the set, based on date and _internal_previous_date
- $earliest = $objects->transactionJournals->pluck('date')->sort()->first();
- $fromInternalDate = $this->getFromInternalDate($objects->transactionJournals->pluck('id')->toArray());
- $earliest = $fromInternalDate->lt($earliest) ? $fromInternalDate : $earliest;
- Log::debug(sprintf('Found earliest date: %s', $earliest->toW3cString()));
+ /** @var MessageGeneratorInterface $engine */
+ $engine = app(MessageGeneratorInterface::class);
+ $engine->setUser($user);
- Log::debug('Found accounts to process', $objects->accounts->pluck('id')->toArray());
+ // tell the generator which trigger it should look for
+ $engine->setTrigger($trigger);
+ // tell the generator which objects to process
+ $engine->setObjects($groups);
+ // tell the generator to generate the messages
+ $engine->generateMessages();
- AccountBalanceCalculator::optimizedCalculation($objects->accounts, $earliest);
+ Log::debug(sprintf('Done with create webhook messages for %d group(s)', $groups->count()));
}
private function getFromInternalDate(array $ids): Carbon
@@ -167,4 +156,15 @@ trait SupportsGroupProcessingTrait
return $return;
}
+
+ private function recalculateCredit(Collection $accounts): void
+ {
+ Log::debug(sprintf('Will now recalculateCredit for %d account(s)', $accounts->count()));
+
+ /** @var CreditRecalculateService $object */
+ $object = app(CreditRecalculateService::class);
+ $object->setAccounts($accounts);
+ $object->recalculate();
+ Log::debug(sprintf('Done with recalculateCredit for %d account(s)', $accounts->count()));
+ }
}
diff --git a/app/Listeners/Security/System/HandlesNewUserRegistration.php b/app/Listeners/Security/System/HandlesNewUserRegistration.php
index ff06b3a786..e3054d9d79 100644
--- a/app/Listeners/Security/System/HandlesNewUserRegistration.php
+++ b/app/Listeners/Security/System/HandlesNewUserRegistration.php
@@ -64,6 +64,15 @@ class HandlesNewUserRegistration implements ShouldQueue
}
}
+ /**
+ * @SuppressWarnings("PHPMD.UnusedFormalParameter")
+ */
+ private function createExchangeRates(): void
+ {
+ $seeder = new ExchangeRateSeeder();
+ $seeder->run();
+ }
+
/**
* @throws FireflyException
*/
@@ -101,15 +110,6 @@ class HandlesNewUserRegistration implements ShouldQueue
$user->save();
}
- /**
- * @SuppressWarnings("PHPMD.UnusedFormalParameter")
- */
- private function createExchangeRates(): void
- {
- $seeder = new ExchangeRateSeeder();
- $seeder->run();
- }
-
private function sendAdminRegistrationNotification(User $user, OwnerNotifiable $owner): void
{
$sendMail = (bool) FireflyConfig::get('notification_admin_new_reg', true)->data;
diff --git a/app/Listeners/Security/System/NotifiesAboutNewInvitation.php b/app/Listeners/Security/System/NotifiesAboutNewInvitation.php
index ae0f293667..807d81c46e 100644
--- a/app/Listeners/Security/System/NotifiesAboutNewInvitation.php
+++ b/app/Listeners/Security/System/NotifiesAboutNewInvitation.php
@@ -45,6 +45,16 @@ class NotifiesAboutNewInvitation implements ShouldQueue
$this->sendRegistrationInvite($event->invitee);
}
+ private function sendInvitationNotification(InvitedUser $invitee): void
+ {
+ $sendMail = FireflyConfig::get('notification_invite_created', true)->data;
+ if (false === $sendMail) {
+ return;
+ }
+
+ NotificationSender::send(new OwnerNotifiable(), new UserInvitation($invitee));
+ }
+
private function sendRegistrationInvite(InvitedUser $invitee): void
{
$email = $invitee->email;
@@ -60,14 +70,4 @@ class NotifiesAboutNewInvitation implements ShouldQueue
throw new FireflyException($e->getMessage(), 0, $e);
}
}
-
- private function sendInvitationNotification(InvitedUser $invitee): void
- {
- $sendMail = FireflyConfig::get('notification_invite_created', true)->data;
- if (false === $sendMail) {
- return;
- }
-
- NotificationSender::send(new OwnerNotifiable(), new UserInvitation($invitee));
- }
}
diff --git a/app/Listeners/System/RecalculatesPrimaryCurrencyAmounts.php b/app/Listeners/System/RecalculatesPrimaryCurrencyAmounts.php
index 8b9fee70cf..295a0a7f32 100644
--- a/app/Listeners/System/RecalculatesPrimaryCurrencyAmounts.php
+++ b/app/Listeners/System/RecalculatesPrimaryCurrencyAmounts.php
@@ -92,6 +92,20 @@ class RecalculatesPrimaryCurrencyAmounts
}
}
+ private function resetBudgets(UserGroup $userGroup): void
+ {
+ $repository = app(BudgetRepositoryInterface::class);
+ $repository->setUserGroup($userGroup);
+ $set = $repository->getBudgets();
+
+ Log::debug(sprintf('Reset primary currency of %d budget(s).', $set->count()));
+
+ /** @var Budget $budget */
+ foreach ($set as $budget) {
+ $this->resetBudget($budget);
+ }
+ }
+
private function resetPiggyBank(PiggyBank $piggyBank): void
{
if ('' !== (string) $piggyBank->native_target_amount) {
@@ -115,6 +129,19 @@ class RecalculatesPrimaryCurrencyAmounts
}
}
+ private function resetPiggyBanks(UserGroup $userGroup): void
+ {
+ $repository = app(PiggyBankRepositoryInterface::class);
+ $repository->setUserGroup($userGroup);
+ $piggyBanks = $repository->getPiggyBanks();
+ Log::debug(sprintf('Reset primary currency of %d piggy bank(s).', $piggyBanks->count()));
+
+ /** @var PiggyBank $piggyBank */
+ foreach ($piggyBanks as $piggyBank) {
+ $this->resetPiggyBank($piggyBank);
+ }
+ }
+
private function resetTransactions(UserGroup $userGroup): void
{
// custom query because of the potential size of this update.
@@ -133,31 +160,4 @@ class RecalculatesPrimaryCurrencyAmounts
;
Log::debug(sprintf('Reset %d transactions.', $success));
}
-
- private function resetPiggyBanks(UserGroup $userGroup): void
- {
- $repository = app(PiggyBankRepositoryInterface::class);
- $repository->setUserGroup($userGroup);
- $piggyBanks = $repository->getPiggyBanks();
- Log::debug(sprintf('Reset primary currency of %d piggy bank(s).', $piggyBanks->count()));
-
- /** @var PiggyBank $piggyBank */
- foreach ($piggyBanks as $piggyBank) {
- $this->resetPiggyBank($piggyBank);
- }
- }
-
- private function resetBudgets(UserGroup $userGroup): void
- {
- $repository = app(BudgetRepositoryInterface::class);
- $repository->setUserGroup($userGroup);
- $set = $repository->getBudgets();
-
- Log::debug(sprintf('Reset primary currency of %d budget(s).', $set->count()));
-
- /** @var Budget $budget */
- foreach ($set as $budget) {
- $this->resetBudget($budget);
- }
- }
}
diff --git a/app/Models/Account.php b/app/Models/Account.php
index 3a6f89952e..4888430ee3 100644
--- a/app/Models/Account.php
+++ b/app/Models/Account.php
@@ -81,14 +81,14 @@ class Account extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
+ public function accountBalances(): HasMany
{
- return $this->belongsTo(User::class);
+ return $this->hasMany(AccountBalance::class);
}
- public function accountBalances(): HasMany
+ public function accountMeta(): HasMany
{
- return $this->hasMany(AccountBalance::class);
+ return $this->hasMany(AccountMeta::class);
}
public function accountType(): BelongsTo
@@ -127,6 +127,11 @@ class Account extends Model
return $this->belongsToMany(PiggyBank::class);
}
+ public function primaryPeriodStatistics(): MorphMany
+ {
+ return $this->morphMany(PeriodStatistic::class, 'primary_statable');
+ }
+
public function setVirtualBalanceAttribute(mixed $value): void
{
$value = (string) $value;
@@ -141,6 +146,11 @@ class Account extends Model
return $this->hasMany(Transaction::class);
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
public function userGroup(): BelongsTo
{
return $this->belongsTo(UserGroup::class);
@@ -164,11 +174,6 @@ class Account extends Model
});
}
- public function accountMeta(): HasMany
- {
- return $this->hasMany(AccountMeta::class);
- }
-
/**
* Get the user ID
*/
@@ -231,9 +236,4 @@ class Account extends Model
{
return Attribute::make(get: static fn ($value): string => (string) $value);
}
-
- public function primaryPeriodStatistics(): MorphMany
- {
- return $this->morphMany(PeriodStatistic::class, 'primary_statable');
- }
}
diff --git a/app/Models/Attachment.php b/app/Models/Attachment.php
index 898afa613c..b692264aea 100644
--- a/app/Models/Attachment.php
+++ b/app/Models/Attachment.php
@@ -83,11 +83,6 @@ class Attachment extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
/**
* Get all of the owning attachable models.
*/
@@ -112,6 +107,11 @@ class Attachment extends Model
return $this->morphMany(Note::class, 'noteable');
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
protected function attachableId(): Attribute
{
return Attribute::make(get: static fn ($value): int => (int) $value);
diff --git a/app/Models/AvailableBudget.php b/app/Models/AvailableBudget.php
index 16e86ab99f..056e0d5dc0 100644
--- a/app/Models/AvailableBudget.php
+++ b/app/Models/AvailableBudget.php
@@ -80,14 +80,14 @@ class AvailableBudget extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
+ public function transactionCurrency(): BelongsTo
{
- return $this->belongsTo(User::class);
+ return $this->belongsTo(TransactionCurrency::class);
}
- public function transactionCurrency(): BelongsTo
+ public function user(): BelongsTo
{
- return $this->belongsTo(TransactionCurrency::class);
+ return $this->belongsTo(User::class);
}
protected function amount(): Attribute
diff --git a/app/Models/Bill.php b/app/Models/Bill.php
index fdd13a2631..3f4563f8bd 100644
--- a/app/Models/Bill.php
+++ b/app/Models/Bill.php
@@ -95,11 +95,6 @@ class Bill extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
public function attachments(): MorphMany
{
return $this->morphMany(Attachment::class, 'attachable');
@@ -147,6 +142,11 @@ class Bill extends Model
return $this->hasMany(TransactionJournal::class);
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
/**
* Get the max amount
*/
diff --git a/app/Models/Budget.php b/app/Models/Budget.php
index 98ead22ba0..73c54cef6b 100644
--- a/app/Models/Budget.php
+++ b/app/Models/Budget.php
@@ -71,11 +71,6 @@ class Budget extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
public function attachments(): MorphMany
{
return $this->morphMany(Attachment::class, 'attachable');
@@ -99,6 +94,11 @@ class Budget extends Model
return $this->morphMany(Note::class, 'noteable');
}
+ public function primaryPeriodStatistics(): MorphMany
+ {
+ return $this->morphMany(PeriodStatistic::class, 'primary_statable');
+ }
+
public function transactionJournals(): BelongsToMany
{
return $this->belongsToMany(TransactionJournal::class, 'budget_transaction_journal', 'budget_id');
@@ -109,6 +109,11 @@ class Budget extends Model
return $this->belongsToMany(Transaction::class, 'budget_transaction', 'budget_id');
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
protected function casts(): array
{
return [
@@ -126,9 +131,4 @@ class Budget extends Model
{
return Attribute::make(get: static fn ($value): int => (int) $value);
}
-
- public function primaryPeriodStatistics(): MorphMany
- {
- return $this->morphMany(PeriodStatistic::class, 'primary_statable');
- }
}
diff --git a/app/Models/Category.php b/app/Models/Category.php
index 937f443958..6d8cc4e360 100644
--- a/app/Models/Category.php
+++ b/app/Models/Category.php
@@ -73,11 +73,6 @@ class Category extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
public function attachments(): MorphMany
{
return $this->morphMany(Attachment::class, 'attachable');
@@ -91,6 +86,11 @@ class Category extends Model
return $this->morphMany(Note::class, 'noteable');
}
+ public function primaryPeriodStatistics(): MorphMany
+ {
+ return $this->morphMany(PeriodStatistic::class, 'primary_statable');
+ }
+
public function transactionJournals(): BelongsToMany
{
return $this->belongsToMany(TransactionJournal::class, 'category_transaction_journal', 'category_id');
@@ -101,6 +101,11 @@ class Category extends Model
return $this->belongsToMany(Transaction::class, 'category_transaction', 'category_id');
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
protected function casts(): array
{
return [
@@ -112,9 +117,4 @@ class Category extends Model
'user_group_id' => 'integer',
];
}
-
- public function primaryPeriodStatistics(): MorphMany
- {
- return $this->morphMany(PeriodStatistic::class, 'primary_statable');
- }
}
diff --git a/app/Models/ObjectGroup.php b/app/Models/ObjectGroup.php
index eb0f5e4ac9..1e6ac321f0 100644
--- a/app/Models/ObjectGroup.php
+++ b/app/Models/ObjectGroup.php
@@ -63,11 +63,6 @@ class ObjectGroup extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
/**
* @return MorphToMany
*/
@@ -92,6 +87,11 @@ class ObjectGroup extends Model
return $this->morphedByMany(PiggyBank::class, 'object_groupable');
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
protected function casts(): array
{
return [
diff --git a/app/Models/PeriodStatistic.php b/app/Models/PeriodStatistic.php
index 9a9e9d158b..e80612e2ad 100644
--- a/app/Models/PeriodStatistic.php
+++ b/app/Models/PeriodStatistic.php
@@ -15,38 +15,38 @@ class PeriodStatistic extends Model
{
use ReturnsIntegerUserIdTrait;
- protected function casts(): array
+ public function primaryStatable(): MorphTo
{
- return [
- 'created_at' => 'datetime',
- 'updated_at' => 'datetime',
- 'start' => SeparateTimezoneCaster::class,
- 'end' => SeparateTimezoneCaster::class,
- ];
+ return $this->morphTo();
}
- public function userGroup(): BelongsTo
+ public function secondaryStatable(): MorphTo
{
- return $this->belongsTo(UserGroup::class);
+ return $this->morphTo();
}
- protected function count(): Attribute
+ public function tertiaryStatable(): MorphTo
{
- return Attribute::make(get: static fn ($value): int => (int) $value);
+ return $this->morphTo();
}
- public function primaryStatable(): MorphTo
+ public function userGroup(): BelongsTo
{
- return $this->morphTo();
+ return $this->belongsTo(UserGroup::class);
}
- public function secondaryStatable(): MorphTo
+ protected function casts(): array
{
- return $this->morphTo();
+ return [
+ 'created_at' => 'datetime',
+ 'updated_at' => 'datetime',
+ 'start' => SeparateTimezoneCaster::class,
+ 'end' => SeparateTimezoneCaster::class,
+ ];
}
- public function tertiaryStatable(): MorphTo
+ protected function count(): Attribute
{
- return $this->morphTo();
+ return Attribute::make(get: static fn ($value): int => (int) $value);
}
}
diff --git a/app/Models/Recurrence.php b/app/Models/Recurrence.php
index aaf5826769..3a079e8f12 100644
--- a/app/Models/Recurrence.php
+++ b/app/Models/Recurrence.php
@@ -95,11 +95,6 @@ class Recurrence extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
public function attachments(): MorphMany
{
return $this->morphMany(Attachment::class, 'attachable');
@@ -138,6 +133,11 @@ class Recurrence extends Model
return $this->belongsTo(TransactionType::class);
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
protected function casts(): array
{
return [
diff --git a/app/Models/Rule.php b/app/Models/Rule.php
index c8bf52fe7f..9a241e4f7a 100644
--- a/app/Models/Rule.php
+++ b/app/Models/Rule.php
@@ -73,11 +73,6 @@ class Rule extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
public function ruleActions(): HasMany
{
return $this->hasMany(RuleAction::class);
@@ -93,6 +88,11 @@ class Rule extends Model
return $this->hasMany(RuleTrigger::class);
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
public function userGroup(): BelongsTo
{
return $this->belongsTo(UserGroup::class);
diff --git a/app/Models/RuleGroup.php b/app/Models/RuleGroup.php
index 9c1aa35fda..3f07e5d0bc 100644
--- a/app/Models/RuleGroup.php
+++ b/app/Models/RuleGroup.php
@@ -75,14 +75,14 @@ class RuleGroup extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
+ public function rules(): HasMany
{
- return $this->belongsTo(User::class);
+ return $this->hasMany(Rule::class);
}
- public function rules(): HasMany
+ public function user(): BelongsTo
{
- return $this->hasMany(Rule::class);
+ return $this->belongsTo(User::class);
}
protected function casts(): array
diff --git a/app/Models/Tag.php b/app/Models/Tag.php
index 94e31c6855..92e4496c02 100644
--- a/app/Models/Tag.php
+++ b/app/Models/Tag.php
@@ -73,11 +73,6 @@ class Tag extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
public function attachments(): MorphMany
{
return $this->morphMany(Attachment::class, 'attachable');
@@ -88,11 +83,21 @@ class Tag extends Model
return $this->morphMany(Location::class, 'locatable');
}
+ public function primaryPeriodStatistics(): MorphMany
+ {
+ return $this->morphMany(PeriodStatistic::class, 'primary_statable');
+ }
+
public function transactionJournals(): BelongsToMany
{
return $this->belongsToMany(TransactionJournal::class);
}
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
protected function casts(): array
{
return [
@@ -107,9 +112,4 @@ class Tag extends Model
'user_group_id' => 'integer',
];
}
-
- public function primaryPeriodStatistics(): MorphMany
- {
- return $this->morphMany(PeriodStatistic::class, 'primary_statable');
- }
}
diff --git a/app/Models/Transaction.php b/app/Models/Transaction.php
index 5a20bf7492..6b35261c96 100644
--- a/app/Models/Transaction.php
+++ b/app/Models/Transaction.php
@@ -59,6 +59,22 @@ class Transaction extends Model
protected $hidden = ['encrypted'];
+ /**
+ * Check if a table is joined.
+ */
+ public static function isJoined(Builder $query, string $table): bool
+ {
+ $joins = $query->getQuery()->joins;
+
+ foreach ($joins as $join) {
+ if ($join->table === $table) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
/**
* Get the account this object belongs to.
*/
@@ -126,22 +142,6 @@ class Transaction extends Model
$query->where('transaction_journals.date', '>=', $date->format('Y-m-d 00:00:00'));
}
- /**
- * Check if a table is joined.
- */
- public static function isJoined(Builder $query, string $table): bool
- {
- $joins = $query->getQuery()->joins;
-
- foreach ($joins as $join) {
- if ($join->table === $table) {
- return true;
- }
- }
-
- return false;
- }
-
/**
* Get the amount
*/
diff --git a/app/Models/TransactionCurrency.php b/app/Models/TransactionCurrency.php
index 5a8582e6f6..a7b953760b 100644
--- a/app/Models/TransactionCurrency.php
+++ b/app/Models/TransactionCurrency.php
@@ -66,6 +66,11 @@ class TransactionCurrency extends Model
throw new NotFoundHttpException();
}
+ public function budgetLimits(): HasMany
+ {
+ return $this->hasMany(BudgetLimit::class);
+ }
+
public function refreshForUser(User $user): void
{
$current = $user->userGroup->currencies()->where('transaction_currencies.id', $this->id)->first();
@@ -74,11 +79,6 @@ class TransactionCurrency extends Model
$this->userGroupEnabled = null !== $current;
}
- public function budgetLimits(): HasMany
- {
- return $this->hasMany(BudgetLimit::class);
- }
-
public function transactionJournals(): HasMany
{
return $this->hasMany(TransactionJournal::class);
diff --git a/app/Models/TransactionGroup.php b/app/Models/TransactionGroup.php
index a78585d536..bae17696e3 100644
--- a/app/Models/TransactionGroup.php
+++ b/app/Models/TransactionGroup.php
@@ -86,14 +86,14 @@ class TransactionGroup extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
+ public function transactionJournals(): HasMany
{
- return $this->belongsTo(User::class);
+ return $this->hasMany(TransactionJournal::class);
}
- public function transactionJournals(): HasMany
+ public function user(): BelongsTo
{
- return $this->hasMany(TransactionJournal::class);
+ return $this->belongsTo(User::class);
}
public function userGroup(): BelongsTo
diff --git a/app/Models/TransactionJournal.php b/app/Models/TransactionJournal.php
index 295bc84aaa..696c18494c 100644
--- a/app/Models/TransactionJournal.php
+++ b/app/Models/TransactionJournal.php
@@ -74,6 +74,21 @@ class TransactionJournal extends Model
protected $hidden = ['encrypted'];
+ /**
+ * Checks if tables are joined.
+ */
+ public static function isJoined(EloquentBuilder $query, string $table): bool
+ {
+ $joins = $query->getQuery()->joins;
+ foreach ($joins as $join) {
+ if ($join->table === $table) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
/**
* Route binder. Converts the key in the URL to the specified object (or throw 404).
*
@@ -100,11 +115,6 @@ class TransactionJournal extends Model
throw new NotFoundHttpException();
}
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
public function attachments(): MorphMany
{
return $this->morphMany(Attachment::class, 'attachable');
@@ -197,14 +207,19 @@ class TransactionJournal extends Model
return $this->hasMany(TransactionJournalMeta::class);
}
+ public function transactions(): HasMany
+ {
+ return $this->hasMany(Transaction::class);
+ }
+
public function transactionType(): BelongsTo
{
return $this->belongsTo(TransactionType::class);
}
- public function transactions(): HasMany
+ public function user(): BelongsTo
{
- return $this->hasMany(Transaction::class);
+ return $this->belongsTo(User::class);
}
public function userGroup(): BelongsTo
@@ -251,19 +266,4 @@ class TransactionJournal extends Model
$query->whereIn('transaction_types.type', $types);
}
}
-
- /**
- * Checks if tables are joined.
- */
- public static function isJoined(EloquentBuilder $query, string $table): bool
- {
- $joins = $query->getQuery()->joins;
- foreach ($joins as $join) {
- if ($join->table === $table) {
- return true;
- }
- }
-
- return false;
- }
}
diff --git a/app/Models/UserGroup.php b/app/Models/UserGroup.php
index 47fa04f4bb..08e1efb9f5 100644
--- a/app/Models/UserGroup.php
+++ b/app/Models/UserGroup.php
@@ -80,14 +80,6 @@ class UserGroup extends Model
return $this->hasMany(Account::class);
}
- /**
- * Link to accounts.
- */
- public function periodStatistics(): HasMany
- {
- return $this->hasMany(PeriodStatistic::class);
- }
-
/**
* Link to attachments.
*/
@@ -154,6 +146,14 @@ class UserGroup extends Model
return $this->hasMany(ObjectGroup::class);
}
+ /**
+ * Link to accounts.
+ */
+ public function periodStatistics(): HasMany
+ {
+ return $this->hasMany(PeriodStatistic::class);
+ }
+
/**
* Link to piggy banks.
*/
diff --git a/app/Notifications/User/BillReminder.php b/app/Notifications/User/BillReminder.php
index c0e6cea97d..742a1ed852 100644
--- a/app/Notifications/User/BillReminder.php
+++ b/app/Notifications/User/BillReminder.php
@@ -65,15 +65,6 @@ class BillReminder extends Notification
;
}
- private function getSubject(): string
- {
- if (0 === $this->diff) {
- return (string) trans(sprintf('email.bill_warning_subject_now_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]);
- }
-
- return (string) trans(sprintf('email.bill_warning_subject_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]);
- }
-
// public function toNtfy(User $notifiable): Message
// {
// $settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
@@ -117,4 +108,13 @@ class BillReminder extends Notification
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
+
+ private function getSubject(): string
+ {
+ if (0 === $this->diff) {
+ return (string) trans(sprintf('email.bill_warning_subject_now_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]);
+ }
+
+ return (string) trans(sprintf('email.bill_warning_subject_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]);
+ }
}
diff --git a/app/Notifications/User/SubscriptionsOverdueReminder.php b/app/Notifications/User/SubscriptionsOverdueReminder.php
index dfda7bb422..a5fe00757d 100644
--- a/app/Notifications/User/SubscriptionsOverdueReminder.php
+++ b/app/Notifications/User/SubscriptionsOverdueReminder.php
@@ -72,15 +72,6 @@ class SubscriptionsOverdueReminder extends Notification
;
}
- private function getSubject(): string
- {
- if (count($this->overdue) > 1) {
- return (string) trans('email.subscriptions_overdue_subject_multi', ['count' => count($this->overdue)]);
- }
-
- return (string) trans('email.subscriptions_overdue_subject_single');
- }
-
// public function toNtfy(User $notifiable): Message
// {
// $settings = ReturnsSettings::getSettings('ntfy', 'user', $notifiable);
@@ -123,4 +114,13 @@ class SubscriptionsOverdueReminder extends Notification
{
return ReturnsAvailableChannels::returnChannels('user', $notifiable);
}
+
+ private function getSubject(): string
+ {
+ if (count($this->overdue) > 1) {
+ return (string) trans('email.subscriptions_overdue_subject_multi', ['count' => count($this->overdue)]);
+ }
+
+ return (string) trans('email.subscriptions_overdue_subject_single');
+ }
}
diff --git a/app/Policies/AccountPolicy.php b/app/Policies/AccountPolicy.php
index 7897ca32bc..bd08035f36 100644
--- a/app/Policies/AccountPolicy.php
+++ b/app/Policies/AccountPolicy.php
@@ -35,11 +35,6 @@ class AccountPolicy
return auth()->check();
}
- public function viewAccountBalances(User $user, Account $account): bool
- {
- return $this->view($user, $account);
- }
-
/**
* TODO needs better authentication, also for group.
*/
@@ -48,6 +43,11 @@ class AccountPolicy
return auth()->check() && $user->id === $account->user_id;
}
+ public function viewAccountBalances(User $user, Account $account): bool
+ {
+ return $this->view($user, $account);
+ }
+
/**
* Everybody can do this, but selection should limit to user.
*/
diff --git a/app/Providers/FireflySessionProvider.php b/app/Providers/FireflySessionProvider.php
index 9cdc725c67..2e9eb7e1a9 100644
--- a/app/Providers/FireflySessionProvider.php
+++ b/app/Providers/FireflySessionProvider.php
@@ -46,14 +46,6 @@ class FireflySessionProvider extends ServiceProvider
$this->app->singleton(StartFireflySession::class);
}
- /**
- * Register the session manager instance.
- */
- protected function registerSessionManager(): void
- {
- $this->app->singleton('session', static fn ($app): SessionManager => new SessionManager($app));
- }
-
/**
* Register the session driver instance.
*/
@@ -66,4 +58,12 @@ class FireflySessionProvider extends ServiceProvider
=> $app->make('session')->driver()
);
}
+
+ /**
+ * Register the session manager instance.
+ */
+ protected function registerSessionManager(): void
+ {
+ $this->app->singleton('session', static fn ($app): SessionManager => new SessionManager($app));
+ }
}
diff --git a/app/Providers/JournalServiceProvider.php b/app/Providers/JournalServiceProvider.php
index 6305ada76b..2eaefa317e 100644
--- a/app/Providers/JournalServiceProvider.php
+++ b/app/Providers/JournalServiceProvider.php
@@ -58,6 +58,35 @@ class JournalServiceProvider extends ServiceProvider
$this->registerGroupCollector();
}
+ private function registerGroupCollector(): void
+ {
+ $this->app->bind(static function (Application $app): GroupCollectorInterface {
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollector::class);
+ if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth)
+ $collector->setUser(auth()->user());
+ }
+
+ return $collector;
+ });
+ }
+
+ /**
+ * Register group repos.
+ */
+ private function registerGroupRepository(): void
+ {
+ $this->app->bind(static function (Application $app): TransactionGroupRepositoryInterface {
+ /** @var TransactionGroupRepositoryInterface $repository */
+ $repository = app(TransactionGroupRepository::class);
+ if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth)
+ $repository->setUser(auth()->user());
+ }
+
+ return $repository;
+ });
+ }
+
/**
* Register repository.
*/
@@ -95,33 +124,4 @@ class JournalServiceProvider extends ServiceProvider
return $repository;
});
}
-
- /**
- * Register group repos.
- */
- private function registerGroupRepository(): void
- {
- $this->app->bind(static function (Application $app): TransactionGroupRepositoryInterface {
- /** @var TransactionGroupRepositoryInterface $repository */
- $repository = app(TransactionGroupRepository::class);
- if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth)
- $repository->setUser(auth()->user());
- }
-
- return $repository;
- });
- }
-
- private function registerGroupCollector(): void
- {
- $this->app->bind(static function (Application $app): GroupCollectorInterface {
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollector::class);
- if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth)
- $collector->setUser(auth()->user());
- }
-
- return $collector;
- });
- }
}
diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php
index 63dfcbfe56..c19476ed37 100644
--- a/app/Repositories/Account/AccountRepository.php
+++ b/app/Repositories/Account/AccountRepository.php
@@ -58,6 +58,15 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
{
use UserGroupTrait;
+ public function count(array $types): int
+ {
+ return $this->user
+ ->accounts()
+ ->accountTypeIn($types)
+ ->count()
+ ;
+ }
+
/**
* Moved here from account CRUD.
*/
@@ -111,6 +120,12 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return $result;
}
+ public function find(int $accountId): ?Account
+ {
+ /** @var null|Account */
+ return $this->user->accounts()->find($accountId);
+ }
+
public function findByAccountNumber(string $number, array $types): ?Account
{
$dbQuery = $this->user
@@ -175,12 +190,21 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return $account;
}
- /**
- * Return account type or null if not found.
- */
- public function getAccountTypeByType(string $type): ?AccountType
+ public function getAccountCurrency(Account $account): ?TransactionCurrency
{
- return AccountType::whereType(ucfirst($type))->first();
+ $type = $account->accountType->type;
+ $list = config('firefly.valid_currency_account_types');
+
+ // return null if not in this list.
+ if (!in_array($type, $list, true)) {
+ return null;
+ }
+ $currencyId = (int) $this->getMetaValue($account, 'currency_id');
+ if ($currencyId > 0) {
+ return Amount::getTransactionCurrencyById($currencyId);
+ }
+
+ return null;
}
public function getAccountsById(array $accountIds): Collection
@@ -197,6 +221,52 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return $query->get(['accounts.*']);
}
+ public function getAccountsByType(array $types, ?array $sort = []): Collection
+ {
+ $res = array_intersect([
+ AccountTypeEnum::ASSET->value,
+ AccountTypeEnum::MORTGAGE->value,
+ AccountTypeEnum::LOAN->value,
+ AccountTypeEnum::DEBT->value,
+ ], $types);
+ $query = $this->user->accounts();
+ if (0 !== count($types)) {
+ $query->accountTypeIn($types);
+ }
+
+ // add sort parameters
+ $allowed = config('firefly.allowed_db_sort_parameters.Account', []);
+ $sorted = 0;
+ if (0 !== count($sort)) {
+ foreach ($sort as $param) {
+ if (in_array($param[0], $allowed, true)) {
+ $query->orderBy($param[0], $param[1]);
+ ++$sorted;
+ }
+ }
+ }
+
+ if (0 === $sorted) {
+ if (0 !== count($res)) {
+ $query->orderBy('accounts.order', 'ASC');
+ }
+ $query->orderBy('accounts.active', 'DESC');
+ $query->orderBy('accounts.name', 'ASC');
+ $query->orderBy('accounts.account_type_id', 'ASC');
+ $query->orderBy('accounts.id', 'ASC');
+ }
+
+ return $query->get(['accounts.*']);
+ }
+
+ /**
+ * Return account type or null if not found.
+ */
+ public function getAccountTypeByType(string $type): ?AccountType
+ {
+ return AccountType::whereType(ucfirst($type))->first();
+ }
+
public function getActiveAccountsByType(array $types): Collection
{
$query = $this->user
@@ -286,6 +356,22 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return $account->locations()->first();
}
+ /**
+ * Return meta value for account. Null if not found.
+ */
+ public function getMetaValue(Account $account, string $field): ?string
+ {
+ $result = $account->accountMeta->filter(static fn (AccountMeta $meta): bool => strtolower($meta->name) === strtolower($field));
+ if (0 === $result->count()) {
+ return null;
+ }
+ if (1 === $result->count()) {
+ return (string) $result->first()->data;
+ }
+
+ return null;
+ }
+
/**
* Get note text or null.
*/
@@ -294,6 +380,15 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return $account->notes()->first()?->text;
}
+ public function getOpeningBalance(Account $account): ?TransactionJournal
+ {
+ return TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
+ ->where('transactions.account_id', $account->id)
+ ->transactionTypes([TransactionTypeEnum::OPENING_BALANCE->value])
+ ->first(['transaction_journals.*'])
+ ;
+ }
+
/**
* Returns the amount of the opening balance for this account.
*/
@@ -338,15 +433,6 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return $journal?->transactionGroup;
}
- public function getOpeningBalance(Account $account): ?TransactionJournal
- {
- return TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
- ->where('transactions.account_id', $account->id)
- ->transactionTypes([TransactionTypeEnum::OPENING_BALANCE->value])
- ->first(['transaction_journals.*'])
- ;
- }
-
public function getPiggyBanks(Account $account): Collection
{
return $account->piggyBanks()->get();
@@ -394,54 +480,6 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return $factory->create($data);
}
- public function getAccountCurrency(Account $account): ?TransactionCurrency
- {
- $type = $account->accountType->type;
- $list = config('firefly.valid_currency_account_types');
-
- // return null if not in this list.
- if (!in_array($type, $list, true)) {
- return null;
- }
- $currencyId = (int) $this->getMetaValue($account, 'currency_id');
- if ($currencyId > 0) {
- return Amount::getTransactionCurrencyById($currencyId);
- }
-
- return null;
- }
-
- /**
- * Return meta value for account. Null if not found.
- */
- public function getMetaValue(Account $account, string $field): ?string
- {
- $result = $account->accountMeta->filter(static fn (AccountMeta $meta): bool => strtolower($meta->name) === strtolower($field));
- if (0 === $result->count()) {
- return null;
- }
- if (1 === $result->count()) {
- return (string) $result->first()->data;
- }
-
- return null;
- }
-
- public function count(array $types): int
- {
- return $this->user
- ->accounts()
- ->accountTypeIn($types)
- ->count()
- ;
- }
-
- public function find(int $accountId): ?Account
- {
- /** @var null|Account */
- return $this->user->accounts()->find($accountId);
- }
-
public function getUsedCurrencies(Account $account): Collection
{
$info = $account->transactions()->distinct()->groupBy('transaction_currency_id')->get(['transaction_currency_id'])->toArray();
@@ -507,54 +545,6 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return $order;
}
- public function getAccountsByType(array $types, ?array $sort = []): Collection
- {
- $res = array_intersect([
- AccountTypeEnum::ASSET->value,
- AccountTypeEnum::MORTGAGE->value,
- AccountTypeEnum::LOAN->value,
- AccountTypeEnum::DEBT->value,
- ], $types);
- $query = $this->user->accounts();
- if (0 !== count($types)) {
- $query->accountTypeIn($types);
- }
-
- // add sort parameters
- $allowed = config('firefly.allowed_db_sort_parameters.Account', []);
- $sorted = 0;
- if (0 !== count($sort)) {
- foreach ($sort as $param) {
- if (in_array($param[0], $allowed, true)) {
- $query->orderBy($param[0], $param[1]);
- ++$sorted;
- }
- }
- }
-
- if (0 === $sorted) {
- if (0 !== count($res)) {
- $query->orderBy('accounts.order', 'ASC');
- }
- $query->orderBy('accounts.active', 'DESC');
- $query->orderBy('accounts.name', 'ASC');
- $query->orderBy('accounts.account_type_id', 'ASC');
- $query->orderBy('accounts.id', 'ASC');
- }
-
- return $query->get(['accounts.*']);
- }
-
- /**
- * Returns the date of the very first transaction in this account.
- */
- public function oldestJournalDate(Account $account): ?Carbon
- {
- $journal = $this->oldestJournal($account);
-
- return $journal?->date;
- }
-
/**
* Returns the date of the very first transaction in this account.
*/
@@ -578,6 +568,16 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return null;
}
+ /**
+ * Returns the date of the very first transaction in this account.
+ */
+ public function oldestJournalDate(Account $account): ?Carbon
+ {
+ $journal = $this->oldestJournal($account);
+
+ return $journal?->date;
+ }
+
#[Override]
public function periodCollection(Account $account, Carbon $start, Carbon $end): array
{
@@ -661,17 +661,6 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
;
}
- /**
- * @throws FireflyException
- */
- public function update(Account $account, array $data): Account
- {
- /** @var AccountUpdateService $service */
- $service = app(AccountUpdateService::class);
-
- return $service->update($account, $data);
- }
-
public function searchAccount(string $query, array $types, int $limit): Collection
{
$dbQuery = $this->user
@@ -743,4 +732,15 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
return $factory->create($data);
}
+
+ /**
+ * @throws FireflyException
+ */
+ public function update(Account $account, array $data): Account
+ {
+ /** @var AccountUpdateService $service */
+ $service = app(AccountUpdateService::class);
+
+ return $service->update($account, $data);
+ }
}
diff --git a/app/Repositories/Account/AccountRepositoryInterface.php b/app/Repositories/Account/AccountRepositoryInterface.php
index 43b3334f15..4513fc4bfb 100644
--- a/app/Repositories/Account/AccountRepositoryInterface.php
+++ b/app/Repositories/Account/AccountRepositoryInterface.php
@@ -73,11 +73,6 @@ interface AccountRepositoryInterface
public function getAccountCurrency(Account $account): ?TransactionCurrency;
- /**
- * Return account type or null if not found.
- */
- public function getAccountTypeByType(string $type): ?AccountType;
-
public function getAccountsById(array $accountIds): Collection;
/**
@@ -85,6 +80,11 @@ interface AccountRepositoryInterface
*/
public function getAccountsByType(array $types, ?array $sort = []): Collection;
+ /**
+ * Return account type or null if not found.
+ */
+ public function getAccountTypeByType(string $type): ?AccountType;
+
public function getActiveAccountsByType(array $types): Collection;
public function getAttachments(Account $account): Collection;
diff --git a/app/Repositories/Account/AccountTasker.php b/app/Repositories/Account/AccountTasker.php
index d5e8d011eb..e4e9c4cb77 100644
--- a/app/Repositories/Account/AccountTasker.php
+++ b/app/Repositories/Account/AccountTasker.php
@@ -144,6 +144,34 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface
return $report;
}
+ /**
+ * @throws FireflyException
+ */
+ public function getIncomeReport(Carbon $start, Carbon $end, Collection $accounts): array
+ {
+ // get all incomes for the given accounts in the given period!
+ // also transfers!
+ // get all transactions:
+
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->setDestinationAccounts($accounts)->setRange($start, $end);
+ $collector->excludeSourceAccounts($accounts);
+ $collector->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])->withAccountInformation();
+ $report = $this->groupIncomeBySource($collector->getExtractedJournals());
+
+ // sort the result
+ // Obtain a list of columns
+ $sum = [];
+ foreach ($report['accounts'] as $accountId => $row) {
+ $sum[$accountId] = (float) $row['sum']; // intentional float
+ }
+
+ array_multisort($sum, SORT_DESC, $report['accounts']);
+
+ return $report;
+ }
+
private function groupExpenseByDestination(array $array): array
{
$primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
@@ -198,34 +226,6 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface
return $report;
}
- /**
- * @throws FireflyException
- */
- public function getIncomeReport(Carbon $start, Carbon $end, Collection $accounts): array
- {
- // get all incomes for the given accounts in the given period!
- // also transfers!
- // get all transactions:
-
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->setDestinationAccounts($accounts)->setRange($start, $end);
- $collector->excludeSourceAccounts($accounts);
- $collector->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])->withAccountInformation();
- $report = $this->groupIncomeBySource($collector->getExtractedJournals());
-
- // sort the result
- // Obtain a list of columns
- $sum = [];
- foreach ($report['accounts'] as $accountId => $row) {
- $sum[$accountId] = (float) $row['sum']; // intentional float
- }
-
- array_multisort($sum, SORT_DESC, $report['accounts']);
-
- return $report;
- }
-
private function groupIncomeBySource(array $array): array
{
$primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
diff --git a/app/Repositories/Account/OperationsRepository.php b/app/Repositories/Account/OperationsRepository.php
index a81863f50b..e896c23a62 100644
--- a/app/Repositories/Account/OperationsRepository.php
+++ b/app/Repositories/Account/OperationsRepository.php
@@ -53,56 +53,6 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $this->sortByCurrency($journals, 'negative');
}
- /**
- * Collect transactions with some parameters
- */
- private function getTransactions(Carbon $start, Carbon $end, Collection $accounts, string $type): array
- {
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->setUser($this->user)->setRange($start, $end)->setTypes([$type]);
- $collector->setBothAccounts($accounts);
- $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation()->withTagInformation();
-
- return $collector->getExtractedJournals();
- }
-
- private function sortByCurrency(array $journals, string $direction): array
- {
- $array = [];
- foreach ($journals as $journal) {
- $currencyId = (int) $journal['currency_id'];
- $journalId = (int) $journal['transaction_journal_id'];
- $array[$currencyId] ??= [
- 'currency_id' => $journal['currency_id'],
- 'currency_name' => $journal['currency_name'],
- 'currency_symbol' => $journal['currency_symbol'],
- 'currency_code' => $journal['currency_code'],
- 'currency_decimal_places' => $journal['currency_decimal_places'],
- 'transaction_journals' => [],
- ];
-
- $array[$currencyId]['transaction_journals'][$journalId] = [
- 'amount' => Steam::{$direction}((string) $journal['amount']), // @phpstan-ignore-line
- 'date' => $journal['date'],
- 'transaction_journal_id' => $journalId,
- 'budget_name' => $journal['budget_name'],
- 'category_name' => $journal['category_name'],
- 'source_account_id' => $journal['source_account_id'],
- 'source_account_name' => $journal['source_account_name'],
- 'source_account_iban' => $journal['source_account_iban'],
- 'destination_account_id' => $journal['destination_account_id'],
- 'destination_account_name' => $journal['destination_account_name'],
- 'destination_account_iban' => $journal['destination_account_iban'],
- 'tags' => $journal['tags'],
- 'description' => $journal['description'],
- 'transaction_group_id' => $journal['transaction_group_id'],
- ];
- }
-
- return $array;
- }
-
/**
* This method returns a list of all the deposit transaction journals (as arrays) set in that period
* which have the specified accounts. It's grouped per currency, with as few details in the array
@@ -130,6 +80,102 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $this->groupByCurrency($journals, 'negative');
}
+ /**
+ * @SuppressWarnings("PHPMD.ExcessiveParameterList")
+ */
+ public function sumExpensesByDestination(
+ Carbon $start,
+ Carbon $end,
+ ?Collection $accounts = null,
+ ?Collection $expense = null,
+ ?TransactionCurrency $currency = null
+ ): array {
+ $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency);
+
+ return $this->groupByDirection($journals, 'destination', 'negative');
+ }
+
+ /**
+ * @SuppressWarnings("PHPMD.ExcessiveParameterList")
+ */
+ public function sumExpensesBySource(
+ Carbon $start,
+ Carbon $end,
+ ?Collection $accounts = null,
+ ?Collection $expense = null,
+ ?TransactionCurrency $currency = null
+ ): array {
+ $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency);
+
+ return $this->groupByDirection($journals, 'source', 'negative');
+ }
+
+ /**
+ * @SuppressWarnings("PHPMD.ExcessiveParameterList")
+ */
+ public function sumIncome(
+ Carbon $start,
+ Carbon $end,
+ ?Collection $accounts = null,
+ ?Collection $revenue = null,
+ ?TransactionCurrency $currency = null
+ ): array {
+ $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency);
+
+ return $this->groupByCurrency($journals, 'positive');
+ }
+
+ /**
+ * @SuppressWarnings("PHPMD.ExcessiveParameterList")
+ */
+ public function sumIncomeByDestination(
+ Carbon $start,
+ Carbon $end,
+ ?Collection $accounts = null,
+ ?Collection $revenue = null,
+ ?TransactionCurrency $currency = null
+ ): array {
+ $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency);
+
+ return $this->groupByDirection($journals, 'destination', 'positive');
+ }
+
+ /**
+ * @SuppressWarnings("PHPMD.ExcessiveParameterList")
+ */
+ public function sumIncomeBySource(
+ Carbon $start,
+ Carbon $end,
+ ?Collection $accounts = null,
+ ?Collection $revenue = null,
+ ?TransactionCurrency $currency = null
+ ): array {
+ $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency);
+
+ return $this->groupByDirection($journals, 'source', 'positive');
+ }
+
+ public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array
+ {
+ $journals = $this->getTransactionsForSum(TransactionTypeEnum::TRANSFER->value, $start, $end, $accounts, null, $currency);
+
+ return $this->groupByEither($journals);
+ }
+
+ /**
+ * Collect transactions with some parameters
+ */
+ private function getTransactions(Carbon $start, Carbon $end, Collection $accounts, string $type): array
+ {
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->setUser($this->user)->setRange($start, $end)->setTypes([$type]);
+ $collector->setBothAccounts($accounts);
+ $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation()->withTagInformation();
+
+ return $collector->getExtractedJournals();
+ }
+
/**
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
* @SuppressWarnings("PHPMD.NPathComplexity")
@@ -214,21 +260,6 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $summarizer->groupByCurrencyId($journals, $direction);
}
- /**
- * @SuppressWarnings("PHPMD.ExcessiveParameterList")
- */
- public function sumExpensesByDestination(
- Carbon $start,
- Carbon $end,
- ?Collection $accounts = null,
- ?Collection $expense = null,
- ?TransactionCurrency $currency = null
- ): array {
- $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency);
-
- return $this->groupByDirection($journals, 'destination', 'negative');
- }
-
private function groupByDirection(array $journals, string $direction, string $method): array
{
$summarizer = new TransactionSummarizer($this->user);
@@ -236,73 +267,6 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $summarizer->groupByDirection($journals, $method, $direction);
}
- /**
- * @SuppressWarnings("PHPMD.ExcessiveParameterList")
- */
- public function sumExpensesBySource(
- Carbon $start,
- Carbon $end,
- ?Collection $accounts = null,
- ?Collection $expense = null,
- ?TransactionCurrency $currency = null
- ): array {
- $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency);
-
- return $this->groupByDirection($journals, 'source', 'negative');
- }
-
- /**
- * @SuppressWarnings("PHPMD.ExcessiveParameterList")
- */
- public function sumIncome(
- Carbon $start,
- Carbon $end,
- ?Collection $accounts = null,
- ?Collection $revenue = null,
- ?TransactionCurrency $currency = null
- ): array {
- $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency);
-
- return $this->groupByCurrency($journals, 'positive');
- }
-
- /**
- * @SuppressWarnings("PHPMD.ExcessiveParameterList")
- */
- public function sumIncomeByDestination(
- Carbon $start,
- Carbon $end,
- ?Collection $accounts = null,
- ?Collection $revenue = null,
- ?TransactionCurrency $currency = null
- ): array {
- $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency);
-
- return $this->groupByDirection($journals, 'destination', 'positive');
- }
-
- /**
- * @SuppressWarnings("PHPMD.ExcessiveParameterList")
- */
- public function sumIncomeBySource(
- Carbon $start,
- Carbon $end,
- ?Collection $accounts = null,
- ?Collection $revenue = null,
- ?TransactionCurrency $currency = null
- ): array {
- $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency);
-
- return $this->groupByDirection($journals, 'source', 'positive');
- }
-
- public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array
- {
- $journals = $this->getTransactionsForSum(TransactionTypeEnum::TRANSFER->value, $start, $end, $accounts, null, $currency);
-
- return $this->groupByEither($journals);
- }
-
private function groupByEither(array $journals): array
{
$return = [];
@@ -413,4 +377,40 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $return;
}
+
+ private function sortByCurrency(array $journals, string $direction): array
+ {
+ $array = [];
+ foreach ($journals as $journal) {
+ $currencyId = (int) $journal['currency_id'];
+ $journalId = (int) $journal['transaction_journal_id'];
+ $array[$currencyId] ??= [
+ 'currency_id' => $journal['currency_id'],
+ 'currency_name' => $journal['currency_name'],
+ 'currency_symbol' => $journal['currency_symbol'],
+ 'currency_code' => $journal['currency_code'],
+ 'currency_decimal_places' => $journal['currency_decimal_places'],
+ 'transaction_journals' => [],
+ ];
+
+ $array[$currencyId]['transaction_journals'][$journalId] = [
+ 'amount' => Steam::{$direction}((string) $journal['amount']), // @phpstan-ignore-line
+ 'date' => $journal['date'],
+ 'transaction_journal_id' => $journalId,
+ 'budget_name' => $journal['budget_name'],
+ 'category_name' => $journal['category_name'],
+ 'source_account_id' => $journal['source_account_id'],
+ 'source_account_name' => $journal['source_account_name'],
+ 'source_account_iban' => $journal['source_account_iban'],
+ 'destination_account_id' => $journal['destination_account_id'],
+ 'destination_account_name' => $journal['destination_account_name'],
+ 'destination_account_iban' => $journal['destination_account_iban'],
+ 'tags' => $journal['tags'],
+ 'description' => $journal['description'],
+ 'transaction_group_id' => $journal['transaction_group_id'],
+ ];
+ }
+
+ return $array;
+ }
}
diff --git a/app/Repositories/Attachment/AttachmentRepository.php b/app/Repositories/Attachment/AttachmentRepository.php
index baef97884d..38a6dec3c2 100644
--- a/app/Repositories/Attachment/AttachmentRepository.php
+++ b/app/Repositories/Attachment/AttachmentRepository.php
@@ -66,6 +66,19 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn
return true;
}
+ public function exists(Attachment $attachment): bool
+ {
+ /** @var Storage $disk */
+ $disk = Storage::disk('upload');
+
+ return $disk->exists($attachment->fileName());
+ }
+
+ public function get(): Collection
+ {
+ return $this->user->attachments()->get();
+ }
+
public function getContent(Attachment $attachment): string
{
// create a disk.
@@ -87,19 +100,6 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn
return $unencryptedContent;
}
- public function exists(Attachment $attachment): bool
- {
- /** @var Storage $disk */
- $disk = Storage::disk('upload');
-
- return $disk->exists($attachment->fileName());
- }
-
- public function get(): Collection
- {
- return $this->user->attachments()->get();
- }
-
/**
* Get attachment note text or empty string.
*/
diff --git a/app/Repositories/AuditLogEntry/ALERepository.php b/app/Repositories/AuditLogEntry/ALERepository.php
index 50e4adaf08..139fd075ff 100644
--- a/app/Repositories/AuditLogEntry/ALERepository.php
+++ b/app/Repositories/AuditLogEntry/ALERepository.php
@@ -33,6 +33,12 @@ use Illuminate\Support\Collection;
*/
class ALERepository implements ALERepositoryInterface
{
+ public function getForId(string $model, int $modelId): Collection
+ {
+ // all Models have an ID.
+ return AuditLogEntry::where('auditable_id', $modelId)->where('auditable_type', $model)->get();
+ }
+
public function getForObject(Model $model): Collection
{
// all Models have an ID.
@@ -52,10 +58,4 @@ class ALERepository implements ALERepositoryInterface
return $auditLogEntry;
}
-
- public function getForId(string $model, int $modelId): Collection
- {
- // all Models have an ID.
- return AuditLogEntry::where('auditable_id', $modelId)->where('auditable_type', $model)->get();
- }
}
diff --git a/app/Repositories/AuditLogEntry/ALERepositoryInterface.php b/app/Repositories/AuditLogEntry/ALERepositoryInterface.php
index 3860b52b3b..61bfdedea0 100644
--- a/app/Repositories/AuditLogEntry/ALERepositoryInterface.php
+++ b/app/Repositories/AuditLogEntry/ALERepositoryInterface.php
@@ -44,9 +44,9 @@ use Illuminate\Support\Collection;
*/
interface ALERepositoryInterface
{
- public function getForObject(Model $model): Collection;
-
public function getForId(string $model, int $modelId): Collection;
+ public function getForObject(Model $model): Collection;
+
public function store(array $data): AuditLogEntry;
}
diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php
index 7bcc0a78fe..dc8ef58de1 100644
--- a/app/Repositories/Bill/BillRepository.php
+++ b/app/Repositories/Bill/BillRepository.php
@@ -102,6 +102,22 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
}
}
+ #[Override]
+ public function correctTransfers(): void
+ {
+ /** @var null|TransactionType $withdrawal */
+ $withdrawal = TransactionType::where('type', TransactionTypeEnum::WITHDRAWAL->value)->first();
+ if (null === $withdrawal) {
+ return;
+ }
+ $this->user
+ ->transactionJournals()
+ ->whereNotNull('bill_id')
+ ->where('transaction_type_id', '!=', $withdrawal->id)
+ ->update(['bill_id' => null])
+ ;
+ }
+
public function destroy(Bill $bill): bool
{
/** @var BillDestroyService $service */
@@ -117,6 +133,15 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
$this->user->bills()->delete();
}
+ /**
+ * Find a bill by ID.
+ */
+ public function find(int $billId): ?Bill
+ {
+ /** @var null|Bill */
+ return $this->user->bills()->find($billId);
+ }
+
/**
* Find bill by parameters.
*/
@@ -143,15 +168,6 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
return null;
}
- /**
- * Find a bill by ID.
- */
- public function find(int $billId): ?Bill
- {
- /** @var null|Bill */
- return $this->user->bills()->find($billId);
- }
-
/**
* Find a bill by name.
*/
@@ -165,6 +181,16 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
;
}
+ public function getActiveBills(): Collection
+ {
+ return $this->user
+ ->bills()
+ ->where('active', true)
+ ->orderBy('bills.name', 'ASC')
+ ->get(['bills.*', DB::raw('((bills.amount_min + bills.amount_max) / 2) AS expectedAmount')]) // @phpstan-ignore-line
+ ;
+ }
+
/**
* Get all attachments.
*/
@@ -344,6 +370,36 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
;
}
+ /**
+ * Between start and end, tells you on which date(s) the bill is expected to hit.
+ */
+ public function getPayDatesInRange(Bill $bill, Carbon $start, Carbon $end): Collection
+ {
+ $set = new Collection();
+ $currentStart = clone $start;
+ // \Illuminate\Support\Facades\Log::debug(sprintf('Now at bill "%s" (%s)', $bill->name, $bill->repeat_freq));
+ // \Illuminate\Support\Facades\Log::debug(sprintf('First currentstart is %s', $currentStart->format('Y-m-d')));
+
+ while ($currentStart <= $end) {
+ // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d')));
+ $nextExpectedMatch = $this->nextDateMatch($bill, $currentStart);
+ // \Illuminate\Support\Facades\Log::debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d')));
+ if ($nextExpectedMatch > $end) {
+ // If nextExpectedMatch is after end, we continue
+ break;
+ }
+ $set->push(clone $nextExpectedMatch);
+ // \Illuminate\Support\Facades\Log::debug(sprintf('Now %d dates in set.', $set->count()));
+ $nextExpectedMatch->addDay();
+
+ // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d')));
+
+ $currentStart = clone $nextExpectedMatch;
+ }
+
+ return $set;
+ }
+
/**
* Return all rules for one bill
*/
@@ -457,6 +513,30 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
}
}
+ /**
+ * Given a bill and a date, this method will tell you at which moment this bill expects its next
+ * transaction. Whether or not it is there already, is not relevant.
+ */
+ public function nextDateMatch(Bill $bill, Carbon $date): Carbon
+ {
+ $cache = new CacheProperties();
+ $cache->addProperty($bill->id);
+ $cache->addProperty('nextDateMatch');
+ $cache->addProperty($date);
+ if ($cache->has()) {
+ return $cache->get();
+ }
+ // find the most recent date for this bill NOT in the future. Cache this date:
+ $start = clone $bill->date;
+
+ while ($start < $date) {
+ $start = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip);
+ }
+ $cache->store($start);
+
+ return $start;
+ }
+
/**
* Given the date in $date, this method will return a moment in the future where the bill is expected to be paid.
*/
@@ -500,18 +580,6 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
return $start;
}
- /**
- * @throws FireflyException
- */
- public function store(array $data): Bill
- {
- /** @var BillFactory $factory */
- $factory = app(BillFactory::class);
- $factory->setUser($this->user);
-
- return $factory->create($data);
- }
-
public function removeObjectGroup(Bill $bill): Bill
{
$bill->objectGroups()->sync([]);
@@ -548,6 +616,18 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
$bill->save();
}
+ /**
+ * @throws FireflyException
+ */
+ public function store(array $data): Bill
+ {
+ /** @var BillFactory $factory */
+ $factory = app(BillFactory::class);
+ $factory->setUser($this->user);
+
+ return $factory->create($data);
+ }
+
public function sumPaidInRange(Carbon $start, Carbon $end): array
{
Log::debug(sprintf('sumPaidInRange from %s to %s', $start->toW3cString(), $end->toW3cString()));
@@ -609,16 +689,6 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
return $final;
}
- public function getActiveBills(): Collection
- {
- return $this->user
- ->bills()
- ->where('active', true)
- ->orderBy('bills.name', 'ASC')
- ->get(['bills.*', DB::raw('((bills.amount_min + bills.amount_max) / 2) AS expectedAmount')]) // @phpstan-ignore-line
- ;
- }
-
public function sumUnpaidInRange(Carbon $start, Carbon $end): array
{
Log::debug(sprintf('Now in sumUnpaidInRange("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d')));
@@ -659,60 +729,6 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
return $return;
}
- /**
- * Between start and end, tells you on which date(s) the bill is expected to hit.
- */
- public function getPayDatesInRange(Bill $bill, Carbon $start, Carbon $end): Collection
- {
- $set = new Collection();
- $currentStart = clone $start;
- // \Illuminate\Support\Facades\Log::debug(sprintf('Now at bill "%s" (%s)', $bill->name, $bill->repeat_freq));
- // \Illuminate\Support\Facades\Log::debug(sprintf('First currentstart is %s', $currentStart->format('Y-m-d')));
-
- while ($currentStart <= $end) {
- // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d')));
- $nextExpectedMatch = $this->nextDateMatch($bill, $currentStart);
- // \Illuminate\Support\Facades\Log::debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d')));
- if ($nextExpectedMatch > $end) {
- // If nextExpectedMatch is after end, we continue
- break;
- }
- $set->push(clone $nextExpectedMatch);
- // \Illuminate\Support\Facades\Log::debug(sprintf('Now %d dates in set.', $set->count()));
- $nextExpectedMatch->addDay();
-
- // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d')));
-
- $currentStart = clone $nextExpectedMatch;
- }
-
- return $set;
- }
-
- /**
- * Given a bill and a date, this method will tell you at which moment this bill expects its next
- * transaction. Whether or not it is there already, is not relevant.
- */
- public function nextDateMatch(Bill $bill, Carbon $date): Carbon
- {
- $cache = new CacheProperties();
- $cache->addProperty($bill->id);
- $cache->addProperty('nextDateMatch');
- $cache->addProperty($date);
- if ($cache->has()) {
- return $cache->get();
- }
- // find the most recent date for this bill NOT in the future. Cache this date:
- $start = clone $bill->date;
-
- while ($start < $date) {
- $start = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip);
- }
- $cache->store($start);
-
- return $start;
- }
-
public function unlinkAll(Bill $bill): void
{
$this->user
@@ -732,19 +748,4 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
return $service->update($bill, $data);
}
-
- #[Override]
- public function correctTransfers(): void
- {
- /** @var null|TransactionType $withdrawal */
- $withdrawal = TransactionType::where('type', TransactionTypeEnum::WITHDRAWAL->value)->first();
- if (null === $withdrawal) {
- return;
- }
- $this->user
- ->transactionJournals()
- ->whereNotNull('bill_id')
- ->where('transaction_type_id', '!=', $withdrawal->id)
- ->update(['bill_id' => null]);
- }
}
diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.php
index d2efc9b69c..089935702b 100644
--- a/app/Repositories/Budget/AvailableBudgetRepository.php
+++ b/app/Repositories/Budget/AvailableBudgetRepository.php
@@ -38,6 +38,7 @@ use Illuminate\Support\Facades\Log;
use Spatie\Period\Boundaries;
use Spatie\Period\Period;
use Spatie\Period\Precision;
+use Override;
/**
* Class AvailableBudgetRepository
@@ -53,41 +54,23 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
/** @var AvailableBudget $availableBudget */
foreach ($availableBudgets as $availableBudget) {
- $start = $availableBudget->start_date->format('Y-m-d');
- $end = $availableBudget->end_date->format('Y-m-d');
- $key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end);
+ $start = $availableBudget->start_date->format('Y-m-d');
+ $end = $availableBudget->end_date->format('Y-m-d');
+ $key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end);
if (array_key_exists($key, $exists)) {
Log::debug(sprintf(
- 'Found duplicate AB: %s %s, %s-%s. Has been deleted',
- $availableBudget->transaction_currency_id,
- $availableBudget->amount,
- $start,
- $end
- ));
+ 'Found duplicate AB: %s %s, %s-%s. Has been deleted',
+ $availableBudget->transaction_currency_id,
+ $availableBudget->amount,
+ $start,
+ $end
+ ));
$availableBudget->delete();
}
$exists[$key] = true;
}
}
- /**
- * Return a list of all available budgets (in all currencies) (for the selected period).
- */
- public function get(?Carbon $start = null, ?Carbon $end = null): Collection
- {
- $query = $this->user->availableBudgets()->with(['transactionCurrency']);
- if ($start instanceof Carbon && $end instanceof Carbon) {
- $query->where(static function (Builder $q1) use ($start, $end): void {
- $q1->where('start_date', '=', $start->format('Y-m-d'));
- $q1->where('end_date', '=', $end->format('Y-m-d'));
- });
- }
- $result = $query->get(['available_budgets.*']);
- Log::debug(sprintf('Found %d available budgets between %s and %s', $result->count(), $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
-
- return $result;
- }
-
/**
* Delete all available budgets.
*/
@@ -102,11 +85,6 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
$availableBudget->delete();
}
- public function findById(int $id): ?AvailableBudget
- {
- return $this->user->availableBudgets->find($id);
- }
-
/**
* Find existing AB.
*/
@@ -118,13 +96,37 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
->where('transaction_currency_id', $currency->id)
->where('start_date', $start->format('Y-m-d'))
->where('end_date', $end->format('Y-m-d'))
- ->first();
+ ->first()
+ ;
+ }
+
+ public function findById(int $id): ?AvailableBudget
+ {
+ return $this->user->availableBudgets->find($id);
+ }
+
+ /**
+ * Return a list of all available budgets (in all currencies) (for the selected period).
+ */
+ public function get(?Carbon $start = null, ?Carbon $end = null): Collection
+ {
+ $query = $this->user->availableBudgets()->with(['transactionCurrency']);
+ if ($start instanceof Carbon && $end instanceof Carbon) {
+ $query->where(static function (Builder $q1) use ($start, $end): void {
+ $q1->where('start_date', '=', $start->format('Y-m-d'));
+ $q1->where('end_date', '=', $end->format('Y-m-d'));
+ });
+ }
+ $result = $query->get(['available_budgets.*']);
+ Log::debug(sprintf('Found %d available budgets between %s and %s', $result->count(), $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
+
+ return $result;
}
#[Deprecated]
public function getAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end): string
{
- $amount = '0';
+ $amount = '0';
/** @var null|AvailableBudget $availableBudget */
$availableBudget = $this->user
@@ -132,7 +134,8 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
->where('transaction_currency_id', $currency->id)
->where('start_date', $start->format('Y-m-d'))
->where('end_date', $end->format('Y-m-d'))
- ->first();
+ ->first()
+ ;
if (null !== $availableBudget) {
return $availableBudget->amount;
}
@@ -140,37 +143,6 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
return $amount;
}
- public function getAvailableBudgetWithCurrency(Carbon $start, Carbon $end): array
- {
- Log::debug(sprintf('Now in %s(%s, %s)', __METHOD__, $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
- $return = [];
- $availableBudgets = $this->user
- ->availableBudgets()
- ->where('start_date', $start->format('Y-m-d'))
- ->where('end_date', $end->format('Y-m-d'))
- ->get();
-
- Log::debug(sprintf('Found %d available budgets (already converted)', $availableBudgets->count()));
-
- // use primary amount if necessary?
- $convertToPrimary = Amount::convertToPrimary($this->user);
- $primary = Amount::getPrimaryCurrency();
-
- /** @var AvailableBudget $availableBudget */
- foreach ($availableBudgets as $availableBudget) {
- $currencyId = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id
- ? $primary->id
- : $availableBudget->transaction_currency_id;
- $field = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? 'native_amount' : 'amount';
- $return[$currencyId] ??= '0';
- $amount = '' === (string)$availableBudget->{$field} ? '0' : (string)$availableBudget->{$field};
- $return[$currencyId] = bcadd($return[$currencyId], $amount);
- Log::debug(sprintf('Add #%d %s (%s) for a total of %s', $currencyId, $amount, $field, $return[$currencyId]));
- }
-
- return $return;
- }
-
/**
* Returns all available budget objects.
*/
@@ -179,7 +151,8 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
return $this->user
->availableBudgets()
->where('transaction_currency_id', $currency->id)
- ->get();
+ ->get()
+ ;
}
/**
@@ -208,7 +181,40 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
->availableBudgets()
->where('start_date', '=', $start->format('Y-m-d'))
->where('end_date', '=', $end->format('Y-m-d'))
- ->get();
+ ->get()
+ ;
+ }
+
+ public function getAvailableBudgetWithCurrency(Carbon $start, Carbon $end): array
+ {
+ Log::debug(sprintf('Now in %s(%s, %s)', __METHOD__, $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
+ $return = [];
+ $availableBudgets = $this->user
+ ->availableBudgets()
+ ->where('start_date', $start->format('Y-m-d'))
+ ->where('end_date', $end->format('Y-m-d'))
+ ->get()
+ ;
+
+ Log::debug(sprintf('Found %d available budgets (already converted)', $availableBudgets->count()));
+
+ // use primary amount if necessary?
+ $convertToPrimary = Amount::convertToPrimary($this->user);
+ $primary = Amount::getPrimaryCurrency();
+
+ /** @var AvailableBudget $availableBudget */
+ foreach ($availableBudgets as $availableBudget) {
+ $currencyId = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id
+ ? $primary->id
+ : $availableBudget->transaction_currency_id;
+ $field = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? 'native_amount' : 'amount';
+ $return[$currencyId] ??= '0';
+ $amount = '' === (string) $availableBudget->{$field} ? '0' : (string) $availableBudget->{$field};
+ $return[$currencyId] = bcadd($return[$currencyId], $amount);
+ Log::debug(sprintf('Add #%d %s (%s) for a total of %s', $currencyId, $amount, $field, $return[$currencyId]));
+ }
+
+ return $return;
}
public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): ?AvailableBudget
@@ -219,21 +225,55 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
->where('transaction_currency_id', $currency->id)
->where('start_date', $start->format('Y-m-d'))
->where('end_date', $end->format('Y-m-d'))
- ->first();
+ ->first()
+ ;
+ }
+
+ #[Override]
+ public function recalculateAmount(AvailableBudget $availableBudget): void
+ {
+ Log::debug(sprintf('Now in recalculateAmount(#%d)', $availableBudget->id));
+ $newAmount = '0';
+ $period = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY());
+ Log::debug(sprintf(
+ 'Now recalculating available budget #%d, (%s to %s)',
+ $availableBudget->id,
+ $availableBudget->start_date->format('Y-m-d'),
+ $availableBudget->end_date->format('Y-m-d')
+ ));
+ // have to recalculate everything just in case.
+ $blRepository = app(BudgetLimitRepositoryInterface::class);
+ $blRepository->setUser($this->user);
+ $set = $blRepository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date);
+ Log::debug(sprintf('Found %d interesting budget limit(s).', $set->count()));
+
+ /** @var BudgetLimit $budgetLimit */
+ foreach ($set as $budgetLimit) {
+ $newAmount = bcadd($newAmount, $this->getAmountFromBudgetLimit($budgetLimit, $period));
+ }
+ if (0 === bccomp('0', $newAmount)) {
+ Log::debug('New amount is zero, deleting AB.');
+ $availableBudget->delete();
+
+ return;
+ }
+ Log::debug(sprintf('Concluded new amount for this AB must be %s', $newAmount));
+ $this->update($availableBudget, ['amount' => $newAmount]);
}
#[Deprecated]
public function setAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end, string $amount): AvailableBudget
{
/** @var null|AvailableBudget $availableBudget */
- $availableBudget = $this->user
+ $availableBudget = $this->user
->availableBudgets()
->where('transaction_currency_id', $currency->id)
->where('start_date', $start->format('Y-m-d'))
->where('end_date', $end->format('Y-m-d'))
- ->first();
+ ->first()
+ ;
if (null === $availableBudget) {
- $availableBudget = new AvailableBudget();
+ $availableBudget = new AvailableBudget();
$availableBudget->user()->associate($this->user);
$availableBudget->transactionCurrency()->associate($currency);
$availableBudget->start_date = $start->startOfDay();
@@ -253,21 +293,21 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
if ($start instanceof Carbon) {
$start = $data['start']->startOfDay();
}
- $end = $data['end'];
+ $end = $data['end'];
if ($end instanceof Carbon) {
$end = $data['end']->endOfDay();
}
return AvailableBudget::create([
- 'user_id' => $this->user->id,
- 'user_group_id' => $this->user->user_group_id,
- 'transaction_currency_id' => $data['currency_id'],
- 'amount' => $data['amount'],
- 'start_date' => $start,
- 'start_date_tz' => $start->format('e'),
- 'end_date' => $end,
- 'end_date_tz' => $end->format('e'),
- ]);
+ 'user_id' => $this->user->id,
+ 'user_group_id' => $this->user->user_group_id,
+ 'transaction_currency_id' => $data['currency_id'],
+ 'amount' => $data['amount'],
+ 'start_date' => $start,
+ 'start_date_tz' => $start->format('e'),
+ 'end_date' => $end,
+ 'end_date_tz' => $end->format('e'),
+ ]);
}
public function update(AvailableBudget $availableBudget, array $data): AvailableBudget
@@ -313,61 +353,46 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
return $availableBudget;
}
- #[\Override]
- public function recalculateAmount(AvailableBudget $availableBudget): void
- {
- Log::debug(sprintf('Now in recalculateAmount(#%d)', $availableBudget->id));
- $newAmount = '0';
- $period = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY());
- Log::debug(sprintf('Now recalculating available budget #%d, (%s to %s)', $availableBudget->id, $availableBudget->start_date->format('Y-m-d'), $availableBudget->end_date->format('Y-m-d')));
- // have to recalculate everything just in case.
- $blRepository = app(BudgetLimitRepositoryInterface::class);
- $blRepository->setUser($this->user);
- $set = $blRepository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date);
- Log::debug(sprintf('Found %d interesting budget limit(s).', $set->count()));
-
- /** @var BudgetLimit $budgetLimit */
- foreach ($set as $budgetLimit) {
- $newAmount = bcadd($newAmount, $this->getAmountFromBudgetLimit($budgetLimit, $period));
- }
- if (0 === bccomp('0', $newAmount)) {
- Log::debug('New amount is zero, deleting AB.');
- $availableBudget->delete();
-
- return;
- }
- Log::debug(sprintf('Concluded new amount for this AB must be %s', $newAmount));
- $this->update($availableBudget, ['amount' => $newAmount]);
- }
-
-
private function getAmountFromBudgetLimit(BudgetLimit $budgetLimit, Period $availableBudgetPeriod): string
{
$blRepository = app(BudgetLimitRepositoryInterface::class);
$blRepository->setUser($this->user);
- Log::debug(sprintf('Found interesting budget limit #%d (%s to %s)', $budgetLimit->id, $budgetLimit->start_date->format('Y-m-d'), $budgetLimit->end_date->format('Y-m-d')));
+ Log::debug(sprintf(
+ 'Found interesting budget limit #%d (%s to %s)',
+ $budgetLimit->id,
+ $budgetLimit->start_date->format('Y-m-d'),
+ $budgetLimit->end_date->format('Y-m-d')
+ ));
// overlap in days:
- $limitPeriod = Period::make($budgetLimit->start_date, $budgetLimit->end_date, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());
+ $limitPeriod = Period::make($budgetLimit->start_date, $budgetLimit->end_date, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());
// if both equal each other, amount from this BL must be added to the AB
if ($limitPeriod->equals($availableBudgetPeriod)) {
Log::debug('This budget limit is equal to the available budget period.');
- return (string)$budgetLimit->amount;
+
+ return (string) $budgetLimit->amount;
}
// if budget limit period is inside AB period, it can be added in full.
if (!$limitPeriod->equals($availableBudgetPeriod) && $availableBudgetPeriod->contains($limitPeriod)) {
Log::debug('This budget limit is smaller than the available budget period.');
- return (string)$budgetLimit->amount;
+
+ return (string) $budgetLimit->amount;
}
- if (!$limitPeriod->equals($availableBudgetPeriod) && !$availableBudgetPeriod->contains($limitPeriod) && $availableBudgetPeriod->overlapsWith($limitPeriod)) {
+ if (
+ !$limitPeriod->equals($availableBudgetPeriod)
+ && !$availableBudgetPeriod->contains($limitPeriod)
+ && $availableBudgetPeriod->overlapsWith($limitPeriod)
+ ) {
Log::debug('This budget limit is something else entirely!');
$overlap = $availableBudgetPeriod->overlap($limitPeriod);
if ($overlap instanceof Period) {
$length = $overlap->length();
- return bcmul($blRepository->getDailyAmount($budgetLimit), (string)$length);
+
+ return bcmul($blRepository->getDailyAmount($budgetLimit), (string) $length);
}
}
+
return '0';
}
}
diff --git a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php
index 635c1d2cc7..8e001f8cdc 100644
--- a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php
+++ b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php
@@ -70,8 +70,6 @@ interface AvailableBudgetRepositoryInterface
#[Deprecated]
public function getAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end): string;
- public function getAvailableBudgetWithCurrency(Carbon $start, Carbon $end): array;
-
/**
* Returns all available budget objects.
*/
@@ -84,6 +82,8 @@ interface AvailableBudgetRepositoryInterface
public function getAvailableBudgetsByExactDate(Carbon $start, Carbon $end): Collection;
+ public function getAvailableBudgetWithCurrency(Carbon $start, Carbon $end): array;
+
/**
* Get by transaction currency and date. Should always result in one entry or NULL.
*/
diff --git a/app/Repositories/Budget/BudgetLimitRepository.php b/app/Repositories/Budget/BudgetLimitRepository.php
index 2081fd2d12..1044e883f0 100644
--- a/app/Repositories/Budget/BudgetLimitRepository.php
+++ b/app/Repositories/Budget/BudgetLimitRepository.php
@@ -60,9 +60,9 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
*/
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(static function (Builder $q5) use ($start, $end): void {
+ ->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'));
@@ -77,10 +77,11 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
$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 ($budgets instanceof Collection && $budgets->count() > 0) {
$query->whereIn('budget_limits.budget_id', $budgets->pluck('id')->toArray());
}
@@ -90,7 +91,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
/** @var BudgetLimit $budgetLimit */
foreach ($set as $budgetLimit) {
- $result = bcadd((string)$budgetLimit->amount, $result);
+ $result = bcadd((string) $budgetLimit->amount, $result);
}
return $result;
@@ -115,35 +116,24 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
*/
public function destroyBudgetLimit(BudgetLimit $budgetLimit): void
{
- $user = $budgetLimit->budget->user;
+ $user = $budgetLimit->budget->user;
$start = $budgetLimit->start_date->clone();
- $end = $budgetLimit->end_date->clone();
+ $end = $budgetLimit->end_date->clone();
event(new DestroyedBudgetLimit($user, $budgetLimit->budget, $start, $end, true));
$budgetLimit->delete();
event(new WebhookMessagesRequestSending());
}
- public function getDailyAmount(BudgetLimit $budgetLimit): string
- {
- $limitPeriod = Period::make($budgetLimit->start_date, $budgetLimit->end_date, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());
- $days = $limitPeriod->length();
- $amount = bcdiv($budgetLimit->amount, (string) $days, 12);
- Log::debug(sprintf(
- 'Total amount for budget limit #%d is %s. Nr. of days is %d. Amount per day is %s',
- $budgetLimit->id,
- $budgetLimit->amount,
- $days,
- $amount
- ));
-
- return $amount;
- }
-
- public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection
+ public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit
{
- return $this->getAllBudgetLimits($start, $end)->filter(
- static fn(BudgetLimit $budgetLimit): bool => $budgetLimit->transaction_currency_id === $currency->id
- );
+ /** @var null|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()
+ ;
}
public function getAllBudgetLimits(?Carbon $start = null, ?Carbon $end = null): Collection
@@ -151,17 +141,19 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
// both are NULL:
if (!$start instanceof Carbon && !$end instanceof Carbon) {
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 (!$start instanceof Carbon xor !$end instanceof Carbon) {
$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 ($end instanceof Carbon) {
// end date must be before $end.
$query->where('end_date', '<=', $end->format('Y-m-d 00:00:00'));
@@ -176,25 +168,33 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
// 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 getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection
+ {
+ return $this->getAllBudgetLimits($start, $end)->filter(
+ static fn (BudgetLimit $budgetLimit): bool => $budgetLimit->transaction_currency_id === $currency->id
+ );
}
public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection
@@ -232,7 +232,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
->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'));
@@ -240,13 +241,47 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
});
})
->orderBy('budget_limits.start_date', 'DESC')
- ->get(['budget_limits.*']);
+ ->get(['budget_limits.*'])
+ ;
+ }
+
+ public function getDailyAmount(BudgetLimit $budgetLimit): string
+ {
+ $limitPeriod = Period::make($budgetLimit->start_date, $budgetLimit->end_date, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE());
+ $days = $limitPeriod->length();
+ $amount = bcdiv($budgetLimit->amount, (string) $days, 12);
+ Log::debug(sprintf(
+ 'Total amount for budget limit #%d is %s. Nr. of days is %d. Amount per day is %s',
+ $budgetLimit->id,
+ $budgetLimit->amount,
+ $days,
+ $amount
+ ));
+
+ return $amount;
}
#[Override]
public function getNoteText(BudgetLimit $budgetLimit): string
{
- return (string)$budgetLimit->notes()->first()?->text;
+ 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();
}
/**
@@ -256,86 +291,60 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
{
// 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 = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
}
- $currency->enabled = true;
+ $currency->enabled = true;
$currency->save();
// find the budget:
/** @var null|Budget $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
+ $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.*']);
+ ->first(['budget_limits.*'])
+ ;
if (null !== $limit) {
throw new FireflyException('200027: Budget limit already exists.');
}
Log::debug('No existing budget limit, create a new one');
// this is a lame trick to communicate with the observer.
- $singleton = PreferencesSingleton::getInstance();
+ $singleton = PreferencesSingleton::getInstance();
$singleton->setPreference('fire_webhooks_bl_store', $data['fire_webhooks'] ?? true);
// 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->generated = $data['generated'] ?? false;
- $limit->period = $data['period'] ?? '';
+ $limit->generated = $data['generated'] ?? false;
+ $limit->period = $data['period'] ?? '';
$limit->transaction_currency_id = $currency->id;
$limit->save();
- $noteText = (string)($data['notes'] ?? '');
+ $noteText = (string) ($data['notes'] ?? '');
if ('' !== $noteText) {
$this->setNoteText($limit, $noteText);
}
Log::debug(sprintf('Created new budget limit with ID #%d and amount %s', $limit->id, $data['amount']));
- $createWebhookMessages = $data['fire_webhooks'] ?? true;
+ $createWebhookMessages = $data['fire_webhooks'] ?? true;
event(new CreatedBudgetLimit($limit, $createWebhookMessages));
event(new WebhookMessagesRequestSending());
- return $limit;
- }
-
- public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit
- {
- /** @var null|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();
- }
- #[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();
+ return $limit;
}
/**
@@ -343,8 +352,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
*/
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();
@@ -356,7 +365,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
}
// 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)) {
@@ -368,12 +377,12 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
if (null === $currency) {
$currency = $budgetLimit->transactionCurrency ?? Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
}
- $currency->enabled = true;
+ $currency->enabled = true;
$currency->save();
// this is a lame trick to communicate with the observer.
// FIXME so don't do that lol.
- $singleton = PreferencesSingleton::getInstance();
+ $singleton = PreferencesSingleton::getInstance();
$singleton->setPreference('fire_webhooks_bl_update', $data['fire_webhooks'] ?? true);
$budgetLimit->transaction_currency_id = $currency->id;
@@ -381,12 +390,12 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
// update notes if they exist.
if (array_key_exists('notes', $data)) {
- $this->setNoteText($budgetLimit, (string)$data['notes']);
+ $this->setNoteText($budgetLimit, (string) $data['notes']);
}
- $generateMessages = $data['fire_webhooks'] ?? true;
+ $generateMessages = $data['fire_webhooks'] ?? true;
event(new UpdatedBudgetLimit($budgetLimit, $generateMessages));
event(new WebhookMessagesRequestSending());
+
return $budgetLimit;
}
-
}
diff --git a/app/Repositories/Budget/BudgetLimitRepositoryInterface.php b/app/Repositories/Budget/BudgetLimitRepositoryInterface.php
index b9a99fc276..d865349acf 100644
--- a/app/Repositories/Budget/BudgetLimitRepositoryInterface.php
+++ b/app/Repositories/Budget/BudgetLimitRepositoryInterface.php
@@ -52,8 +52,6 @@ interface BudgetLimitRepositoryInterface
*/
public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, ?Collection $budgets = null): string;
- public function getDailyAmount(BudgetLimit $budgetLimit): string;
-
/**
* Destroy all budget limits.
*/
@@ -75,6 +73,8 @@ interface BudgetLimitRepositoryInterface
public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection;
+ public function getDailyAmount(BudgetLimit $budgetLimit): string;
+
public function getNoteText(BudgetLimit $budgetLimit): string;
public function setNoteText(BudgetLimit $budgetLimit, string $text): void;
diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php
index b324de1ce7..89c9f731bf 100644
--- a/app/Repositories/Budget/BudgetRepository.php
+++ b/app/Repositories/Budget/BudgetRepository.php
@@ -63,28 +63,6 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
{
use UserGroupTrait;
- public function budgetEndsWith(string $query, int $limit): Collection
- {
- $search = $this->user->budgets();
- if ('' !== $query) {
- $search->whereLike('name', sprintf('%%%s', $query));
- }
- $search->orderBy('order', 'ASC')->orderBy('name', 'ASC')->where('active', true);
-
- return $search->take($limit)->get();
- }
-
- public function budgetStartsWith(string $query, int $limit): Collection
- {
- $search = $this->user->budgets();
- if ('' !== $query) {
- $search->whereLike('name', sprintf('%s%%', $query));
- }
- $search->orderBy('order', 'ASC')->orderBy('name', 'ASC')->where('active', true);
-
- return $search->take($limit)->get();
- }
-
public function budgetedInPeriod(Carbon $start, Carbon $end): array
{
Log::debug(sprintf('Now in budgetedInPeriod("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d')));
@@ -157,51 +135,6 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
return $return;
}
- public function getActiveBudgets(): Collection
- {
- return $this->user
- ->budgets()
- ->where('active', true)
- ->orderBy('order', 'ASC')
- ->orderBy('name', 'ASC')
- ->get()
- ;
- }
-
- /**
- * How many days of this budget limit are between start and end?
- */
- private function daysInOverlap(BudgetLimit $limit, Carbon $start, Carbon $end): int
- {
- // start1 = $start
- // start2 = $limit->start_date
- // start1 = $end
- // start2 = $limit->end_date
-
- // limit is larger than start and end (inclusive)
- // |-----------|
- // |----------------|
- if ($start->gte($limit->start_date) && $end->lte($limit->end_date)) {
- return (int) $start->diffInDays($end, true) + 1; // add one day
- }
- // limit starts earlier and limit ends first:
- // |-----------|
- // |-------|
- if ($limit->start_date->lte($start) && $limit->end_date->lte($end)) {
- // return days in the range $start-$limit_end
- return (int) $start->diffInDays($limit->end_date, true) + 1; // add one day, the day itself
- }
- // limit starts later and limit ends earlier
- // |-----------|
- // |-------|
- if ($limit->start_date->gte($start) && $limit->end_date->gte($end)) {
- // return days in the range $limit_start - $end
- return (int) $limit->start_date->diffInDays($end, true) + 1; // add one day, the day itself
- }
-
- return 0;
- }
-
public function budgetedInPeriodForBudget(Budget $budget, Carbon $start, Carbon $end): array
{
Log::debug(sprintf('Now in budgetedInPeriod(#%d, "%s", "%s")', $budget->id, $start->format('Y-m-d'), $end->format('Y-m-d')));
@@ -257,6 +190,28 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
return $return;
}
+ public function budgetEndsWith(string $query, int $limit): Collection
+ {
+ $search = $this->user->budgets();
+ if ('' !== $query) {
+ $search->whereLike('name', sprintf('%%%s', $query));
+ }
+ $search->orderBy('order', 'ASC')->orderBy('name', 'ASC')->where('active', true);
+
+ return $search->take($limit)->get();
+ }
+
+ public function budgetStartsWith(string $query, int $limit): Collection
+ {
+ $search = $this->user->budgets();
+ if ('' !== $query) {
+ $search->whereLike('name', sprintf('%s%%', $query));
+ }
+ $search->orderBy('order', 'ASC')->orderBy('name', 'ASC')->where('active', true);
+
+ return $search->take($limit)->get();
+ }
+
public function cleanupBudgets(): bool
{
// delete limits with amount 0:
@@ -281,174 +236,6 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
return true;
}
- /**
- * @throws FireflyException
- */
- public function update(Budget $budget, array $data): Budget
- {
- Log::debug('Now in update()');
-
- // this is a lame trick to communicate with the observer.
- $singleton = PreferencesSingleton::getInstance();
- $singleton->setPreference('fire_webhooks_budget_update', $data['fire_webhooks'] ?? true);
-
- $oldName = $budget->name;
- if (array_key_exists('name', $data)) {
- $budget->name = $data['name'];
- $this->updateRuleActions($oldName, $budget->name);
- $this->updateRuleTriggers($oldName, $budget->name);
- }
- if (array_key_exists('active', $data)) {
- $budget->active = $data['active'];
- }
- if (array_key_exists('notes', $data)) {
- $this->setNoteText($budget, (string) $data['notes']);
- }
- $budget->save();
-
- $createWebhookMessages = $data['fire_webhooks'] ?? true;
- event(new UpdatedBudget($budget, $createWebhookMessages));
- event(new WebhookMessagesRequestSending());
-
- // update or create auto-budget:
- $autoBudget = $this->getAutoBudget($budget);
-
- // first things first: delete when no longer required:
- $autoBudgetType = $data['auto_budget_type'] ?? null;
-
- if (0 === $autoBudgetType && $autoBudget instanceof AutoBudget) {
- // delete!
- $autoBudget->delete();
-
- return $budget;
- }
- if (0 === $autoBudgetType) {
- return $budget;
- }
- if (null === $autoBudgetType) {
- return $budget;
- }
- $this->updateAutoBudget($budget, $data);
-
- return $budget;
- }
-
- private function updateRuleActions(string $oldName, string $newName): void
- {
- $types = ['set_budget'];
- $actions = RuleAction::leftJoin('rules', 'rules.id', '=', 'rule_actions.rule_id')
- ->where('rules.user_id', $this->user->id)
- ->whereIn('rule_actions.action_type', $types)
- ->where('rule_actions.action_value', $oldName)
- ->get(['rule_actions.*'])
- ;
- Log::debug(sprintf('Found %d actions to update.', $actions->count()));
-
- /** @var RuleAction $action */
- foreach ($actions as $action) {
- $action->action_value = $newName;
- $action->save();
- Log::debug(sprintf('Updated action %d: %s', $action->id, $action->action_value));
- }
- }
-
- private function updateRuleTriggers(string $oldName, string $newName): void
- {
- $types = ['budget_is'];
- $triggers = RuleTrigger::leftJoin('rules', 'rules.id', '=', 'rule_triggers.rule_id')
- ->where('rules.user_id', $this->user->id)
- ->whereIn('rule_triggers.trigger_type', $types)
- ->where('rule_triggers.trigger_value', $oldName)
- ->get(['rule_triggers.*'])
- ;
- Log::debug(sprintf('Found %d triggers to update.', $triggers->count()));
-
- /** @var RuleTrigger $trigger */
- foreach ($triggers as $trigger) {
- $trigger->trigger_value = $newName;
- $trigger->save();
- Log::debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value));
- }
- }
-
- private function setNoteText(Budget $budget, string $text): void
- {
- $dbNote = $budget->notes()->first();
- if ('' !== $text) {
- if (null === $dbNote) {
- $dbNote = new Note();
- $dbNote->noteable()->associate($budget);
- }
- $dbNote->text = trim($text);
- $dbNote->save();
-
- return;
- }
- $dbNote?->delete();
- }
-
- public function getAutoBudget(Budget $budget): ?AutoBudget
- {
- /** @var null|AutoBudget */
- return $budget->autoBudgets()->first();
- }
-
- private function updateAutoBudget(Budget $budget, array $data): void
- {
- // update or create auto-budget:
- $autoBudget = $this->getAutoBudget($budget);
-
- // grab default currency:
- $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
-
- if (!$autoBudget instanceof AutoBudget) {
- // at this point it's a blind assumption auto_budget_type is 1 or 2.
- $autoBudget = new AutoBudget();
- $autoBudget->auto_budget_type = $data['auto_budget_type'];
- $autoBudget->budget_id = $budget->id;
- $autoBudget->transaction_currency_id = $currency->id;
- }
-
- // set or update the currency.
- if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
- /** @var CurrencyRepositoryInterface $repos */
- $repos = app(CurrencyRepositoryInterface::class);
- $currencyId = (int) ($data['currency_id'] ?? 0);
- $currencyCode = (string) ($data['currency_code'] ?? '');
- $currency = $repos->find($currencyId);
- if (null === $currency) {
- $currency = $repos->findByCode($currencyCode);
- }
- if (null !== $currency) {
- $autoBudget->transaction_currency_id = $currency->id;
- }
- }
-
- // change values if submitted or presented:
- if (array_key_exists('auto_budget_type', $data)) {
- $autoBudget->auto_budget_type = $data['auto_budget_type'];
- }
- if (array_key_exists('auto_budget_amount', $data)) {
- $autoBudget->amount = $data['auto_budget_amount'];
- }
- if (array_key_exists('auto_budget_period', $data)) {
- $autoBudget->period = $data['auto_budget_period'];
- }
-
- $autoBudget->save();
- }
-
- /**
- * Find a budget or return NULL
- *
- * @param null|int $budgetId |null
- */
- public function find(?int $budgetId = null): ?Budget
- {
- /** @var null|Budget */
- return $this->user->budgets()->find($budgetId);
- }
-
public function destroy(Budget $budget): bool
{
/** @var BudgetDestroyService $service */
@@ -476,16 +263,6 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
Log::channel('audit')->info('Delete all budgets through destroyAll');
}
- public function getBudgets(): Collection
- {
- return $this->user
- ->budgets()
- ->orderBy('order', 'ASC')
- ->orderBy('name', 'ASC')
- ->get()
- ;
- }
-
public function destroyAutoBudget(Budget $budget): void
{
/** @var AutoBudget $autoBudget */
@@ -494,6 +271,17 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
}
}
+ /**
+ * Find a budget or return NULL
+ *
+ * @param null|int $budgetId |null
+ */
+ public function find(?int $budgetId = null): ?Budget
+ {
+ /** @var null|Budget */
+ return $this->user->budgets()->find($budgetId);
+ }
+
public function findBudget(?int $budgetId, ?string $budgetName): ?Budget
{
Log::debug('Now in findBudget()');
@@ -540,6 +328,17 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
return $journal?->date;
}
+ public function getActiveBudgets(): Collection
+ {
+ return $this->user
+ ->budgets()
+ ->where('active', true)
+ ->orderBy('order', 'ASC')
+ ->orderBy('name', 'ASC')
+ ->get()
+ ;
+ }
+
public function getAttachments(Budget $budget): Collection
{
$set = $budget->attachments()->get();
@@ -555,6 +354,22 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
});
}
+ public function getAutoBudget(Budget $budget): ?AutoBudget
+ {
+ /** @var null|AutoBudget */
+ return $budget->autoBudgets()->first();
+ }
+
+ public function getBudgets(): Collection
+ {
+ return $this->user
+ ->budgets()
+ ->orderBy('order', 'ASC')
+ ->orderBy('name', 'ASC')
+ ->get()
+ ;
+ }
+
/**
* Get all budgets with these ID's.
*/
@@ -578,6 +393,11 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
;
}
+ public function getMaxOrder(): int
+ {
+ return (int) $this->user->budgets()->max('order');
+ }
+
public function getNoteText(Budget $budget): ?string
{
$note = $budget->notes()->first();
@@ -761,7 +581,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
$this->setNoteText($newBudget, (string) $data['notes']);
}
- $createWebhookMessages = $data['fire_webhooks'] ?? true;
+ $createWebhookMessages = $data['fire_webhooks'] ?? true;
event(new CreatedBudget($newBudget, $createWebhookMessages));
event(new WebhookMessagesRequestSending());
@@ -815,19 +635,199 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
$limitRepos = app(BudgetLimitRepositoryInterface::class);
$limitRepos->setUser($this->user);
$limitRepos->store([
- 'budget_id' => $newBudget->id,
- 'currency_id' => $autoBudget->transaction_currency_id,
- 'start_date' => $start,
- 'end_date' => $end,
- 'amount' => $autoBudget->amount,
+ 'budget_id' => $newBudget->id,
+ 'currency_id' => $autoBudget->transaction_currency_id,
+ 'start_date' => $start,
+ 'end_date' => $end,
+ 'amount' => $autoBudget->amount,
'fire_webhooks' => false,
]);
return $newBudget;
}
- public function getMaxOrder(): int
+ /**
+ * @throws FireflyException
+ */
+ public function update(Budget $budget, array $data): Budget
{
- return (int) $this->user->budgets()->max('order');
+ Log::debug('Now in update()');
+
+ // this is a lame trick to communicate with the observer.
+ $singleton = PreferencesSingleton::getInstance();
+ $singleton->setPreference('fire_webhooks_budget_update', $data['fire_webhooks'] ?? true);
+
+ $oldName = $budget->name;
+ if (array_key_exists('name', $data)) {
+ $budget->name = $data['name'];
+ $this->updateRuleActions($oldName, $budget->name);
+ $this->updateRuleTriggers($oldName, $budget->name);
+ }
+ if (array_key_exists('active', $data)) {
+ $budget->active = $data['active'];
+ }
+ if (array_key_exists('notes', $data)) {
+ $this->setNoteText($budget, (string) $data['notes']);
+ }
+ $budget->save();
+
+ $createWebhookMessages = $data['fire_webhooks'] ?? true;
+ event(new UpdatedBudget($budget, $createWebhookMessages));
+ event(new WebhookMessagesRequestSending());
+
+ // update or create auto-budget:
+ $autoBudget = $this->getAutoBudget($budget);
+
+ // first things first: delete when no longer required:
+ $autoBudgetType = $data['auto_budget_type'] ?? null;
+
+ if (0 === $autoBudgetType && $autoBudget instanceof AutoBudget) {
+ // delete!
+ $autoBudget->delete();
+
+ return $budget;
+ }
+ if (0 === $autoBudgetType) {
+ return $budget;
+ }
+ if (null === $autoBudgetType) {
+ return $budget;
+ }
+ $this->updateAutoBudget($budget, $data);
+
+ return $budget;
+ }
+
+ /**
+ * How many days of this budget limit are between start and end?
+ */
+ private function daysInOverlap(BudgetLimit $limit, Carbon $start, Carbon $end): int
+ {
+ // start1 = $start
+ // start2 = $limit->start_date
+ // start1 = $end
+ // start2 = $limit->end_date
+
+ // limit is larger than start and end (inclusive)
+ // |-----------|
+ // |----------------|
+ if ($start->gte($limit->start_date) && $end->lte($limit->end_date)) {
+ return (int) $start->diffInDays($end, true) + 1; // add one day
+ }
+ // limit starts earlier and limit ends first:
+ // |-----------|
+ // |-------|
+ if ($limit->start_date->lte($start) && $limit->end_date->lte($end)) {
+ // return days in the range $start-$limit_end
+ return (int) $start->diffInDays($limit->end_date, true) + 1; // add one day, the day itself
+ }
+ // limit starts later and limit ends earlier
+ // |-----------|
+ // |-------|
+ if ($limit->start_date->gte($start) && $limit->end_date->gte($end)) {
+ // return days in the range $limit_start - $end
+ return (int) $limit->start_date->diffInDays($end, true) + 1; // add one day, the day itself
+ }
+
+ return 0;
+ }
+
+ private function setNoteText(Budget $budget, string $text): void
+ {
+ $dbNote = $budget->notes()->first();
+ if ('' !== $text) {
+ if (null === $dbNote) {
+ $dbNote = new Note();
+ $dbNote->noteable()->associate($budget);
+ }
+ $dbNote->text = trim($text);
+ $dbNote->save();
+
+ return;
+ }
+ $dbNote?->delete();
+ }
+
+ private function updateAutoBudget(Budget $budget, array $data): void
+ {
+ // update or create auto-budget:
+ $autoBudget = $this->getAutoBudget($budget);
+
+ // grab default currency:
+ $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
+
+ if (!$autoBudget instanceof AutoBudget) {
+ // at this point it's a blind assumption auto_budget_type is 1 or 2.
+ $autoBudget = new AutoBudget();
+ $autoBudget->auto_budget_type = $data['auto_budget_type'];
+ $autoBudget->budget_id = $budget->id;
+ $autoBudget->transaction_currency_id = $currency->id;
+ }
+
+ // set or update the currency.
+ if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
+ /** @var CurrencyRepositoryInterface $repos */
+ $repos = app(CurrencyRepositoryInterface::class);
+ $currencyId = (int) ($data['currency_id'] ?? 0);
+ $currencyCode = (string) ($data['currency_code'] ?? '');
+ $currency = $repos->find($currencyId);
+ if (null === $currency) {
+ $currency = $repos->findByCode($currencyCode);
+ }
+ if (null !== $currency) {
+ $autoBudget->transaction_currency_id = $currency->id;
+ }
+ }
+
+ // change values if submitted or presented:
+ if (array_key_exists('auto_budget_type', $data)) {
+ $autoBudget->auto_budget_type = $data['auto_budget_type'];
+ }
+ if (array_key_exists('auto_budget_amount', $data)) {
+ $autoBudget->amount = $data['auto_budget_amount'];
+ }
+ if (array_key_exists('auto_budget_period', $data)) {
+ $autoBudget->period = $data['auto_budget_period'];
+ }
+
+ $autoBudget->save();
+ }
+
+ private function updateRuleActions(string $oldName, string $newName): void
+ {
+ $types = ['set_budget'];
+ $actions = RuleAction::leftJoin('rules', 'rules.id', '=', 'rule_actions.rule_id')
+ ->where('rules.user_id', $this->user->id)
+ ->whereIn('rule_actions.action_type', $types)
+ ->where('rule_actions.action_value', $oldName)
+ ->get(['rule_actions.*'])
+ ;
+ Log::debug(sprintf('Found %d actions to update.', $actions->count()));
+
+ /** @var RuleAction $action */
+ foreach ($actions as $action) {
+ $action->action_value = $newName;
+ $action->save();
+ Log::debug(sprintf('Updated action %d: %s', $action->id, $action->action_value));
+ }
+ }
+
+ private function updateRuleTriggers(string $oldName, string $newName): void
+ {
+ $types = ['budget_is'];
+ $triggers = RuleTrigger::leftJoin('rules', 'rules.id', '=', 'rule_triggers.rule_id')
+ ->where('rules.user_id', $this->user->id)
+ ->whereIn('rule_triggers.trigger_type', $types)
+ ->where('rule_triggers.trigger_value', $oldName)
+ ->get(['rule_triggers.*'])
+ ;
+ Log::debug(sprintf('Found %d triggers to update.', $triggers->count()));
+
+ /** @var RuleTrigger $trigger */
+ foreach ($triggers as $trigger) {
+ $trigger->trigger_value = $newName;
+ $trigger->save();
+ Log::debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value));
+ }
}
}
diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php
index b12aed2796..79795ae236 100644
--- a/app/Repositories/Budget/BudgetRepositoryInterface.php
+++ b/app/Repositories/Budget/BudgetRepositoryInterface.php
@@ -45,10 +45,6 @@ use Illuminate\Support\Collection;
*/
interface BudgetRepositoryInterface
{
- public function budgetEndsWith(string $query, int $limit): Collection;
-
- public function budgetStartsWith(string $query, int $limit): Collection;
-
/**
* Returns the amount that is budgeted in a period.
*/
@@ -59,6 +55,10 @@ interface BudgetRepositoryInterface
*/
public function budgetedInPeriodForBudget(Budget $budget, Carbon $start, Carbon $end): array;
+ public function budgetEndsWith(string $query, int $limit): Collection;
+
+ public function budgetStartsWith(string $query, int $limit): Collection;
+
public function cleanupBudgets(): bool;
public function destroy(Budget $budget): bool;
diff --git a/app/Repositories/Budget/NoBudgetRepository.php b/app/Repositories/Budget/NoBudgetRepository.php
index 3a48f7e469..45751a082e 100644
--- a/app/Repositories/Budget/NoBudgetRepository.php
+++ b/app/Repositories/Budget/NoBudgetRepository.php
@@ -43,6 +43,25 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf
{
use UserGroupTrait;
+ #[Override]
+ public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array
+ {
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
+
+ if ($accounts instanceof Collection && $accounts->count() > 0) {
+ $collector->setAccounts($accounts);
+ }
+ if ($currency instanceof TransactionCurrency) {
+ $collector->setCurrency($currency);
+ }
+ $collector->withoutBudget();
+ $collector->withBudgetInformation();
+
+ return $collector->getExtractedJournals();
+ }
+
#[Deprecated]
public function getNoBudgetPeriodReport(Collection $accounts, Carbon $start, Carbon $end): array
{
@@ -102,23 +121,4 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf
return $summarizer->groupByCurrencyId($journals);
}
-
- #[Override]
- public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array
- {
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
-
- if ($accounts instanceof Collection && $accounts->count() > 0) {
- $collector->setAccounts($accounts);
- }
- if ($currency instanceof TransactionCurrency) {
- $collector->setCurrency($currency);
- }
- $collector->withoutBudget();
- $collector->withBudgetInformation();
-
- return $collector->getExtractedJournals();
- }
}
diff --git a/app/Repositories/Budget/NoBudgetRepositoryInterface.php b/app/Repositories/Budget/NoBudgetRepositoryInterface.php
index 13d12a1122..d0308a663e 100644
--- a/app/Repositories/Budget/NoBudgetRepositoryInterface.php
+++ b/app/Repositories/Budget/NoBudgetRepositoryInterface.php
@@ -45,10 +45,10 @@ use Illuminate\Support\Collection;
*/
interface NoBudgetRepositoryInterface
{
+ public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array;
+
#[Deprecated]
public function getNoBudgetPeriodReport(Collection $accounts, Carbon $start, Carbon $end): array;
public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array;
-
- public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array;
}
diff --git a/app/Repositories/Budget/OperationsRepository.php b/app/Repositories/Budget/OperationsRepository.php
index d7ca57ed36..5d5ec67de9 100644
--- a/app/Repositories/Budget/OperationsRepository.php
+++ b/app/Repositories/Budget/OperationsRepository.php
@@ -77,6 +77,57 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $avg;
}
+ #[Override]
+ public function collectExpenses(
+ Carbon $start,
+ Carbon $end,
+ ?Collection $accounts = null,
+ ?Collection $budgets = null,
+ ?TransactionCurrency $currency = null
+ ): array {
+ Log::debug(sprintf('Start of %s(%s, %s, array, array, "%s").', __METHOD__, $start->toW3cString(), $end->toW3cString(), $currency?->code));
+ // this collector excludes all transfers TO liabilities (which are also withdrawals)
+ // because those expenses only become expenses once they move from the liability to the friend.
+ // 2024-12-24 disable the exclusion for now.
+
+ $repository = app(AccountRepositoryInterface::class);
+ $repository->setUser($this->user);
+ $subset = $repository->getAccountsByType(config('firefly.valid_liabilities'));
+ $selection = new Collection();
+
+ /** @var Account $account */
+ foreach ($subset as $account) {
+ if ('credit' === $repository->getMetaValue($account, 'liability_direction')) {
+ $selection->push($account);
+ }
+ }
+
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector
+ ->setUser($this->user)
+ ->setRange($start, $end)
+ // ->excludeDestinationAccounts($selection)
+ ->setTypes([TransactionTypeEnum::WITHDRAWAL->value])
+ ;
+
+ if ($accounts instanceof Collection) {
+ $collector->setAccounts($accounts);
+ }
+ if (!$budgets instanceof Collection) {
+ $budgets = $this->getBudgets();
+ }
+ if ($currency instanceof TransactionCurrency) {
+ Log::debug(sprintf('Limit to normal currency %s', $currency->code));
+ $collector->setNormalCurrency($currency);
+ }
+ if ($budgets->count() > 0) {
+ $collector->setBudgets($budgets);
+ }
+
+ return $collector->getExtractedJournals();
+ }
+
/**
* This method is being used to generate the budget overview in the year/multi-year report. Its used
* in both the year/multi-year budget overview AND in the accompanying chart.
@@ -217,77 +268,6 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $array;
}
- private function getBudgets(): Collection
- {
- /** @var BudgetRepositoryInterface $repos */
- $repos = app(BudgetRepositoryInterface::class);
-
- return $repos->getActiveBudgets();
- }
-
- /**
- * @SuppressWarnings("PHPMD.ExcessiveParameterList")
- */
- public function sumExpenses(
- Carbon $start,
- Carbon $end,
- ?Collection $accounts = null,
- ?Collection $budgets = null,
- ?TransactionCurrency $currency = null,
- bool $convertToPrimary = false
- ): array {
- Log::debug(sprintf('Start of %s(date, date, array, array, "%s", %s).', __METHOD__, $currency?->code, var_export($convertToPrimary, true)));
- // this collector excludes all transfers TO liabilities (which are also withdrawals)
- // because those expenses only become expenses once they move from the liability to the friend.
- // 2024-12-24 disable the exclusion for now.
-
- $repository = app(AccountRepositoryInterface::class);
- $repository->setUser($this->user);
- $subset = $repository->getAccountsByType(config('firefly.valid_liabilities'));
- $selection = new Collection();
-
- /** @var Account $account */
- foreach ($subset as $account) {
- if ('credit' === $repository->getMetaValue($account, 'liability_direction')) {
- $selection->push($account);
- }
- }
-
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector
- ->setUser($this->user)
- ->setRange($start, $end)
- // ->excludeDestinationAccounts($selection)
- ->setTypes([TransactionTypeEnum::WITHDRAWAL->value])
- ;
-
- if ($accounts instanceof Collection) {
- $collector->setAccounts($accounts);
- }
- if (!$budgets instanceof Collection) {
- $budgets = $this->getBudgets();
- }
- if ($currency instanceof TransactionCurrency) {
- Log::debug(sprintf('Limit to normal currency %s', $currency->code));
- $collector->setNormalCurrency($currency);
- }
- if ($budgets->count() > 0) {
- $collector->setBudgets($budgets);
- }
- $journals = $collector->getExtractedJournals();
-
- // same but for transactions in the foreign currency:
- if ($currency instanceof TransactionCurrency) {
- Log::debug('STOP looking for transactions in the foreign currency.');
- }
- $summarizer = new TransactionSummarizer($this->user);
- // 2025-04-21 overrule "convertToPrimary" because in this particular view, we never want to do this.
- $summarizer->setConvertToPrimary($convertToPrimary);
-
- return $summarizer->groupByCurrencyId($journals, 'negative', false);
- }
-
public function sumCollectedExpenses(
array $expenses,
Carbon $start,
@@ -320,15 +300,18 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $summarizer->groupByCurrencyId($expenses, 'negative', false);
}
- #[Override]
- public function collectExpenses(
+ /**
+ * @SuppressWarnings("PHPMD.ExcessiveParameterList")
+ */
+ public function sumExpenses(
Carbon $start,
Carbon $end,
?Collection $accounts = null,
?Collection $budgets = null,
- ?TransactionCurrency $currency = null
+ ?TransactionCurrency $currency = null,
+ bool $convertToPrimary = false
): array {
- Log::debug(sprintf('Start of %s(%s, %s, array, array, "%s").', __METHOD__, $start->toW3cString(), $end->toW3cString(), $currency?->code));
+ Log::debug(sprintf('Start of %s(date, date, array, array, "%s", %s).', __METHOD__, $currency?->code, var_export($convertToPrimary, true)));
// this collector excludes all transfers TO liabilities (which are also withdrawals)
// because those expenses only become expenses once they move from the liability to the friend.
// 2024-12-24 disable the exclusion for now.
@@ -367,7 +350,24 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
if ($budgets->count() > 0) {
$collector->setBudgets($budgets);
}
+ $journals = $collector->getExtractedJournals();
- return $collector->getExtractedJournals();
+ // same but for transactions in the foreign currency:
+ if ($currency instanceof TransactionCurrency) {
+ Log::debug('STOP looking for transactions in the foreign currency.');
+ }
+ $summarizer = new TransactionSummarizer($this->user);
+ // 2025-04-21 overrule "convertToPrimary" because in this particular view, we never want to do this.
+ $summarizer->setConvertToPrimary($convertToPrimary);
+
+ return $summarizer->groupByCurrencyId($journals, 'negative', false);
+ }
+
+ private function getBudgets(): Collection
+ {
+ /** @var BudgetRepositoryInterface $repos */
+ $repos = app(BudgetRepositoryInterface::class);
+
+ return $repos->getActiveBudgets();
}
}
diff --git a/app/Repositories/Budget/OperationsRepositoryInterface.php b/app/Repositories/Budget/OperationsRepositoryInterface.php
index d2f41f8f00..fa1acb7d53 100644
--- a/app/Repositories/Budget/OperationsRepositoryInterface.php
+++ b/app/Repositories/Budget/OperationsRepositoryInterface.php
@@ -52,6 +52,14 @@ interface OperationsRepositoryInterface
*/
public function budgetedPerDay(Budget $budget): string;
+ public function collectExpenses(
+ Carbon $start,
+ Carbon $end,
+ ?Collection $accounts = null,
+ ?Collection $budgets = null,
+ ?TransactionCurrency $currency = null
+ ): array;
+
#[Deprecated]
public function getBudgetPeriodReport(Collection $budgets, Collection $accounts, Carbon $start, Carbon $end): array;
@@ -62,18 +70,6 @@ interface OperationsRepositoryInterface
*/
public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $budgets = null): array;
- /**
- * @SuppressWarnings("PHPMD.ExcessiveParameterList")
- */
- public function sumExpenses(
- Carbon $start,
- Carbon $end,
- ?Collection $accounts = null,
- ?Collection $budgets = null,
- ?TransactionCurrency $currency = null,
- bool $convertToPrimary = false
- ): array;
-
public function sumCollectedExpenses(
array $expenses,
Carbon $start,
@@ -84,11 +80,15 @@ interface OperationsRepositoryInterface
public function sumCollectedExpensesByBudget(array $expenses, Budget $budget, bool $convertToPrimary = false): array;
- public function collectExpenses(
+ /**
+ * @SuppressWarnings("PHPMD.ExcessiveParameterList")
+ */
+ public function sumExpenses(
Carbon $start,
Carbon $end,
?Collection $accounts = null,
?Collection $budgets = null,
- ?TransactionCurrency $currency = null
+ ?TransactionCurrency $currency = null,
+ bool $convertToPrimary = false
): array;
}
diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php
index 8fd410c4e9..003966c82a 100644
--- a/app/Repositories/Category/CategoryRepository.php
+++ b/app/Repositories/Category/CategoryRepository.php
@@ -96,15 +96,24 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
}
/**
- * Returns a list of all the categories belonging to a user.
+ * Find a category or return NULL
*/
- public function getCategories(): Collection
+ public function find(int $categoryId): ?Category
+ {
+ /** @var null|Category */
+ return $this->user->categories()->find($categoryId);
+ }
+
+ /**
+ * Find a category.
+ */
+ public function findByName(string $name): ?Category
{
+ /** @var null|Category */
return $this->user
->categories()
- ->with(['attachments'])
- ->orderBy('name', 'ASC')
- ->get()
+ ->where('name', $name)
+ ->first(['categories.*'])
;
}
@@ -132,69 +141,6 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
return $result;
}
- /**
- * Find a category or return NULL
- */
- public function find(int $categoryId): ?Category
- {
- /** @var null|Category */
- return $this->user->categories()->find($categoryId);
- }
-
- /**
- * Find a category.
- */
- public function findByName(string $name): ?Category
- {
- /** @var null|Category */
- return $this->user
- ->categories()
- ->where('name', $name)
- ->first(['categories.*'])
- ;
- }
-
- /**
- * @throws FireflyException
- */
- public function store(array $data): Category
- {
- /** @var CategoryFactory $factory */
- $factory = app(CategoryFactory::class);
- $factory->setUser($this->user);
-
- $category = $factory->findOrCreate(null, $data['name']);
-
- if (null === $category) {
- throw new FireflyException(sprintf('400003: Could not store new category with name "%s"', $data['name']));
- }
-
- if (array_key_exists('notes', $data) && '' === $data['notes']) {
- $this->removeNotes($category);
- }
- if (array_key_exists('notes', $data) && '' !== $data['notes']) {
- $this->updateNotes($category, $data['notes']);
- }
-
- return $category;
- }
-
- public function removeNotes(Category $category): void
- {
- $category->notes()->delete();
- }
-
- public function updateNotes(Category $category, string $notes): void
- {
- $dbNote = $category->notes()->first();
- if (null === $dbNote) {
- $dbNote = new Note();
- $dbNote->noteable()->associate($category);
- }
- $dbNote->text = trim($notes);
- $dbNote->save();
- }
-
public function firstUseDate(Category $category): ?Carbon
{
$firstJournalDate = $this->getFirstJournalDate($category);
@@ -217,31 +163,6 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
return $firstJournalDate;
}
- private function getFirstJournalDate(Category $category): ?Carbon
- {
- $query = $category->transactionJournals()->orderBy('date', 'ASC');
- $result = $query->first(['transaction_journals.*']);
-
- return $result?->date;
- }
-
- private function getFirstTransactionDate(Category $category): ?Carbon
- {
- // check transactions:
- $query = $category
- ->transactions()
- ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
- ->orderBy('transaction_journals.date', 'ASC')
- ;
-
- $lastTransaction = $query->first(['transaction_journals.*']);
- if (null !== $lastTransaction) {
- return new Carbon($lastTransaction->date);
- }
-
- return null;
- }
-
public function getAttachments(Category $category): Collection
{
$set = $category->attachments()->get();
@@ -269,6 +190,19 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
;
}
+ /**
+ * Returns a list of all the categories belonging to a user.
+ */
+ public function getCategories(): Collection
+ {
+ return $this->user
+ ->categories()
+ ->with(['attachments'])
+ ->orderBy('name', 'ASC')
+ ->get()
+ ;
+ }
+
public function getNoteText(Category $category): ?string
{
$dbNote = $category->notes()->first();
@@ -301,66 +235,6 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
return $lastJournalDate;
}
- private function getLastJournalDate(Category $category, Collection $accounts): ?Carbon
- {
- $query = $category->transactionJournals()->orderBy('date', 'DESC');
-
- if ($accounts->count() > 0) {
- $query->leftJoin('transactions as t', 't.transaction_journal_id', '=', 'transaction_journals.id');
- $query->whereIn('t.account_id', $accounts->pluck('id')->toArray());
- }
-
- $result = $query->first(['transaction_journals.*']);
-
- return $result?->date;
- }
-
- /**
- * @throws Exception
- */
- private function getLastTransactionDate(Category $category, Collection $accounts): ?Carbon
- {
- // check transactions:
- $query = $category
- ->transactions()
- ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
- ->orderBy('transaction_journals.date', 'DESC')
- ;
- if ($accounts->count() > 0) {
- // filter journals:
- $query->whereIn('transactions.account_id', $accounts->pluck('id')->toArray());
- }
-
- $lastTransaction = $query->first(['transaction_journals.*']);
- if (null !== $lastTransaction) {
- return new Carbon($lastTransaction->date);
- }
-
- return null;
- }
-
- public function searchCategory(string $query, int $limit): Collection
- {
- $search = $this->user->categories()->orderBy('name', 'ASC');
- if ('' !== $query) {
- $search->whereLike('name', sprintf('%%%s%%', $query));
- }
-
- return $search->take($limit)->get();
- }
-
- /**
- * @throws Exception
- */
- public function update(Category $category, array $data): Category
- {
- /** @var CategoryUpdateService $service */
- $service = app(CategoryUpdateService::class);
- $service->setUser($this->user);
-
- return $service->update($category, $data);
- }
-
public function periodCollection(Category $category, Carbon $start, Carbon $end): array
{
Log::debug(sprintf('periodCollection(#%d, %s, %s)', $category->id, $start->format('Y-m-d'), $end->format('Y-m-d')));
@@ -397,6 +271,133 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
'transactions.native_amount as pc_amount',
'transactions.foreign_amount',
])
- ->toArray();
+ ->toArray()
+ ;
+ }
+
+ public function removeNotes(Category $category): void
+ {
+ $category->notes()->delete();
+ }
+
+ public function searchCategory(string $query, int $limit): Collection
+ {
+ $search = $this->user->categories()->orderBy('name', 'ASC');
+ if ('' !== $query) {
+ $search->whereLike('name', sprintf('%%%s%%', $query));
+ }
+
+ return $search->take($limit)->get();
+ }
+
+ /**
+ * @throws FireflyException
+ */
+ public function store(array $data): Category
+ {
+ /** @var CategoryFactory $factory */
+ $factory = app(CategoryFactory::class);
+ $factory->setUser($this->user);
+
+ $category = $factory->findOrCreate(null, $data['name']);
+
+ if (null === $category) {
+ throw new FireflyException(sprintf('400003: Could not store new category with name "%s"', $data['name']));
+ }
+
+ if (array_key_exists('notes', $data) && '' === $data['notes']) {
+ $this->removeNotes($category);
+ }
+ if (array_key_exists('notes', $data) && '' !== $data['notes']) {
+ $this->updateNotes($category, $data['notes']);
+ }
+
+ return $category;
+ }
+
+ /**
+ * @throws Exception
+ */
+ public function update(Category $category, array $data): Category
+ {
+ /** @var CategoryUpdateService $service */
+ $service = app(CategoryUpdateService::class);
+ $service->setUser($this->user);
+
+ return $service->update($category, $data);
+ }
+
+ public function updateNotes(Category $category, string $notes): void
+ {
+ $dbNote = $category->notes()->first();
+ if (null === $dbNote) {
+ $dbNote = new Note();
+ $dbNote->noteable()->associate($category);
+ }
+ $dbNote->text = trim($notes);
+ $dbNote->save();
+ }
+
+ private function getFirstJournalDate(Category $category): ?Carbon
+ {
+ $query = $category->transactionJournals()->orderBy('date', 'ASC');
+ $result = $query->first(['transaction_journals.*']);
+
+ return $result?->date;
+ }
+
+ private function getFirstTransactionDate(Category $category): ?Carbon
+ {
+ // check transactions:
+ $query = $category
+ ->transactions()
+ ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
+ ->orderBy('transaction_journals.date', 'ASC')
+ ;
+
+ $lastTransaction = $query->first(['transaction_journals.*']);
+ if (null !== $lastTransaction) {
+ return new Carbon($lastTransaction->date);
+ }
+
+ return null;
+ }
+
+ private function getLastJournalDate(Category $category, Collection $accounts): ?Carbon
+ {
+ $query = $category->transactionJournals()->orderBy('date', 'DESC');
+
+ if ($accounts->count() > 0) {
+ $query->leftJoin('transactions as t', 't.transaction_journal_id', '=', 'transaction_journals.id');
+ $query->whereIn('t.account_id', $accounts->pluck('id')->toArray());
+ }
+
+ $result = $query->first(['transaction_journals.*']);
+
+ return $result?->date;
+ }
+
+ /**
+ * @throws Exception
+ */
+ private function getLastTransactionDate(Category $category, Collection $accounts): ?Carbon
+ {
+ // check transactions:
+ $query = $category
+ ->transactions()
+ ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
+ ->orderBy('transaction_journals.date', 'DESC')
+ ;
+ if ($accounts->count() > 0) {
+ // filter journals:
+ $query->whereIn('transactions.account_id', $accounts->pluck('id')->toArray());
+ }
+
+ $lastTransaction = $query->first(['transaction_journals.*']);
+ if (null !== $lastTransaction) {
+ return new Carbon($lastTransaction->date);
+ }
+
+ return null;
}
}
diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php
index cef58d2d17..cf48a707b0 100644
--- a/app/Repositories/Category/CategoryRepositoryInterface.php
+++ b/app/Repositories/Category/CategoryRepositoryInterface.php
@@ -48,8 +48,6 @@ interface CategoryRepositoryInterface
public function categoryStartsWith(string $query, int $limit): Collection;
- public function periodCollection(Category $category, Carbon $start, Carbon $end): array;
-
public function destroy(Category $category): bool;
/**
@@ -90,6 +88,8 @@ interface CategoryRepositoryInterface
*/
public function lastUseDate(Category $category, Collection $accounts): ?Carbon;
+ public function periodCollection(Category $category, Carbon $start, Carbon $end): array;
+
/**
* Remove notes.
*/
diff --git a/app/Repositories/Category/OperationsRepository.php b/app/Repositories/Category/OperationsRepository.php
index 518615b6de..d54219dea3 100644
--- a/app/Repositories/Category/OperationsRepository.php
+++ b/app/Repositories/Category/OperationsRepository.php
@@ -43,6 +43,58 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
{
use UserGroupTrait;
+ public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
+ {
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
+
+ if ($accounts instanceof Collection && $accounts->count() > 0) {
+ $collector->setAccounts($accounts);
+ }
+ if (!$categories instanceof Collection || 0 === $categories->count()) {
+ $categories = $this->getCategories();
+ }
+ $collector->setCategories($categories);
+ $collector->withCategoryInformation();
+
+ return $collector->getExtractedJournals();
+ }
+
+ public function collectIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
+ {
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]);
+
+ if ($accounts instanceof Collection && $accounts->count() > 0) {
+ $collector->setAccounts($accounts);
+ }
+ if (!$categories instanceof Collection || 0 === $categories->count()) {
+ $categories = $this->getCategories();
+ }
+ $collector->setCategories($categories);
+
+ return $collector->getExtractedJournals();
+ }
+
+ public function collectTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
+ {
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value]);
+
+ if ($accounts instanceof Collection && $accounts->count() > 0) {
+ $collector->setAccounts($accounts);
+ }
+ if (!$categories instanceof Collection || 0 === $categories->count()) {
+ $categories = $this->getCategories();
+ }
+ $collector->setCategories($categories);
+
+ return $collector->getExtractedJournals();
+ }
+
/**
* This method returns a list of all the withdrawal transaction journals (as arrays) set in that period
* which have the specified category set to them. It's grouped per currency, with as few details in the array
@@ -115,14 +167,6 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $array;
}
- /**
- * Returns a list of all the categories belonging to a user.
- */
- private function getCategories(): Collection
- {
- return $this->user->categories()->get();
- }
-
/**
* This method returns a list of all the deposit transaction journals (as arrays) set in that period
* which have the specified category set to them. It's grouped per currency, with as few details in the array
@@ -326,6 +370,18 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $array;
}
+ public function sumCollectedTransactionsByCategory(array $expenses, Category $category, string $method, bool $convertToPrimary = false): array
+ {
+ Log::debug(sprintf('Start of %s.', __METHOD__));
+ $summarizer = new TransactionSummarizer($this->user);
+ $summarizer->setConvertToPrimary($convertToPrimary);
+
+ // filter $journals by range AND currency if it is present.
+ $expenses = array_filter($expenses, static fn (array $expense): bool => $expense['category_id'] === $category->id);
+
+ return $summarizer->groupByCurrencyId($expenses, $method, false);
+ }
+
/**
* Sum of withdrawal journals in period for a set of categories, grouped per currency. Amounts are always negative.
*/
@@ -451,67 +507,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $array;
}
- public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
- {
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
-
- if ($accounts instanceof Collection && $accounts->count() > 0) {
- $collector->setAccounts($accounts);
- }
- if (!$categories instanceof Collection || 0 === $categories->count()) {
- $categories = $this->getCategories();
- }
- $collector->setCategories($categories);
- $collector->withCategoryInformation();
-
- return $collector->getExtractedJournals();
- }
-
- public function collectIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
- {
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]);
-
- if ($accounts instanceof Collection && $accounts->count() > 0) {
- $collector->setAccounts($accounts);
- }
- if (!$categories instanceof Collection || 0 === $categories->count()) {
- $categories = $this->getCategories();
- }
- $collector->setCategories($categories);
-
- return $collector->getExtractedJournals();
- }
-
- public function collectTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array
- {
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value]);
-
- if ($accounts instanceof Collection && $accounts->count() > 0) {
- $collector->setAccounts($accounts);
- }
- if (!$categories instanceof Collection || 0 === $categories->count()) {
- $categories = $this->getCategories();
- }
- $collector->setCategories($categories);
-
- return $collector->getExtractedJournals();
- }
-
- public function sumCollectedTransactionsByCategory(array $expenses, Category $category, string $method, bool $convertToPrimary = false): array
+ /**
+ * Returns a list of all the categories belonging to a user.
+ */
+ private function getCategories(): Collection
{
- Log::debug(sprintf('Start of %s.', __METHOD__));
- $summarizer = new TransactionSummarizer($this->user);
- $summarizer->setConvertToPrimary($convertToPrimary);
-
- // filter $journals by range AND currency if it is present.
- $expenses = array_filter($expenses, static fn (array $expense): bool => $expense['category_id'] === $category->id);
-
- return $summarizer->groupByCurrencyId($expenses, $method, false);
+ return $this->user->categories()->get();
}
}
diff --git a/app/Repositories/Category/OperationsRepositoryInterface.php b/app/Repositories/Category/OperationsRepositoryInterface.php
index e8fcdab41b..07ca9daec7 100644
--- a/app/Repositories/Category/OperationsRepositoryInterface.php
+++ b/app/Repositories/Category/OperationsRepositoryInterface.php
@@ -44,6 +44,12 @@ use Illuminate\Support\Collection;
*/
interface OperationsRepositoryInterface
{
+ public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
+
+ public function collectIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
+
+ public function collectTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
+
/**
* This method returns a list of all the withdrawal transaction journals (as arrays) set in that period
* which have the specified category set to them. It's grouped per currency, with as few details in the array
@@ -74,19 +80,13 @@ interface OperationsRepositoryInterface
*/
public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array;
+ public function sumCollectedTransactionsByCategory(array $expenses, Category $category, string $method, bool $convertToPrimary = false): array;
+
/**
* Sum of withdrawal journals in period for a set of categories, grouped per currency. Amounts are always negative.
*/
public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
- public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
-
- public function collectIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
-
- public function collectTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array;
-
- public function sumCollectedTransactionsByCategory(array $expenses, Category $category, string $method, bool $convertToPrimary = false): array;
-
/**
* Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive.
*/
diff --git a/app/Repositories/Currency/CurrencyRepository.php b/app/Repositories/Currency/CurrencyRepository.php
index 74e8958f64..a16287a666 100644
--- a/app/Repositories/Currency/CurrencyRepository.php
+++ b/app/Repositories/Currency/CurrencyRepository.php
@@ -179,52 +179,6 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
return null;
}
- private function countJournals(TransactionCurrency $currency): int
- {
- $count = $currency->transactions()->whereNull('deleted_at')->count() + $currency->transactionJournals()->whereNull('deleted_at')->count();
-
- // also count foreign:
- return $count + Transaction::where('foreign_currency_id', $currency->id)->count();
- }
-
- /**
- * Returns ALL currencies, regardless of whether they are enabled or not.
- */
- public function getAll(): Collection
- {
- $all = TransactionCurrency::orderBy('code', 'ASC')->get();
- $local = $this->get();
-
- return $all->map(static function (TransactionCurrency $current) use ($local): TransactionCurrency {
- $hasId = $local->contains(static fn (TransactionCurrency $entry): bool => $entry->id === $current->id);
- $isPrimary = $local->contains(
- static fn (TransactionCurrency $entry): bool => 1 === (int) $entry->pivot->group_default && $entry->id === $current->id
- );
- $current->userGroupEnabled = $hasId;
- $current->userGroupNative = $isPrimary;
-
- return $current;
- });
- }
-
- public function get(): Collection
- {
- $all = $this->userGroup
- ->currencies()
- ->orderBy('code', 'ASC')
- ->withPivot(['group_default'])
- ->get()
- ;
- $all->map(static function (TransactionCurrency $current): TransactionCurrency { // @phpstan-ignore-line
- $current->userGroupEnabled = true;
- $current->userGroupNative = 1 === (int) $current->pivot->group_default;
-
- return $current;
- });
-
- return $all;
- }
-
public function destroy(TransactionCurrency $currency): bool
{
/** @var UserRepositoryInterface $repository */
@@ -245,6 +199,39 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
$currency->save();
}
+ public function enable(TransactionCurrency $currency): void
+ {
+ $this->userGroup->currencies()->syncWithoutDetaching([$currency->id]);
+ $currency->enabled = false;
+ $currency->save();
+ }
+
+ #[Override]
+ public function find(int $currencyId): ?TransactionCurrency
+ {
+ try {
+ $result = Amount::getTransactionCurrencyById($currencyId);
+ } catch (FireflyException) {
+ return null;
+ }
+
+ return $result;
+ }
+
+ /**
+ * Find by currency code, return NULL if unfound.
+ */
+ public function findByCode(string $currencyCode): ?TransactionCurrency
+ {
+ try {
+ $result = Amount::getTransactionCurrencyByCode($currencyCode);
+ } catch (FireflyException) {
+ return null;
+ }
+
+ return $result;
+ }
+
public function findByName(string $name): ?TransactionCurrency
{
return TransactionCurrency::where('name', $name)->first();
@@ -303,37 +290,42 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
return null;
}
- #[Override]
- public function find(int $currencyId): ?TransactionCurrency
+ public function get(): Collection
{
- try {
- $result = Amount::getTransactionCurrencyById($currencyId);
- } catch (FireflyException) {
- return null;
- }
+ $all = $this->userGroup
+ ->currencies()
+ ->orderBy('code', 'ASC')
+ ->withPivot(['group_default'])
+ ->get()
+ ;
+ $all->map(static function (TransactionCurrency $current): TransactionCurrency { // @phpstan-ignore-line
+ $current->userGroupEnabled = true;
+ $current->userGroupNative = 1 === (int) $current->pivot->group_default;
- return $result;
+ return $current;
+ });
+
+ return $all;
}
/**
- * Find by currency code, return NULL if unfound.
+ * Returns ALL currencies, regardless of whether they are enabled or not.
*/
- public function findByCode(string $currencyCode): ?TransactionCurrency
+ public function getAll(): Collection
{
- try {
- $result = Amount::getTransactionCurrencyByCode($currencyCode);
- } catch (FireflyException) {
- return null;
- }
+ $all = TransactionCurrency::orderBy('code', 'ASC')->get();
+ $local = $this->get();
- return $result;
- }
+ return $all->map(static function (TransactionCurrency $current) use ($local): TransactionCurrency {
+ $hasId = $local->contains(static fn (TransactionCurrency $entry): bool => $entry->id === $current->id);
+ $isPrimary = $local->contains(
+ static fn (TransactionCurrency $entry): bool => 1 === (int) $entry->pivot->group_default && $entry->id === $current->id
+ );
+ $current->userGroupEnabled = $hasId;
+ $current->userGroupNative = $isPrimary;
- public function enable(TransactionCurrency $currency): void
- {
- $this->userGroup->currencies()->syncWithoutDetaching([$currency->id]);
- $currency->enabled = false;
- $currency->save();
+ return $current;
+ });
}
/**
@@ -380,6 +372,22 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
return $currency->code === config('firefly.default_currency', 'EUR');
}
+ public function makePrimary(TransactionCurrency $currency): void
+ {
+ $current = Amount::getPrimaryCurrencyByUserGroup($this->userGroup);
+ Log::debug(sprintf('Enabled + made default currency %s for user #%d', $currency->code, $this->userGroup->id));
+ $this->userGroup->currencies()->detach($currency->id);
+ foreach ($this->userGroup->currencies()->get() as $item) {
+ $this->userGroup->currencies()->updateExistingPivot($item->id, ['group_default' => false]);
+ }
+ $this->userGroup->currencies()->syncWithoutDetaching([$currency->id => ['group_default' => true]]);
+ if ($current->id !== $currency->id) {
+ Log::debug('Trigger on a different default currency.');
+ // clear all primary currency amounts through an event.
+ event(new UserGroupChangedPrimaryCurrency($this->userGroup));
+ }
+ }
+
public function searchCurrency(string $search, int $limit): Collection
{
$query = TransactionCurrency::where('enabled', true)->orderBy('code', 'ASC');
@@ -461,19 +469,11 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
return $service->update($currency, $data);
}
- public function makePrimary(TransactionCurrency $currency): void
+ private function countJournals(TransactionCurrency $currency): int
{
- $current = Amount::getPrimaryCurrencyByUserGroup($this->userGroup);
- Log::debug(sprintf('Enabled + made default currency %s for user #%d', $currency->code, $this->userGroup->id));
- $this->userGroup->currencies()->detach($currency->id);
- foreach ($this->userGroup->currencies()->get() as $item) {
- $this->userGroup->currencies()->updateExistingPivot($item->id, ['group_default' => false]);
- }
- $this->userGroup->currencies()->syncWithoutDetaching([$currency->id => ['group_default' => true]]);
- if ($current->id !== $currency->id) {
- Log::debug('Trigger on a different default currency.');
- // clear all primary currency amounts through an event.
- event(new UserGroupChangedPrimaryCurrency($this->userGroup));
- }
+ $count = $currency->transactions()->whereNull('deleted_at')->count() + $currency->transactionJournals()->whereNull('deleted_at')->count();
+
+ // also count foreign:
+ return $count + Transaction::where('foreign_currency_id', $currency->id)->count();
}
}
diff --git a/app/Repositories/ExchangeRate/ExchangeRateRepository.php b/app/Repositories/ExchangeRate/ExchangeRateRepository.php
index fcc6f0b432..e158960721 100644
--- a/app/Repositories/ExchangeRate/ExchangeRateRepository.php
+++ b/app/Repositories/ExchangeRate/ExchangeRateRepository.php
@@ -47,6 +47,16 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro
;
}
+ public function deleteRates(TransactionCurrency $from, TransactionCurrency $to): void
+ {
+ $this->userGroup
+ ->currencyExchangeRates()
+ ->where('from_currency_id', $from->id)
+ ->where('to_currency_id', $to->id)
+ ->delete()
+ ;
+ }
+
#[Override]
public function getAll(): Collection
{
@@ -115,13 +125,4 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro
return $object;
}
-
- public function deleteRates(TransactionCurrency $from, TransactionCurrency $to): void
- {
- $this->userGroup
- ->currencyExchangeRates()
- ->where('from_currency_id', $from->id)
- ->where('to_currency_id', $to->id)
- ->delete();
- }
}
diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php
index 7eb52b496f..4a3d714440 100644
--- a/app/Repositories/Journal/JournalRepository.php
+++ b/app/Repositories/Journal/JournalRepository.php
@@ -62,6 +62,15 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac
$service->destroy($journal);
}
+ /**
+ * Find a specific journal.
+ */
+ public function find(int $journalId): ?TransactionJournal
+ {
+ /** @var null|TransactionJournal */
+ return $this->user->transactionJournals()->find($journalId);
+ }
+
public function findByType(array $types): Collection
{
return $this->user
@@ -84,6 +93,12 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac
;
}
+ #[Override]
+ public function getAllUncompletedJournals(): Collection
+ {
+ return TransactionJournal::where('completed', false)->get(['transaction_journals.*']);
+ }
+
public function getDestinationAccount(TransactionJournal $journal): Account
{
/** @var null|Transaction $transaction */
@@ -166,6 +181,22 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac
return $transaction->account;
}
+ #[Override]
+ public function getUncompletedJournals(): Collection
+ {
+ return $this->userGroup
+ ->transactionJournals()
+ ->where('completed', false)
+ ->get(['transaction_journals.*'])
+ ;
+ }
+
+ #[Override]
+ public function markAsCompleted(Collection $set): void
+ {
+ TransactionJournal::whereIn('id', $set->pluck('id')->toArray())->update(['completed' => true]);
+ }
+
public function reconcileById(int $journalId): void
{
/** @var null|TransactionJournal $journal */
@@ -173,15 +204,6 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac
$journal?->transactions()->update(['reconciled' => true]);
}
- /**
- * Find a specific journal.
- */
- public function find(int $journalId): ?TransactionJournal
- {
- /** @var null|TransactionJournal */
- return $this->user->transactionJournals()->find($journalId);
- }
-
/**
* Search in journal descriptions.
*/
@@ -251,26 +273,4 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac
return $journal;
}
-
- #[Override]
- public function getUncompletedJournals(): Collection
- {
- return $this->userGroup
- ->transactionJournals()
- ->where('completed', false)
- ->get(['transaction_journals.*'])
- ;
- }
-
- #[Override]
- public function getAllUncompletedJournals(): Collection
- {
- return TransactionJournal::where('completed', false)->get(['transaction_journals.*']);
- }
-
- #[Override]
- public function markAsCompleted(Collection $set): void
- {
- TransactionJournal::whereIn('id', $set->pluck('id')->toArray())->update(['completed' => true]);
- }
}
diff --git a/app/Repositories/Journal/JournalRepositoryInterface.php b/app/Repositories/Journal/JournalRepositoryInterface.php
index 0a30d87c5f..cd56939b56 100644
--- a/app/Repositories/Journal/JournalRepositoryInterface.php
+++ b/app/Repositories/Journal/JournalRepositoryInterface.php
@@ -52,12 +52,6 @@ interface JournalRepositoryInterface
*/
public function destroyGroup(TransactionGroup $transactionGroup): void;
- public function getUncompletedJournals(): Collection;
-
- public function getAllUncompletedJournals(): Collection;
-
- public function markAsCompleted(Collection $set): void;
-
/**
* Deletes a journal.
*/
@@ -75,6 +69,8 @@ interface JournalRepositoryInterface
*/
public function firstNull(): ?TransactionJournal;
+ public function getAllUncompletedJournals(): Collection;
+
/**
* Returns the destination account of the journal.
*
@@ -103,6 +99,10 @@ interface JournalRepositoryInterface
*/
public function getSourceAccount(TransactionJournal $journal): Account;
+ public function getUncompletedJournals(): Collection;
+
+ public function markAsCompleted(Collection $set): void;
+
/**
* TODO Maybe to account repository? Do this wen reconcile is API only.
*/
diff --git a/app/Repositories/LinkType/LinkTypeRepository.php b/app/Repositories/LinkType/LinkTypeRepository.php
index def2c260f9..64892381ac 100644
--- a/app/Repositories/LinkType/LinkTypeRepository.php
+++ b/app/Repositories/LinkType/LinkTypeRepository.php
@@ -55,22 +55,6 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
return true;
}
- public function update(LinkType $linkType, array $data): LinkType
- {
- if (array_key_exists('name', $data) && '' !== (string) $data['name']) {
- $linkType->name = $data['name'];
- }
- if (array_key_exists('inward', $data) && '' !== (string) $data['inward']) {
- $linkType->inward = $data['inward'];
- }
- if (array_key_exists('outward', $data) && '' !== (string) $data['outward']) {
- $linkType->outward = $data['outward'];
- }
- $linkType->save();
-
- return $linkType;
- }
-
/**
* @throws Exception
*/
@@ -81,6 +65,20 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
return true;
}
+ public function find(int $linkTypeId): ?LinkType
+ {
+ return LinkType::find($linkTypeId);
+ }
+
+ public function findByName(?string $name = null): ?LinkType
+ {
+ if (null === $name) {
+ return null;
+ }
+
+ return LinkType::where('name', $name)->first();
+ }
+
/**
* Check if link exists between journals.
*/
@@ -93,6 +91,23 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
return ($count + $opposingCount) > 0;
}
+ /**
+ * See if such a link already exists (and get it).
+ */
+ public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink
+ {
+ return TransactionJournalLink::where('link_type_id', $linkType->id)
+ ->where('source_id', $inward->id)
+ ->where('destination_id', $outward->id)
+ ->first()
+ ;
+ }
+
+ public function get(): Collection
+ {
+ return LinkType::orderBy('name', 'ASC')->get();
+ }
+
/**
* Return array of all journal ID's for this type of link.
*/
@@ -105,11 +120,6 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
return array_unique(array_merge($sources, $destinations));
}
- public function get(): Collection
- {
- return LinkType::orderBy('name', 'ASC')->get();
- }
-
/**
* Returns all the journal links (of a specific type).
*/
@@ -209,49 +219,14 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
return $link;
}
- public function find(int $linkTypeId): ?LinkType
- {
- return LinkType::find($linkTypeId);
- }
-
- public function findByName(?string $name = null): ?LinkType
- {
- if (null === $name) {
- return null;
- }
-
- return LinkType::where('name', $name)->first();
- }
-
- /**
- * See if such a link already exists (and get it).
- */
- public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink
- {
- return TransactionJournalLink::where('link_type_id', $linkType->id)
- ->where('source_id', $inward->id)
- ->where('destination_id', $outward->id)
- ->first()
- ;
- }
-
- /**
- * @throws Exception
- */
- private function setNoteText(TransactionJournalLink $link, string $text): void
+ public function switchLink(TransactionJournalLink $link): bool
{
- $dbNote = $link->notes()->first();
- if ('' !== $text) {
- if (null === $dbNote) {
- $dbNote = new Note();
- $dbNote->noteable()->associate($link);
- }
- $dbNote->text = trim($text);
- $dbNote->save();
+ $source = $link->source_id;
+ $link->source_id = $link->destination_id;
+ $link->destination_id = $source;
+ $link->save();
- return;
- }
- $dbNote?->delete();
+ return true;
}
public function switchLinkById(int $linkId): bool
@@ -265,14 +240,20 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
return true;
}
- public function switchLink(TransactionJournalLink $link): bool
+ public function update(LinkType $linkType, array $data): LinkType
{
- $source = $link->source_id;
- $link->source_id = $link->destination_id;
- $link->destination_id = $source;
- $link->save();
+ if (array_key_exists('name', $data) && '' !== (string) $data['name']) {
+ $linkType->name = $data['name'];
+ }
+ if (array_key_exists('inward', $data) && '' !== (string) $data['inward']) {
+ $linkType->inward = $data['inward'];
+ }
+ if (array_key_exists('outward', $data) && '' !== (string) $data['outward']) {
+ $linkType->outward = $data['outward'];
+ }
+ $linkType->save();
- return true;
+ return $linkType;
}
/**
@@ -302,4 +283,23 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
return $journalLink;
}
+
+ /**
+ * @throws Exception
+ */
+ private function setNoteText(TransactionJournalLink $link, string $text): void
+ {
+ $dbNote = $link->notes()->first();
+ if ('' !== $text) {
+ if (null === $dbNote) {
+ $dbNote = new Note();
+ $dbNote->noteable()->associate($link);
+ }
+ $dbNote->text = trim($text);
+ $dbNote->save();
+
+ return;
+ }
+ $dbNote?->delete();
+ }
}
diff --git a/app/Repositories/ObjectGroup/CreatesObjectGroups.php b/app/Repositories/ObjectGroup/CreatesObjectGroups.php
index e77d7823ea..bd68339e45 100644
--- a/app/Repositories/ObjectGroup/CreatesObjectGroups.php
+++ b/app/Repositories/ObjectGroup/CreatesObjectGroups.php
@@ -31,6 +31,16 @@ use FireflyIII\Models\ObjectGroup;
*/
trait CreatesObjectGroups
{
+ protected function findObjectGroup(string $title): ?ObjectGroup
+ {
+ /** @var null|ObjectGroup */
+ return $this->user
+ ->objectGroups()
+ ->where('title', $title)
+ ->first()
+ ;
+ }
+
protected function findObjectGroupById(int $groupId): ?ObjectGroup
{
/** @var null|ObjectGroup */
@@ -70,14 +80,4 @@ trait CreatesObjectGroups
->count()
;
}
-
- protected function findObjectGroup(string $title): ?ObjectGroup
- {
- /** @var null|ObjectGroup */
- return $this->user
- ->objectGroups()
- ->where('title', $title)
- ->first()
- ;
- }
}
diff --git a/app/Repositories/ObjectGroup/ObjectGroupRepository.php b/app/Repositories/ObjectGroup/ObjectGroupRepository.php
index 449c1669de..e5b258a3f6 100644
--- a/app/Repositories/ObjectGroup/ObjectGroupRepository.php
+++ b/app/Repositories/ObjectGroup/ObjectGroupRepository.php
@@ -51,17 +51,6 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup
}
}
- public function get(): Collection
- {
- return $this->user
- ->objectGroups()
- ->with(['piggyBanks', 'bills'])
- ->orderBy('order', 'ASC')
- ->orderBy('title', 'ASC')
- ->get()
- ;
- }
-
public function deleteEmpty(): void
{
$all = $this->get();
@@ -87,6 +76,17 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup
$objectGroup->delete();
}
+ public function get(): Collection
+ {
+ return $this->user
+ ->objectGroups()
+ ->with(['piggyBanks', 'bills'])
+ ->orderBy('order', 'ASC')
+ ->orderBy('title', 'ASC')
+ ->get()
+ ;
+ }
+
public function getBills(ObjectGroup $objectGroup): Collection
{
return $objectGroup->bills;
@@ -139,21 +139,6 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup
return $dbQuery->take($limit)->get(['object_groups.*']);
}
- public function update(ObjectGroup $objectGroup, array $data): ObjectGroup
- {
- if (array_key_exists('title', $data)) {
- $objectGroup->title = $data['title'];
- }
-
- if (array_key_exists('order', $data)) {
- $this->setOrder($objectGroup, (int) $data['order']);
- }
-
- $objectGroup->save();
-
- return $objectGroup;
- }
-
public function setOrder(ObjectGroup $objectGroup, int $newOrder): ObjectGroup
{
$oldOrder = $objectGroup->order;
@@ -187,4 +172,19 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup
return $objectGroup;
}
+
+ public function update(ObjectGroup $objectGroup, array $data): ObjectGroup
+ {
+ if (array_key_exists('title', $data)) {
+ $objectGroup->title = $data['title'];
+ }
+
+ if (array_key_exists('order', $data)) {
+ $this->setOrder($objectGroup, (int) $data['order']);
+ }
+
+ $objectGroup->save();
+
+ return $objectGroup;
+ }
}
diff --git a/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php b/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php
index 2a746b12a7..71aa913bf4 100644
--- a/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php
+++ b/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php
@@ -41,56 +41,11 @@ class PeriodStatisticRepository implements PeriodStatisticRepositoryInterface, U
{
use UserGroupTrait;
- public function findPeriodStatistics(Model $model, Carbon $start, Carbon $end, array $types): Collection
- {
- return $model->primaryPeriodStatistics()->where('start', $start)->where('end', $end)->whereIn('type', $types)->get();
- }
-
- public function findPeriodStatistic(Model $model, Carbon $start, Carbon $end, string $type): Collection
- {
- return $model->primaryPeriodStatistics()->where('start', $start)->where('end', $end)->where('type', $type)->get();
- }
-
- public function saveStatistic(Model $model, int $currencyId, Carbon $start, Carbon $end, string $type, int $count, string $amount): PeriodStatistic
- {
- $stat = new PeriodStatistic();
- $stat->primaryStatable()->associate($model);
- $stat->transaction_currency_id = $currencyId;
- $stat->user_group_id = $this->getUserGroup()->id;
- $stat->start = $start;
- $stat->start_tz = $start->format('e');
- $stat->end = $end;
- $stat->end_tz = $end->format('e');
- $stat->amount = $amount;
- $stat->count = $count;
- $stat->type = $type;
- $stat->save();
-
- Log::debug(sprintf(
- 'Saved #%d [currency #%d, Model %s #%d, %s to %s, %d, %s] as new statistic.',
- $stat->id,
- $model::class,
- $model->id,
- $stat->transaction_currency_id,
- $stat->start->toW3cString(),
- $stat->end->toW3cString(),
- $count,
- $amount
- ));
-
- return $stat;
- }
-
public function allInRangeForModel(Model $model, Carbon $start, Carbon $end): Collection
{
return $model->primaryPeriodStatistics()->where('start', '>=', $start)->where('end', '<=', $end)->get();
}
- public function deleteStatisticsForModel(Model $model, Carbon $date): void
- {
- $model->primaryPeriodStatistics()->where('start', '<=', $date)->where('end', '>=', $date)->delete();
- }
-
#[Override]
public function allInRangeForPrefix(string $prefix, Carbon $start, Carbon $end): Collection
{
@@ -104,39 +59,37 @@ class PeriodStatisticRepository implements PeriodStatisticRepositoryInterface, U
}
#[Override]
- public function savePrefixedStatistic(
- string $prefix,
- int $currencyId,
- Carbon $start,
- Carbon $end,
- string $type,
- int $count,
- string $amount
- ): PeriodStatistic {
- $stat = new PeriodStatistic();
- $stat->transaction_currency_id = $currencyId;
- $stat->user_group_id = $this->getUserGroup()->id;
- $stat->start = $start;
- $stat->start_tz = $start->format('e');
- $stat->end = $end;
- $stat->end_tz = $end->format('e');
- $stat->amount = $amount;
- $stat->count = $count;
- $stat->type = sprintf('%s_%s', $prefix, $type);
- $stat->save();
-
- Log::debug(sprintf(
- 'Saved #%d [currency #%d, type "%s", %s to %s, %d, %s] as new statistic.',
- $stat->id,
- $stat->transaction_currency_id,
- $stat->type,
- $stat->start->toW3cString(),
- $stat->end->toW3cString(),
- $count,
- $amount
- ));
+ public function deleteStatisticsForCollection(Collection $set): void
+ {
+ // Log::debug(sprintf('Delete statistics for %d transaction journals.', count($set)));
+ // // collect all transactions:
+ // $transactions = Transaction::whereIn('transaction_journal_id', $set->pluck('id')->toArray())->get(['transactions.*']);
+ // Log::debug('Collected transaction IDs', $transactions->pluck('id')->toArray());
+ //
+ // // collect all accounts and delete stats:
+ // $accounts = Account::whereIn('id', $transactions->pluck('account_id')->toArray())->get(['accounts.*']);
+ // Log::debug('Collected account IDs', $accounts->pluck('id')->toArray());
+ // $dates = $set->pluck('date');
+ // $this->deleteStatisticsForType(Account::class, $accounts, $dates);
+ //
+ // // remove for no tag, no cat, etc.
+ // if (0 === $categories->count()) {
+ // Log::debug('No categories, delete "no_category" stats.');
+ // $this->deleteStatisticsForPrefix('no_category', $dates);
+ // }
+ // if (0 === $budgets->count()) {
+ // Log::debug('No budgets, delete "no_category" stats.');
+ // $this->deleteStatisticsForPrefix('no_budget', $dates);
+ // }
+ // if (0 === $tags->count()) {
+ // Log::debug('No tags, delete "no_category" stats.');
+ // $this->deleteStatisticsForPrefix('no_tag', $dates);
+ // }
+ }
- return $stat;
+ public function deleteStatisticsForModel(Model $model, Carbon $date): void
+ {
+ $model->primaryPeriodStatistics()->where('start', '<=', $date)->where('end', '>=', $date)->delete();
}
#[Override]
@@ -178,32 +131,79 @@ class PeriodStatisticRepository implements PeriodStatisticRepositoryInterface, U
Log::debug(sprintf('Delete %d statistics for %dx %s', $count, $objects->count(), $class));
}
+ public function findPeriodStatistic(Model $model, Carbon $start, Carbon $end, string $type): Collection
+ {
+ return $model->primaryPeriodStatistics()->where('start', $start)->where('end', $end)->where('type', $type)->get();
+ }
+
+ public function findPeriodStatistics(Model $model, Carbon $start, Carbon $end, array $types): Collection
+ {
+ return $model->primaryPeriodStatistics()->where('start', $start)->where('end', $end)->whereIn('type', $types)->get();
+ }
+
#[Override]
- public function deleteStatisticsForCollection(Collection $set): void
+ public function savePrefixedStatistic(
+ string $prefix,
+ int $currencyId,
+ Carbon $start,
+ Carbon $end,
+ string $type,
+ int $count,
+ string $amount
+ ): PeriodStatistic {
+ $stat = new PeriodStatistic();
+ $stat->transaction_currency_id = $currencyId;
+ $stat->user_group_id = $this->getUserGroup()->id;
+ $stat->start = $start;
+ $stat->start_tz = $start->format('e');
+ $stat->end = $end;
+ $stat->end_tz = $end->format('e');
+ $stat->amount = $amount;
+ $stat->count = $count;
+ $stat->type = sprintf('%s_%s', $prefix, $type);
+ $stat->save();
+
+ Log::debug(sprintf(
+ 'Saved #%d [currency #%d, type "%s", %s to %s, %d, %s] as new statistic.',
+ $stat->id,
+ $stat->transaction_currency_id,
+ $stat->type,
+ $stat->start->toW3cString(),
+ $stat->end->toW3cString(),
+ $count,
+ $amount
+ ));
+
+ return $stat;
+ }
+
+ public function saveStatistic(Model $model, int $currencyId, Carbon $start, Carbon $end, string $type, int $count, string $amount): PeriodStatistic
{
- // Log::debug(sprintf('Delete statistics for %d transaction journals.', count($set)));
- // // collect all transactions:
- // $transactions = Transaction::whereIn('transaction_journal_id', $set->pluck('id')->toArray())->get(['transactions.*']);
- // Log::debug('Collected transaction IDs', $transactions->pluck('id')->toArray());
- //
- // // collect all accounts and delete stats:
- // $accounts = Account::whereIn('id', $transactions->pluck('account_id')->toArray())->get(['accounts.*']);
- // Log::debug('Collected account IDs', $accounts->pluck('id')->toArray());
- // $dates = $set->pluck('date');
- // $this->deleteStatisticsForType(Account::class, $accounts, $dates);
- //
- // // remove for no tag, no cat, etc.
- // if (0 === $categories->count()) {
- // Log::debug('No categories, delete "no_category" stats.');
- // $this->deleteStatisticsForPrefix('no_category', $dates);
- // }
- // if (0 === $budgets->count()) {
- // Log::debug('No budgets, delete "no_category" stats.');
- // $this->deleteStatisticsForPrefix('no_budget', $dates);
- // }
- // if (0 === $tags->count()) {
- // Log::debug('No tags, delete "no_category" stats.');
- // $this->deleteStatisticsForPrefix('no_tag', $dates);
- // }
+ $stat = new PeriodStatistic();
+ $stat->primaryStatable()->associate($model);
+ $stat->transaction_currency_id = $currencyId;
+ $stat->user_group_id = $this->getUserGroup()->id;
+ $stat->start = $start;
+ $stat->start_tz = $start->format('e');
+ $stat->end = $end;
+ $stat->end_tz = $end->format('e');
+ $stat->amount = $amount;
+ $stat->count = $count;
+ $stat->type = $type;
+ $stat->save();
+
+ Log::debug(sprintf(
+ 'Saved #%d [currency #%d, Model %s #%d, %s to %s, %d, %s] as new statistic.',
+ $stat->id,
+ $model::class,
+ $model->id,
+ $stat->transaction_currency_id,
+ $stat->start->toW3cString(),
+ $stat->end->toW3cString(),
+ $count,
+ $amount
+ ));
+
+ return $stat;
}
}
diff --git a/app/Repositories/PeriodStatistic/PeriodStatisticRepositoryInterface.php b/app/Repositories/PeriodStatistic/PeriodStatisticRepositoryInterface.php
index d74140c6d6..5291934ea9 100644
--- a/app/Repositories/PeriodStatistic/PeriodStatisticRepositoryInterface.php
+++ b/app/Repositories/PeriodStatistic/PeriodStatisticRepositoryInterface.php
@@ -31,13 +31,19 @@ use Illuminate\Support\Collection;
interface PeriodStatisticRepositoryInterface
{
+ public function allInRangeForModel(Model $model, Carbon $start, Carbon $end): Collection;
+
+ public function allInRangeForPrefix(string $prefix, Carbon $start, Carbon $end): Collection;
+
public function deleteStatisticsForCollection(Collection $set);
- public function findPeriodStatistics(Model $model, Carbon $start, Carbon $end, array $types): Collection;
+ public function deleteStatisticsForModel(Model $model, Carbon $date): void;
+
+ public function deleteStatisticsForPrefix(string $prefix, Collection $dates): void;
public function findPeriodStatistic(Model $model, Carbon $start, Carbon $end, string $type): Collection;
- public function saveStatistic(Model $model, int $currencyId, Carbon $start, Carbon $end, string $type, int $count, string $amount): PeriodStatistic;
+ public function findPeriodStatistics(Model $model, Carbon $start, Carbon $end, array $types): Collection;
public function savePrefixedStatistic(
string $prefix,
@@ -49,11 +55,5 @@ interface PeriodStatisticRepositoryInterface
string $amount
): PeriodStatistic;
- public function allInRangeForModel(Model $model, Carbon $start, Carbon $end): Collection;
-
- public function allInRangeForPrefix(string $prefix, Carbon $start, Carbon $end): Collection;
-
- public function deleteStatisticsForModel(Model $model, Carbon $date): void;
-
- public function deleteStatisticsForPrefix(string $prefix, Collection $dates): void;
+ public function saveStatistic(Model $model, int $currencyId, Carbon $start, Carbon $end, string $type, int $count, string $amount): PeriodStatistic;
}
diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
index 6255262009..95eea35f7a 100644
--- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
+++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php
@@ -49,46 +49,6 @@ trait ModifiesPiggyBanks
{
use CreatesObjectGroups;
- public function addAmountToPiggyBank(PiggyBank $piggyBank, string $amount, TransactionJournal $journal): void
- {
- Log::debug(sprintf('addAmountToPiggyBank: %s', $amount));
- if (-1 === bccomp($amount, '0')) {
- /** @var Transaction $source */
- $source = $journal->transactions()->with(['account'])->where('amount', '<', 0)->first();
- Log::debug('Remove amount.');
- $this->removeAmount($piggyBank, $source->account, bcmul($amount, '-1'), $journal);
- }
- if (1 === bccomp($amount, '0')) {
- /** @var Transaction $destination */
- $destination = $journal->transactions()->with(['account'])->where('amount', '>', 0)->first();
- Log::debug('Add amount.');
- $this->addAmount($piggyBank, $destination->account, $amount, $journal);
- }
- }
-
- public function removeAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool
- {
- $currentAmount = $this->getCurrentAmount($piggyBank, $account);
- $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot;
- $pivot->current_amount = bcsub((string) $currentAmount, $amount);
- $pivot->native_current_amount = null;
-
- // also update native_current_amount.
- $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
- if ($userCurrency->id !== $piggyBank->transaction_currency_id) {
- $converter = new ExchangeRateConverter();
- $converter->setIgnoreSettings(true);
- $pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount);
- }
-
- $pivot->save();
-
- Log::debug('ChangedAmount: removeAmount [a]: Trigger change for negative amount.');
- event(new PiggyBankAmountIsChanged($piggyBank, bcmul($amount, '-1'), $journal, null));
-
- return true;
- }
-
public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool
{
$currentAmount = $this->getCurrentAmount($piggyBank, $account);
@@ -112,6 +72,23 @@ trait ModifiesPiggyBanks
return true;
}
+ public function addAmountToPiggyBank(PiggyBank $piggyBank, string $amount, TransactionJournal $journal): void
+ {
+ Log::debug(sprintf('addAmountToPiggyBank: %s', $amount));
+ if (-1 === bccomp($amount, '0')) {
+ /** @var Transaction $source */
+ $source = $journal->transactions()->with(['account'])->where('amount', '<', 0)->first();
+ Log::debug('Remove amount.');
+ $this->removeAmount($piggyBank, $source->account, bcmul($amount, '-1'), $journal);
+ }
+ if (1 === bccomp($amount, '0')) {
+ /** @var Transaction $destination */
+ $destination = $journal->transactions()->with(['account'])->where('amount', '>', 0)->first();
+ Log::debug('Add amount.');
+ $this->addAmount($piggyBank, $destination->account, $amount, $journal);
+ }
+ }
+
public function canAddAmount(PiggyBank $piggyBank, Account $account, string $amount): bool
{
Log::debug('Now in canAddAmount');
@@ -169,6 +146,45 @@ trait ModifiesPiggyBanks
return true;
}
+ public function removeAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool
+ {
+ $currentAmount = $this->getCurrentAmount($piggyBank, $account);
+ $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot;
+ $pivot->current_amount = bcsub((string) $currentAmount, $amount);
+ $pivot->native_current_amount = null;
+
+ // also update native_current_amount.
+ $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
+ if ($userCurrency->id !== $piggyBank->transaction_currency_id) {
+ $converter = new ExchangeRateConverter();
+ $converter->setIgnoreSettings(true);
+ $pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount);
+ }
+
+ $pivot->save();
+
+ Log::debug('ChangedAmount: removeAmount [a]: Trigger change for negative amount.');
+ event(new PiggyBankAmountIsChanged($piggyBank, bcmul($amount, '-1'), $journal, null));
+
+ return true;
+ }
+
+ public function removeAmountFromAll(PiggyBank $piggyBank, string $amount): void
+ {
+ foreach ($piggyBank->accounts as $account) {
+ $current = $account->pivot->current_amount;
+ // if this account contains more than the amount, remove the amount and return.
+ if (1 === bccomp((string) $current, $amount)) {
+ $this->removeAmount($piggyBank, $account, $amount);
+
+ return;
+ }
+ // if this account contains less than the amount, remove the current amount, update the amount and continue.
+ $this->removeAmount($piggyBank, $account, $current);
+ $amount = bcsub($amount, (string) $current);
+ }
+ }
+
public function removeObjectGroup(PiggyBank $piggyBank): PiggyBank
{
$piggyBank->objectGroups()->sync([]);
@@ -212,6 +228,44 @@ trait ModifiesPiggyBanks
return $piggyBank;
}
+ public function setOrder(PiggyBank $piggyBank, int $newOrder): bool
+ {
+ $oldOrder = $piggyBank->order;
+ // Log::debug(sprintf('Will move piggy bank #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));
+ if ($newOrder > $oldOrder) {
+ 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)
+ ->where('piggy_banks.order', '<=', $newOrder)
+ ->where('piggy_banks.order', '>', $oldOrder)
+ ->where('piggy_banks.id', '!=', $piggyBank->id)
+ ->distinct()
+ ->decrement('piggy_banks.order')
+ ;
+
+ $piggyBank->order = $newOrder;
+ Log::debug(sprintf('[1] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));
+ $piggyBank->save();
+
+ return true;
+ }
+ 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)
+ ->where('piggy_banks.order', '>=', $newOrder)
+ ->where('piggy_banks.order', '<', $oldOrder)
+ ->where('piggy_banks.id', '!=', $piggyBank->id)
+ ->distinct()
+ ->increment('piggy_banks.order')
+ ;
+
+ $piggyBank->order = $newOrder;
+ Log::debug(sprintf('[2] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));
+ $piggyBank->save();
+
+ return true;
+ }
+
/**
* @throws FireflyException
*/
@@ -293,6 +347,23 @@ trait ModifiesPiggyBanks
return $piggyBank;
}
+ public function updateNote(PiggyBank $piggyBank, string $note): void
+ {
+ if ('' === $note) {
+ $dbNote = $piggyBank->notes()->first();
+ $dbNote?->delete();
+
+ return;
+ }
+ $dbNote = $piggyBank->notes()->first();
+ if (null === $dbNote) {
+ $dbNote = new Note();
+ $dbNote->noteable()->associate($piggyBank);
+ }
+ $dbNote->text = trim($note);
+ $dbNote->save();
+ }
+
private function updateProperties(PiggyBank $piggyBank, array $data): PiggyBank
{
if (array_key_exists('name', $data) && '' !== $data['name']) {
@@ -322,75 +393,4 @@ trait ModifiesPiggyBanks
return $piggyBank;
}
-
- public function updateNote(PiggyBank $piggyBank, string $note): void
- {
- if ('' === $note) {
- $dbNote = $piggyBank->notes()->first();
- $dbNote?->delete();
-
- return;
- }
- $dbNote = $piggyBank->notes()->first();
- if (null === $dbNote) {
- $dbNote = new Note();
- $dbNote->noteable()->associate($piggyBank);
- }
- $dbNote->text = trim($note);
- $dbNote->save();
- }
-
- public function setOrder(PiggyBank $piggyBank, int $newOrder): bool
- {
- $oldOrder = $piggyBank->order;
- // Log::debug(sprintf('Will move piggy bank #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));
- if ($newOrder > $oldOrder) {
- 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)
- ->where('piggy_banks.order', '<=', $newOrder)
- ->where('piggy_banks.order', '>', $oldOrder)
- ->where('piggy_banks.id', '!=', $piggyBank->id)
- ->distinct()
- ->decrement('piggy_banks.order')
- ;
-
- $piggyBank->order = $newOrder;
- Log::debug(sprintf('[1] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));
- $piggyBank->save();
-
- return true;
- }
- 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)
- ->where('piggy_banks.order', '>=', $newOrder)
- ->where('piggy_banks.order', '<', $oldOrder)
- ->where('piggy_banks.id', '!=', $piggyBank->id)
- ->distinct()
- ->increment('piggy_banks.order')
- ;
-
- $piggyBank->order = $newOrder;
- Log::debug(sprintf('[2] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder));
- $piggyBank->save();
-
- return true;
- }
-
- public function removeAmountFromAll(PiggyBank $piggyBank, string $amount): void
- {
- foreach ($piggyBank->accounts as $account) {
- $current = $account->pivot->current_amount;
- // if this account contains more than the amount, remove the amount and return.
- if (1 === bccomp((string) $current, $amount)) {
- $this->removeAmount($piggyBank, $account, $amount);
-
- return;
- }
- // if this account contains less than the amount, remove the current amount, update the amount and continue.
- $this->removeAmount($piggyBank, $account, $current);
- $amount = bcsub($amount, (string) $current);
- }
- }
}
diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php
index f4df324a66..2135fa45e5 100644
--- a/app/Repositories/PiggyBank/PiggyBankRepository.php
+++ b/app/Repositories/PiggyBank/PiggyBankRepository.php
@@ -66,6 +66,29 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
;
}
+ public function find(int $piggyBankId): ?PiggyBank
+ {
+ 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', $this->user->id)
+ ->where('piggy_banks.id', $piggyBankId)
+ ->first(['piggy_banks.*'])
+ ;
+ }
+
+ /**
+ * Find by name or return NULL.
+ */
+ public function findByName(string $name): ?PiggyBank
+ {
+ 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', $this->user->id)
+ ->where('piggy_banks.name', $name)
+ ->first(['piggy_banks.*'])
+ ;
+ }
+
public function findPiggyBank(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank
{
Log::debug('Searching for piggy information.');
@@ -91,29 +114,6 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
return null;
}
- public function find(int $piggyBankId): ?PiggyBank
- {
- 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', $this->user->id)
- ->where('piggy_banks.id', $piggyBankId)
- ->first(['piggy_banks.*'])
- ;
- }
-
- /**
- * Find by name or return NULL.
- */
- public function findByName(string $name): ?PiggyBank
- {
- 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', $this->user->id)
- ->where('piggy_banks.name', $name)
- ->first(['piggy_banks.*'])
- ;
- }
-
public function getAttachments(PiggyBank $piggyBank): Collection
{
$set = $piggyBank->attachments()->get();
@@ -129,6 +129,25 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
});
}
+ /**
+ * Get current amount saved in piggy bank.
+ */
+ public function getCurrentAmount(PiggyBank $piggyBank, ?Account $account = null): string
+ {
+ $sum = '0';
+ foreach ($piggyBank->accounts as $current) {
+ if ($account instanceof Account && $account->id !== $current->id) {
+ continue;
+ }
+ $amount = (string) $current->pivot->current_amount;
+ $amount = '' === $amount ? '0' : $amount;
+ $sum = bcadd($sum, $amount);
+ }
+ Log::debug(sprintf('Current amount in piggy bank #%d ("%s") is %s', $piggyBank->id, $piggyBank->name, $sum));
+
+ return $sum;
+ }
+
/**
* Get current amount saved in piggy bank.
*/
@@ -261,25 +280,6 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
return $amount;
}
- /**
- * Get current amount saved in piggy bank.
- */
- public function getCurrentAmount(PiggyBank $piggyBank, ?Account $account = null): string
- {
- $sum = '0';
- foreach ($piggyBank->accounts as $current) {
- if ($account instanceof Account && $account->id !== $current->id) {
- continue;
- }
- $amount = (string) $current->pivot->current_amount;
- $amount = '' === $amount ? '0' : $amount;
- $sum = bcadd($sum, $amount);
- }
- Log::debug(sprintf('Current amount in piggy bank #%d ("%s") is %s', $piggyBank->id, $piggyBank->name, $sum));
-
- return $sum;
- }
-
/**
* Return note for piggy bank.
*/
@@ -291,22 +291,6 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
return (string) $note?->text;
}
- /**
- * Also add amount in name.
- */
- public function getPiggyBanksWithAmount(): Collection
- {
- $set = $this->getPiggyBanks();
-
- /** @var PiggyBank $piggy */
- foreach ($set as $piggy) {
- $currentAmount = $this->getCurrentAmount($piggy);
- $piggy->name = sprintf('%s (%s)', $piggy->name, Amount::formatAnything($piggy->transactionCurrency, $currentAmount, false));
- }
-
- return $set;
- }
-
public function getPiggyBanks(): Collection
{
$query = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')->leftJoin(
@@ -325,6 +309,22 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
return $query->with(['objectGroups'])->orderBy('piggy_banks.order', 'ASC')->distinct()->get(['piggy_banks.*']);
}
+ /**
+ * Also add amount in name.
+ */
+ public function getPiggyBanksWithAmount(): Collection
+ {
+ $set = $this->getPiggyBanks();
+
+ /** @var PiggyBank $piggy */
+ foreach ($set as $piggy) {
+ $currentAmount = $this->getCurrentAmount($piggy);
+ $piggy->name = sprintf('%s (%s)', $piggy->name, Amount::formatAnything($piggy->transactionCurrency, $currentAmount, false));
+ }
+
+ return $set;
+ }
+
public function getRepetition(PiggyBank $piggyBank, bool $overrule = false): ?PiggyBankRepetition
{
if (false === $overrule) {
@@ -403,6 +403,16 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
;
}
+ public function resetHistory(PiggyBank $piggyBank): void
+ {
+ $piggyBank->piggyBankEvents()->delete();
+ foreach ($piggyBank->accounts as $account) {
+ if (0 !== bccomp('0', (string) $account->pivot->current_amount)) {
+ event(new PiggyBankAmountIsChanged($piggyBank, $account->pivot->current_amount, null, null));
+ }
+ }
+ }
+
#[Override]
public function resetOrder(): void
{
@@ -428,14 +438,4 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
return $search->take($limit)->get(['piggy_banks.*']);
}
-
- public function resetHistory(PiggyBank $piggyBank): void
- {
- $piggyBank->piggyBankEvents()->delete();
- foreach ($piggyBank->accounts as $account) {
- if (0 !== bccomp('0', (string) $account->pivot->current_amount)) {
- event(new PiggyBankAmountIsChanged($piggyBank, $account->pivot->current_amount, null, null));
- }
- }
- }
}
diff --git a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php
index 0f9a259942..bdcd9d138e 100644
--- a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php
+++ b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php
@@ -47,8 +47,6 @@ use Illuminate\Support\Collection;
*/
interface PiggyBankRepositoryInterface
{
- public function resetHistory(PiggyBank $piggyBank): void;
-
public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool;
public function addAmountToPiggyBank(PiggyBank $piggyBank, string $amount, TransactionJournal $journal): void;
@@ -131,6 +129,8 @@ interface PiggyBankRepositoryInterface
public function removeObjectGroup(PiggyBank $piggyBank): PiggyBank;
+ public function resetHistory(PiggyBank $piggyBank): void;
+
public function resetOrder(): void;
/**
diff --git a/app/Repositories/Recurring/RecurringRepository.php b/app/Repositories/Recurring/RecurringRepository.php
index 9d62b454d6..66cceee19b 100644
--- a/app/Repositories/Recurring/RecurringRepository.php
+++ b/app/Repositories/Recurring/RecurringRepository.php
@@ -94,21 +94,6 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
return false;
}
- /**
- * Returns all the user's recurring transactions.
- */
- public function get(): Collection
- {
- return $this->user
- ->recurrences()
- ->with(['TransactionCurrency', 'TransactionType', 'RecurrenceRepetitions', 'RecurrenceTransactions'])
- ->orderBy('active', 'DESC')
- ->orderBy('transaction_type_id', 'ASC')
- ->orderBy('title', 'ASC')
- ->get()
- ;
- }
-
/**
* Destroy a recurring transaction.
*/
@@ -125,6 +110,21 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
$this->user->recurrences()->delete();
}
+ /**
+ * Returns all the user's recurring transactions.
+ */
+ public function get(): Collection
+ {
+ return $this->user
+ ->recurrences()
+ ->with(['TransactionCurrency', 'TransactionType', 'RecurrenceRepetitions', 'RecurrenceTransactions'])
+ ->orderBy('active', 'DESC')
+ ->orderBy('transaction_type_id', 'ASC')
+ ->orderBy('title', 'ASC')
+ ->get()
+ ;
+ }
+
/**
* Get ALL recurring transactions.
*/
@@ -253,6 +253,38 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
return (string) $note?->text;
}
+ /**
+ * Generate events in the date range.
+ */
+ public function getOccurrencesInRange(RecurrenceRepetition $repetition, Carbon $start, Carbon $end): array
+ {
+ $occurrences = [];
+ $mutator = clone $start;
+ $mutator->startOfDay();
+ $skipMod = $repetition->repetition_skip + 1;
+ Log::debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type));
+ Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d')));
+
+ if ('daily' === $repetition->repetition_type) {
+ $occurrences = $this->getDailyInRange($mutator, $end, $skipMod);
+ }
+ if ('weekly' === $repetition->repetition_type) {
+ $occurrences = $this->getWeeklyInRange($mutator, $end, $skipMod, $repetition->repetition_moment);
+ }
+ if ('monthly' === $repetition->repetition_type) {
+ $occurrences = $this->getMonthlyInRange($mutator, $end, $skipMod, $repetition->repetition_moment);
+ }
+ if ('ndom' === $repetition->repetition_type) {
+ $occurrences = $this->getNdomInRange($mutator, $end, $skipMod, $repetition->repetition_moment);
+ }
+ if ('yearly' === $repetition->repetition_type) {
+ $occurrences = $this->getYearlyInRange($mutator, $end, $skipMod, $repetition->repetition_moment);
+ }
+
+ // filter out all the weekend days:
+ return $this->filterWeekends($repetition, $occurrences);
+ }
+
public function getPiggyBank(RecurrenceTransaction $transaction): ?int
{
$meta = $transaction->recurrenceTransactionMeta;
@@ -410,25 +442,17 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
return $this->filterMaxDate($repeatUntil, $occurrences);
}
- private function filterMaxDate(?Carbon $max, array $occurrences): array
+ public function markGroupsAsNow(Collection $groups): void
{
- $filtered = [];
- if (!$max instanceof Carbon) {
- foreach ($occurrences as $date) {
- if ($date->gt(today())) {
- $filtered[] = $date;
- }
- }
-
- return $filtered;
- }
- foreach ($occurrences as $date) {
- if ($date->lte($max) && $date->gt(today())) {
- $filtered[] = $date;
+ /** @var TransactionGroup $group */
+ foreach ($groups as $group) {
+ /** @var TransactionJournal $journal */
+ foreach ($group->transactionJournals as $journal) {
+ Log::debug(sprintf('Set date of journal #%d to today!', $journal->id));
+ $journal->date = now(config('app.timezone'));
+ $journal->save();
}
}
-
- return $filtered;
}
/**
@@ -505,6 +529,16 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
return $search->take($limit)->get(['id', 'title', 'description']);
}
+ #[Override]
+ public function setLatestDate(Recurrence $recurrence, ?Carbon $date): Recurrence
+ {
+ $recurrence->latest_date = $date;
+ $recurrence->latest_date_tz = $date?->format('e');
+ $recurrence->save();
+
+ return $recurrence;
+ }
+
/**
* @throws FireflyException
*/
@@ -538,38 +572,6 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
return 0;
}
- /**
- * Generate events in the date range.
- */
- public function getOccurrencesInRange(RecurrenceRepetition $repetition, Carbon $start, Carbon $end): array
- {
- $occurrences = [];
- $mutator = clone $start;
- $mutator->startOfDay();
- $skipMod = $repetition->repetition_skip + 1;
- Log::debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type));
- Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d')));
-
- if ('daily' === $repetition->repetition_type) {
- $occurrences = $this->getDailyInRange($mutator, $end, $skipMod);
- }
- if ('weekly' === $repetition->repetition_type) {
- $occurrences = $this->getWeeklyInRange($mutator, $end, $skipMod, $repetition->repetition_moment);
- }
- if ('monthly' === $repetition->repetition_type) {
- $occurrences = $this->getMonthlyInRange($mutator, $end, $skipMod, $repetition->repetition_moment);
- }
- if ('ndom' === $repetition->repetition_type) {
- $occurrences = $this->getNdomInRange($mutator, $end, $skipMod, $repetition->repetition_moment);
- }
- if ('yearly' === $repetition->repetition_type) {
- $occurrences = $this->getYearlyInRange($mutator, $end, $skipMod, $repetition->repetition_moment);
- }
-
- // filter out all the weekend days:
- return $this->filterWeekends($repetition, $occurrences);
- }
-
/**
* Update a recurring transaction.
*
@@ -583,26 +585,24 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
return $service->update($recurrence, $data);
}
- public function markGroupsAsNow(Collection $groups): void
+ private function filterMaxDate(?Carbon $max, array $occurrences): array
{
- /** @var TransactionGroup $group */
- foreach ($groups as $group) {
- /** @var TransactionJournal $journal */
- foreach ($group->transactionJournals as $journal) {
- Log::debug(sprintf('Set date of journal #%d to today!', $journal->id));
- $journal->date = now(config('app.timezone'));
- $journal->save();
+ $filtered = [];
+ if (!$max instanceof Carbon) {
+ foreach ($occurrences as $date) {
+ if ($date->gt(today())) {
+ $filtered[] = $date;
+ }
}
- }
- }
- #[Override]
- public function setLatestDate(Recurrence $recurrence, ?Carbon $date): Recurrence
- {
- $recurrence->latest_date = $date;
- $recurrence->latest_date_tz = $date?->format('e');
- $recurrence->save();
+ return $filtered;
+ }
+ foreach ($occurrences as $date) {
+ if ($date->lte($max) && $date->gt(today())) {
+ $filtered[] = $date;
+ }
+ }
- return $recurrence;
+ return $filtered;
}
}
diff --git a/app/Repositories/Recurring/RecurringRepositoryInterface.php b/app/Repositories/Recurring/RecurringRepositoryInterface.php
index 22cc3a2145..1f280a619f 100644
--- a/app/Repositories/Recurring/RecurringRepositoryInterface.php
+++ b/app/Repositories/Recurring/RecurringRepositoryInterface.php
@@ -48,8 +48,6 @@ use Illuminate\Support\Collection;
*/
interface RecurringRepositoryInterface
{
- public function setLatestDate(Recurrence $recurrence, Carbon $date): Recurrence;
-
public function createdPreviously(Recurrence $recurrence, Carbon $date): bool;
/**
@@ -150,6 +148,8 @@ interface RecurringRepositoryInterface
public function searchRecurrence(string $query, int $limit): Collection;
+ public function setLatestDate(Recurrence $recurrence, Carbon $date): Recurrence;
+
/**
* Store a new recurring transaction.
*
diff --git a/app/Repositories/Rule/RuleRepository.php b/app/Repositories/Rule/RuleRepository.php
index 836e5b44e9..d60846fbae 100644
--- a/app/Repositories/Rule/RuleRepository.php
+++ b/app/Repositories/Rule/RuleRepository.php
@@ -43,6 +43,11 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
{
use UserGroupTrait;
+ public function count(): int
+ {
+ return $this->user->rules()->count();
+ }
+
/**
* @throws Exception
*/
@@ -84,6 +89,12 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
return $newRule;
}
+ public function find(int $ruleId): ?Rule
+ {
+ /** @var null|Rule */
+ return $this->user->rules()->find($ruleId);
+ }
+
/**
* Get all the users rules.
*/
@@ -123,11 +134,6 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
return $rule->ruleTriggers()->where('trigger_type', 'user_action')->first()->trigger_value;
}
- public function count(): int
- {
- return $this->user->rules()->count();
- }
-
public function getRuleActions(Rule $rule): Collection
{
return $rule->ruleActions()->orderBy('order', 'ASC')->get();
@@ -219,6 +225,32 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
return $filtered;
}
+ public function maxOrder(RuleGroup $ruleGroup): int
+ {
+ return (int) $ruleGroup->rules()->max('order');
+ }
+
+ public function moveRule(Rule $rule, RuleGroup $ruleGroup, int $order): Rule
+ {
+ if ($rule->rule_group_id !== $ruleGroup->id) {
+ $rule->rule_group_id = $ruleGroup->id;
+ }
+ $rule->save();
+ $rule->refresh();
+ $this->setOrder($rule, $order);
+
+ return $rule;
+ }
+
+ public function resetRuleOrder(RuleGroup $ruleGroup): bool
+ {
+ $groupRepository = app(RuleGroupRepositoryInterface::class);
+ $groupRepository->setUser($ruleGroup->user);
+ $groupRepository->resetRuleOrder($ruleGroup);
+
+ return true;
+ }
+
public function searchRule(string $query, int $limit): Collection
{
$search = $this->user->rules();
@@ -230,6 +262,43 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
return $search->take($limit)->get(['id', 'title', 'description']);
}
+ public function setOrder(Rule $rule, int $newOrder): void
+ {
+ $oldOrder = $rule->order;
+ $groupId = $rule->rule_group_id;
+ $maxOrder = $this->maxOrder($rule->ruleGroup);
+ $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder;
+ Log::debug(sprintf('New order will be %d', $newOrder));
+
+ if ($newOrder > $oldOrder) {
+ $this->user
+ ->rules()
+ ->where('rules.rule_group_id', $groupId)
+ ->where('rules.order', '<=', $newOrder)
+ ->where('rules.order', '>', $oldOrder)
+ ->where('rules.id', '!=', $rule->id)
+ ->decrement('rules.order')
+ ;
+ $rule->order = $newOrder;
+ Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder));
+ $rule->save();
+
+ return;
+ }
+
+ $this->user
+ ->rules()
+ ->where('rules.rule_group_id', $groupId)
+ ->where('rules.order', '>=', $newOrder)
+ ->where('rules.order', '<', $oldOrder)
+ ->where('rules.id', '!=', $rule->id)
+ ->increment('rules.order')
+ ;
+ $rule->order = $newOrder;
+ Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder));
+ $rule->save();
+ }
+
/**
* @throws FireflyException
*/
@@ -288,10 +357,79 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
return $rule;
}
- public function find(int $ruleId): ?Rule
+ public function storeAction(Rule $rule, array $values): RuleAction
{
- /** @var null|Rule */
- return $this->user->rules()->find($ruleId);
+ $ruleAction = new RuleAction();
+ $ruleAction->rule()->associate($rule);
+ $ruleAction->order = $values['order'];
+ $ruleAction->active = $values['active'];
+ $ruleAction->stop_processing = $values['stop_processing'];
+ $ruleAction->action_type = $values['action'];
+ $ruleAction->action_value = $values['value'] ?? '';
+ $ruleAction->save();
+
+ return $ruleAction;
+ }
+
+ public function storeTrigger(Rule $rule, array $values): RuleTrigger
+ {
+ $ruleTrigger = new RuleTrigger();
+ $ruleTrigger->rule()->associate($rule);
+ $ruleTrigger->order = $values['order'];
+ $ruleTrigger->active = $values['active'];
+ $ruleTrigger->stop_processing = $values['stop_processing'];
+ $ruleTrigger->trigger_type = $values['action'];
+ $ruleTrigger->trigger_value = $values['value'] ?? '';
+ $ruleTrigger->save();
+
+ return $ruleTrigger;
+ }
+
+ public function update(Rule $rule, array $data): Rule
+ {
+ // update rule:
+ $fields = ['title', 'description', 'strict', 'rule_group_id', 'active', 'stop_processing'];
+ foreach ($fields as $field) {
+ if (array_key_exists($field, $data)) {
+ $rule->{$field} = $data[$field];
+ }
+ }
+ $rule->save();
+ $rule->refresh();
+ $group = $rule->ruleGroup;
+ // update the order:
+ $this->resetRuleOrder($group);
+ if (array_key_exists('order', $data)) {
+ $this->moveRule($rule, $group, (int) $data['order']);
+ }
+
+ // update the triggers:
+ if (array_key_exists('trigger', $data) && 'update-journal' === $data['trigger']) {
+ $this->setRuleTrigger('update-journal', $rule);
+ }
+ if (array_key_exists('trigger', $data) && 'manual-activation' === $data['trigger']) {
+ $this->setRuleTrigger('manual-activation', $rule);
+ }
+ if (array_key_exists('trigger', $data) && 'store-journal' === $data['trigger']) {
+ $this->setRuleTrigger('store-journal', $rule);
+ }
+ if (array_key_exists('triggers', $data)) {
+ // delete triggers:
+ $rule->ruleTriggers()->where('trigger_type', '!=', 'user_action')->delete();
+
+ // recreate triggers:
+ $this->storeTriggers($rule, $data);
+ }
+
+ if (array_key_exists('actions', $data)) {
+ // delete triggers:
+ $rule->ruleActions()->delete();
+
+ // recreate actions:
+ $this->storeActions($rule, $data);
+ }
+
+ return $rule;
}
private function setRuleTrigger(string $moment, Rule $rule): void
@@ -314,55 +452,23 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
$trigger->save();
}
- public function resetRuleOrder(RuleGroup $ruleGroup): bool
- {
- $groupRepository = app(RuleGroupRepositoryInterface::class);
- $groupRepository->setUser($ruleGroup->user);
- $groupRepository->resetRuleOrder($ruleGroup);
-
- return true;
- }
-
- public function setOrder(Rule $rule, int $newOrder): void
+ private function storeActions(Rule $rule, array $data): void
{
- $oldOrder = $rule->order;
- $groupId = $rule->rule_group_id;
- $maxOrder = $this->maxOrder($rule->ruleGroup);
- $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder;
- Log::debug(sprintf('New order will be %d', $newOrder));
-
- if ($newOrder > $oldOrder) {
- $this->user
- ->rules()
- ->where('rules.rule_group_id', $groupId)
- ->where('rules.order', '<=', $newOrder)
- ->where('rules.order', '>', $oldOrder)
- ->where('rules.id', '!=', $rule->id)
- ->decrement('rules.order')
- ;
- $rule->order = $newOrder;
- Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder));
- $rule->save();
-
- return;
+ $order = 1;
+ foreach ($data['actions'] as $action) {
+ $value = $action['value'] ?? '';
+ $stopProcessing = $action['stop_processing'] ?? false;
+ $active = $action['active'] ?? true;
+ $actionValues = [
+ 'action' => $action['type'],
+ 'value' => $value,
+ 'stop_processing' => $stopProcessing,
+ 'order' => $order,
+ 'active' => $active,
+ ];
+ $this->storeAction($rule, $actionValues);
+ ++$order;
}
-
- $this->user
- ->rules()
- ->where('rules.rule_group_id', $groupId)
- ->where('rules.order', '>=', $newOrder)
- ->where('rules.order', '<', $oldOrder)
- ->where('rules.id', '!=', $rule->id)
- ->increment('rules.order')
- ;
- $rule->order = $newOrder;
- Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder));
- $rule->save();
- }
-
- public function maxOrder(RuleGroup $ruleGroup): int
- {
- return (int) $ruleGroup->rules()->max('order');
}
private function storeTriggers(Rule $rule, array $data): void
@@ -417,110 +523,4 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
++$order;
}
}
-
- public function storeTrigger(Rule $rule, array $values): RuleTrigger
- {
- $ruleTrigger = new RuleTrigger();
- $ruleTrigger->rule()->associate($rule);
- $ruleTrigger->order = $values['order'];
- $ruleTrigger->active = $values['active'];
- $ruleTrigger->stop_processing = $values['stop_processing'];
- $ruleTrigger->trigger_type = $values['action'];
- $ruleTrigger->trigger_value = $values['value'] ?? '';
- $ruleTrigger->save();
-
- return $ruleTrigger;
- }
-
- private function storeActions(Rule $rule, array $data): void
- {
- $order = 1;
- foreach ($data['actions'] as $action) {
- $value = $action['value'] ?? '';
- $stopProcessing = $action['stop_processing'] ?? false;
- $active = $action['active'] ?? true;
- $actionValues = [
- 'action' => $action['type'],
- 'value' => $value,
- 'stop_processing' => $stopProcessing,
- 'order' => $order,
- 'active' => $active,
- ];
- $this->storeAction($rule, $actionValues);
- ++$order;
- }
- }
-
- public function storeAction(Rule $rule, array $values): RuleAction
- {
- $ruleAction = new RuleAction();
- $ruleAction->rule()->associate($rule);
- $ruleAction->order = $values['order'];
- $ruleAction->active = $values['active'];
- $ruleAction->stop_processing = $values['stop_processing'];
- $ruleAction->action_type = $values['action'];
- $ruleAction->action_value = $values['value'] ?? '';
- $ruleAction->save();
-
- return $ruleAction;
- }
-
- public function update(Rule $rule, array $data): Rule
- {
- // update rule:
- $fields = ['title', 'description', 'strict', 'rule_group_id', 'active', 'stop_processing'];
- foreach ($fields as $field) {
- if (array_key_exists($field, $data)) {
- $rule->{$field} = $data[$field];
- }
- }
- $rule->save();
- $rule->refresh();
- $group = $rule->ruleGroup;
- // update the order:
- $this->resetRuleOrder($group);
- if (array_key_exists('order', $data)) {
- $this->moveRule($rule, $group, (int) $data['order']);
- }
-
- // update the triggers:
- if (array_key_exists('trigger', $data) && 'update-journal' === $data['trigger']) {
- $this->setRuleTrigger('update-journal', $rule);
- }
- if (array_key_exists('trigger', $data) && 'manual-activation' === $data['trigger']) {
- $this->setRuleTrigger('manual-activation', $rule);
- }
- if (array_key_exists('trigger', $data) && 'store-journal' === $data['trigger']) {
- $this->setRuleTrigger('store-journal', $rule);
- }
- if (array_key_exists('triggers', $data)) {
- // delete triggers:
- $rule->ruleTriggers()->where('trigger_type', '!=', 'user_action')->delete();
-
- // recreate triggers:
- $this->storeTriggers($rule, $data);
- }
-
- if (array_key_exists('actions', $data)) {
- // delete triggers:
- $rule->ruleActions()->delete();
-
- // recreate actions:
- $this->storeActions($rule, $data);
- }
-
- return $rule;
- }
-
- public function moveRule(Rule $rule, RuleGroup $ruleGroup, int $order): Rule
- {
- if ($rule->rule_group_id !== $ruleGroup->id) {
- $rule->rule_group_id = $ruleGroup->id;
- }
- $rule->save();
- $rule->refresh();
- $this->setOrder($rule, $order);
-
- return $rule;
- }
}
diff --git a/app/Repositories/RuleGroup/RuleGroupRepository.php b/app/Repositories/RuleGroup/RuleGroupRepository.php
index 67a7fa6db5..40a65b9dc3 100644
--- a/app/Repositories/RuleGroup/RuleGroupRepository.php
+++ b/app/Repositories/RuleGroup/RuleGroupRepository.php
@@ -62,15 +62,6 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
}
}
- public function get(): Collection
- {
- return $this->user
- ->ruleGroups()
- ->orderBy('order', 'ASC')
- ->get()
- ;
- }
-
public function count(): int
{
return $this->user->ruleGroups()->count();
@@ -103,87 +94,6 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
return true;
}
- public function resetOrder(): bool
- {
- $set = $this->user
- ->ruleGroups()
- ->whereNull('deleted_at')
- ->orderBy('order', 'ASC')
- ->orderBy('title', 'DESC')
- ->get()
- ;
- $count = 1;
-
- /** @var RuleGroup $entry */
- foreach ($set as $entry) {
- if ($entry->order !== $count) {
- $entry->order = $count;
- $entry->save();
- }
-
- // also update rules in group.
- $this->resetRuleOrder($entry);
-
- ++$count;
- }
-
- return true;
- }
-
- public function resetRuleOrder(RuleGroup $ruleGroup): bool
- {
- $set = $ruleGroup->rules()->orderBy('order', 'ASC')->orderBy('title', 'DESC')->orderBy('updated_at', 'DESC')->get(['rules.*']);
- $count = 1;
-
- /** @var Rule $entry */
- foreach ($set as $entry) {
- if ($entry->order !== $count) {
- Log::debug(sprintf('Rule #%d was on spot %d but must be on spot %d', $entry->id, $entry->order, $count));
- $entry->order = $count;
- $entry->save();
- }
- $this->resetRuleActionOrder($entry);
- $this->resetRuleTriggerOrder($entry);
-
- ++$count;
- }
-
- return true;
- }
-
- private function resetRuleActionOrder(Rule $rule): void
- {
- $actions = $rule->ruleActions()->orderBy('order', 'ASC')->orderBy('active', 'DESC')->orderBy('action_type', 'ASC')->get();
- $index = 1;
-
- /** @var RuleAction $action */
- foreach ($actions as $action) {
- if ($action->order !== $index) {
- $action->order = $index;
- $action->save();
- Log::debug(sprintf('Rule action #%d was on spot %d but must be on spot %d', $action->id, $action->order, $index));
- }
- ++$index;
- }
- }
-
- private function resetRuleTriggerOrder(Rule $rule): void
- {
- $triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->orderBy('active', 'DESC')->orderBy('trigger_type', 'ASC')->get();
- $index = 1;
-
- /** @var RuleTrigger $trigger */
- foreach ($triggers as $trigger) {
- $order = $trigger->order;
- if ($order !== $index) {
- $trigger->order = $index;
- $trigger->save();
- Log::debug(sprintf('Rule trigger #%d was on spot %d but must be on spot %d', $trigger->id, $order, $index));
- }
- ++$index;
- }
- }
-
public function destroyAll(): void
{
Log::channel('audit')->info('Delete all rule groups through destroyAll');
@@ -212,6 +122,15 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
;
}
+ public function get(): Collection
+ {
+ return $this->user
+ ->ruleGroups()
+ ->orderBy('order', 'ASC')
+ ->get()
+ ;
+ }
+
public function getActiveGroups(): Collection
{
return $this->user
@@ -366,6 +285,54 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
;
}
+ public function resetOrder(): bool
+ {
+ $set = $this->user
+ ->ruleGroups()
+ ->whereNull('deleted_at')
+ ->orderBy('order', 'ASC')
+ ->orderBy('title', 'DESC')
+ ->get()
+ ;
+ $count = 1;
+
+ /** @var RuleGroup $entry */
+ foreach ($set as $entry) {
+ if ($entry->order !== $count) {
+ $entry->order = $count;
+ $entry->save();
+ }
+
+ // also update rules in group.
+ $this->resetRuleOrder($entry);
+
+ ++$count;
+ }
+
+ return true;
+ }
+
+ public function resetRuleOrder(RuleGroup $ruleGroup): bool
+ {
+ $set = $ruleGroup->rules()->orderBy('order', 'ASC')->orderBy('title', 'DESC')->orderBy('updated_at', 'DESC')->get(['rules.*']);
+ $count = 1;
+
+ /** @var Rule $entry */
+ foreach ($set as $entry) {
+ if ($entry->order !== $count) {
+ Log::debug(sprintf('Rule #%d was on spot %d but must be on spot %d', $entry->id, $entry->order, $count));
+ $entry->order = $count;
+ $entry->save();
+ }
+ $this->resetRuleActionOrder($entry);
+ $this->resetRuleTriggerOrder($entry);
+
+ ++$count;
+ }
+
+ return true;
+ }
+
public function searchRuleGroup(string $query, int $limit): Collection
{
$search = $this->user->ruleGroups();
@@ -377,25 +344,6 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
return $search->take($limit)->get(['id', 'title', 'description']);
}
- public function store(array $data): RuleGroup
- {
- $newRuleGroup = new RuleGroup([
- 'user_id' => $this->user->id,
- 'user_group_id' => $this->user->user_group_id,
- 'title' => $data['title'],
- 'description' => $data['description'],
- 'order' => 31337,
- 'active' => array_key_exists('active', $data) ? $data['active'] : true,
- ]);
- $newRuleGroup->save();
- $this->resetOrder();
- if (array_key_exists('order', $data)) {
- $this->setOrder($newRuleGroup, $data['order']);
- }
-
- return $newRuleGroup;
- }
-
public function setOrder(RuleGroup $ruleGroup, int $newOrder): void
{
$oldOrder = $ruleGroup->order;
@@ -427,6 +375,25 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
$ruleGroup->save();
}
+ public function store(array $data): RuleGroup
+ {
+ $newRuleGroup = new RuleGroup([
+ 'user_id' => $this->user->id,
+ 'user_group_id' => $this->user->user_group_id,
+ 'title' => $data['title'],
+ 'description' => $data['description'],
+ 'order' => 31337,
+ 'active' => array_key_exists('active', $data) ? $data['active'] : true,
+ ]);
+ $newRuleGroup->save();
+ $this->resetOrder();
+ if (array_key_exists('order', $data)) {
+ $this->setOrder($newRuleGroup, $data['order']);
+ }
+
+ return $newRuleGroup;
+ }
+
public function update(RuleGroup $ruleGroup, array $data): RuleGroup
{
// update the account:
@@ -449,4 +416,37 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
return $ruleGroup;
}
+
+ private function resetRuleActionOrder(Rule $rule): void
+ {
+ $actions = $rule->ruleActions()->orderBy('order', 'ASC')->orderBy('active', 'DESC')->orderBy('action_type', 'ASC')->get();
+ $index = 1;
+
+ /** @var RuleAction $action */
+ foreach ($actions as $action) {
+ if ($action->order !== $index) {
+ $action->order = $index;
+ $action->save();
+ Log::debug(sprintf('Rule action #%d was on spot %d but must be on spot %d', $action->id, $action->order, $index));
+ }
+ ++$index;
+ }
+ }
+
+ private function resetRuleTriggerOrder(Rule $rule): void
+ {
+ $triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->orderBy('active', 'DESC')->orderBy('trigger_type', 'ASC')->get();
+ $index = 1;
+
+ /** @var RuleTrigger $trigger */
+ foreach ($triggers as $trigger) {
+ $order = $trigger->order;
+ if ($order !== $index) {
+ $trigger->order = $index;
+ $trigger->save();
+ Log::debug(sprintf('Rule trigger #%d was on spot %d but must be on spot %d', $trigger->id, $order, $index));
+ }
+ ++$index;
+ }
+ }
}
diff --git a/app/Repositories/Tag/OperationsRepository.php b/app/Repositories/Tag/OperationsRepository.php
index 4e2f2877c6..128b4676ae 100644
--- a/app/Repositories/Tag/OperationsRepository.php
+++ b/app/Repositories/Tag/OperationsRepository.php
@@ -111,14 +111,6 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
return $array;
}
- private function getTags(): Collection
- {
- /** @var TagRepositoryInterface $repository */
- $repository = app(TagRepositoryInterface::class);
-
- return $repository->get();
- }
-
/**
* This method returns a list of all the deposit transaction journals (as arrays) set in that period
* which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array
@@ -214,4 +206,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
{
throw new FireflyException(sprintf('%s is not yet implemented.', __METHOD__));
}
+
+ private function getTags(): Collection
+ {
+ /** @var TagRepositoryInterface $repository */
+ $repository = app(TagRepositoryInterface::class);
+
+ return $repository->get();
+ }
}
diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php
index 4c0d8c29c2..6e0d13c766 100644
--- a/app/Repositories/Tag/TagRepository.php
+++ b/app/Repositories/Tag/TagRepository.php
@@ -80,15 +80,6 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
}
}
- public function get(): Collection
- {
- return $this->user
- ->tags()
- ->orderBy('tag', 'ASC')
- ->get(['tags.*'])
- ;
- }
-
public function expenseInPeriod(Tag $tag, Carbon $start, Carbon $end): array
{
/** @var GroupCollectorInterface $collector */
@@ -121,6 +112,15 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
return $tag->transactionJournals()->orderBy('date', 'ASC')->first()?->date;
}
+ public function get(): Collection
+ {
+ return $this->user
+ ->tags()
+ ->orderBy('tag', 'ASC')
+ ->get(['tags.*'])
+ ;
+ }
+
public function getAttachments(Tag $tag): Collection
{
$set = $tag->attachments()->get();
@@ -135,6 +135,12 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
});
}
+ public function getLocation(Tag $tag): ?Location
+ {
+ /** @var null|Location */
+ return $tag->locations()->first();
+ }
+
public function getTagsInYear(?int $year): array
{
// get all tags in the year (if present):
@@ -214,6 +220,47 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
;
}
+ #[Override]
+ public function periodCollection(Tag $tag, Carbon $start, Carbon $end): array
+ {
+ Log::debug(sprintf('periodCollection(#%d, %s, %s)', $tag->id, $start->format('Y-m-d'), $end->format('Y-m-d')));
+
+ return $tag
+ ->transactionJournals()
+ ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
+ ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
+ ->leftJoin('transaction_currencies', 'transaction_currencies.id', '=', 'transactions.transaction_currency_id')
+ ->leftJoin('transaction_currencies as foreign_currencies', 'foreign_currencies.id', '=', 'transactions.foreign_currency_id')
+ ->where('transaction_journals.date', '>=', $start)
+ ->where('transaction_journals.date', '<=', $end)
+ ->where('transactions.amount', '>', 0)
+ ->get([
+ // currencies
+ 'transaction_currencies.id as currency_id',
+ 'transaction_currencies.code as currency_code',
+ 'transaction_currencies.name as currency_name',
+ 'transaction_currencies.symbol as currency_symbol',
+ 'transaction_currencies.decimal_places as currency_decimal_places',
+
+ // foreign
+ 'foreign_currencies.id as foreign_currency_id',
+ 'foreign_currencies.code as foreign_currency_code',
+ 'foreign_currencies.name as foreign_currency_name',
+ 'foreign_currencies.symbol as foreign_currency_symbol',
+ 'foreign_currencies.decimal_places as foreign_currency_decimal_places',
+
+ // fields
+ 'transaction_journals.date',
+ 'transaction_types.type',
+ 'transaction_journals.transaction_currency_id',
+ 'transactions.amount',
+ 'transactions.native_amount as pc_amount',
+ 'transactions.foreign_amount',
+ ])
+ ->toArray()
+ ;
+ }
+
/**
* Find one or more tags based on the query.
*/
@@ -404,50 +451,4 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
return $tag;
}
-
- public function getLocation(Tag $tag): ?Location
- {
- /** @var null|Location */
- return $tag->locations()->first();
- }
-
- #[Override]
- public function periodCollection(Tag $tag, Carbon $start, Carbon $end): array
- {
- Log::debug(sprintf('periodCollection(#%d, %s, %s)', $tag->id, $start->format('Y-m-d'), $end->format('Y-m-d')));
-
- return $tag
- ->transactionJournals()
- ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
- ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
- ->leftJoin('transaction_currencies', 'transaction_currencies.id', '=', 'transactions.transaction_currency_id')
- ->leftJoin('transaction_currencies as foreign_currencies', 'foreign_currencies.id', '=', 'transactions.foreign_currency_id')
- ->where('transaction_journals.date', '>=', $start)
- ->where('transaction_journals.date', '<=', $end)
- ->where('transactions.amount', '>', 0)
- ->get([
- // currencies
- 'transaction_currencies.id as currency_id',
- 'transaction_currencies.code as currency_code',
- 'transaction_currencies.name as currency_name',
- 'transaction_currencies.symbol as currency_symbol',
- 'transaction_currencies.decimal_places as currency_decimal_places',
-
- // foreign
- 'foreign_currencies.id as foreign_currency_id',
- 'foreign_currencies.code as foreign_currency_code',
- 'foreign_currencies.name as foreign_currency_name',
- 'foreign_currencies.symbol as foreign_currency_symbol',
- 'foreign_currencies.decimal_places as foreign_currency_decimal_places',
-
- // fields
- 'transaction_journals.date',
- 'transaction_types.type',
- 'transaction_journals.transaction_currency_id',
- 'transactions.amount',
- 'transactions.native_amount as pc_amount',
- 'transactions.foreign_amount',
- ])
- ->toArray();
- }
}
diff --git a/app/Repositories/Tag/TagRepositoryInterface.php b/app/Repositories/Tag/TagRepositoryInterface.php
index 5a53efe7fe..1ef24a22fc 100644
--- a/app/Repositories/Tag/TagRepositoryInterface.php
+++ b/app/Repositories/Tag/TagRepositoryInterface.php
@@ -51,8 +51,6 @@ interface TagRepositoryInterface
*/
public function destroy(Tag $tag): bool;
- public function periodCollection(Tag $tag, Carbon $start, Carbon $end): array;
-
/**
* Destroy all tags.
*/
@@ -94,6 +92,8 @@ interface TagRepositoryInterface
*/
public function oldestTag(): ?Tag;
+ public function periodCollection(Tag $tag, Carbon $start, Carbon $end): array;
+
/**
* Find one or more tags based on the query.
*/
diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.php
index ed75d7d118..10ca551313 100644
--- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php
+++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php
@@ -74,15 +74,6 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
return $journal->attachments()->count();
}
- /**
- * Find a transaction group by its ID.
- */
- public function find(int $groupId): ?TransactionGroup
- {
- /** @var null|TransactionGroup */
- return $this->user->transactionGroups()->find($groupId);
- }
-
public function destroy(TransactionGroup $group): void
{
Log::debug(sprintf('Now in %s', __METHOD__));
@@ -103,44 +94,13 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
return $result;
}
- private function expandJournal(TransactionJournal $journal): array
- {
- $array = $journal->toArray();
- $array['transactions'] = [];
- $array['meta'] = $journal->transactionJournalMeta->toArray();
- $array['tags'] = $journal->tags->toArray();
- $array['categories'] = $journal->categories->toArray();
- $array['budgets'] = $journal->budgets->toArray();
- $array['notes'] = $journal->notes->toArray();
- $array['locations'] = [];
- $array['attachments'] = $journal->attachments->toArray();
- $array['links'] = [];
- $array['piggy_bank_events'] = $journal->piggyBankEvents->toArray();
-
- /** @var Transaction $transaction */
- foreach ($journal->transactions as $transaction) {
- $array['transactions'][] = $this->expandTransaction($transaction);
- }
-
- return $array;
- }
-
- private function expandTransaction(Transaction $transaction): array
+ /**
+ * Find a transaction group by its ID.
+ */
+ public function find(int $groupId): ?TransactionGroup
{
- $array = $transaction->toArray();
- $array['account'] = $transaction->account->toArray();
- $array['budgets'] = [];
- $array['categories'] = [];
-
- foreach ($transaction->categories as $category) {
- $array['categories'][] = $category->toArray();
- }
-
- foreach ($transaction->budgets as $budget) {
- $array['budgets'][] = $budget->toArray();
- }
-
- return $array;
+ /** @var null|TransactionGroup */
+ return $this->user->transactionGroups()->find($groupId);
}
/**
@@ -175,15 +135,25 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
return $result;
}
- /**
- * Get the note text for a journal (by ID).
- */
- public function getNoteText(int $journalId): ?string
+ public function getCompareHash(TransactionGroup $group): string
{
- /** @var null|Note $note */
- $note = Note::where('noteable_id', $journalId)->where('noteable_type', TransactionJournal::class)->first();
+ $sum = '0';
+ $names = '';
- return $note?->text;
+ /** @var TransactionJournal $journal */
+ foreach ($group->transactionJournals as $journal) {
+ $names = sprintf('%s%s', $names, $journal->date->format('Y-m-d-H:i:s'));
+
+ /** @var Transaction $transaction */
+ foreach ($journal->transactions as $transaction) {
+ if (-1 === bccomp('0', (string) $transaction->amount)) {
+ $sum = bcadd($sum, (string) $transaction->amount);
+ $names = sprintf('%s%s', $names, $transaction->account->name);
+ }
+ }
+ }
+
+ return hash('sha256', sprintf('%s-%s', $names, $sum));
}
/**
@@ -241,42 +211,6 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
return $return;
}
- private function getFormattedAmount(TransactionJournal $journal): string
- {
- /** @var Transaction $transaction */
- $transaction = $journal->transactions->first();
- $currency = $transaction->transactionCurrency;
- $type = $journal->transactionType->type;
- $amount = Steam::positive($transaction->amount);
- if (TransactionTypeEnum::WITHDRAWAL->value === $type) {
- return Amount::formatAnything($currency, Steam::negative($amount));
- }
-
- return Amount::formatAnything($currency, $amount);
- }
-
- private function getFormattedForeignAmount(TransactionJournal $journal): string
- {
- /** @var Transaction $transaction */
- $transaction = $journal->transactions->first();
- if (null === $transaction->foreign_amount || '' === $transaction->foreign_amount) {
- return '';
- }
-
- if (0 === bccomp('0', (string) $transaction->foreign_amount)) {
- return '';
- }
-
- $currency = $transaction->foreignCurrency;
- $type = $journal->transactionType->type;
- $amount = Steam::positive($transaction->foreign_amount);
- if (TransactionTypeEnum::WITHDRAWAL->value === $type) {
- return Amount::formatAnything($currency, Steam::negative($amount));
- }
-
- return Amount::formatAnything($currency, $amount);
- }
-
public function getLocation(int $journalId): ?Location
{
/** @var TransactionJournal $journal */
@@ -328,6 +262,17 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
return new NullArrayObject($return);
}
+ /**
+ * Get the note text for a journal (by ID).
+ */
+ public function getNoteText(int $journalId): ?string
+ {
+ /** @var null|Note $note */
+ $note = Note::where('noteable_id', $journalId)->where('noteable_type', TransactionJournal::class)->first();
+
+ return $note?->text;
+ }
+
/**
* Return all piggy bank events for all journals in the group.
*
@@ -438,24 +383,79 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
return $service->update($transactionGroup, $data);
}
- public function getCompareHash(TransactionGroup $group): string
+ private function expandJournal(TransactionJournal $journal): array
{
- $sum = '0';
- $names = '';
+ $array = $journal->toArray();
+ $array['transactions'] = [];
+ $array['meta'] = $journal->transactionJournalMeta->toArray();
+ $array['tags'] = $journal->tags->toArray();
+ $array['categories'] = $journal->categories->toArray();
+ $array['budgets'] = $journal->budgets->toArray();
+ $array['notes'] = $journal->notes->toArray();
+ $array['locations'] = [];
+ $array['attachments'] = $journal->attachments->toArray();
+ $array['links'] = [];
+ $array['piggy_bank_events'] = $journal->piggyBankEvents->toArray();
- /** @var TransactionJournal $journal */
- foreach ($group->transactionJournals as $journal) {
- $names = sprintf('%s%s', $names, $journal->date->format('Y-m-d-H:i:s'));
+ /** @var Transaction $transaction */
+ foreach ($journal->transactions as $transaction) {
+ $array['transactions'][] = $this->expandTransaction($transaction);
+ }
- /** @var Transaction $transaction */
- foreach ($journal->transactions as $transaction) {
- if (-1 === bccomp('0', (string) $transaction->amount)) {
- $sum = bcadd($sum, (string) $transaction->amount);
- $names = sprintf('%s%s', $names, $transaction->account->name);
- }
- }
+ return $array;
+ }
+
+ private function expandTransaction(Transaction $transaction): array
+ {
+ $array = $transaction->toArray();
+ $array['account'] = $transaction->account->toArray();
+ $array['budgets'] = [];
+ $array['categories'] = [];
+
+ foreach ($transaction->categories as $category) {
+ $array['categories'][] = $category->toArray();
}
- return hash('sha256', sprintf('%s-%s', $names, $sum));
+ foreach ($transaction->budgets as $budget) {
+ $array['budgets'][] = $budget->toArray();
+ }
+
+ return $array;
+ }
+
+ private function getFormattedAmount(TransactionJournal $journal): string
+ {
+ /** @var Transaction $transaction */
+ $transaction = $journal->transactions->first();
+ $currency = $transaction->transactionCurrency;
+ $type = $journal->transactionType->type;
+ $amount = Steam::positive($transaction->amount);
+ if (TransactionTypeEnum::WITHDRAWAL->value === $type) {
+ return Amount::formatAnything($currency, Steam::negative($amount));
+ }
+
+ return Amount::formatAnything($currency, $amount);
+ }
+
+ private function getFormattedForeignAmount(TransactionJournal $journal): string
+ {
+ /** @var Transaction $transaction */
+ $transaction = $journal->transactions->first();
+ if (null === $transaction->foreign_amount || '' === $transaction->foreign_amount) {
+ return '';
+ }
+
+ if (0 === bccomp('0', (string) $transaction->foreign_amount)) {
+ return '';
+ }
+
+ $currency = $transaction->foreignCurrency;
+ $type = $journal->transactionType->type;
+ $amount = Steam::positive($transaction->foreign_amount);
+ if (TransactionTypeEnum::WITHDRAWAL->value === $type) {
+ return Amount::formatAnything($currency, Steam::negative($amount));
+ }
+
+ return Amount::formatAnything($currency, $amount);
}
}
diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php
index e95cd68f75..b1481ab4a9 100644
--- a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php
+++ b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php
@@ -49,11 +49,6 @@ interface TransactionGroupRepositoryInterface
{
public function countAttachments(int $journalId): int;
- /**
- * Small method that returns a hash that can be used to compare two transaction groups.
- */
- public function getCompareHash(TransactionGroup $group): string;
-
public function destroy(TransactionGroup $group): void;
/**
@@ -71,6 +66,11 @@ interface TransactionGroupRepositoryInterface
*/
public function getAttachments(TransactionGroup $group): array;
+ /**
+ * Small method that returns a hash that can be used to compare two transaction groups.
+ */
+ public function getCompareHash(TransactionGroup $group): string;
+
/**
* Return all journal links for all journals in the group.
*/
diff --git a/app/Repositories/TransactionType/TransactionTypeRepository.php b/app/Repositories/TransactionType/TransactionTypeRepository.php
index 25cdfb741a..384838e3ea 100644
--- a/app/Repositories/TransactionType/TransactionTypeRepository.php
+++ b/app/Repositories/TransactionType/TransactionTypeRepository.php
@@ -34,6 +34,13 @@ use Illuminate\Support\Facades\Log;
*/
class TransactionTypeRepository implements TransactionTypeRepositoryInterface
{
+ public function findByType(string $type): ?TransactionType
+ {
+ $search = ucfirst($type);
+
+ return TransactionType::whereType($search)->first();
+ }
+
public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType
{
Log::debug('Now looking for a transaction type.');
@@ -52,13 +59,6 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface
return $search;
}
- public function findByType(string $type): ?TransactionType
- {
- $search = ucfirst($type);
-
- return TransactionType::whereType($search)->first();
- }
-
public function searchTypes(string $query, int $limit): Collection
{
if ('' === $query) {
diff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.php
index eae5178ce3..2831518c9d 100644
--- a/app/Repositories/User/UserRepository.php
+++ b/app/Repositories/User/UserRepository.php
@@ -46,6 +46,30 @@ use SensitiveParameter;
*/
class UserRepository implements UserRepositoryInterface
{
+ public function all(): Collection
+ {
+ return User::orderBy('id', 'DESC')->get(['users.*']);
+ }
+
+ public function attachRole(User $user, string $role): bool
+ {
+ $roleObject = Role::where('name', $role)->first();
+ if (null === $roleObject) {
+ Log::error(sprintf('Could not find role "%s" in attachRole()', $role));
+
+ return false;
+ }
+
+ try {
+ $user->roles()->attach($roleObject);
+ } catch (QueryException $e) {
+ // don't care
+ Log::error(sprintf('Query exception when giving user a role: %s', $e->getMessage()));
+ }
+
+ return true;
+ }
+
/**
* This updates the users email address and records some things so it can be confirmed or undone later.
* The user is blocked until the change is confirmed.
@@ -93,11 +117,30 @@ class UserRepository implements UserRepositoryInterface
return true;
}
+ public function count(): int
+ {
+ return $this->all()->count();
+ }
+
public function createRole(string $name, string $displayName, string $description): Role
{
return Role::create(['name' => $name, 'display_name' => $displayName, 'description' => $description]);
}
+ public function deleteEmptyGroups(): void
+ {
+ $groups = UserGroup::get();
+
+ /** @var UserGroup $group */
+ foreach ($groups as $group) {
+ $count = $group->groupMemberships()->count();
+ if (0 === $count) {
+ Log::info(sprintf('Deleted empty group #%d ("%s")', $group->id, $group->title));
+ $group->delete();
+ }
+ }
+ }
+
public function deleteInvite(InvitedUser $invite): void
{
Log::debug(sprintf('Deleting invite #%d', $invite->id));
@@ -118,28 +161,9 @@ class UserRepository implements UserRepositoryInterface
return true;
}
- public function deleteEmptyGroups(): void
- {
- $groups = UserGroup::get();
-
- /** @var UserGroup $group */
- foreach ($groups as $group) {
- $count = $group->groupMemberships()->count();
- if (0 === $count) {
- Log::info(sprintf('Deleted empty group #%d ("%s")', $group->id, $group->title));
- $group->delete();
- }
- }
- }
-
- public function count(): int
- {
- return $this->all()->count();
- }
-
- public function all(): Collection
+ public function find(int $userId): ?User
{
- return User::orderBy('id', 'DESC')->get(['users.*']);
+ return User::find($userId);
}
public function findByEmail(string $email): ?User
@@ -160,6 +184,11 @@ class UserRepository implements UserRepositoryInterface
return InvitedUser::with('user')->get();
}
+ public function getRole(string $role): ?Role
+ {
+ return Role::where('name', $role)->first();
+ }
+
public function getRoleByUser(User $user): ?string
{
/** @var null|Role $role */
@@ -190,11 +219,6 @@ class UserRepository implements UserRepositoryInterface
return $roles;
}
- public function find(int $userId): ?User
- {
- return User::find($userId);
- }
-
/**
* Return basic user information.
*/
@@ -225,23 +249,6 @@ class UserRepository implements UserRepositoryInterface
];
}
- public function hasRole(Authenticatable|User|null $user, string $role): bool
- {
- if (!$user instanceof Authenticatable) {
- return false;
- }
- if ($user instanceof User) {
- /** @var Role $userRole */
- foreach ($user->roles as $userRole) {
- if ($userRole->name === $role) {
- return true;
- }
- }
- }
-
- return false;
- }
-
#[Override]
public function getUserGroups(User $user): Collection
{
@@ -266,6 +273,23 @@ class UserRepository implements UserRepositoryInterface
return $collection;
}
+ public function hasRole(Authenticatable|User|null $user, string $role): bool
+ {
+ if (!$user instanceof Authenticatable) {
+ return false;
+ }
+ if ($user instanceof User) {
+ /** @var Role $userRole */
+ foreach ($user->roles as $userRole) {
+ if ($userRole->name === $role) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
public function inviteUser(Authenticatable|User|null $user, string $email): InvitedUser
{
if (!$user instanceof User) {
@@ -294,6 +318,18 @@ class UserRepository implements UserRepositoryInterface
}
}
+ /**
+ * Remove any role the user has.
+ */
+ public function removeRole(User $user, string $role): void
+ {
+ $roleObj = $this->getRole($role);
+ if (!$roleObj instanceof Role) {
+ return;
+ }
+ $user->roles()->detach($roleObj->id);
+ }
+
/**
* Set MFA code.
*/
@@ -319,25 +355,6 @@ class UserRepository implements UserRepositoryInterface
return $user;
}
- public function attachRole(User $user, string $role): bool
- {
- $roleObject = Role::where('name', $role)->first();
- if (null === $roleObject) {
- Log::error(sprintf('Could not find role "%s" in attachRole()', $role));
-
- return false;
- }
-
- try {
- $user->roles()->attach($roleObject);
- } catch (QueryException $e) {
- // don't care
- Log::error(sprintf('Query exception when giving user a role: %s', $e->getMessage()));
- }
-
- return true;
- }
-
public function unblockUser(User $user): void
{
$user->blocked = false;
@@ -392,23 +409,6 @@ class UserRepository implements UserRepositoryInterface
return true;
}
- /**
- * Remove any role the user has.
- */
- public function removeRole(User $user, string $role): void
- {
- $roleObj = $this->getRole($role);
- if (!$roleObj instanceof Role) {
- return;
- }
- $user->roles()->detach($roleObj->id);
- }
-
- public function getRole(string $role): ?Role
- {
- return Role::where('name', $role)->first();
- }
-
public function validateInviteCode(string $code): bool
{
$now = today(config('app.timezone'));
diff --git a/app/Repositories/UserGroup/UserGroupRepository.php b/app/Repositories/UserGroup/UserGroupRepository.php
index 6aa8425f46..882f8394b5 100644
--- a/app/Repositories/UserGroup/UserGroupRepository.php
+++ b/app/Repositories/UserGroup/UserGroupRepository.php
@@ -109,6 +109,11 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
Log::debug('Done!');
}
+ public function findByName(string $title): ?UserGroup
+ {
+ return UserGroup::whereTitle($title)->first();
+ }
+
/**
* Returns all groups the user is member in.
*/
@@ -135,48 +140,6 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
return $collection;
}
- /**
- * Because there is the chance that a group with this name already exists,
- * Firefly III runs a little loop of combinations to make sure the group name is unique.
- */
- private function createNewUserGroup(User $user): UserGroup
- {
- $loop = 0;
- $groupName = $user->email;
- $exists = true;
- $existingGroup = null;
- while ($exists && $loop < 10) {
- $existingGroup = $this->findByName($groupName);
- if (!$existingGroup instanceof UserGroup) {
- $exists = false;
-
- $existingGroup = $this->store(['user' => $user, 'title' => $groupName]);
- }
- $groupName = sprintf('%s-%s', $user->email, substr(sha1(random_int(1000, 9999).microtime()), 0, 4));
- ++$loop;
- }
-
- return $existingGroup;
- }
-
- public function findByName(string $title): ?UserGroup
- {
- return UserGroup::whereTitle($title)->first();
- }
-
- /**
- * @throws FireflyException
- */
- public function store(array $data): UserGroup
- {
- $data['user'] = $this->user;
-
- /** @var UserGroupFactory $factory */
- $factory = app(UserGroupFactory::class);
-
- return $factory->create($data);
- }
-
/**
* Returns all groups.
*/
@@ -201,6 +164,19 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
;
}
+ /**
+ * @throws FireflyException
+ */
+ public function store(array $data): UserGroup
+ {
+ $data['user'] = $this->user;
+
+ /** @var UserGroupFactory $factory */
+ $factory = app(UserGroupFactory::class);
+
+ return $factory->create($data);
+ }
+
public function update(UserGroup $userGroup, array $data): UserGroup
{
$userGroup->title = $data['title'];
@@ -309,6 +285,37 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
return $userGroup;
}
+ #[Override]
+ public function useUserGroup(UserGroup $userGroup): void
+ {
+ $this->user->user_group_id = $userGroup->id;
+ $this->user->save();
+ }
+
+ /**
+ * Because there is the chance that a group with this name already exists,
+ * Firefly III runs a little loop of combinations to make sure the group name is unique.
+ */
+ private function createNewUserGroup(User $user): UserGroup
+ {
+ $loop = 0;
+ $groupName = $user->email;
+ $exists = true;
+ $existingGroup = null;
+ while ($exists && $loop < 10) {
+ $existingGroup = $this->findByName($groupName);
+ if (!$existingGroup instanceof UserGroup) {
+ $exists = false;
+
+ $existingGroup = $this->store(['user' => $user, 'title' => $groupName]);
+ }
+ $groupName = sprintf('%s-%s', $user->email, substr(sha1(random_int(1000, 9999).microtime()), 0, 4));
+ ++$loop;
+ }
+
+ return $existingGroup;
+ }
+
private function simplifyListByName(array $roles): array
{
if (in_array(UserRoleEnum::OWNER->value, $roles, true)) {
@@ -324,11 +331,4 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
return $roles;
}
-
- #[Override]
- public function useUserGroup(UserGroup $userGroup): void
- {
- $this->user->user_group_id = $userGroup->id;
- $this->user->save();
- }
}
diff --git a/app/Rules/BelongsUser.php b/app/Rules/BelongsUser.php
index b0acc68ecd..cdcbcb9a6f 100644
--- a/app/Rules/BelongsUser.php
+++ b/app/Rules/BelongsUser.php
@@ -67,6 +67,32 @@ class BelongsUser implements ValidationRule
}
}
+ protected function countField(string $class, string $field, string $value): int
+ {
+ $value = trim($value);
+ $objects = [];
+ // get all objects belonging to user:
+ if (PiggyBank::class === $class) {
+ $objects = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where('accounts.user_id', '=', auth()->user()->id)->get([
+ 'piggy_banks.*',
+ ]);
+ }
+ if (PiggyBank::class !== $class) {
+ $objects = $class::where('user_id', '=', auth()->user()->id)->get();
+ }
+ $count = 0;
+ foreach ($objects as $object) {
+ $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line
+ Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value));
+ if ($objectValue === $value) {
+ ++$count;
+ Log::debug(sprintf('Hit! Count is now %d', $count));
+ }
+ }
+
+ return $count;
+ }
+
private function parseAttribute(string $attribute): string
{
$parts = explode('.', $attribute);
@@ -80,46 +106,23 @@ class BelongsUser implements ValidationRule
return $attribute;
}
- private function validatePiggyBankId(int $value): bool
- {
- $count = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
- ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
- ->where('piggy_banks.id', '=', $value)
- ->where('accounts.user_id', '=', auth()->user()->id)
- ->count()
- ;
-
- return $count > 0;
- }
-
- private function validatePiggyBankName(string $value): bool
- {
- $count = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
- ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
- ->where('piggy_banks.name', '=', $value)
- ->where('accounts.user_id', '=', auth()->user()->id)
- ->count()
- ;
-
- return $count > 0;
- }
-
- private function validateBillId(int $value): bool
+ private function validateAccountId(int $value): bool
{
if (0 === $value) {
+ // its ok to submit 0. other checks will fail.
return true;
}
- $count = Bill::where('id', '=', $value)->where('user_id', '=', auth()->user()->id)->count();
+ $count = Account::where('id', '=', $value)->where('user_id', '=', auth()->user()->id)->count();
return 1 === $count;
}
- private function validateJournalId(int $value): bool
+ private function validateBillId(int $value): bool
{
if (0 === $value) {
return true;
}
- $count = TransactionJournal::where('id', '=', $value)->where('user_id', '=', auth()->user()->id)->count();
+ $count = Bill::where('id', '=', $value)->where('user_id', '=', auth()->user()->id)->count();
return 1 === $count;
}
@@ -132,32 +135,6 @@ class BelongsUser implements ValidationRule
return 1 === $count;
}
- protected function countField(string $class, string $field, string $value): int
- {
- $value = trim($value);
- $objects = [];
- // get all objects belonging to user:
- if (PiggyBank::class === $class) {
- $objects = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where('accounts.user_id', '=', auth()->user()->id)->get([
- 'piggy_banks.*',
- ]);
- }
- if (PiggyBank::class !== $class) {
- $objects = $class::where('user_id', '=', auth()->user()->id)->get();
- }
- $count = 0;
- foreach ($objects as $object) {
- $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line
- Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value));
- if ($objectValue === $value) {
- ++$count;
- Log::debug(sprintf('Hit! Count is now %d', $count));
- }
- }
-
- return $count;
- }
-
private function validateBudgetId(int $value): bool
{
if (0 === $value) {
@@ -168,28 +145,51 @@ class BelongsUser implements ValidationRule
return 1 === $count;
}
- private function validateCategoryId(int $value): bool
+ private function validateBudgetName(string $value): bool
{
- $count = Category::where('id', '=', $value)->where('user_id', '=', auth()->user()->id)->count();
+ $count = $this->countField(Budget::class, 'name', $value);
return 1 === $count;
}
- private function validateBudgetName(string $value): bool
+ private function validateCategoryId(int $value): bool
{
- $count = $this->countField(Budget::class, 'name', $value);
+ $count = Category::where('id', '=', $value)->where('user_id', '=', auth()->user()->id)->count();
return 1 === $count;
}
- private function validateAccountId(int $value): bool
+ private function validateJournalId(int $value): bool
{
if (0 === $value) {
- // its ok to submit 0. other checks will fail.
return true;
}
- $count = Account::where('id', '=', $value)->where('user_id', '=', auth()->user()->id)->count();
+ $count = TransactionJournal::where('id', '=', $value)->where('user_id', '=', auth()->user()->id)->count();
return 1 === $count;
}
+
+ private function validatePiggyBankId(int $value): bool
+ {
+ $count = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
+ ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
+ ->where('piggy_banks.id', '=', $value)
+ ->where('accounts.user_id', '=', auth()->user()->id)
+ ->count()
+ ;
+
+ return $count > 0;
+ }
+
+ private function validatePiggyBankName(string $value): bool
+ {
+ $count = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
+ ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
+ ->where('piggy_banks.name', '=', $value)
+ ->where('accounts.user_id', '=', auth()->user()->id)
+ ->count()
+ ;
+
+ return $count > 0;
+ }
}
diff --git a/app/Rules/BelongsUserGroup.php b/app/Rules/BelongsUserGroup.php
index a9c74c0bda..7827cb7456 100644
--- a/app/Rules/BelongsUserGroup.php
+++ b/app/Rules/BelongsUserGroup.php
@@ -78,37 +78,6 @@ class BelongsUserGroup implements ValidationRule
}
}
- private function parseAttribute(string $attribute): string
- {
- $parts = explode('.', $attribute);
- if (1 === count($parts)) {
- return $attribute;
- }
- if (3 === count($parts)) {
- return $parts[2];
- }
-
- return $attribute;
- }
-
- private function validatePiggyBankId(int $value): bool
- {
- $count = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')
- ->where('piggy_banks.id', '=', $value)
- ->where('accounts.user_group_id', '=', $this->userGroup->id)
- ->count()
- ;
-
- return 1 === $count;
- }
-
- private function validatePiggyBankName(string $value): bool
- {
- $count = $this->countField(PiggyBank::class, 'name', $value);
-
- return 1 === $count;
- }
-
protected function countField(string $class, string $field, string $value): int
{
$value = trim($value);
@@ -137,22 +106,36 @@ class BelongsUserGroup implements ValidationRule
return $count;
}
- private function validateBillId(int $value): bool
+ private function parseAttribute(string $attribute): string
+ {
+ $parts = explode('.', $attribute);
+ if (1 === count($parts)) {
+ return $attribute;
+ }
+ if (3 === count($parts)) {
+ return $parts[2];
+ }
+
+ return $attribute;
+ }
+
+ private function validateAccountId(int $value): bool
{
if (0 === $value) {
+ // it's ok to submit 0. other checks will fail.
return true;
}
- $count = Bill::where('id', '=', $value)->where('user_group_id', '=', $this->userGroup->id)->count();
+ $count = Account::where('id', '=', $value)->where('user_group_id', '=', $this->userGroup->id)->count();
return 1 === $count;
}
- private function validateJournalId(int $value): bool
+ private function validateBillId(int $value): bool
{
if (0 === $value) {
return true;
}
- $count = TransactionJournal::where('id', '=', $value)->where('user_group_id', '=', $this->userGroup->id)->count();
+ $count = Bill::where('id', '=', $value)->where('user_group_id', '=', $this->userGroup->id)->count();
return 1 === $count;
}
@@ -175,27 +158,44 @@ class BelongsUserGroup implements ValidationRule
return 1 === $count;
}
- private function validateCategoryId(int $value): bool
+ private function validateBudgetName(string $value): bool
{
- $count = Category::where('id', '=', $value)->where('user_group_id', '=', $this->userGroup->id)->count();
+ $count = $this->countField(Budget::class, 'name', $value);
return 1 === $count;
}
- private function validateBudgetName(string $value): bool
+ private function validateCategoryId(int $value): bool
{
- $count = $this->countField(Budget::class, 'name', $value);
+ $count = Category::where('id', '=', $value)->where('user_group_id', '=', $this->userGroup->id)->count();
return 1 === $count;
}
- private function validateAccountId(int $value): bool
+ private function validateJournalId(int $value): bool
{
if (0 === $value) {
- // it's ok to submit 0. other checks will fail.
return true;
}
- $count = Account::where('id', '=', $value)->where('user_group_id', '=', $this->userGroup->id)->count();
+ $count = TransactionJournal::where('id', '=', $value)->where('user_group_id', '=', $this->userGroup->id)->count();
+
+ return 1 === $count;
+ }
+
+ private function validatePiggyBankId(int $value): bool
+ {
+ $count = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')
+ ->where('piggy_banks.id', '=', $value)
+ ->where('accounts.user_group_id', '=', $this->userGroup->id)
+ ->count()
+ ;
+
+ return 1 === $count;
+ }
+
+ private function validatePiggyBankName(string $value): bool
+ {
+ $count = $this->countField(PiggyBank::class, 'name', $value);
return 1 === $count;
}
diff --git a/app/Rules/IsValidAttachmentModel.php b/app/Rules/IsValidAttachmentModel.php
index f825bc535a..d82d62ecea 100644
--- a/app/Rules/IsValidAttachmentModel.php
+++ b/app/Rules/IsValidAttachmentModel.php
@@ -59,15 +59,6 @@ class IsValidAttachmentModel implements ValidationRule
$this->model = $model;
}
- private function normalizeModel(string $model): string
- {
- $search = ['FireflyIII\Models\\'];
- $replace = '';
- $model = str_replace($search, $replace, $model);
-
- return sprintf('FireflyIII\Models\%s', $model);
- }
-
/**
* @SuppressWarnings("PHPMD.UnusedFormalParameter")
*/
@@ -95,6 +86,15 @@ class IsValidAttachmentModel implements ValidationRule
}
}
+ private function normalizeModel(string $model): string
+ {
+ $search = ['FireflyIII\Models\\'];
+ $replace = '';
+ $model = str_replace($search, $replace, $model);
+
+ return sprintf('FireflyIII\Models\%s', $model);
+ }
+
private function validateAccount(int $value): bool
{
/** @var AccountRepositoryInterface $repository */
@@ -131,6 +131,14 @@ class IsValidAttachmentModel implements ValidationRule
return null !== $repository->find($value);
}
+ private function validateJournal(int $value): bool
+ {
+ $repository = app(JournalRepositoryInterface::class);
+ $repository->setUser(auth()->user());
+
+ return null !== $repository->find($value);
+ }
+
private function validatePiggyBank(int $value): bool
{
/** @var PiggyBankRepositoryInterface $repository */
@@ -157,12 +165,4 @@ class IsValidAttachmentModel implements ValidationRule
return null !== $repository->findTransaction($value);
}
-
- private function validateJournal(int $value): bool
- {
- $repository = app(JournalRepositoryInterface::class);
- $repository->setUser(auth()->user());
-
- return null !== $repository->find($value);
- }
}
diff --git a/app/Rules/UniqueAccountNumber.php b/app/Rules/UniqueAccountNumber.php
index d8219cfdc8..c74d721d7f 100644
--- a/app/Rules/UniqueAccountNumber.php
+++ b/app/Rules/UniqueAccountNumber.php
@@ -106,6 +106,23 @@ class UniqueAccountNumber implements ValidationRule
Log::debug('Account number is valid.');
}
+ private function countHits(string $type, string $accountNumber): int
+ {
+ $query = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id')
+ ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
+ ->where('accounts.user_id', auth()->user()->id)
+ ->where('account_types.type', $type)
+ ->where('account_meta.name', '=', 'account_number')
+ ->where('account_meta.data', json_encode($accountNumber))
+ ;
+
+ if ($this->account instanceof Account) {
+ $query->where('accounts.id', '!=', $this->account->id);
+ }
+
+ return $query->count();
+ }
+
private function getMaxOccurrences(): array
{
$maxCounts = [AccountTypeEnum::ASSET->value => 0, AccountTypeEnum::EXPENSE->value => 0, AccountTypeEnum::REVENUE->value => 0];
@@ -123,21 +140,4 @@ class UniqueAccountNumber implements ValidationRule
return $maxCounts;
}
-
- private function countHits(string $type, string $accountNumber): int
- {
- $query = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id')
- ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
- ->where('accounts.user_id', auth()->user()->id)
- ->where('account_types.type', $type)
- ->where('account_meta.name', '=', 'account_number')
- ->where('account_meta.data', json_encode($accountNumber))
- ;
-
- if ($this->account instanceof Account) {
- $query->where('accounts.id', '!=', $this->account->id);
- }
-
- return $query->count();
- }
}
diff --git a/app/Rules/UniqueIban.php b/app/Rules/UniqueIban.php
index 4df6c9de58..071202d87c 100644
--- a/app/Rules/UniqueIban.php
+++ b/app/Rules/UniqueIban.php
@@ -72,13 +72,6 @@ class UniqueIban implements ValidationRule
return (string) trans('validation.unique_iban_for_user');
}
- public function validate(string $attribute, mixed $value, Closure $fail): void
- {
- if (!$this->passes($attribute, $value)) {
- $fail((string) trans('validation.unique_iban_for_user'));
- }
- }
-
/**
* Determine if the validation rule passes.
*
@@ -123,27 +116,11 @@ class UniqueIban implements ValidationRule
return true;
}
- private function getMaxOccurrences(): array
+ public function validate(string $attribute, mixed $value, Closure $fail): void
{
- $maxCounts = [
- AccountTypeEnum::ASSET->value => 0,
- AccountTypeEnum::EXPENSE->value => 0,
- AccountTypeEnum::REVENUE->value => 0,
- 'liabilities' => 0,
- ];
-
- if (in_array('expense', $this->expectedTypes, true) || in_array(AccountTypeEnum::EXPENSE->value, $this->expectedTypes, true)) {
- // IBAN should be unique amongst expense and asset accounts.
- // may appear once in revenue accounts
- $maxCounts[AccountTypeEnum::REVENUE->value] = 1;
- }
- if (in_array('revenue', $this->expectedTypes, true) || in_array(AccountTypeEnum::REVENUE->value, $this->expectedTypes, true)) {
- // IBAN should be unique amongst revenue and asset accounts.
- // may appear once in expense accounts
- $maxCounts[AccountTypeEnum::EXPENSE->value] = 1;
+ if (!$this->passes($attribute, $value)) {
+ $fail((string) trans('validation.unique_iban_for_user'));
}
-
- return $maxCounts;
}
private function countHits(string $type, string $iban): int
@@ -166,4 +143,27 @@ class UniqueIban implements ValidationRule
return $query->count();
}
+
+ private function getMaxOccurrences(): array
+ {
+ $maxCounts = [
+ AccountTypeEnum::ASSET->value => 0,
+ AccountTypeEnum::EXPENSE->value => 0,
+ AccountTypeEnum::REVENUE->value => 0,
+ 'liabilities' => 0,
+ ];
+
+ if (in_array('expense', $this->expectedTypes, true) || in_array(AccountTypeEnum::EXPENSE->value, $this->expectedTypes, true)) {
+ // IBAN should be unique amongst expense and asset accounts.
+ // may appear once in revenue accounts
+ $maxCounts[AccountTypeEnum::REVENUE->value] = 1;
+ }
+ if (in_array('revenue', $this->expectedTypes, true) || in_array(AccountTypeEnum::REVENUE->value, $this->expectedTypes, true)) {
+ // IBAN should be unique amongst revenue and asset accounts.
+ // may appear once in expense accounts
+ $maxCounts[AccountTypeEnum::EXPENSE->value] = 1;
+ }
+
+ return $maxCounts;
+ }
}
diff --git a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php
index 0f5b694c69..de5a43a8ce 100644
--- a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php
+++ b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php
@@ -193,25 +193,6 @@ class UpdateRequest implements UpdateRequestInterface
return $return;
}
- private function runsNewerVersion(string $current, string $latest): array
- {
- $return = [
- 'level' => 'info',
- 'message' => (string) trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $latest]),
- ];
- Log::debug('User is running a newer version', $return);
-
- return $return;
- }
-
- private function runsSameVersion(string $current): array
- {
- $return = ['level' => 'info', 'message' => (string) trans('firefly.update_current_version_alert', ['version' => $current])];
- Log::debug('User is the current version.', $return);
-
- return $return;
- }
-
private function releasedNewAlpha(string $current, string $latest, Carbon $date): array
{
Log::debug('New release is also a alpha!');
@@ -249,4 +230,23 @@ class UpdateRequest implements UpdateRequestInterface
return ['level' => 'success', 'message' => $message];
}
+
+ private function runsNewerVersion(string $current, string $latest): array
+ {
+ $return = [
+ 'level' => 'info',
+ 'message' => (string) trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $latest]),
+ ];
+ Log::debug('User is running a newer version', $return);
+
+ return $return;
+ }
+
+ private function runsSameVersion(string $current): array
+ {
+ $return = ['level' => 'info', 'message' => (string) trans('firefly.update_current_version_alert', ['version' => $current])];
+ Log::debug('User is the current version.', $return);
+
+ return $return;
+ }
}
diff --git a/app/Services/Internal/Destroy/AccountDestroyService.php b/app/Services/Internal/Destroy/AccountDestroyService.php
index d17542f220..8b8a62cdab 100644
--- a/app/Services/Internal/Destroy/AccountDestroyService.php
+++ b/app/Services/Internal/Destroy/AccountDestroyService.php
@@ -64,6 +64,37 @@ class AccountDestroyService
$account->delete();
}
+ public function moveTransactions(Account $account, Account $moveTo): void
+ {
+ Log::debug(sprintf('Move from account #%d to #%d', $account->id, $moveTo->id));
+ DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]);
+
+ $collection = Transaction::groupBy('transaction_journal_id', 'account_id')->where('account_id', $moveTo->id)->get([
+ 'transaction_journal_id',
+ 'account_id',
+ DB::raw('count(*) as the_count'),
+ ]);
+ if (0 === $collection->count()) {
+ return;
+ }
+
+ /** @var JournalDestroyService $service */
+ $service = app(JournalDestroyService::class);
+ $user = $account->user;
+
+ /** @var stdClass $row */
+ foreach ($collection as $row) {
+ if ((int) $row->the_count > 1) {
+ $journalId = $row->transaction_journal_id;
+ $journal = $user->transactionJournals()->find($journalId);
+ if (null !== $journal) {
+ Log::debug(sprintf('Deleted journal #%d because it has the same source as destination.', $journal->id));
+ $service->destroy($journal);
+ }
+ }
+ }
+ }
+
private function destroyOpeningBalance(Account $account): void
{
Log::debug(sprintf('Searching for opening balance for account #%d "%s"', $account->id, $account->name));
@@ -102,43 +133,6 @@ class AccountDestroyService
}
}
- public function moveTransactions(Account $account, Account $moveTo): void
- {
- Log::debug(sprintf('Move from account #%d to #%d', $account->id, $moveTo->id));
- DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]);
-
- $collection = Transaction::groupBy('transaction_journal_id', 'account_id')->where('account_id', $moveTo->id)->get([
- 'transaction_journal_id',
- 'account_id',
- DB::raw('count(*) as the_count'),
- ]);
- if (0 === $collection->count()) {
- return;
- }
-
- /** @var JournalDestroyService $service */
- $service = app(JournalDestroyService::class);
- $user = $account->user;
-
- /** @var stdClass $row */
- foreach ($collection as $row) {
- if ((int) $row->the_count > 1) {
- $journalId = $row->transaction_journal_id;
- $journal = $user->transactionJournals()->find($journalId);
- if (null !== $journal) {
- Log::debug(sprintf('Deleted journal #%d because it has the same source as destination.', $journal->id));
- $service->destroy($journal);
- }
- }
- }
- }
-
- private function updateRecurrences(Account $account, Account $moveTo): void
- {
- DB::table('recurrences_transactions')->where('source_id', $account->id)->update(['source_id' => $moveTo->id]);
- DB::table('recurrences_transactions')->where('destination_id', $account->id)->update(['destination_id' => $moveTo->id]);
- }
-
private function destroyRecurrences(Account $account): void
{
$recurrences = RecurrenceTransaction::where(static function (Builder $q) use ($account): void {
@@ -152,4 +146,10 @@ class AccountDestroyService
$destroyService->destroyById((int) $recurrenceId);
}
}
+
+ private function updateRecurrences(Account $account, Account $moveTo): void
+ {
+ DB::table('recurrences_transactions')->where('source_id', $account->id)->update(['source_id' => $moveTo->id]);
+ DB::table('recurrences_transactions')->where('destination_id', $account->id)->update(['destination_id' => $moveTo->id]);
+ }
}
diff --git a/app/Services/Internal/Destroy/BillDestroyService.php b/app/Services/Internal/Destroy/BillDestroyService.php
index 04bedb9b1c..a31c84d697 100644
--- a/app/Services/Internal/Destroy/BillDestroyService.php
+++ b/app/Services/Internal/Destroy/BillDestroyService.php
@@ -44,7 +44,6 @@ class BillDestroyService
}
$bill->notes()->delete();
-
$bill->delete();
}
}
diff --git a/app/Services/Internal/Destroy/BudgetDestroyService.php b/app/Services/Internal/Destroy/BudgetDestroyService.php
index 998bfa9707..bfc343b9b2 100644
--- a/app/Services/Internal/Destroy/BudgetDestroyService.php
+++ b/app/Services/Internal/Destroy/BudgetDestroyService.php
@@ -24,19 +24,14 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Destroy;
-use FireflyIII\Enums\WebhookTrigger;
use FireflyIII\Events\Model\Budget\DestroyedBudget;
use FireflyIII\Events\Model\Budget\DestroyingBudget;
-use FireflyIII\Events\Model\Webhook\WebhookMessagesRequestSending;
-use FireflyIII\Generator\Webhook\MessageGeneratorInterface;
use FireflyIII\Models\Attachment;
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface;
use FireflyIII\Support\Models\AvailableBudgetCalculator;
-use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Log;
/**
* Class BudgetDestroyService
@@ -49,7 +44,7 @@ class BudgetDestroyService
event(new DestroyingBudget($budget));
// remove attachments
- $repository = app(AttachmentRepositoryInterface::class);
+ $repository = app(AttachmentRepositoryInterface::class);
$repository->setUser($budget->user);
/** @var Attachment $attachment */
diff --git a/app/Services/Internal/Destroy/JournalDestroyService.php b/app/Services/Internal/Destroy/JournalDestroyService.php
index 36ff621698..2939fe8db2 100644
--- a/app/Services/Internal/Destroy/JournalDestroyService.php
+++ b/app/Services/Internal/Destroy/JournalDestroyService.php
@@ -36,7 +36,6 @@ class JournalDestroyService
{
Log::debug(sprintf('Now in %s', __METHOD__));
-
// delete group, if group is empty:
$group = $journal->transactionGroup;
if (null !== $group) {
@@ -47,6 +46,5 @@ class JournalDestroyService
}
$journal->delete();
-
}
}
diff --git a/app/Services/Internal/Destroy/RecurrenceDestroyService.php b/app/Services/Internal/Destroy/RecurrenceDestroyService.php
index 4c9385bc77..e599b90f37 100644
--- a/app/Services/Internal/Destroy/RecurrenceDestroyService.php
+++ b/app/Services/Internal/Destroy/RecurrenceDestroyService.php
@@ -32,18 +32,6 @@ use FireflyIII\Models\RecurrenceTransaction;
*/
class RecurrenceDestroyService
{
- /**
- * Delete recurrence by ID
- */
- public function destroyById(int $recurrenceId): void
- {
- $recurrence = Recurrence::find($recurrenceId);
- if (null === $recurrence) {
- return;
- }
- $this->destroy($recurrence);
- }
-
/**
* Delete recurrence.
*/
@@ -64,4 +52,16 @@ class RecurrenceDestroyService
// delete recurrence
$recurrence->delete();
}
+
+ /**
+ * Delete recurrence by ID
+ */
+ public function destroyById(int $recurrenceId): void
+ {
+ $recurrence = Recurrence::find($recurrenceId);
+ if (null === $recurrence) {
+ return;
+ }
+ $this->destroy($recurrence);
+ }
}
diff --git a/app/Services/Internal/Recalculate/PrimaryAmountRecalculationService.php b/app/Services/Internal/Recalculate/PrimaryAmountRecalculationService.php
index ad080e661e..b5a930ae3e 100644
--- a/app/Services/Internal/Recalculate/PrimaryAmountRecalculationService.php
+++ b/app/Services/Internal/Recalculate/PrimaryAmountRecalculationService.php
@@ -65,19 +65,35 @@ class PrimaryAmountRecalculationService
}
}
- private function recalculateForGroup(UserGroup $userGroup): void
+ private function calculateTransactions(UserGroup $userGroup, TransactionCurrency $currency): void
{
- Log::debug(sprintf('Now recalculating primary amounts for user group #%d', $userGroup->id));
- $this->recalculateAccounts($userGroup);
-
- // do a check with the group's currency so we can skip some stuff.
- $currency = Amount::getPrimaryCurrencyByUserGroup($userGroup);
-
- $this->recalculatePiggyBanks($userGroup, $currency);
- $this->recalculateBudgets($userGroup, $currency);
- $this->recalculateAvailableBudgets($userGroup, $currency);
- $this->recalculateBills($userGroup, $currency);
- $this->calculateTransactions($userGroup, $currency);
+ // custom query because of the potential size of this update.
+ $set = DB::table('transactions')
+ ->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
+ ->where('transaction_journals.user_group_id', $userGroup->id)
+ ->where(static function (DatabaseBuilder $q1) use ($currency): void {
+ $q1->where(static function (DatabaseBuilder $q2) use ($currency): void {
+ $q2->whereNot('transactions.transaction_currency_id', $currency->id)->whereNull('transactions.foreign_currency_id');
+ })->orWhere(static function (DatabaseBuilder $q3) use ($currency): void {
+ $q3->whereNot('transactions.transaction_currency_id', $currency->id)->whereNot('transactions.foreign_currency_id', $currency->id);
+ });
+ })
+ // ->where(static function (DatabaseBuilder $q) use ($currency): void {
+ // $q->whereNot('transactions.transaction_currency_id', $currency->id)
+ // ->whereNot('transactions.foreign_currency_id', $currency->id)
+ // ;
+ // })
+ ->get(['transactions.id'])
+ ;
+ TransactionObserver::$recalculate = false;
+ foreach ($set as $item) {
+ // here we are.
+ /** @var null|Transaction $transaction */
+ $transaction = Transaction::find($item->id);
+ $transaction?->touch();
+ }
+ TransactionObserver::$recalculate = true;
+ Log::debug(sprintf('Recalculated %d transactions.', $set->count()));
}
private function recalculateAccounts(UserGroup $userGroup): void
@@ -105,55 +121,38 @@ class PrimaryAmountRecalculationService
Log::debug(sprintf('Recalculated %d accounts for user group #%d.', $set->count(), $userGroup->id));
}
- private function recalculatePiggyBanks(UserGroup $userGroup, TransactionCurrency $currency): void
+ private function recalculateAutoBudgets(Budget $budget, TransactionCurrency $currency): void
{
- $converter = new ExchangeRateConverter();
- $converter->setUserGroup($userGroup);
- $converter->setIgnoreSettings(true);
- $repository = app(PiggyBankRepositoryInterface::class);
- $repository->setUserGroup($userGroup);
- $set = $repository->getPiggyBanks();
- $set = $set->filter(static fn (PiggyBank $piggyBank): bool => $currency->id !== $piggyBank->transaction_currency_id);
- foreach ($set as $piggyBank) {
- $piggyBank->encrypted = false;
- $piggyBank->save();
+ $set = $budget->autoBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
- foreach ($piggyBank->accounts as $account) {
- $account->pivot->native_current_amount = null;
- if (0 !== bccomp((string) $account->pivot->current_amount, '0')) {
- $account->pivot->native_current_amount = $converter->convert(
- $piggyBank->transactionCurrency,
- $currency,
- today(),
- (string) $account->pivot->current_amount
- );
- }
- $account->pivot->save();
- }
- $this->recalculatePiggyBankEvents($piggyBank);
+ /** @var AutoBudget $autoBudget */
+ foreach ($set as $autoBudget) {
+ $autoBudget->touch();
}
- Log::debug(sprintf('Recalculated %d piggy banks for user group #%d.', $set->count(), $userGroup->id));
+ Log::debug(sprintf('Recalculated %d auto budgets for budget #%d.', $set->count(), $budget->id));
}
- private function recalculatePiggyBankEvents(PiggyBank $piggyBank): void
+ private function recalculateAvailableBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
{
- $set = $piggyBank->piggyBankEvents()->get();
- $set->each(static function (PiggyBankEvent $event): void { // @phpstan-ignore-line
- $event->touch();
- });
- Log::debug(sprintf('Recalculated %d piggy bank events.', $set->count()));
+ Log::debug('Start with available budgets.');
+ $set = $userGroup->availableBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
+
+ /** @var AvailableBudget $budget */
+ foreach ($set as $budget) {
+ $budget->touch();
+ }
+ Log::debug(sprintf('Recalculated %d available budgets.', $set->count()));
}
- private function recalculateBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
+ private function recalculateBills(UserGroup $userGroup, TransactionCurrency $currency): void
{
- $set = $userGroup->budgets()->get();
+ $set = $userGroup->bills()->where('transaction_currency_id', '!=', $currency->id)->get();
- /** @var Budget $budget */
- foreach ($set as $budget) {
- $this->recalculateBudgetLimits($budget, $currency);
- $this->recalculateAutoBudgets($budget, $currency);
+ /** @var Bill $bill */
+ foreach ($set as $bill) {
+ $bill->touch();
}
- Log::debug(sprintf('Recalculated %d budgets.', $set->count()));
+ Log::debug(sprintf('Recalculated %d bills.', $set->count()));
}
private function recalculateBudgetLimits(Budget $budget, TransactionCurrency $currency): void
@@ -169,68 +168,69 @@ class PrimaryAmountRecalculationService
Log::debug(sprintf('Recalculated %d budget limits for budget #%d.', $set->count(), $budget->id));
}
- private function recalculateAutoBudgets(Budget $budget, TransactionCurrency $currency): void
+ private function recalculateBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
{
- $set = $budget->autoBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
+ $set = $userGroup->budgets()->get();
- /** @var AutoBudget $autoBudget */
- foreach ($set as $autoBudget) {
- $autoBudget->touch();
+ /** @var Budget $budget */
+ foreach ($set as $budget) {
+ $this->recalculateBudgetLimits($budget, $currency);
+ $this->recalculateAutoBudgets($budget, $currency);
}
- Log::debug(sprintf('Recalculated %d auto budgets for budget #%d.', $set->count(), $budget->id));
+ Log::debug(sprintf('Recalculated %d budgets.', $set->count()));
}
- private function recalculateAvailableBudgets(UserGroup $userGroup, TransactionCurrency $currency): void
+ private function recalculateForGroup(UserGroup $userGroup): void
{
- Log::debug('Start with available budgets.');
- $set = $userGroup->availableBudgets()->where('transaction_currency_id', '!=', $currency->id)->get();
+ Log::debug(sprintf('Now recalculating primary amounts for user group #%d', $userGroup->id));
+ $this->recalculateAccounts($userGroup);
- /** @var AvailableBudget $budget */
- foreach ($set as $budget) {
- $budget->touch();
- }
- Log::debug(sprintf('Recalculated %d available budgets.', $set->count()));
+ // do a check with the group's currency so we can skip some stuff.
+ $currency = Amount::getPrimaryCurrencyByUserGroup($userGroup);
+
+ $this->recalculatePiggyBanks($userGroup, $currency);
+ $this->recalculateBudgets($userGroup, $currency);
+ $this->recalculateAvailableBudgets($userGroup, $currency);
+ $this->recalculateBills($userGroup, $currency);
+ $this->calculateTransactions($userGroup, $currency);
}
- private function recalculateBills(UserGroup $userGroup, TransactionCurrency $currency): void
+ private function recalculatePiggyBankEvents(PiggyBank $piggyBank): void
{
- $set = $userGroup->bills()->where('transaction_currency_id', '!=', $currency->id)->get();
-
- /** @var Bill $bill */
- foreach ($set as $bill) {
- $bill->touch();
- }
- Log::debug(sprintf('Recalculated %d bills.', $set->count()));
+ $set = $piggyBank->piggyBankEvents()->get();
+ $set->each(static function (PiggyBankEvent $event): void { // @phpstan-ignore-line
+ $event->touch();
+ });
+ Log::debug(sprintf('Recalculated %d piggy bank events.', $set->count()));
}
- private function calculateTransactions(UserGroup $userGroup, TransactionCurrency $currency): void
+ private function recalculatePiggyBanks(UserGroup $userGroup, TransactionCurrency $currency): void
{
- // custom query because of the potential size of this update.
- $set = DB::table('transactions')
- ->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
- ->where('transaction_journals.user_group_id', $userGroup->id)
- ->where(static function (DatabaseBuilder $q1) use ($currency): void {
- $q1->where(static function (DatabaseBuilder $q2) use ($currency): void {
- $q2->whereNot('transactions.transaction_currency_id', $currency->id)->whereNull('transactions.foreign_currency_id');
- })->orWhere(static function (DatabaseBuilder $q3) use ($currency): void {
- $q3->whereNot('transactions.transaction_currency_id', $currency->id)->whereNot('transactions.foreign_currency_id', $currency->id);
- });
- })
- // ->where(static function (DatabaseBuilder $q) use ($currency): void {
- // $q->whereNot('transactions.transaction_currency_id', $currency->id)
- // ->whereNot('transactions.foreign_currency_id', $currency->id)
- // ;
- // })
- ->get(['transactions.id'])
- ;
- TransactionObserver::$recalculate = false;
- foreach ($set as $item) {
- // here we are.
- /** @var null|Transaction $transaction */
- $transaction = Transaction::find($item->id);
- $transaction?->touch();
+ $converter = new ExchangeRateConverter();
+ $converter->setUserGroup($userGroup);
+ $converter->setIgnoreSettings(true);
+ $repository = app(PiggyBankRepositoryInterface::class);
+ $repository->setUserGroup($userGroup);
+ $set = $repository->getPiggyBanks();
+ $set = $set->filter(static fn (PiggyBank $piggyBank): bool => $currency->id !== $piggyBank->transaction_currency_id);
+ foreach ($set as $piggyBank) {
+ $piggyBank->encrypted = false;
+ $piggyBank->save();
+
+ foreach ($piggyBank->accounts as $account) {
+ $account->pivot->native_current_amount = null;
+ if (0 !== bccomp((string) $account->pivot->current_amount, '0')) {
+ $account->pivot->native_current_amount = $converter->convert(
+ $piggyBank->transactionCurrency,
+ $currency,
+ today(),
+ (string) $account->pivot->current_amount
+ );
+ }
+ $account->pivot->save();
+ }
+ $this->recalculatePiggyBankEvents($piggyBank);
}
- TransactionObserver::$recalculate = true;
- Log::debug(sprintf('Recalculated %d transactions.', $set->count()));
+ Log::debug(sprintf('Recalculated %d piggy banks for user group #%d.', $set->count(), $userGroup->id));
}
}
diff --git a/app/Services/Internal/Support/AccountServiceTrait.php b/app/Services/Internal/Support/AccountServiceTrait.php
index de50f81f5f..523785366b 100644
--- a/app/Services/Internal/Support/AccountServiceTrait.php
+++ b/app/Services/Internal/Support/AccountServiceTrait.php
@@ -193,6 +193,96 @@ trait AccountServiceTrait
return false;
}
+ /**
+ * @throws FireflyException
+ */
+ protected function createCreditTransaction(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
+ {
+ Log::debug('Now going to create an createCreditTransaction.');
+
+ if (0 === bccomp($openingBalance, '0')) {
+ Log::debug('Amount is zero, so will not make an liability credit group.');
+
+ throw new FireflyException('Amount for new liability credit was unexpectedly 0.');
+ }
+
+ $language = Preferences::getForUser($account->user, 'language', 'en_US')->data;
+ if (is_array($language)) {
+ $language = 'en_US';
+ }
+ $language = (string) $language;
+
+ // set source and/or destination based on whether the amount is positive or negative.
+ // first, assume the amount is positive and go from there:
+ // if amount is positive ("I am owed this debt"), source is special account, destination is the liability.
+ $sourceId = null;
+ $sourceName = trans('firefly.liability_credit_description', ['account' => $account->name], $language);
+ $destId = $account->id;
+ $destName = null;
+ if (-1 === bccomp($openingBalance, '0')) {
+ // amount is negative, reverse it
+ $sourceId = $account->id;
+ $sourceName = null;
+ $destId = null;
+ $destName = trans('firefly.liability_credit_description', ['account' => $account->name], $language);
+ }
+
+ // amount must be positive for the transaction to work.
+ $amount = Steam::positive($openingBalance);
+
+ // get or grab currency:
+ $currency = $this->accountRepository->getAccountCurrency($account);
+ if (null === $currency) {
+ $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup);
+ }
+ // submit to factory:
+ $submission = [
+ 'group_title' => null,
+ 'user' => $account->user,
+ 'user_group' => $account->user->userGroup,
+ 'transactions' => [[
+ 'type' => 'Liability credit',
+ 'date' => $openingBalanceDate,
+ 'source_id' => $sourceId,
+ 'source_name' => $sourceName,
+ 'destination_id' => $destId,
+ 'destination_name' => $destName,
+ 'user' => $account->user,
+ 'user_group' => $account->user->userGroup,
+ 'currency_id' => $currency->id,
+ 'order' => 0,
+ 'amount' => $amount,
+ 'foreign_amount' => null,
+ 'description' => trans('firefly.liability_credit_description', ['account' => $account->name]),
+ 'budget_id' => null,
+ 'budget_name' => null,
+ 'category_id' => null,
+ 'category_name' => null,
+ 'piggy_bank_id' => null,
+ 'piggy_bank_name' => null,
+ 'reconciled' => false,
+ 'notes' => null,
+ 'tags' => [],
+ ]],
+ ];
+ Log::debug('Going for submission in createCreditTransaction', $submission);
+
+ /** @var TransactionGroupFactory $factory */
+ $factory = app(TransactionGroupFactory::class);
+ $factory->setUser($account->user);
+
+ try {
+ $group = $factory->create($submission);
+ } catch (DuplicateTransactionException $e) {
+ Log::error($e->getMessage());
+ Log::error($e->getTraceAsString());
+
+ throw new FireflyException($e->getMessage(), 0, $e);
+ }
+
+ return $group;
+ }
+
/**
* @throws FireflyException
* *
@@ -288,6 +378,98 @@ trait AccountServiceTrait
return $group;
}
+ /**
+ * @throws FireflyException
+ */
+ protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
+ {
+ Log::debug('Now going to create an OB group.');
+ $language = Preferences::getForUser($account->user, 'language', 'en_US')->data;
+ if (is_array($language)) {
+ $language = 'en_US';
+ }
+ $language = (string) $language;
+ $sourceId = null;
+ $sourceName = null;
+ $destId = null;
+ $destName = null;
+
+ // amount is positive.
+ if (1 === bccomp($openingBalance, '0')) {
+ Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $openingBalance, $account->id));
+ $sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language);
+ $destId = $account->id;
+ }
+ // amount is not positive
+ if (-1 === bccomp($openingBalance, '0')) {
+ Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $openingBalance, $account->id));
+ $destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language);
+ $sourceId = $account->id;
+ }
+ // amount is 0
+ if (0 === bccomp($openingBalance, '0')) {
+ Log::debug('Amount is zero, so will not make an OB group.');
+
+ throw new FireflyException('Amount for new opening balance was unexpectedly 0.');
+ }
+
+ // make amount positive, regardless:
+ $amount = Steam::positive($openingBalance);
+
+ // get or grab currency:
+ $currency = $this->accountRepository->getAccountCurrency($account);
+ if (null === $currency) {
+ $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup);
+ }
+
+ // submit to factory:
+ $submission = [
+ 'group_title' => null,
+ 'user' => $account->user,
+ 'user_group' => $account->user->userGroup,
+ 'transactions' => [[
+ 'type' => 'Opening balance',
+ 'date' => $openingBalanceDate,
+ 'source_id' => $sourceId,
+ 'source_name' => $sourceName,
+ 'destination_id' => $destId,
+ 'destination_name' => $destName,
+ 'user' => $account->user,
+ 'user_group' => $account->user->userGroup,
+ 'currency_id' => $currency->id,
+ 'order' => 0,
+ 'amount' => $amount,
+ 'foreign_amount' => null,
+ 'description' => trans('firefly.initial_balance_description', ['account' => $account->name]),
+ 'budget_id' => null,
+ 'budget_name' => null,
+ 'category_id' => null,
+ 'category_name' => null,
+ 'piggy_bank_id' => null,
+ 'piggy_bank_name' => null,
+ 'reconciled' => false,
+ 'notes' => null,
+ 'tags' => [],
+ ]],
+ ];
+ Log::debug('Going for submission in createOBGroupV2', $submission);
+
+ /** @var TransactionGroupFactory $factory */
+ $factory = app(TransactionGroupFactory::class);
+ $factory->setUser($account->user);
+
+ try {
+ $group = $factory->create($submission);
+ } catch (DuplicateTransactionException $e) {
+ Log::error($e->getMessage());
+ Log::error($e->getTraceAsString());
+
+ throw new FireflyException($e->getMessage(), 0, $e);
+ }
+
+ return $group;
+ }
+
/**
* Delete TransactionGroup with liability credit in it.
*/
@@ -305,16 +487,6 @@ trait AccountServiceTrait
}
}
- /**
- * Returns the credit transaction group, or NULL if it does not exist.
- */
- protected function getCreditTransaction(Account $account): ?TransactionGroup
- {
- Log::debug(sprintf('Now at %s', __METHOD__));
-
- return $this->accountRepository->getCreditTransactionGroup($account);
- }
-
/**
* Delete TransactionGroup with opening balance in it.
*/
@@ -334,11 +506,13 @@ trait AccountServiceTrait
}
/**
- * Returns the opening balance group, or NULL if it does not exist.
+ * Returns the credit transaction group, or NULL if it does not exist.
*/
- protected function getOBGroup(Account $account): ?TransactionGroup
+ protected function getCreditTransaction(Account $account): ?TransactionGroup
{
- return $this->accountRepository->getOpeningBalanceGroup($account);
+ Log::debug(sprintf('Now at %s', __METHOD__));
+
+ return $this->accountRepository->getCreditTransactionGroup($account);
}
protected function getCurrency(int $currencyId, string $currencyCode): TransactionCurrency
@@ -360,6 +534,14 @@ trait AccountServiceTrait
return $currency;
}
+ /**
+ * Returns the opening balance group, or NULL if it does not exist.
+ */
+ protected function getOBGroup(Account $account): ?TransactionGroup
+ {
+ return $this->accountRepository->getOpeningBalanceGroup($account);
+ }
+
/**
* Create the opposing "credit liability" transaction for credit liabilities.
*
@@ -418,142 +600,6 @@ trait AccountServiceTrait
return $clGroup;
}
- /**
- * @throws FireflyException
- */
- protected function createCreditTransaction(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
- {
- Log::debug('Now going to create an createCreditTransaction.');
-
- if (0 === bccomp($openingBalance, '0')) {
- Log::debug('Amount is zero, so will not make an liability credit group.');
-
- throw new FireflyException('Amount for new liability credit was unexpectedly 0.');
- }
-
- $language = Preferences::getForUser($account->user, 'language', 'en_US')->data;
- if (is_array($language)) {
- $language = 'en_US';
- }
- $language = (string) $language;
-
- // set source and/or destination based on whether the amount is positive or negative.
- // first, assume the amount is positive and go from there:
- // if amount is positive ("I am owed this debt"), source is special account, destination is the liability.
- $sourceId = null;
- $sourceName = trans('firefly.liability_credit_description', ['account' => $account->name], $language);
- $destId = $account->id;
- $destName = null;
- if (-1 === bccomp($openingBalance, '0')) {
- // amount is negative, reverse it
- $sourceId = $account->id;
- $sourceName = null;
- $destId = null;
- $destName = trans('firefly.liability_credit_description', ['account' => $account->name], $language);
- }
-
- // amount must be positive for the transaction to work.
- $amount = Steam::positive($openingBalance);
-
- // get or grab currency:
- $currency = $this->accountRepository->getAccountCurrency($account);
- if (null === $currency) {
- $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup);
- }
- // submit to factory:
- $submission = [
- 'group_title' => null,
- 'user' => $account->user,
- 'user_group' => $account->user->userGroup,
- 'transactions' => [[
- 'type' => 'Liability credit',
- 'date' => $openingBalanceDate,
- 'source_id' => $sourceId,
- 'source_name' => $sourceName,
- 'destination_id' => $destId,
- 'destination_name' => $destName,
- 'user' => $account->user,
- 'user_group' => $account->user->userGroup,
- 'currency_id' => $currency->id,
- 'order' => 0,
- 'amount' => $amount,
- 'foreign_amount' => null,
- 'description' => trans('firefly.liability_credit_description', ['account' => $account->name]),
- 'budget_id' => null,
- 'budget_name' => null,
- 'category_id' => null,
- 'category_name' => null,
- 'piggy_bank_id' => null,
- 'piggy_bank_name' => null,
- 'reconciled' => false,
- 'notes' => null,
- 'tags' => [],
- ]],
- ];
- Log::debug('Going for submission in createCreditTransaction', $submission);
-
- /** @var TransactionGroupFactory $factory */
- $factory = app(TransactionGroupFactory::class);
- $factory->setUser($account->user);
-
- try {
- $group = $factory->create($submission);
- } catch (DuplicateTransactionException $e) {
- Log::error($e->getMessage());
- Log::error($e->getTraceAsString());
-
- throw new FireflyException($e->getMessage(), 0, $e);
- }
-
- return $group;
- }
-
- /**
- * TODO refactor to "getfirstjournal"
- *
- * @throws FireflyException
- */
- private function getObJournal(TransactionGroup $group): TransactionJournal
- {
- /** @var null|TransactionJournal $journal */
- $journal = $group->transactionJournals()->first();
- if (null === $journal) {
- throw new FireflyException(sprintf('Group #%d has no OB journal', $group->id));
- }
-
- return $journal;
- }
-
- /**
- * TODO Rename to getOpposingTransaction
- *
- * @throws FireflyException
- */
- private function getOBTransaction(TransactionJournal $journal, Account $account): Transaction
- {
- /** @var null|Transaction $transaction */
- $transaction = $journal->transactions()->where('account_id', '!=', $account->id)->first();
- if (null === $transaction) {
- throw new FireflyException(sprintf('Could not get OB transaction for journal #%d', $journal->id));
- }
-
- return $transaction;
- }
-
- /**
- * @throws FireflyException
- */
- private function getNotOBTransaction(TransactionJournal $journal, Account $account): Transaction
- {
- /** @var null|Transaction $transaction */
- $transaction = $journal->transactions()->where('account_id', $account->id)->first();
- if (null === $transaction) {
- throw new FireflyException(sprintf('Could not get non-OB transaction for journal #%d', $journal->id));
- }
-
- return $transaction;
- }
-
/**
* Update or create the opening balance group.
* Since opening balance and date can still be empty strings, it may fail.
@@ -616,92 +662,46 @@ trait AccountServiceTrait
/**
* @throws FireflyException
*/
- protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
+ private function getNotOBTransaction(TransactionJournal $journal, Account $account): Transaction
{
- Log::debug('Now going to create an OB group.');
- $language = Preferences::getForUser($account->user, 'language', 'en_US')->data;
- if (is_array($language)) {
- $language = 'en_US';
- }
- $language = (string) $language;
- $sourceId = null;
- $sourceName = null;
- $destId = null;
- $destName = null;
-
- // amount is positive.
- if (1 === bccomp($openingBalance, '0')) {
- Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $openingBalance, $account->id));
- $sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language);
- $destId = $account->id;
- }
- // amount is not positive
- if (-1 === bccomp($openingBalance, '0')) {
- Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $openingBalance, $account->id));
- $destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language);
- $sourceId = $account->id;
- }
- // amount is 0
- if (0 === bccomp($openingBalance, '0')) {
- Log::debug('Amount is zero, so will not make an OB group.');
-
- throw new FireflyException('Amount for new opening balance was unexpectedly 0.');
+ /** @var null|Transaction $transaction */
+ $transaction = $journal->transactions()->where('account_id', $account->id)->first();
+ if (null === $transaction) {
+ throw new FireflyException(sprintf('Could not get non-OB transaction for journal #%d', $journal->id));
}
- // make amount positive, regardless:
- $amount = Steam::positive($openingBalance);
+ return $transaction;
+ }
- // get or grab currency:
- $currency = $this->accountRepository->getAccountCurrency($account);
- if (null === $currency) {
- $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup);
+ /**
+ * TODO refactor to "getfirstjournal"
+ *
+ * @throws FireflyException
+ */
+ private function getObJournal(TransactionGroup $group): TransactionJournal
+ {
+ /** @var null|TransactionJournal $journal */
+ $journal = $group->transactionJournals()->first();
+ if (null === $journal) {
+ throw new FireflyException(sprintf('Group #%d has no OB journal', $group->id));
}
- // submit to factory:
- $submission = [
- 'group_title' => null,
- 'user' => $account->user,
- 'user_group' => $account->user->userGroup,
- 'transactions' => [[
- 'type' => 'Opening balance',
- 'date' => $openingBalanceDate,
- 'source_id' => $sourceId,
- 'source_name' => $sourceName,
- 'destination_id' => $destId,
- 'destination_name' => $destName,
- 'user' => $account->user,
- 'user_group' => $account->user->userGroup,
- 'currency_id' => $currency->id,
- 'order' => 0,
- 'amount' => $amount,
- 'foreign_amount' => null,
- 'description' => trans('firefly.initial_balance_description', ['account' => $account->name]),
- 'budget_id' => null,
- 'budget_name' => null,
- 'category_id' => null,
- 'category_name' => null,
- 'piggy_bank_id' => null,
- 'piggy_bank_name' => null,
- 'reconciled' => false,
- 'notes' => null,
- 'tags' => [],
- ]],
- ];
- Log::debug('Going for submission in createOBGroupV2', $submission);
-
- /** @var TransactionGroupFactory $factory */
- $factory = app(TransactionGroupFactory::class);
- $factory->setUser($account->user);
-
- try {
- $group = $factory->create($submission);
- } catch (DuplicateTransactionException $e) {
- Log::error($e->getMessage());
- Log::error($e->getTraceAsString());
+ return $journal;
+ }
- throw new FireflyException($e->getMessage(), 0, $e);
+ /**
+ * TODO Rename to getOpposingTransaction
+ *
+ * @throws FireflyException
+ */
+ private function getOBTransaction(TransactionJournal $journal, Account $account): Transaction
+ {
+ /** @var null|Transaction $transaction */
+ $transaction = $journal->transactions()->where('account_id', '!=', $account->id)->first();
+ if (null === $transaction) {
+ throw new FireflyException(sprintf('Could not get OB transaction for journal #%d', $journal->id));
}
- return $group;
+ return $transaction;
}
}
diff --git a/app/Services/Internal/Support/CreditRecalculateService.php b/app/Services/Internal/Support/CreditRecalculateService.php
index 000c3ef335..c3685c525d 100644
--- a/app/Services/Internal/Support/CreditRecalculateService.php
+++ b/app/Services/Internal/Support/CreditRecalculateService.php
@@ -81,6 +81,26 @@ class CreditRecalculateService
$this->processWork();
}
+ public function setAccount(?Account $account): void
+ {
+ $this->account = $account;
+ }
+
+ public function setAccounts(Collection $accounts): void
+ {
+ $this->accounts = $accounts;
+ }
+
+ public function setGroup(TransactionGroup $group): void
+ {
+ $this->group = $group;
+ }
+
+ public function setJournals(Collection $journals): void
+ {
+ $this->journals = $journals;
+ }
+
private function collectFromJournals(Collection $transactionJournals): void
{
Log::debug('Now in collectFromJournals()');
@@ -100,16 +120,6 @@ class CreditRecalculateService
}
}
- private function processGroup(): void
- {
- $this->collectFromJournals($this->group->transactionJournals);
- }
-
- private function processJournals(): void
- {
- $this->collectFromJournals($this->journals);
- }
-
/**
* @throws FireflyException
*/
@@ -128,14 +138,6 @@ class CreditRecalculateService
}
}
- /**
- * @throws FireflyException
- */
- private function getSourceAccount(TransactionJournal $journal): Account
- {
- return $this->getAccountByDirection($journal, '<');
- }
-
/**
* @throws FireflyException
*/
@@ -156,6 +158,19 @@ class CreditRecalculateService
return $foundAccount;
}
+ private function getAmountToUse(Transaction $transaction, TransactionCurrency $accountCurrency, ?TransactionCurrency $foreignCurrency): string
+ {
+ $usedAmount = $transaction->amount;
+ // Log::debug(sprintf('Amount of transaction is %s', \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2)));
+ if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id === $accountCurrency->id) {
+ $usedAmount = $transaction->foreign_amount;
+
+ // Log::debug(sprintf('Overruled by foreign amount. Amount of transaction is now %s', \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2)));
+ }
+
+ return $usedAmount;
+ }
+
/**
* @throws FireflyException
*/
@@ -164,94 +179,127 @@ class CreditRecalculateService
return $this->getAccountByDirection($journal, '>');
}
- private function processAccount(): void
+ /**
+ * @throws FireflyException
+ */
+ private function getSourceAccount(TransactionJournal $journal): Account
{
- $valid = config('firefly.valid_liabilities');
- if (in_array($this->account->accountType->type, $valid, true)) {
- $this->work[] = $this->account;
- }
+ return $this->getAccountByDirection($journal, '<');
}
- private function processWork(): void
+ /**
+ * case 4
+ * it's a deposit into this liability (from revenue account).
+ * if it's a credit ("I am owed") this increases the amount due.
+ * because the person is having to pay more money.
+ */
+ private function isDepositIn(string $amount, string $transactionType): bool
{
- $this->repository = app(AccountRepositoryInterface::class);
- foreach ($this->work as $account) {
- $this->processWorkAccount($account);
- }
+ return TransactionTypeEnum::DEPOSIT->value === $transactionType && 1 === bccomp($amount, '0');
}
- private function processWorkAccount(Account $account): void
+ /**
+ * it's a deposit out of this liability (to asset).
+ *
+ * case 3
+ * if it's a credit ("I am owed") this decreases the amount due.
+ * because the person is paying us back.
+ *
+ * case 7
+ * if it's a debit ("I owe") this increases the amount due.
+ * because we are borrowing more money.
+ */
+ private function isDepositOut(string $amount, string $transactionType): bool
{
- Log::debug(sprintf('Now processing account #%d ("%s").', $account->id, $account->name));
- // get opening balance (if present)
- $this->repository->setUser($account->user);
- $direction = (string) $this->repository->getMetaValue($account, 'liability_direction');
- $openingBalance = $this->repository->getOpeningBalance($account);
- // Log::debug(sprintf('Found opening balance transaction journal #%d', $openingBalance->id));
- // if account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account:
- if ($openingBalance instanceof TransactionJournal && 'debit' === $direction) {
- $this->validateOpeningBalance($account, $openingBalance);
- }
- $startOfDebt = $this->repository->getOpeningBalanceAmount($account, false) ?? '0';
- $leftOfDebt = Steam::positive($startOfDebt);
- // Log::debug(sprintf('Start of debt is "%s", so initial left of debt is "%s"', \FireflyIII\Support\Facades\Steam::bcround($startOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2)));
+ return TransactionTypeEnum::DEPOSIT->value === $transactionType && -1 === bccomp($amount, '0');
+ }
- /** @var AccountMetaFactory $factory */
- $factory = app(AccountMetaFactory::class);
+ /**
+ * case 5: transfer into loan (from other loan).
+ * if it's a credit ("I am owed") this increases the amount due,
+ * because the person has to pay more back.
+ *
+ * case 8: transfer into loan (from other loan).
+ * if it's a debit ("I owe") this decreases the amount due.
+ * because the person has to pay more back.
+ */
+ private function isTransferIn(string $amount, string $transactionType): bool
+ {
+ return TransactionTypeEnum::TRANSFER->value === $transactionType && 1 === bccomp($amount, '0');
+ }
- // amount is positive or negative, doesn't matter.
- $factory->crud($account, 'start_of_debt', $startOfDebt);
+ /**
+ * it's a transfer out of loan (from other loan)
+ *
+ * case 9
+ * if it's a debit ("I owe") this decreases the amount due.
+ * because we remove money from the amount left to owe
+ */
+ private function isTransferOut(string $amount, string $transactionType): bool
+ {
+ return TransactionTypeEnum::TRANSFER->value === $transactionType && -1 === bccomp($amount, '0');
+ }
- // Log::debug(sprintf('Debt direction is "%s"', $direction));
+ /**
+ * It's a withdrawal into this liability (from asset).
+ *
+ * Case 1 = credit
+ * if it's a credit ("I am owed"), this increases the amount due,
+ * because we're lending person X more money
+ *
+ * Case 6 = debit
+ * if it's a debit ("I owe this amount"), this decreases the amount due,
+ * because we're paying off the debt
+ */
+ private function isWithdrawalIn(string $amount, string $transactionType): bool
+ {
+ return TransactionTypeEnum::WITHDRAWAL->value === $transactionType && 1 === bccomp($amount, '0');
+ }
- // now loop all transactions (except opening balance and credit thing)
- $transactions = $account
- ->transactions()
- ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
- ->orderBy('transaction_journals.date', 'ASC')
- ->get(['transactions.*'])
- ;
- // $transactions->count();
- // Log::debug(sprintf('Found %d transaction(s) to process.', $total));
+ /**
+ * it's a withdrawal away from this liability (into expense account).
+ *
+ * Case 2
+ * if it's a credit ("I am owed"), this decreases the amount due,
+ * because we're sending money away from the loan (like loan forgiveness)
+ *
+ * Case 8
+ * if it's a debit ("I owe this amount") this increase the amount due.
+ * because we are paying interest.
+ */
+ private function isWithdrawalOut(string $amount, string $transactionType): bool
+ {
+ return TransactionTypeEnum::WITHDRAWAL->value === $transactionType && -1 === bccomp($amount, '0');
+ }
- /** @var Transaction $transaction */
- foreach ($transactions as $transaction) {
- // Log::debug(sprintf('[%d/%d] Processing transaction.', $index + 1, $total));
- $leftOfDebt = $this->processTransaction($account, $direction, $transaction, $leftOfDebt);
+ private function processAccount(): void
+ {
+ $valid = config('firefly.valid_liabilities');
+ if (in_array($this->account->accountType->type, $valid, true)) {
+ $this->work[] = $this->account;
}
- $factory->crud($account, 'current_debt', $leftOfDebt);
- Log::debug(sprintf('Done processing account #%d ("%s")', $account->id, $account->name));
}
- /**
- * If account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account:
- */
- private function validateOpeningBalance(Account $account, TransactionJournal $openingBalance): void
+ private function processAccounts(): void
{
- /** @var Transaction $source */
- $source = $openingBalance->transactions()->where('amount', '<', 0)->first();
+ $valid = config('firefly.valid_liabilities');
- /** @var Transaction $dest */
- $dest = $openingBalance->transactions()->where('amount', '>', 0)->first();
- if ($source->account_id !== $account->id) {
- Log::info(sprintf('Liability #%d has a reversed opening balance. Will fix this now.', $account->id));
- Log::debug(sprintf('Source amount "%s" is now "%s"', $source->amount, Steam::positive($source->amount)));
- Log::debug(sprintf('Destination amount "%s" is now "%s"', $dest->amount, Steam::negative($dest->amount)));
- $source->amount = Steam::positive($source->amount);
- $dest->amount = Steam::negative($source->amount);
- if (null !== $source->foreign_amount && '' !== $source->foreign_amount) {
- $source->foreign_amount = Steam::positive($source->foreign_amount);
- Log::debug(sprintf('Source foreign amount "%s" is now "%s"', $source->foreign_amount, Steam::positive($source->foreign_amount)));
- }
- if (null !== $dest->foreign_amount && '' !== $dest->foreign_amount) {
- $dest->foreign_amount = Steam::negative($dest->foreign_amount);
- Log::debug(sprintf('Destination amount "%s" is now "%s"', $dest->foreign_amount, Steam::negative($dest->foreign_amount)));
+ /** @var Account $account */
+ foreach ($this->accounts as $account) {
+ if (in_array($account->accountType->type, $valid, true)) {
+ $this->work[] = $account;
}
- $source->save();
- $dest->save();
}
+ }
- // Log::debug('Opening balance is valid');
+ private function processGroup(): void
+ {
+ $this->collectFromJournals($this->group->transactionJournals);
+ }
+
+ private function processJournals(): void
+ {
+ $this->collectFromJournals($this->journals);
}
/**
@@ -386,133 +434,85 @@ class CreditRecalculateService
return $leftOfDebt;
}
- private function getAmountToUse(Transaction $transaction, TransactionCurrency $accountCurrency, ?TransactionCurrency $foreignCurrency): string
+ private function processWork(): void
{
- $usedAmount = $transaction->amount;
- // Log::debug(sprintf('Amount of transaction is %s', \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2)));
- if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id === $accountCurrency->id) {
- $usedAmount = $transaction->foreign_amount;
-
- // Log::debug(sprintf('Overruled by foreign amount. Amount of transaction is now %s', \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2)));
+ $this->repository = app(AccountRepositoryInterface::class);
+ foreach ($this->work as $account) {
+ $this->processWorkAccount($account);
}
-
- return $usedAmount;
}
- /**
- * It's a withdrawal into this liability (from asset).
- *
- * Case 1 = credit
- * if it's a credit ("I am owed"), this increases the amount due,
- * because we're lending person X more money
- *
- * Case 6 = debit
- * if it's a debit ("I owe this amount"), this decreases the amount due,
- * because we're paying off the debt
- */
- private function isWithdrawalIn(string $amount, string $transactionType): bool
+ private function processWorkAccount(Account $account): void
{
- return TransactionTypeEnum::WITHDRAWAL->value === $transactionType && 1 === bccomp($amount, '0');
- }
+ Log::debug(sprintf('Now processing account #%d ("%s").', $account->id, $account->name));
+ // get opening balance (if present)
+ $this->repository->setUser($account->user);
+ $direction = (string) $this->repository->getMetaValue($account, 'liability_direction');
+ $openingBalance = $this->repository->getOpeningBalance($account);
+ // Log::debug(sprintf('Found opening balance transaction journal #%d', $openingBalance->id));
+ // if account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account:
+ if ($openingBalance instanceof TransactionJournal && 'debit' === $direction) {
+ $this->validateOpeningBalance($account, $openingBalance);
+ }
+ $startOfDebt = $this->repository->getOpeningBalanceAmount($account, false) ?? '0';
+ $leftOfDebt = Steam::positive($startOfDebt);
+ // Log::debug(sprintf('Start of debt is "%s", so initial left of debt is "%s"', \FireflyIII\Support\Facades\Steam::bcround($startOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2)));
- /**
- * it's a withdrawal away from this liability (into expense account).
- *
- * Case 2
- * if it's a credit ("I am owed"), this decreases the amount due,
- * because we're sending money away from the loan (like loan forgiveness)
- *
- * Case 8
- * if it's a debit ("I owe this amount") this increase the amount due.
- * because we are paying interest.
- */
- private function isWithdrawalOut(string $amount, string $transactionType): bool
- {
- return TransactionTypeEnum::WITHDRAWAL->value === $transactionType && -1 === bccomp($amount, '0');
- }
+ /** @var AccountMetaFactory $factory */
+ $factory = app(AccountMetaFactory::class);
- /**
- * it's a deposit out of this liability (to asset).
- *
- * case 3
- * if it's a credit ("I am owed") this decreases the amount due.
- * because the person is paying us back.
- *
- * case 7
- * if it's a debit ("I owe") this increases the amount due.
- * because we are borrowing more money.
- */
- private function isDepositOut(string $amount, string $transactionType): bool
- {
- return TransactionTypeEnum::DEPOSIT->value === $transactionType && -1 === bccomp($amount, '0');
- }
+ // amount is positive or negative, doesn't matter.
+ $factory->crud($account, 'start_of_debt', $startOfDebt);
- /**
- * case 4
- * it's a deposit into this liability (from revenue account).
- * if it's a credit ("I am owed") this increases the amount due.
- * because the person is having to pay more money.
- */
- private function isDepositIn(string $amount, string $transactionType): bool
- {
- return TransactionTypeEnum::DEPOSIT->value === $transactionType && 1 === bccomp($amount, '0');
- }
+ // Log::debug(sprintf('Debt direction is "%s"', $direction));
- /**
- * case 5: transfer into loan (from other loan).
- * if it's a credit ("I am owed") this increases the amount due,
- * because the person has to pay more back.
- *
- * case 8: transfer into loan (from other loan).
- * if it's a debit ("I owe") this decreases the amount due.
- * because the person has to pay more back.
- */
- private function isTransferIn(string $amount, string $transactionType): bool
- {
- return TransactionTypeEnum::TRANSFER->value === $transactionType && 1 === bccomp($amount, '0');
+ // now loop all transactions (except opening balance and credit thing)
+ $transactions = $account
+ ->transactions()
+ ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
+ ->orderBy('transaction_journals.date', 'ASC')
+ ->get(['transactions.*'])
+ ;
+ // $transactions->count();
+ // Log::debug(sprintf('Found %d transaction(s) to process.', $total));
+
+ /** @var Transaction $transaction */
+ foreach ($transactions as $transaction) {
+ // Log::debug(sprintf('[%d/%d] Processing transaction.', $index + 1, $total));
+ $leftOfDebt = $this->processTransaction($account, $direction, $transaction, $leftOfDebt);
+ }
+ $factory->crud($account, 'current_debt', $leftOfDebt);
+ Log::debug(sprintf('Done processing account #%d ("%s")', $account->id, $account->name));
}
/**
- * it's a transfer out of loan (from other loan)
- *
- * case 9
- * if it's a debit ("I owe") this decreases the amount due.
- * because we remove money from the amount left to owe
+ * If account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account:
*/
- private function isTransferOut(string $amount, string $transactionType): bool
- {
- return TransactionTypeEnum::TRANSFER->value === $transactionType && -1 === bccomp($amount, '0');
- }
-
- public function setAccount(?Account $account): void
- {
- $this->account = $account;
- }
-
- public function setGroup(TransactionGroup $group): void
- {
- $this->group = $group;
- }
-
- public function setJournals(Collection $journals): void
- {
- $this->journals = $journals;
- }
-
- private function processAccounts(): void
+ private function validateOpeningBalance(Account $account, TransactionJournal $openingBalance): void
{
- $valid = config('firefly.valid_liabilities');
+ /** @var Transaction $source */
+ $source = $openingBalance->transactions()->where('amount', '<', 0)->first();
- /** @var Account $account */
- foreach ($this->accounts as $account) {
- if (in_array($account->accountType->type, $valid, true)) {
- $this->work[] = $account;
+ /** @var Transaction $dest */
+ $dest = $openingBalance->transactions()->where('amount', '>', 0)->first();
+ if ($source->account_id !== $account->id) {
+ Log::info(sprintf('Liability #%d has a reversed opening balance. Will fix this now.', $account->id));
+ Log::debug(sprintf('Source amount "%s" is now "%s"', $source->amount, Steam::positive($source->amount)));
+ Log::debug(sprintf('Destination amount "%s" is now "%s"', $dest->amount, Steam::negative($dest->amount)));
+ $source->amount = Steam::positive($source->amount);
+ $dest->amount = Steam::negative($source->amount);
+ if (null !== $source->foreign_amount && '' !== $source->foreign_amount) {
+ $source->foreign_amount = Steam::positive($source->foreign_amount);
+ Log::debug(sprintf('Source foreign amount "%s" is now "%s"', $source->foreign_amount, Steam::positive($source->foreign_amount)));
+ }
+ if (null !== $dest->foreign_amount && '' !== $dest->foreign_amount) {
+ $dest->foreign_amount = Steam::negative($dest->foreign_amount);
+ Log::debug(sprintf('Destination amount "%s" is now "%s"', $dest->foreign_amount, Steam::negative($dest->foreign_amount)));
}
+ $source->save();
+ $dest->save();
}
- }
- public function setAccounts(Collection $accounts): void
- {
- $this->accounts = $accounts;
+ // Log::debug('Opening balance is valid');
}
}
diff --git a/app/Services/Internal/Support/JournalServiceTrait.php b/app/Services/Internal/Support/JournalServiceTrait.php
index 0566be1ce1..8ecefe74bd 100644
--- a/app/Services/Internal/Support/JournalServiceTrait.php
+++ b/app/Services/Internal/Support/JournalServiceTrait.php
@@ -112,153 +112,122 @@ trait JournalServiceTrait
return $result;
}
- private function findAccountById(array $data, array $types, ?Account $opposite = null): ?Account
+ /**
+ * @throws FireflyException
+ */
+ protected function getAmount(string $amount): string
{
- // first attempt, find by ID.
- if (null !== $data['id']) {
- $search = $this->accountRepository->find((int) $data['id']);
- if (null !== $search && in_array($search->accountType->type, $types, true)) {
- Log::debug(sprintf('Found "account_id" object: #%d, "%s" of type %s (1)', $search->id, $search->name, $search->accountType->type));
-
- if ($opposite?->id === $search->id) {
- Log::debug(sprintf('Account #%d is the same as opposite account #%d, returning NULL.', $search->id, $opposite->id));
-
- return null;
- }
-
- return $search;
- }
- if (null !== $search && 0 === count($types)) {
- Log::debug(sprintf('Found "account_id" object: #%d, "%s" of type %s (2)', $search->id, $search->name, $search->accountType->type));
-
- return $search;
- }
+ if ('' === $amount) {
+ throw new FireflyException(sprintf('The amount cannot be an empty string: "%s"', $amount));
+ }
+ Log::debug(sprintf('Now in getAmount("%s")', $amount));
+ if (0 === bccomp('0', $amount)) {
+ throw new FireflyException(sprintf('The amount seems to be zero: "%s"', $amount));
}
- Log::debug(sprintf('Found no account by ID #%d of types', $data['id']), $types);
- return null;
+ return $amount;
}
- private function findAccountByIban(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account
+ protected function getForeignAmount(?string $amount): ?string
{
- if ($account instanceof Account) {
- Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name));
+ if (null === $amount) {
+ Log::debug('No foreign amount info in array. Return NULL');
- return $account;
+ return null;
}
- if (null === $data['iban'] || '' === $data['iban']) {
- Log::debug('IBAN is empty, will not search for IBAN.');
+ if ('' === $amount) {
+ Log::debug('Foreign amount is empty string, return NULL.');
return null;
}
- // find by preferred type.
- $result = $this->accountRepository->findByIbanNull($data['iban'], [$types[0]]);
- // or any expected type.
- $result ??= $this->accountRepository->findByIbanNull($data['iban'], $types);
-
- if (null !== $result) {
- Log::debug(sprintf('Found "account_iban" object: #%d, %s', $result->id, $result->name));
-
- if ($opposite?->id === $result->id) {
- Log::debug(sprintf('Account #%d is the same as opposite account #%d, returning NULL.', $result->id, $opposite->id));
-
- return null;
- }
+ if (0 === bccomp('0', $amount)) {
+ Log::debug('Foreign amount is 0.0, return NULL.');
- return $result;
+ return null;
}
- Log::debug(sprintf('Found no account with IBAN "%s" of expected types', $data['iban']), $types);
+ Log::debug(sprintf('Foreign amount is %s', $amount));
- return null;
+ return $amount;
}
- private function findAccountByNumber(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account
+ protected function storeBudget(TransactionJournal $journal, NullArrayObject $data): void
{
- if ($account instanceof Account) {
- Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name));
-
- return $account;
- }
- if (null === $data['number'] || '' === $data['number']) {
- Log::debug('Account number is empty, will not search for account number.');
+ if (TransactionTypeEnum::WITHDRAWAL->value !== $journal->transactionType->type) {
+ $journal->budgets()->sync([]);
- return null;
+ return;
}
- // find by preferred type.
- $result = $this->accountRepository->findByAccountNumber((string) $data['number'], [$types[0]]);
-
- // or any expected type.
- $result ??= $this->accountRepository->findByAccountNumber((string) $data['number'], $types);
-
- if (null !== $result) {
- Log::debug(sprintf('Found account: #%d, %s', $result->id, $result->name));
-
- if ($opposite?->id === $result->id) {
- Log::debug(sprintf('Account #%d is the same as opposite account #%d, returning NULL.', $result->id, $opposite->id));
-
- return null;
- }
+ $budget = $this->budgetRepository->findBudget($data['budget_id'], $data['budget_name']);
+ if (null !== $budget) {
+ Log::debug(sprintf('Link budget #%d to journal #%d', $budget->id, $journal->id));
+ $journal->budgets()->sync([$budget->id]);
- return $result;
+ return;
}
-
- Log::debug(sprintf('Found no account with account number "%s" of expected types', $data['number']), $types);
-
- return null;
+ // if the budget is NULL, sync empty.
+ $journal->budgets()->sync([]);
}
- private function findAccountByName(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account
+ protected function storeCategory(TransactionJournal $journal, NullArrayObject $data): void
{
- if ($account instanceof Account) {
- Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name));
-
- return $account;
- }
- if (null === $data['name'] || '' === $data['name']) {
- Log::debug('Account name is empty, will not search for account name.');
+ $category = $this->categoryRepository->findCategory($data['category_id'], $data['category_name']);
+ if (null !== $category) {
+ Log::debug(sprintf('Link category #%d to journal #%d', $category->id, $journal->id));
+ $journal->categories()->sync([$category->id]);
- return null;
+ return;
}
+ // if the category is NULL, sync empty.
+ $journal->categories()->sync([]);
+ }
- // find by preferred type.
- Log::debug('Find by preferred type.');
- $result = $this->accountRepository->findByName($data['name'], [$types[0]]);
-
- // or any expected type.
- Log::debug('Find by any expected type.');
- $result ??= $this->accountRepository->findByName($data['name'], $types);
-
- if (null !== $result) {
- Log::debug(sprintf('Found "account_name" object: #%d, %s', $result->id, $result->name));
-
- if ($opposite?->id === $result->id) {
- Log::debug(sprintf('Account #%d is the same as opposite account #%d, returning NULL.', $result->id, $opposite->id));
-
- return null;
+ protected function storeNotes(TransactionJournal $journal, ?string $notes): void
+ {
+ $notes = (string) $notes;
+ $note = $journal->notes()->first();
+ if ('' !== $notes) {
+ if (null === $note) {
+ $note = new Note();
+ $note->noteable()->associate($journal);
}
+ $note->text = $notes;
+ $note->save();
+ Log::debug(sprintf('Stored notes for journal #%d', $journal->id));
- return $result;
+ return;
}
- Log::debug(sprintf('Found no account with account name "%s" of expected types', $data['name']), $types);
-
- return null;
+ // try to delete existing notes.
+ $note?->delete();
}
- private function getCreatableType(array $types): ?string
+ /**
+ * Link tags to journal.
+ */
+ protected function storeTags(TransactionJournal $journal, ?array $tags): void
{
- $result = null;
- $list = config('firefly.dynamic_creation_allowed');
-
- /** @var string $type */
- foreach ($types as $type) {
- if (in_array($type, $list, true)) {
- $result = $type;
+ Log::debug('Now in storeTags()', $tags ?? []);
+ $this->tagFactory->setUser($journal->user);
+ $set = [];
+ if (!is_array($tags)) {
+ Log::debug('Tags is not an array, break.');
- break;
+ return;
+ }
+ Log::debug('Start of loop.');
+ foreach ($tags as $string) {
+ $string = (string) $string;
+ Log::debug(sprintf('Now at tag "%s"', $string));
+ if ('' !== $string) {
+ $tag = $this->tagFactory->findOrCreate($string);
+ if (null !== $tag) {
+ $set[] = $tag->id;
+ }
}
}
-
- return $result;
+ $set = array_unique($set);
+ Log::debug('End of loop.');
+ Log::debug(sprintf('Total nr. of tags: %d', count($tags)), $tags);
+ $journal->tags()->sync($set);
}
/**
@@ -329,132 +298,163 @@ trait JournalServiceTrait
return $account;
}
- private function getCashAccount(?Account $account, array $data, array $types): ?Account
+ private function findAccountByIban(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account
{
- // return cash account.
- if (!$account instanceof Account && '' === (string) $data['name'] && in_array(AccountTypeEnum::CASH->value, $types, true)) {
- $account = $this->accountRepository->getCashAccount();
+ if ($account instanceof Account) {
+ Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name));
+
+ return $account;
}
- Log::debug('Cannot return cash account, return input instead.');
+ if (null === $data['iban'] || '' === $data['iban']) {
+ Log::debug('IBAN is empty, will not search for IBAN.');
- return $account;
+ return null;
+ }
+ // find by preferred type.
+ $result = $this->accountRepository->findByIbanNull($data['iban'], [$types[0]]);
+ // or any expected type.
+ $result ??= $this->accountRepository->findByIbanNull($data['iban'], $types);
+
+ if (null !== $result) {
+ Log::debug(sprintf('Found "account_iban" object: #%d, %s', $result->id, $result->name));
+
+ if ($opposite?->id === $result->id) {
+ Log::debug(sprintf('Account #%d is the same as opposite account #%d, returning NULL.', $result->id, $opposite->id));
+
+ return null;
+ }
+
+ return $result;
+ }
+ Log::debug(sprintf('Found no account with IBAN "%s" of expected types', $data['iban']), $types);
+
+ return null;
}
- /**
- * @throws FireflyException
- */
- protected function getAmount(string $amount): string
+ private function findAccountById(array $data, array $types, ?Account $opposite = null): ?Account
{
- if ('' === $amount) {
- throw new FireflyException(sprintf('The amount cannot be an empty string: "%s"', $amount));
- }
- Log::debug(sprintf('Now in getAmount("%s")', $amount));
- if (0 === bccomp('0', $amount)) {
- throw new FireflyException(sprintf('The amount seems to be zero: "%s"', $amount));
+ // first attempt, find by ID.
+ if (null !== $data['id']) {
+ $search = $this->accountRepository->find((int) $data['id']);
+ if (null !== $search && in_array($search->accountType->type, $types, true)) {
+ Log::debug(sprintf('Found "account_id" object: #%d, "%s" of type %s (1)', $search->id, $search->name, $search->accountType->type));
+
+ if ($opposite?->id === $search->id) {
+ Log::debug(sprintf('Account #%d is the same as opposite account #%d, returning NULL.', $search->id, $opposite->id));
+
+ return null;
+ }
+
+ return $search;
+ }
+ if (null !== $search && 0 === count($types)) {
+ Log::debug(sprintf('Found "account_id" object: #%d, "%s" of type %s (2)', $search->id, $search->name, $search->accountType->type));
+
+ return $search;
+ }
}
+ Log::debug(sprintf('Found no account by ID #%d of types', $data['id']), $types);
- return $amount;
+ return null;
}
- protected function getForeignAmount(?string $amount): ?string
+ private function findAccountByName(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account
{
- if (null === $amount) {
- Log::debug('No foreign amount info in array. Return NULL');
+ if ($account instanceof Account) {
+ Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name));
- return null;
+ return $account;
}
- if ('' === $amount) {
- Log::debug('Foreign amount is empty string, return NULL.');
+ if (null === $data['name'] || '' === $data['name']) {
+ Log::debug('Account name is empty, will not search for account name.');
return null;
}
- if (0 === bccomp('0', $amount)) {
- Log::debug('Foreign amount is 0.0, return NULL.');
- return null;
+ // find by preferred type.
+ Log::debug('Find by preferred type.');
+ $result = $this->accountRepository->findByName($data['name'], [$types[0]]);
+
+ // or any expected type.
+ Log::debug('Find by any expected type.');
+ $result ??= $this->accountRepository->findByName($data['name'], $types);
+
+ if (null !== $result) {
+ Log::debug(sprintf('Found "account_name" object: #%d, %s', $result->id, $result->name));
+
+ if ($opposite?->id === $result->id) {
+ Log::debug(sprintf('Account #%d is the same as opposite account #%d, returning NULL.', $result->id, $opposite->id));
+
+ return null;
+ }
+
+ return $result;
}
- Log::debug(sprintf('Foreign amount is %s', $amount));
+ Log::debug(sprintf('Found no account with account name "%s" of expected types', $data['name']), $types);
- return $amount;
+ return null;
}
- protected function storeBudget(TransactionJournal $journal, NullArrayObject $data): void
+ private function findAccountByNumber(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account
{
- if (TransactionTypeEnum::WITHDRAWAL->value !== $journal->transactionType->type) {
- $journal->budgets()->sync([]);
+ if ($account instanceof Account) {
+ Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name));
- return;
+ return $account;
}
- $budget = $this->budgetRepository->findBudget($data['budget_id'], $data['budget_name']);
- if (null !== $budget) {
- Log::debug(sprintf('Link budget #%d to journal #%d', $budget->id, $journal->id));
- $journal->budgets()->sync([$budget->id]);
+ if (null === $data['number'] || '' === $data['number']) {
+ Log::debug('Account number is empty, will not search for account number.');
- return;
+ return null;
}
- // if the budget is NULL, sync empty.
- $journal->budgets()->sync([]);
- }
+ // find by preferred type.
+ $result = $this->accountRepository->findByAccountNumber((string) $data['number'], [$types[0]]);
- protected function storeCategory(TransactionJournal $journal, NullArrayObject $data): void
- {
- $category = $this->categoryRepository->findCategory($data['category_id'], $data['category_name']);
- if (null !== $category) {
- Log::debug(sprintf('Link category #%d to journal #%d', $category->id, $journal->id));
- $journal->categories()->sync([$category->id]);
+ // or any expected type.
+ $result ??= $this->accountRepository->findByAccountNumber((string) $data['number'], $types);
- return;
+ if (null !== $result) {
+ Log::debug(sprintf('Found account: #%d, %s', $result->id, $result->name));
+
+ if ($opposite?->id === $result->id) {
+ Log::debug(sprintf('Account #%d is the same as opposite account #%d, returning NULL.', $result->id, $opposite->id));
+
+ return null;
+ }
+
+ return $result;
}
- // if the category is NULL, sync empty.
- $journal->categories()->sync([]);
+
+ Log::debug(sprintf('Found no account with account number "%s" of expected types', $data['number']), $types);
+
+ return null;
}
- protected function storeNotes(TransactionJournal $journal, ?string $notes): void
+ private function getCashAccount(?Account $account, array $data, array $types): ?Account
{
- $notes = (string) $notes;
- $note = $journal->notes()->first();
- if ('' !== $notes) {
- if (null === $note) {
- $note = new Note();
- $note->noteable()->associate($journal);
- }
- $note->text = $notes;
- $note->save();
- Log::debug(sprintf('Stored notes for journal #%d', $journal->id));
-
- return;
+ // return cash account.
+ if (!$account instanceof Account && '' === (string) $data['name'] && in_array(AccountTypeEnum::CASH->value, $types, true)) {
+ $account = $this->accountRepository->getCashAccount();
}
- // try to delete existing notes.
- $note?->delete();
+ Log::debug('Cannot return cash account, return input instead.');
+
+ return $account;
}
- /**
- * Link tags to journal.
- */
- protected function storeTags(TransactionJournal $journal, ?array $tags): void
+ private function getCreatableType(array $types): ?string
{
- Log::debug('Now in storeTags()', $tags ?? []);
- $this->tagFactory->setUser($journal->user);
- $set = [];
- if (!is_array($tags)) {
- Log::debug('Tags is not an array, break.');
+ $result = null;
+ $list = config('firefly.dynamic_creation_allowed');
- return;
- }
- Log::debug('Start of loop.');
- foreach ($tags as $string) {
- $string = (string) $string;
- Log::debug(sprintf('Now at tag "%s"', $string));
- if ('' !== $string) {
- $tag = $this->tagFactory->findOrCreate($string);
- if (null !== $tag) {
- $set[] = $tag->id;
- }
+ /** @var string $type */
+ foreach ($types as $type) {
+ if (in_array($type, $list, true)) {
+ $result = $type;
+
+ break;
}
}
- $set = array_unique($set);
- Log::debug('End of loop.');
- Log::debug(sprintf('Total nr. of tags: %d', count($tags)), $tags);
- $journal->tags()->sync($set);
+
+ return $result;
}
}
diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.php
index e9fd511ba9..09c9e0390f 100644
--- a/app/Services/Internal/Support/RecurringTransactionTrait.php
+++ b/app/Services/Internal/Support/RecurringTransactionTrait.php
@@ -165,6 +165,23 @@ trait RecurringTransactionTrait
}
}
+ protected function deleteRepetitions(Recurrence $recurrence): void
+ {
+ $recurrence->recurrenceRepetitions()->delete();
+ }
+
+ protected function deleteTransactions(Recurrence $recurrence): void
+ {
+ Log::debug('deleteTransactions()');
+
+ /** @var RecurrenceTransaction $transaction */
+ foreach ($recurrence->recurrenceTransactions as $transaction) {
+ $transaction->recurrenceTransactionMeta()->delete();
+
+ $transaction->delete();
+ }
+ }
+
protected function findAccount(array $expectedTypes, ?int $accountId, ?string $accountName): Account
{
$result = null;
@@ -217,27 +234,42 @@ trait RecurringTransactionTrait
return $result ?? $repository->getCashAccount();
}
- private function setBudget(RecurrenceTransaction $transaction, int $budgetId): void
+ protected function updatePiggyBank(RecurrenceTransaction $transaction, int $piggyId): void
{
- Log::debug(sprintf('Now in %s', __METHOD__));
- $budgetFactory = app(BudgetFactory::class);
- $budgetFactory->setUser($transaction->recurrence->user);
- $budget = $budgetFactory->find($budgetId, null);
- if (null === $budget) {
- // remove budget from recurring transaction:
- $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->delete();
-
- return;
+ /** @var PiggyBankFactory $factory */
+ $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();
+ if (null === $entry) {
+ $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'piggy_bank_id', 'value' => $piggyBank->id]);
+ }
+ $entry->value = $piggyBank->id;
+ $entry->save();
}
+ if (null === $piggyBank) {
+ // delete if present
+ $transaction->recurrenceTransactionMeta()->where('name', 'piggy_bank_id')->delete();
+ }
+ }
- $meta = $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->first();
- if (null === $meta) {
- $meta = new RecurrenceTransactionMeta();
- $meta->rt_id = $transaction->id;
- $meta->name = 'budget_id';
+ protected function updateTags(RecurrenceTransaction $transaction, array $tags): void
+ {
+ if (0 !== count($tags)) {
+ /** @var null|RecurrenceMeta $entry */
+ $entry = $transaction->recurrenceTransactionMeta()->where('name', 'tags')->first();
+ if (null === $entry) {
+ $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => json_encode($tags)]);
+ }
+ $entry->value = json_encode($tags);
+ $entry->save();
+ }
+ if (0 === count($tags)) {
+ // delete if present
+ $transaction->recurrenceTransactionMeta()->where('name', 'tags')->delete();
}
- $meta->value = $budget->id;
- $meta->save();
}
private function setBill(RecurrenceTransaction $transaction, int $billId): void
@@ -262,6 +294,29 @@ trait RecurringTransactionTrait
$meta->save();
}
+ private function setBudget(RecurrenceTransaction $transaction, int $budgetId): void
+ {
+ Log::debug(sprintf('Now in %s', __METHOD__));
+ $budgetFactory = app(BudgetFactory::class);
+ $budgetFactory->setUser($transaction->recurrence->user);
+ $budget = $budgetFactory->find($budgetId, null);
+ if (null === $budget) {
+ // remove budget from recurring transaction:
+ $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->delete();
+
+ return;
+ }
+
+ $meta = $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->first();
+ if (null === $meta) {
+ $meta = new RecurrenceTransactionMeta();
+ $meta->rt_id = $transaction->id;
+ $meta->name = 'budget_id';
+ }
+ $meta->value = $budget->id;
+ $meta->save();
+ }
+
private function setCategory(RecurrenceTransaction $transaction, int $categoryId): void
{
$categoryFactory = app(CategoryFactory::class);
@@ -284,59 +339,4 @@ trait RecurringTransactionTrait
$meta->value = $category->id;
$meta->save();
}
-
- protected function updatePiggyBank(RecurrenceTransaction $transaction, int $piggyId): void
- {
- /** @var PiggyBankFactory $factory */
- $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();
- if (null === $entry) {
- $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'piggy_bank_id', 'value' => $piggyBank->id]);
- }
- $entry->value = $piggyBank->id;
- $entry->save();
- }
- if (null === $piggyBank) {
- // delete if present
- $transaction->recurrenceTransactionMeta()->where('name', 'piggy_bank_id')->delete();
- }
- }
-
- protected function updateTags(RecurrenceTransaction $transaction, array $tags): void
- {
- if (0 !== count($tags)) {
- /** @var null|RecurrenceMeta $entry */
- $entry = $transaction->recurrenceTransactionMeta()->where('name', 'tags')->first();
- if (null === $entry) {
- $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => json_encode($tags)]);
- }
- $entry->value = json_encode($tags);
- $entry->save();
- }
- if (0 === count($tags)) {
- // delete if present
- $transaction->recurrenceTransactionMeta()->where('name', 'tags')->delete();
- }
- }
-
- protected function deleteRepetitions(Recurrence $recurrence): void
- {
- $recurrence->recurrenceRepetitions()->delete();
- }
-
- protected function deleteTransactions(Recurrence $recurrence): void
- {
- Log::debug('deleteTransactions()');
-
- /** @var RecurrenceTransaction $transaction */
- foreach ($recurrence->recurrenceTransactions as $transaction) {
- $transaction->recurrenceTransactionMeta()->delete();
-
- $transaction->delete();
- }
- }
}
diff --git a/app/Services/Internal/Update/AccountUpdateService.php b/app/Services/Internal/Update/AccountUpdateService.php
index 6dce8b30c6..7ef55d69d9 100644
--- a/app/Services/Internal/Update/AccountUpdateService.php
+++ b/app/Services/Internal/Update/AccountUpdateService.php
@@ -46,11 +46,11 @@ class AccountUpdateService
use AccountServiceTrait;
protected AccountRepositoryInterface $accountRepository;
- protected array $validAssetFields;
- protected array $validCCFields;
- protected array $validFields;
- private array $canHaveOpeningBalance;
- private User $user;
+ protected array $validAssetFields;
+ protected array $validCCFields;
+ protected array $validFields;
+ private array $canHaveOpeningBalance;
+ private User $user;
/**
* Constructor.
@@ -64,6 +64,11 @@ class AccountUpdateService
$this->accountRepository = app(AccountRepositoryInterface::class);
}
+ public function setUser(User $user): void
+ {
+ $this->user = $user;
+ }
+
/**
* Update account data.
*
@@ -79,7 +84,7 @@ class AccountUpdateService
// find currency, or use default currency instead.
if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
- $currency = $this->getCurrency((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null));
+ $currency = $this->getCurrency((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null));
unset($data['currency_code'], $data['currency_id']);
$data['currency_id'] = $currency->id;
}
@@ -98,7 +103,7 @@ class AccountUpdateService
// update note:
if (array_key_exists('notes', $data) && null !== $data['notes']) {
- $this->updateNote($account, (string)$data['notes']);
+ $this->updateNote($account, (string) $data['notes']);
}
// update preferences if inactive:
@@ -109,62 +114,6 @@ class AccountUpdateService
return $account;
}
- public function setUser(User $user): void
- {
- $this->user = $user;
- }
-
- private function updateAccount(Account $account, array $data): Account
- {
- // update the account itself:
- if (array_key_exists('name', $data)) {
- $account->name = $data['name'];
- }
- if (array_key_exists('active', $data)) {
- $account->active = $data['active'];
- }
- if (array_key_exists('iban', $data)) {
- $account->iban = Steam::filterSpaces((string)$data['iban']);
- }
-
- // set liability, but account must already be a liability.
- // $liabilityType = $data['liability_type'] ?? '';
- if ($this->isLiability($account) && array_key_exists('liability_type', $data)) {
- $type = $this->getAccountType($data['liability_type']);
- $account->account_type_id = $type->id;
- }
- // set liability, alternative method used in v1 layout:
-
- if ($this->isLiability($account) && array_key_exists('account_type_id', $data)) {
- $type = AccountType::find((int)$data['account_type_id']);
-
- if (null !== $type && in_array($type->type, config('firefly.valid_liabilities'), true)) {
- $account->account_type_id = $type->id;
- }
- }
-
- // update virtual balance (could be set to zero if empty string).
- if (array_key_exists('virtual_balance', $data) && null !== $data['virtual_balance']) {
- $account->virtual_balance = '' === trim($data['virtual_balance']) ? '0' : $data['virtual_balance'];
- }
-
- $account->save();
-
- return $account;
- }
-
- private function isLiability(Account $account): bool
- {
- $type = $account->accountType->type;
-
- return in_array($type, [AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value], true);
- }
-
- private function getAccountType(string $type): AccountType
- {
- return AccountType::whereType(ucfirst($type))->first();
- }
-
public function updateAccountOrder(Account $account, array $data): Account
{
// skip if no order info
@@ -174,7 +123,7 @@ class AccountUpdateService
return $account;
}
// skip if not of orderable type.
- $type = $account->accountType->type;
+ $type = $account->accountType->type;
if (!in_array(
$type,
[AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value],
@@ -185,10 +134,10 @@ class AccountUpdateService
return $account;
}
// get account type ID's because a join and an update is hard:
- $oldOrder = $account->order;
- $newOrder = $data['order'];
+ $oldOrder = $account->order;
+ $newOrder = $data['order'];
Log::debug(sprintf('Order is set to be updated from %s to %s', $oldOrder, $newOrder));
- $list = $this->getTypeIds([AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value]);
+ $list = $this->getTypeIds([AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value]);
if (AccountTypeEnum::ASSET->value === $type) {
$list = $this->getTypeIds([AccountTypeEnum::ASSET->value]);
}
@@ -200,7 +149,8 @@ class AccountUpdateService
->where('accounts.order', '>', $oldOrder)
->where('accounts.id', '!=', $account->id)
->whereIn('accounts.account_type_id', $list)
- ->decrement('order');
+ ->decrement('order')
+ ;
$account->order = $newOrder;
Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder));
$account->save();
@@ -214,7 +164,8 @@ class AccountUpdateService
->where('accounts.order', '<', $oldOrder)
->where('accounts.id', '!=', $account->id)
->whereIn('accounts.account_type_id', $list)
- ->increment('order');
+ ->increment('order')
+ ;
$account->order = $newOrder;
Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder));
$account->save();
@@ -222,6 +173,11 @@ class AccountUpdateService
return $account;
}
+ private function getAccountType(string $type): AccountType
+ {
+ return AccountType::whereType(ucfirst($type))->first();
+ }
+
private function getTypeIds(array $array): array
{
$return = [];
@@ -236,6 +192,52 @@ class AccountUpdateService
return $return;
}
+ private function isLiability(Account $account): bool
+ {
+ $type = $account->accountType->type;
+
+ return in_array($type, [AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value], true);
+ }
+
+ private function updateAccount(Account $account, array $data): Account
+ {
+ // update the account itself:
+ if (array_key_exists('name', $data)) {
+ $account->name = $data['name'];
+ }
+ if (array_key_exists('active', $data)) {
+ $account->active = $data['active'];
+ }
+ if (array_key_exists('iban', $data)) {
+ $account->iban = Steam::filterSpaces((string) $data['iban']);
+ }
+
+ // set liability, but account must already be a liability.
+ // $liabilityType = $data['liability_type'] ?? '';
+ if ($this->isLiability($account) && array_key_exists('liability_type', $data)) {
+ $type = $this->getAccountType($data['liability_type']);
+ $account->account_type_id = $type->id;
+ }
+ // set liability, alternative method used in v1 layout:
+
+ if ($this->isLiability($account) && array_key_exists('account_type_id', $data)) {
+ $type = AccountType::find((int) $data['account_type_id']);
+
+ if (null !== $type && in_array($type->type, config('firefly.valid_liabilities'), true)) {
+ $account->account_type_id = $type->id;
+ }
+ }
+
+ // update virtual balance (could be set to zero if empty string).
+ if (array_key_exists('virtual_balance', $data) && null !== $data['virtual_balance']) {
+ $account->virtual_balance = '' === trim($data['virtual_balance']) ? '0' : $data['virtual_balance'];
+ }
+
+ $account->save();
+
+ return $account;
+ }
+
private function updateLocation(Account $account, array $data): void
{
$updateLocation = $data['update_location'] ?? false;
@@ -248,7 +250,7 @@ class AccountUpdateService
// otherwise, update or create.
if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) {
- $location = $this->accountRepository->getLocation($account);
+ $location = $this->accountRepository->getLocation($account);
if (!$location instanceof Location) {
$location = new Location();
$location->locatable()->associate($account);
@@ -299,11 +301,11 @@ class AccountUpdateService
if (true === $account->active) {
return;
}
- $preference = Preferences::getForUser($account->user, 'frontpageAccounts');
+ $preference = Preferences::getForUser($account->user, 'frontpageAccounts');
if (null === $preference) {
return;
}
- $array = $preference->data;
+ $array = $preference->data;
if (!is_array($array)) {
$array = [$array];
}
@@ -312,9 +314,9 @@ class AccountUpdateService
$removeAccountId = $account->id;
$new = [];
foreach ($array as $value) {
- if ((int)$value !== $removeAccountId) {
+ if ((int) $value !== $removeAccountId) {
Log::debug(sprintf('Will include: %d', $value));
- $new[] = (int)$value;
+ $new[] = (int) $value;
}
}
Log::debug('Final new array is', $new);
diff --git a/app/Services/Internal/Update/BillUpdateService.php b/app/Services/Internal/Update/BillUpdateService.php
index 97c2e5f803..1052470112 100644
--- a/app/Services/Internal/Update/BillUpdateService.php
+++ b/app/Services/Internal/Update/BillUpdateService.php
@@ -131,6 +131,12 @@ class BillUpdateService
return $bill;
}
+ private function getRuleTrigger(Rule $rule, string $key): ?RuleTrigger
+ {
+ /** @var null|RuleTrigger */
+ return $rule->ruleTriggers()->where('trigger_type', $key)->first();
+ }
+
/**
* @SuppressWarnings("PHPMD.NPathComplexity")
*/
@@ -175,32 +181,6 @@ class BillUpdateService
return $bill;
}
- private function updateOrder(Bill $bill, int $oldOrder, int $newOrder): void
- {
- if ($newOrder > $oldOrder) {
- $this->user
- ->bills()
- ->where('order', '<=', $newOrder)
- ->where('order', '>', $oldOrder)
- ->where('bills.id', '!=', $bill->id)
- ->decrement('bills.order')
- ;
- $bill->order = $newOrder;
- $bill->save();
- }
- if ($newOrder < $oldOrder) {
- $this->user
- ->bills()
- ->where('order', '>=', $newOrder)
- ->where('order', '<', $oldOrder)
- ->where('bills.id', '!=', $bill->id)
- ->increment('bills.order')
- ;
- $bill->order = $newOrder;
- $bill->save();
- }
- }
-
private function updateBillTriggers(Bill $bill, array $oldData, array $newData): void
{
Log::debug(sprintf('Now in updateBillTriggers(%d, "%s")', $bill->id, $bill->name));
@@ -234,6 +214,32 @@ class BillUpdateService
}
}
+ private function updateOrder(Bill $bill, int $oldOrder, int $newOrder): void
+ {
+ if ($newOrder > $oldOrder) {
+ $this->user
+ ->bills()
+ ->where('order', '<=', $newOrder)
+ ->where('order', '>', $oldOrder)
+ ->where('bills.id', '!=', $bill->id)
+ ->decrement('bills.order')
+ ;
+ $bill->order = $newOrder;
+ $bill->save();
+ }
+ if ($newOrder < $oldOrder) {
+ $this->user
+ ->bills()
+ ->where('order', '>=', $newOrder)
+ ->where('order', '<', $oldOrder)
+ ->where('bills.id', '!=', $bill->id)
+ ->increment('bills.order')
+ ;
+ $bill->order = $newOrder;
+ $bill->save();
+ }
+ }
+
private function updateRules(Collection $rules, string $key, string $oldValue, string $newValue): void
{
/** @var Rule $rule */
@@ -258,10 +264,4 @@ class BillUpdateService
}
}
}
-
- private function getRuleTrigger(Rule $rule, string $key): ?RuleTrigger
- {
- /** @var null|RuleTrigger */
- return $rule->ruleTriggers()->where('trigger_type', $key)->first();
- }
}
diff --git a/app/Services/Internal/Update/CategoryUpdateService.php b/app/Services/Internal/Update/CategoryUpdateService.php
index 1711f164f1..7deaadc1be 100644
--- a/app/Services/Internal/Update/CategoryUpdateService.php
+++ b/app/Services/Internal/Update/CategoryUpdateService.php
@@ -80,23 +80,39 @@ class CategoryUpdateService
return $category;
}
- private function updateRuleTriggers(string $oldName, string $newName): void
+ /**
+ * @throws Exception
+ */
+ private function updateNotes(Category $category, array $data): void
{
- $types = ['category_is'];
- $triggers = RuleTrigger::leftJoin('rules', 'rules.id', '=', 'rule_triggers.rule_id')
- ->where('rules.user_id', $this->user->id)
- ->whereIn('rule_triggers.trigger_type', $types)
- ->where('rule_triggers.trigger_value', $oldName)
- ->get(['rule_triggers.*'])
- ;
- Log::debug(sprintf('Found %d triggers to update.', $triggers->count()));
+ $note = $data['notes'] ?? null;
+ if (null === $note) {
+ return;
+ }
+ if ('' === $note) {
+ $dbNote = $category->notes()->first();
+ $dbNote?->delete();
- /** @var RuleTrigger $trigger */
- foreach ($triggers as $trigger) {
- $trigger->trigger_value = $newName;
- $trigger->save();
- Log::debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value));
+ return;
}
+ $dbNote = $category->notes()->first();
+ if (null === $dbNote) {
+ $dbNote = new Note();
+ $dbNote->noteable()->associate($category);
+ }
+ $dbNote->text = trim((string) $note);
+ $dbNote->save();
+ }
+
+ private function updateRecurrences(string $oldName, string $newName): void
+ {
+ RecurrenceTransactionMeta::leftJoin('recurrences_transactions', 'rt_meta.rt_id', '=', 'recurrences_transactions.id')
+ ->leftJoin('recurrences', 'recurrences.id', '=', 'recurrences_transactions.recurrence_id')
+ ->where('recurrences.user_id', $this->user->id)
+ ->where('rt_meta.name', 'category_name')
+ ->where('rt_meta.value', $oldName)
+ ->update(['rt_meta.value' => $newName])
+ ;
}
private function updateRuleActions(string $oldName, string $newName): void
@@ -118,38 +134,22 @@ class CategoryUpdateService
}
}
- private function updateRecurrences(string $oldName, string $newName): void
+ private function updateRuleTriggers(string $oldName, string $newName): void
{
- RecurrenceTransactionMeta::leftJoin('recurrences_transactions', 'rt_meta.rt_id', '=', 'recurrences_transactions.id')
- ->leftJoin('recurrences', 'recurrences.id', '=', 'recurrences_transactions.recurrence_id')
- ->where('recurrences.user_id', $this->user->id)
- ->where('rt_meta.name', 'category_name')
- ->where('rt_meta.value', $oldName)
- ->update(['rt_meta.value' => $newName])
+ $types = ['category_is'];
+ $triggers = RuleTrigger::leftJoin('rules', 'rules.id', '=', 'rule_triggers.rule_id')
+ ->where('rules.user_id', $this->user->id)
+ ->whereIn('rule_triggers.trigger_type', $types)
+ ->where('rule_triggers.trigger_value', $oldName)
+ ->get(['rule_triggers.*'])
;
- }
-
- /**
- * @throws Exception
- */
- private function updateNotes(Category $category, array $data): void
- {
- $note = $data['notes'] ?? null;
- if (null === $note) {
- return;
- }
- if ('' === $note) {
- $dbNote = $category->notes()->first();
- $dbNote?->delete();
+ Log::debug(sprintf('Found %d triggers to update.', $triggers->count()));
- return;
- }
- $dbNote = $category->notes()->first();
- if (null === $dbNote) {
- $dbNote = new Note();
- $dbNote->noteable()->associate($category);
+ /** @var RuleTrigger $trigger */
+ foreach ($triggers as $trigger) {
+ $trigger->trigger_value = $newName;
+ $trigger->save();
+ Log::debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value));
}
- $dbNote->text = trim((string) $note);
- $dbNote->save();
}
}
diff --git a/app/Services/Internal/Update/GroupCloneService.php b/app/Services/Internal/Update/GroupCloneService.php
index 2555dbf01f..da02258fc0 100644
--- a/app/Services/Internal/Update/GroupCloneService.php
+++ b/app/Services/Internal/Update/GroupCloneService.php
@@ -119,12 +119,13 @@ class GroupCloneService
}
}
- private function cloneTransaction(Transaction $transaction, TransactionJournal $newJournal): void
+ private function cloneMeta(TransactionJournalMeta $meta, TransactionJournal $newJournal): void
{
- $newTransaction = $transaction->replicate();
- $newTransaction->transaction_journal_id = $newJournal->id;
- $newTransaction->reconciled = false;
- $newTransaction->save();
+ $newMeta = $meta->replicate();
+ $newMeta->transaction_journal_id = $newJournal->id;
+ if ('recurrence_id' !== $newMeta->name) {
+ $newMeta->save();
+ }
}
private function cloneNote(Note $note, TransactionJournal $newJournal, int $oldGroupId): void
@@ -138,12 +139,11 @@ class GroupCloneService
$newNote->save();
}
- private function cloneMeta(TransactionJournalMeta $meta, TransactionJournal $newJournal): void
+ private function cloneTransaction(Transaction $transaction, TransactionJournal $newJournal): void
{
- $newMeta = $meta->replicate();
- $newMeta->transaction_journal_id = $newJournal->id;
- if ('recurrence_id' !== $newMeta->name) {
- $newMeta->save();
- }
+ $newTransaction = $transaction->replicate();
+ $newTransaction->transaction_journal_id = $newJournal->id;
+ $newTransaction->reconciled = false;
+ $newTransaction->save();
}
}
diff --git a/app/Services/Internal/Update/GroupUpdateService.php b/app/Services/Internal/Update/GroupUpdateService.php
index fcc3fa298f..9213637dac 100644
--- a/app/Services/Internal/Update/GroupUpdateService.php
+++ b/app/Services/Internal/Update/GroupUpdateService.php
@@ -114,6 +114,36 @@ class GroupUpdateService
return $transactionGroup;
}
+ /**
+ * @throws DuplicateTransactionException
+ * @throws FireflyException
+ */
+ private function createTransactionJournal(TransactionGroup $transactionGroup, array $data): ?TransactionJournal
+ {
+ $submission = ['transactions' => [$data]];
+
+ /** @var TransactionJournalFactory $factory */
+ $factory = app(TransactionJournalFactory::class);
+ $factory->setUser($transactionGroup->user);
+
+ try {
+ $collection = $factory->create($submission);
+ } catch (FireflyException $e) {
+ Log::error($e->getMessage());
+ Log::error($e->getTraceAsString());
+
+ throw new FireflyException(sprintf('Could not create new transaction journal: %s', $e->getMessage()), 0, $e);
+ }
+ $collection->each(static function (TransactionJournal $journal) use ($transactionGroup): void {
+ $transactionGroup->transactionJournals()->save($journal);
+ });
+ if (0 === $collection->count()) {
+ return null;
+ }
+
+ return $collection->first();
+ }
+
/**
* Update single journal.
*/
@@ -189,34 +219,4 @@ class GroupUpdateService
return $updated;
}
-
- /**
- * @throws DuplicateTransactionException
- * @throws FireflyException
- */
- private function createTransactionJournal(TransactionGroup $transactionGroup, array $data): ?TransactionJournal
- {
- $submission = ['transactions' => [$data]];
-
- /** @var TransactionJournalFactory $factory */
- $factory = app(TransactionJournalFactory::class);
- $factory->setUser($transactionGroup->user);
-
- try {
- $collection = $factory->create($submission);
- } catch (FireflyException $e) {
- Log::error($e->getMessage());
- Log::error($e->getTraceAsString());
-
- throw new FireflyException(sprintf('Could not create new transaction journal: %s', $e->getMessage()), 0, $e);
- }
- $collection->each(static function (TransactionJournal $journal) use ($transactionGroup): void {
- $transactionGroup->transactionJournals()->save($journal);
- });
- if (0 === $collection->count()) {
- return null;
- }
-
- return $collection->first();
- }
}
diff --git a/app/Services/Internal/Update/JournalUpdateService.php b/app/Services/Internal/Update/JournalUpdateService.php
index c1c722b618..d53fc889cf 100644
--- a/app/Services/Internal/Update/JournalUpdateService.php
+++ b/app/Services/Internal/Update/JournalUpdateService.php
@@ -111,6 +111,22 @@ class JournalUpdateService
$this->transactionGroupRepository = app(TransactionGroupRepositoryInterface::class);
}
+ public function isCompareHashChanged(): bool
+ {
+ Log::debug(sprintf('Now in %s', __METHOD__));
+ $compareHash = hash('sha256', sprintf('%s', Carbon::now()->getTimestamp()));
+ if (!$this->transactionGroup instanceof TransactionGroup) {
+ $compareHash = $this->transactionGroupRepository->getCompareHash($this->transactionJournal->transactionGroup);
+ }
+ if ($this->transactionGroup instanceof TransactionGroup) {
+ $this->transactionGroupRepository->getCompareHash($this->transactionGroup);
+ }
+ Log::debug(sprintf('Compare hash is "%s".', $compareHash));
+ Log::debug(sprintf('Start compare hash is "%s".', $this->startCompareHash));
+
+ return $compareHash !== $this->startCompareHash;
+ }
+
public function setData(array $data): void
{
$this->data = $data;
@@ -180,47 +196,49 @@ class JournalUpdateService
Log::debug('Done with update journal routine');
}
- private function hasValidAccounts(): bool
+ /**
+ * Get destination transaction.
+ */
+ private function getDestinationTransaction(): Transaction
{
- Log::debug('Now in hasValidAccounts().');
+ if (!$this->destinationTransaction instanceof Transaction) {
+ /** @var null|Transaction $result */
+ $result = $this->transactionJournal
+ ->transactions()
+ ->where('amount', '>', 0)
+ ->first()
+ ;
+ $this->destinationTransaction = $result;
+ }
- return $this->hasValidSourceAccount() && $this->hasValidDestinationAccount();
+ return $this->destinationTransaction;
}
- private function hasValidSourceAccount(): bool
+ /**
+ * This method returns the current or expected type of the journal (in case of a change) based on the data in the
+ * array.
+ *
+ * If the array contains key 'type' and the value is correct, this is returned. Otherwise, the original type is
+ * returned.
+ */
+ private function getExpectedType(): string
{
- $sourceId = $this->data['source_id'] ?? null;
- $sourceName = $this->data['source_name'] ?? null;
- Log::debug(sprintf('Now in hasValidSourceAccount("%s","%s").', $sourceId, $sourceName));
-
- if (!$this->hasFields(['source_id', 'source_name'])) {
- $origSourceAccount = $this->getOriginalSourceAccount();
- $sourceId = $origSourceAccount->id;
- $sourceName = $origSourceAccount->name;
+ Log::debug('Now in getExpectedType()');
+ if ($this->hasFields(['type'])) {
+ return ucfirst('opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type']);
}
- // make new account validator.
- $expectedType = $this->getExpectedType();
- Log::debug(sprintf('(a) Expected type (new or unchanged) is %s', $expectedType));
-
- // make a new validator.
- /** @var AccountValidator $validator */
- $validator = app(AccountValidator::class);
- $validator->setTransactionType($expectedType);
- $validator->setUser($this->transactionJournal->user);
-
- $result = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]);
- Log::debug(sprintf('hasValidSourceAccount(%d, "%s") will return %s', $sourceId, $sourceName, var_export($result, true)));
-
- // TODO type overrule the account validator may have a different opinion on the transaction type.
-
- // validate submitted info:
- return $result;
+ return $this->transactionJournal->transactionType->type;
}
- private function hasFields(array $fields): bool
+ private function getOriginalDestinationAccount(): Account
{
- return array_any($fields, fn ($field): bool => array_key_exists($field, $this->data));
+ if (!$this->destinationAccount instanceof Account) {
+ $destination = $this->getDestinationTransaction();
+ $this->destinationAccount = $destination->account;
+ }
+
+ return $this->destinationAccount;
}
private function getOriginalSourceAccount(): Account
@@ -251,80 +269,36 @@ class JournalUpdateService
}
/**
- * This method returns the current or expected type of the journal (in case of a change) based on the data in the
- * array.
- *
- * If the array contains key 'type' and the value is correct, this is returned. Otherwise, the original type is
- * returned.
+ * Does a validation and returns the destination account. This method will break if the dest isn't really valid.
*/
- private function getExpectedType(): string
- {
- Log::debug('Now in getExpectedType()');
- if ($this->hasFields(['type'])) {
- return ucfirst('opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type']);
- }
-
- return $this->transactionJournal->transactionType->type;
- }
-
- private function hasValidDestinationAccount(): bool
+ private function getValidDestinationAccount(): Account
{
- Log::debug('Now in hasValidDestinationAccount().');
- $destId = $this->data['destination_id'] ?? null;
- $destName = $this->data['destination_name'] ?? null;
+ Log::debug('Now in getValidDestinationAccount().');
if (!$this->hasFields(['destination_id', 'destination_name'])) {
- Log::debug('No destination info submitted, grab the original data.');
- $destination = $this->getOriginalDestinationAccount();
- $destId = $destination->id;
- $destName = $destination->name;
+ return $this->getOriginalDestinationAccount();
}
- // make new account validator.
- $expectedType = $this->getExpectedType();
- Log::debug(sprintf('(b) Expected type (new or unchanged) is %s', $expectedType));
-
- // make a new validator.
- /** @var AccountValidator $validator */
- $validator = app(AccountValidator::class);
- $validator->setTransactionType($expectedType);
- $validator->setUser($this->transactionJournal->user);
- $validator->source = $this->getValidSourceAccount();
- $result = $validator->validateDestination(['id' => $destId, 'name' => $destName]);
- Log::debug(sprintf('hasValidDestinationAccount(%d, "%s") will return %s', $destId, $destName, var_export($result, true)));
-
- // TODO typeOverrule: the account validator may have another opinion on the transaction type.
-
- // validate submitted info:
- return $result;
- }
-
- private function getOriginalDestinationAccount(): Account
- {
- if (!$this->destinationAccount instanceof Account) {
- $destination = $this->getDestinationTransaction();
- $this->destinationAccount = $destination->account;
- }
+ $destInfo = [
+ 'id' => (int) ($this->data['destination_id'] ?? null),
+ 'name' => $this->data['destination_name'] ?? null,
+ 'iban' => $this->data['destination_iban'] ?? null,
+ 'number' => $this->data['destination_number'] ?? null,
+ 'bic' => $this->data['destination_bic'] ?? null,
+ ];
- return $this->destinationAccount;
- }
+ // make new account validator.
+ $expectedType = $this->getExpectedType();
+ Log::debug(sprintf('(c) Expected type (new or unchanged) is %s', $expectedType));
- /**
- * Get destination transaction.
- */
- private function getDestinationTransaction(): Transaction
- {
- if (!$this->destinationTransaction instanceof Transaction) {
- /** @var null|Transaction $result */
- $result = $this->transactionJournal
- ->transactions()
- ->where('amount', '>', 0)
- ->first()
- ;
- $this->destinationTransaction = $result;
+ try {
+ $result = $this->getAccount($expectedType, 'destination', $destInfo);
+ } catch (FireflyException $e) {
+ Log::error(sprintf('getValidDestinationAccount() threw unexpected error: %s', $e->getMessage()));
+ $result = $this->getOriginalDestinationAccount();
}
- return $this->destinationTransaction;
+ return $result;
}
/**
@@ -361,295 +335,161 @@ class JournalUpdateService
return $result;
}
- /**
- * Will update the source and destination accounts of this journal. Assumes they are valid.
- */
- private function updateAccounts(): void
+ private function hasFields(array $fields): bool
{
- $source = $this->getValidSourceAccount();
- $destination = $this->getValidDestinationAccount();
-
- // cowardly refuse to update if both accounts are the same.
- if ($source->id === $destination->id) {
- Log::error(sprintf('Source + dest accounts are equal (%d, "%s")', $source->id, $source->name));
-
- return;
- }
-
- $origSourceTransaction = $this->getSourceTransaction();
- $origSourceTransaction->account()->associate($source);
- $origSourceTransaction->save();
+ return array_any($fields, fn ($field): bool => array_key_exists($field, $this->data));
+ }
- $destTransaction = $this->getDestinationTransaction();
- $destTransaction->account()->associate($destination);
- $destTransaction->save();
+ private function hasValidAccounts(): bool
+ {
+ Log::debug('Now in hasValidAccounts().');
- // refresh transactions.
- $this->sourceTransaction->refresh();
- $this->destinationTransaction->refresh();
- Log::debug(sprintf('Will set source to #%d ("%s")', $source->id, $source->name));
- Log::debug(sprintf('Will set dest to #%d ("%s")', $destination->id, $destination->name));
+ return $this->hasValidSourceAccount() && $this->hasValidDestinationAccount();
}
- /**
- * Does a validation and returns the destination account. This method will break if the dest isn't really valid.
- */
- private function getValidDestinationAccount(): Account
+ private function hasValidDestinationAccount(): bool
{
- Log::debug('Now in getValidDestinationAccount().');
+ Log::debug('Now in hasValidDestinationAccount().');
+ $destId = $this->data['destination_id'] ?? null;
+ $destName = $this->data['destination_name'] ?? null;
if (!$this->hasFields(['destination_id', 'destination_name'])) {
- return $this->getOriginalDestinationAccount();
+ Log::debug('No destination info submitted, grab the original data.');
+ $destination = $this->getOriginalDestinationAccount();
+ $destId = $destination->id;
+ $destName = $destination->name;
}
- $destInfo = [
- 'id' => (int) ($this->data['destination_id'] ?? null),
- 'name' => $this->data['destination_name'] ?? null,
- 'iban' => $this->data['destination_iban'] ?? null,
- 'number' => $this->data['destination_number'] ?? null,
- 'bic' => $this->data['destination_bic'] ?? null,
- ];
-
// make new account validator.
- $expectedType = $this->getExpectedType();
- Log::debug(sprintf('(c) Expected type (new or unchanged) is %s', $expectedType));
+ $expectedType = $this->getExpectedType();
+ Log::debug(sprintf('(b) Expected type (new or unchanged) is %s', $expectedType));
- try {
- $result = $this->getAccount($expectedType, 'destination', $destInfo);
- } catch (FireflyException $e) {
- Log::error(sprintf('getValidDestinationAccount() threw unexpected error: %s', $e->getMessage()));
- $result = $this->getOriginalDestinationAccount();
- }
+ // make a new validator.
+ /** @var AccountValidator $validator */
+ $validator = app(AccountValidator::class);
+ $validator->setTransactionType($expectedType);
+ $validator->setUser($this->transactionJournal->user);
+ $validator->source = $this->getValidSourceAccount();
+ $result = $validator->validateDestination(['id' => $destId, 'name' => $destName]);
+ Log::debug(sprintf('hasValidDestinationAccount(%d, "%s") will return %s', $destId, $destName, var_export($result, true)));
+
+ // TODO typeOverrule: the account validator may have another opinion on the transaction type.
+ // validate submitted info:
return $result;
}
- /**
- * Updates journal transaction type.
- */
- private function updateType(): void
+ private function hasValidSourceAccount(): bool
{
- Log::debug('Now in updateType()');
- if ($this->hasFields(['type'])) {
- $type = 'opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type'];
- Log::debug(sprintf(
- 'Trying to change journal #%d from a %s to a %s.',
- $this->transactionJournal->id,
- $this->transactionJournal->transactionType->type,
- $type
- ));
-
- /** @var TransactionTypeFactory $typeFactory */
- $typeFactory = app(TransactionTypeFactory::class);
- $result = $typeFactory->find($this->data['type']);
- if (null !== $result) {
- Log::debug('Changed transaction type!');
- $this->transactionJournal->transaction_type_id = $result->id;
- $this->transactionJournal->save();
-
- return;
- }
-
- return;
- }
- Log::debug('No type field present.');
- }
+ $sourceId = $this->data['source_id'] ?? null;
+ $sourceName = $this->data['source_name'] ?? null;
+ Log::debug(sprintf('Now in hasValidSourceAccount("%s","%s").', $sourceId, $sourceName));
- /**
- * Update journal bill information.
- */
- private function updateBill(): void
- {
- $type = $this->transactionJournal->transactionType->type;
- if ((array_key_exists('bill_id', $this->data) || array_key_exists('bill_name', $this->data)) && TransactionTypeEnum::WITHDRAWAL->value === $type) {
- $billId = (int) ($this->data['bill_id'] ?? 0);
- $billName = (string) ($this->data['bill_name'] ?? '');
- $bill = $this->billRepository->findBill($billId, $billName);
- $this->transactionJournal->bill_id = $bill?->id;
- Log::debug('Updated bill ID');
+ if (!$this->hasFields(['source_id', 'source_name'])) {
+ $origSourceAccount = $this->getOriginalSourceAccount();
+ $sourceId = $origSourceAccount->id;
+ $sourceName = $origSourceAccount->name;
}
- }
-
- /**
- * Update journal generic field. Cannot be set to NULL.
- */
- private function updateField(string $fieldName): void
- {
- if (array_key_exists($fieldName, $this->data) && '' !== (string) $this->data[$fieldName]) {
- $value = $this->data[$fieldName];
- if ('date' === $fieldName) {
- if (!$value instanceof Carbon) {
- $value = new Carbon($value);
- }
+ // make new account validator.
+ $expectedType = $this->getExpectedType();
+ Log::debug(sprintf('(a) Expected type (new or unchanged) is %s', $expectedType));
- $value->setTimezone(config('app.timezone'));
- // 2024-11-22, overrule timezone with UTC and store it as UTC.
- if (true === FireflyConfig::get('utc', false)->data) {
- $value->setTimezone('UTC');
- }
+ // make a new validator.
+ /** @var AccountValidator $validator */
+ $validator = app(AccountValidator::class);
+ $validator->setTransactionType($expectedType);
+ $validator->setUser($this->transactionJournal->user);
- // do some parsing.
- Log::debug(sprintf('Create date value from string "%s".', $value));
- $this->transactionJournal->date_tz = $value->format('e');
- $res = $value->gt($this->transactionJournal->date);
- Log::debug(sprintf('Old date: %s, new date: %s', $this->transactionJournal->date->toW3cString(), $value->toW3cString()));
+ $result = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]);
+ Log::debug(sprintf('hasValidSourceAccount(%d, "%s") will return %s', $sourceId, $sourceName, var_export($result, true)));
- /** @var TransactionJournalMetaFactory $factory */
- $factory = app(TransactionJournalMetaFactory::class);
- $set = ['journal' => $this->transactionJournal, 'name' => '_internal_previous_date', 'data' => null];
- if ($res) {
- Log::debug('Transaction is set to be AFTER its current date. Save also the "_internal_previous_date"-field.');
- $set['data'] = clone $this->transactionJournal->date;
- }
- if (!$res) {
- Log::debug('Transaction is NOT set to be AFTER its current date. Remove the "_internal_previous_date"-field.');
- }
- $factory->updateOrCreate($set);
- }
- event(
- new TransactionGroupRequestsAuditLogEntry(
- $this->transactionJournal->user,
- $this->transactionJournal,
- sprintf('update_%s', $fieldName),
- $this->transactionJournal->{$fieldName},
- $value
- )
- );
+ // TODO type overrule the account validator may have a different opinion on the transaction type.
- $this->transactionJournal->{$fieldName} = $value; // @phpstan-ignore-line
- Log::debug(sprintf('Updated %s', $fieldName));
- }
+ // validate submitted info:
+ return $result;
}
- private function updateCategory(): void
+ private function isBetweenAssetAndLiability(): bool
{
- // update category
- if ($this->hasFields(['category_id', 'category_name'])) {
- Log::debug('Will update category.');
+ /** @var null|Transaction $sourceTransaction */
+ $sourceTransaction = $this->transactionJournal
+ ->transactions()
+ ->where('amount', '<', 0)
+ ->first()
+ ;
- $this->storeCategory($this->transactionJournal, new NullArrayObject($this->data));
- }
- }
+ /** @var null|Transaction $destinationTransaction */
+ $destinationTransaction = $this->transactionJournal
+ ->transactions()
+ ->where('amount', '>', 0)
+ ->first()
+ ;
+ if (null === $sourceTransaction || null === $destinationTransaction) {
+ Log::warning('Either transaction is false, stop.');
- private function updateBudget(): void
- {
- // update budget
- if ($this->hasFields(['budget_id', 'budget_name'])) {
- Log::debug('Will update budget.');
- $this->storeBudget($this->transactionJournal, new NullArrayObject($this->data));
- }
- // is transfer? remove budget
- if (TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type) {
- $this->transactionJournal->budgets()->sync([]);
+ return false;
}
- }
+ if (null === $sourceTransaction->foreign_amount || null === $destinationTransaction->foreign_amount) {
+ Log::warning('Either foreign amount is false, stop.');
- private function updateTags(): void
- {
- if ($this->hasFields(['tags'])) {
- Log::debug('Will update tags.');
- $tags = $this->data['tags'] ?? null;
- $this->storeTags($this->transactionJournal, $tags);
+ return false;
}
- }
- private function updateReconciled(): void
- {
- if (array_key_exists('reconciled', $this->data) && is_bool($this->data['reconciled'])) {
- $this->transactionJournal->transactions()->update(['reconciled' => $this->data['reconciled']]);
- }
- }
+ $source = $sourceTransaction->account;
+ $destination = $destinationTransaction->account;
- private function updateNotes(): void
- {
- // update notes.
- if ($this->hasFields(['notes'])) {
- $notes = '' === (string) $this->data['notes'] ? null : $this->data['notes'];
- $this->storeNotes($this->transactionJournal, $notes);
- }
- }
+ if (null === $source || null === $destination) {
+ Log::warning('Either is false, stop.');
- private function updateMeta(): void
- {
- // update meta fields.
- // first string
- if ($this->hasFields($this->metaString)) {
- Log::debug('Meta string fields are present.');
- $this->updateMetaFields();
+ return false;
}
+ $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
- // then date fields.
- if ($this->hasFields($this->metaDate)) {
- Log::debug('Meta date fields are present.');
- $this->updateMetaDateFields();
- }
- }
+ // source is liability, destination is asset
+ if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) {
+ Log::debug('Source is a liability account, destination is an asset account, return TRUE.');
- private function updateMetaFields(): void
- {
- /** @var TransactionJournalMetaFactory $factory */
- $factory = app(TransactionJournalMetaFactory::class);
+ return true;
+ }
+ // source is asset, destination is liability
+ if (in_array($destination->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $source->accountType->type) {
+ Log::debug('Destination is a liability account, source is an asset account, return TRUE.');
- foreach ($this->metaString as $field) {
- if ($this->hasFields([$field])) {
- $value = '' === $this->data[$field] ? null : $this->data[$field];
- Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value));
- $set = ['journal' => $this->transactionJournal, 'name' => $field, 'data' => $value];
- $factory->updateOrCreate($set);
- }
+ return true;
}
+
+ return false;
}
- private function updateMetaDateFields(): void
+ /**
+ * Will update the source and destination accounts of this journal. Assumes they are valid.
+ */
+ private function updateAccounts(): void
{
- /** @var TransactionJournalMetaFactory $factory */
- $factory = app(TransactionJournalMetaFactory::class);
-
- foreach ($this->metaDate as $field) {
- if ($this->hasFields([$field])) {
- try {
- $value = '' === (string) $this->data[$field] ? null : new Carbon($this->data[$field]);
- } catch (InvalidDateException|InvalidFormatException $e) { // @phpstan-ignore-line
- Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage()));
+ $source = $this->getValidSourceAccount();
+ $destination = $this->getValidDestinationAccount();
- return;
- }
- Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value));
- $set = ['journal' => $this->transactionJournal, 'name' => $field, 'data' => $value];
- $factory->updateOrCreate($set);
- // also set date with timezone.
- $set = ['journal' => $this->transactionJournal, 'name' => sprintf('%s_tz', $field), 'data' => $value?->format('e')];
- $factory->updateOrCreate($set);
- }
- }
- }
+ // cowardly refuse to update if both accounts are the same.
+ if ($source->id === $destination->id) {
+ Log::error(sprintf('Source + dest accounts are equal (%d, "%s")', $source->id, $source->name));
- private function updateCurrency(): void
- {
- // update transactions.
- if (!$this->hasFields(['currency_id', 'currency_code'])) {
return;
}
- $currencyId = $this->data['currency_id'] ?? null;
- $currencyCode = $this->data['currency_code'] ?? null;
- $currency = $this->currencyRepository->findCurrency($currencyId, $currencyCode);
- // update currency everywhere.
- $this->transactionJournal->transaction_currency_id = $currency->id;
- $this->transactionJournal->save();
- $source = $this->getSourceTransaction();
- $source->transaction_currency_id = $currency->id;
- $source->save();
+ $origSourceTransaction = $this->getSourceTransaction();
+ $origSourceTransaction->account()->associate($source);
+ $origSourceTransaction->save();
- $dest = $this->getDestinationTransaction();
- $dest->transaction_currency_id = $currency->id;
- $dest->save();
+ $destTransaction = $this->getDestinationTransaction();
+ $destTransaction->account()->associate($destination);
+ $destTransaction->save();
// refresh transactions.
$this->sourceTransaction->refresh();
$this->destinationTransaction->refresh();
- Log::debug(sprintf('Updated currency to #%d (%s)', $currency->id, $currency->code));
+ Log::debug(sprintf('Will set source to #%d ("%s")', $source->id, $source->name));
+ Log::debug(sprintf('Will set dest to #%d ("%s")', $destination->id, $destination->name));
}
private function updateAmount(): void
@@ -723,6 +563,123 @@ class JournalUpdateService
);
}
+ /**
+ * Update journal bill information.
+ */
+ private function updateBill(): void
+ {
+ $type = $this->transactionJournal->transactionType->type;
+ if ((array_key_exists('bill_id', $this->data) || array_key_exists('bill_name', $this->data)) && TransactionTypeEnum::WITHDRAWAL->value === $type) {
+ $billId = (int) ($this->data['bill_id'] ?? 0);
+ $billName = (string) ($this->data['bill_name'] ?? '');
+ $bill = $this->billRepository->findBill($billId, $billName);
+ $this->transactionJournal->bill_id = $bill?->id;
+ Log::debug('Updated bill ID');
+ }
+ }
+
+ private function updateBudget(): void
+ {
+ // update budget
+ if ($this->hasFields(['budget_id', 'budget_name'])) {
+ Log::debug('Will update budget.');
+ $this->storeBudget($this->transactionJournal, new NullArrayObject($this->data));
+ }
+ // is transfer? remove budget
+ if (TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type) {
+ $this->transactionJournal->budgets()->sync([]);
+ }
+ }
+
+ private function updateCategory(): void
+ {
+ // update category
+ if ($this->hasFields(['category_id', 'category_name'])) {
+ Log::debug('Will update category.');
+
+ $this->storeCategory($this->transactionJournal, new NullArrayObject($this->data));
+ }
+ }
+
+ private function updateCurrency(): void
+ {
+ // update transactions.
+ if (!$this->hasFields(['currency_id', 'currency_code'])) {
+ return;
+ }
+ $currencyId = $this->data['currency_id'] ?? null;
+ $currencyCode = $this->data['currency_code'] ?? null;
+ $currency = $this->currencyRepository->findCurrency($currencyId, $currencyCode);
+ // update currency everywhere.
+ $this->transactionJournal->transaction_currency_id = $currency->id;
+ $this->transactionJournal->save();
+
+ $source = $this->getSourceTransaction();
+ $source->transaction_currency_id = $currency->id;
+ $source->save();
+
+ $dest = $this->getDestinationTransaction();
+ $dest->transaction_currency_id = $currency->id;
+ $dest->save();
+
+ // refresh transactions.
+ $this->sourceTransaction->refresh();
+ $this->destinationTransaction->refresh();
+ Log::debug(sprintf('Updated currency to #%d (%s)', $currency->id, $currency->code));
+ }
+
+ /**
+ * Update journal generic field. Cannot be set to NULL.
+ */
+ private function updateField(string $fieldName): void
+ {
+ if (array_key_exists($fieldName, $this->data) && '' !== (string) $this->data[$fieldName]) {
+ $value = $this->data[$fieldName];
+
+ if ('date' === $fieldName) {
+ if (!$value instanceof Carbon) {
+ $value = new Carbon($value);
+ }
+
+ $value->setTimezone(config('app.timezone'));
+ // 2024-11-22, overrule timezone with UTC and store it as UTC.
+ if (true === FireflyConfig::get('utc', false)->data) {
+ $value->setTimezone('UTC');
+ }
+
+ // do some parsing.
+ Log::debug(sprintf('Create date value from string "%s".', $value));
+ $this->transactionJournal->date_tz = $value->format('e');
+ $res = $value->gt($this->transactionJournal->date);
+ Log::debug(sprintf('Old date: %s, new date: %s', $this->transactionJournal->date->toW3cString(), $value->toW3cString()));
+
+ /** @var TransactionJournalMetaFactory $factory */
+ $factory = app(TransactionJournalMetaFactory::class);
+ $set = ['journal' => $this->transactionJournal, 'name' => '_internal_previous_date', 'data' => null];
+ if ($res) {
+ Log::debug('Transaction is set to be AFTER its current date. Save also the "_internal_previous_date"-field.');
+ $set['data'] = clone $this->transactionJournal->date;
+ }
+ if (!$res) {
+ Log::debug('Transaction is NOT set to be AFTER its current date. Remove the "_internal_previous_date"-field.');
+ }
+ $factory->updateOrCreate($set);
+ }
+ event(
+ new TransactionGroupRequestsAuditLogEntry(
+ $this->transactionJournal->user,
+ $this->transactionJournal,
+ sprintf('update_%s', $fieldName),
+ $this->transactionJournal->{$fieldName},
+ $value
+ )
+ );
+
+ $this->transactionJournal->{$fieldName} = $value; // @phpstan-ignore-line
+ Log::debug(sprintf('Updated %s', $fieldName));
+ }
+ }
+
private function updateForeignAmount(): void
{
// amount, foreign currency.
@@ -840,71 +797,114 @@ class JournalUpdateService
$this->destinationTransaction->refresh();
}
- private function isBetweenAssetAndLiability(): bool
+ private function updateMeta(): void
{
- /** @var null|Transaction $sourceTransaction */
- $sourceTransaction = $this->transactionJournal
- ->transactions()
- ->where('amount', '<', 0)
- ->first()
- ;
-
- /** @var null|Transaction $destinationTransaction */
- $destinationTransaction = $this->transactionJournal
- ->transactions()
- ->where('amount', '>', 0)
- ->first()
- ;
- if (null === $sourceTransaction || null === $destinationTransaction) {
- Log::warning('Either transaction is false, stop.');
-
- return false;
+ // update meta fields.
+ // first string
+ if ($this->hasFields($this->metaString)) {
+ Log::debug('Meta string fields are present.');
+ $this->updateMetaFields();
}
- if (null === $sourceTransaction->foreign_amount || null === $destinationTransaction->foreign_amount) {
- Log::warning('Either foreign amount is false, stop.');
- return false;
+ // then date fields.
+ if ($this->hasFields($this->metaDate)) {
+ Log::debug('Meta date fields are present.');
+ $this->updateMetaDateFields();
}
+ }
- $source = $sourceTransaction->account;
- $destination = $destinationTransaction->account;
+ private function updateMetaDateFields(): void
+ {
+ /** @var TransactionJournalMetaFactory $factory */
+ $factory = app(TransactionJournalMetaFactory::class);
- if (null === $source || null === $destination) {
- Log::warning('Either is false, stop.');
+ foreach ($this->metaDate as $field) {
+ if ($this->hasFields([$field])) {
+ try {
+ $value = '' === (string) $this->data[$field] ? null : new Carbon($this->data[$field]);
+ } catch (InvalidDateException|InvalidFormatException $e) { // @phpstan-ignore-line
+ Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage()));
- return false;
+ return;
+ }
+ Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value));
+ $set = ['journal' => $this->transactionJournal, 'name' => $field, 'data' => $value];
+ $factory->updateOrCreate($set);
+ // also set date with timezone.
+ $set = ['journal' => $this->transactionJournal, 'name' => sprintf('%s_tz', $field), 'data' => $value?->format('e')];
+ $factory->updateOrCreate($set);
+ }
}
- $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value];
+ }
- // source is liability, destination is asset
- if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) {
- Log::debug('Source is a liability account, destination is an asset account, return TRUE.');
+ private function updateMetaFields(): void
+ {
+ /** @var TransactionJournalMetaFactory $factory */
+ $factory = app(TransactionJournalMetaFactory::class);
- return true;
+ foreach ($this->metaString as $field) {
+ if ($this->hasFields([$field])) {
+ $value = '' === $this->data[$field] ? null : $this->data[$field];
+ Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value));
+ $set = ['journal' => $this->transactionJournal, 'name' => $field, 'data' => $value];
+ $factory->updateOrCreate($set);
+ }
}
- // source is asset, destination is liability
- if (in_array($destination->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $source->accountType->type) {
- Log::debug('Destination is a liability account, source is an asset account, return TRUE.');
+ }
- return true;
+ private function updateNotes(): void
+ {
+ // update notes.
+ if ($this->hasFields(['notes'])) {
+ $notes = '' === (string) $this->data['notes'] ? null : $this->data['notes'];
+ $this->storeNotes($this->transactionJournal, $notes);
}
-
- return false;
}
- public function isCompareHashChanged(): bool
+ private function updateReconciled(): void
{
- Log::debug(sprintf('Now in %s', __METHOD__));
- $compareHash = hash('sha256', sprintf('%s', Carbon::now()->getTimestamp()));
- if (!$this->transactionGroup instanceof TransactionGroup) {
- $compareHash = $this->transactionGroupRepository->getCompareHash($this->transactionJournal->transactionGroup);
+ if (array_key_exists('reconciled', $this->data) && is_bool($this->data['reconciled'])) {
+ $this->transactionJournal->transactions()->update(['reconciled' => $this->data['reconciled']]);
}
- if ($this->transactionGroup instanceof TransactionGroup) {
- $this->transactionGroupRepository->getCompareHash($this->transactionGroup);
+ }
+
+ private function updateTags(): void
+ {
+ if ($this->hasFields(['tags'])) {
+ Log::debug('Will update tags.');
+ $tags = $this->data['tags'] ?? null;
+ $this->storeTags($this->transactionJournal, $tags);
}
- Log::debug(sprintf('Compare hash is "%s".', $compareHash));
- Log::debug(sprintf('Start compare hash is "%s".', $this->startCompareHash));
+ }
- return $compareHash !== $this->startCompareHash;
+ /**
+ * Updates journal transaction type.
+ */
+ private function updateType(): void
+ {
+ Log::debug('Now in updateType()');
+ if ($this->hasFields(['type'])) {
+ $type = 'opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type'];
+ Log::debug(sprintf(
+ 'Trying to change journal #%d from a %s to a %s.',
+ $this->transactionJournal->id,
+ $this->transactionJournal->transactionType->type,
+ $type
+ ));
+
+ /** @var TransactionTypeFactory $typeFactory */
+ $typeFactory = app(TransactionTypeFactory::class);
+ $result = $typeFactory->find($this->data['type']);
+ if (null !== $result) {
+ Log::debug('Changed transaction type!');
+ $this->transactionJournal->transaction_type_id = $result->id;
+ $this->transactionJournal->save();
+
+ return;
+ }
+
+ return;
+ }
+ Log::debug('No type field present.');
}
}
diff --git a/app/Services/Internal/Update/RecurrenceUpdateService.php b/app/Services/Internal/Update/RecurrenceUpdateService.php
index 272a60dab8..a0c21bd335 100644
--- a/app/Services/Internal/Update/RecurrenceUpdateService.php
+++ b/app/Services/Internal/Update/RecurrenceUpdateService.php
@@ -108,55 +108,10 @@ class RecurrenceUpdateService
return $recurrence;
}
- private function setNoteText(Recurrence $recurrence, string $text): void
- {
- $dbNote = $recurrence->notes()->first();
- if ('' !== $text) {
- if (null === $dbNote) {
- $dbNote = new Note();
- $dbNote->noteable()->associate($recurrence);
- }
- $dbNote->text = trim($text);
- $dbNote->save();
-
- return;
- }
- $dbNote?->delete();
- }
-
- /**
- * @throws FireflyException
- */
- private function updateRepetitions(Recurrence $recurrence, array $repetitions): void
+ private function deleteTransaction(Recurrence $recurrence, int $transactionId): void
{
- $originalCount = $recurrence->recurrenceRepetitions()->count();
- if (0 === count($repetitions)) {
- // won't drop repetition, rather avoid.
- return;
- }
- // user added or removed repetitions, delete all and recreate:
- if ($originalCount !== count($repetitions)) {
- Log::debug('Delete existing repetitions and create new ones.');
- $this->deleteRepetitions($recurrence);
- $this->createRepetitions($recurrence, $repetitions);
-
- return;
- }
- // loop all and try to match them:
- Log::debug('Loop and find');
- foreach ($repetitions as $current) {
- $match = $this->matchRepetition($recurrence, $current);
- if (!$match instanceof RecurrenceRepetition) {
- throw new FireflyException('Cannot match recurring repetition to existing repetition. Not sure what to do. Break.');
- }
- $fields = ['type' => 'repetition_type', 'moment' => 'repetition_moment', 'skip' => 'repetition_skip', 'weekend' => 'weekend'];
- foreach ($fields as $field => $column) {
- if (array_key_exists($field, $current)) {
- $match->{$column} = $current[$field];
- $match->save();
- }
- }
- }
+ Log::debug(sprintf('Will delete transaction #%d in recurrence #%d.', $transactionId, $recurrence->id));
+ $recurrence->recurrenceTransactions()->where('id', $transactionId)->delete();
}
private function matchRepetition(Recurrence $recurrence, array $data): ?RecurrenceRepetition
@@ -181,54 +136,20 @@ class RecurrenceUpdateService
return $query->first();
}
- /**
- * TODO this method is very complex.
- *
- * @throws FireflyException
- */
- private function updateTransactions(Recurrence $recurrence, array $transactions): void
+ private function setNoteText(Recurrence $recurrence, string $text): void
{
- Log::debug('Now in updateTransactions()');
- $originalCount = $recurrence->recurrenceTransactions()->count();
- Log::debug(sprintf('Original count is %d', $originalCount));
- if (0 === count($transactions)) {
- // won't drop transactions, rather avoid.
- Log::warning('No transactions to update, too scared to continue!');
+ $dbNote = $recurrence->notes()->first();
+ if ('' !== $text) {
+ if (null === $dbNote) {
+ $dbNote = new Note();
+ $dbNote->noteable()->associate($recurrence);
+ }
+ $dbNote->text = trim($text);
+ $dbNote->save();
return;
}
- $combinations = [];
- $originalTransactions = $recurrence->recurrenceTransactions()->get()->toArray();
- // First, make sure to loop all existing transactions and match them to a counterpart in the submitted transactions array.
- foreach ($originalTransactions as $i => $originalTransaction) {
- foreach ($transactions as $ii => $submittedTransaction) {
- if (array_key_exists('id', $submittedTransaction) && (int) $originalTransaction['id'] === (int) $submittedTransaction['id']) {
- Log::debug(sprintf('Match original transaction #%d with an entry in the submitted array.', $originalTransaction['id']));
- $combinations[] = ['original' => $originalTransaction, 'submitted' => $submittedTransaction];
- unset($originalTransactions[$i], $transactions[$ii]);
- }
- }
- }
- // If one left of both we can match those as well and presto.
- if (1 === count($originalTransactions) && 1 === count($transactions)) {
- $first = array_shift($originalTransactions);
- Log::debug(sprintf('One left of each, link them (ID is #%d)', $first['id']));
- $combinations[] = ['original' => $first, 'submitted' => array_shift($transactions)];
- unset($first);
- }
- // if they are both empty, we can safely loop all combinations and update them.
- if (0 === count($originalTransactions) && 0 === count($transactions)) {
- foreach ($combinations as $combination) {
- $this->updateCombination($recurrence, $combination);
- }
- }
- // anything left in the original transactions array can be deleted.
- foreach ($originalTransactions as $original) {
- Log::debug(sprintf('Original transaction #%d is unmatched, delete it!', $original['id']));
- $this->deleteTransaction($recurrence, (int) $original['id']);
- }
- // anything left is new.
- $this->createTransactions($recurrence, $transactions);
+ $dbNote?->delete();
}
/**
@@ -319,9 +240,88 @@ class RecurrenceUpdateService
}
}
- private function deleteTransaction(Recurrence $recurrence, int $transactionId): void
+ /**
+ * @throws FireflyException
+ */
+ private function updateRepetitions(Recurrence $recurrence, array $repetitions): void
{
- Log::debug(sprintf('Will delete transaction #%d in recurrence #%d.', $transactionId, $recurrence->id));
- $recurrence->recurrenceTransactions()->where('id', $transactionId)->delete();
+ $originalCount = $recurrence->recurrenceRepetitions()->count();
+ if (0 === count($repetitions)) {
+ // won't drop repetition, rather avoid.
+ return;
+ }
+ // user added or removed repetitions, delete all and recreate:
+ if ($originalCount !== count($repetitions)) {
+ Log::debug('Delete existing repetitions and create new ones.');
+ $this->deleteRepetitions($recurrence);
+ $this->createRepetitions($recurrence, $repetitions);
+
+ return;
+ }
+ // loop all and try to match them:
+ Log::debug('Loop and find');
+ foreach ($repetitions as $current) {
+ $match = $this->matchRepetition($recurrence, $current);
+ if (!$match instanceof RecurrenceRepetition) {
+ throw new FireflyException('Cannot match recurring repetition to existing repetition. Not sure what to do. Break.');
+ }
+ $fields = ['type' => 'repetition_type', 'moment' => 'repetition_moment', 'skip' => 'repetition_skip', 'weekend' => 'weekend'];
+ foreach ($fields as $field => $column) {
+ if (array_key_exists($field, $current)) {
+ $match->{$column} = $current[$field];
+ $match->save();
+ }
+ }
+ }
+ }
+
+ /**
+ * TODO this method is very complex.
+ *
+ * @throws FireflyException
+ */
+ private function updateTransactions(Recurrence $recurrence, array $transactions): void
+ {
+ Log::debug('Now in updateTransactions()');
+ $originalCount = $recurrence->recurrenceTransactions()->count();
+ Log::debug(sprintf('Original count is %d', $originalCount));
+ if (0 === count($transactions)) {
+ // won't drop transactions, rather avoid.
+ Log::warning('No transactions to update, too scared to continue!');
+
+ return;
+ }
+ $combinations = [];
+ $originalTransactions = $recurrence->recurrenceTransactions()->get()->toArray();
+ // First, make sure to loop all existing transactions and match them to a counterpart in the submitted transactions array.
+ foreach ($originalTransactions as $i => $originalTransaction) {
+ foreach ($transactions as $ii => $submittedTransaction) {
+ if (array_key_exists('id', $submittedTransaction) && (int) $originalTransaction['id'] === (int) $submittedTransaction['id']) {
+ Log::debug(sprintf('Match original transaction #%d with an entry in the submitted array.', $originalTransaction['id']));
+ $combinations[] = ['original' => $originalTransaction, 'submitted' => $submittedTransaction];
+ unset($originalTransactions[$i], $transactions[$ii]);
+ }
+ }
+ }
+ // If one left of both we can match those as well and presto.
+ if (1 === count($originalTransactions) && 1 === count($transactions)) {
+ $first = array_shift($originalTransactions);
+ Log::debug(sprintf('One left of each, link them (ID is #%d)', $first['id']));
+ $combinations[] = ['original' => $first, 'submitted' => array_shift($transactions)];
+ unset($first);
+ }
+ // if they are both empty, we can safely loop all combinations and update them.
+ if (0 === count($originalTransactions) && 0 === count($transactions)) {
+ foreach ($combinations as $combination) {
+ $this->updateCombination($recurrence, $combination);
+ }
+ }
+ // anything left in the original transactions array can be deleted.
+ foreach ($originalTransactions as $original) {
+ Log::debug(sprintf('Original transaction #%d is unmatched, delete it!', $original['id']));
+ $this->deleteTransaction($recurrence, (int) $original['id']);
+ }
+ // anything left is new.
+ $this->createTransactions($recurrence, $transactions);
}
}
diff --git a/app/Support/Calendar/Calculator.php b/app/Support/Calendar/Calculator.php
index 02b4f7ce84..8f5ccb9ecf 100644
--- a/app/Support/Calendar/Calculator.php
+++ b/app/Support/Calendar/Calculator.php
@@ -36,28 +36,9 @@ class Calculator
public const int DEFAULT_INTERVAL = 1;
private static ?SplObjectStorage $intervalMap = null; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private static array $intervals = [];
- private function containsInterval(Periodicity $periodicity): bool
- {
- return $this->loadIntervalMap()->contains($periodicity);
- }
-
- private function loadIntervalMap(): SplObjectStorage
- {
- if (self::$intervalMap instanceof SplObjectStorage) {
- return self::$intervalMap;
- }
- self::$intervalMap = new SplObjectStorage();
- foreach (Periodicity::cases() as $interval) {
- $periodicityClass = sprintf('%s\Periodicity\%s', __NAMESPACE__, $interval->name);
- self::$intervals[] = $interval->name;
- self::$intervalMap->attach($interval, new $periodicityClass());
- }
-
- return self::$intervalMap;
- }
-
public function isAvailablePeriodicity(Periodicity $periodicity): bool
{
return $this->containsInterval($periodicity);
@@ -79,6 +60,26 @@ class Calculator
return $periodicity->nextDate($epoch->clone(), $interval);
}
+ private function containsInterval(Periodicity $periodicity): bool
+ {
+ return $this->loadIntervalMap()->contains($periodicity);
+ }
+
+ private function loadIntervalMap(): SplObjectStorage
+ {
+ if (self::$intervalMap instanceof SplObjectStorage) {
+ return self::$intervalMap;
+ }
+ self::$intervalMap = new SplObjectStorage();
+ foreach (Periodicity::cases() as $interval) {
+ $periodicityClass = sprintf('%s\Periodicity\%s', __NAMESPACE__, $interval->name);
+ self::$intervals[] = $interval->name;
+ self::$intervalMap->attach($interval, new $periodicityClass());
+ }
+
+ return self::$intervalMap;
+ }
+
private function skipInterval(int $skip): int
{
return self::DEFAULT_INTERVAL + $skip;
diff --git a/app/Support/Export/ExportDataGenerator.php b/app/Support/Export/ExportDataGenerator.php
index 30107f2c8f..fa562856cc 100644
--- a/app/Support/Export/ExportDataGenerator.php
+++ b/app/Support/Export/ExportDataGenerator.php
@@ -90,6 +90,8 @@ class ExportDataGenerator
private User $user;
private UserGroup $userGroup; // @phpstan-ignore-line
+ // @phpstan-ignore-line
+
public function __construct()
{
$this->accounts = new Collection();
diff --git a/app/Support/Http/Controllers/PeriodOverview.php b/app/Support/Http/Controllers/PeriodOverview.php
index b439d7c256..13b4f35e05 100644
--- a/app/Support/Http/Controllers/PeriodOverview.php
+++ b/app/Support/Http/Controllers/PeriodOverview.php
@@ -81,8 +81,11 @@ trait PeriodOverview
protected JournalRepositoryInterface $journalRepos;
protected PeriodStatisticRepositoryInterface $periodStatisticRepo;
private Collection $statistics; // temp data holder
+ // temp data holder
private array $transactions; // temp data holder
+ // temp data holder
+
/**
* This method returns "period entries", so nov-2015, dec-2015, etc. (this depends on the users session range)
* and for each period, the amount of money spent and earned. This is a complex operation which is cached for
@@ -114,25 +117,6 @@ trait PeriodOverview
return $entries;
}
- private function getPeriodFromBlocks(array $dates, Carbon $start, Carbon $end): array
- {
- Log::debug('Filter generated periods to select the oldest and newest date.');
- foreach ($dates as $row) {
- $currentStart = clone $row['start'];
- $currentEnd = clone $row['end'];
- if ($currentStart->lt($start)) {
- Log::debug(sprintf('New start: was %s, now %s', $start->format('Y-m-d'), $currentStart->format('Y-m-d')));
- $start = $currentStart;
- }
- if ($currentEnd->gt($end)) {
- Log::debug(sprintf('New end: was %s, now %s', $end->format('Y-m-d'), $currentEnd->format('Y-m-d')));
- $end = $currentEnd;
- }
- }
-
- return [$start, $end];
- }
-
/**
* Overview for single category. Has been refactored recently.
*
@@ -189,107 +173,6 @@ trait PeriodOverview
return $entries;
}
- private function getSingleNoModelPeriodOverview(string $model, Carbon $start, Carbon $end, string $period): array
- {
- Log::debug(sprintf('getSingleNoModelPeriodOverview(%s, %s, %s, %s)', $model, $start->format('Y-m-d'), $end->format('Y-m-d'), $period));
- $statistics = $this->filterPrefixedStatistics($start, $end, sprintf('no_%s', $model));
- $title = Navigation::periodShow($end, $period);
-
- if (0 === $statistics->count()) {
- Log::debug(sprintf('Found no statistics in period %s - %s, regenerating them.', $start->format('Y-m-d'), $end->format('Y-m-d')));
-
- switch ($model) {
- default:
- throw new FireflyException(sprintf('Cannot deal with model of type "%s"', $model));
-
- case 'budget':
- // get all expenses without a budget.
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->setRange($start, $end)->withoutBudget()->withAccountInformation()->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
- $spent = $collector->getExtractedJournals();
- $earned = [];
- $transferred = [];
-
- break;
-
- case 'category':
- // collect all expenses in this period:
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->withoutCategory();
- $collector->setRange($start, $end);
- $collector->setTypes([TransactionTypeEnum::DEPOSIT->value]);
- $earned = $collector->getExtractedJournals();
-
- // collect all income in this period:
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->withoutCategory();
- $collector->setRange($start, $end);
- $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
- $spent = $collector->getExtractedJournals();
-
- // collect all transfers in this period:
- /** @var GroupCollectorInterface $collector */
- $collector = app(GroupCollectorInterface::class);
- $collector->withoutCategory();
- $collector->setRange($start, $end);
- $collector->setTypes([TransactionTypeEnum::TRANSFER->value]);
- $transferred = $collector->getExtractedJournals();
-
- break;
- }
- $groupedSpent = $this->groupByCurrency($spent);
- $groupedEarned = $this->groupByCurrency($earned);
- $groupedTransferred = $this->groupByCurrency($transferred);
- $entry = ['title' => $title, 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [
- $start->format('Y-m-d'),
- $end->format('Y-m-d'),
- ]), 'total_transactions' => count($spent), 'spent' => $groupedSpent, 'earned' => $groupedEarned, 'transferred' => $groupedTransferred];
- $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'spent', $groupedSpent);
- $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'earned', $groupedEarned);
- $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'transferred', $groupedTransferred);
-
- return $entry;
- }
- Log::debug(sprintf('Found %d statistics in period %s - %s.', count($statistics), $start->format('Y-m-d'), $end->format('Y-m-d')));
-
- $entry = ['title' => $title, 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [
- $start->format('Y-m-d'),
- $end->format('Y-m-d'),
- ]), 'total_transactions' => 0, 'spent' => [], 'earned' => [], 'transferred' => []];
- $grouped = [];
-
- /** @var PeriodStatistic $statistic */
- foreach ($statistics as $statistic) {
- $type = str_replace(sprintf('no_%s_', $model), '', $statistic->type);
- $id = (int) $statistic->transaction_currency_id;
- $currency = Amount::getTransactionCurrencyById($id);
- $grouped[$type]['count'] ??= 0;
- $grouped[$type][$id] = [
- 'amount' => (string) $statistic->amount,
- 'count' => (int) $statistic->count,
- 'currency_id' => $currency->id,
- 'currency_name' => $currency->name,
- 'currency_code' => $currency->code,
- 'currency_symbol' => $currency->symbol,
- 'currency_decimal_places' => $currency->decimal_places,
- ];
- $grouped[$type]['count'] += (int) $statistic->count;
- }
- $types = ['spent', 'earned', 'transferred'];
- foreach ($types as $type) {
- if (array_key_exists($type, $grouped)) {
- $entry['total_transactions'] += $grouped[$type]['count'];
- unset($grouped[$type]['count']);
- $entry[$type] = $grouped[$type];
- }
- }
-
- return $entry;
- }
-
protected function getSingleModelPeriod(Model $model, string $period, Carbon $start, Carbon $end): array
{
Log::debug(sprintf('Now in getSingleModelPeriod(%s #%d, %s %s)', $model::class, $model->id, $start->format('Y-m-d'), $end->format('Y-m-d')));
@@ -314,126 +197,6 @@ trait PeriodOverview
return $return;
}
- private function filterStatistics(Carbon $start, Carbon $end, string $type): Collection
- {
- if (0 === $this->statistics->count()) {
- Log::debug('Have no statistic to filter!');
-
- return new Collection();
- }
-
- return $this->statistics->filter(
- static fn (PeriodStatistic $statistic): bool => $statistic->start->eq($start) && $statistic->end->eq($end) && $statistic->type === $type
- );
- }
-
- private function filterPrefixedStatistics(Carbon $start, Carbon $end, string $prefix): Collection
- {
- if (0 === $this->statistics->count()) {
- Log::debug('Have no statistic to filter!');
-
- return new Collection();
- }
-
- return $this->statistics->filter(
- static fn (PeriodStatistic $statistic): bool => (
- $statistic->start->eq($start)
- && $statistic->end->eq($end)
- && str_starts_with($statistic->type, $prefix)
- )
- );
- }
-
- private function getSingleModelPeriodByType(Model $model, Carbon $start, Carbon $end, string $type): array
- {
- Log::debug(sprintf(
- 'Now in getSingleModelPeriodByType(%s #%d, %s %s, %s)',
- $model::class,
- $model->id,
- $start->format('Y-m-d'),
- $end->format('Y-m-d'),
- $type
- ));
- $statistics = $this->filterStatistics($start, $end, $type);
-
- // nothing found, regenerate them.
- if (0 === $statistics->count()) {
- Log::debug(sprintf('Found nothing in this period for type "%s"', $type));
- if (0 === count($this->transactions)) {
- switch ($model::class) {
- default:
- throw new FireflyException(sprintf('Cannot deal with model of type "%s"', $model::class));
-
- case Category::class:
- $this->transactions = $this->categoryRepository->periodCollection($model, $start, $end);
-
- break;
-
- case Account::class:
- $this->transactions = $this->accountRepository->periodCollection($model, $start, $end);
-
- break;
-
- case Tag::class:
- $this->transactions = $this->tagRepository->periodCollection($model, $start, $end);
-
- break;
- }
- }
-
- switch ($type) {
- default:
- throw new FireflyException(sprintf('Cannot deal with category period type %s', $type));
-
- case 'spent':
- $result = $this->filterTransactionsByType(TransactionTypeEnum::WITHDRAWAL, $start, $end);
-
- break;
-
- case 'earned':
- $result = $this->filterTransactionsByType(TransactionTypeEnum::DEPOSIT, $start, $end);
-
- break;
-
- case 'transferred_in':
- $result = $this->filterTransfers('in', $start, $end);
-
- break;
-
- case 'transferred_away':
- $result = $this->filterTransfers('away', $start, $end);
-
- break;
- }
- // each result must be grouped by currency, then saved as period statistic.
- Log::debug(sprintf('Going to group %d found journal(s)', count($result)));
- $grouped = $this->groupByCurrency($result);
-
- $this->saveGroupedAsStatistics($model, $start, $end, $type, $grouped);
-
- return $grouped;
- }
- $grouped = ['count' => 0];
-
- /** @var PeriodStatistic $statistic */
- foreach ($statistics as $statistic) {
- $id = (int) $statistic->transaction_currency_id;
- $currency = Amount::getTransactionCurrencyById($id);
- $grouped[$id] = [
- 'amount' => (string) $statistic->amount,
- 'count' => (int) $statistic->count,
- 'currency_id' => $currency->id,
- 'currency_name' => $currency->name,
- 'currency_code' => $currency->code,
- 'currency_symbol' => $currency->symbol,
- 'currency_decimal_places' => $currency->decimal_places,
- ];
- $grouped['count'] += (int) $statistic->count;
- }
-
- return $grouped;
- }
-
/**
* This shows a period overview for a tag. It goes back in time and lists all relevant transactions and sums.
*
@@ -526,62 +289,51 @@ trait PeriodOverview
return $entries;
}
- private function saveGroupedAsStatistics(Model $model, Carbon $start, Carbon $end, string $type, array $array): void
+ /**
+ * Filter a list of journals by a set of dates, and then group them by currency.
+ */
+ private function filterJournalsByDate(array $array, Carbon $start, Carbon $end): array
{
- unset($array['count']);
- Log::debug(sprintf(
- 'saveGroupedAsStatistics(%s #%d, %s, %s, "%s", array(%d))',
- $model::class,
- $model->id,
- $start->format('Y-m-d'),
- $end->format('Y-m-d'),
- $type,
- count($array)
- ));
- foreach ($array as $entry) {
- $this->periodStatisticRepo->saveStatistic($model, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']);
- }
- if (0 === count($array)) {
- Log::debug('Save empty statistic.');
- $this->periodStatisticRepo->saveStatistic($model, $this->primaryCurrency->id, $start, $end, $type, 0, '0');
+ $result = [];
+
+ /** @var array $journal */
+ foreach ($array as $journal) {
+ if ($journal['date'] <= $end && $journal['date'] >= $start) {
+ $result[] = $journal;
+ }
}
+
+ return $result;
}
- private function saveGroupedForPrefix(string $prefix, Carbon $start, Carbon $end, string $type, array $array): void
+ private function filterPrefixedStatistics(Carbon $start, Carbon $end, string $prefix): Collection
{
- unset($array['count']);
- Log::debug(sprintf(
- 'saveGroupedForPrefix("%s", %s, %s, "%s", array(%d))',
- $prefix,
- $start->format('Y-m-d'),
- $end->format('Y-m-d'),
- $type,
- count($array)
- ));
- foreach ($array as $entry) {
- $this->periodStatisticRepo->savePrefixedStatistic($prefix, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']);
- }
- if (0 === count($array)) {
- Log::debug('Save empty statistic.');
- $this->periodStatisticRepo->savePrefixedStatistic($prefix, $this->primaryCurrency->id, $start, $end, $type, 0, '0');
+ if (0 === $this->statistics->count()) {
+ Log::debug('Have no statistic to filter!');
+
+ return new Collection();
}
+
+ return $this->statistics->filter(
+ static fn (PeriodStatistic $statistic): bool => (
+ $statistic->start->eq($start)
+ && $statistic->end->eq($end)
+ && str_starts_with($statistic->type, $prefix)
+ )
+ );
}
- /**
- * Filter a list of journals by a set of dates, and then group them by currency.
- */
- private function filterJournalsByDate(array $array, Carbon $start, Carbon $end): array
+ private function filterStatistics(Carbon $start, Carbon $end, string $type): Collection
{
- $result = [];
+ if (0 === $this->statistics->count()) {
+ Log::debug('Have no statistic to filter!');
- /** @var array $journal */
- foreach ($array as $journal) {
- if ($journal['date'] <= $end && $journal['date'] >= $start) {
- $result[] = $journal;
- }
+ return new Collection();
}
- return $result;
+ return $this->statistics->filter(
+ static fn (PeriodStatistic $statistic): bool => $statistic->start->eq($start) && $statistic->end->eq($end) && $statistic->type === $type
+ );
}
private function filterTransactionsByType(TransactionTypeEnum $type, Carbon $start, Carbon $end): array
@@ -624,6 +376,216 @@ trait PeriodOverview
return $result;
}
+ private function getPeriodFromBlocks(array $dates, Carbon $start, Carbon $end): array
+ {
+ Log::debug('Filter generated periods to select the oldest and newest date.');
+ foreach ($dates as $row) {
+ $currentStart = clone $row['start'];
+ $currentEnd = clone $row['end'];
+ if ($currentStart->lt($start)) {
+ Log::debug(sprintf('New start: was %s, now %s', $start->format('Y-m-d'), $currentStart->format('Y-m-d')));
+ $start = $currentStart;
+ }
+ if ($currentEnd->gt($end)) {
+ Log::debug(sprintf('New end: was %s, now %s', $end->format('Y-m-d'), $currentEnd->format('Y-m-d')));
+ $end = $currentEnd;
+ }
+ }
+
+ return [$start, $end];
+ }
+
+ private function getSingleModelPeriodByType(Model $model, Carbon $start, Carbon $end, string $type): array
+ {
+ Log::debug(sprintf(
+ 'Now in getSingleModelPeriodByType(%s #%d, %s %s, %s)',
+ $model::class,
+ $model->id,
+ $start->format('Y-m-d'),
+ $end->format('Y-m-d'),
+ $type
+ ));
+ $statistics = $this->filterStatistics($start, $end, $type);
+
+ // nothing found, regenerate them.
+ if (0 === $statistics->count()) {
+ Log::debug(sprintf('Found nothing in this period for type "%s"', $type));
+ if (0 === count($this->transactions)) {
+ switch ($model::class) {
+ default:
+ throw new FireflyException(sprintf('Cannot deal with model of type "%s"', $model::class));
+
+ case Category::class:
+ $this->transactions = $this->categoryRepository->periodCollection($model, $start, $end);
+
+ break;
+
+ case Account::class:
+ $this->transactions = $this->accountRepository->periodCollection($model, $start, $end);
+
+ break;
+
+ case Tag::class:
+ $this->transactions = $this->tagRepository->periodCollection($model, $start, $end);
+
+ break;
+ }
+ }
+
+ switch ($type) {
+ default:
+ throw new FireflyException(sprintf('Cannot deal with category period type %s', $type));
+
+ case 'spent':
+ $result = $this->filterTransactionsByType(TransactionTypeEnum::WITHDRAWAL, $start, $end);
+
+ break;
+
+ case 'earned':
+ $result = $this->filterTransactionsByType(TransactionTypeEnum::DEPOSIT, $start, $end);
+
+ break;
+
+ case 'transferred_in':
+ $result = $this->filterTransfers('in', $start, $end);
+
+ break;
+
+ case 'transferred_away':
+ $result = $this->filterTransfers('away', $start, $end);
+
+ break;
+ }
+ // each result must be grouped by currency, then saved as period statistic.
+ Log::debug(sprintf('Going to group %d found journal(s)', count($result)));
+ $grouped = $this->groupByCurrency($result);
+
+ $this->saveGroupedAsStatistics($model, $start, $end, $type, $grouped);
+
+ return $grouped;
+ }
+ $grouped = ['count' => 0];
+
+ /** @var PeriodStatistic $statistic */
+ foreach ($statistics as $statistic) {
+ $id = (int) $statistic->transaction_currency_id;
+ $currency = Amount::getTransactionCurrencyById($id);
+ $grouped[$id] = [
+ 'amount' => (string) $statistic->amount,
+ 'count' => (int) $statistic->count,
+ 'currency_id' => $currency->id,
+ 'currency_name' => $currency->name,
+ 'currency_code' => $currency->code,
+ 'currency_symbol' => $currency->symbol,
+ 'currency_decimal_places' => $currency->decimal_places,
+ ];
+ $grouped['count'] += (int) $statistic->count;
+ }
+
+ return $grouped;
+ }
+
+ private function getSingleNoModelPeriodOverview(string $model, Carbon $start, Carbon $end, string $period): array
+ {
+ Log::debug(sprintf('getSingleNoModelPeriodOverview(%s, %s, %s, %s)', $model, $start->format('Y-m-d'), $end->format('Y-m-d'), $period));
+ $statistics = $this->filterPrefixedStatistics($start, $end, sprintf('no_%s', $model));
+ $title = Navigation::periodShow($end, $period);
+
+ if (0 === $statistics->count()) {
+ Log::debug(sprintf('Found no statistics in period %s - %s, regenerating them.', $start->format('Y-m-d'), $end->format('Y-m-d')));
+
+ switch ($model) {
+ default:
+ throw new FireflyException(sprintf('Cannot deal with model of type "%s"', $model));
+
+ case 'budget':
+ // get all expenses without a budget.
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->setRange($start, $end)->withoutBudget()->withAccountInformation()->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
+ $spent = $collector->getExtractedJournals();
+ $earned = [];
+ $transferred = [];
+
+ break;
+
+ case 'category':
+ // collect all expenses in this period:
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->withoutCategory();
+ $collector->setRange($start, $end);
+ $collector->setTypes([TransactionTypeEnum::DEPOSIT->value]);
+ $earned = $collector->getExtractedJournals();
+
+ // collect all income in this period:
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->withoutCategory();
+ $collector->setRange($start, $end);
+ $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
+ $spent = $collector->getExtractedJournals();
+
+ // collect all transfers in this period:
+ /** @var GroupCollectorInterface $collector */
+ $collector = app(GroupCollectorInterface::class);
+ $collector->withoutCategory();
+ $collector->setRange($start, $end);
+ $collector->setTypes([TransactionTypeEnum::TRANSFER->value]);
+ $transferred = $collector->getExtractedJournals();
+
+ break;
+ }
+ $groupedSpent = $this->groupByCurrency($spent);
+ $groupedEarned = $this->groupByCurrency($earned);
+ $groupedTransferred = $this->groupByCurrency($transferred);
+ $entry = ['title' => $title, 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [
+ $start->format('Y-m-d'),
+ $end->format('Y-m-d'),
+ ]), 'total_transactions' => count($spent), 'spent' => $groupedSpent, 'earned' => $groupedEarned, 'transferred' => $groupedTransferred];
+ $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'spent', $groupedSpent);
+ $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'earned', $groupedEarned);
+ $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'transferred', $groupedTransferred);
+
+ return $entry;
+ }
+ Log::debug(sprintf('Found %d statistics in period %s - %s.', count($statistics), $start->format('Y-m-d'), $end->format('Y-m-d')));
+
+ $entry = ['title' => $title, 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [
+ $start->format('Y-m-d'),
+ $end->format('Y-m-d'),
+ ]), 'total_transactions' => 0, 'spent' => [], 'earned' => [], 'transferred' => []];
+ $grouped = [];
+
+ /** @var PeriodStatistic $statistic */
+ foreach ($statistics as $statistic) {
+ $type = str_replace(sprintf('no_%s_', $model), '', $statistic->type);
+ $id = (int) $statistic->transaction_currency_id;
+ $currency = Amount::getTransactionCurrencyById($id);
+ $grouped[$type]['count'] ??= 0;
+ $grouped[$type][$id] = [
+ 'amount' => (string) $statistic->amount,
+ 'count' => (int) $statistic->count,
+ 'currency_id' => $currency->id,
+ 'currency_name' => $currency->name,
+ 'currency_code' => $currency->code,
+ 'currency_symbol' => $currency->symbol,
+ 'currency_decimal_places' => $currency->decimal_places,
+ ];
+ $grouped[$type]['count'] += (int) $statistic->count;
+ }
+ $types = ['spent', 'earned', 'transferred'];
+ foreach ($types as $type) {
+ if (array_key_exists($type, $grouped)) {
+ $entry['total_transactions'] += $grouped[$type]['count'];
+ unset($grouped[$type]['count']);
+ $entry[$type] = $grouped[$type];
+ }
+ }
+
+ return $entry;
+ }
+
private function groupByCurrency(array $journals): array
{
Log::debug('groupByCurrency()');
@@ -675,4 +637,45 @@ trait PeriodOverview
return $return;
}
+
+ private function saveGroupedAsStatistics(Model $model, Carbon $start, Carbon $end, string $type, array $array): void
+ {
+ unset($array['count']);
+ Log::debug(sprintf(
+ 'saveGroupedAsStatistics(%s #%d, %s, %s, "%s", array(%d))',
+ $model::class,
+ $model->id,
+ $start->format('Y-m-d'),
+ $end->format('Y-m-d'),
+ $type,
+ count($array)
+ ));
+ foreach ($array as $entry) {
+ $this->periodStatisticRepo->saveStatistic($model, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']);
+ }
+ if (0 === count($array)) {
+ Log::debug('Save empty statistic.');
+ $this->periodStatisticRepo->saveStatistic($model, $this->primaryCurrency->id, $start, $end, $type, 0, '0');
+ }
+ }
+
+ private function saveGroupedForPrefix(string $prefix, Carbon $start, Carbon $end, string $type, array $array): void
+ {
+ unset($array['count']);
+ Log::debug(sprintf(
+ 'saveGroupedForPrefix("%s", %s, %s, "%s", array(%d))',
+ $prefix,
+ $start->format('Y-m-d'),
+ $end->format('Y-m-d'),
+ $type,
+ count($array)
+ ));
+ foreach ($array as $entry) {
+ $this->periodStatisticRepo->savePrefixedStatistic($prefix, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']);
+ }
+ if (0 === count($array)) {
+ Log::debug('Save empty statistic.');
+ $this->periodStatisticRepo->savePrefixedStatistic($prefix, $this->primaryCurrency->id, $start, $end, $type, 0, '0');
+ }
+ }
}
diff --git a/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php b/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php
index a0ce1f289b..93f0a19dfb 100644
--- a/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php
+++ b/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php
@@ -41,7 +41,9 @@ use Override;
class AvailableBudgetEnrichment implements EnrichmentInterface
{
private Collection $collection; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private readonly bool $convertToPrimary; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private array $currencies = [];
private array $currencyIds = [];
private array $ids = [];
diff --git a/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php b/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php
index 4fc7ead343..4a48bf0375 100644
--- a/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php
+++ b/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php
@@ -41,6 +41,7 @@ class BudgetLimitEnrichment implements EnrichmentInterface
{
private Collection $collection;
private readonly bool $convertToPrimary; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private array $currencies = [];
private array $currencyIds = [];
private Carbon $end;
diff --git a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php
index 867c41abd2..96abefec59 100644
--- a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php
+++ b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php
@@ -43,7 +43,9 @@ use Illuminate\Support\Facades\Log;
class PiggyBankEnrichment implements EnrichmentInterface
{
private array $accountIds = []; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private array $accounts = []; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private array $amounts = [];
private Collection $collection;
private array $currencies = [];
@@ -83,6 +85,11 @@ class PiggyBankEnrichment implements EnrichmentInterface
return $collection->first();
}
+ public function setDate(?Carbon $date): void
+ {
+ $this->date = $date;
+ }
+
public function setUser(User $user): void
{
$this->setUserGroup($user->userGroup);
@@ -175,11 +182,6 @@ class PiggyBankEnrichment implements EnrichmentInterface
});
}
- public function setDate(?Carbon $date): void
- {
- $this->date = $date;
- }
-
private function collectIds(): void
{
/** @var PiggyBank $piggy */
diff --git a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php
index d15814f937..fa1d95b238 100644
--- a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php
+++ b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php
@@ -38,7 +38,9 @@ use Illuminate\Support\Facades\Log;
class PiggyBankEventEnrichment implements EnrichmentInterface
{
private array $accountCurrencies = []; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private array $accountIds = []; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private Collection $collection;
private array $currencies = [];
private array $groupIds = [];
diff --git a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php
index 3c6e239fb5..3bbeb2a8b9 100644
--- a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php
+++ b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php
@@ -47,6 +47,7 @@ class SubscriptionEnrichment implements EnrichmentInterface
{
private BillDateCalculator $calculator;
private Collection $collection; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private readonly bool $convertToPrimary;
private ?Carbon $end = null;
private array $mappedObjects = [];
diff --git a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php
index b9f9b939de..d8df35c7e0 100644
--- a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php
+++ b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php
@@ -55,6 +55,8 @@ class TransactionGroupEnrichment implements EnrichmentInterface
private readonly TransactionCurrency $primaryCurrency;
private array $tags = []; // @phpstan-ignore-line
+ // @phpstan-ignore-line
+
public function __construct()
{
$this->dateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date'];
diff --git a/app/Support/JsonApi/Enrichments/WebhookEnrichment.php b/app/Support/JsonApi/Enrichments/WebhookEnrichment.php
index c477b23813..4979cdc147 100644
--- a/app/Support/JsonApi/Enrichments/WebhookEnrichment.php
+++ b/app/Support/JsonApi/Enrichments/WebhookEnrichment.php
@@ -43,7 +43,9 @@ class WebhookEnrichment implements EnrichmentInterface
{
private Collection $collection;
private array $deliveries = []; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private array $ids = []; // @phpstan-ignore-line
+ // @phpstan-ignore-line
private array $responses = [];
private array $triggers = [];
private array $webhookDeliveries = [];
diff --git a/app/Support/Models/AccountBalanceCalculator.php b/app/Support/Models/AccountBalanceCalculator.php
index 4308bf0983..99d7676dfd 100644
--- a/app/Support/Models/AccountBalanceCalculator.php
+++ b/app/Support/Models/AccountBalanceCalculator.php
@@ -46,47 +46,6 @@ class AccountBalanceCalculator
// no-op
}
- /**
- * Recalculate all account and transaction balances.
- */
- public static function recalculateAll(bool $forced): void
- {
- if ($forced) {
- Transaction::whereNull('deleted_at')->update(['balance_dirty' => true]);
-
- // also delete account balances.
- // AccountBalance::whereNotNull('created_at')->delete();
- }
- $object = new self();
- self::optimizedCalculation(new Collection());
- }
-
- public static function recalculateForJournal(TransactionJournal $transactionJournal): void
- {
- if (false === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data) {
- return;
- }
- Log::debug(__METHOD__);
- $object = new self();
-
- $set = [];
- foreach ($transactionJournal->transactions as $transaction) {
- $set[$transaction->account_id] = $transaction->account;
- }
- $accounts = new Collection()->push(...$set);
-
- // find meta value:
- $date = $transactionJournal->date;
- $meta = $transactionJournal->transactionJournalMeta()->where('name', '_internal_previous_date')->where('data', '!=', '')->first();
- Log::debug(sprintf('Date used is "%s"', $date->toW3cString()));
- if (null !== $meta) {
- $date = Carbon::parse($meta->data);
- Log::debug(sprintf('Date is overruled with "%s"', $date->toW3cString()));
- }
-
- self::optimizedCalculation($accounts, $date);
- }
-
public static function getLatestBalance(int $accountId, int $currencyId, ?Carbon $notBefore): string
{
if (!$notBefore instanceof Carbon) {
@@ -212,4 +171,45 @@ class AccountBalanceCalculator
// save all collected balances in their respective account objects.
// $this->storeAccountBalances($balances);
}
+
+ /**
+ * Recalculate all account and transaction balances.
+ */
+ public static function recalculateAll(bool $forced): void
+ {
+ if ($forced) {
+ Transaction::whereNull('deleted_at')->update(['balance_dirty' => true]);
+
+ // also delete account balances.
+ // AccountBalance::whereNotNull('created_at')->delete();
+ }
+ $object = new self();
+ self::optimizedCalculation(new Collection());
+ }
+
+ public static function recalculateForJournal(TransactionJournal $transactionJournal): void
+ {
+ if (false === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data) {
+ return;
+ }
+ Log::debug(__METHOD__);
+ $object = new self();
+
+ $set = [];
+ foreach ($transactionJournal->transactions as $transaction) {
+ $set[$transaction->account_id] = $transaction->account;
+ }
+ $accounts = new Collection()->push(...$set);
+
+ // find meta value:
+ $date = $transactionJournal->date;
+ $meta = $transactionJournal->transactionJournalMeta()->where('name', '_internal_previous_date')->where('data', '!=', '')->first();
+ Log::debug(sprintf('Date used is "%s"', $date->toW3cString()));
+ if (null !== $meta) {
+ $date = Carbon::parse($meta->data);
+ Log::debug(sprintf('Date is overruled with "%s"', $date->toW3cString()));
+ }
+
+ self::optimizedCalculation($accounts, $date);
+ }
}
diff --git a/app/Support/Models/AvailableBudgetCalculator.php b/app/Support/Models/AvailableBudgetCalculator.php
index 8ae2f694fa..6df237cb3e 100644
--- a/app/Support/Models/AvailableBudgetCalculator.php
+++ b/app/Support/Models/AvailableBudgetCalculator.php
@@ -1,4 +1,7 @@
<?php
+
+declare(strict_types=1);
+
/*
* AvailableBudgetCalculator.php
* Copyright (c) 2026 [email protected]
@@ -35,15 +38,15 @@ use Spatie\Period\Precision;
class AvailableBudgetCalculator
{
- private User $user;
+ private User $user;
private bool $create = true;
- private Carbon $start;
- private Carbon $end;
- private string $viewRange;
+ private Carbon $start;
+ private Carbon $end;
+ private string $viewRange;
private TransactionCurrency $currency;
private AvailableBudgetRepositoryInterface $abRepository;
- private BudgetLimitRepositoryInterface $blRepository;
+ private BudgetLimitRepositoryInterface $blRepository;
public function recalculateByRange(): void
{
@@ -51,9 +54,9 @@ class AvailableBudgetCalculator
// based on the view range of the user (month week quarter etc) the budget limit could
// either overlap multiple available budget periods or be contained in a single one.
// all have to be created or updated.
- $start = Navigation::startOfPeriod($this->start, $this->viewRange);
- $end = Navigation::startOfPeriod($this->end, $this->viewRange);
- $end = Navigation::endOfPeriod($end, $this->viewRange);
+ $start = Navigation::startOfPeriod($this->start, $this->viewRange);
+ $end = Navigation::startOfPeriod($this->end, $this->viewRange);
+ $end = Navigation::endOfPeriod($end, $this->viewRange);
if ($end < $start) {
[$start, $end] = [$end, $start];
@@ -65,25 +68,21 @@ class AvailableBudgetCalculator
Log::debug(sprintf('Limit period is from %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d')));
// from the start until the end of the budget limit, need to loop!
- $current = clone $start;
+ $current = clone $start;
while ($current <= $end) {
$this->refreshAvailableBudget($current);
$current = Navigation::addPeriod($current, $this->viewRange);
}
}
- public function setUser(User $user): void
+ public function setCreate(bool $create): void
{
- $this->user = $user;
- $this->abRepository = app(AvailableBudgetRepositoryInterface::class);
- $this->blRepository = app(BudgetLimitRepositoryInterface::class);
- $this->abRepository->setUser($user);
- $this->blRepository->setUser($user);
-
- $viewRange = Preferences::getForUser($user, 'viewRange', '1M')->data;
- $viewRange = !is_string($viewRange) ? '1M' : $viewRange;
- $this->viewRange = $this->correctViewRange($viewRange);
+ $this->create = $create;
+ }
+ public function setCurrency(TransactionCurrency $currency): void
+ {
+ $this->currency = $currency;
}
public function setEnd(Carbon $end): void
@@ -96,62 +95,69 @@ class AvailableBudgetCalculator
$this->start = $start;
}
- public function setCurrency(TransactionCurrency $currency): void
+ public function setUser(User $user): void
{
- $this->currency = $currency;
+ $this->user = $user;
+ $this->abRepository = app(AvailableBudgetRepositoryInterface::class);
+ $this->blRepository = app(BudgetLimitRepositoryInterface::class);
+ $this->abRepository->setUser($user);
+ $this->blRepository->setUser($user);
+
+ $viewRange = Preferences::getForUser($user, 'viewRange', '1M')->data;
+ $viewRange = !is_string($viewRange) ? '1M' : $viewRange;
+ $this->viewRange = $this->correctViewRange($viewRange);
}
private function correctViewRange(string $viewRange): string
{
if ('MTD' === $viewRange) {
Log::debug(sprintf('Overrule %s to 1M', $viewRange));
+
return '1M';
}
if ('QTD' === $viewRange) {
Log::debug(sprintf('Overrule %s to 3M', $viewRange));
+
return '3M';
}
if ('YTD' === $viewRange) {
Log::debug(sprintf('Overrule %s to 1Y', $viewRange));
+
return '1Y';
}
+
return $viewRange;
}
private function refreshAvailableBudget(Carbon $start): void
{
- $end = Navigation::endOfPeriod($start, $this->viewRange);
+ $end = Navigation::endOfPeriod($start, $this->viewRange);
Log::debug(sprintf('refreshAvailableBudget(%s), end is %s', $start->format('Y-m-d'), $end->format('Y-m-d')));
$availableBudget = $this->abRepository->find($this->currency, $start, $end);
if (null !== $availableBudget) {
Log::debug('Found available budget for this period, will update it.');
$this->abRepository->recalculateAmount($availableBudget);
+
return;
}
if (!$this->create) {
Log::debug('Can stop here. have not been asked to create an available budget.');
+
return;
}
if ($end->lt($start)) {
Log::error(sprintf('%s is less than %s, stop.', $start->format('Y-m-d'), $end->format('Y-m-d')));
+
return;
}
Log::debug(sprintf('Will create new available budget for period %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d')));
- $availableBudget = $this->abRepository->store(
- [
- 'start' => $start,
- 'end' => $end,
- 'currency_id' => $this->currency->id,
- 'amount' => '1',
- ]
- );
+ $availableBudget = $this->abRepository->store([
+ 'start' => $start,
+ 'end' => $end,
+ 'currency_id' => $this->currency->id,
+ 'amount' => '1',
+ ]);
$this->abRepository->recalculateAmount($availableBudget);
}
-
- public function setCreate(bool $create): void
- {
- $this->create = $create;
- }
-
}
diff --git a/app/Support/Repositories/UserGroup/UserGroupTrait.php b/app/Support/Repositories/UserGroup/UserGroupTrait.php
index c9d3b3fc1c..dcc2dcbd8a 100644
--- a/app/Support/Repositories/UserGroup/UserGroupTrait.php
+++ b/app/Support/Repositories/UserGroup/UserGroupTrait.php
@@ -58,6 +58,11 @@ trait UserGroupTrait
return $this->user;
}
+ public function getUserGroup(): ?UserGroup
+ {
+ return $this->userGroup;
+ }
+
/**
* @throws FireflyException
*/
@@ -77,11 +82,6 @@ trait UserGroupTrait
throw new FireflyException(sprintf('Object is %s, not User.', $class));
}
- public function getUserGroup(): ?UserGroup
- {
- return $this->userGroup;
- }
-
/**
* TODO This method does not check if the user has access to this particular user group.
*/
diff --git a/app/Support/Request/AppendsLocationData.php b/app/Support/Request/AppendsLocationData.php
index 0db2b39909..ac36baa19b 100644
--- a/app/Support/Request/AppendsLocationData.php
+++ b/app/Support/Request/AppendsLocationData.php
@@ -31,23 +31,6 @@ use Illuminate\Support\Facades\Log;
*/
trait AppendsLocationData
{
- public function addFromromTransactionStore(array $information, array $return): array
- {
- $return['store_location'] = false;
- if (true === $information['store_location']) {
- $long = $information['longitude'] ?? null;
- $lat = $information['latitude'] ?? null;
- if (null !== $long && null !== $lat && $this->validLongitude($long) && $this->validLatitude($lat)) {
- $return['store_location'] = true;
- $return['longitude'] = $information['longitude'];
- $return['latitude'] = $information['latitude'];
- $return['zoom_level'] = $information['zoom_level'];
- }
- }
-
- return $return;
- }
-
/**
* Abstract method stolen from "InteractsWithInput".
*
@@ -85,6 +68,23 @@ trait AppendsLocationData
*/
abstract public function routeIs(...$patterns);
+ public function addFromromTransactionStore(array $information, array $return): array
+ {
+ $return['store_location'] = false;
+ if (true === $information['store_location']) {
+ $long = $information['longitude'] ?? null;
+ $lat = $information['latitude'] ?? null;
+ if (null !== $long && null !== $lat && $this->validLongitude($long) && $this->validLatitude($lat)) {
+ $return['store_location'] = true;
+ $return['longitude'] = $information['longitude'];
+ $return['latitude'] = $information['latitude'];
+ $return['zoom_level'] = $information['zoom_level'];
+ }
+ }
+
+ return $return;
+ }
+
/**
* Read the submitted Request data and add new or updated Location data to the array.
*/
@@ -159,30 +159,28 @@ trait AppendsLocationData
&& ('PUT' === $this->method() || 'POST' === $this->method() && $this->routeIs('*.update'));
}
- private function isValidPUT(?string $prefix): bool
+ private function isValidPost(?string $prefix): bool
{
+ Log::debug('Now in isValidPost()');
$longitudeKey = $this->getLocationKey($prefix, 'longitude');
$latitudeKey = $this->getLocationKey($prefix, 'latitude');
$zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level');
$hasLocationKey = $this->getLocationKey($prefix, 'has_location');
- Log::debug('Now in isValidPUT()');
-
- // all fields must be set:
+ // fields must not be null:
if (!in_array(null, [$this->get($longitudeKey), $this->get($latitudeKey), $this->get($zoomLevelKey)], true)) {
- Log::debug('All fields present.');
- // must be PUT and API route:
- if ('PUT' === $this->method() && $this->routeIs('api.v1.*')) {
+ Log::debug('All fields present');
+ // if is POST and route contains API, this is enough:
+ if ('POST' === $this->method() && $this->routeIs('api.v1.*')) {
Log::debug('Is API location');
return true;
}
- // if POST and not API route, must also have "has_location"
// if is POST and route does not contain API, must also have "has_location" = true
- if ('POST' === $this->method() && $this->routeIs('*.update') && !$this->routeIs('api.v1.*') && '' !== $hasLocationKey) {
+ if ('POST' === $this->method() && $this->routeIs('*.store') && !$this->routeIs('api.v1.*') && '' !== $hasLocationKey) {
Log::debug('Is POST + store route.');
$hasLocation = $this->boolean($hasLocationKey);
if (true === $hasLocation) {
- Log::debug('Has form location data + has_location');
+ Log::debug('Has form form location');
return true;
}
@@ -199,28 +197,30 @@ trait AppendsLocationData
return false;
}
- private function isValidPost(?string $prefix): bool
+ private function isValidPUT(?string $prefix): bool
{
- Log::debug('Now in isValidPost()');
$longitudeKey = $this->getLocationKey($prefix, 'longitude');
$latitudeKey = $this->getLocationKey($prefix, 'latitude');
$zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level');
$hasLocationKey = $this->getLocationKey($prefix, 'has_location');
- // fields must not be null:
+ Log::debug('Now in isValidPUT()');
+
+ // all fields must be set:
if (!in_array(null, [$this->get($longitudeKey), $this->get($latitudeKey), $this->get($zoomLevelKey)], true)) {
- Log::debug('All fields present');
- // if is POST and route contains API, this is enough:
- if ('POST' === $this->method() && $this->routeIs('api.v1.*')) {
+ Log::debug('All fields present.');
+ // must be PUT and API route:
+ if ('PUT' === $this->method() && $this->routeIs('api.v1.*')) {
Log::debug('Is API location');
return true;
}
+ // if POST and not API route, must also have "has_location"
// if is POST and route does not contain API, must also have "has_location" = true
- if ('POST' === $this->method() && $this->routeIs('*.store') && !$this->routeIs('api.v1.*') && '' !== $hasLocationKey) {
+ if ('POST' === $this->method() && $this->routeIs('*.update') && !$this->routeIs('api.v1.*') && '' !== $hasLocationKey) {
Log::debug('Is POST + store route.');
$hasLocation = $this->boolean($hasLocationKey);
if (true === $hasLocation) {
- Log::debug('Has form form location');
+ Log::debug('Has form location data + has_location');
return true;
}
diff --git a/app/Support/Request/ConvertsDataTypes.php b/app/Support/Request/ConvertsDataTypes.php
index d5050bb22c..c0d7e7f45e 100644
--- a/app/Support/Request/ConvertsDataTypes.php
+++ b/app/Support/Request/ConvertsDataTypes.php
@@ -91,6 +91,22 @@ trait ConvertsDataTypes
"\r", // carriage return
];
+ /**
+ * Abstract method that always exists in the Request classes that use this
+ * trait, OR a stub needs to be added by any other class that uses this train.
+ */
+ abstract public function get(string $key, mixed $default = null): mixed;
+
+ /**
+ * Abstract method that always exists in the Request classes that use this
+ * trait, OR a stub needs to be added by any other class that uses this train.
+ *
+ * @param mixed $key
+ *
+ * @return mixed
+ */
+ abstract public function has($key);
+
public function clearIban(?string $string): ?string
{
$string = $this->clearString($string);
@@ -179,12 +195,6 @@ trait ConvertsDataTypes
return (string) $this->clearString((string) $entry);
}
- /**
- * Abstract method that always exists in the Request classes that use this
- * trait, OR a stub needs to be added by any other class that uses this train.
- */
- abstract public function get(string $key, mixed $default = null): mixed;
-
/**
* TODO duplicate, see SelectTransactionsRequest
*
@@ -217,16 +227,6 @@ trait ConvertsDataTypes
return $collection;
}
- /**
- * Abstract method that always exists in the Request classes that use this
- * trait, OR a stub needs to be added by any other class that uses this train.
- *
- * @param mixed $key
- *
- * @return mixed
- */
- abstract public function has($key);
-
/**
* Return string value with newlines.
*/
diff --git a/app/Support/Steam.php b/app/Support/Steam.php
index 568ebff821..860bb4d53e 100644
--- a/app/Support/Steam.php
+++ b/app/Support/Steam.php
@@ -52,6 +52,23 @@ use function Safe\preg_replace;
*/
class Steam
{
+ /**
+ * Calls accountsBalancesOptimized for the given accounts and makes sure that inclusive is set to false, so it
+ * properly gets the balance of a range.
+ */
+ public function accountsBalancesInRange(
+ Collection $accounts,
+ Carbon $start,
+ Carbon $end,
+ ?TransactionCurrency $primary = null,
+ ?bool $convertToPrimary = null
+ ): array {
+ return [
+ $this->accountsBalancesOptimized($accounts, $start, $primary, $convertToPrimary, inclusive: false),
+ $this->accountsBalancesOptimized($accounts, $end, $primary, $convertToPrimary),
+ ];
+ }
+
public function accountsBalancesOptimized(
Collection $accounts,
Carbon $date,
@@ -138,21 +155,17 @@ class Steam
return $result;
}
- /**
- * Calls accountsBalancesOptimized for the given accounts and makes sure that inclusive is set to false, so it
- * properly gets the balance of a range.
- */
- public function accountsBalancesInRange(
- Collection $accounts,
- Carbon $start,
- Carbon $end,
- ?TransactionCurrency $primary = null,
- ?bool $convertToPrimary = null
- ): array {
- return [
- $this->accountsBalancesOptimized($accounts, $start, $primary, $convertToPrimary, inclusive: false),
- $this->accountsBalancesOptimized($accounts, $end, $primary, $convertToPrimary),
- ];
+ public function anonymous(): bool // get preference
+ {
+ $singleton = PreferencesSingleton::getInstance();
+ $cached = $singleton->getPreference('anonymous');
+ if (null !== $cached) {
+ return $cached;
+ }
+ $anonymous = Preferences::get('anonymous', config('firefly.default_preferences.anonymous', false))->data;
+ $singleton->setPreference('anonymous', $anonymous);
+
+ return $anonymous;
}
/**
@@ -646,19 +659,6 @@ class Steam
return $locale;
}
- public function anonymous(): bool // get preference
- {
- $singleton = PreferencesSingleton::getInstance();
- $cached = $singleton->getPreference('anonymous');
- if (null !== $cached) {
- return $cached;
- }
- $anonymous = Preferences::get('anonymous', config('firefly.default_preferences.anonymous', false))->data;
- $singleton->setPreference('anonymous', $anonymous);
-
- return $anonymous;
- }
-
public function getLocaleArray(string $locale): array
{
return [sprintf('%s.utf8', $locale), sprintf('%s.UTF-8', $locale)];
diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php
index 3d13930dc3..ffb2da2ca0 100644
--- a/app/Support/Twig/General.php
+++ b/app/Support/Twig/General.php
@@ -359,6 +359,14 @@ class General extends AbstractExtension
);
}
+ /**
+ * Basic example thing for some views.
+ */
+ protected function phpdate(): TwigFunction
+ {
+ return new TwigFunction('phpdate', date(...));
+ }
+
/**
* Show URL host name
*/
@@ -378,14 +386,6 @@ class General extends AbstractExtension
});
}
- /**
- * Basic example thing for some views.
- */
- protected function phpdate(): TwigFunction
- {
- return new TwigFunction('phpdate', date(...));
- }
-
private function fireflyIIIConfig()
{
return new TwigFunction('fireflyiiiconfig', static fn (string $string, mixed $default): mixed => FireflyConfig::get($string, $default)->data);
diff --git a/app/TransactionRules/Actions/ConvertToDeposit.php b/app/TransactionRules/Actions/ConvertToDeposit.php
index d7d68d44e9..3527f1644a 100644
--- a/app/TransactionRules/Actions/ConvertToDeposit.php
+++ b/app/TransactionRules/Actions/ConvertToDeposit.php
@@ -135,6 +135,56 @@ class ConvertToDeposit implements ActionInterface
return false;
}
+ /**
+ * Input is a transfer from A to B.
+ * Output is a deposit from C to B.
+ * The source account is replaced.
+ *
+ * @throws FireflyException
+ */
+ private function convertTransferArray(TransactionJournal $journal, string $actionValue = ''): bool
+ {
+ $user = $journal->user;
+
+ // find or create revenue account.
+ /** @var AccountFactory $factory */
+ $factory = app(AccountFactory::class);
+ $factory->setUser($user);
+
+ $repository = app(AccountRepositoryInterface::class);
+ $repository->setUser($user);
+
+ $sourceAccount = $this->getSourceAccount($journal);
+
+ // get the action value, or use the original source name in case the action value is empty:
+ // this becomes a new or existing (revenue) account, which is the source of the new deposit.
+ $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue;
+ // we check all possible source account types if one exists:
+ $validTypes = config('firefly.expected_source_types.source.Deposit');
+ $opposingAccount = $repository->findByName($opposingName, $validTypes);
+ if (null === $opposingAccount) {
+ $opposingAccount = $factory->findOrCreate($opposingName, AccountTypeEnum::REVENUE->value);
+ }
+
+ Log::debug(sprintf('ConvertToDeposit. Action value is "%s", revenue name is "%s"', $actionValue, $opposingAccount->name));
+
+ // update source transaction(s) to be revenue account
+ DB::table('transactions')
+ ->where('transaction_journal_id', '=', $journal->id)
+ ->where('amount', '<', 0)
+ ->update(['account_id' => $opposingAccount->id])
+ ;
+
+ // change transaction type of journal:
+ $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first();
+
+ DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]);
+
+ Log::debug('Converted transfer to deposit.');
+
+ return true;
+ }
+
/**
* Input is a withdrawal from A to B
* Is converted to a deposit from C to A.
@@ -219,54 +269,4 @@ class ConvertToDeposit implements ActionInterface
return $sourceTransaction->account;
}
-
- /**
- * Input is a transfer from A to B.
- * Output is a deposit from C to B.
- * The source account is replaced.
- *
- * @throws FireflyException
- */
- private function convertTransferArray(TransactionJournal $journal, string $actionValue = ''): bool
- {
- $user = $journal->user;
-
- // find or create revenue account.
- /** @var AccountFactory $factory */
- $factory = app(AccountFactory::class);
- $factory->setUser($user);
-
- $repository = app(AccountRepositoryInterface::class);
- $repository->setUser($user);
-
- $sourceAccount = $this->getSourceAccount($journal);
-
- // get the action value, or use the original source name in case the action value is empty:
- // this becomes a new or existing (revenue) account, which is the source of the new deposit.
- $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue;
- // we check all possible source account types if one exists:
- $validTypes = config('firefly.expected_source_types.source.Deposit');
- $opposingAccount = $repository->findByName($opposingName, $validTypes);
- if (null === $opposingAccount) {
- $opposingAccount = $factory->findOrCreate($opposingName, AccountTypeEnum::REVENUE->value);
- }
-
- Log::debug(sprintf('ConvertToDeposit. Action value is "%s", revenue name is "%s"', $actionValue, $opposingAccount->name));
-
- // update source transaction(s) to be revenue account
- DB::table('transactions')
- ->where('transaction_journal_id', '=', $journal->id)
- ->where('amount', '<', 0)
- ->update(['account_id' => $opposingAccount->id])
- ;
-
- // change transaction type of journal:
- $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first();
-
- DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]);
-
- Log::debug('Converted transfer to deposit.');
-
- return true;
- }
}
diff --git a/app/TransactionRules/Actions/ConvertToTransfer.php b/app/TransactionRules/Actions/ConvertToTransfer.php
index ed9344e2e2..84efc7a0d5 100644
--- a/app/TransactionRules/Actions/ConvertToTransfer.php
+++ b/app/TransactionRules/Actions/ConvertToTransfer.php
@@ -175,30 +175,41 @@ class ConvertToTransfer implements ActionInterface
return $res;
}
- private function getSourceType(int $journalId): string
+ /**
+ * A deposit is from Revenue to Asset.
+ * We replace the Revenue with another asset.
+ *
+ * @throws FireflyException
+ */
+ private function convertDepositArray(TransactionJournal $journal, Account $opposing): bool
{
- /** @var null|TransactionJournal $journal */
- $journal = TransactionJournal::find($journalId);
- if (null === $journal) {
- Log::error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId));
+ $destAccount = $this->getDestinationAccount($journal);
+ if ($destAccount->id === $opposing->id) {
+ Log::error(vsprintf('Journal #%d has already has "%s" as a destination asset. ConvertToTransfer failed. (rule #%d).', [
+ $journal->id,
+ $opposing->name,
+ $this->action->rule_id,
+ ]));
+ event(new RuleActionFailedOnObject($this->action, $journal, trans('rules.already_has_destination_asset', ['name' => $opposing->name])));
- return '';
+ return false;
}
- return (string) $journal->transactions()->where('amount', '<', 0)->first()?->account?->accountType?->type;
- }
+ // update source transaction:
+ DB::table('transactions')
+ ->where('transaction_journal_id', '=', $journal->id)
+ ->where('amount', '<', 0)
+ ->update(['account_id' => $opposing->id])
+ ;
- private function getDestinationType(int $journalId): string
- {
- /** @var null|TransactionJournal $journal */
- $journal = TransactionJournal::find($journalId);
- if (null === $journal) {
- Log::error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId));
+ // change transaction type of journal:
+ $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first();
- return '';
- }
+ DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]);
- return (string) $journal->transactions()->where('amount', '>', 0)->first()?->account?->accountType?->type;
+ Log::debug('Converted deposit to transfer.');
+
+ return true;
}
/**
@@ -286,65 +297,54 @@ class ConvertToTransfer implements ActionInterface
/**
* @throws FireflyException
*/
- private function getSourceAccount(TransactionJournal $journal): Account
+ private function getDestinationAccount(TransactionJournal $journal): Account
{
- /** @var null|Transaction $sourceTransaction */
- $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
- if (null === $sourceTransaction) {
- throw new FireflyException(sprintf('Cannot find source transaction for journal #%d', $journal->id));
+ /** @var null|Transaction $destAccount */
+ $destAccount = $journal->transactions()->where('amount', '>', 0)->first();
+ if (null === $destAccount) {
+ throw new FireflyException(sprintf('Cannot find destination transaction for journal #%d', $journal->id));
}
- return $sourceTransaction->account;
+ return $destAccount->account;
}
- /**
- * A deposit is from Revenue to Asset.
- * We replace the Revenue with another asset.
- *
- * @throws FireflyException
- */
- private function convertDepositArray(TransactionJournal $journal, Account $opposing): bool
+ private function getDestinationType(int $journalId): string
{
- $destAccount = $this->getDestinationAccount($journal);
- if ($destAccount->id === $opposing->id) {
- Log::error(vsprintf('Journal #%d has already has "%s" as a destination asset. ConvertToTransfer failed. (rule #%d).', [
- $journal->id,
- $opposing->name,
- $this->action->rule_id,
- ]));
- event(new RuleActionFailedOnObject($this->action, $journal, trans('rules.already_has_destination_asset', ['name' => $opposing->name])));
+ /** @var null|TransactionJournal $journal */
+ $journal = TransactionJournal::find($journalId);
+ if (null === $journal) {
+ Log::error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId));
- return false;
+ return '';
}
- // update source transaction:
- DB::table('transactions')
- ->where('transaction_journal_id', '=', $journal->id)
- ->where('amount', '<', 0)
- ->update(['account_id' => $opposing->id])
- ;
-
- // change transaction type of journal:
- $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first();
-
- DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]);
-
- Log::debug('Converted deposit to transfer.');
-
- return true;
+ return (string) $journal->transactions()->where('amount', '>', 0)->first()?->account?->accountType?->type;
}
/**
* @throws FireflyException
*/
- private function getDestinationAccount(TransactionJournal $journal): Account
+ private function getSourceAccount(TransactionJournal $journal): Account
{
- /** @var null|Transaction $destAccount */
- $destAccount = $journal->transactions()->where('amount', '>', 0)->first();
- if (null === $destAccount) {
- throw new FireflyException(sprintf('Cannot find destination transaction for journal #%d', $journal->id));
+ /** @var null|Transaction $sourceTransaction */
+ $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
+ if (null === $sourceTransaction) {
+ throw new FireflyException(sprintf('Cannot find source transaction for journal #%d', $journal->id));
}
- return $destAccount->account;
+ return $sourceTransaction->account;
+ }
+
+ private function getSourceType(int $journalId): string
+ {
+ /** @var null|TransactionJournal $journal */
+ $journal = TransactionJournal::find($journalId);
+ if (null === $journal) {
+ Log::error(sprintf('Journal #%d does not exist. Cannot convert to transfer.', $journalId));
+
+ return '';
+ }
+
+ return (string) $journal->transactions()->where('amount', '<', 0)->first()?->account?->accountType?->type;
}
}
diff --git a/app/TransactionRules/Actions/ConvertToWithdrawal.php b/app/TransactionRules/Actions/ConvertToWithdrawal.php
index 3db1193c25..73164972e4 100644
--- a/app/TransactionRules/Actions/ConvertToWithdrawal.php
+++ b/app/TransactionRules/Actions/ConvertToWithdrawal.php
@@ -185,34 +185,6 @@ class ConvertToWithdrawal implements ActionInterface
return true;
}
- /**
- * @throws FireflyException
- */
- private function getSourceAccount(TransactionJournal $journal): Account
- {
- /** @var null|Transaction $sourceTransaction */
- $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
- if (null === $sourceTransaction) {
- throw new FireflyException(sprintf('Cannot find source transaction for journal #%d', $journal->id));
- }
-
- return $sourceTransaction->account;
- }
-
- /**
- * @throws FireflyException
- */
- private function getDestinationAccount(TransactionJournal $journal): Account
- {
- /** @var null|Transaction $destAccount */
- $destAccount = $journal->transactions()->where('amount', '>', 0)->first();
- if (null === $destAccount) {
- throw new FireflyException(sprintf('Cannot find destination transaction for journal #%d', $journal->id));
- }
-
- return $destAccount->account;
- }
-
/**
* Input is a transfer from A to B.
* Output is a withdrawal from A to C.
@@ -260,4 +232,32 @@ class ConvertToWithdrawal implements ActionInterface
return true;
}
+
+ /**
+ * @throws FireflyException
+ */
+ private function getDestinationAccount(TransactionJournal $journal): Account
+ {
+ /** @var null|Transaction $destAccount */
+ $destAccount = $journal->transactions()->where('amount', '>', 0)->first();
+ if (null === $destAccount) {
+ throw new FireflyException(sprintf('Cannot find destination transaction for journal #%d', $journal->id));
+ }
+
+ return $destAccount->account;
+ }
+
+ /**
+ * @throws FireflyException
+ */
+ private function getSourceAccount(TransactionJournal $journal): Account
+ {
+ /** @var null|Transaction $sourceTransaction */
+ $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
+ if (null === $sourceTransaction) {
+ throw new FireflyException(sprintf('Cannot find source transaction for journal #%d', $journal->id));
+ }
+
+ return $sourceTransaction->account;
+ }
}
diff --git a/app/TransactionRules/Actions/SetAmount.php b/app/TransactionRules/Actions/SetAmount.php
index c5ee14185d..69e2a071ea 100644
--- a/app/TransactionRules/Actions/SetAmount.php
+++ b/app/TransactionRules/Actions/SetAmount.php
@@ -100,16 +100,6 @@ class SetAmount implements ActionInterface
return true;
}
- private function updatePositive(TransactionJournal $object, string $amount): void
- {
- /** @var null|Transaction $transaction */
- $transaction = $object->transactions()->where('amount', '>', 0)->first();
- if (null === $transaction) {
- return;
- }
- $this->updateAmount($transaction, $amount);
- }
-
private function updateAmount(Transaction $transaction, string $amount): void
{
$transaction->amount = $amount;
@@ -126,4 +116,14 @@ class SetAmount implements ActionInterface
}
$this->updateAmount($transaction, $amount);
}
+
+ private function updatePositive(TransactionJournal $object, string $amount): void
+ {
+ /** @var null|Transaction $transaction */
+ $transaction = $object->transactions()->where('amount', '>', 0)->first();
+ if (null === $transaction) {
+ return;
+ }
+ $this->updateAmount($transaction, $amount);
+ }
}
diff --git a/app/TransactionRules/Actions/UpdatePiggyBank.php b/app/TransactionRules/Actions/UpdatePiggyBank.php
index 5825a55128..0ca2afcb72 100644
--- a/app/TransactionRules/Actions/UpdatePiggyBank.php
+++ b/app/TransactionRules/Actions/UpdatePiggyBank.php
@@ -139,6 +139,54 @@ class UpdatePiggyBank implements ActionInterface
return false;
}
+ private function addAmount(PiggyBank $piggyBank, array $array, TransactionJournal $journal, Account $account, string $amount): void
+ {
+ $repository = app(PiggyBankRepositoryInterface::class);
+ $accountRepository = app(AccountRepositoryInterface::class);
+ $repository->setUser($journal->user);
+ $accountRepository->setUser($account->user);
+
+ // how much can we add to the piggy bank?
+ if (0 !== bccomp($piggyBank->target_amount, '0')) {
+ $toAdd = bcsub($piggyBank->target_amount, $repository->getCurrentAmount($piggyBank, $account));
+ 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;
+ Log::debug(sprintf('Amount is now %s', $amount));
+ }
+ if (0 === bccomp($piggyBank->target_amount, '0')) {
+ Log::debug('Target amount is zero, can add anything.');
+ }
+
+ // if amount is zero, stop.
+ if (0 === bccomp('0', $amount)) {
+ Log::warning('Amount left is zero, stop.');
+ event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_add_zero_piggy', ['name' => $piggyBank->name])));
+
+ return;
+ }
+
+ if (false === $repository->canAddAmount($piggyBank, $account, $amount)) {
+ Log::warning(sprintf('Cannot add %s to piggy bank.', $amount));
+ $currency = $accountRepository->getAccountCurrency($account) ?? Amount::getPrimaryCurrency();
+ event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_add_to_piggy', [
+ 'amount' => Amount::formatAnything($currency, $amount, false),
+ 'name' => $piggyBank->name,
+ ])));
+
+ return;
+ }
+ Log::debug(sprintf('Will now add %s to piggy bank.', $amount));
+
+ $repository->addAmount($piggyBank, $account, $amount, $journal);
+ }
+
+ private function alreadyEventPresent(PiggyBank $piggyBank, array $journal): bool
+ {
+ return $piggyBank->piggyBankEvents()->where('transaction_journal_id', $journal['transaction_journal_id'])->exists();
+ }
+
private function findPiggyBank(User $user, string $name): ?PiggyBank
{
/** @var PiggyBankRepositoryInterface $repository */
@@ -208,52 +256,4 @@ class UpdatePiggyBank implements ActionInterface
$repository->removeAmount($piggyBank, $account, $amount, $journal);
}
-
- private function addAmount(PiggyBank $piggyBank, array $array, TransactionJournal $journal, Account $account, string $amount): void
- {
- $repository = app(PiggyBankRepositoryInterface::class);
- $accountRepository = app(AccountRepositoryInterface::class);
- $repository->setUser($journal->user);
- $accountRepository->setUser($account->user);
-
- // how much can we add to the piggy bank?
- if (0 !== bccomp($piggyBank->target_amount, '0')) {
- $toAdd = bcsub($piggyBank->target_amount, $repository->getCurrentAmount($piggyBank, $account));
- 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;
- Log::debug(sprintf('Amount is now %s', $amount));
- }
- if (0 === bccomp($piggyBank->target_amount, '0')) {
- Log::debug('Target amount is zero, can add anything.');
- }
-
- // if amount is zero, stop.
- if (0 === bccomp('0', $amount)) {
- Log::warning('Amount left is zero, stop.');
- event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_add_zero_piggy', ['name' => $piggyBank->name])));
-
- return;
- }
-
- if (false === $repository->canAddAmount($piggyBank, $account, $amount)) {
- Log::warning(sprintf('Cannot add %s to piggy bank.', $amount));
- $currency = $accountRepository->getAccountCurrency($account) ?? Amount::getPrimaryCurrency();
- event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_add_to_piggy', [
- 'amount' => Amount::formatAnything($currency, $amount, false),
- 'name' => $piggyBank->name,
- ])));
-
- return;
- }
- Log::debug(sprintf('Will now add %s to piggy bank.', $amount));
-
- $repository->addAmount($piggyBank, $account, $amount, $journal);
- }
-
- private function alreadyEventPresent(PiggyBank $piggyBank, array $journal): bool
- {
- return $piggyBank->piggyBankEvents()->where('transaction_journal_id', $journal['transaction_journal_id'])->exists();
- }
}
diff --git a/app/TransactionRules/Engine/SearchRuleEngine.php b/app/TransactionRules/Engine/SearchRuleEngine.php
index 13b3dac12b..ed78800ac9 100644
--- a/app/TransactionRules/Engine/SearchRuleEngine.php
+++ b/app/TransactionRules/Engine/SearchRuleEngine.php
@@ -85,122 +85,79 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
- * Finds the transactions a strict rule will execute on.
+ * @throws FireflyException
*/
- private function findStrictRule(Rule $rule): Collection
+ public function fire(): void
{
- Log::debug(sprintf('Now in findStrictRule(#%d)', $rule->id ?? 0));
- $searchArray = [];
- $triggers = [];
- if ($this->refreshTriggers) {
- $triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->get();
- }
- if (!$this->refreshTriggers) {
- $triggers = $rule->ruleTriggers;
- }
+ $this->resultCount = [];
+ Log::debug('SearchRuleEngine::fire()!');
- /** @var RuleTrigger $ruleTrigger */
- foreach ($triggers as $ruleTrigger) {
- if (false === $ruleTrigger->active) {
- continue;
- }
- $contextSearch = $ruleTrigger->trigger_type;
- if (str_starts_with((string) $ruleTrigger->trigger_type, '-')) {
- $contextSearch = substr((string) $ruleTrigger->trigger_type, 1);
- }
+ // if rules and no rule groups, file each rule separately.
+ if (0 !== $this->rules->count()) {
+ Log::debug(sprintf('SearchRuleEngine:: found %d rule(s) to fire.', $this->rules->count()));
- // if the trigger needs no context, value is different:
- $needsContext = (bool) (config(sprintf('search.operators.%s.needs_context', $contextSearch)) ?? true);
- if (false === $needsContext) {
- Log::debug(sprintf('SearchRuleEngine:: add a rule trigger (no context): %s:true', $ruleTrigger->trigger_type));
- $searchArray[$ruleTrigger->trigger_type][] = 'true';
- }
- if ($needsContext) {
- Log::debug(sprintf('SearchRuleEngine:: add a rule trigger (context): %s:"%s"', $ruleTrigger->trigger_type, $ruleTrigger->trigger_value));
- $searchArray[$ruleTrigger->trigger_type][] = sprintf('"%s"', $ruleTrigger->trigger_value);
+ /** @var Rule $rule */
+ foreach ($this->rules as $rule) { // @phpstan-ignore-line
+ $result = $this->fireRule($rule);
+ if ($result && true === $rule->stop_processing) {
+ Log::debug(sprintf(
+ 'Rule #%d has triggered and executed, but calls to stop processing. Since not in the context of a group, do not stop.',
+ $rule->id
+ ));
+ }
+ if (false === $result && true === $rule->stop_processing) {
+ Log::debug(sprintf('Rule #%d has triggered and changed nothing, but calls to stop processing. Do not stop.', $rule->id));
+ }
}
- }
+ Log::debug('SearchRuleEngine:: done processing all rules!');
- // add local operators:
- foreach ($this->operators as $operator) {
- Log::debug(sprintf('SearchRuleEngine:: add local added operator: %s:"%s"', $operator['type'], $operator['value']));
- $searchArray[$operator['type']][] = sprintf('"%s"', $operator['value']);
- }
- $date = today(config('app.timezone'));
- if ($this->hasSpecificJournalTrigger($searchArray)) {
- $date = $this->setDateFromJournalTrigger($searchArray);
+ return;
}
+ if (0 !== $this->groups->count()) {
+ Log::debug(sprintf('SearchRuleEngine:: found %d rule group(s) to fire.', $this->groups->count()));
- // build and run the search engine.
- $searchEngine = app(SearchInterface::class);
- $searchEngine->setUser($this->user);
- $searchEngine->setPage(1);
- $searchEngine->setLimit(31337);
- $searchEngine->setDate($date);
- Log::debug('Search array', $searchArray);
- foreach ($searchArray as $type => $searches) {
- foreach ($searches as $value) {
- $query = sprintf('%s:%s', $type, $value);
- Log::debug(sprintf('SearchRuleEngine:: add query "%s"', $query));
- $searchEngine->parseQuery($query);
+ // fire each group:
+ /** @var RuleGroup $group */
+ foreach ($this->groups as $group) { // @phpstan-ignore-line
+ $this->fireGroup($group);
}
}
-
- $result = $searchEngine->searchTransactions();
-
- return $result->getCollection();
+ Log::debug('SearchRuleEngine:: done processing all rules!');
}
/**
- * Search in the triggers of this particular search and if it contains
- * one search operator for "journal_id" it means the date ranges
- * in the search may need to be updated.
+ * Return the number of changed transactions from the previous "fire" action.
*/
- private function hasSpecificJournalTrigger(array $array): bool
+ public function getResults(): int
{
- Log::debug('Now in hasSpecificJournalTrigger.');
- $journalTrigger = false;
- $dateTrigger = false;
- foreach ($array as $triggerName => $values) {
- if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
- Log::debug('Found a journal_id trigger with 1 journal, true.');
- $journalTrigger = true;
- }
- if (in_array($triggerName, ['date_is', 'date', 'on', 'date_before', 'before', 'date_after', 'after'], true)) {
- Log::debug('Found a date related trigger, set to true.');
- $dateTrigger = true;
- }
- }
- $result = $journalTrigger && $dateTrigger;
- Log::debug(sprintf('Result of hasSpecificJournalTrigger is %s.', var_export($result, true)));
+ return count($this->resultCount);
+ }
- return $result;
+ public function setRefreshTriggers(bool $refreshTriggers): void
+ {
+ $this->refreshTriggers = $refreshTriggers;
}
- private function setDateFromJournalTrigger(array $array): Carbon
+ public function setRuleGroups(Collection $ruleGroups): void
{
- Log::debug('Now in setDateFromJournalTrigger()');
- $journalId = 0;
- foreach ($array as $triggerName => $values) {
- if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
- $journalId = (int) trim($values[0] ?? '"0"', '"'); // follows format "123".
- Log::debug(sprintf('Found journal ID #%d', $journalId));
+ Log::debug(__METHOD__);
+ foreach ($ruleGroups as $group) {
+ if ($group instanceof RuleGroup) {
+ Log::debug(sprintf('Adding a rule group to the SearchRuleEngine: #%d ("%s")', $group->id, $group->title));
+ $this->groups->push($group);
}
}
- if (0 !== $journalId) {
- $repository = app(JournalRepositoryInterface::class);
- $repository->setUser($this->user);
- $journal = $repository->find($journalId);
- if (null !== $journal) {
- $date = $journal->date;
- Log::debug(sprintf('Found journal #%d with date %s.', $journal->id, $journal->date->format('Y-m-d')));
+ }
- return $date;
+ public function setRules(Collection $rules): void
+ {
+ Log::debug(__METHOD__);
+ foreach ($rules as $rule) {
+ if ($rule instanceof Rule) {
+ Log::debug(sprintf('Adding a rule to the SearchRuleEngine: #%d ("%s")', $rule->id, $rule->title));
+ $this->rules->push($rule);
}
}
- Log::debug('Found no journal, return default date.');
-
- return today(config('app.timezone'));
}
public function setUser(User $user): void
@@ -209,6 +166,21 @@ class SearchRuleEngine implements RuleEngineInterface
$this->operators = [];
}
+ private function addNotes(array $transaction): array
+ {
+ $transaction['notes'] = '';
+ $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id'])
+ ->where('noteable_type', TransactionJournal::class)
+ ->first(['notes.*'])
+ ;
+ if (null !== $dbNote) {
+ $transaction['notes'] = $dbNote->text;
+ }
+ Log::debug(sprintf('Notes of journal #%d filled in.', $transaction['transaction_journal_id']));
+
+ return $transaction;
+ }
+
private function findNonStrictRule(Rule $rule): Collection
{
Log::debug(sprintf('findNonStrictRule(#%d)', $rule->id));
@@ -306,44 +278,123 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
- * @throws FireflyException
+ * Finds the transactions a strict rule will execute on.
*/
- public function fire(): void
+ private function findStrictRule(Rule $rule): Collection
{
- $this->resultCount = [];
- Log::debug('SearchRuleEngine::fire()!');
+ Log::debug(sprintf('Now in findStrictRule(#%d)', $rule->id ?? 0));
+ $searchArray = [];
+ $triggers = [];
+ if ($this->refreshTriggers) {
+ $triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->get();
+ }
+ if (!$this->refreshTriggers) {
+ $triggers = $rule->ruleTriggers;
+ }
- // if rules and no rule groups, file each rule separately.
- if (0 !== $this->rules->count()) {
- Log::debug(sprintf('SearchRuleEngine:: found %d rule(s) to fire.', $this->rules->count()));
+ /** @var RuleTrigger $ruleTrigger */
+ foreach ($triggers as $ruleTrigger) {
+ if (false === $ruleTrigger->active) {
+ continue;
+ }
+ $contextSearch = $ruleTrigger->trigger_type;
+ if (str_starts_with((string) $ruleTrigger->trigger_type, '-')) {
+ $contextSearch = substr((string) $ruleTrigger->trigger_type, 1);
+ }
- /** @var Rule $rule */
- foreach ($this->rules as $rule) { // @phpstan-ignore-line
- $result = $this->fireRule($rule);
- if ($result && true === $rule->stop_processing) {
- Log::debug(sprintf(
- 'Rule #%d has triggered and executed, but calls to stop processing. Since not in the context of a group, do not stop.',
- $rule->id
- ));
- }
- if (false === $result && true === $rule->stop_processing) {
- Log::debug(sprintf('Rule #%d has triggered and changed nothing, but calls to stop processing. Do not stop.', $rule->id));
- }
+ // if the trigger needs no context, value is different:
+ $needsContext = (bool) (config(sprintf('search.operators.%s.needs_context', $contextSearch)) ?? true);
+ if (false === $needsContext) {
+ Log::debug(sprintf('SearchRuleEngine:: add a rule trigger (no context): %s:true', $ruleTrigger->trigger_type));
+ $searchArray[$ruleTrigger->trigger_type][] = 'true';
}
- Log::debug('SearchRuleEngine:: done processing all rules!');
+ if ($needsContext) {
+ Log::debug(sprintf('SearchRuleEngine:: add a rule trigger (context): %s:"%s"', $ruleTrigger->trigger_type, $ruleTrigger->trigger_value));
+ $searchArray[$ruleTrigger->trigger_type][] = sprintf('"%s"', $ruleTrigger->trigger_value);
+ }
+ }
- return;
+ // add local operators:
+ foreach ($this->operators as $operator) {
+ Log::debug(sprintf('SearchRuleEngine:: add local added operator: %s:"%s"', $operator['type'], $operator['value']));
+ $searchArray[$operator['type']][] = sprintf('"%s"', $operator['value']);
+ }
+ $date = today(config('app.timezone'));
+ if ($this->hasSpecificJournalTrigger($searchArray)) {
+ $date = $this->setDateFromJournalTrigger($searchArray);
}
- if (0 !== $this->groups->count()) {
- Log::debug(sprintf('SearchRuleEngine:: found %d rule group(s) to fire.', $this->groups->count()));
- // fire each group:
- /** @var RuleGroup $group */
- foreach ($this->groups as $group) { // @phpstan-ignore-line
- $this->fireGroup($group);
+ // build and run the search engine.
+ $searchEngine = app(SearchInterface::class);
+ $searchEngine->setUser($this->user);
+ $searchEngine->setPage(1);
+ $searchEngine->setLimit(31337);
+ $searchEngine->setDate($date);
+ Log::debug('Search array', $searchArray);
+ foreach ($searchArray as $type => $searches) {
+ foreach ($searches as $value) {
+ $query = sprintf('%s:%s', $type, $value);
+ Log::debug(sprintf('SearchRuleEngine:: add query "%s"', $query));
+ $searchEngine->parseQuery($query);
}
}
- Log::debug('SearchRuleEngine:: done processing all rules!');
+
+ $result = $searchEngine->searchTransactions();
+
+ return $result->getCollection();
+ }
+
+ /**
+ * @throws FireflyException
+ */
+ private function fireGroup(RuleGroup $group): void
+ {
+ $rules = [];
+ if ($group->relationLoaded('rules')) {
+ Log::debug('Group rules have been pre-loaded, do not reload them.');
+ $rules = $group->rules;
+ }
+ if (!$group->relationLoaded('rules')) {
+ Log::debug('Group rules have NOT been pre-loaded, load them NOW.');
+ $rules = $group
+ ->rules()
+ ->orderBy('rules.order', 'ASC')
+ // ->leftJoin('rule_triggers', 'rules.id', '=', 'rule_triggers.rule_id')
+ // ->where('rule_triggers.trigger_type', 'user_action')
+ // ->where('rule_triggers.trigger_value', 'store-journal')
+ ->where('rules.active', true)
+ ->get(['rules.*'])
+ ;
+ }
+ Log::debug(sprintf('Going to fire group #%d with %d rule(s)', $group->id, $rules->count()));
+
+ /** @var Rule $rule */
+ foreach ($rules as $rule) {
+ Log::debug(sprintf('Going to fire rule #%d with order #%d from group #%d', $rule->id, $rule->order, $group->id));
+ $result = $this->fireRule($rule);
+ if ($result && true === $rule->stop_processing) {
+ Log::debug(sprintf('The rule was triggered and rule->stop_processing = true, so group #%d will stop processing further rules.', $group->id));
+
+ return;
+ }
+ }
+ Log::debug(sprintf('Done with rule group #%d.', $group->id));
+ }
+
+ /**
+ * Return true if the rule is fired (the collection is larger than zero).
+ *
+ * @throws FireflyException
+ */
+ private function fireNonStrictRule(Rule $rule): bool
+ {
+ Log::debug(sprintf('SearchRuleEngine::fireNonStrictRule(%d)!', $rule->id));
+ $collection = $this->findNonStrictRule($rule);
+
+ $this->processResults($rule, $collection);
+ Log::debug(sprintf('SearchRuleEngine:: Done processing non-strict rule #%d', $rule->id));
+
+ return $collection->count() > 0;
}
/**
@@ -393,48 +444,41 @@ class SearchRuleEngine implements RuleEngineInterface
}
/**
- * @throws FireflyException
+ * Search in the triggers of this particular search and if it contains
+ * one search operator for "journal_id" it means the date ranges
+ * in the search may need to be updated.
*/
- private function processResults(Rule $rule, Collection $collection): void
+ private function hasSpecificJournalTrigger(array $array): bool
{
- Log::debug(sprintf('SearchRuleEngine:: Going to process %d results.', $collection->count()));
-
- /** @var array $group */
- foreach ($collection as $group) {
- $this->processTransactionGroup($rule, $group);
+ Log::debug('Now in hasSpecificJournalTrigger.');
+ $journalTrigger = false;
+ $dateTrigger = false;
+ foreach ($array as $triggerName => $values) {
+ if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
+ Log::debug('Found a journal_id trigger with 1 journal, true.');
+ $journalTrigger = true;
+ }
+ if (in_array($triggerName, ['date_is', 'date', 'on', 'date_before', 'before', 'date_after', 'after'], true)) {
+ Log::debug('Found a date related trigger, set to true.');
+ $dateTrigger = true;
+ }
}
- }
-
- /**
- * @throws FireflyException
- */
- private function processTransactionGroup(Rule $rule, array $group): void
- {
- Log::debug(sprintf('SearchRuleEngine:: Will now execute actions on transaction group #%d', $group['id']));
+ $result = $journalTrigger && $dateTrigger;
+ Log::debug(sprintf('Result of hasSpecificJournalTrigger is %s.', var_export($result, true)));
- /** @var array $transaction */
- foreach ($group['transactions'] as $transaction) {
- $this->processTransactionJournal($rule, $transaction);
- }
+ return $result;
}
/**
* @throws FireflyException
*/
- private function processTransactionJournal(Rule $rule, array $transaction): void
+ private function processResults(Rule $rule, Collection $collection): void
{
- Log::debug(sprintf('SearchRuleEngine:: Will now execute actions on transaction journal #%d', $transaction['transaction_journal_id']));
- $actions = $rule->ruleActions()->orderBy('order', 'ASC')->get();
+ Log::debug(sprintf('SearchRuleEngine:: Going to process %d results.', $collection->count()));
- /** @var RuleAction $ruleAction */
- foreach ($actions as $ruleAction) {
- if (false === $ruleAction->active) {
- continue;
- }
- $break = $this->processRuleAction($ruleAction, $transaction);
- if ($break) {
- break;
- }
+ /** @var array $group */
+ foreach ($collection as $group) {
+ $this->processTransactionGroup($rule, $group);
}
}
@@ -474,106 +518,62 @@ class SearchRuleEngine implements RuleEngineInterface
return false;
}
- private function addNotes(array $transaction): array
- {
- $transaction['notes'] = '';
- $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id'])
- ->where('noteable_type', TransactionJournal::class)
- ->first(['notes.*'])
- ;
- if (null !== $dbNote) {
- $transaction['notes'] = $dbNote->text;
- }
- Log::debug(sprintf('Notes of journal #%d filled in.', $transaction['transaction_journal_id']));
-
- return $transaction;
- }
-
/**
- * Return true if the rule is fired (the collection is larger than zero).
- *
* @throws FireflyException
*/
- private function fireNonStrictRule(Rule $rule): bool
+ private function processTransactionGroup(Rule $rule, array $group): void
{
- Log::debug(sprintf('SearchRuleEngine::fireNonStrictRule(%d)!', $rule->id));
- $collection = $this->findNonStrictRule($rule);
-
- $this->processResults($rule, $collection);
- Log::debug(sprintf('SearchRuleEngine:: Done processing non-strict rule #%d', $rule->id));
+ Log::debug(sprintf('SearchRuleEngine:: Will now execute actions on transaction group #%d', $group['id']));
- return $collection->count() > 0;
+ /** @var array $transaction */
+ foreach ($group['transactions'] as $transaction) {
+ $this->processTransactionJournal($rule, $transaction);
+ }
}
/**
* @throws FireflyException
*/
- private function fireGroup(RuleGroup $group): void
+ private function processTransactionJournal(Rule $rule, array $transaction): void
{
- $rules = [];
- if ($group->relationLoaded('rules')) {
- Log::debug('Group rules have been pre-loaded, do not reload them.');
- $rules = $group->rules;
- }
- if (!$group->relationLoaded('rules')) {
- Log::debug('Group rules have NOT been pre-loaded, load them NOW.');
- $rules = $group
- ->rules()
- ->orderBy('rules.order', 'ASC')
- // ->leftJoin('rule_triggers', 'rules.id', '=', 'rule_triggers.rule_id')
- // ->where('rule_triggers.trigger_type', 'user_action')
- // ->where('rule_triggers.trigger_value', 'store-journal')
- ->where('rules.active', true)
- ->get(['rules.*'])
- ;
- }
- Log::debug(sprintf('Going to fire group #%d with %d rule(s)', $group->id, $rules->count()));
-
- /** @var Rule $rule */
- foreach ($rules as $rule) {
- Log::debug(sprintf('Going to fire rule #%d with order #%d from group #%d', $rule->id, $rule->order, $group->id));
- $result = $this->fireRule($rule);
- if ($result && true === $rule->stop_processing) {
- Log::debug(sprintf('The rule was triggered and rule->stop_processing = true, so group #%d will stop processing further rules.', $group->id));
+ Log::debug(sprintf('SearchRuleEngine:: Will now execute actions on transaction journal #%d', $transaction['transaction_journal_id']));
+ $actions = $rule->ruleActions()->orderBy('order', 'ASC')->get();
- return;
+ /** @var RuleAction $ruleAction */
+ foreach ($actions as $ruleAction) {
+ if (false === $ruleAction->active) {
+ continue;
+ }
+ $break = $this->processRuleAction($ruleAction, $transaction);
+ if ($break) {
+ break;
}
}
- Log::debug(sprintf('Done with rule group #%d.', $group->id));
}
- /**
- * Return the number of changed transactions from the previous "fire" action.
- */
- public function getResults(): int
- {
- return count($this->resultCount);
- }
-
- public function setRefreshTriggers(bool $refreshTriggers): void
- {
- $this->refreshTriggers = $refreshTriggers;
- }
-
- public function setRuleGroups(Collection $ruleGroups): void
+ private function setDateFromJournalTrigger(array $array): Carbon
{
- Log::debug(__METHOD__);
- foreach ($ruleGroups as $group) {
- if ($group instanceof RuleGroup) {
- Log::debug(sprintf('Adding a rule group to the SearchRuleEngine: #%d ("%s")', $group->id, $group->title));
- $this->groups->push($group);
+ Log::debug('Now in setDateFromJournalTrigger()');
+ $journalId = 0;
+ foreach ($array as $triggerName => $values) {
+ if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
+ $journalId = (int) trim($values[0] ?? '"0"', '"'); // follows format "123".
+ Log::debug(sprintf('Found journal ID #%d', $journalId));
}
}
- }
+ if (0 !== $journalId) {
+ $repository = app(JournalRepositoryInterface::class);
+ $repository->setUser($this->user);
+ $journal = $repository->find($journalId);
+ if (null !== $journal) {
+ $date = $journal->date;
+ Log::debug(sprintf('Found journal #%d with date %s.', $journal->id, $journal->date->format('Y-m-d')));
- public function setRules(Collection $rules): void
- {
- Log::debug(__METHOD__);
- foreach ($rules as $rule) {
- if ($rule instanceof Rule) {
- Log::debug(sprintf('Adding a rule to the SearchRuleEngine: #%d ("%s")', $rule->id, $rule->title));
- $this->rules->push($rule);
+ return $date;
}
}
+ Log::debug('Found no journal, return default date.');
+
+ return today(config('app.timezone'));
}
}
diff --git a/app/TransactionRules/Expressions/ActionExpression.php b/app/TransactionRules/Expressions/ActionExpression.php
index 1cf73f613d..88eb7b7634 100644
--- a/app/TransactionRules/Expressions/ActionExpression.php
+++ b/app/TransactionRules/Expressions/ActionExpression.php
@@ -96,38 +96,13 @@ class ActionExpression
$this->validationError = $this->validate();
}
- private function isExpression(string $expr): bool
- {
- return str_starts_with($expr, '=') && strlen($expr) > 1;
- }
-
- private function validate(): ?SyntaxError
- {
- if (!$this->isExpression) {
- return null;
- }
-
- try {
- $this->lint();
-
- return null;
- } catch (SyntaxError $e) {
- return $e;
- }
- }
-
- private function lint(): void
+ public function evaluate(array $journal): string
{
if (!$this->isExpression) {
- return;
+ return $this->expr;
}
- $this->lintExpression(substr($this->expr, 1));
- }
-
- private function lintExpression(string $expr): void
- {
- $this->expressionLanguage->lint($expr, self::$NAMES);
+ return $this->evaluateExpression(substr($this->expr, 1), $journal);
}
public function getValidationError(): ?SyntaxError
@@ -152,12 +127,37 @@ class ActionExpression
return (string) $result;
}
- public function evaluate(array $journal): string
+ private function isExpression(string $expr): bool
+ {
+ return str_starts_with($expr, '=') && strlen($expr) > 1;
+ }
+
+ private function lint(): void
{
if (!$this->isExpression) {
- return $this->expr;
+ return;
}
- return $this->evaluateExpression(substr($this->expr, 1), $journal);
+ $this->lintExpression(substr($this->expr, 1));
+ }
+
+ private function lintExpression(string $expr): void
+ {
+ $this->expressionLanguage->lint($expr, self::$NAMES);
+ }
+
+ private function validate(): ?SyntaxError
+ {
+ if (!$this->isExpression) {
+ return null;
+ }
+
+ try {
+ $this->lint();
+
+ return null;
+ } catch (SyntaxError $e) {
+ return $e;
+ }
}
}
diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php
index 535ac867e3..1658167ab0 100644
--- a/app/Transformers/AccountTransformer.php
+++ b/app/Transformers/AccountTransformer.php
@@ -192,6 +192,18 @@ class AccountTransformer extends AbstractTransformer
return [$creditCardType, $monthlyPaymentDate];
}
+ private function getInterest(Account $account, string $accountType): array
+ {
+ $interest = null;
+ $interestPeriod = null;
+ if ('liabilities' === $accountType) {
+ $interest = $account->meta['interest'] ?? null;
+ $interestPeriod = $account->meta['interest_period'] ?? null;
+ }
+
+ return [$interest, $interestPeriod];
+ }
+
private function getOpeningBalance(Account $account, string $accountType): ?string
{
$openingBalanceDate = null;
@@ -208,16 +220,4 @@ class AccountTransformer extends AbstractTransformer
return $openingBalanceDate;
}
-
- private function getInterest(Account $account, string $accountType): array
- {
- $interest = null;
- $interestPeriod = null;
- if ('liabilities' === $accountType) {
- $interest = $account->meta['interest'] ?? null;
- $interestPeriod = $account->meta['interest_period'] ?? null;
- }
-
- return [$interest, $interestPeriod];
- }
}
diff --git a/app/Transformers/RuleTransformer.php b/app/Transformers/RuleTransformer.php
index 1c37d87cb3..b81b42437a 100644
--- a/app/Transformers/RuleTransformer.php
+++ b/app/Transformers/RuleTransformer.php
@@ -73,6 +73,28 @@ class RuleTransformer extends AbstractTransformer
];
}
+ private function actions(Rule $rule): array
+ {
+ $result = [];
+ $actions = $this->ruleRepository->getRuleActions($rule);
+
+ /** @var RuleAction $ruleAction */
+ foreach ($actions as $ruleAction) {
+ $result[] = [
+ 'id' => (string) $ruleAction->id,
+ 'created_at' => $ruleAction->created_at->toAtomString(),
+ 'updated_at' => $ruleAction->updated_at->toAtomString(),
+ 'type' => $ruleAction->action_type,
+ 'value' => $ruleAction->action_value,
+ 'order' => $ruleAction->order,
+ 'active' => $ruleAction->active,
+ 'stop_processing' => $ruleAction->stop_processing,
+ ];
+ }
+
+ return $result;
+ }
+
/**
* @throws FireflyException
*/
@@ -133,26 +155,4 @@ class RuleTransformer extends AbstractTransformer
return $result;
}
-
- private function actions(Rule $rule): array
- {
- $result = [];
- $actions = $this->ruleRepository->getRuleActions($rule);
-
- /** @var RuleAction $ruleAction */
- foreach ($actions as $ruleAction) {
- $result[] = [
- 'id' => (string) $ruleAction->id,
- 'created_at' => $ruleAction->created_at->toAtomString(),
- 'updated_at' => $ruleAction->updated_at->toAtomString(),
- 'type' => $ruleAction->action_type,
- 'value' => $ruleAction->action_value,
- 'order' => $ruleAction->order,
- 'active' => $ruleAction->active,
- 'stop_processing' => $ruleAction->stop_processing,
- ];
- }
-
- return $result;
- }
}
diff --git a/app/Transformers/TransactionGroupTransformer.php b/app/Transformers/TransactionGroupTransformer.php
index 27d7e07df4..e16b3dd03b 100644
--- a/app/Transformers/TransactionGroupTransformer.php
+++ b/app/Transformers/TransactionGroupTransformer.php
@@ -95,148 +95,141 @@ class TransactionGroupTransformer extends AbstractTransformer
];
}
- private function transformTransactions(NullArrayObject $data): array
- {
- $result = [];
- $transactions = $data['transactions'] ?? [];
- foreach ($transactions as $transaction) {
- $result[] = $this->transformTransaction($transaction);
- }
-
- return $result;
- }
-
/**
- * @SuppressWarnings("PHPMD.ExcessiveMethodLength")
+ * @throws FireflyException
*/
- private function transformTransaction(array $transaction): array
+ public function transformObject(TransactionGroup $group): array
{
- // amount:
- $amount = Steam::positive((string) ($transaction['amount'] ?? '0'));
- $foreignAmount = null;
- if (null !== $transaction['foreign_amount'] && '' !== $transaction['foreign_amount'] && 0 !== bccomp('0', (string) $transaction['foreign_amount'])) {
- $foreignAmount = Steam::positive($transaction['foreign_amount']);
- }
-
- // set primary amount to the normal amount if the currency matches.
- if ($transaction['primary_currency']['id'] ?? null === $transaction['currency_id']) {
- $transaction['pc_amount'] = $amount;
- }
+ try {
+ $result = [
+ 'id' => $group->id,
+ 'created_at' => $group->created_at->toAtomString(),
+ 'updated_at' => $group->updated_at->toAtomString(),
+ 'user' => $group->user_id,
+ 'group_title' => $group->title,
+ 'transactions' => $this->transformJournals($group->transactionJournals),
+ 'links' => [['rel' => 'self', 'uri' => '/transactions/'.$group->id]],
+ ];
+ } catch (FireflyException $e) {
+ Log::error($e->getMessage());
+ Log::error($e->getTraceAsString());
- if (array_key_exists('pc_amount', $transaction) && null !== $transaction['pc_amount']) {
- $transaction['pc_amount'] = Steam::positive($transaction['pc_amount']);
+ throw new FireflyException(sprintf('Transaction group #%d is broken. Please check out your log files.', $group->id), 0, $e);
}
- $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionTypeEnum::WITHDRAWAL->value);
-
- // must be 0 (int) or NULL
- $recurrenceTotal = $transaction['meta']['recurrence_total'] ?? null;
- $recurrenceTotal = null !== $recurrenceTotal ? (int) $recurrenceTotal : null;
- $recurrenceCount = $transaction['meta']['recurrence_count'] ?? null;
- $recurrenceCount = null !== $recurrenceCount ? (int) $recurrenceCount : null;
- return [
- 'user' => (string) $transaction['user_id'],
- 'transaction_journal_id' => (string) $transaction['transaction_journal_id'],
- 'type' => strtolower((string) $type),
- 'date' => $transaction['date']->toAtomString(),
- 'order' => $transaction['order'],
-
- // currency information, structured for 6.3.0.
- 'object_has_currency_setting' => true,
+ // do something else.
- 'currency_id' => (string) $transaction['currency_id'],
- 'currency_code' => $transaction['currency_code'],
- 'currency_name' => $transaction['currency_name'],
- 'currency_symbol' => $transaction['currency_symbol'],
- 'currency_decimal_places' => (int) $transaction['currency_decimal_places'],
+ return $result;
+ }
- 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null),
- 'foreign_currency_code' => $transaction['foreign_currency_code'],
- 'foreign_currency_name' => $transaction['foreign_currency_name'],
- 'foreign_currency_symbol' => $transaction['foreign_currency_symbol'],
- 'foreign_currency_decimal_places' => $transaction['foreign_currency_decimal_places'],
+ private function getAmount(string $amount): string
+ {
+ return Steam::positive($amount);
+ }
- 'primary_currency_id' => $transaction['primary_currency']['id'] ?? null,
- 'primary_currency_code' => $transaction['primary_currency']['code'] ?? null,
- 'primary_currency_name' => $transaction['primary_currency']['name'] ?? null,
- 'primary_currency_symbol' => $transaction['primary_currency']['symbol'] ?? null,
- 'primary_currency_decimal_places' => $transaction['primary_currency']['decimal_places'] ?? null,
+ private function getBill(?Bill $bill): array
+ {
+ $array = ['id' => null, 'name' => null];
+ if (!$bill instanceof Bill) {
+ return $array;
+ }
+ $array['id'] = (string) $bill->id;
+ $array['name'] = $bill->name;
- // amounts, structured for 6.3.0.
- 'amount' => $amount,
- 'pc_amount' => $transaction['pc_amount'] ?? null,
+ return $array;
+ }
- 'foreign_amount' => $foreignAmount,
- 'pc_foreign_amount' => null,
+ private function getBudget(?Budget $budget): array
+ {
+ $array = ['id' => null, 'name' => null];
+ if (!$budget instanceof Budget) {
+ return $array;
+ }
+ $array['id'] = $budget->id;
+ $array['name'] = $budget->name;
- 'source_balance_after' => $transaction['source_balance_after'] ?? null,
- 'pc_source_balance_after' => null,
+ return $array;
+ }
- // destination balance after
- 'destination_balance_after' => $transaction['destination_balance_after'] ?? null,
- 'pc_destination_balance_after' => null,
+ private function getCategory(?Category $category): array
+ {
+ $array = ['id' => null, 'name' => null];
+ if (!$category instanceof Category) {
+ return $array;
+ }
+ $array['id'] = $category->id;
+ $array['name'] = $category->name;
- 'source_balance_dirty' => $transaction['source_balance_dirty'],
- 'destination_balance_dirty' => $transaction['destination_balance_dirty'],
+ return $array;
+ }
- 'description' => $transaction['description'],
+ private function getDates(NullArrayObject $dates): array
+ {
+ $fields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date'];
+ $return = [];
+ foreach ($fields as $field) {
+ $return[$field] = null;
+ if (null !== $dates[$field]) {
+ $return[$field] = $dates[$field]->toAtomString();
+ }
+ }
- 'source_id' => (string) $transaction['source_account_id'],
- 'source_name' => $transaction['source_account_name'],
- 'source_iban' => $transaction['source_account_iban'],
- 'source_type' => $transaction['source_account_type'],
+ return $return;
+ }
- 'destination_id' => (string) $transaction['destination_account_id'],
- 'destination_name' => $transaction['destination_account_name'],
- 'destination_iban' => $transaction['destination_account_iban'],
- 'destination_type' => $transaction['destination_account_type'],
+ /**
+ * @throws FireflyException
+ */
+ private function getDestinationTransaction(TransactionJournal $journal): Transaction
+ {
+ $result = $journal->transactions->first(static fn (Transaction $transaction): bool => (float) $transaction->amount > 0);
+ if (null === $result) {
+ throw new FireflyException(sprintf('Journal #%d unexpectedly has no destination transaction.', $journal->id));
+ }
- 'budget_id' => $this->stringFromArray($transaction, 'budget_id', null),
- 'budget_name' => $transaction['budget_name'],
+ return $result;
+ }
- 'category_id' => $this->stringFromArray($transaction, 'category_id', null),
- 'category_name' => $transaction['category_name'],
+ private function getForeignAmount(?string $foreignAmount): ?string
+ {
+ if (null !== $foreignAmount && '' !== $foreignAmount && 0 !== bccomp('0', $foreignAmount)) {
+ return Steam::positive($foreignAmount);
+ }
- 'bill_id' => $this->stringFromArray($transaction, 'bill_id', null),
- 'bill_name' => $transaction['bill_name'],
- 'subscription_id' => $this->stringFromArray($transaction, 'bill_id', null),
- 'subscription_name' => $transaction['bill_name'],
+ return null;
+ }
- 'reconciled' => $transaction['reconciled'],
- 'notes' => $transaction['notes'],
- 'tags' => $transaction['tags'],
+ private function getForeignCurrency(?TransactionCurrency $currency): array
+ {
+ $array = ['id' => null, 'code' => null, 'symbol' => null, 'decimal_places' => null];
+ if (!$currency instanceof TransactionCurrency) {
+ return $array;
+ }
+ $array['id'] = $currency->id;
+ $array['code'] = $currency->code;
+ $array['symbol'] = $currency->symbol;
+ $array['decimal_places'] = $currency->decimal_places;
- 'internal_reference' => $transaction['meta']['internal_reference'] ?? null,
- 'external_id' => $transaction['meta']['external_id'] ?? null,
- 'original_source' => $transaction['meta']['original_source'] ?? null,
- 'recurrence_id' => $transaction['meta']['recurrence_id'] ?? null,
- 'recurrence_total' => $recurrenceTotal,
- 'recurrence_count' => $recurrenceCount,
- 'external_url' => $transaction['meta']['external_url'] ?? null,
- 'import_hash_v2' => $transaction['meta']['import_hash_v2'] ?? null,
+ return $array;
+ }
- 'sepa_cc' => $transaction['meta']['sepa_cc'] ?? null,
- 'sepa_ct_op' => $transaction['meta']['sepa_ct_op'] ?? null,
- 'sepa_ct_id' => $transaction['meta']['sepa_ct_id'] ?? null,
- 'sepa_db' => $transaction['meta']['sepa_db'] ?? null,
- 'sepa_country' => $transaction['meta']['sepa_country'] ?? null,
- 'sepa_ep' => $transaction['meta']['sepa_ep'] ?? null,
- 'sepa_ci' => $transaction['meta']['sepa_ci'] ?? null,
- 'sepa_batch_id' => $transaction['meta']['sepa_batch_id'] ?? null,
+ private function getLocation(TransactionJournal $journal): ?Location
+ {
+ /** @var null|Location */
+ return $journal->locations()->first();
+ }
- 'interest_date' => array_key_exists('interest_date', $transaction['meta_date']) ? $transaction['meta_date']['interest_date']->toW3CString() : null,
- 'book_date' => array_key_exists('book_date', $transaction['meta_date']) ? $transaction['meta_date']['book_date']->toW3CString() : null,
- 'process_date' => array_key_exists('process_date', $transaction['meta_date']) ? $transaction['meta_date']['process_date']->toW3CString() : null,
- 'due_date' => array_key_exists('due_date', $transaction['meta_date']) ? $transaction['meta_date']['due_date']->toW3CString() : null,
- 'payment_date' => array_key_exists('payment_date', $transaction['meta_date']) ? $transaction['meta_date']['payment_date']->toW3CString() : null,
- 'invoice_date' => array_key_exists('invoice_date', $transaction['meta_date']) ? $transaction['meta_date']['invoice_date']->toW3CString() : null,
+ /**
+ * @throws FireflyException
+ */
+ private function getSourceTransaction(TransactionJournal $journal): Transaction
+ {
+ $result = $journal->transactions->first(static fn (Transaction $transaction): bool => (float) $transaction->amount < 0);
+ if (null === $result) {
+ throw new FireflyException(sprintf('Journal #%d unexpectedly has no source transaction.', $journal->id));
+ }
- // location data
- 'longitude' => $transaction['location']['longitude'],
- 'latitude' => $transaction['location']['latitude'],
- 'zoom_level' => $transaction['location']['zoom_level'],
- 'has_attachments' => $transaction['attachment_count'] > 0,
- ];
+ return $result;
}
private function stringFromArray(array $array, string $key, ?string $default): ?string
@@ -258,48 +251,6 @@ class TransactionGroupTransformer extends AbstractTransformer
return $default;
}
- /**
- * @throws FireflyException
- */
- public function transformObject(TransactionGroup $group): array
- {
- try {
- $result = [
- 'id' => $group->id,
- 'created_at' => $group->created_at->toAtomString(),
- 'updated_at' => $group->updated_at->toAtomString(),
- 'user' => $group->user_id,
- 'group_title' => $group->title,
- 'transactions' => $this->transformJournals($group->transactionJournals),
- 'links' => [['rel' => 'self', 'uri' => '/transactions/'.$group->id]],
- ];
- } catch (FireflyException $e) {
- Log::error($e->getMessage());
- Log::error($e->getTraceAsString());
-
- throw new FireflyException(sprintf('Transaction group #%d is broken. Please check out your log files.', $group->id), 0, $e);
- }
-
- // do something else.
-
- return $result;
- }
-
- /**
- * @throws FireflyException
- */
- private function transformJournals(Collection $transactionJournals): array
- {
- $result = [];
-
- /** @var TransactionJournal $journal */
- foreach ($transactionJournals as $journal) {
- $result[] = $this->transformJournal($journal);
- }
-
- return $result;
- }
-
/**
* @throws FireflyException
*
@@ -412,110 +363,159 @@ class TransactionGroupTransformer extends AbstractTransformer
/**
* @throws FireflyException
*/
- private function getSourceTransaction(TransactionJournal $journal): Transaction
+ private function transformJournals(Collection $transactionJournals): array
{
- $result = $journal->transactions->first(static fn (Transaction $transaction): bool => (float) $transaction->amount < 0);
- if (null === $result) {
- throw new FireflyException(sprintf('Journal #%d unexpectedly has no source transaction.', $journal->id));
+ $result = [];
+
+ /** @var TransactionJournal $journal */
+ foreach ($transactionJournals as $journal) {
+ $result[] = $this->transformJournal($journal);
}
return $result;
}
/**
- * @throws FireflyException
+ * @SuppressWarnings("PHPMD.ExcessiveMethodLength")
*/
- private function getDestinationTransaction(TransactionJournal $journal): Transaction
+ private function transformTransaction(array $transaction): array
{
- $result = $journal->transactions->first(static fn (Transaction $transaction): bool => (float) $transaction->amount > 0);
- if (null === $result) {
- throw new FireflyException(sprintf('Journal #%d unexpectedly has no destination transaction.', $journal->id));
+ // amount:
+ $amount = Steam::positive((string) ($transaction['amount'] ?? '0'));
+ $foreignAmount = null;
+ if (null !== $transaction['foreign_amount'] && '' !== $transaction['foreign_amount'] && 0 !== bccomp('0', (string) $transaction['foreign_amount'])) {
+ $foreignAmount = Steam::positive($transaction['foreign_amount']);
}
- return $result;
- }
-
- private function getAmount(string $amount): string
- {
- return Steam::positive($amount);
- }
+ // set primary amount to the normal amount if the currency matches.
+ if ($transaction['primary_currency']['id'] ?? null === $transaction['currency_id']) {
+ $transaction['pc_amount'] = $amount;
+ }
- private function getForeignAmount(?string $foreignAmount): ?string
- {
- if (null !== $foreignAmount && '' !== $foreignAmount && 0 !== bccomp('0', $foreignAmount)) {
- return Steam::positive($foreignAmount);
+ if (array_key_exists('pc_amount', $transaction) && null !== $transaction['pc_amount']) {
+ $transaction['pc_amount'] = Steam::positive($transaction['pc_amount']);
}
+ $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionTypeEnum::WITHDRAWAL->value);
- return null;
- }
+ // must be 0 (int) or NULL
+ $recurrenceTotal = $transaction['meta']['recurrence_total'] ?? null;
+ $recurrenceTotal = null !== $recurrenceTotal ? (int) $recurrenceTotal : null;
+ $recurrenceCount = $transaction['meta']['recurrence_count'] ?? null;
+ $recurrenceCount = null !== $recurrenceCount ? (int) $recurrenceCount : null;
- private function getDates(NullArrayObject $dates): array
- {
- $fields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date'];
- $return = [];
- foreach ($fields as $field) {
- $return[$field] = null;
- if (null !== $dates[$field]) {
- $return[$field] = $dates[$field]->toAtomString();
- }
- }
+ return [
+ 'user' => (string) $transaction['user_id'],
+ 'transaction_journal_id' => (string) $transaction['transaction_journal_id'],
+ 'type' => strtolower((string) $type),
+ 'date' => $transaction['date']->toAtomString(),
+ 'order' => $transaction['order'],
- return $return;
- }
+ // currency information, structured for 6.3.0.
+ 'object_has_currency_setting' => true,
- private function getForeignCurrency(?TransactionCurrency $currency): array
- {
- $array = ['id' => null, 'code' => null, 'symbol' => null, 'decimal_places' => null];
- if (!$currency instanceof TransactionCurrency) {
- return $array;
- }
- $array['id'] = $currency->id;
- $array['code'] = $currency->code;
- $array['symbol'] = $currency->symbol;
- $array['decimal_places'] = $currency->decimal_places;
+ 'currency_id' => (string) $transaction['currency_id'],
+ 'currency_code' => $transaction['currency_code'],
+ 'currency_name' => $transaction['currency_name'],
+ 'currency_symbol' => $transaction['currency_symbol'],
+ 'currency_decimal_places' => (int) $transaction['currency_decimal_places'],
- return $array;
- }
+ 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null),
+ 'foreign_currency_code' => $transaction['foreign_currency_code'],
+ 'foreign_currency_name' => $transaction['foreign_currency_name'],
+ 'foreign_currency_symbol' => $transaction['foreign_currency_symbol'],
+ 'foreign_currency_decimal_places' => $transaction['foreign_currency_decimal_places'],
- private function getBudget(?Budget $budget): array
- {
- $array = ['id' => null, 'name' => null];
- if (!$budget instanceof Budget) {
- return $array;
- }
- $array['id'] = $budget->id;
- $array['name'] = $budget->name;
+ 'primary_currency_id' => $transaction['primary_currency']['id'] ?? null,
+ 'primary_currency_code' => $transaction['primary_currency']['code'] ?? null,
+ 'primary_currency_name' => $transaction['primary_currency']['name'] ?? null,
+ 'primary_currency_symbol' => $transaction['primary_currency']['symbol'] ?? null,
+ 'primary_currency_decimal_places' => $transaction['primary_currency']['decimal_places'] ?? null,
- return $array;
- }
+ // amounts, structured for 6.3.0.
+ 'amount' => $amount,
+ 'pc_amount' => $transaction['pc_amount'] ?? null,
- private function getCategory(?Category $category): array
- {
- $array = ['id' => null, 'name' => null];
- if (!$category instanceof Category) {
- return $array;
- }
- $array['id'] = $category->id;
- $array['name'] = $category->name;
+ 'foreign_amount' => $foreignAmount,
+ 'pc_foreign_amount' => null,
- return $array;
- }
+ 'source_balance_after' => $transaction['source_balance_after'] ?? null,
+ 'pc_source_balance_after' => null,
- private function getBill(?Bill $bill): array
- {
- $array = ['id' => null, 'name' => null];
- if (!$bill instanceof Bill) {
- return $array;
- }
- $array['id'] = (string) $bill->id;
- $array['name'] = $bill->name;
+ // destination balance after
+ 'destination_balance_after' => $transaction['destination_balance_after'] ?? null,
+ 'pc_destination_balance_after' => null,
- return $array;
+ 'source_balance_dirty' => $transaction['source_balance_dirty'],
+ 'destination_balance_dirty' => $transaction['destination_balance_dirty'],
+
+ 'description' => $transaction['description'],
+
+ 'source_id' => (string) $transaction['source_account_id'],
+ 'source_name' => $transaction['source_account_name'],
+ 'source_iban' => $transaction['source_account_iban'],
+ 'source_type' => $transaction['source_account_type'],
+
+ 'destination_id' => (string) $transaction['destination_account_id'],
+ 'destination_name' => $transaction['destination_account_name'],
+ 'destination_iban' => $transaction['destination_account_iban'],
+ 'destination_type' => $transaction['destination_account_type'],
+
+ 'budget_id' => $this->stringFromArray($transaction, 'budget_id', null),
+ 'budget_name' => $transaction['budget_name'],
+
+ 'category_id' => $this->stringFromArray($transaction, 'category_id', null),
+ 'category_name' => $transaction['category_name'],
+
+ 'bill_id' => $this->stringFromArray($transaction, 'bill_id', null),
+ 'bill_name' => $transaction['bill_name'],
+ 'subscription_id' => $this->stringFromArray($transaction, 'bill_id', null),
+ 'subscription_name' => $transaction['bill_name'],
+
+ 'reconciled' => $transaction['reconciled'],
+ 'notes' => $transaction['notes'],
+ 'tags' => $transaction['tags'],
+
+ 'internal_reference' => $transaction['meta']['internal_reference'] ?? null,
+ 'external_id' => $transaction['meta']['external_id'] ?? null,
+ 'original_source' => $transaction['meta']['original_source'] ?? null,
+ 'recurrence_id' => $transaction['meta']['recurrence_id'] ?? null,
+ 'recurrence_total' => $recurrenceTotal,
+ 'recurrence_count' => $recurrenceCount,
+ 'external_url' => $transaction['meta']['external_url'] ?? null,
+ 'import_hash_v2' => $transaction['meta']['import_hash_v2'] ?? null,
+
+ 'sepa_cc' => $transaction['meta']['sepa_cc'] ?? null,
+ 'sepa_ct_op' => $transaction['meta']['sepa_ct_op'] ?? null,
+ 'sepa_ct_id' => $transaction['meta']['sepa_ct_id'] ?? null,
+ 'sepa_db' => $transaction['meta']['sepa_db'] ?? null,
+ 'sepa_country' => $transaction['meta']['sepa_country'] ?? null,
+ 'sepa_ep' => $transaction['meta']['sepa_ep'] ?? null,
+ 'sepa_ci' => $transaction['meta']['sepa_ci'] ?? null,
+ 'sepa_batch_id' => $transaction['meta']['sepa_batch_id'] ?? null,
+
+ 'interest_date' => array_key_exists('interest_date', $transaction['meta_date']) ? $transaction['meta_date']['interest_date']->toW3CString() : null,
+ 'book_date' => array_key_exists('book_date', $transaction['meta_date']) ? $transaction['meta_date']['book_date']->toW3CString() : null,
+ 'process_date' => array_key_exists('process_date', $transaction['meta_date']) ? $transaction['meta_date']['process_date']->toW3CString() : null,
+ 'due_date' => array_key_exists('due_date', $transaction['meta_date']) ? $transaction['meta_date']['due_date']->toW3CString() : null,
+ 'payment_date' => array_key_exists('payment_date', $transaction['meta_date']) ? $transaction['meta_date']['payment_date']->toW3CString() : null,
+ 'invoice_date' => array_key_exists('invoice_date', $transaction['meta_date']) ? $transaction['meta_date']['invoice_date']->toW3CString() : null,
+
+ // location data
+ 'longitude' => $transaction['location']['longitude'],
+ 'latitude' => $transaction['location']['latitude'],
+ 'zoom_level' => $transaction['location']['zoom_level'],
+ 'has_attachments' => $transaction['attachment_count'] > 0,
+ ];
}
- private function getLocation(TransactionJournal $journal): ?Location
+ private function transformTransactions(NullArrayObject $data): array
{
- /** @var null|Location */
- return $journal->locations()->first();
+ $result = [];
+ $transactions = $data['transactions'] ?? [];
+ foreach ($transactions as $transaction) {
+ $result[] = $this->transformTransaction($transaction);
+ }
+
+ return $result;
}
}
diff --git a/app/Transformers/UserGroupTransformer.php b/app/Transformers/UserGroupTransformer.php
index 63be3fe689..bff85bd283 100644
--- a/app/Transformers/UserGroupTransformer.php
+++ b/app/Transformers/UserGroupTransformer.php
@@ -73,26 +73,6 @@ class UserGroupTransformer extends AbstractTransformer
return $objects;
}
- private function mergeMemberships(): void
- {
- $new = [];
- foreach ($this->memberships as $groupId => $members) {
- $new[$groupId] ??= [];
-
- foreach ($members as $member) {
- $mail = $member['user_email'];
- $new[$groupId][$mail] ??= [
- 'user_id' => (string) $member['user_id'],
- 'user_email' => $member['user_email'],
- 'you' => $member['you'],
- 'roles' => [],
- ];
- $new[$groupId][$mail]['roles'][] = $member['role'];
- }
- }
- $this->memberships = $new;
- }
-
/**
* Transform the user group.
*/
@@ -117,4 +97,24 @@ class UserGroupTransformer extends AbstractTransformer
// if the user has a specific role in this group, then collect the memberships.
}
+
+ private function mergeMemberships(): void
+ {
+ $new = [];
+ foreach ($this->memberships as $groupId => $members) {
+ $new[$groupId] ??= [];
+
+ foreach ($members as $member) {
+ $mail = $member['user_email'];
+ $new[$groupId][$mail] ??= [
+ 'user_id' => (string) $member['user_id'],
+ 'user_email' => $member['user_email'],
+ 'you' => $member['you'],
+ 'roles' => [],
+ ];
+ $new[$groupId][$mail]['roles'][] = $member['role'];
+ }
+ }
+ $this->memberships = $new;
+ }
}
diff --git a/app/User.php b/app/User.php
index bc1f661b6e..e29d75d038 100644
--- a/app/User.php
+++ b/app/User.php
@@ -233,6 +233,19 @@ class User extends Authenticatable
return 'objectguid';
}
+ public function groupMemberships(): HasMany
+ {
+ return $this->hasMany(GroupMembership::class)->with(['userGroup', 'userRole']);
+ }
+
+ /**
+ * This method refers to the "global" role a user can have, outside of any group they may be part of.
+ */
+ public function hasRole(string $role): bool
+ {
+ return 1 === $this->roles()->where('name', $role)->count();
+ }
+
/**
* Does the user have role X in group Y, or is the user the group owner of has full rights to the group?
*
@@ -246,73 +259,6 @@ class User extends Authenticatable
return $this->hasAnyRoleInGroup($userGroup, $roles);
}
- /**
- * Does the user have role X, Y or Z in group A?
- */
- private function hasAnyRoleInGroup(UserGroup $userGroup, array $roles): bool
- {
- Log::debug(sprintf('in hasAnyRoleInGroup(%s)', implode(', ', $roles)));
-
- /** @var Collection $dbRoles */
- $dbRoles = UserRole::whereIn('title', $roles)->get();
- if (0 === $dbRoles->count()) {
- Log::error(sprintf('Could not find role(s): %s. Probably migration mishap.', implode(', ', $roles)));
-
- return false;
- }
- $dbRolesIds = $dbRoles->pluck('id')->toArray();
- $dbRolesTitles = $dbRoles->pluck('title')->toArray();
-
- $groupMemberships = $this
- ->groupMemberships()
- ->whereIn('user_role_id', $dbRolesIds)
- ->where('user_group_id', $userGroup->id)
- ->get()
- ;
- if (0 === $groupMemberships->count()) {
- Log::error(sprintf(
- 'User #%d "%s" does not have roles %s in user group #%d "%s"',
- $this->id,
- $this->email,
- implode(', ', $roles),
- $userGroup->id,
- $userGroup->title
- ));
-
- return false;
- }
- foreach ($groupMemberships as $membership) {
- Log::debug(sprintf(
- 'User #%d "%s" has role "%s" in user group #%d "%s"',
- $this->id,
- $this->email,
- $membership->userRole->title,
- $userGroup->id,
- $userGroup->title
- ));
- if (in_array($membership->userRole->title, $dbRolesTitles, true)) {
- Log::debug(sprintf('Return true, found role "%s"', $membership->userRole->title));
-
- return true;
- }
- }
- Log::error(sprintf(
- 'User #%d "%s" does not have roles %s in user group #%d "%s"',
- $this->id,
- $this->email,
- implode(', ', $roles),
- $userGroup->id,
- $userGroup->title
- ));
-
- return false;
- }
-
- public function groupMemberships(): HasMany
- {
- return $this->hasMany(GroupMembership::class)->with(['userGroup', 'userRole']);
- }
-
/**
* Does the user have role X in group Y?
*/
@@ -353,6 +299,14 @@ class User extends Authenticatable
return $this->hasMany(Recurrence::class);
}
+ /**
+ * Link to roles.
+ */
+ public function roles(): BelongsToMany
+ {
+ return $this->belongsToMany(Role::class);
+ }
+
/**
* Get the notification routing information for the given driver.
*
@@ -384,22 +338,6 @@ class User extends Authenticatable
};
}
- /**
- * This method refers to the "global" role a user can have, outside of any group they may be part of.
- */
- public function hasRole(string $role): bool
- {
- return 1 === $this->roles()->where('name', $role)->count();
- }
-
- /**
- * Link to roles.
- */
- public function roles(): BelongsToMany
- {
- return $this->belongsToMany(Role::class);
- }
-
public function routeNotificationForPushover(): PushoverReceiver
{
$appToken = (string) Preferences::getEncrypted('pushover_app_token', '')->data;
@@ -540,4 +478,66 @@ class User extends Authenticatable
{
return ['created_at' => 'datetime', 'updated_at' => 'datetime', 'blocked' => 'boolean'];
}
+
+ /**
+ * Does the user have role X, Y or Z in group A?
+ */
+ private function hasAnyRoleInGroup(UserGroup $userGroup, array $roles): bool
+ {
+ Log::debug(sprintf('in hasAnyRoleInGroup(%s)', implode(', ', $roles)));
+
+ /** @var Collection $dbRoles */
+ $dbRoles = UserRole::whereIn('title', $roles)->get();
+ if (0 === $dbRoles->count()) {
+ Log::error(sprintf('Could not find role(s): %s. Probably migration mishap.', implode(', ', $roles)));
+
+ return false;
+ }
+ $dbRolesIds = $dbRoles->pluck('id')->toArray();
+ $dbRolesTitles = $dbRoles->pluck('title')->toArray();
+
+ $groupMemberships = $this
+ ->groupMemberships()
+ ->whereIn('user_role_id', $dbRolesIds)
+ ->where('user_group_id', $userGroup->id)
+ ->get()
+ ;
+ if (0 === $groupMemberships->count()) {
+ Log::error(sprintf(
+ 'User #%d "%s" does not have roles %s in user group #%d "%s"',
+ $this->id,
+ $this->email,
+ implode(', ', $roles),
+ $userGroup->id,
+ $userGroup->title
+ ));
+
+ return false;
+ }
+ foreach ($groupMemberships as $membership) {
+ Log::debug(sprintf(
+ 'User #%d "%s" has role "%s" in user group #%d "%s"',
+ $this->id,
+ $this->email,
+ $membership->userRole->title,
+ $userGroup->id,
+ $userGroup->title
+ ));
+ if (in_array($membership->userRole->title, $dbRolesTitles, true)) {
+ Log::debug(sprintf('Return true, found role "%s"', $membership->userRole->title));
+
+ return true;
+ }
+ }
+ Log::error(sprintf(
+ 'User #%d "%s" does not have roles %s in user group #%d "%s"',
+ $this->id,
+ $this->email,
+ implode(', ', $roles),
+ $userGroup->id,
+ $userGroup->title
+ ));
+
+ return false;
+ }
}
diff --git a/app/Validation/Account/DepositValidation.php b/app/Validation/Account/DepositValidation.php
index 068a9c0217..31d12a6ded 100644
--- a/app/Validation/Account/DepositValidation.php
+++ b/app/Validation/Account/DepositValidation.php
@@ -34,6 +34,10 @@ use Illuminate\Support\Facades\Log;
*/
trait DepositValidation
{
+ abstract protected function canCreateTypes(array $accountTypes): bool;
+
+ abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
+
protected function validateDepositDestination(array $array): bool
{
$result = null;
@@ -77,10 +81,6 @@ trait DepositValidation
return $result;
}
- abstract protected function canCreateTypes(array $accountTypes): bool;
-
- abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
-
/**
* Pretty complex unfortunately.
*
diff --git a/app/Validation/Account/OBValidation.php b/app/Validation/Account/OBValidation.php
index 526141833a..2b63ab554c 100644
--- a/app/Validation/Account/OBValidation.php
+++ b/app/Validation/Account/OBValidation.php
@@ -34,6 +34,8 @@ use Illuminate\Support\Facades\Log;
*/
trait OBValidation
{
+ abstract protected function canCreateTypes(array $accountTypes): bool;
+
protected function validateOBDestination(array $array): bool
{
$result = null;
@@ -75,8 +77,6 @@ trait OBValidation
return $result;
}
- abstract protected function canCreateTypes(array $accountTypes): bool;
-
/**
* Source of an opening balance can either be an asset account
* or an "initial balance account". The latter can be created.
diff --git a/app/Validation/Account/TransferValidation.php b/app/Validation/Account/TransferValidation.php
index c4aeeb2dc1..35a4f2dfff 100644
--- a/app/Validation/Account/TransferValidation.php
+++ b/app/Validation/Account/TransferValidation.php
@@ -32,6 +32,10 @@ use Illuminate\Support\Facades\Log;
*/
trait TransferValidation
{
+ abstract protected function canCreateTypes(array $accountTypes): bool;
+
+ abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
+
protected function validateTransferDestination(array $array): bool
{
$accountId = $array['id'] ?? null;
@@ -69,10 +73,6 @@ trait TransferValidation
return true;
}
- abstract protected function canCreateTypes(array $accountTypes): bool;
-
- abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
-
protected function validateTransferSource(array $array): bool
{
$accountId = $array['id'] ?? null;
diff --git a/app/Validation/Account/WithdrawalValidation.php b/app/Validation/Account/WithdrawalValidation.php
index 668037010d..5efc68d6f4 100644
--- a/app/Validation/Account/WithdrawalValidation.php
+++ b/app/Validation/Account/WithdrawalValidation.php
@@ -33,6 +33,10 @@ use Illuminate\Support\Facades\Log;
*/
trait WithdrawalValidation
{
+ abstract protected function canCreateTypes(array $accountTypes): bool;
+
+ abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
+
protected function validateGenericSource(array $array): bool
{
$accountId = $array['id'] ?? null;
@@ -70,10 +74,6 @@ trait WithdrawalValidation
return true;
}
- abstract protected function canCreateTypes(array $accountTypes): bool;
-
- abstract protected function findExistingAccount(array $validTypes, array $data): ?Account;
-
protected function validateWithdrawalDestination(array $array): bool
{
$accountId = $array['id'] ?? null;
diff --git a/app/Validation/AccountValidator.php b/app/Validation/AccountValidator.php
index 166a577d08..e55238c40f 100644
--- a/app/Validation/AccountValidator.php
+++ b/app/Validation/AccountValidator.php
@@ -73,26 +73,26 @@ class AccountValidator
return $this->source;
}
- public function setSource(?Account $account): void
+ public function setDestination(?Account $account): void
{
if (!$account instanceof Account) {
- Log::debug('AccountValidator source is set to NULL');
+ Log::debug('AccountValidator destination is set to NULL');
}
if ($account instanceof Account) {
- Log::debug(sprintf('AccountValidator source is set to #%d: "%s" (%s)', $account->id, $account->name, $account->accountType?->type));
+ Log::debug(sprintf('AccountValidator destination is set to #%d: "%s" (%s)', $account->id, $account->name, $account->accountType->type));
}
- $this->source = $account;
+ $this->destination = $account;
}
- public function setDestination(?Account $account): void
+ public function setSource(?Account $account): void
{
if (!$account instanceof Account) {
- Log::debug('AccountValidator destination is set to NULL');
+ Log::debug('AccountValidator source is set to NULL');
}
if ($account instanceof Account) {
- Log::debug(sprintf('AccountValidator destination is set to #%d: "%s" (%s)', $account->id, $account->name, $account->accountType->type));
+ Log::debug(sprintf('AccountValidator source is set to #%d: "%s" (%s)', $account->id, $account->name, $account->accountType?->type));
}
- $this->destination = $account;
+ $this->source = $account;
}
public function setTransactionType(string $transactionType): void
@@ -210,6 +210,18 @@ class AccountValidator
return $result;
}
+ protected function canCreateType(string $accountType): bool
+ {
+ $canCreate = [
+ AccountTypeEnum::EXPENSE->value,
+ AccountTypeEnum::REVENUE->value,
+ AccountTypeEnum::INITIAL_BALANCE->value,
+ AccountTypeEnum::LIABILITY_CREDIT->value,
+ ];
+
+ return in_array($accountType, $canCreate, true);
+ }
+
protected function canCreateTypes(array $accountTypes): bool
{
Log::debug('Can we create any of these types?', $accountTypes);
@@ -227,18 +239,6 @@ class AccountValidator
return false;
}
- protected function canCreateType(string $accountType): bool
- {
- $canCreate = [
- AccountTypeEnum::EXPENSE->value,
- AccountTypeEnum::REVENUE->value,
- AccountTypeEnum::INITIAL_BALANCE->value,
- AccountTypeEnum::LIABILITY_CREDIT->value,
- ];
-
- return in_array($accountType, $canCreate, true);
- }
-
/**
* It's a long and fairly complex method, but I don't mind.
*
diff --git a/app/Validation/CurrencyValidation.php b/app/Validation/CurrencyValidation.php
index d663dc95d8..b0a59a254a 100644
--- a/app/Validation/CurrencyValidation.php
+++ b/app/Validation/CurrencyValidation.php
@@ -36,6 +36,8 @@ trait CurrencyValidation
{
public const string TEST = 'Test';
+ abstract protected function getTransactionsArray(Validator $validator): array;
+
/**
* If the transactions contain foreign amounts, there must also be foreign currency information.
*/
@@ -94,6 +96,4 @@ trait CurrencyValidation
}
}
}
-
- abstract protected function getTransactionsArray(Validator $validator): array;
}
diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php
index 641bb73668..46582c6d07 100644
--- a/app/Validation/FireflyValidator.php
+++ b/app/Validation/FireflyValidator.php
@@ -576,94 +576,6 @@ class FireflyValidator extends Validator
return $this->validateByAccountName($value);
}
- private function validateAccountAnonymously(): bool
- {
- if (!array_key_exists('user_id', $this->data)) {
- return false;
- }
-
- /** @var User $user */
- $user = User::find($this->data['user_id']);
- $type = AccountType::find($this->data['account_type_id'])->first();
- $value = $this->data['name'];
-
- /** @var null|Account $result */
- $result = $user->accounts()->where('account_type_id', $type->id)->where('name', $value)->first();
-
- return null === $result;
- }
-
- private function validateByAccountTypeString(string $value, array $parameters, string $type): bool
- {
- /** @var null|array $search */
- $search = Config::get('firefly.accountTypeByIdentifier.'.$type);
-
- if (null === $search) {
- return false;
- }
-
- $accountTypes = AccountType::whereIn('type', $search)->get();
- $ignore = (int) ($parameters[0] ?? 0.0);
- $accountTypeIds = $accountTypes->pluck('id')->toArray();
-
- /** @var null|Account $result */
- $result = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->where('name', $value)->first();
-
- return null === $result;
- }
-
- /**
- * @param mixed $value
- * @param mixed $parameters
- */
- private function validateByAccountTypeId($value, $parameters): bool
- {
- $type = AccountType::find($this->data['account_type_id'])->first();
- $ignore = (int) ($parameters[0] ?? 0.0);
-
- /** @var null|Account $result */
- $result = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first();
-
- return null === $result;
- }
-
- /**
- * @param mixed $value
- */
- private function validateByParameterId(int $accountId, $value): bool
- {
- /** @var Account $existingAccount */
- $existingAccount = Account::find($accountId);
-
- $type = $existingAccount->accountType;
- $ignore = $existingAccount->id;
-
- $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first();
-
- return null === $entry;
- }
-
- /**
- * @param mixed $value
- */
- private function validateByAccountId($value): bool
- {
- /** @var Account $existingAccount */
- $existingAccount = Account::find($this->data['id']);
-
- $type = $existingAccount->accountType;
- $ignore = $existingAccount->id;
-
- $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first();
-
- return null === $entry;
- }
-
- private function validateByAccountName(string $value): bool
- {
- return 0 === auth()->user()->accounts()->where('name', $value)->count();
- }
-
/**
* @param mixed $attribute
* @param mixed $value
@@ -724,14 +636,6 @@ class FireflyValidator extends Validator
return false;
}
- /**
- * @SuppressWarnings("PHPMD.UnusedFormalParameter")
- */
- public function validateUniqueCurrencyCode(?string $attribute, ?string $value): bool
- {
- return $this->validateUniqueCurrency('code', (string) $attribute, (string) $value);
- }
-
/**
* @SuppressWarnings("PHPMD.UnusedFormalParameter")
*/
@@ -744,6 +648,14 @@ class FireflyValidator extends Validator
;
}
+ /**
+ * @SuppressWarnings("PHPMD.UnusedFormalParameter")
+ */
+ public function validateUniqueCurrencyCode(?string $attribute, ?string $value): bool
+ {
+ return $this->validateUniqueCurrency('code', (string) $attribute, (string) $value);
+ }
+
public function validateUniqueCurrencyName(?string $attribute, ?string $value): bool
{
return $this->validateUniqueCurrency('name', (string) $attribute, (string) $value);
@@ -915,9 +827,98 @@ class FireflyValidator extends Validator
->where('response', $response)
->where('delivery', $delivery)
->where('url', $url)
- ->count();
+ ->count()
+ ;
}
return false;
}
+
+ private function validateAccountAnonymously(): bool
+ {
+ if (!array_key_exists('user_id', $this->data)) {
+ return false;
+ }
+
+ /** @var User $user */
+ $user = User::find($this->data['user_id']);
+ $type = AccountType::find($this->data['account_type_id'])->first();
+ $value = $this->data['name'];
+
+ /** @var null|Account $result */
+ $result = $user->accounts()->where('account_type_id', $type->id)->where('name', $value)->first();
+
+ return null === $result;
+ }
+
+ /**
+ * @param mixed $value
+ */
+ private function validateByAccountId($value): bool
+ {
+ /** @var Account $existingAccount */
+ $existingAccount = Account::find($this->data['id']);
+
+ $type = $existingAccount->accountType;
+ $ignore = $existingAccount->id;
+
+ $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first();
+
+ return null === $entry;
+ }
+
+ private function validateByAccountName(string $value): bool
+ {
+ return 0 === auth()->user()->accounts()->where('name', $value)->count();
+ }
+
+ /**
+ * @param mixed $value
+ * @param mixed $parameters
+ */
+ private function validateByAccountTypeId($value, $parameters): bool
+ {
+ $type = AccountType::find($this->data['account_type_id'])->first();
+ $ignore = (int) ($parameters[0] ?? 0.0);
+
+ /** @var null|Account $result */
+ $result = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first();
+
+ return null === $result;
+ }
+
+ private function validateByAccountTypeString(string $value, array $parameters, string $type): bool
+ {
+ /** @var null|array $search */
+ $search = Config::get('firefly.accountTypeByIdentifier.'.$type);
+
+ if (null === $search) {
+ return false;
+ }
+
+ $accountTypes = AccountType::whereIn('type', $search)->get();
+ $ignore = (int) ($parameters[0] ?? 0.0);
+ $accountTypeIds = $accountTypes->pluck('id')->toArray();
+
+ /** @var null|Account $result */
+ $result = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->where('name', $value)->first();
+
+ return null === $result;
+ }
+
+ /**
+ * @param mixed $value
+ */
+ private function validateByParameterId(int $accountId, $value): bool
+ {
+ /** @var Account $existingAccount */
+ $existingAccount = Account::find($accountId);
+
+ $type = $existingAccount->accountType;
+ $ignore = $existingAccount->id;
+
+ $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first();
+
+ return null === $entry;
+ }
}
diff --git a/app/Validation/GroupValidation.php b/app/Validation/GroupValidation.php
index 87372dcd1c..bcb4c20afe 100644
--- a/app/Validation/GroupValidation.php
+++ b/app/Validation/GroupValidation.php
@@ -37,6 +37,8 @@ use Illuminate\Support\Facades\Log;
*/
trait GroupValidation
{
+ abstract protected function getTransactionsArray(Validator $validator): array;
+
/**
* A catch when users submit splits with no source or destination info at all.
*
@@ -81,8 +83,6 @@ trait GroupValidation
// only an issue if there is no transaction_journal_id
}
- abstract protected function getTransactionsArray(Validator $validator): array;
-
protected function preventUpdateReconciled(Validator $validator, TransactionGroup $transactionGroup): void
{
Log::debug(sprintf('Now in %s', __METHOD__));
diff --git a/app/Validation/RecurrenceValidation.php b/app/Validation/RecurrenceValidation.php
index 6a0925124e..68a1c4e97b 100644
--- a/app/Validation/RecurrenceValidation.php
+++ b/app/Validation/RecurrenceValidation.php
@@ -38,84 +38,6 @@ use InvalidArgumentException;
*/
trait RecurrenceValidation
{
- /**
- * Validate account information input for recurrences which are being updated.
- *
- * TODO Must always trigger when the type of the recurrence changes.
- */
- public function valUpdateAccountInfo(Validator $validator): void
- {
- $data = $validator->getData();
-
- $transactionType = $data['type'] ?? 'invalid';
-
- // grab model from parameter and try to set the transaction type from it
- if ('invalid' === $transactionType) {
- Log::debug('Type is invalid but we will search for it.');
-
- /** @var null|Recurrence $recurrence */
- $recurrence = $this->route()?->parameter('recurrence');
- if (null !== $recurrence) {
- Log::debug('There is a recurrence in the route.');
-
- // ok so we have a recurrence should be able to extract type somehow.
- /** @var null|RecurrenceTransaction $first */
- $first = $recurrence->recurrenceTransactions()->first();
- if (null !== $first) {
- $transactionType = null !== $first->transactionType ? $first->transactionType->type : 'withdrawal';
- Log::debug(sprintf('Determined type to be %s.', $transactionType));
- }
- if (null === $first) {
- Log::warning('Just going to assume type is a withdrawal.');
- $transactionType = 'withdrawal';
- }
- }
- }
-
- $transactions = $data['transactions'] ?? [];
-
- /** @var AccountValidator $accountValidator */
- $accountValidator = app(AccountValidator::class);
-
- Log::debug(sprintf('Going to loop %d transaction(s)', count($transactions)));
- foreach ($transactions as $index => $transaction) {
- $transactionType = $transaction['type'] ?? $transactionType;
- $accountValidator->setTransactionType($transactionType);
-
- if (
- !array_key_exists('source_id', $transaction)
- && !array_key_exists('destination_id', $transaction)
- && !array_key_exists('source_name', $transaction)
- && !array_key_exists('destination_name', $transaction)
- ) {
- continue;
- }
- // validate source account.
- $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null;
- $sourceName = $transaction['source_name'] ?? null;
- $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]);
-
- // do something with result:
- if (false === $validSource) {
- $validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError);
- $validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError);
-
- return;
- }
- // validate destination account
- $destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null;
- $destinationName = $transaction['destination_name'] ?? null;
- $validDestination = $accountValidator->validateDestination(['id' => $destinationId, 'name' => $destinationName]);
- // do something with result:
- if (false === $validDestination) {
- $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError);
- $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError);
-
- return;
- }
- }
- }
-
/**
* Adds an error to the validator when there are no repetitions in the array of data.
*/
@@ -235,6 +157,84 @@ trait RecurrenceValidation
}
}
+ /**
+ * Validate account information input for recurrences which are being updated.
+ *
+ * TODO Must always trigger when the type of the recurrence changes.
+ */
+ public function valUpdateAccountInfo(Validator $validator): void
+ {
+ $data = $validator->getData();
+
+ $transactionType = $data['type'] ?? 'invalid';
+
+ // grab model from parameter and try to set the transaction type from it
+ if ('invalid' === $transactionType) {
+ Log::debug('Type is invalid but we will search for it.');
+
+ /** @var null|Recurrence $recurrence */
+ $recurrence = $this->route()?->parameter('recurrence');
+ if (null !== $recurrence) {
+ Log::debug('There is a recurrence in the route.');
+
+ // ok so we have a recurrence should be able to extract type somehow.
+ /** @var null|RecurrenceTransaction $first */
+ $first = $recurrence->recurrenceTransactions()->first();
+ if (null !== $first) {
+ $transactionType = null !== $first->transactionType ? $first->transactionType->type : 'withdrawal';
+ Log::debug(sprintf('Determined type to be %s.', $transactionType));
+ }
+ if (null === $first) {
+ Log::warning('Just going to assume type is a withdrawal.');
+ $transactionType = 'withdrawal';
+ }
+ }
+ }
+
+ $transactions = $data['transactions'] ?? [];
+
+ /** @var AccountValidator $accountValidator */
+ $accountValidator = app(AccountValidator::class);
+
+ Log::debug(sprintf('Going to loop %d transaction(s)', count($transactions)));
+ foreach ($transactions as $index => $transaction) {
+ $transactionType = $transaction['type'] ?? $transactionType;
+ $accountValidator->setTransactionType($transactionType);
+
+ if (
+ !array_key_exists('source_id', $transaction)
+ && !array_key_exists('destination_id', $transaction)
+ && !array_key_exists('source_name', $transaction)
+ && !array_key_exists('destination_name', $transaction)
+ ) {
+ continue;
+ }
+ // validate source account.
+ $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null;
+ $sourceName = $transaction['source_name'] ?? null;
+ $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]);
+
+ // do something with result:
+ if (false === $validSource) {
+ $validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError);
+ $validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError);
+
+ return;
+ }
+ // validate destination account
+ $destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null;
+ $destinationName = $transaction['destination_name'] ?? null;
+ $validDestination = $accountValidator->validateDestination(['id' => $destinationId, 'name' => $destinationName]);
+ // do something with result:
+ if (false === $validDestination) {
+ $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError);
+ $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError);
+
+ return;
+ }
+ }
+ }
+
/**
* If the repetition type is daily, the moment should be empty.
*/
@@ -279,29 +279,6 @@ trait RecurrenceValidation
}
}
- /**
- * If the repetition type is weekly, the moment should be a day between 1-7 (inclusive).
- */
- protected function validateWeekly(Validator $validator, int $index, int $dayOfWeek): void
- {
- if ($dayOfWeek < 1 || $dayOfWeek > 7) {
- $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
- }
- }
-
- /**
- * If the repetition type is yearly, the moment should be a valid date.
- */
- protected function validateYearly(Validator $validator, int $index, string $moment): void
- {
- try {
- Carbon::createFromFormat('Y-m-d', $moment);
- } catch (InvalidArgumentException $e) { // @phpstan-ignore-line
- Log::debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage()));
- $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
- }
- }
-
/**
* @SuppressWarnings("PHPMD.NPathComplexity")
*/
@@ -400,4 +377,27 @@ trait RecurrenceValidation
}
Log::debug('Done with ID validation.');
}
+
+ /**
+ * If the repetition type is weekly, the moment should be a day between 1-7 (inclusive).
+ */
+ protected function validateWeekly(Validator $validator, int $index, int $dayOfWeek): void
+ {
+ if ($dayOfWeek < 1 || $dayOfWeek > 7) {
+ $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
+ }
+ }
+
+ /**
+ * If the repetition type is yearly, the moment should be a valid date.
+ */
+ protected function validateYearly(Validator $validator, int $index, string $moment): void
+ {
+ try {
+ Carbon::createFromFormat('Y-m-d', $moment);
+ } catch (InvalidArgumentException $e) { // @phpstan-ignore-line
+ Log::debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage()));
+ $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment'));
+ }
+ }
}
diff --git a/app/Validation/TransactionValidation.php b/app/Validation/TransactionValidation.php
index 098f72ae4c..92b59070cb 100644
--- a/app/Validation/TransactionValidation.php
+++ b/app/Validation/TransactionValidation.php
@@ -75,74 +75,150 @@ trait TransactionValidation
}
}
- protected function getTransactionsArray(Validator $validator): array
+ /**
+ * Validates the given account information. Switches on given transaction type.
+ *
+ * @throws FireflyException
+ */
+ public function validateAccountInformationUpdate(Validator $validator, TransactionGroup $transactionGroup): void
{
- Log::debug('Now in getTransactionsArray');
- $data = $validator->getData();
- $transactions = [];
- if (array_key_exists('transactions', $data) && is_array($data['transactions'])) {
- Log::debug('Transactions key exists and is array.');
- $transactions = $data['transactions'];
+ Log::debug('Now in validateAccountInformationUpdate()');
+ if ($validator->errors()->count() > 0) {
+ Log::debug('Validator already has errors, so return.');
+
+ return;
}
- if (array_key_exists('transactions', $data) && !is_array($data['transactions'])) {
- Log::debug(sprintf('Transactions key exists but is NOT array, its a %s', gettype($data['transactions'])));
+
+ $transactions = $this->getTransactionsArray($validator);
+
+ /**
+ * @var int|string $index
+ * @var array $transaction
+ */
+ foreach ($transactions as $index => $transaction) {
+ if (!is_int($index)) {
+ throw new FireflyException('Invalid data submitted: transaction is not array.');
+ }
+ $this->validateSingleUpdate($validator, $index, $transaction, $transactionGroup);
}
+ }
- return $transactions;
+ /**
+ * Adds an error to the validator when there are no transactions in the array of data.
+ */
+ public function validateOneRecurrenceTransaction(Validator $validator): void
+ {
+ Log::debug('Now in validateOneRecurrenceTransaction()');
+ $transactions = $this->getTransactionsArray($validator);
+
+ // need at least one transaction
+ if (0 === count($transactions)) {
+ $validator->errors()->add('transactions', (string) trans('validation.at_least_one_transaction'));
+ }
}
/**
- * @SuppressWarnings("PHPMD.NPathComplexity")
+ * Adds an error to the validator when there are no transactions in the array of data.
*/
- protected function validateSingleAccount(Validator $validator, int $index, string $transactionType, array $transaction): void
+ public function validateOneTransaction(Validator $validator): void
{
- Log::debug(sprintf('Now in validateSingleAccount(%d)', $index));
+ Log::debug('Now in validateOneTransaction');
+ if ($validator->errors()->count() > 0) {
+ Log::debug('Validator already has errors, so return.');
- /** @var AccountValidator $accountValidator */
- $accountValidator = app(AccountValidator::class);
+ return;
+ }
+ $transactions = $this->getTransactionsArray($validator);
+ // need at least one transaction
+ if (0 === count($transactions)) {
+ $validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction'));
+ Log::debug('Added error: at_least_one_transaction.');
- if (array_key_exists('user', $transaction) && null !== $transaction['user']) {
- $accountValidator->setUser($transaction['user']);
+ return;
}
- if (array_key_exists('user_group', $transaction) && null !== $transaction['user_group']) {
- $accountValidator->setUserGroup($transaction['user_group']);
+ Log::debug('Added NO errors.');
+ }
+
+ public function validateTransactionArray(Validator $validator): void
+ {
+ if ($validator->errors()->count() > 0) {
+ return;
}
+ $transactions = $this->getTransactionsArray($validator);
+ foreach (array_keys($transactions) as $key) {
+ if (!is_int($key)) {
+ $validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction'));
+ Log::debug('Added error: at_least_one_transaction.');
- $transactionType = $transaction['type'] ?? $transactionType;
- $accountValidator->setTransactionType($transactionType);
+ return;
+ }
+ }
+ }
- // validate source account.
- $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null;
- $sourceName = array_key_exists('source_name', $transaction) ? (string) $transaction['source_name'] : null;
- $sourceIban = array_key_exists('source_iban', $transaction) ? (string) $transaction['source_iban'] : null;
- $sourceNumber = array_key_exists('source_number', $transaction) ? (string) $transaction['source_number'] : null;
- $source = ['id' => $sourceId, 'name' => $sourceName, 'iban' => $sourceIban, 'number' => $sourceNumber];
- $validSource = $accountValidator->validateSource($source);
+ /**
+ * All types of splits must be equal.
+ */
+ public function validateTransactionTypes(Validator $validator): void
+ {
+ if ($validator->errors()->count() > 0) {
+ return;
+ }
+ Log::debug('Now in validateTransactionTypes()');
+ $transactions = $this->getTransactionsArray($validator);
- // do something with result:
- if (false === $validSource) {
- $validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError);
- $validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError);
+ $types = [];
+ foreach ($transactions as $transaction) {
+ $types[] = $transaction['type'] ?? 'invalid';
+ }
+ $unique = array_unique($types);
+ if (count($unique) > 1) {
+ $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal'));
return;
}
- // validate destination account
- $destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null;
- $destinationName = array_key_exists('destination_name', $transaction) ? (string) $transaction['destination_name'] : null;
- $destinationIban = array_key_exists('destination_iban', $transaction) ? (string) $transaction['destination_iban'] : null;
- $destinationNumber = array_key_exists('destination_number', $transaction) ? (string) $transaction['destination_number'] : null;
- $destination = ['id' => $destinationId, 'name' => $destinationName, 'iban' => $destinationIban, 'number' => $destinationNumber];
- $validDestination = $accountValidator->validateDestination($destination);
- // do something with result:
- if (false === $validDestination) {
- $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError);
- $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError);
+ $first = $unique[0] ?? 'invalid';
+ if ('invalid' === $first) {
+ $validator->errors()->add('transactions.0.type', (string) trans('validation.invalid_transaction_type'));
}
- // sanity check for reconciliation accounts. They can't both be null.
- $this->sanityCheckReconciliation($validator, $transactionType, $index, $source, $destination);
+ }
- // sanity check for currency information.
- $this->sanityCheckForeignCurrency($validator, $accountValidator, $transaction, $transactionType, $index);
+ /**
+ * All types of splits must be equal.
+ */
+ public function validateTransactionTypesForUpdate(Validator $validator): void
+ {
+ Log::debug('Now in validateTransactionTypesForUpdate()');
+ $transactions = $this->getTransactionsArray($validator);
+ $types = [];
+ foreach ($transactions as $transaction) {
+ $originalType = $this->getOriginalType((int) ($transaction['transaction_journal_id'] ?? 0));
+ // if type is not set, fall back to the type of the journal, if one is given.
+ $types[] = $transaction['type'] ?? $originalType;
+ }
+ $unique = array_unique($types);
+ if (count($unique) > 1) {
+ Log::warning('Add error for mismatch transaction types.');
+ $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal'));
+
+ return;
+ }
+ Log::debug('No errors in validateTransactionTypesForUpdate()');
+ }
+
+ protected function getTransactionsArray(Validator $validator): array
+ {
+ Log::debug('Now in getTransactionsArray');
+ $data = $validator->getData();
+ $transactions = [];
+ if (array_key_exists('transactions', $data) && is_array($data['transactions'])) {
+ Log::debug('Transactions key exists and is array.');
+ $transactions = $data['transactions'];
+ }
+ if (array_key_exists('transactions', $data) && !is_array($data['transactions'])) {
+ Log::debug(sprintf('Transactions key exists but is NOT array, its a %s', gettype($data['transactions'])));
+ }
+
+ return $transactions;
}
/**
@@ -178,179 +254,58 @@ trait TransactionValidation
}
}
- /**
- * TODO describe this method.
- *
- * @SuppressWarnings("PHPMD.ExcessiveParameterList")
- * @SuppressWarnings("PHPMD.NPathComplexity")
- */
- private function sanityCheckForeignCurrency(
- Validator $validator,
- AccountValidator $accountValidator,
- array $transaction,
- string $transactionType,
- int $index
- ): void {
- Log::debug('Now in sanityCheckForeignCurrency()');
- if (0 !== $validator->errors()->count()) {
- Log::debug('Already have errors, return');
-
- return;
- }
- if (!$accountValidator->source instanceof Account) {
- Log::debug('No source, return');
-
- return;
- }
- if (!$accountValidator->destination instanceof Account) {
- Log::debug('No destination, return');
-
- return;
- }
- $source = $accountValidator->source;
- $destination = $accountValidator->destination;
-
- Log::debug(sprintf('Source: #%d "%s (%s)"', $source->id, $source->name, $source->accountType->type));
- Log::debug(sprintf('Destination: #%d "%s" (%s)', $destination->id, $destination->name, $destination->accountType->type));
-
- if (!$this->isLiabilityOrAsset($source) || !$this->isLiabilityOrAsset($destination)) {
- Log::debug('Any account must be liability or asset account to continue.');
-
- return;
- }
-
- /** @var AccountRepository $accountRepository */
- $accountRepository = app(AccountRepositoryInterface::class);
- $primaryCurrency = Amount::getPrimaryCurrency();
- $sourceCurrency = $accountRepository->getAccountCurrency($source) ?? $primaryCurrency;
- $destinationCurrency = $accountRepository->getAccountCurrency($destination) ?? $primaryCurrency;
- // if both accounts have the same currency, continue.
- if ($sourceCurrency->code === $destinationCurrency->code) {
- Log::debug('Both accounts have the same currency, continue.');
-
- return;
- }
- Log::debug(sprintf('Source account expects #%d: %s', $sourceCurrency->id, $sourceCurrency->code));
- Log::debug(sprintf('Destination account expects #%d: %s', $destinationCurrency->id, $destinationCurrency->code));
-
- Log::debug(sprintf('Amount is %s', $transaction['amount']));
-
- if (TransactionTypeEnum::DEPOSIT->value === ucfirst($transactionType)) {
- Log::debug(sprintf('Processing as a "%s"', $transactionType));
- // use case: deposit from liability account to an asset account
- // the amount must be in the currency of the SOURCE
- // the foreign amount must be in the currency of the DESTINATION
-
- // no foreign currency information is present:
- if (!$this->hasForeignCurrencyInfo($transaction)) {
- $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string) trans('validation.require_foreign_currency'));
-
- return;
- }
-
- // wrong currency information is present
- $foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false;
- $foreignCurrencyId = (int) ($transaction['foreign_currency_id'] ?? 0);
- Log::debug(sprintf('[a] Foreign currency code seems to be #%d "%s"', $foreignCurrencyId, $foreignCurrencyCode), $transaction);
- if ($foreignCurrencyCode !== $destinationCurrency->code && $foreignCurrencyId !== $destinationCurrency->id) {
- $validator->errors()->add(sprintf('transactions.%d.foreign_currency_code', $index), (string) trans('validation.require_foreign_src'));
-
- return;
- }
- }
- if (TransactionTypeEnum::TRANSFER->value === ucfirst($transactionType) || TransactionTypeEnum::WITHDRAWAL->value === ucfirst($transactionType)) {
- Log::debug(sprintf('Processing as a "%s"', $transactionType));
- // use case: withdrawal from asset account to a liability account.
- // the foreign amount must be in the currency of the destination
- // the amount must be in the currency of the source
-
- // use case: transfer between accounts with different currencies.
- // the foreign amount must be in the currency of the destination
- // the amount must be in the currency of the source
-
- // no foreign currency information is present:
- if (!$this->hasForeignCurrencyInfo($transaction)) {
- $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string) trans('validation.require_foreign_currency'));
-
- return;
- }
-
- // wrong currency information is present
- $foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false;
- $foreignCurrencyId = (int) ($transaction['foreign_currency_id'] ?? 0);
- Log::debug(sprintf('[b] Foreign currency code seems to be #%d "%s"', $foreignCurrencyId, $foreignCurrencyCode), $transaction);
- if ($foreignCurrencyCode !== $destinationCurrency->code && $foreignCurrencyId !== $destinationCurrency->id) {
- Log::debug(sprintf('No match on code, "%s" vs "%s"', $foreignCurrencyCode, $destinationCurrency->code));
- Log::debug(sprintf('No match on ID, #%d vs #%d', $foreignCurrencyId, $destinationCurrency->id));
- $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string) trans('validation.require_foreign_dest'));
- }
- }
- }
-
- private function isLiabilityOrAsset(Account $account): bool
- {
- if ($this->isLiability($account)) {
- return true;
- }
-
- return $this->isAsset($account);
- }
-
- private function isLiability(Account $account): bool
- {
- $type = $account->accountType->type;
-
- return in_array($type, config('firefly.valid_liabilities'), true);
- }
-
- private function isAsset(Account $account): bool
+ /**
+ * @SuppressWarnings("PHPMD.NPathComplexity")
+ */
+ protected function validateSingleAccount(Validator $validator, int $index, string $transactionType, array $transaction): void
{
- $type = $account->accountType->type;
+ Log::debug(sprintf('Now in validateSingleAccount(%d)', $index));
- return AccountTypeEnum::ASSET->value === $type;
- }
+ /** @var AccountValidator $accountValidator */
+ $accountValidator = app(AccountValidator::class);
- private function hasForeignCurrencyInfo(array $transaction): bool
- {
- if (!array_key_exists('foreign_currency_code', $transaction) && !array_key_exists('foreign_currency_id', $transaction)) {
- return false;
- }
- if (!array_key_exists('foreign_amount', $transaction)) {
- return false;
+ if (array_key_exists('user', $transaction) && null !== $transaction['user']) {
+ $accountValidator->setUser($transaction['user']);
}
- if ('' === $transaction['foreign_amount']) {
- return false;
+ if (array_key_exists('user_group', $transaction) && null !== $transaction['user_group']) {
+ $accountValidator->setUserGroup($transaction['user_group']);
}
- return 0 !== bccomp('0', (string) $transaction['foreign_amount']);
- }
+ $transactionType = $transaction['type'] ?? $transactionType;
+ $accountValidator->setTransactionType($transactionType);
- /**
- * Validates the given account information. Switches on given transaction type.
- *
- * @throws FireflyException
- */
- public function validateAccountInformationUpdate(Validator $validator, TransactionGroup $transactionGroup): void
- {
- Log::debug('Now in validateAccountInformationUpdate()');
- if ($validator->errors()->count() > 0) {
- Log::debug('Validator already has errors, so return.');
+ // validate source account.
+ $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null;
+ $sourceName = array_key_exists('source_name', $transaction) ? (string) $transaction['source_name'] : null;
+ $sourceIban = array_key_exists('source_iban', $transaction) ? (string) $transaction['source_iban'] : null;
+ $sourceNumber = array_key_exists('source_number', $transaction) ? (string) $transaction['source_number'] : null;
+ $source = ['id' => $sourceId, 'name' => $sourceName, 'iban' => $sourceIban, 'number' => $sourceNumber];
+ $validSource = $accountValidator->validateSource($source);
+
+ // do something with result:
+ if (false === $validSource) {
+ $validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError);
+ $validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError);
return;
}
-
- $transactions = $this->getTransactionsArray($validator);
-
- /**
- * @var int|string $index
- * @var array $transaction
- */
- foreach ($transactions as $index => $transaction) {
- if (!is_int($index)) {
- throw new FireflyException('Invalid data submitted: transaction is not array.');
- }
- $this->validateSingleUpdate($validator, $index, $transaction, $transactionGroup);
+ // validate destination account
+ $destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null;
+ $destinationName = array_key_exists('destination_name', $transaction) ? (string) $transaction['destination_name'] : null;
+ $destinationIban = array_key_exists('destination_iban', $transaction) ? (string) $transaction['destination_iban'] : null;
+ $destinationNumber = array_key_exists('destination_number', $transaction) ? (string) $transaction['destination_number'] : null;
+ $destination = ['id' => $destinationId, 'name' => $destinationName, 'iban' => $destinationIban, 'number' => $destinationNumber];
+ $validDestination = $accountValidator->validateDestination($destination);
+ // do something with result:
+ if (false === $validDestination) {
+ $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError);
+ $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError);
}
+ // sanity check for reconciliation accounts. They can't both be null.
+ $this->sanityCheckReconciliation($validator, $transactionType, $index, $source, $destination);
+
+ // sanity check for currency information.
+ $this->sanityCheckForeignCurrency($validator, $accountValidator, $transaction, $transactionType, $index);
}
protected function validateSingleUpdate(Validator $validator, int $index, array $transaction, TransactionGroup $transactionGroup): void
@@ -457,9 +412,111 @@ trait TransactionValidation
Log::debug('Done with validateSingleUpdate().');
}
- private function getTransactionType(TransactionGroup $group, array $transactions): string
+ private function arrayEqual(array $array): bool
{
- return $transactions[0]['type'] ?? strtolower((string) $group->transactionJournals()->first()?->transactionType->type);
+ return 1 === count(array_unique($array));
+ }
+
+ private function collectComparisonData(array $transactions): array
+ {
+ $fields = ['source_id', 'destination_id', 'source_name', 'destination_name'];
+ $comparison = [];
+ foreach ($fields as $field) {
+ $comparison[$field] = [];
+
+ /** @var array $transaction */
+ foreach ($transactions as $transaction) {
+ // source or destination may be omitted. If this is the case, use the original source / destination name + ID.
+ $originalData = $this->getOriginalData((int) ($transaction['transaction_journal_id'] ?? 0));
+
+ // get field.
+ $comparison[$field][] = $transaction[$field] ?? $originalData[$field];
+ }
+ }
+
+ return $comparison;
+ }
+
+ private function compareAccountData(string $type, array $comparison): bool
+ {
+ return match ($type) {
+ default => $this->compareAccountDataWithdrawal($comparison),
+ 'deposit' => $this->compareAccountDataDeposit($comparison),
+ 'transfer' => $this->compareAccountDataTransfer($comparison)
+ };
+ }
+
+ private function compareAccountDataDeposit(array $comparison): bool
+ {
+ if ($this->arrayEqual($comparison['destination_id'])) {
+ // destination ID's are equal, return void.
+ return true;
+ }
+
+ // destination names are equal, return void.
+ return (bool) $this->arrayEqual($comparison['destination_name']);
+ }
+
+ private function compareAccountDataTransfer(array $comparison): bool
+ {
+ if ($this->arrayEqual($comparison['source_id'])) {
+ // source ID's are equal, return void.
+ return true;
+ }
+ if ($this->arrayEqual($comparison['source_name'])) {
+ // source names are equal, return void.
+ return true;
+ }
+ if ($this->arrayEqual($comparison['destination_id'])) {
+ // destination ID's are equal, return void.
+ return true;
+ }
+
+ // destination names are equal, return void.
+ return (bool) $this->arrayEqual($comparison['destination_name']);
+ }
+
+ private function compareAccountDataWithdrawal(array $comparison): bool
+ {
+ if ($this->arrayEqual($comparison['source_id'])) {
+ // source ID's are equal, return void.
+ return true;
+ }
+
+ // source names are equal, return void.
+ return (bool) $this->arrayEqual($comparison['source_name']);
+ }
+
+ private function getOriginalData(int $journalId): array
+ {
+ $return = ['source_id' => 0, 'source_name' => '', 'destination_id' => 0, 'destination_name' => ''];
+ if (0 === $journalId) {
+ return $return;
+ }
+
+ /** @var null|Transaction $source */
+ $source = Transaction::where('transaction_journal_id', $journalId)
+ ->where('amount', '<', 0)
+ ->with(['account'])
+ ->first()
+ ;
+ if (null !== $source) {
+ $return['source_id'] = $source->account_id;
+ $return['source_name'] = $source->account->name;
+ }
+
+ /** @var null|Transaction $destination */
+ $destination = Transaction::where('transaction_journal_id', $journalId)
+ ->where('amount', '>', 0)
+ ->with(['account'])
+ ->first()
+ ;
+ if (null !== $destination) {
+ $return['destination_id'] = $destination->account_id;
+ $return['destination_name'] = $destination->account->name;
+ }
+
+ return $return;
}
private function getOriginalSource(array $transaction, TransactionGroup $transactionGroup): ?Account
@@ -481,121 +538,171 @@ trait TransactionValidation
return null;
}
- /**
- * Adds an error to the validator when there are no transactions in the array of data.
- */
- public function validateOneRecurrenceTransaction(Validator $validator): void
+ private function getOriginalType(int $journalId): string
{
- Log::debug('Now in validateOneRecurrenceTransaction()');
- $transactions = $this->getTransactionsArray($validator);
+ if (0 === $journalId) {
+ return 'invalid';
+ }
- // need at least one transaction
- if (0 === count($transactions)) {
- $validator->errors()->add('transactions', (string) trans('validation.at_least_one_transaction'));
+ /** @var null|TransactionJournal $journal */
+ $journal = TransactionJournal::with(['transactionType'])->find($journalId);
+ if (null !== $journal) {
+ return strtolower((string) $journal->transactionType->type);
}
+
+ return 'invalid';
}
- /**
- * Adds an error to the validator when there are no transactions in the array of data.
- */
- public function validateOneTransaction(Validator $validator): void
+ private function getTransactionType(TransactionGroup $group, array $transactions): string
{
- Log::debug('Now in validateOneTransaction');
- if ($validator->errors()->count() > 0) {
- Log::debug('Validator already has errors, so return.');
+ return $transactions[0]['type'] ?? strtolower((string) $group->transactionJournals()->first()?->transactionType->type);
+ }
- return;
+ private function hasForeignCurrencyInfo(array $transaction): bool
+ {
+ if (!array_key_exists('foreign_currency_code', $transaction) && !array_key_exists('foreign_currency_id', $transaction)) {
+ return false;
}
- $transactions = $this->getTransactionsArray($validator);
- // need at least one transaction
- if (0 === count($transactions)) {
- $validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction'));
- Log::debug('Added error: at_least_one_transaction.');
-
- return;
+ if (!array_key_exists('foreign_amount', $transaction)) {
+ return false;
}
- Log::debug('Added NO errors.');
+ if ('' === $transaction['foreign_amount']) {
+ return false;
+ }
+
+ return 0 !== bccomp('0', (string) $transaction['foreign_amount']);
+ }
+
+ private function isAsset(Account $account): bool
+ {
+ $type = $account->accountType->type;
+
+ return AccountTypeEnum::ASSET->value === $type;
+ }
+
+ private function isLiability(Account $account): bool
+ {
+ $type = $account->accountType->type;
+
+ return in_array($type, config('firefly.valid_liabilities'), true);
}
- public function validateTransactionArray(Validator $validator): void
+ private function isLiabilityOrAsset(Account $account): bool
{
- if ($validator->errors()->count() > 0) {
- return;
+ if ($this->isLiability($account)) {
+ return true;
}
- $transactions = $this->getTransactionsArray($validator);
- foreach (array_keys($transactions) as $key) {
- if (!is_int($key)) {
- $validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction'));
- Log::debug('Added error: at_least_one_transaction.');
- return;
- }
- }
+ return $this->isAsset($account);
}
/**
- * All types of splits must be equal.
+ * TODO describe this method.
+ *
+ * @SuppressWarnings("PHPMD.ExcessiveParameterList")
+ * @SuppressWarnings("PHPMD.NPathComplexity")
*/
- public function validateTransactionTypes(Validator $validator): void
- {
- if ($validator->errors()->count() > 0) {
+ private function sanityCheckForeignCurrency(
+ Validator $validator,
+ AccountValidator $accountValidator,
+ array $transaction,
+ string $transactionType,
+ int $index
+ ): void {
+ Log::debug('Now in sanityCheckForeignCurrency()');
+ if (0 !== $validator->errors()->count()) {
+ Log::debug('Already have errors, return');
+
return;
}
- Log::debug('Now in validateTransactionTypes()');
- $transactions = $this->getTransactionsArray($validator);
+ if (!$accountValidator->source instanceof Account) {
+ Log::debug('No source, return');
- $types = [];
- foreach ($transactions as $transaction) {
- $types[] = $transaction['type'] ?? 'invalid';
+ return;
}
- $unique = array_unique($types);
- if (count($unique) > 1) {
- $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal'));
+ if (!$accountValidator->destination instanceof Account) {
+ Log::debug('No destination, return');
return;
}
- $first = $unique[0] ?? 'invalid';
- if ('invalid' === $first) {
- $validator->errors()->add('transactions.0.type', (string) trans('validation.invalid_transaction_type'));
- }
- }
+ $source = $accountValidator->source;
+ $destination = $accountValidator->destination;
- /**
- * All types of splits must be equal.
- */
- public function validateTransactionTypesForUpdate(Validator $validator): void
- {
- Log::debug('Now in validateTransactionTypesForUpdate()');
- $transactions = $this->getTransactionsArray($validator);
- $types = [];
- foreach ($transactions as $transaction) {
- $originalType = $this->getOriginalType((int) ($transaction['transaction_journal_id'] ?? 0));
- // if type is not set, fall back to the type of the journal, if one is given.
- $types[] = $transaction['type'] ?? $originalType;
- }
- $unique = array_unique($types);
- if (count($unique) > 1) {
- Log::warning('Add error for mismatch transaction types.');
- $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal'));
+ Log::debug(sprintf('Source: #%d "%s (%s)"', $source->id, $source->name, $source->accountType->type));
+ Log::debug(sprintf('Destination: #%d "%s" (%s)', $destination->id, $destination->name, $destination->accountType->type));
+
+ if (!$this->isLiabilityOrAsset($source) || !$this->isLiabilityOrAsset($destination)) {
+ Log::debug('Any account must be liability or asset account to continue.');
return;
}
- Log::debug('No errors in validateTransactionTypesForUpdate()');
- }
- private function getOriginalType(int $journalId): string
- {
- if (0 === $journalId) {
- return 'invalid';
+ /** @var AccountRepository $accountRepository */
+ $accountRepository = app(AccountRepositoryInterface::class);
+ $primaryCurrency = Amount::getPrimaryCurrency();
+ $sourceCurrency = $accountRepository->getAccountCurrency($source) ?? $primaryCurrency;
+ $destinationCurrency = $accountRepository->getAccountCurrency($destination) ?? $primaryCurrency;
+ // if both accounts have the same currency, continue.
+ if ($sourceCurrency->code === $destinationCurrency->code) {
+ Log::debug('Both accounts have the same currency, continue.');
+
+ return;
}
+ Log::debug(sprintf('Source account expects #%d: %s', $sourceCurrency->id, $sourceCurrency->code));
+ Log::debug(sprintf('Destination account expects #%d: %s', $destinationCurrency->id, $destinationCurrency->code));
- /** @var null|TransactionJournal $journal */
- $journal = TransactionJournal::with(['transactionType'])->find($journalId);
- if (null !== $journal) {
- return strtolower((string) $journal->transactionType->type);
+ Log::debug(sprintf('Amount is %s', $transaction['amount']));
+
+ if (TransactionTypeEnum::DEPOSIT->value === ucfirst($transactionType)) {
+ Log::debug(sprintf('Processing as a "%s"', $transactionType));
+ // use case: deposit from liability account to an asset account
+ // the amount must be in the currency of the SOURCE
+ // the foreign amount must be in the currency of the DESTINATION
+
+ // no foreign currency information is present:
+ if (!$this->hasForeignCurrencyInfo($transaction)) {
+ $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string) trans('validation.require_foreign_currency'));
+
+ return;
+ }
+
+ // wrong currency information is present
+ $foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false;
+ $foreignCurrencyId = (int) ($transaction['foreign_currency_id'] ?? 0);
+ Log::debug(sprintf('[a] Foreign currency code seems to be #%d "%s"', $foreignCurrencyId, $foreignCurrencyCode), $transaction);
+ if ($foreignCurrencyCode !== $destinationCurrency->code && $foreignCurrencyId !== $destinationCurrency->id) {
+ $validator->errors()->add(sprintf('transactions.%d.foreign_currency_code', $index), (string) trans('validation.require_foreign_src'));
+
+ return;
+ }
}
+ if (TransactionTypeEnum::TRANSFER->value === ucfirst($transactionType) || TransactionTypeEnum::WITHDRAWAL->value === ucfirst($transactionType)) {
+ Log::debug(sprintf('Processing as a "%s"', $transactionType));
+ // use case: withdrawal from asset account to a liability account.
+ // the foreign amount must be in the currency of the destination
+ // the amount must be in the currency of the source
- return 'invalid';
+ // use case: transfer between accounts with different currencies.
+ // the foreign amount must be in the currency of the destination
+ // the amount must be in the currency of the source
+
+ // no foreign currency information is present:
+ if (!$this->hasForeignCurrencyInfo($transaction)) {
+ $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string) trans('validation.require_foreign_currency'));
+
+ return;
+ }
+
+ // wrong currency information is present
+ $foreignCurrencyCode = $transaction['foreign_currency_code'] ?? false;
+ $foreignCurrencyId = (int) ($transaction['foreign_currency_id'] ?? 0);
+ Log::debug(sprintf('[b] Foreign currency code seems to be #%d "%s"', $foreignCurrencyId, $foreignCurrencyCode), $transaction);
+ if ($foreignCurrencyCode !== $destinationCurrency->code && $foreignCurrencyId !== $destinationCurrency->id) {
+ Log::debug(sprintf('No match on code, "%s" vs "%s"', $foreignCurrencyCode, $destinationCurrency->code));
+ Log::debug(sprintf('No match on ID, #%d vs #%d', $foreignCurrencyId, $destinationCurrency->id));
+ $validator->errors()->add(sprintf('transactions.%d.foreign_amount', $index), (string) trans('validation.require_foreign_dest'));
+ }
+ }
}
private function validateEqualAccounts(Validator $validator): void
@@ -688,111 +795,4 @@ trait TransactionValidation
}
Log::debug('No errors found in validateEqualAccountsForUpdate');
}
-
- private function collectComparisonData(array $transactions): array
- {
- $fields = ['source_id', 'destination_id', 'source_name', 'destination_name'];
- $comparison = [];
- foreach ($fields as $field) {
- $comparison[$field] = [];
-
- /** @var array $transaction */
- foreach ($transactions as $transaction) {
- // source or destination may be omitted. If this is the case, use the original source / destination name + ID.
- $originalData = $this->getOriginalData((int) ($transaction['transaction_journal_id'] ?? 0));
-
- // get field.
- $comparison[$field][] = $transaction[$field] ?? $originalData[$field];
- }
- }
-
- return $comparison;
- }
-
- private function getOriginalData(int $journalId): array
- {
- $return = ['source_id' => 0, 'source_name' => '', 'destination_id' => 0, 'destination_name' => ''];
- if (0 === $journalId) {
- return $return;
- }
-
- /** @var null|Transaction $source */
- $source = Transaction::where('transaction_journal_id', $journalId)
- ->where('amount', '<', 0)
- ->with(['account'])
- ->first()
- ;
- if (null !== $source) {
- $return['source_id'] = $source->account_id;
- $return['source_name'] = $source->account->name;
- }
-
- /** @var null|Transaction $destination */
- $destination = Transaction::where('transaction_journal_id', $journalId)
- ->where('amount', '>', 0)
- ->with(['account'])
- ->first()
- ;
- if (null !== $destination) {
- $return['destination_id'] = $destination->account_id;
- $return['destination_name'] = $destination->account->name;
- }
-
- return $return;
- }
-
- private function compareAccountData(string $type, array $comparison): bool
- {
- return match ($type) {
- default => $this->compareAccountDataWithdrawal($comparison),
- 'deposit' => $this->compareAccountDataDeposit($comparison),
- 'transfer' => $this->compareAccountDataTransfer($comparison)
- };
- }
-
- private function compareAccountDataWithdrawal(array $comparison): bool
- {
- if ($this->arrayEqual($comparison['source_id'])) {
- // source ID's are equal, return void.
- return true;
- }
-
- // source names are equal, return void.
- return (bool) $this->arrayEqual($comparison['source_name']);
- }
-
- private function arrayEqual(array $array): bool
- {
- return 1 === count(array_unique($array));
- }
-
- private function compareAccountDataDeposit(array $comparison): bool
- {
- if ($this->arrayEqual($comparison['destination_id'])) {
- // destination ID's are equal, return void.
- return true;
- }
-
- // destination names are equal, return void.
- return (bool) $this->arrayEqual($comparison['destination_name']);
- }
-
- private function compareAccountDataTransfer(array $comparison): bool
- {
- if ($this->arrayEqual($comparison['source_id'])) {
- // source ID's are equal, return void.
- return true;
- }
- if ($this->arrayEqual($comparison['source_name'])) {
- // source names are equal, return void.
- return true;
- }
- if ($this->arrayEqual($comparison['destination_id'])) {
- // destination ID's are equal, return void.
- return true;
- }
-
- // destination names are equal, return void.
- return (bool) $this->arrayEqual($comparison['destination_name']);
- }
}
diff --git a/composer.lock b/composer.lock
index f8b7bf6340..6dcb372eff 100644
--- a/composer.lock
+++ b/composer.lock
@@ -130,16 +130,16 @@
},
{
"name": "brick/math",
- "version": "0.14.5",
+ "version": "0.14.6",
"source": {
"type": "git",
"url": "https://github.com/brick/math.git",
- "reference": "618a8077b3c326045e10d5788ed713b341fcfe40"
+ "reference": "32498d5e1897e7642c0b961ace2df6d7dc9a3bc3"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/brick/math/zipball/618a8077b3c326045e10d5788ed713b341fcfe40",
- "reference": "618a8077b3c326045e10d5788ed713b341fcfe40",
+ "url": "https://api.github.com/repos/brick/math/zipball/32498d5e1897e7642c0b961ace2df6d7dc9a3bc3",
+ "reference": "32498d5e1897e7642c0b961ace2df6d7dc9a3bc3",
"shasum": ""
},
"require": {
@@ -178,7 +178,7 @@
],
"support": {
"issues": "https://github.com/brick/math/issues",
- "source": "https://github.com/brick/math/tree/0.14.5"
+ "source": "https://github.com/brick/math/tree/0.14.6"
},
"funding": [
{
@@ -186,7 +186,7 @@
"type": "github"
}
],
- "time": "2026-02-03T18:06:51+00:00"
+ "time": "2026-02-05T07:59:58+00:00"
},
{
"name": "carbonphp/carbon-doctrine-types",
@@ -11562,16 +11562,16 @@
},
{
"name": "phpunit/php-code-coverage",
- "version": "12.5.2",
+ "version": "12.5.3",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
- "reference": "4a9739b51cbcb355f6e95659612f92e282a7077b"
+ "reference": "b015312f28dd75b75d3422ca37dff2cd1a565e8d"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/4a9739b51cbcb355f6e95659612f92e282a7077b",
- "reference": "4a9739b51cbcb355f6e95659612f92e282a7077b",
+ "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/b015312f28dd75b75d3422ca37dff2cd1a565e8d",
+ "reference": "b015312f28dd75b75d3422ca37dff2cd1a565e8d",
"shasum": ""
},
"require": {
@@ -11627,7 +11627,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
"security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy",
- "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/12.5.2"
+ "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/12.5.3"
},
"funding": [
{
@@ -11647,7 +11647,7 @@
"type": "tidelift"
}
],
- "time": "2025-12-24T07:03:04+00:00"
+ "time": "2026-02-06T06:01:44+00:00"
},
{
"name": "phpunit/php-file-iterator",
@@ -11908,16 +11908,16 @@
},
{
"name": "phpunit/phpunit",
- "version": "12.5.8",
+ "version": "12.5.9",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
- "reference": "37ddb96c14bfee10304825edbb7e66d341ec6889"
+ "reference": "83d4c158526c879b4c5cf7149d27958b6d912373"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/37ddb96c14bfee10304825edbb7e66d341ec6889",
- "reference": "37ddb96c14bfee10304825edbb7e66d341ec6889",
+ "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/83d4c158526c879b4c5cf7149d27958b6d912373",
+ "reference": "83d4c158526c879b4c5cf7149d27958b6d912373",
"shasum": ""
},
"require": {
@@ -11932,7 +11932,7 @@
"phar-io/version": "^3.2.1",
"php": ">=8.3",
"phpunit/php-code-coverage": "^12.5.2",
- "phpunit/php-file-iterator": "^6.0.0",
+ "phpunit/php-file-iterator": "^6.0.1",
"phpunit/php-invoker": "^6.0.0",
"phpunit/php-text-template": "^5.0.0",
"phpunit/php-timer": "^8.0.0",
@@ -11943,6 +11943,7 @@
"sebastian/exporter": "^7.0.2",
"sebastian/global-state": "^8.0.2",
"sebastian/object-enumerator": "^7.0.0",
+ "sebastian/recursion-context": "^7.0.1",
"sebastian/type": "^6.0.3",
"sebastian/version": "^6.0.0",
"staabm/side-effects-detector": "^1.0.5"
@@ -11985,7 +11986,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
- "source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.8"
+ "source": "https://github.com/sebastianbergmann/phpunit/tree/12.5.9"
},
"funding": [
{
@@ -12009,7 +12010,7 @@
"type": "tidelift"
}
],
- "time": "2026-01-27T06:12:29+00:00"
+ "time": "2026-02-05T08:01:09+00:00"
},
{
"name": "rector/rector",
diff --git a/config/firefly.php b/config/firefly.php
index 80e6c68060..f3cf06a094 100644
--- a/config/firefly.php
+++ b/config/firefly.php
@@ -78,8 +78,8 @@ return [
'running_balance_column' => (bool)envNonEmpty('USE_RUNNING_BALANCE', true), // this is only the default value, is not used.
// see cer.php for exchange rates feature flag.
],
- 'version' => 'develop/2026-02-05',
- 'build_time' => 1770268364,
+ 'version' => 'develop/2026-02-06',
+ 'build_time' => 1770382386,
'api_version' => '2.1.0', // field is no longer used.
'db_version' => 28, // field is no longer used.
diff --git a/database/migrations/2016_06_16_000000_create_support_tables.php b/database/migrations/2016_06_16_000000_create_support_tables.php
index d602a25f39..4d70e4f708 100644
--- a/database/migrations/2016_06_16_000000_create_support_tables.php
+++ b/database/migrations/2016_06_16_000000_create_support_tables.php
@@ -91,43 +91,41 @@ class CreateSupportTables extends Migration
}
}
- private function createCurrencyTable(): void
+ private function createConfigurationTable(): void
{
- if (!Schema::hasTable('transaction_currencies')) {
+ if (!Schema::hasTable('configuration')) {
try {
- Schema::create('transaction_currencies', static function (Blueprint $table): void {
+ Schema::create('configuration', static function (Blueprint $table): void {
$table->increments('id');
$table->timestamps();
$table->softDeletes();
- $table->string('code', 3);
- $table->string('name', 255);
- $table->string('symbol', 12);
-
- // code must be unique.
- $table->unique(['code']);
+ $table->string('name', 50);
+ $table->text('data');
});
} catch (QueryException $e) {
- app('log')->error(sprintf(self::TABLE_ERROR, 'transaction_currencies', $e->getMessage()));
+ app('log')->error(sprintf(self::TABLE_ERROR, 'configuration', $e->getMessage()));
app('log')->error(self::TABLE_ALREADY_EXISTS);
}
}
}
- private function createTransactionTypeTable(): void
+ private function createCurrencyTable(): void
{
- if (!Schema::hasTable('transaction_types')) {
+ if (!Schema::hasTable('transaction_currencies')) {
try {
- Schema::create('transaction_types', static function (Blueprint $table): void {
+ Schema::create('transaction_currencies', static function (Blueprint $table): void {
$table->increments('id');
$table->timestamps();
$table->softDeletes();
- $table->string('type', 50);
+ $table->string('code', 3);
+ $table->string('name', 255);
+ $table->string('symbol', 12);
- // type must be unique.
- $table->unique(['type']);
+ // code must be unique.
+ $table->unique(['code']);
});
} catch (QueryException $e) {
- app('log')->error(sprintf(self::TABLE_ERROR, 'transaction_types', $e->getMessage()));
+ app('log')->error(sprintf(self::TABLE_ERROR, 'transaction_currencies', $e->getMessage()));
app('log')->error(self::TABLE_ALREADY_EXISTS);
}
}
@@ -173,6 +171,26 @@ class CreateSupportTables extends Migration
}
}
+ private function createPermissionRoleTable(): void
+ {
+ if (!Schema::hasTable('permission_role')) {
+ try {
+ Schema::create('permission_role', static function (Blueprint $table): void {
+ $table->integer('permission_id')->unsigned();
+ $table->integer('role_id')->unsigned();
+
+ $table->foreign('permission_id')->references('id')->on('permissions')->onUpdate('cascade')->onDelete('cascade');
+ $table->foreign('role_id')->references('id')->on('roles')->onUpdate('cascade')->onDelete('cascade');
+
+ $table->primary(['permission_id', 'role_id']);
+ });
+ } catch (QueryException $e) {
+ app('log')->error(sprintf(self::TABLE_ERROR, 'permission_role', $e->getMessage()));
+ app('log')->error(self::TABLE_ALREADY_EXISTS);
+ }
+ }
+ }
+
private function createPermissionsTable(): void
{
if (!Schema::hasTable('permissions')) {
@@ -209,26 +227,6 @@ class CreateSupportTables extends Migration
}
}
- private function createPermissionRoleTable(): void
- {
- if (!Schema::hasTable('permission_role')) {
- try {
- Schema::create('permission_role', static function (Blueprint $table): void {
- $table->integer('permission_id')->unsigned();
- $table->integer('role_id')->unsigned();
-
- $table->foreign('permission_id')->references('id')->on('permissions')->onUpdate('cascade')->onDelete('cascade');
- $table->foreign('role_id')->references('id')->on('roles')->onUpdate('cascade')->onDelete('cascade');
-
- $table->primary(['permission_id', 'role_id']);
- });
- } catch (QueryException $e) {
- app('log')->error(sprintf(self::TABLE_ERROR, 'permission_role', $e->getMessage()));
- app('log')->error(self::TABLE_ALREADY_EXISTS);
- }
- }
- }
-
private function createSessionsTable(): void
{
if (!Schema::hasTable('sessions')) {
@@ -248,19 +246,21 @@ class CreateSupportTables extends Migration
}
}
- private function createConfigurationTable(): void
+ private function createTransactionTypeTable(): void
{
- if (!Schema::hasTable('configuration')) {
+ if (!Schema::hasTable('transaction_types')) {
try {
- Schema::create('configuration', static function (Blueprint $table): void {
+ Schema::create('transaction_types', static function (Blueprint $table): void {
$table->increments('id');
$table->timestamps();
$table->softDeletes();
- $table->string('name', 50);
- $table->text('data');
+ $table->string('type', 50);
+
+ // type must be unique.
+ $table->unique(['type']);
});
} catch (QueryException $e) {
- app('log')->error(sprintf(self::TABLE_ERROR, 'configuration', $e->getMessage()));
+ app('log')->error(sprintf(self::TABLE_ERROR, 'transaction_types', $e->getMessage()));
app('log')->error(self::TABLE_ALREADY_EXISTS);
}
}
diff --git a/database/migrations/2016_06_16_000002_create_main_tables.php b/database/migrations/2016_06_16_000002_create_main_tables.php
index 717a31d124..6f6fd9430a 100644
--- a/database/migrations/2016_06_16_000002_create_main_tables.php
+++ b/database/migrations/2016_06_16_000002_create_main_tables.php
@@ -132,48 +132,6 @@ class CreateMainTables extends Migration
}
}
- private function createPiggyBanksTable(): void
- {
- if (!Schema::hasTable('piggy_banks')) {
- try {
- Schema::create('piggy_banks', static function (Blueprint $table): void {
- $table->increments('id');
- $table->timestamps();
- $table->softDeletes();
- $table->integer('account_id', false, true);
- $table->string('name', 1024);
- $table->decimal('targetamount', 32, 12);
- $table->date('startdate')->nullable();
- $table->date('targetdate')->nullable();
- $table->integer('order', false, true)->default(0);
- $table->boolean('active')->default(0);
- $table->boolean('encrypted')->default(1);
- $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
- });
- } catch (QueryException $e) {
- app('log')->error(sprintf(self::TABLE_ERROR, 'piggy_banks', $e->getMessage()));
- app('log')->error(self::TABLE_ALREADY_EXISTS);
- }
- }
-
- if (!Schema::hasTable('piggy_bank_repetitions')) {
- try {
- Schema::create('piggy_bank_repetitions', static function (Blueprint $table): void {
- $table->increments('id');
- $table->timestamps();
- $table->integer('piggy_bank_id', false, true);
- $table->date('startdate')->nullable();
- $table->date('targetdate')->nullable();
- $table->decimal('currentamount', 32, 12);
- $table->foreign('piggy_bank_id')->references('id')->on('piggy_banks')->onDelete('cascade');
- });
- } catch (QueryException $e) {
- app('log')->error(sprintf(self::TABLE_ERROR, 'piggy_bank_repetitions', $e->getMessage()));
- app('log')->error(self::TABLE_ALREADY_EXISTS);
- }
- }
- }
-
private function createAttachmentsTable(): void
{
if (!Schema::hasTable('attachments')) {
@@ -295,6 +253,48 @@ class CreateMainTables extends Migration
}
}
+ private function createPiggyBanksTable(): void
+ {
+ if (!Schema::hasTable('piggy_banks')) {
+ try {
+ Schema::create('piggy_banks', static function (Blueprint $table): void {
+ $table->increments('id');
+ $table->timestamps();
+ $table->softDeletes();
+ $table->integer('account_id', false, true);
+ $table->string('name', 1024);
+ $table->decimal('targetamount', 32, 12);
+ $table->date('startdate')->nullable();
+ $table->date('targetdate')->nullable();
+ $table->integer('order', false, true)->default(0);
+ $table->boolean('active')->default(0);
+ $table->boolean('encrypted')->default(1);
+ $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
+ });
+ } catch (QueryException $e) {
+ app('log')->error(sprintf(self::TABLE_ERROR, 'piggy_banks', $e->getMessage()));
+ app('log')->error(self::TABLE_ALREADY_EXISTS);
+ }
+ }
+
+ if (!Schema::hasTable('piggy_bank_repetitions')) {
+ try {
+ Schema::create('piggy_bank_repetitions', static function (Blueprint $table): void {
+ $table->increments('id');
+ $table->timestamps();
+ $table->integer('piggy_bank_id', false, true);
+ $table->date('startdate')->nullable();
+ $table->date('targetdate')->nullable();
+ $table->decimal('currentamount', 32, 12);
+ $table->foreign('piggy_bank_id')->references('id')->on('piggy_banks')->onDelete('cascade');
+ });
+ } catch (QueryException $e) {
+ app('log')->error(sprintf(self::TABLE_ERROR, 'piggy_bank_repetitions', $e->getMessage()));
+ app('log')->error(self::TABLE_ALREADY_EXISTS);
+ }
+ }
+ }
+
private function createPreferencesTable(): void
{
if (!Schema::hasTable('preferences')) {
diff --git a/database/migrations/2022_08_21_104626_add_user_groups.php b/database/migrations/2022_08_21_104626_add_user_groups.php
index 75e31af332..a861181562 100644
--- a/database/migrations/2022_08_21_104626_add_user_groups.php
+++ b/database/migrations/2022_08_21_104626_add_user_groups.php
@@ -29,17 +29,17 @@ use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
/**
- * Run the migrations.
- *
- * @SuppressWarnings("PHPMD.ShortMethodName")
+ * Reverse the migrations.
*/
- public function up(): void
+ public function down(): void
{
try {
Schema::table('currency_exchange_rates', static function (Blueprint $table): void {
- if (!Schema::hasColumn('currency_exchange_rates', 'user_group_id')) {
- $table->bigInteger('user_group_id', false, true)->nullable()->after('user_id');
- $table->foreign('user_group_id', 'cer_to_ugi')->references('id')->on('user_groups')->onDelete('set null')->onUpdate('cascade');
+ if ('sqlite' !== config('database.default')) {
+ $table->dropForeign('cer_to_ugi');
+ }
+ if (Schema::hasColumn('currency_exchange_rates', 'user_group_id')) {
+ $table->dropColumn('user_group_id');
}
});
} catch (QueryException $e) {
@@ -49,17 +49,17 @@ return new class() extends Migration {
}
/**
- * Reverse the migrations.
+ * Run the migrations.
+ *
+ * @SuppressWarnings("PHPMD.ShortMethodName")
*/
- public function down(): void
+ public function up(): void
{
try {
Schema::table('currency_exchange_rates', static function (Blueprint $table): void {
- if ('sqlite' !== config('database.default')) {
- $table->dropForeign('cer_to_ugi');
- }
- if (Schema::hasColumn('currency_exchange_rates', 'user_group_id')) {
- $table->dropColumn('user_group_id');
+ if (!Schema::hasColumn('currency_exchange_rates', 'user_group_id')) {
+ $table->bigInteger('user_group_id', false, true)->nullable()->after('user_id');
+ $table->foreign('user_group_id', 'cer_to_ugi')->references('id')->on('user_groups')->onDelete('set null')->onUpdate('cascade');
}
});
} catch (QueryException $e) {
diff --git a/database/migrations/2022_09_18_123911_create_notifications_table.php b/database/migrations/2022_09_18_123911_create_notifications_table.php
index 74117eb407..2664ca770c 100644
--- a/database/migrations/2022_09_18_123911_create_notifications_table.php
+++ b/database/migrations/2022_09_18_123911_create_notifications_table.php
@@ -28,6 +28,14 @@ use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('notifications');
+ }
+
/**
* Run the migrations.
*
@@ -53,12 +61,4 @@ return new class() extends Migration {
}
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- Schema::dropIfExists('notifications');
- }
};
diff --git a/database/migrations/2022_10_01_074908_invited_users.php b/database/migrations/2022_10_01_074908_invited_users.php
index d892e4d93d..d7f6eb50e0 100644
--- a/database/migrations/2022_10_01_074908_invited_users.php
+++ b/database/migrations/2022_10_01_074908_invited_users.php
@@ -28,6 +28,14 @@ use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('invited_users');
+ }
+
/**
* Run the migrations.
*
@@ -55,12 +63,4 @@ return new class() extends Migration {
}
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- Schema::dropIfExists('invited_users');
- }
};
diff --git a/database/migrations/2022_10_01_210238_audit_log_entries.php b/database/migrations/2022_10_01_210238_audit_log_entries.php
index 56e1be3c1c..f5110acab0 100644
--- a/database/migrations/2022_10_01_210238_audit_log_entries.php
+++ b/database/migrations/2022_10_01_210238_audit_log_entries.php
@@ -28,6 +28,14 @@ use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('audit_log_entries');
+ }
+
/**
* Run the migrations.
*
@@ -60,12 +68,4 @@ return new class() extends Migration {
}
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- Schema::dropIfExists('audit_log_entries');
- }
};
diff --git a/database/migrations/2023_08_11_192521_upgrade_og_table.php b/database/migrations/2023_08_11_192521_upgrade_og_table.php
index ab9fd0eb50..66e4375094 100644
--- a/database/migrations/2023_08_11_192521_upgrade_og_table.php
+++ b/database/migrations/2023_08_11_192521_upgrade_og_table.php
@@ -29,22 +29,17 @@ use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
/**
- * Run the migrations.
- *
- * @SuppressWarnings("PHPMD.ShortMethodName")
+ * Reverse the migrations.
*/
- public function up(): void
+ public function down(): void
{
try {
Schema::table('object_groups', static function (Blueprint $table): void {
- if (!Schema::hasColumn('object_groups', 'user_group_id')) {
- $table->bigInteger('user_group_id', false, true)->nullable()->after('user_id');
- $table
- ->foreign('user_group_id', sprintf('%s_to_ugi', 'object_groups'))
- ->references('id')
- ->on('user_groups')
- ->onDelete('set null')
- ->onUpdate('cascade');
+ if ('sqlite' !== config('database.default')) {
+ $table->dropForeign(sprintf('%s_to_ugi', 'object_groups'));
+ }
+ if (Schema::hasColumn('object_groups', 'user_group_id')) {
+ $table->dropColumn('user_group_id');
}
});
} catch (QueryException $e) {
@@ -54,17 +49,22 @@ return new class() extends Migration {
}
/**
- * Reverse the migrations.
+ * Run the migrations.
+ *
+ * @SuppressWarnings("PHPMD.ShortMethodName")
*/
- public function down(): void
+ public function up(): void
{
try {
Schema::table('object_groups', static function (Blueprint $table): void {
- if ('sqlite' !== config('database.default')) {
- $table->dropForeign(sprintf('%s_to_ugi', 'object_groups'));
- }
- if (Schema::hasColumn('object_groups', 'user_group_id')) {
- $table->dropColumn('user_group_id');
+ if (!Schema::hasColumn('object_groups', 'user_group_id')) {
+ $table->bigInteger('user_group_id', false, true)->nullable()->after('user_id');
+ $table
+ ->foreign('user_group_id', sprintf('%s_to_ugi', 'object_groups'))
+ ->references('id')
+ ->on('user_groups')
+ ->onDelete('set null')
+ ->onUpdate('cascade');
}
});
} catch (QueryException $e) {
diff --git a/database/migrations/2023_10_21_113213_add_currency_pivot_tables.php b/database/migrations/2023_10_21_113213_add_currency_pivot_tables.php
index ae3b445952..a5ab00e0cd 100644
--- a/database/migrations/2023_10_21_113213_add_currency_pivot_tables.php
+++ b/database/migrations/2023_10_21_113213_add_currency_pivot_tables.php
@@ -28,6 +28,15 @@ use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('transaction_currency_user');
+ Schema::dropIfExists('transaction_currency_user_group');
+ }
+
/**
* @SuppressWarnings("PHPMD.ShortMethodName")
* Run the migrations.
@@ -76,13 +85,4 @@ return new class() extends Migration {
}
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- Schema::dropIfExists('transaction_currency_user');
- Schema::dropIfExists('transaction_currency_user_group');
- }
};
diff --git a/database/migrations/2024_03_03_174645_add_indices.php b/database/migrations/2024_03_03_174645_add_indices.php
index 51f9cc0d1c..5107649317 100644
--- a/database/migrations/2024_03_03_174645_add_indices.php
+++ b/database/migrations/2024_03_03_174645_add_indices.php
@@ -31,6 +31,13 @@ return new class() extends Migration {
private const string QUERY_ERROR = 'Could not execute query (table "%s", field "%s"): %s';
private const string EXPL = 'If the index already exists (see error), or if MySQL can\'t do it, this is not an problem. Otherwise, please open a GitHub discussion.';
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ }
+
/**
* Run the migrations.
*/
@@ -70,11 +77,4 @@ return new class() extends Migration {
}
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- }
};
diff --git a/database/migrations/2024_04_01_174351_expand_preferences_table.php b/database/migrations/2024_04_01_174351_expand_preferences_table.php
index 59e9d9d3f7..510d8de286 100644
--- a/database/migrations/2024_04_01_174351_expand_preferences_table.php
+++ b/database/migrations/2024_04_01_174351_expand_preferences_table.php
@@ -28,6 +28,13 @@ use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ }
+
/**
* Run the migrations.
*/
@@ -45,11 +52,4 @@ return new class() extends Migration {
app('log')->error('If the column or index already exists (see error), this is not an problem. Otherwise, please open a GitHub discussion.');
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- }
};
diff --git a/database/migrations/2024_05_12_060551_create_account_balance_table.php b/database/migrations/2024_05_12_060551_create_account_balance_table.php
index 65cca06576..f11a3f3eff 100644
--- a/database/migrations/2024_05_12_060551_create_account_balance_table.php
+++ b/database/migrations/2024_05_12_060551_create_account_balance_table.php
@@ -27,6 +27,14 @@ use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('account_balances');
+ }
+
/**
* Run the migrations.
*/
@@ -50,12 +58,4 @@ return new class() extends Migration {
});
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- Schema::dropIfExists('account_balances');
- }
};
diff --git a/database/migrations/2024_07_28_145631_add_running_balance.php b/database/migrations/2024_07_28_145631_add_running_balance.php
index b838d01691..b04ee78bda 100644
--- a/database/migrations/2024_07_28_145631_add_running_balance.php
+++ b/database/migrations/2024_07_28_145631_add_running_balance.php
@@ -29,14 +29,14 @@ use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
/**
- * Run the migrations.
+ * Reverse the migrations.
*/
- public function up(): void
+ public function down(): void
{
try {
Schema::table('transactions', static function (Blueprint $table): void {
- if (!Schema::hasColumn('transactions', 'balance_before')) {
- $table->decimal('balance_before', 32, 12)->nullable()->after('amount');
+ if (Schema::hasColumn('transactions', 'balance_before')) {
+ $table->dropColumn('balance_before');
}
});
} catch (QueryException $e) {
@@ -46,8 +46,8 @@ return new class() extends Migration {
try {
Schema::table('transactions', static function (Blueprint $table): void {
- if (!Schema::hasColumn('transactions', 'balance_after')) {
- $table->decimal('balance_after', 32, 12)->nullable()->after('balance_before');
+ if (Schema::hasColumn('transactions', 'balance_after')) {
+ $table->dropColumn('balance_after');
}
});
} catch (QueryException $e) {
@@ -57,8 +57,8 @@ return new class() extends Migration {
try {
Schema::table('transactions', static function (Blueprint $table): void {
- if (!Schema::hasColumn('transactions', 'balance_dirty')) {
- $table->boolean('balance_dirty')->default(true)->after('balance_after');
+ if (Schema::hasColumn('transactions', 'balance_dirty')) {
+ $table->dropColumn('balance_dirty');
}
});
} catch (QueryException $e) {
@@ -68,14 +68,14 @@ return new class() extends Migration {
}
/**
- * Reverse the migrations.
+ * Run the migrations.
*/
- public function down(): void
+ public function up(): void
{
try {
Schema::table('transactions', static function (Blueprint $table): void {
- if (Schema::hasColumn('transactions', 'balance_before')) {
- $table->dropColumn('balance_before');
+ if (!Schema::hasColumn('transactions', 'balance_before')) {
+ $table->decimal('balance_before', 32, 12)->nullable()->after('amount');
}
});
} catch (QueryException $e) {
@@ -85,8 +85,8 @@ return new class() extends Migration {
try {
Schema::table('transactions', static function (Blueprint $table): void {
- if (Schema::hasColumn('transactions', 'balance_after')) {
- $table->dropColumn('balance_after');
+ if (!Schema::hasColumn('transactions', 'balance_after')) {
+ $table->decimal('balance_after', 32, 12)->nullable()->after('balance_before');
}
});
} catch (QueryException $e) {
@@ -96,8 +96,8 @@ return new class() extends Migration {
try {
Schema::table('transactions', static function (Blueprint $table): void {
- if (Schema::hasColumn('transactions', 'balance_dirty')) {
- $table->dropColumn('balance_dirty');
+ if (!Schema::hasColumn('transactions', 'balance_dirty')) {
+ $table->boolean('balance_dirty')->default(true)->after('balance_after');
}
});
} catch (QueryException $e) {
diff --git a/database/migrations/2024_11_05_062108_add_date_tz_columns.php b/database/migrations/2024_11_05_062108_add_date_tz_columns.php
index 068e49bf98..47705b5752 100644
--- a/database/migrations/2024_11_05_062108_add_date_tz_columns.php
+++ b/database/migrations/2024_11_05_062108_add_date_tz_columns.php
@@ -48,6 +48,13 @@ return new class() extends Migration {
];
}
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ }
+
/**
* Run the migrations.
* TODO journal_meta, all date fields?
@@ -72,11 +79,4 @@ return new class() extends Migration {
}
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- }
};
diff --git a/database/migrations/2024_11_30_075826_multi_piggy.php b/database/migrations/2024_11_30_075826_multi_piggy.php
index f7b81f5e87..733cb1154e 100644
--- a/database/migrations/2024_11_30_075826_multi_piggy.php
+++ b/database/migrations/2024_11_30_075826_multi_piggy.php
@@ -28,6 +28,60 @@ use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
return new class() extends Migration {
+ protected static function hasForeign(string $table, string $column): bool
+ {
+ $foreignKeysDefinitions = Schema::getForeignKeys($table);
+ foreach ($foreignKeysDefinitions as $foreignKeyDefinition) {
+ if ($foreignKeyDefinition['name'] === $column) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::table('piggy_banks', static function (Blueprint $table): void {
+ // 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
+ if (self::hasForeign('piggy_banks', 'unique_currency')) {
+ $table->dropForeign('unique_currency');
+ }
+ $table->dropColumn('transaction_currency_id');
+
+ // 2. make column non-nullable.
+ $table->unsignedInteger('account_id')->nullable()->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): void {
+ // 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');
+ }
+
/**
* Run the migrations.
*/
@@ -114,58 +168,4 @@ return new class() extends Migration {
});
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- Schema::table('piggy_banks', static function (Blueprint $table): void {
- // 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
- if (self::hasForeign('piggy_banks', 'unique_currency')) {
- $table->dropForeign('unique_currency');
- }
- $table->dropColumn('transaction_currency_id');
-
- // 2. make column non-nullable.
- $table->unsignedInteger('account_id')->nullable()->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): void {
- // 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');
- }
-
- protected static function hasForeign(string $table, string $column): bool
- {
- $foreignKeysDefinitions = Schema::getForeignKeys($table);
- foreach ($foreignKeysDefinitions as $foreignKeyDefinition) {
- if ($foreignKeyDefinition['name'] === $column) {
- return true;
- }
- }
-
- return false;
- }
};
diff --git a/database/migrations/2024_12_19_061003_add_native_amount_column.php b/database/migrations/2024_12_19_061003_add_native_amount_column.php
index 75dbe1bf4d..4776b05fff 100644
--- a/database/migrations/2024_12_19_061003_add_native_amount_column.php
+++ b/database/migrations/2024_12_19_061003_add_native_amount_column.php
@@ -41,32 +41,32 @@ return new class() extends Migration {
];
/**
- * Run the migrations.
+ * Reverse the migrations.
*/
- public function up(): void
+ public function down(): void
{
foreach ($this->tables as $table => $fields) {
foreach ($fields as $field) {
- Schema::table($table, static function (Blueprint $tableObject) use ($table, $field): void {
+ Schema::table($table, static function (Blueprint $table) use ($field): void {
// add amount column
- if (!Schema::hasColumn($table, $field)) {
- $tableObject->decimal($field, 32, 12)->nullable();
- }
+ $table->dropColumn($field);
});
}
}
}
/**
- * Reverse the migrations.
+ * Run the migrations.
*/
- public function down(): void
+ public function up(): void
{
foreach ($this->tables as $table => $fields) {
foreach ($fields as $field) {
- Schema::table($table, static function (Blueprint $table) use ($field): void {
+ Schema::table($table, static function (Blueprint $tableObject) use ($table, $field): void {
// add amount column
- $table->dropColumn($field);
+ if (!Schema::hasColumn($table, $field)) {
+ $tableObject->decimal($field, 32, 12)->nullable();
+ }
});
}
}
diff --git a/database/migrations/2025_07_10_065736_rename_tag_mode.php b/database/migrations/2025_07_10_065736_rename_tag_mode.php
index 79cbe3610b..d001bd4d4b 100644
--- a/database/migrations/2025_07_10_065736_rename_tag_mode.php
+++ b/database/migrations/2025_07_10_065736_rename_tag_mode.php
@@ -27,21 +27,14 @@ use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
- * Run the migrations.
+ * Reverse the migrations.
*/
- public function up(): void
+ public function down(): void
{
try {
- // normal case
Schema::table('tags', static function (Blueprint $table): void {
- if (Schema::hasColumn('tags', 'tagMode') && !Schema::hasColumn('piggy_banks', 'tag_mode')) {
- $table->renameColumn('tagMode', 'tag_mode');
- }
- });
- // lower case just in case (haha)
- Schema::table('tags', static function (Blueprint $table): void {
- if (Schema::hasColumn('tags', 'tagmode') && !Schema::hasColumn('piggy_banks', 'tag_mode')) {
- $table->renameColumn('tagmode', 'tag_mode');
+ if (Schema::hasColumn('tags', 'tag_mode') && !Schema::hasColumn('piggy_banks', 'tagMode')) {
+ $table->renameColumn('tag_mode', 'tagMode');
}
});
} catch (RuntimeException $e) {
@@ -50,14 +43,21 @@ return new class extends Migration {
}
/**
- * Reverse the migrations.
+ * Run the migrations.
*/
- public function down(): void
+ public function up(): void
{
try {
+ // normal case
Schema::table('tags', static function (Blueprint $table): void {
- if (Schema::hasColumn('tags', 'tag_mode') && !Schema::hasColumn('piggy_banks', 'tagMode')) {
- $table->renameColumn('tag_mode', 'tagMode');
+ if (Schema::hasColumn('tags', 'tagMode') && !Schema::hasColumn('piggy_banks', 'tag_mode')) {
+ $table->renameColumn('tagMode', 'tag_mode');
+ }
+ });
+ // lower case just in case (haha)
+ Schema::table('tags', static function (Blueprint $table): void {
+ if (Schema::hasColumn('tags', 'tagmode') && !Schema::hasColumn('piggy_banks', 'tag_mode')) {
+ $table->renameColumn('tagmode', 'tag_mode');
}
});
} catch (RuntimeException $e) {
diff --git a/database/migrations/2025_08_19_180459_create_webhook_details_tables.php b/database/migrations/2025_08_19_180459_create_webhook_details_tables.php
index 68fc3fb6d5..4709fc81a2 100644
--- a/database/migrations/2025_08_19_180459_create_webhook_details_tables.php
+++ b/database/migrations/2025_08_19_180459_create_webhook_details_tables.php
@@ -29,6 +29,20 @@ return new class extends Migration {
private const TABLE_ALREADY_EXISTS = 'If this table exists already (see the error message), this is not a problem. Other errors? Please open a discussion on GitHub.';
private const TABLE_ERROR = 'Could not create table "%s": %s';
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('webhook_webhook_delivery');
+ Schema::dropIfExists('webhook_webhook_trigger');
+ Schema::dropIfExists('webhook_webhook_response');
+
+ Schema::dropIfExists('webhook_triggers');
+ Schema::dropIfExists('webhook_responses');
+ Schema::dropIfExists('webhook_deliveries');
+ }
+
/**
* Run the migrations.
*/
@@ -119,18 +133,4 @@ return new class extends Migration {
}
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- Schema::dropIfExists('webhook_webhook_delivery');
- Schema::dropIfExists('webhook_webhook_trigger');
- Schema::dropIfExists('webhook_webhook_response');
-
- Schema::dropIfExists('webhook_triggers');
- Schema::dropIfExists('webhook_responses');
- Schema::dropIfExists('webhook_deliveries');
- }
};
diff --git a/database/migrations/2025_09_25_175248_create_period_statistics.php b/database/migrations/2025_09_25_175248_create_period_statistics.php
index e4f66dea79..fc2f12fde8 100644
--- a/database/migrations/2025_09_25_175248_create_period_statistics.php
+++ b/database/migrations/2025_09_25_175248_create_period_statistics.php
@@ -5,6 +5,14 @@ use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('period_statistics');
+ }
+
/**
* Run the migrations.
*/
@@ -41,12 +49,4 @@ return new class extends Migration {
});
}
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- Schema::dropIfExists('period_statistics');
- }
};
diff --git a/database/migrations/2026_01_28_201901_migrations_01_2026.php b/database/migrations/2026_01_28_201901_migrations_01_2026.php
index 27518eab1f..20c6460adb 100644
--- a/database/migrations/2026_01_28_201901_migrations_01_2026.php
+++ b/database/migrations/2026_01_28_201901_migrations_01_2026.php
@@ -8,6 +8,14 @@ use Illuminate\Support\Facades\Schema;
* Fixes #11620
*/
return new class extends Migration {
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ //
+ }
+
public function up(): void
{
Schema::table('transactions', static function (Blueprint $blueprint): void {
@@ -21,12 +29,4 @@ return new class extends Migration {
$blueprint->index(['deleted_at'], 'idx_tj_deleted');
});
}
-
- /**
- * Reverse the migrations.
- */
- public function down(): void
- {
- //
- }
};
diff --git a/database/seeders/ExchangeRateSeeder.php b/database/seeders/ExchangeRateSeeder.php
index c5229d0413..f45a119f7c 100644
--- a/database/seeders/ExchangeRateSeeder.php
+++ b/database/seeders/ExchangeRateSeeder.php
@@ -71,16 +71,6 @@ class ExchangeRateSeeder extends Seeder
}
}
- private function getCurrency(string $code): null|TransactionCurrency
- {
- return TransactionCurrency::whereNull('deleted_at')->where('code', $code)->first();
- }
-
- private function hasRate(User $user, TransactionCurrency $from, TransactionCurrency $to, string $date): bool
- {
- return $user->currencyExchangeRates()->where('from_currency_id', $from->id)->where('to_currency_id', $to->id)->where('date', $date)->count() > 0;
- }
-
/**
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
@@ -95,4 +85,14 @@ class ExchangeRateSeeder extends Seeder
'rate' => $rate
]);
}
+
+ private function getCurrency(string $code): null|TransactionCurrency
+ {
+ return TransactionCurrency::whereNull('deleted_at')->where('code', $code)->first();
+ }
+
+ private function hasRate(User $user, TransactionCurrency $from, TransactionCurrency $to, string $date): bool
+ {
+ return $user->currencyExchangeRates()->where('from_currency_id', $from->id)->where('to_currency_id', $to->id)->where('date', $date)->count() > 0;
+ }
}
diff --git a/package-lock.json b/package-lock.json
index a79d1562b2..c2c45b6eb8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1710,9 +1710,9 @@
"license": "MIT"
},
"node_modules/@esbuild/aix-ppc64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
- "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",
+ "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",
"cpu": [
"ppc64"
],
@@ -1727,9 +1727,9 @@
}
},
"node_modules/@esbuild/android-arm": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",
- "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz",
+ "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==",
"cpu": [
"arm"
],
@@ -1744,9 +1744,9 @@
}
},
"node_modules/@esbuild/android-arm64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",
- "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz",
+ "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==",
"cpu": [
"arm64"
],
@@ -1761,9 +1761,9 @@
}
},
"node_modules/@esbuild/android-x64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",
- "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz",
+ "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==",
"cpu": [
"x64"
],
@@ -1778,9 +1778,9 @@
}
},
"node_modules/@esbuild/darwin-arm64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz",
- "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz",
+ "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==",
"cpu": [
"arm64"
],
@@ -1795,9 +1795,9 @@
}
},
"node_modules/@esbuild/darwin-x64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",
- "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz",
+ "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==",
"cpu": [
"x64"
],
@@ -1812,9 +1812,9 @@
}
},
"node_modules/@esbuild/freebsd-arm64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",
- "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz",
+ "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==",
"cpu": [
"arm64"
],
@@ -1829,9 +1829,9 @@
}
},
"node_modules/@esbuild/freebsd-x64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",
- "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz",
+ "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==",
"cpu": [
"x64"
],
@@ -1846,9 +1846,9 @@
}
},
"node_modules/@esbuild/linux-arm": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",
- "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz",
+ "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==",
"cpu": [
"arm"
],
@@ -1863,9 +1863,9 @@
}
},
"node_modules/@esbuild/linux-arm64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",
- "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz",
+ "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==",
"cpu": [
"arm64"
],
@@ -1880,9 +1880,9 @@
}
},
"node_modules/@esbuild/linux-ia32": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",
- "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz",
+ "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==",
"cpu": [
"ia32"
],
@@ -1897,9 +1897,9 @@
}
},
"node_modules/@esbuild/linux-loong64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",
- "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz",
+ "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==",
"cpu": [
"loong64"
],
@@ -1914,9 +1914,9 @@
}
},
"node_modules/@esbuild/linux-mips64el": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",
- "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz",
+ "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==",
"cpu": [
"mips64el"
],
@@ -1931,9 +1931,9 @@
}
},
"node_modules/@esbuild/linux-ppc64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",
- "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz",
+ "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==",
"cpu": [
"ppc64"
],
@@ -1948,9 +1948,9 @@
}
},
"node_modules/@esbuild/linux-riscv64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",
- "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz",
+ "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==",
"cpu": [
"riscv64"
],
@@ -1965,9 +1965,9 @@
}
},
"node_modules/@esbuild/linux-s390x": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",
- "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz",
+ "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==",
"cpu": [
"s390x"
],
@@ -1982,9 +1982,9 @@
}
},
"node_modules/@esbuild/linux-x64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",
- "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz",
+ "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==",
"cpu": [
"x64"
],
@@ -1999,9 +1999,9 @@
}
},
"node_modules/@esbuild/netbsd-arm64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",
- "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz",
+ "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",
"cpu": [
"arm64"
],
@@ -2016,9 +2016,9 @@
}
},
"node_modules/@esbuild/netbsd-x64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",
- "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz",
+ "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==",
"cpu": [
"x64"
],
@@ -2033,9 +2033,9 @@
}
},
"node_modules/@esbuild/openbsd-arm64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",
- "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz",
+ "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",
"cpu": [
"arm64"
],
@@ -2050,9 +2050,9 @@
}
},
"node_modules/@esbuild/openbsd-x64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",
- "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz",
+ "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==",
"cpu": [
"x64"
],
@@ -2067,9 +2067,9 @@
}
},
"node_modules/@esbuild/openharmony-arm64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",
- "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz",
+ "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",
"cpu": [
"arm64"
],
@@ -2084,9 +2084,9 @@
}
},
"node_modules/@esbuild/sunos-x64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",
- "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz",
+ "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==",
"cpu": [
"x64"
],
@@ -2101,9 +2101,9 @@
}
},
"node_modules/@esbuild/win32-arm64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",
- "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz",
+ "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==",
"cpu": [
"arm64"
],
@@ -2118,9 +2118,9 @@
}
},
"node_modules/@esbuild/win32-ia32": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",
- "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz",
+ "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==",
"cpu": [
"ia32"
],
@@ -2135,9 +2135,9 @@
}
},
"node_modules/@esbuild/win32-x64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",
- "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz",
+ "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==",
"cpu": [
"x64"
],
@@ -3246,9 +3246,9 @@
"license": "MIT"
},
"node_modules/@types/node": {
- "version": "25.2.0",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-25.2.0.tgz",
- "integrity": "sha512-DZ8VwRFUNzuqJ5khrvwMXHmvPe+zGayJhr2CDNiKB1WBE1ST8Djl00D0IC4vvNmHMdj6DlbYRIaFE7WHjlDl5w==",
+ "version": "25.2.1",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-25.2.1.tgz",
+ "integrity": "sha512-CPrnr8voK8vC6eEtyRzvMpgp3VyVRhgclonE7qYi6P9sXwYb59ucfrnmFBTaP0yUi8Gk4yZg/LlTJULGxvTNsg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4578,9 +4578,9 @@
}
},
"node_modules/caniuse-lite": {
- "version": "1.0.30001767",
- "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001767.tgz",
- "integrity": "sha512-34+zUAMhSH+r+9eKmYG+k2Rpt8XttfE4yXAjoZvkAPs15xcYQhyBYdalJ65BzivAvGRMViEjy6oKr/S91loekQ==",
+ "version": "1.0.30001769",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001769.tgz",
+ "integrity": "sha512-BCfFL1sHijQlBGWBMuJyhZUhzo7wer5sVj9hqekB/7xn0Ypy+pER/edCYQm4exbXj4WiySGp40P8UuTh6w1srg==",
"dev": true,
"funding": [
{
@@ -5943,9 +5943,9 @@
}
},
"node_modules/esbuild": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",
- "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==",
+ "version": "0.27.3",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz",
+ "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
@@ -5956,32 +5956,32 @@
"node": ">=18"
},
"optionalDependencies": {
- "@esbuild/aix-ppc64": "0.27.2",
- "@esbuild/android-arm": "0.27.2",
- "@esbuild/android-arm64": "0.27.2",
- "@esbuild/android-x64": "0.27.2",
- "@esbuild/darwin-arm64": "0.27.2",
- "@esbuild/darwin-x64": "0.27.2",
- "@esbuild/freebsd-arm64": "0.27.2",
- "@esbuild/freebsd-x64": "0.27.2",
- "@esbuild/linux-arm": "0.27.2",
- "@esbuild/linux-arm64": "0.27.2",
- "@esbuild/linux-ia32": "0.27.2",
- "@esbuild/linux-loong64": "0.27.2",
- "@esbuild/linux-mips64el": "0.27.2",
- "@esbuild/linux-ppc64": "0.27.2",
- "@esbuild/linux-riscv64": "0.27.2",
- "@esbuild/linux-s390x": "0.27.2",
- "@esbuild/linux-x64": "0.27.2",
- "@esbuild/netbsd-arm64": "0.27.2",
- "@esbuild/netbsd-x64": "0.27.2",
- "@esbuild/openbsd-arm64": "0.27.2",
- "@esbuild/openbsd-x64": "0.27.2",
- "@esbuild/openharmony-arm64": "0.27.2",
- "@esbuild/sunos-x64": "0.27.2",
- "@esbuild/win32-arm64": "0.27.2",
- "@esbuild/win32-ia32": "0.27.2",
- "@esbuild/win32-x64": "0.27.2"
+ "@esbuild/aix-ppc64": "0.27.3",
+ "@esbuild/android-arm": "0.27.3",
+ "@esbuild/android-arm64": "0.27.3",
+ "@esbuild/android-x64": "0.27.3",
+ "@esbuild/darwin-arm64": "0.27.3",
+ "@esbuild/darwin-x64": "0.27.3",
+ "@esbuild/freebsd-arm64": "0.27.3",
+ "@esbuild/freebsd-x64": "0.27.3",
+ "@esbuild/linux-arm": "0.27.3",
+ "@esbuild/linux-arm64": "0.27.3",
+ "@esbuild/linux-ia32": "0.27.3",
+ "@esbuild/linux-loong64": "0.27.3",
+ "@esbuild/linux-mips64el": "0.27.3",
+ "@esbuild/linux-ppc64": "0.27.3",
+ "@esbuild/linux-riscv64": "0.27.3",
+ "@esbuild/linux-s390x": "0.27.3",
+ "@esbuild/linux-x64": "0.27.3",
+ "@esbuild/netbsd-arm64": "0.27.3",
+ "@esbuild/netbsd-x64": "0.27.3",
+ "@esbuild/openbsd-arm64": "0.27.3",
+ "@esbuild/openbsd-x64": "0.27.3",
+ "@esbuild/openharmony-arm64": "0.27.3",
+ "@esbuild/sunos-x64": "0.27.3",
+ "@esbuild/win32-arm64": "0.27.3",
+ "@esbuild/win32-ia32": "0.27.3",
+ "@esbuild/win32-x64": "0.27.3"
}
},
"node_modules/escalade": {
@@ -7118,9 +7118,9 @@
}
},
"node_modules/i18next": {
- "version": "25.8.3",
- "resolved": "https://registry.npmjs.org/i18next/-/i18next-25.8.3.tgz",
- "integrity": "sha512-IC/pp2vkczdu1sBheq1eC92bLavN6fM5jH61c7Xa23PGio5ePEd+EP+re1IkO7KEM9eyeJHUxvIRxsaYTlsSyQ==",
+ "version": "25.8.4",
+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-25.8.4.tgz",
+ "integrity": "sha512-a9A0MnUjKvzjEN/26ZY1okpra9kA8MEwzYEz1BNm+IyxUKPRH6ihf0p7vj8YvULwZHKHl3zkJ6KOt4hewxBecQ==",
"funding": [
{
"type": "individual",
@@ -10290,9 +10290,9 @@
}
},
"node_modules/semver": {
- "version": "7.7.3",
- "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz",
- "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==",
+ "version": "7.7.4",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
+ "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
diff --git a/tests/integration/Api/Autocomplete/BillControllerTest.php b/tests/integration/Api/Autocomplete/BillControllerTest.php
index eba0e2b5cf..41c7d64454 100644
--- a/tests/integration/Api/Autocomplete/BillControllerTest.php
+++ b/tests/integration/Api/Autocomplete/BillControllerTest.php
@@ -43,23 +43,6 @@ final class BillControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestBills(int $count, User $user): void
- {
- for ($i = 1; $i <= $count; ++$i) {
- $bill = Bill::create([
- 'user_id' => $user->id,
- 'name' => 'Bill '.$i,
- 'user_group_id' => $user->user_group_id,
- 'amount_min' => random_int(1, 100), // random amount
- 'amount_max' => random_int(101, 200), // random amount
- 'match' => 'MIGRATED_TO_RULES',
- 'date' => '2024-01-01',
- 'repeat_freq' => 'monthly',
- 'automatch' => 1,
- ]);
- }
- }
-
public function testGivenAnUnauthenticatedRequestWhenCallingTheBillsEndpointThenReturns401HttpCode(): void
{
// test API
@@ -94,33 +77,50 @@ final class BillControllerTest extends TestCase
$response->assertJsonStructure(['*' => ['id', 'name', 'active']]);
}
- public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointWithQueryThenReturnsBillsWithLimit(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointWithQueryThenReturnsBillsThatMatchQuery(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestBills(5, $user);
- $response = $this->get(route('api.v1.autocomplete.bills', ['query' => 'Bill', 'limit' => 3]), ['Accept' => 'application/json']);
+ $this->createTestBills(20, $user);
+ $response = $this->get(route('api.v1.autocomplete.bills', ['query' => 'Bill 1', 'limit' => 20]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- $response->assertJsonCount(3);
- $response->assertJsonFragment(['name' => 'Bill 1']);
- $response->assertJsonStructure(['*' => ['id', 'name', 'active']]);
+ // Bill 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
+ $response->assertJsonCount(11);
+ $response->assertJsonMissing(['name' => 'Bill 2']);
}
- public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointWithQueryThenReturnsBillsThatMatchQuery(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointWithQueryThenReturnsBillsWithLimit(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestBills(20, $user);
- $response = $this->get(route('api.v1.autocomplete.bills', ['query' => 'Bill 1', 'limit' => 20]), ['Accept' => 'application/json']);
+ $this->createTestBills(5, $user);
+ $response = $this->get(route('api.v1.autocomplete.bills', ['query' => 'Bill', 'limit' => 3]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- // Bill 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
- $response->assertJsonCount(11);
- $response->assertJsonMissing(['name' => 'Bill 2']);
+ $response->assertJsonCount(3);
+ $response->assertJsonFragment(['name' => 'Bill 1']);
+ $response->assertJsonStructure(['*' => ['id', 'name', 'active']]);
+ }
+
+ private function createTestBills(int $count, User $user): void
+ {
+ for ($i = 1; $i <= $count; ++$i) {
+ $bill = Bill::create([
+ 'user_id' => $user->id,
+ 'name' => 'Bill '.$i,
+ 'user_group_id' => $user->user_group_id,
+ 'amount_min' => random_int(1, 100), // random amount
+ 'amount_max' => random_int(101, 200), // random amount
+ 'match' => 'MIGRATED_TO_RULES',
+ 'date' => '2024-01-01',
+ 'repeat_freq' => 'monthly',
+ 'automatch' => 1,
+ ]);
+ }
}
}
diff --git a/tests/integration/Api/Autocomplete/BudgetControllerTest.php b/tests/integration/Api/Autocomplete/BudgetControllerTest.php
index ddace5d35f..24cd2f4326 100644
--- a/tests/integration/Api/Autocomplete/BudgetControllerTest.php
+++ b/tests/integration/Api/Autocomplete/BudgetControllerTest.php
@@ -43,18 +43,6 @@ final class BudgetControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestBudgets(int $count, User $user): void
- {
- for ($i = 1; $i <= $count; ++$i) {
- $budget = Budget::create([
- 'user_id' => $user->id,
- 'name' => 'Budget '.$i,
- 'user_group_id' => $user->user_group_id,
- 'active' => 1,
- ]);
- }
- }
-
public function testGivenAnUnauthenticatedRequestWhenCallingTheBudgetsEndpointThenReturns401HttpCode(): void
{
// test API
@@ -89,31 +77,43 @@ final class BudgetControllerTest extends TestCase
$response->assertJsonStructure(['*' => ['id', 'name']]);
}
- public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsWithLimit(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsThatMatchQuery(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestBudgets(5, $user);
- $response = $this->get(route('api.v1.autocomplete.budgets', ['query' => 'Budget', 'limit' => 3]), ['Accept' => 'application/json']);
+ $this->createTestBudgets(20, $user);
+ $response = $this->get(route('api.v1.autocomplete.budgets', ['query' => 'Budget 1', 'limit' => 20]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- $response->assertJsonCount(3);
+ // Budget 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
+ $response->assertJsonCount(11);
+ $response->assertJsonMissing(['name' => 'Budget 2']);
}
- public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsThatMatchQuery(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsWithLimit(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestBudgets(20, $user);
- $response = $this->get(route('api.v1.autocomplete.budgets', ['query' => 'Budget 1', 'limit' => 20]), ['Accept' => 'application/json']);
+ $this->createTestBudgets(5, $user);
+ $response = $this->get(route('api.v1.autocomplete.budgets', ['query' => 'Budget', 'limit' => 3]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- // Budget 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
- $response->assertJsonCount(11);
- $response->assertJsonMissing(['name' => 'Budget 2']);
+ $response->assertJsonCount(3);
+ }
+
+ private function createTestBudgets(int $count, User $user): void
+ {
+ for ($i = 1; $i <= $count; ++$i) {
+ $budget = Budget::create([
+ 'user_id' => $user->id,
+ 'name' => 'Budget '.$i,
+ 'user_group_id' => $user->user_group_id,
+ 'active' => 1,
+ ]);
+ }
}
}
diff --git a/tests/integration/Api/Autocomplete/CategoryControllerTest.php b/tests/integration/Api/Autocomplete/CategoryControllerTest.php
index 79a9d4d012..547573ea34 100644
--- a/tests/integration/Api/Autocomplete/CategoryControllerTest.php
+++ b/tests/integration/Api/Autocomplete/CategoryControllerTest.php
@@ -43,13 +43,6 @@ final class CategoryControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestCategories(int $count, User $user): void
- {
- for ($i = 1; $i <= $count; ++$i) {
- $category = Category::create(['user_id' => $user->id, 'name' => 'Category '.$i, 'user_group_id' => $user->user_group_id]);
- }
- }
-
public function testGivenAnUnauthenticatedRequestWhenCallingTheCategoriesEndpointThenReturns401HttpCode(): void
{
// test API
@@ -84,31 +77,38 @@ final class CategoryControllerTest extends TestCase
$response->assertJsonStructure(['*' => ['id', 'name']]);
}
- public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointWithQueryThenReturnsCategoriesWithLimit(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointWithQueryThenReturnsCategoriesThatMatchQuery(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestCategories(5, $user);
- $response = $this->get(route('api.v1.autocomplete.categories', ['query' => 'Category', 'limit' => 3]), ['Accept' => 'application/json']);
+ $this->createTestCategories(20, $user);
+ $response = $this->get(route('api.v1.autocomplete.categories', ['query' => 'Category 1', 'limit' => 20]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- $response->assertJsonCount(3);
+ // Category 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
+ $response->assertJsonCount(11);
+ $response->assertJsonMissing(['name' => 'Category 2']);
}
- public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointWithQueryThenReturnsCategoriesThatMatchQuery(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointWithQueryThenReturnsCategoriesWithLimit(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestCategories(20, $user);
- $response = $this->get(route('api.v1.autocomplete.categories', ['query' => 'Category 1', 'limit' => 20]), ['Accept' => 'application/json']);
+ $this->createTestCategories(5, $user);
+ $response = $this->get(route('api.v1.autocomplete.categories', ['query' => 'Category', 'limit' => 3]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- // Category 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
- $response->assertJsonCount(11);
- $response->assertJsonMissing(['name' => 'Category 2']);
+ $response->assertJsonCount(3);
+ }
+
+ private function createTestCategories(int $count, User $user): void
+ {
+ for ($i = 1; $i <= $count; ++$i) {
+ $category = Category::create(['user_id' => $user->id, 'name' => 'Category '.$i, 'user_group_id' => $user->user_group_id]);
+ }
}
}
diff --git a/tests/integration/Api/Autocomplete/CurrencyControllerTest.php b/tests/integration/Api/Autocomplete/CurrencyControllerTest.php
index 8df8d87cdb..9a9cbe76bf 100644
--- a/tests/integration/Api/Autocomplete/CurrencyControllerTest.php
+++ b/tests/integration/Api/Autocomplete/CurrencyControllerTest.php
@@ -42,19 +42,6 @@ final class CurrencyControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestCurrencies(int $count, bool $enabled): void
- {
- for ($i = 1; $i <= $count; ++$i) {
- $currency = TransactionCurrency::create([
- 'name' => 'Currency '.$i,
- 'code' => 'CUR'.$i,
- 'symbol' => 'C'.$i,
- 'decimal_places' => $i,
- 'enabled' => $enabled,
- ]);
- }
- }
-
public function testGivenAnUnauthenticatedRequestWhenCallingTheCurrenciesEndpointThenReturns401HttpCode(): void
{
// test API
@@ -64,6 +51,22 @@ final class CurrencyControllerTest extends TestCase
$response->assertContent('{"message":"Unauthenticated.","exception":"AuthenticationException"}');
}
+ public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointDoesNotReturnDisabledCurrencies(): void
+ {
+ // act as a user
+ $user = $this->createAuthenticatedUser();
+ $this->actingAs($user);
+
+ // create test data
+ $this->createTestCurrencies(10, false);
+
+ // test API
+ $response = $this->get(route('api.v1.autocomplete.currencies'), ['Accept' => 'application/json']);
+ $response->assertStatus(200);
+ $response->assertHeader('Content-Type', 'application/json');
+ $response->assertJsonCount(1); // always connects to EUR.
+ }
+
public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointThenReturns200HttpCode(): void
{
// act as a user
@@ -96,20 +99,17 @@ final class CurrencyControllerTest extends TestCase
$response->assertJsonCount(10);
}
- public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointDoesNotReturnDisabledCurrencies(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointWithQueryThenReturnsCurrenciesThatMatchQuery(): void
{
- // act as a user
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- // create test data
- $this->createTestCurrencies(10, false);
-
- // test API
- $response = $this->get(route('api.v1.autocomplete.currencies'), ['Accept' => 'application/json']);
+ $this->createTestCurrencies(20, true);
+ $response = $this->get(route('api.v1.autocomplete.currencies', ['query' => 'Currency 1', 'limit' => 20]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- $response->assertJsonCount(1); // always connects to EUR.
+ // Currency 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
+ $response->assertJsonCount(11);
}
public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointWithQueryThenReturnsCurrenciesWithLimit(): void
@@ -131,16 +131,16 @@ final class CurrencyControllerTest extends TestCase
$response->assertJsonCount(1);
}
- public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointWithQueryThenReturnsCurrenciesThatMatchQuery(): void
+ private function createTestCurrencies(int $count, bool $enabled): void
{
- $user = $this->createAuthenticatedUser();
- $this->actingAs($user);
-
- $this->createTestCurrencies(20, true);
- $response = $this->get(route('api.v1.autocomplete.currencies', ['query' => 'Currency 1', 'limit' => 20]), ['Accept' => 'application/json']);
- $response->assertStatus(200);
- $response->assertHeader('Content-Type', 'application/json');
- // Currency 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
- $response->assertJsonCount(11);
+ for ($i = 1; $i <= $count; ++$i) {
+ $currency = TransactionCurrency::create([
+ 'name' => 'Currency '.$i,
+ 'code' => 'CUR'.$i,
+ 'symbol' => 'C'.$i,
+ 'decimal_places' => $i,
+ 'enabled' => $enabled,
+ ]);
+ }
}
}
diff --git a/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php b/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php
index 7ff8f16f8e..064522d651 100644
--- a/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php
+++ b/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php
@@ -43,18 +43,6 @@ final class ObjectGroupControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestObjectGroups(int $count, User $user): void
- {
- for ($i = 1; $i <= $count; ++$i) {
- $objectGroup = ObjectGroup::create([
- 'title' => 'Object Group '.$i,
- 'order' => $i,
- 'user_group_id' => $user->user_group_id,
- 'user_id' => $user->id,
- ]);
- }
- }
-
public function testGivenAnUnauthenticatedRequestWhenCallingTheObjectGroupEndpointThenReturn401HttpCode(): void
{
$response = $this->get(route('api.v1.autocomplete.object-groups'), ['Accept' => 'application/json']);
@@ -89,33 +77,45 @@ final class ObjectGroupControllerTest extends TestCase
$response->assertJsonStructure(['*' => ['id', 'name', 'title']]);
}
- public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointWithQueryThenReturnsObjectGroupsWithLimit(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointWithQueryThenReturnsObjectGroupsThatMatchQuery(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestObjectGroups(5, $user);
- $response = $this->get(route('api.v1.autocomplete.object-groups', ['query' => 'Object Group', 'limit' => 3]), ['Accept' => 'application/json']);
+ $this->createTestObjectGroups(20, $user);
+ $response = $this->get(route('api.v1.autocomplete.object-groups', ['query' => 'Object Group 1', 'limit' => 20]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- $response->assertJsonCount(3);
- $response->assertJsonFragment(['name' => 'Object Group 1']);
- $response->assertJsonStructure(['*' => ['id', 'name', 'title']]);
+ // Object Group 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
+ $response->assertJsonCount(11);
+ $response->assertJsonMissing(['name' => 'Object Group 2']);
}
- public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointWithQueryThenReturnsObjectGroupsThatMatchQuery(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointWithQueryThenReturnsObjectGroupsWithLimit(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestObjectGroups(20, $user);
- $response = $this->get(route('api.v1.autocomplete.object-groups', ['query' => 'Object Group 1', 'limit' => 20]), ['Accept' => 'application/json']);
+ $this->createTestObjectGroups(5, $user);
+ $response = $this->get(route('api.v1.autocomplete.object-groups', ['query' => 'Object Group', 'limit' => 3]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- // Object Group 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
- $response->assertJsonCount(11);
- $response->assertJsonMissing(['name' => 'Object Group 2']);
+ $response->assertJsonCount(3);
+ $response->assertJsonFragment(['name' => 'Object Group 1']);
+ $response->assertJsonStructure(['*' => ['id', 'name', 'title']]);
+ }
+
+ private function createTestObjectGroups(int $count, User $user): void
+ {
+ for ($i = 1; $i <= $count; ++$i) {
+ $objectGroup = ObjectGroup::create([
+ 'title' => 'Object Group '.$i,
+ 'order' => $i,
+ 'user_group_id' => $user->user_group_id,
+ 'user_id' => $user->id,
+ ]);
+ }
}
}
diff --git a/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php b/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php
index 8d7d3614af..dc2d53c31a 100644
--- a/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php
+++ b/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php
@@ -47,37 +47,6 @@ final class PiggyBankControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestPiggyBanks(int $count, User $user): void
- {
- $type = AccountType::whereType(AccountTypeEnum::DEFAULT->value)->first();
- if (null === $type) {
- $type = AccountType::create(['type' => AccountTypeEnum::DEFAULT->value]);
- }
- $currency = TransactionCurrency::whereCode('EUR')->first();
- if (null === $currency) {
- $currency = TransactionCurrency::create(['code' => 'EUR', 'name' => 'Euro', 'symbol' => '€']);
- }
- for ($i = 1; $i <= $count; ++$i) {
- $piggyBank = PiggyBank::create([
- 'user_id' => $user->id,
- 'name' => 'Piggy bank '.$i,
- 'target_amount' => 1000,
- 'transaction_currency_id' => $currency->id,
- 'target_date' => now()->addDays(30),
- 'user_group_id' => $user->user_group_id,
- 'active' => 1,
- ]);
- $account = Account::create([
- 'user_id' => $user->id,
- 'name' => 'Account '.$i,
- 'user_group_id' => $user->user_group_id,
- 'account_type_id' => $type->id,
- 'active' => 1,
- ]);
- $piggyBank->accounts()->save($account);
- }
- }
-
public function testGivenAnUnauthenticatedRequestWhenCallingTheBudgetsEndpointThenReturns401HttpCode(): void
{
// test API
@@ -112,31 +81,62 @@ final class PiggyBankControllerTest extends TestCase
$response->assertJsonStructure(['*' => ['id', 'name']]);
}
- public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsWithLimit(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsThatMatchQuery(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestPiggyBanks(5, $user);
- $response = $this->get(route('api.v1.autocomplete.piggy-banks', ['query' => 'Piggy', 'limit' => 3]), ['Accept' => 'application/json']);
+ $this->createTestPiggyBanks(20, $user);
+ $response = $this->get(route('api.v1.autocomplete.piggy-banks', ['query' => 'Piggy bank 1', 'limit' => 20]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- $response->assertJsonCount(3);
+ // Budget 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
+ $response->assertJsonCount(11);
+ $response->assertJsonMissing(['name' => 'Piggy bank 2']);
}
- public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsThatMatchQuery(): void
+ public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsWithLimit(): void
{
$user = $this->createAuthenticatedUser();
$this->actingAs($user);
- $this->createTestPiggyBanks(20, $user);
- $response = $this->get(route('api.v1.autocomplete.piggy-banks', ['query' => 'Piggy bank 1', 'limit' => 20]), ['Accept' => 'application/json']);
+ $this->createTestPiggyBanks(5, $user);
+ $response = $this->get(route('api.v1.autocomplete.piggy-banks', ['query' => 'Piggy', 'limit' => 3]), ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/json');
- // Budget 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11)
- $response->assertJsonCount(11);
- $response->assertJsonMissing(['name' => 'Piggy bank 2']);
+ $response->assertJsonCount(3);
+ }
+
+ private function createTestPiggyBanks(int $count, User $user): void
+ {
+ $type = AccountType::whereType(AccountTypeEnum::DEFAULT->value)->first();
+ if (null === $type) {
+ $type = AccountType::create(['type' => AccountTypeEnum::DEFAULT->value]);
+ }
+ $currency = TransactionCurrency::whereCode('EUR')->first();
+ if (null === $currency) {
+ $currency = TransactionCurrency::create(['code' => 'EUR', 'name' => 'Euro', 'symbol' => '€']);
+ }
+ for ($i = 1; $i <= $count; ++$i) {
+ $piggyBank = PiggyBank::create([
+ 'user_id' => $user->id,
+ 'name' => 'Piggy bank '.$i,
+ 'target_amount' => 1000,
+ 'transaction_currency_id' => $currency->id,
+ 'target_date' => now()->addDays(30),
+ 'user_group_id' => $user->user_group_id,
+ 'active' => 1,
+ ]);
+ $account = Account::create([
+ 'user_id' => $user->id,
+ 'name' => 'Account '.$i,
+ 'user_group_id' => $user->user_group_id,
+ 'account_type_id' => $type->id,
+ 'active' => 1,
+ ]);
+ $piggyBank->accounts()->save($account);
+ }
}
}
diff --git a/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php b/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php
index db9fa25329..230ec4ab47 100644
--- a/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php
+++ b/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php
@@ -43,32 +43,6 @@ final class RecurrenceControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestRecurrences(int $count, User $user): void
- {
- for ($i = 1; $i <= $count; ++$i) {
- $recurrence = Recurrence::create([
- 'user_id' => $user->id,
- 'user_group_id' => $user->user_group_id,
- 'transaction_type_id' => 1,
- 'title' => 'Recurrence '.$i,
- 'description' => 'Recurrence '.$i,
- 'first_date' => today(),
- 'apply_rules' => 1,
- 'active' => 1,
- 'repetitions' => 5,
- ]);
- }
- }
-
- public function testUnAuthenticatedCall(): void
- {
- // test API
- $response = $this->get(route('api.v1.autocomplete.recurring'), ['Accept' => 'application/json']);
- $response->assertStatus(401);
- $response->assertHeader('Content-Type', 'application/json');
- $response->assertContent('{"message":"Unauthenticated.","exception":"AuthenticationException"}');
- }
-
public function testAuthenticatedCall(): void
{
// act as a user
@@ -123,4 +97,30 @@ final class RecurrenceControllerTest extends TestCase
$response->assertJsonCount(11);
$response->assertJsonMissing(['name' => 'Recurrence 2']);
}
+
+ public function testUnAuthenticatedCall(): void
+ {
+ // test API
+ $response = $this->get(route('api.v1.autocomplete.recurring'), ['Accept' => 'application/json']);
+ $response->assertStatus(401);
+ $response->assertHeader('Content-Type', 'application/json');
+ $response->assertContent('{"message":"Unauthenticated.","exception":"AuthenticationException"}');
+ }
+
+ private function createTestRecurrences(int $count, User $user): void
+ {
+ for ($i = 1; $i <= $count; ++$i) {
+ $recurrence = Recurrence::create([
+ 'user_id' => $user->id,
+ 'user_group_id' => $user->user_group_id,
+ 'transaction_type_id' => 1,
+ 'title' => 'Recurrence '.$i,
+ 'description' => 'Recurrence '.$i,
+ 'first_date' => today(),
+ 'apply_rules' => 1,
+ 'active' => 1,
+ 'repetitions' => 5,
+ ]);
+ }
+ }
}
diff --git a/tests/integration/Api/Autocomplete/RuleControllerTest.php b/tests/integration/Api/Autocomplete/RuleControllerTest.php
index 76181d0925..0b5eae1a88 100644
--- a/tests/integration/Api/Autocomplete/RuleControllerTest.php
+++ b/tests/integration/Api/Autocomplete/RuleControllerTest.php
@@ -42,41 +42,6 @@ final class RuleControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestRules(int $count, User $user): void
- {
- $ruleGroup = RuleGroup::create([
- 'user_id' => $user->id,
- 'user_group_id' => $user->user_group_id,
- 'title' => 'RuleGroup 1',
- 'description' => 'RuleGroup 1',
- 'order' => 1,
- 'active' => 1,
- 'stop_processing' => 0,
- ]);
- for ($i = 1; $i <= $count; ++$i) {
- $rule = Rule::create([
- 'user_id' => $user->id,
- 'user_group_id' => $user->user_group_id,
- 'rule_group_id' => $ruleGroup->id,
- 'title' => 'Rule '.$i,
- 'description' => 'Rule '.$i,
- 'order' => 1,
- 'active' => 1,
- 'stop_processing' => 0,
- 'strict' => 0,
- ]);
- }
- }
-
- public function testUnauthenticatedCall(): void
- {
- // test API
- $response = $this->get(route('api.v1.autocomplete.rules'), ['Accept' => 'application/json']);
- $response->assertStatus(401);
- $response->assertHeader('Content-Type', 'application/json');
- $response->assertContent('{"message":"Unauthenticated.","exception":"AuthenticationException"}');
- }
-
public function testAuthenticatedCall(): void
{
// act as a user
@@ -131,4 +96,39 @@ final class RuleControllerTest extends TestCase
$response->assertJsonCount(11);
$response->assertJsonMissing(['name' => 'Rule 2']);
}
+
+ public function testUnauthenticatedCall(): void
+ {
+ // test API
+ $response = $this->get(route('api.v1.autocomplete.rules'), ['Accept' => 'application/json']);
+ $response->assertStatus(401);
+ $response->assertHeader('Content-Type', 'application/json');
+ $response->assertContent('{"message":"Unauthenticated.","exception":"AuthenticationException"}');
+ }
+
+ private function createTestRules(int $count, User $user): void
+ {
+ $ruleGroup = RuleGroup::create([
+ 'user_id' => $user->id,
+ 'user_group_id' => $user->user_group_id,
+ 'title' => 'RuleGroup 1',
+ 'description' => 'RuleGroup 1',
+ 'order' => 1,
+ 'active' => 1,
+ 'stop_processing' => 0,
+ ]);
+ for ($i = 1; $i <= $count; ++$i) {
+ $rule = Rule::create([
+ 'user_id' => $user->id,
+ 'user_group_id' => $user->user_group_id,
+ 'rule_group_id' => $ruleGroup->id,
+ 'title' => 'Rule '.$i,
+ 'description' => 'Rule '.$i,
+ 'order' => 1,
+ 'active' => 1,
+ 'stop_processing' => 0,
+ 'strict' => 0,
+ ]);
+ }
+ }
}
diff --git a/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php b/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php
index 61ef3340d5..0131a14f35 100644
--- a/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php
+++ b/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php
@@ -41,30 +41,6 @@ final class RuleGroupControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestRuleGroups(int $count, User $user): void
- {
- for ($i = 1; $i <= $count; ++$i) {
- $ruleGroup = RuleGroup::create([
- 'user_id' => $user->id,
- 'user_group_id' => $user->user_group_id,
- 'title' => 'RuleGroup '.$i,
- 'description' => 'RuleGroup '.$i,
- 'order' => 1,
- 'active' => 1,
- 'stop_processing' => 0,
- ]);
- }
- }
-
- public function testUnauthenticatedCall(): void
- {
- // test API
- $response = $this->get(route('api.v1.autocomplete.rule-groups'), ['Accept' => 'application/json']);
- $response->assertStatus(401);
- $response->assertHeader('Content-Type', 'application/json');
- $response->assertContent('{"message":"Unauthenticated.","exception":"AuthenticationException"}');
- }
-
public function testAuthenticatedCall(): void
{
// act as a user
@@ -119,4 +95,28 @@ final class RuleGroupControllerTest extends TestCase
$response->assertJsonCount(11);
$response->assertJsonMissing(['name' => 'RuleGroup 2']);
}
+
+ public function testUnauthenticatedCall(): void
+ {
+ // test API
+ $response = $this->get(route('api.v1.autocomplete.rule-groups'), ['Accept' => 'application/json']);
+ $response->assertStatus(401);
+ $response->assertHeader('Content-Type', 'application/json');
+ $response->assertContent('{"message":"Unauthenticated.","exception":"AuthenticationException"}');
+ }
+
+ private function createTestRuleGroups(int $count, User $user): void
+ {
+ for ($i = 1; $i <= $count; ++$i) {
+ $ruleGroup = RuleGroup::create([
+ 'user_id' => $user->id,
+ 'user_group_id' => $user->user_group_id,
+ 'title' => 'RuleGroup '.$i,
+ 'description' => 'RuleGroup '.$i,
+ 'order' => 1,
+ 'active' => 1,
+ 'stop_processing' => 0,
+ ]);
+ }
+ }
}
diff --git a/tests/integration/Api/Autocomplete/TagControllerTest.php b/tests/integration/Api/Autocomplete/TagControllerTest.php
index 7904ec1ec6..0069fbdef9 100644
--- a/tests/integration/Api/Autocomplete/TagControllerTest.php
+++ b/tests/integration/Api/Autocomplete/TagControllerTest.php
@@ -41,27 +41,6 @@ final class TagControllerTest extends TestCase
*/
use RefreshDatabase;
- private function createTestTags(int $count, User $user): void
- {
- for ($i = 1; $i <= $count; ++$i) {
- $tag = Tag::create([
- 'user_id' => $user->id,
- 'user_group_id' => $user->user_group_id,
- 'tag' => 'Tag '.$i,
- 'tag_mode' => 'nothing',
- ]);
- }
- }
-
- public function testUnauthenticatedCall(): void
- {
- // test API
- $response = $this->get(route('api.v1.autocomplete.tags'), ['Accept' => 'application/json']);
- $response->assertStatus(401);
- $response->assertHeader('Content-Type', 'application/json');
- $response->assertContent('{"message":"Unauthenticated.","exception":"AuthenticationException"}');
- }
-
public function testAuthenticatedCall(): void
{
// act as a user
@@ -116,4 +95,25 @@ final class TagControllerTest extends TestCase
$response->assertJsonCount(11);
$response->assertJsonMissing(['name' => 'Tag 2']);
}
+
+ public function testUnauthenticatedCall(): void
+ {
+ // test API
+ $response = $this->get(route('api.v1.autocomplete.tags'), ['Accept' => 'application/json']);
+ $response->assertStatus(401);
+ $response->assertHeader('Content-Type', 'application/json');
+ $response->assertContent('{"message":"Unauthenticated.","exception":"AuthenticationException"}');
+ }
+
+ private function createTestTags(int $count, User $user): void
+ {
+ for ($i = 1; $i <= $count; ++$i) {
+ $tag = Tag::create([
+ 'user_id' => $user->id,
+ 'user_group_id' => $user->user_group_id,
+ 'tag' => 'Tag '.$i,
+ 'tag_mode' => 'nothing',
+ ]);
+ }
+ }
}
diff --git a/tests/integration/Api/Chart/AccountControllerTest.php b/tests/integration/Api/Chart/AccountControllerTest.php
index 3e609b6bbb..aa9df496f4 100644
--- a/tests/integration/Api/Chart/AccountControllerTest.php
+++ b/tests/integration/Api/Chart/AccountControllerTest.php
@@ -40,15 +40,12 @@ final class AccountControllerTest extends TestCase
private ?User $user = null;
- #[Override]
- protected function setUp(): void
+ public function testGetOverviewChart(): void
{
- parent::setUp();
-
- if (!$this->user instanceof User) {
- $this->user = $this->createAuthenticatedUser();
- }
$this->actingAs($this->user);
+ $params = ['start' => '2024-01-01', 'end' => '2024-01-31'];
+ $response = $this->getJson(route('api.v1.chart.account.overview').'?'.http_build_query($params));
+ $response->assertStatus(200);
}
public function testGetOverviewChartFails(): void
@@ -58,11 +55,14 @@ final class AccountControllerTest extends TestCase
$response->assertStatus(422);
}
- public function testGetOverviewChart(): void
+ #[Override]
+ protected function setUp(): void
{
+ parent::setUp();
+
+ if (!$this->user instanceof User) {
+ $this->user = $this->createAuthenticatedUser();
+ }
$this->actingAs($this->user);
- $params = ['start' => '2024-01-01', 'end' => '2024-01-31'];
- $response = $this->getJson(route('api.v1.chart.account.overview').'?'.http_build_query($params));
- $response->assertStatus(200);
}
}
diff --git a/tests/integration/Api/Chart/BalanceControllerTest.php b/tests/integration/Api/Chart/BalanceControllerTest.php
index 06f31505d7..e9055a2786 100644
--- a/tests/integration/Api/Chart/BalanceControllerTest.php
+++ b/tests/integration/Api/Chart/BalanceControllerTest.php
@@ -40,15 +40,12 @@ final class BalanceControllerTest extends TestCase
private ?User $user = null;
- #[Override]
- protected function setUp(): void
+ public function testGetOverviewChart(): void
{
- parent::setUp();
-
- if (!$this->user instanceof User) {
- $this->user = $this->createAuthenticatedUser();
- }
$this->actingAs($this->user);
+ $params = ['start' => '2024-01-01', 'end' => '2024-01-31'];
+ $response = $this->getJson(route('api.v1.chart.balance.balance').'?'.http_build_query($params));
+ $response->assertStatus(200);
}
public function testGetOverviewChartFails(): void
@@ -58,11 +55,14 @@ final class BalanceControllerTest extends TestCase
$response->assertStatus(422);
}
- public function testGetOverviewChart(): void
+ #[Override]
+ protected function setUp(): void
{
+ parent::setUp();
+
+ if (!$this->user instanceof User) {
+ $this->user = $this->createAuthenticatedUser();
+ }
$this->actingAs($this->user);
- $params = ['start' => '2024-01-01', 'end' => '2024-01-31'];
- $response = $this->getJson(route('api.v1.chart.balance.balance').'?'.http_build_query($params));
- $response->assertStatus(200);
}
}
diff --git a/tests/integration/Api/Chart/BudgetControllerTest.php b/tests/integration/Api/Chart/BudgetControllerTest.php
index fc275cc70a..a316a7dbfa 100644
--- a/tests/integration/Api/Chart/BudgetControllerTest.php
+++ b/tests/integration/Api/Chart/BudgetControllerTest.php
@@ -40,15 +40,12 @@ final class BudgetControllerTest extends TestCase
private ?User $user = null;
- #[Override]
- protected function setUp(): void
+ public function testGetOverviewChart(): void
{
- parent::setUp();
-
- if (!$this->user instanceof User) {
- $this->user = $this->createAuthenticatedUser();
- }
$this->actingAs($this->user);
+ $params = ['start' => '2024-01-01', 'end' => '2024-01-31'];
+ $response = $this->getJson(route('api.v1.chart.budget.overview').'?'.http_build_query($params));
+ $response->assertStatus(200);
}
public function testGetOverviewChartFails(): void
@@ -58,11 +55,14 @@ final class BudgetControllerTest extends TestCase
$response->assertStatus(422);
}
- public function testGetOverviewChart(): void
+ #[Override]
+ protected function setUp(): void
{
+ parent::setUp();
+
+ if (!$this->user instanceof User) {
+ $this->user = $this->createAuthenticatedUser();
+ }
$this->actingAs($this->user);
- $params = ['start' => '2024-01-01', 'end' => '2024-01-31'];
- $response = $this->getJson(route('api.v1.chart.budget.overview').'?'.http_build_query($params));
- $response->assertStatus(200);
}
}
diff --git a/tests/integration/Api/Chart/CategoryControllerTest.php b/tests/integration/Api/Chart/CategoryControllerTest.php
index 9ee47b495f..cee6e3a0f5 100644
--- a/tests/integration/Api/Chart/CategoryControllerTest.php
+++ b/tests/integration/Api/Chart/CategoryControllerTest.php
@@ -40,15 +40,12 @@ final class CategoryControllerTest extends TestCase
private ?User $user = null;
- #[Override]
- protected function setUp(): void
+ public function testGetOverviewChart(): void
{
- parent::setUp();
-
- if (!$this->user instanceof User) {
- $this->user = $this->createAuthenticatedUser();
- }
$this->actingAs($this->user);
+ $params = ['start' => '2024-01-01', 'end' => '2024-01-31'];
+ $response = $this->getJson(route('api.v1.chart.category.overview').'?'.http_build_query($params));
+ $response->assertStatus(200);
}
public function testGetOverviewChartFails(): void
@@ -58,11 +55,14 @@ final class CategoryControllerTest extends TestCase
$response->assertStatus(422);
}
- public function testGetOverviewChart(): void
+ #[Override]
+ protected function setUp(): void
{
+ parent::setUp();
+
+ if (!$this->user instanceof User) {
+ $this->user = $this->createAuthenticatedUser();
+ }
$this->actingAs($this->user);
- $params = ['start' => '2024-01-01', 'end' => '2024-01-31'];
- $response = $this->getJson(route('api.v1.chart.category.overview').'?'.http_build_query($params));
- $response->assertStatus(200);
}
}
diff --git a/tests/integration/Api/Models/Account/ListControllerTest.php b/tests/integration/Api/Models/Account/ListControllerTest.php
index 2c4c816876..7990994ed9 100644
--- a/tests/integration/Api/Models/Account/ListControllerTest.php
+++ b/tests/integration/Api/Models/Account/ListControllerTest.php
@@ -44,6 +44,22 @@ final class ListControllerTest extends TestCase
private User $user;
private Account $account;
+ public function testIndex(): void
+ {
+ $this->actingAs($this->user);
+ $response = $this->getJson(route('api.v1.accounts.attachments', ['account' => $this->account->id]));
+ $response->assertStatus(200);
+ $response->assertJson(['meta' => ['pagination' => ['total' => 2, 'total_pages' => 1]]]);
+ }
+
+ public function testIndexCanChangePageSize(): void
+ {
+ $this->actingAs($this->user);
+ $response = $this->getJson(route('api.v1.accounts.attachments', ['account' => $this->account->id, 'limit' => 1]));
+ $response->assertStatus(200);
+ $response->assertJson(['meta' => ['pagination' => ['total' => 2, 'total_pages' => 2]]]);
+ }
+
#[Override]
protected function setUp(): void
{
@@ -76,20 +92,4 @@ final class ListControllerTest extends TestCase
])
;
}
-
- public function testIndex(): void
- {
- $this->actingAs($this->user);
- $response = $this->getJson(route('api.v1.accounts.attachments', ['account' => $this->account->id]));
- $response->assertStatus(200);
- $response->assertJson(['meta' => ['pagination' => ['total' => 2, 'total_pages' => 1]]]);
- }
-
- public function testIndexCanChangePageSize(): void
- {
- $this->actingAs($this->user);
- $response = $this->getJson(route('api.v1.accounts.attachments', ['account' => $this->account->id, 'limit' => 1]));
- $response->assertStatus(200);
- $response->assertJson(['meta' => ['pagination' => ['total' => 2, 'total_pages' => 2]]]);
- }
}
diff --git a/tests/integration/Api/Models/Account/ShowControllerTest.php b/tests/integration/Api/Models/Account/ShowControllerTest.php
index 4963a14ed2..f2b3aae24f 100644
--- a/tests/integration/Api/Models/Account/ShowControllerTest.php
+++ b/tests/integration/Api/Models/Account/ShowControllerTest.php
@@ -42,6 +42,33 @@ final class ShowControllerTest extends TestCase
private User $user;
+ public function testIndex(): void
+ {
+ $this->actingAs($this->user);
+ $response = $this->getJson(route('api.v1.accounts.index'));
+ $response->assertStatus(200);
+ $response->assertJson(['meta' => ['pagination' => ['total' => 5]]]);
+ }
+
+ public function testIndexCanFilterOnAccountType(): void
+ {
+ $this->actingAs($this->user);
+ $response = $this->getJson(route('api.v1.accounts.index').'?type=asset');
+ $response->assertStatus(200);
+ $response->assertJson([
+ 'data' => [['attributes' => ['type' => 'asset']], ['attributes' => ['type' => 'asset']]],
+ 'meta' => ['pagination' => ['total' => 2]],
+ ]);
+ }
+
+ public function testIndexFailsOnUnknownAccountType(): void
+ {
+ $this->actingAs($this->user);
+ $response = $this->getJson(route('api.v1.accounts.index').'?type=foobar');
+ $response->assertStatus(422);
+ $response->assertJson(['errors' => ['type' => ['The selected type is invalid.']]]);
+ }
+
#[Override]
protected function setUp(): void
{
@@ -73,34 +100,6 @@ final class ShowControllerTest extends TestCase
Account::factory()
->for($this->user)
->withType(AccountTypeEnum::ASSET)
- ->create()
- ;
- }
-
- public function testIndex(): void
- {
- $this->actingAs($this->user);
- $response = $this->getJson(route('api.v1.accounts.index'));
- $response->assertStatus(200);
- $response->assertJson(['meta' => ['pagination' => ['total' => 5]]]);
- }
-
- public function testIndexFailsOnUnknownAccountType(): void
- {
- $this->actingAs($this->user);
- $response = $this->getJson(route('api.v1.accounts.index').'?type=foobar');
- $response->assertStatus(422);
- $response->assertJson(['errors' => ['type' => ['The selected type is invalid.']]]);
- }
-
- public function testIndexCanFilterOnAccountType(): void
- {
- $this->actingAs($this->user);
- $response = $this->getJson(route('api.v1.accounts.index').'?type=asset');
- $response->assertStatus(200);
- $response->assertJson([
- 'data' => [['attributes' => ['type' => 'asset']], ['attributes' => ['type' => 'asset']]],
- 'meta' => ['pagination' => ['total' => 2]],
- ]);
+ ->create();
}
}
diff --git a/tests/integration/Api/System/AboutControllerTest.php b/tests/integration/Api/System/AboutControllerTest.php
index 4e68500110..b81ee40422 100644
--- a/tests/integration/Api/System/AboutControllerTest.php
+++ b/tests/integration/Api/System/AboutControllerTest.php
@@ -43,17 +43,6 @@ final class AboutControllerTest extends TestCase
private ?User $user = null;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
-
- if (!$this->user instanceof User) {
- $this->user = $this->createAuthenticatedUser();
- }
- $this->actingAs($this->user);
- }
-
public function testGivenAuthenticatedRequestReturnsSystemInformation(): void
{
$response = $this->getJson(route('api.v1.about.index'));
@@ -72,4 +61,15 @@ final class AboutControllerTest extends TestCase
$this->user->role
));
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ if (!$this->user instanceof User) {
+ $this->user = $this->createAuthenticatedUser();
+ }
+ $this->actingAs($this->user);
+ }
}
diff --git a/tests/integration/Support/Models/BillDateCalculatorTest.php b/tests/integration/Support/Models/BillDateCalculatorTest.php
index 98970a331a..d7f29570f6 100644
--- a/tests/integration/Support/Models/BillDateCalculatorTest.php
+++ b/tests/integration/Support/Models/BillDateCalculatorTest.php
@@ -41,13 +41,6 @@ final class BillDateCalculatorTest extends TestCase
{
private BillDateCalculator $calculator;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
- $this->calculator = new BillDateCalculator();
- }
-
/**
* Stupid long method names I'm not going to do that.
*/
@@ -126,4 +119,11 @@ final class BillDateCalculatorTest extends TestCase
['2024-05-01'],
];
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->calculator = new BillDateCalculator();
+ }
}
diff --git a/tests/integration/TestCase.php b/tests/integration/TestCase.php
index 3288708011..342cc4cd7a 100644
--- a/tests/integration/TestCase.php
+++ b/tests/integration/TestCase.php
@@ -57,11 +57,6 @@ abstract class TestCase extends BaseTestCase
];
}
- protected function getAuthenticatedUser(): User
- {
- return User::where('email', 'james@firefly')->first();
- }
-
protected function createAuthenticatedUser(): User
{
$group = UserGroup::create(['title' => '[email protected]']);
@@ -72,4 +67,9 @@ abstract class TestCase extends BaseTestCase
return $user;
}
+
+ protected function getAuthenticatedUser(): User
+ {
+ return User::where('email', 'james@firefly')->first();
+ }
}
diff --git a/tests/unit/Support/Calendar/CalculatorProvider.php b/tests/unit/Support/Calendar/CalculatorProvider.php
index 3681275b8f..d2e6feb550 100644
--- a/tests/unit/Support/Calendar/CalculatorProvider.php
+++ b/tests/unit/Support/Calendar/CalculatorProvider.php
@@ -41,6 +41,11 @@ readonly class CalculatorProvider
$this->label = "{$this->periodicity->name} {$this->intervalProvider->label}";
}
+ public static function from(Periodicity $periodicity, IntervalProvider $interval, int $skip = 0): self
+ {
+ return new self($interval, $periodicity, $skip);
+ }
+
public static function providePeriodicityWithSkippedIntervals(): Generator
{
$intervals = [
@@ -115,11 +120,6 @@ readonly class CalculatorProvider
}
}
- public static function from(Periodicity $periodicity, IntervalProvider $interval, int $skip = 0): self
- {
- return new self($interval, $periodicity, $skip);
- }
-
public function epoch(): Carbon
{
return $this->intervalProvider->epoch;
diff --git a/tests/unit/Support/Calendar/Periodicity/IntervalTestCase.php b/tests/unit/Support/Calendar/Periodicity/IntervalTestCase.php
index 0654ab3247..85f906fe8f 100644
--- a/tests/unit/Support/Calendar/Periodicity/IntervalTestCase.php
+++ b/tests/unit/Support/Calendar/Periodicity/IntervalTestCase.php
@@ -30,6 +30,8 @@ use Tests\integration\TestCase;
abstract class IntervalTestCase extends TestCase
{
+ abstract public static function factory(): Interval;
+
abstract public static function provideIntervals(): array;
#[DataProvider('provider')]
@@ -48,6 +50,4 @@ abstract class IntervalTestCase extends TestCase
yield "{$interval->label}" => [$interval];
}
}
-
- abstract public static function factory(): Interval;
}
diff --git a/tests/unit/Support/NavigationAddPeriodTest.php b/tests/unit/Support/NavigationAddPeriodTest.php
index 71acc3bd13..869334f4b5 100644
--- a/tests/unit/Support/NavigationAddPeriodTest.php
+++ b/tests/unit/Support/NavigationAddPeriodTest.php
@@ -44,13 +44,6 @@ final class NavigationAddPeriodTest extends TestCase
{
private Navigation $navigation;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
- $this->navigation = new Navigation();
- }
-
#[DataProvider('providePeriodsWithSkippingParam')]
public function testGivenAFrequencyAndSkipIntervalWhenCalculateTheDateThenReturnsTheSkippedDateSuccessful(
int $skip,
@@ -368,4 +361,11 @@ final class NavigationAddPeriodTest extends TestCase
yield '2023-10-31 to 2023-11-30' => ['monthly', Carbon::parse('2023-10-31'), Carbon::parse('2023-11-30')];
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->navigation = new Navigation();
+ }
}
diff --git a/tests/unit/Support/NavigationEndOfPeriodTest.php b/tests/unit/Support/NavigationEndOfPeriodTest.php
index 5eb565387c..2ea8e0bf1f 100644
--- a/tests/unit/Support/NavigationEndOfPeriodTest.php
+++ b/tests/unit/Support/NavigationEndOfPeriodTest.php
@@ -43,13 +43,6 @@ final class NavigationEndOfPeriodTest extends TestCase
{
private Navigation $navigation;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
- $this->navigation = new Navigation();
- }
-
#[DataProvider('provideDates')]
public function testGivenADateAndFrequencyWhenCalculateTheDateThenReturnsTheExpectedDateSuccessful(string $frequency, Carbon $from, Carbon $expected): void
{
@@ -215,4 +208,11 @@ final class NavigationEndOfPeriodTest extends TestCase
yield 'empty' => ['', Carbon::now(), Carbon::now()->startOfDay()];
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->navigation = new Navigation();
+ }
}
diff --git a/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php b/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php
index 3ec82efb3d..2667163631 100644
--- a/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php
+++ b/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php
@@ -42,13 +42,6 @@ final class NavigationPreferredCarbonFormatByPeriodTest extends TestCase
{
private Navigation $navigation;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
- $this->navigation = new Navigation();
- }
-
#[DataProvider('providePeriods')]
public function testGivenAPeriodWhenCallPreferredCarbonFormatByPeriodThenReturnsExpectedFormat(string $period, string $expected): void
{
@@ -70,4 +63,11 @@ final class NavigationPreferredCarbonFormatByPeriodTest extends TestCase
yield 'yearly' => ['1Y', 'Y'];
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->navigation = new Navigation();
+ }
}
diff --git a/tests/unit/Support/NavigationPreferredCarbonFormatTest.php b/tests/unit/Support/NavigationPreferredCarbonFormatTest.php
index 8c85182e57..21cadb07a1 100644
--- a/tests/unit/Support/NavigationPreferredCarbonFormatTest.php
+++ b/tests/unit/Support/NavigationPreferredCarbonFormatTest.php
@@ -43,13 +43,6 @@ final class NavigationPreferredCarbonFormatTest extends TestCase
{
private Navigation $navigation;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
- $this->navigation = new Navigation();
- }
-
#[DataProvider('providePeriods')]
public function testGivenStartAndEndDatesWhenCallPreferredCarbonFormatThenReturnsTheExpectedFormatSuccessful(
Carbon $start,
@@ -86,4 +79,11 @@ final class NavigationPreferredCarbonFormatTest extends TestCase
yield '2 years' => [Carbon::now(), Carbon::now()->addYears(2), 'Y'];
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->navigation = new Navigation();
+ }
}
diff --git a/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php b/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php
index 01fd9d35c1..fba3ad0ecc 100644
--- a/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php
+++ b/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php
@@ -43,13 +43,6 @@ final class NavigationPreferredEndOfPeriodTest extends TestCase
{
private Navigation $navigation;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
- $this->navigation = new Navigation();
- }
-
#[DataProvider('providePeriods')]
public function testGivenStartAndEndDatesWhenCallPreferredEndOfPeriodThenReturnsTheExpectedFormatSuccessful(
Carbon $start,
@@ -86,4 +79,11 @@ final class NavigationPreferredEndOfPeriodTest extends TestCase
yield '2 years' => [Carbon::now(), Carbon::now()->addYears(2), 'endOfYear'];
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->navigation = new Navigation();
+ }
}
diff --git a/tests/unit/Support/NavigationPreferredRangeFormatTest.php b/tests/unit/Support/NavigationPreferredRangeFormatTest.php
index 5e9fe0e6e8..5e00acd41b 100644
--- a/tests/unit/Support/NavigationPreferredRangeFormatTest.php
+++ b/tests/unit/Support/NavigationPreferredRangeFormatTest.php
@@ -43,13 +43,6 @@ final class NavigationPreferredRangeFormatTest extends TestCase
{
private Navigation $navigation;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
- $this->navigation = new Navigation();
- }
-
#[DataProvider('providePeriods')]
public function testGivenStartAndEndDatesWhenCallPreferredRangeFormatThenReturnsTheExpectedFormatSuccessful(
Carbon $start,
@@ -86,4 +79,11 @@ final class NavigationPreferredRangeFormatTest extends TestCase
yield '2 years' => [Carbon::now(), Carbon::now()->addYears(2), '1Y'];
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->navigation = new Navigation();
+ }
}
diff --git a/tests/unit/Support/NavigationPreferredSqlFormatTest.php b/tests/unit/Support/NavigationPreferredSqlFormatTest.php
index ff92f1f724..a7f4b92d32 100644
--- a/tests/unit/Support/NavigationPreferredSqlFormatTest.php
+++ b/tests/unit/Support/NavigationPreferredSqlFormatTest.php
@@ -43,13 +43,6 @@ final class NavigationPreferredSqlFormatTest extends TestCase
{
private Navigation $navigation;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
- $this->navigation = new Navigation();
- }
-
#[DataProvider('provideDates')]
public function testGivenStartAndEndDatesWhenCallPreferredSqlFormatThenReturnsTheExpectedFormatSuccessful(
Carbon $start,
@@ -86,4 +79,11 @@ final class NavigationPreferredSqlFormatTest extends TestCase
yield '2 years' => [Carbon::now(), Carbon::now()->addYears(2), '%Y'];
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->navigation = new Navigation();
+ }
}
diff --git a/tests/unit/Support/NavigationStartOfPeriodTest.php b/tests/unit/Support/NavigationStartOfPeriodTest.php
index 4fec705705..1817e0ec34 100644
--- a/tests/unit/Support/NavigationStartOfPeriodTest.php
+++ b/tests/unit/Support/NavigationStartOfPeriodTest.php
@@ -44,13 +44,6 @@ final class NavigationStartOfPeriodTest extends TestCase
{
private Navigation $navigation;
- #[Override]
- protected function setUp(): void
- {
- parent::setUp();
- $this->navigation = new Navigation();
- }
-
#[DataProvider('provideDates')]
public function testGivenADateAndFrequencyWhenCalculateTheDateThenReturnsTheExpectedDateSuccessful(string $frequency, Carbon $from, Carbon $expected): void
{
@@ -131,4 +124,11 @@ final class NavigationStartOfPeriodTest extends TestCase
yield 'empty' => ['', Carbon::now(), Carbon::now()->startOfDay()];
}
+
+ #[Override]
+ protected function setUp(): void
+ {
+ parent::setUp();
+ $this->navigation = new Navigation();
+ }
}
diff --git a/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php b/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php
index fd60b31039..6b8809a45b 100644
--- a/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php
+++ b/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php
@@ -34,8 +34,6 @@ use Tests\integration\TestCase;
abstract class AbstractQueryParserInterfaceParseQueryTester extends TestCase
{
- abstract protected function createParser(): QueryParserInterface;
-
/**
* @param string $query The query string to parse
* @param Node $expected The expected parse result
@@ -147,4 +145,6 @@ abstract class AbstractQueryParserInterfaceParseQueryTester extends TestCase
new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')]), new StringNode('shopping')]),
];
}
+
+ abstract protected function createParser(): QueryParserInterface;
}