Skip to content

Firefly III: a personal finances manager

Pull some preferences more efficiently.

James Cole011475f4c443
diff --git a/app/Api/V1/Controllers/User/PreferencesController.php b/app/Api/V1/Controllers/User/PreferencesController.php
index 9171c0751a..a0deb33374 100644
--- a/app/Api/V1/Controllers/User/PreferencesController.php
+++ b/app/Api/V1/Controllers/User/PreferencesController.php
@@ -33,6 +33,7 @@ use FireflyIII\Support\Facades\Preferences;
use FireflyIII\Transformers\PreferenceTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
+use Illuminate\Support\Collection;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Resource\Collection as FractalCollection;
use League\Fractal\Resource\Item;
@@ -60,14 +61,14 @@ final class PreferencesController extends Controller
$preferences = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
// make paginator:
- $paginator = new LengthAwarePaginator($preferences, $count, $pageSize, $this->parameters->get('page'));
- $paginator->setPath(route('api.v1.preferences.index').$this->buildParams());
+ $paginator = new LengthAwarePaginator($preferences, $count, $pageSize, $this->parameters->get('page'));
+ $paginator->setPath(route('api.v1.preferences.index') . $this->buildParams());
/** @var PreferenceTransformer $transformer */
$transformer = app(PreferenceTransformer::class);
$transformer->setParameters($this->parameters);
- $resource = new FractalCollection($preferences, $transformer, self::RESOURCE_KEY);
+ $resource = new FractalCollection($preferences, $transformer, self::RESOURCE_KEY);
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
@@ -81,7 +82,7 @@ final class PreferencesController extends Controller
*/
public function show(Preference $preference): JsonResponse
{
- $manager = $this->getManager();
+ $manager = $this->getManager();
if ('currencyPreference' === $preference->name) {
throw new FireflyException('Please use api/v1/currencies/primary instead.');
@@ -91,7 +92,26 @@ final class PreferencesController extends Controller
$transformer = app(PreferenceTransformer::class);
$transformer->setParameters($this->parameters);
- $resource = new Item($preference, $transformer, 'preferences');
+ $resource = new Item($preference, $transformer, 'preferences');
+
+ return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
+ }
+
+ public function showList(Collection $preferenceList): JsonResponse
+ {
+ $manager = $this->getManager();
+ $count = $preferenceList->count();
+ $names = implode(',', $preferenceList->pluck('name')->toArray());
+
+ // make paginator:
+ $paginator = new LengthAwarePaginator($preferenceList, $count, 31337, 1);
+ $paginator->setPath(route('api.v1.preferences-list.show', [$names]) . $this->buildParams());
+
+ /** @var PreferenceTransformer $transformer */
+ $transformer = app(PreferenceTransformer::class);
+
+ $resource = new FractalCollection($preferenceList, $transformer, self::RESOURCE_KEY);
+ $resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
@@ -104,20 +124,20 @@ final class PreferencesController extends Controller
*/
public function store(PreferenceStoreRequest $request): JsonResponse
{
- $manager = $this->getManager();
- $data = $request->getAll();
+ $manager = $this->getManager();
+ $data = $request->getAll();
if ('currencyPreference' === $data['name']) {
throw new FireflyException('Please use api/v1/currencies/default instead.');
}
- $pref = Preferences::set($data['name'], $data['data']);
+ $pref = Preferences::set($data['name'], $data['data']);
/** @var PreferenceTransformer $transformer */
$transformer = app(PreferenceTransformer::class);
$transformer->setParameters($this->parameters);
- $resource = new Item($pref, $transformer, 'preferences');
+ $resource = new Item($pref, $transformer, 'preferences');
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
@@ -134,15 +154,15 @@ final class PreferencesController extends Controller
throw new FireflyException('Please use api/v1/currencies/primary instead.');
}
- $manager = $this->getManager();
- $data = $request->getAll();
- $pref = Preferences::set($preference->name, $data['data']);
+ $manager = $this->getManager();
+ $data = $request->getAll();
+ $pref = Preferences::set($preference->name, $data['data']);
/** @var PreferenceTransformer $transformer */
$transformer = app(PreferenceTransformer::class);
$transformer->setParameters($this->parameters);
- $resource = new Item($pref, $transformer, 'preferences');
+ $resource = new Item($pref, $transformer, 'preferences');
return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);
}
diff --git a/app/Support/Binder/PreferenceList.php b/app/Support/Binder/PreferenceList.php
new file mode 100644
index 0000000000..11d773324c
--- /dev/null
+++ b/app/Support/Binder/PreferenceList.php
@@ -0,0 +1,68 @@
+<?php
+
+/**
+ * TagList.php
+ * Copyright (c) 2019 [email protected]
+ *
+ * This file is part of Firefly III (https://github.com/firefly-iii).
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+declare(strict_types=1);
+
+namespace FireflyIII\Support\Binder;
+
+use FireflyIII\Models\Tag;
+use FireflyIII\Repositories\Tag\TagRepositoryInterface;
+use FireflyIII\Support\Facades\Preferences;
+use Illuminate\Routing\Route;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Log;
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
+
+/**
+ * Class TagList.
+ */
+class PreferenceList implements BinderInterface
+{
+ /**
+ * @throws NotFoundHttpException
+ */
+ public static function routeBinder(string $value, Route $route): Collection
+ {
+ if (auth()->check()) {
+ if ('' === $value) {
+ Log::warning('Preference list count is empty, return 404.');
+
+ throw new NotFoundHttpException();
+ }
+
+ $list = array_unique(explode(',', $value));
+ Log::debug('List of preferences is', $list);
+ $result = new Collection;
+ foreach($list as $item) {
+ $current = Preferences::get($item);
+ if(null !== $current) {
+ Log::debug(sprintf('Add %s to the result', $item));
+ $result->push($current);
+ }
+ }
+ Log::debug('List of preferences is', $result->toArray());
+ return $result;
+ }
+ Log::error('PreferenceList: user is not logged in.');
+
+ throw new NotFoundHttpException();
+ }
+}
diff --git a/config/bindables.php b/config/bindables.php
index 79839b4182..76cdcd5cdd 100644
--- a/config/bindables.php
+++ b/config/bindables.php
@@ -56,6 +56,7 @@ use FireflyIII\Support\Binder\Date;
use FireflyIII\Support\Binder\DynamicConfigKey;
use FireflyIII\Support\Binder\EitherConfigKey;
use FireflyIII\Support\Binder\JournalList;
+use FireflyIII\Support\Binder\PreferenceList;
use FireflyIII\Support\Binder\TagList;
use FireflyIII\Support\Binder\TagOrId;
use FireflyIII\Support\Binder\UserGroupAccount;
@@ -109,6 +110,7 @@ return [
'journalList' => JournalList::class,
'categoryList' => CategoryList::class,
'tagList' => TagList::class,
+ 'preferenceList' => PreferenceList::class,
// others
'fromCurrencyCode' => CurrencyCode::class,
diff --git a/resources/assets/v3/js/api/preferences/index.js b/resources/assets/v3/js/api/preferences/index.js
index c53862c7c3..fec8d11f3d 100644
--- a/resources/assets/v3/js/api/preferences/index.js
+++ b/resources/assets/v3/js/api/preferences/index.js
@@ -24,6 +24,9 @@ export default class Preferences {
getByName(name) {
return api.get('/api/v1/preferences/' + name);
}
+ getList(names) {
+ return api.get('/api/v1/preferences-list/' + names);
+ }
getByNameNow(name) {
return api.get('/api/v1/preferences/' + name);
}
diff --git a/resources/assets/v3/js/boot/bootstrap.js b/resources/assets/v3/js/boot/bootstrap.js
index 6d8dc2f812..ed13efc614 100644
--- a/resources/assets/v3/js/boot/bootstrap.js
+++ b/resources/assets/v3/js/boot/bootstrap.js
@@ -28,6 +28,7 @@ import Shepherd from 'shepherd.js';
import "cally";
import {getFreshVariable} from "../store/get-fresh-variable.js";
import {getVariable} from "../store/get-variable.js";
+import {getVariables} from "../store/get-variables.js";
import {getViewRange} from "../support/get-viewrange.js";
import {loadTranslations} from "../support/load-translations.js";
@@ -45,34 +46,32 @@ getFreshVariable('lastActivity').then((serverValue) => {
throw new Error('401 in getFreshVariable.');
}
const localValue = store.get('lastActivity');
- store.set('cacheValid', localValue === serverValue);
- store.set('lastActivity', serverValue);
- console.log('Server value: ' + serverValue);
- console.log('Local value: ' + localValue);
- console.log('Cache valid: ' + (localValue === serverValue));
+ // store.set('cacheValid', localValue === serverValue);
+ // store.set('lastActivity', serverValue);
+ // console.log('Server value: ' + serverValue);
+ // console.log('Local value: ' + localValue);
+ // console.log('Cache valid: ' + (localValue === serverValue));
}).then(() => {
- Promise.all([
- getVariable('viewRange'),
- getVariable('darkMode'),
- getVariable('locale'),
- getVariable('language')
- ]).then((values) => {
+ Promise.resolve(
+ getVariables(['viewRange','darkMode','locale','language', 'convert_to_primary']),
+ ).then((values) => {
+ console.log(values);
if (!store.get('start') || !store.get('end')) {
// calculate new start and end, and store them.
- const range = getViewRange(values[0], new Date);
+ const range = getViewRange(values.viewRange, new Date);
store.set('start', range.start);
store.set('end', range.end);
}
// save local in window.__ something
- window.__localeId__ = values[2];
- store.set('language', values[3]);
- store.set('locale', values[3]);
- loadTranslations(values[3]).then(() => {
+ window.__localeId__ = values.locale;
+ store.set('language', values.language);
+ store.set('locale', values.locale);
+ loadTranslations(values.locale).then(() => {
const event = new Event('firefly-iii-bootstrapped');
document.dispatchEvent(event);
window.bootstrapped = true;
- console.log('Bootstrapped!');
+ // console.log('Bootstrapped!');
// page may have an introduction necessary to be played.
// if (!showTour) {
diff --git a/resources/assets/v3/js/pages/generic.js b/resources/assets/v3/js/pages/generic.js
index 90d03b702b..93d5213e67 100644
--- a/resources/assets/v3/js/pages/generic.js
+++ b/resources/assets/v3/js/pages/generic.js
@@ -25,7 +25,7 @@ import dates from './shared/dates.js';
let index = function () {
return {
init() {
- console.log('Generic JS for page with few features.');
+ // console.log('Generic JS for page with few features.');
}
}
};
@@ -38,22 +38,22 @@ const comps = {
};
function loadPage(comps) {
- console.log('loadPage');
+ // console.log('loadPage');
Object.keys(comps).forEach(comp => {
let data = comps[comp]();
Alpine.data(comp, () => data);
- console.log(comp);
+ // console.log(comp);
});
Alpine.start();
}
// wait for load until bootstrapped event is received.
document.addEventListener('firefly-iii-bootstrapped', () => {
- console.log('Loaded through event listener.');
+ // console.log('Loaded through event listener.');
loadPage(comps);
});
// or is bootstrapped before event is triggered.
if (window.bootstrapped) {
- console.log('Loaded through window variable.');
+ // console.log('Loaded through window variable.');
loadPage(comps);
}
diff --git a/resources/assets/v3/js/store/get-variables.js b/resources/assets/v3/js/store/get-variables.js
new file mode 100644
index 0000000000..50b38d9b9d
--- /dev/null
+++ b/resources/assets/v3/js/store/get-variables.js
@@ -0,0 +1,102 @@
+/*
+ * get-variables.js
+ * Copyright (c) 2026 [email protected]
+ *
+ * This file is part of Firefly III (https://github.com/firefly-iii).
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+import Get from "../api/preferences/index.js";
+
+export function getVariables(preferences) {
+ console.log('Now in getVariables', preferences);
+ let chain = Promise.resolve();
+ let collectable = [];
+ let result = {};
+ const validCache = window.store.get('cacheValid');
+ // let fromStore;
+
+ // first, check cache if elements are present.
+ for (let i = 0; i < preferences.length; i++) {
+ let name = preferences[i];
+ // console.log('Now checking ' + name);
+ // currently unused, window.X can be used by the blade template
+ // to make things available quicker than if the store has to grab it through the API.
+ // then again, it's not that slow.
+ if (validCache && window.hasOwnProperty(name)) {
+ // console.log('Returning "' + name + '" from window: ' + window[name]);
+
+ chain = chain.then(() => {
+ result[name] = window[name];
+ // console.log('Result is now (a) ', result);
+ return Promise.resolve(result);
+ });
+
+ //result[name] = window[name];
+ continue;
+ }
+ // load from store2, if it's present.
+ const fromStore = window.store.get(name);
+ if (validCache && fromStore !== undefined) {
+ // console.log('Returning "' + name + '" from store: ' + fromStore);
+
+ chain = chain.then(() => {
+ result[name] = fromStore;
+ // console.log('Result is now (b) ', result);
+ return Promise.resolve(result);
+ });
+
+ // result[name] = fromStore;
+ continue;
+ }
+ // console.log('Do not have ' + name + ', must be fresh.');
+ collectable.push(name);
+ }
+ if (collectable.length > 0) {
+ let getter = (new Get);
+ // console.log('Have something to collect');
+ chain = chain.then(() => {
+ let names = collectable.join(',');
+ console.log('Will collect', names);
+ return getter.getList(names).then((response) => {
+ let parsed = parseResponses(response);
+ // console.log('Returning "' + names + '" from server: ', parsed);
+ // add to object:
+ result = Object.assign(result, parsed);
+
+ return Promise.resolve(result);
+ }).catch((error) => {
+ console.error(error);
+ });
+ });
+ }
+
+ // console.log('Final result', result);
+
+ return chain;
+}
+
+export function parseResponses(response) {
+ let result = {}
+ for (let i in response.data.data) {
+ if (response.data.data.hasOwnProperty(i)) {
+ let current = response.data.data[i];
+ result[current.attributes.name] = current.attributes.data;
+ window.store.set(current.attributes.name, current.attributes.data);
+ }
+ }
+ console.log('parseResponses', result);
+ return result;
+}
diff --git a/routes/api.php b/routes/api.php
index 34eecee26f..e19bafb8ae 100644
--- a/routes/api.php
+++ b/routes/api.php
@@ -821,6 +821,22 @@ Route::group(
}
);
+// Preference API routes:
+Route::group(
+ [
+ 'namespace' => 'FireflyIII\Api\V1\Controllers\User',
+ 'prefix' => 'v1/preferences-list',
+ 'as' => 'api.v1.preferences-list.',
+ ],
+ static function (): void {
+// Route::get('', ['uses' => 'PreferencesController@index', 'as' => 'index']);
+// Route::post('', ['uses' => 'PreferencesController@store', 'as' => 'store']);
+ // Route::get('{preferenceList}', ['uses' => 'PreferencesController@showList', 'as' => 'show-list'])->where('preferenceList', ',+');
+ Route::get('{preferenceList}', ['uses' => 'PreferencesController@showList', 'as' => 'show']);
+// Route::put('{preferenceName}', ['uses' => 'PreferencesController@update', 'as' => 'update']);
+ }
+);
+
// Webhook API routes:
Route::group(
[