Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Make exchange rate job properly multi-user
Sander Dorigoac543a894f16
diff --git a/app/Console/Commands/Tools/Cron.php b/app/Console/Commands/Tools/Cron.phpindex 41905428b9..5a4860adac 100644--- a/app/Console/Commands/Tools/Cron.php+++ b/app/Console/Commands/Tools/Cron.php@@ -37,6 +37,7 @@ use FireflyIII\Support\Cronjobs\WebhookCronjob;use FireflyIII\Support\Facades\AppConfiguration;use FireflyIII\User;use Illuminate\Console\Command;+use Illuminate\Support\Collection;use Illuminate\Support\Facades\Log;use InvalidArgumentException;@@ -57,19 +58,20 @@ class Cron extends Command{--send-webhook-messages : Sends any stray webhook messages (with a maximum of 5).}';- private User $admin;+ private Collection $users;public function handle(): int{/** @var UserRepositoryInterface $repository */$repository = app(UserRepositoryInterface::class);+ $this->users = $repository->all();+ /** @var User|null $admin */$admin = $repository->getUsersByRole('owner')->first();if (null === $admin) {$this->friendlyError('There is no user in the system with the "owner"-role, cannot continue.');return 1;}- $this->admin = $admin;$doAll = !$this->option('download-cer')&& !$this->option('create-recurring')&& !$this->option('create-auto-budgets')@@ -201,7 +203,7 @@ class Cron extends CommandLog::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__));$exchangeRates = new ExchangeRatesCronjob();$exchangeRates->setForce($force);- $exchangeRates->setUser($this->admin);+ $exchangeRates->setUsers($this->users);// set date in cron job:if ($date instanceof Carbon) {$exchangeRates->setDate($date);diff --git a/app/Jobs/DownloadExchangeRates.php b/app/Jobs/DownloadExchangeRates.phpindex 2df6368014..80832fffc0 100644--- a/app/Jobs/DownloadExchangeRates.php+++ b/app/Jobs/DownloadExchangeRates.php@@ -59,7 +59,6 @@ class DownloadExchangeRates implements ShouldQueueprivate array $active = [];private Carbon $date;private CurrencyRepositoryInterface $repository;- private Collection $users;private User $user;/**@@ -102,13 +101,6 @@ class DownloadExchangeRates implements ShouldQueuepublic function setUser(User $user): void{$this->user = $user;- $this->users = new Collection([$user]);- if ($this->user->hasRole('admin')) {- // get all users:- /** @var UserRepositoryInterface $userRepository */- $userRepository = app(UserRepositoryInterface::class);- $this->users = $userRepository->all();- }}/**@@ -179,13 +171,12 @@ class DownloadExchangeRates implements ShouldQueueprivate function saveRate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date, float $rate): void{- foreach ($this->users as $user) {- $this->repository->setUser($user);- $this->repository->setUserGroup($user->userGroup);+ $this->repository->setUser($this->user);+ $this->repository->setUserGroup($this->user->userGroup);if ($this->repository->isEnabled($from) && $this->repository->isEnabled($to)) {$existing = $this->repository->getExchangeRate($from, $to, $date);if (!$existing instanceof CurrencyExchangeRate) {- Log::debug(sprintf('Saved rate from %s to %s for user #%d.', $from->code, $to->code, $user->id));+ Log::debug(sprintf('Saved rate from %s to %s for user #%d.', $from->code, $to->code, $this->user->id));try {$this->repository->setExchangeRate($from, $to, $date, $rate);@@ -194,7 +185,6 @@ class DownloadExchangeRates implements ShouldQueue}}}- }}private function saveRates(TransactionCurrency $currency, Carbon $date, array $rates): voiddiff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.phpindex fd7d320190..0520405e97 100644--- a/app/Repositories/User/UserRepository.php+++ b/app/Repositories/User/UserRepository.php@@ -51,6 +51,11 @@ class UserRepository implements UserRepositoryInterfacereturn User::query()->orderBy('id', 'DESC')->get(['users.*']);}+ public function allAvailable(): Collection+ {+ return User::query()->orderBy('id', 'DESC')->where('users.blocked',false)->get(['users.*']);+ }+public function attachRole(User $user, string $role): bool{$roleObject = Role::query()->where('name', $role)->first();diff --git a/app/Repositories/User/UserRepositoryInterface.php b/app/Repositories/User/UserRepositoryInterface.phpindex 3591284c04..b744784b11 100644--- a/app/Repositories/User/UserRepositoryInterface.php+++ b/app/Repositories/User/UserRepositoryInterface.php@@ -49,6 +49,11 @@ interface UserRepositoryInterface*/public function all(): Collection;+ /**+ * All users that are not blocked.+ */+ public function allAvailable(): Collection;+/*** Gives a user a role.*/diff --git a/app/Support/Cronjobs/AbstractCronjob.php b/app/Support/Cronjobs/AbstractCronjob.phpindex 89636a79d8..eb8e41335e 100644--- a/app/Support/Cronjobs/AbstractCronjob.php+++ b/app/Support/Cronjobs/AbstractCronjob.php@@ -25,7 +25,9 @@ declare(strict_types=1);namespace FireflyIII\Support\Cronjobs;use Carbon\Carbon;+use FireflyIII\Exceptions\FireflyException;use FireflyIII\User;+use Illuminate\Support\Collection;/*** Class AbstractCronjob@@ -41,12 +43,14 @@ abstract class AbstractCronjobprotected bool $force = false;protected User $user;protected bool $isOwner = false;+ protected Collection $users;/*** AbstractCronjob constructor.*/public function __construct(){+ $this->users = new Collection();$this->date = today(config('app.timezone'));}@@ -65,7 +69,11 @@ abstract class AbstractCronjobfinal public function setUser(User $user): void{+ throw new FireflyException(sprintf('Do not use setUser() in %s', get_class($this)));$this->user = $user;$this->isOwner = $user->hasRole('owner');}+ final public function setUsers(Collection $users): void {+ $this->users = $users;+ }}diff --git a/app/Support/Cronjobs/ExchangeRatesCronjob.php b/app/Support/Cronjobs/ExchangeRatesCronjob.phpindex 7c0677f121..27a917f74f 100644--- a/app/Support/Cronjobs/ExchangeRatesCronjob.php+++ b/app/Support/Cronjobs/ExchangeRatesCronjob.php@@ -29,6 +29,7 @@ use FireflyIII\Jobs\DownloadExchangeRates;use FireflyIII\Models\Configuration;use FireflyIII\Support\Facades\AppConfiguration;use FireflyIII\Support\Facades\Preferences;+use FireflyIII\User;use Illuminate\Support\Facades\Log;/**@@ -38,43 +39,46 @@ class ExchangeRatesCronjob extends AbstractCronjob{public function fire(): void{- /** @var Configuration $config */- $config = AppConfiguration::get('last_cer_job', 0);- $lastTime = (int) $config->data;- $diff = now(config('app.timezone'))->getTimestamp() - $lastTime;- $diffForHumans = now(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true);- if (0 === $lastTime) {- Log::info('Exchange rates cron-job has never fired before.');- }- // less than half a day ago:- if ($lastTime > 0 && $diff <= 43_200) {- Log::info(sprintf('It has been %s since the exchange rates cron-job has fired.', $diffForHumans));- if (false === $this->force || false === $this->isOwner) {- Log::info('The exchange rates cron-job will not fire now.');- $this->message = sprintf('It has been %s since the exchange rates cron-job has fired. It will not fire now.', $diffForHumans);+ /** @var User $user */+ foreach($this->users as $user) {+ $key = sprintf('last_cer_job_%d', $user->id);+ /** @var Configuration $config */+ $config = AppConfiguration::get($key, 0);+ $lastTime = (int) $config->data;+ $diff = now(config('app.timezone'))->getTimestamp() - $lastTime;+ $diffForHumans = now(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true);+ if (0 === $lastTime) {+ Log::info(sprintf('Exchange rates cron-job has never fired before for user #%d.', $user->id));+ }+ // less than half a day ago:+ if ($lastTime > 0 && $diff <= 43_200) {+ Log::info(sprintf('It has been %s since the exchange rates cron-job has fired for user #%d.', $diffForHumans, $user->id));+ if (false === $this->force || false === $this->isOwner) {+ Log::info(sprintf('The exchange rates cron-job will not fire now for user #%d.', $user->id));+ $this->message = sprintf('It has been %s since the exchange rates cron-job has fired for user #%d. It will not fire now.', $diffForHumans, $user->id);+ continue;+ }- return;+ Log::info(sprintf('Execution of the exchange rates cron-job has been FORCED for user #%d.', $user->id));}- Log::info('Execution of the exchange rates cron-job has been FORCED.');- }+ if ($lastTime > 0 && $diff > 43_200) {+ Log::info(sprintf('It has been %s since the exchange rates cron-job has fired. It will fire now!', $diffForHumans));+ }- if ($lastTime > 0 && $diff > 43_200) {- Log::info(sprintf('It has been %s since the exchange rates cron-job has fired. It will fire now!', $diffForHumans));+ $this->fireExchangeRateJob($user);+ Preferences::mark();}-- $this->fireExchangeRateJob();- Preferences::mark();}- private function fireExchangeRateJob(): void+ private function fireExchangeRateJob(User $user): void{- Log::info(sprintf('Will now fire exchange rates cron job task for date "%s".', $this->date->format('Y-m-d')));+ Log::info(sprintf('Will now fire exchange rates cron job task for date "%s" and user #%d.', $this->date->format('Y-m-d'), $user->id));/** @var DownloadExchangeRates $job */$job = app(DownloadExchangeRates::class);$job->setDate($this->date);- $job->setUser($this->user);+ $job->setUser($user);$job->handle();// get stuff from job:@@ -83,7 +87,7 @@ class ExchangeRatesCronjob extends AbstractCronjob$this->jobSucceeded = true;$this->message = 'Exchange rates cron job fired successfully.';- AppConfiguration::set('last_cer_job', (int) $this->date->format('U'));+ AppConfiguration::set(sprintf('last_cer_job_%d', $user->id), (int) $this->date->format('U'));Log::info('Done with exchange rates job task.');}}