Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Sortable and filterable categories.
James Colefe6372aae2d8
diff --git a/app/Api/V1/Controllers/Models/Account/ShowController.php b/app/Api/V1/Controllers/Models/Account/ShowController.phpindex afd2b5d3cc..577f21490d 100644--- a/app/Api/V1/Controllers/Models/Account/ShowController.php+++ b/app/Api/V1/Controllers/Models/Account/ShowController.php@@ -29,6 +29,7 @@ use FireflyIII\Api\V1\Requests\Models\Account\ShowRequest;use FireflyIII\Models\Account;use FireflyIII\Repositories\Account\AccountRepositoryInterface;use FireflyIII\Support\Http\Api\AccountFilter;+use FireflyIII\Support\Http\Api\ChecksSortType;use FireflyIII\Support\JsonApi\Enrichments\AccountEnrichment;use FireflyIII\Transformers\AccountTransformer;use FireflyIII\User;@@ -44,6 +45,7 @@ use League\Fractal\Resource\Item;final class ShowController extends Controller{use AccountFilter;+ use ChecksSortType;public const string RESOURCE_KEY = 'accounts';@@ -151,22 +153,5 @@ final class ShowController extends Controllerreturn response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE);}- private function isAllDatabaseSort(array $instructions, string $model): bool- {- if (0 === count($instructions)) {- return true;- }- $config = config(sprintf('firefly.allowed_db_sort_parameters.%s', $model));- if (null === $config) {- return true;- }- foreach ($instructions as $item) {- $field = $item[0];- if (!in_array($field, $config, true)) {- return false;- }- }- return true;- }}diff --git a/app/Api/V1/Controllers/Models/Category/ShowController.php b/app/Api/V1/Controllers/Models/Category/ShowController.phpindex 87f24f23a7..42acd2c16e 100644--- a/app/Api/V1/Controllers/Models/Category/ShowController.php+++ b/app/Api/V1/Controllers/Models/Category/ShowController.php@@ -25,8 +25,10 @@ declare(strict_types=1);namespace FireflyIII\Api\V1\Controllers\Models\Category;use FireflyIII\Api\V1\Controllers\Controller;+use FireflyIII\Api\V1\Requests\Models\Category\ShowRequest;use FireflyIII\Models\Category;use FireflyIII\Repositories\Category\CategoryRepositoryInterface;+use FireflyIII\Support\Http\Api\ChecksSortType;use FireflyIII\Support\JsonApi\Enrichments\CategoryEnrichment;use FireflyIII\Transformers\CategoryTransformer;use FireflyIII\User;@@ -41,6 +43,7 @@ use League\Fractal\Resource\Item;*/final class ShowController extends Controller{+ use ChecksSortType;private CategoryRepositoryInterface $repository;/**@@ -63,34 +66,50 @@ final class ShowController extends Controller** Display a listing of the resource.*/- public function index(): JsonResponse+ public function index(ShowRequest $request): JsonResponse{$manager = $this->getManager();-- // types to get, page size:- $pageSize = $this->parameters->get('limit');+ [+ 'page' => $page,+ 'limit' => $limit,+ 'offset' => $offset,+ 'sort' => $sort,+ 'filter' => $filter,+ 'start' => $start,+ 'end' => $end,+ ] = $request->attributes->all();// get list of budgets. Count it and split it.- $collection = $this->repository->getCategories();+ $collection = $this->repository->getCategories($sort, $filter);$count = $collection->count();- $categories = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);+ $dbFields = $this->isAllDatabaseSort($sort, 'Category');+ $categories = $collection;+ if ($dbFields) {+ $categories = $collection->slice($offset, $limit);+ }+// enrich/** @var User $admin */$admin = auth()->user();$enrichment = new CategoryEnrichment();+ $enrichment->setSort($sort);$enrichment->setUser($admin);- $enrichment->setStart($this->parameters->get('start'));- $enrichment->setEnd($this->parameters->get('end'));+ $enrichment->setStart($start);+ $enrichment->setEnd($end);$categories = $enrichment->enrich($categories);+ if (!$dbFields) {+ // now do the slicing.+ $categories = $categories->slice($offset, $limit);+ }+// make paginator:- $paginator = new LengthAwarePaginator($categories, $count, $pageSize, $this->parameters->get('page'));+ $paginator = new LengthAwarePaginator($categories, $count, $limit, $page);$paginator->setPath(route('api.v1.categories.index').$this->buildParams());/** @var CategoryTransformer $transformer */$transformer = app(CategoryTransformer::class);- $transformer->setParameters($this->parameters);$resource = new FractalCollection($categories, $transformer, 'categories');$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));diff --git a/app/Api/V1/Requests/Models/Category/ShowRequest.php b/app/Api/V1/Requests/Models/Category/ShowRequest.phpnew file mode 100644index 0000000000..193f006c6a--- /dev/null+++ b/app/Api/V1/Requests/Models/Category/ShowRequest.php@@ -0,0 +1,46 @@+<?php++/*+ * ShowRequest.php+ * 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/>.+ */++declare(strict_types=1);++namespace FireflyIII\Api\V1\Requests\Models\Category;++use FireflyIII\Api\V1\Requests\AggregateFormRequest;+use FireflyIII\Api\V1\Requests\DateRangeRequest;+use FireflyIII\Api\V1\Requests\DateRequest;+use FireflyIII\Api\V1\Requests\Generic\ActiveObjectRequest;+use FireflyIII\Api\V1\Requests\Models\Account\AccountTypeApiRequest;+use FireflyIII\Api\V1\Requests\PaginationRequest;+use FireflyIII\Models\Account;+use FireflyIII\Models\Category;++class ShowRequest extends AggregateFormRequest+{+ protected function getRequests(): array+ {+ return [+ [PaginationRequest::class, 'sort_class' => Category::class],+ DateRangeRequest::class,+ DateRequest::class,+ ];+ }+}diff --git a/app/Models/Category.php b/app/Models/Category.phpindex 6a655e1ffe..0e3c2527ac 100644--- a/app/Models/Category.php+++ b/app/Models/Category.php@@ -44,7 +44,7 @@ class Category extends Modeluse ReturnsIntegerUserIdTrait;use SoftDeletes;- protected $fillable = ['user_id', 'user_group_id', 'name'];+ protected $fillable = ['user_id', 'user_group_id', 'name','color'];protected $hidden = ['encrypted'];diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.phpindex 70f9ed0d23..cc92999c07 100644--- a/app/Repositories/Category/CategoryRepository.php+++ b/app/Repositories/Category/CategoryRepository.php@@ -36,6 +36,8 @@ use FireflyIII\Services\Internal\Destroy\CategoryDestroyService;use FireflyIII\Services\Internal\Update\CategoryUpdateService;use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface;use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait;+use Illuminate\Database\Eloquent\Builder as EloquentBuilder;+use Illuminate\Database\Query\JoinClause;use Illuminate\Support\Collection;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Log;@@ -186,9 +188,42 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf/*** Returns a list of all the categories belonging to a user.*/- public function getCategories(): Collection+ public function getCategories(array $sort = [], array $filter = []): Collection{- return $this->user->categories()->with(['attachments'])->orderBy('name', 'ASC')->get();+ $query = $this->user->categories()->with(['attachments']);++ // add sort parameters+ $allowed = config('firefly.allowed_db_sort_parameters.Category', []);+ $sorted = 0;+ $sort ??= [];+ $filter ??= [];+ if (0 !== count($sort)) {+ foreach ($sort as $param) {+ // basic sort:+ if (in_array($param[0], $allowed, true)) {+ $query->orderBy($param[0], $param[1]);+ ++$sorted;+ }+ }+ }++ // add filter parameters.+ $allowed = config('firefly.allowed_filter_parameters.Category', []);+ if (0 !== count($filter)) {+ foreach ($filter as $field => $search) {+ if (in_array($field, $allowed, true)) {+ if ('' !== (string) $search) {+ $query->whereLike($field, sprintf('%%%s%%', $search));+ }+ }+ }+ }++ if (0 === $sorted) {+ $query->orderBy('categories.name', 'ASC');+ }++ return $query->get(['categories.*']);}public function getNoteText(Category $category): ?stringdiff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.phpindex cf48a707b0..1fd9ac7c39 100644--- a/app/Repositories/Category/CategoryRepositoryInterface.php+++ b/app/Repositories/Category/CategoryRepositoryInterface.php@@ -79,7 +79,7 @@ interface CategoryRepositoryInterface/*** Returns a list of all the categories belonging to a user.*/- public function getCategories(): Collection;+ public function getCategories(array $sort = [], array $filter = []): Collection;public function getNoteText(Category $category): ?string;diff --git a/app/Support/Http/Api/ChecksSortType.php b/app/Support/Http/Api/ChecksSortType.phpnew file mode 100644index 0000000000..2e31760b63--- /dev/null+++ b/app/Support/Http/Api/ChecksSortType.php@@ -0,0 +1,45 @@+<?php+/*+ * ChecksSortType.php+ * 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/>.+ */++declare(strict_types=1);++namespace FireflyIII\Support\Http\Api;++trait ChecksSortType {+ protected function isAllDatabaseSort(array $instructions, string $model): bool+ {+ if (0 === count($instructions)) {+ return true;+ }+ $config = config(sprintf('firefly.allowed_db_sort_parameters.%s', $model));+ if (null === $config) {+ return true;+ }+ foreach ($instructions as $item) {+ $field = $item[0];+ if (!in_array($field, $config, true)) {+ return false;+ }+ }++ return true;+ }+}diff --git a/app/Support/JsonApi/Enrichments/CategoryEnrichment.php b/app/Support/JsonApi/Enrichments/CategoryEnrichment.phpindex a9195ad015..aac65acb9d 100644--- a/app/Support/JsonApi/Enrichments/CategoryEnrichment.php+++ b/app/Support/JsonApi/Enrichments/CategoryEnrichment.php@@ -25,8 +25,11 @@ declare(strict_types=1);namespace FireflyIII\Support\JsonApi\Enrichments;use Carbon\Carbon;+use FireflyIII\Exceptions\FireflyException;+use FireflyIII\Models\Account;use FireflyIII\Models\Category;use FireflyIII\Models\Note;+use FireflyIII\Models\TransactionJournal;use FireflyIII\Models\UserGroup;use FireflyIII\Repositories\Category\OperationsRepositoryInterface;use FireflyIII\User;@@ -36,18 +39,20 @@ use Illuminate\Support\Collection;class CategoryEnrichment implements EnrichmentInterface{private Collection $collection;- private array $earned = [];- private ?Carbon $end = null;- private array $ids = [];- private array $notes = [];- private array $pcEarned = [];- private array $pcSpent = [];- private array $pcTransfers = [];- private array $spent = [];- private ?Carbon $start = null;- private array $transfers = [];- private User $user;- private UserGroup $userGroup;+ private array $earned = [];+ private ?Carbon $end = null;+ private array $ids = [];+ private array $sort = [];+ private array $notes = [];+ private array $pcEarned = [];+ private array $pcSpent = [];+ private array $pcTransfers = [];+ private array $spent = [];+ private ?Carbon $start = null;+ private array $transfers = [];+ private array $lastActivity = [];+ private User $user;+ private UserGroup $userGroup;public function enrich(Collection $collection): Collection{@@ -55,12 +60,14 @@ class CategoryEnrichment implements EnrichmentInterface$this->collectIds();$this->collectNotes();$this->collectTransactions();+ $this->collectLastActivity();$this->appendCollectedData();+ $this->sortData();- return $collection;+ return $this->collection;}- public function enrichSingle(array|Model $model): array|Model+ public function enrichSingle(array | Model $model): array | Model{// Log::debug(__METHOD__);$collection = new Collection()->push($model);@@ -93,8 +100,9 @@ class CategoryEnrichment implements EnrichmentInterfaceprivate function appendCollectedData(): void{$this->collection = $this->collection->map(function (Category $item): Category {- $id = (int) $item->id;+ $id = (int)$item->id;$meta = [+ 'last_activity' => $this->lastActivity[$id] ?? null,'notes' => $this->notes[$id] ?? null,'spent' => $this->spent[$id] ?? null,'pc_spent' => $this->pcSpent[$id] ?? null,@@ -113,23 +121,47 @@ class CategoryEnrichment implements EnrichmentInterface{/** @var Category $category */foreach ($this->collection as $category) {- $this->ids[] = (int) $category->id;+ $this->ids[] = (int)$category->id;}$this->ids = array_unique($this->ids);}+ public function setSort(array $sort): void+ {+ $this->sort = $sort;+ }++ private function collectLastActivity(): void+ {+ $query = TransactionJournal::query()+ ->leftJoin('category_transaction_journal', 'transaction_journals.id', '=', 'category_transaction_journal.transaction_journal_id')+ ->whereIn('category_transaction_journal.category_id', $this->ids)+ ->selectRaw('category_transaction_journal.category_id, MAX(transaction_journals.date) as last_activity')+ ->groupBy('category_transaction_journal.category_id');+ if (null !== $this->end) {+ $query->where('transaction_journals.date', '<=', $this->end);+ }+ if (null !== $this->start) {+ $query->where('transaction_journals.date', '>=', $this->start);+ }++ $set = $query->get(['category_transaction_journal.category_id', 'last_activity']);+ foreach($set as $entry) {+ $this->lastActivity[(int)$entry->category_id] = Carbon::parse($entry->last_activity, config('app.timezone'));+ }+ }+private function collectNotes(): void{$notes = Note::query()- ->whereIn('noteable_id', $this->ids)- ->whereNotNull('notes.text')- ->where('notes.text', '!=', '')- ->where('noteable_type', Category::class)- ->get(['notes.noteable_id', 'notes.text'])- ->toArray()- ;+ ->whereIn('noteable_id', $this->ids)+ ->whereNotNull('notes.text')+ ->where('notes.text', '!=', '')+ ->where('noteable_type', Category::class)+ ->get(['notes.noteable_id', 'notes.text'])+ ->toArray();foreach ($notes as $note) {- $this->notes[(int) $note['noteable_id']] = (string) $note['text'];+ $this->notes[(int)$note['noteable_id']] = (string)$note['text'];}// Log::debug(sprintf('Enrich with %d note(s)', count($this->notes)));@@ -142,11 +174,11 @@ class CategoryEnrichment implements EnrichmentInterface$opsRepository = app(OperationsRepositoryInterface::class);$opsRepository->setUser($this->user);$opsRepository->setUserGroup($this->userGroup);- $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection);- $income = $opsRepository->collectIncome($this->start, $this->end, null, $this->collection);- $transfers = $opsRepository->collectTransfers($this->start, $this->end, null, $this->collection);+ $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection);+ $income = $opsRepository->collectIncome($this->start, $this->end, null, $this->collection);+ $transfers = $opsRepository->collectTransfers($this->start, $this->end, null, $this->collection);foreach ($this->collection as $item) {- $id = (int) $item->id;+ $id = (int)$item->id;$this->spent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative'));$this->pcSpent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative', true));$this->earned[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($income, $item, 'positive'));@@ -156,4 +188,32 @@ class CategoryEnrichment implements EnrichmentInterface}}}+ private function sortData(): void+ {+ $dbParams = config('firefly.allowed_db_sort_parameters.Category', []);++ /** @var array $parameter */+ foreach ($this->sort as $parameter) {+ if (in_array($parameter[0], $dbParams, true)) {+ continue;+ }+ $field = $parameter[0];++ switch ($field) {+ default:+ throw new FireflyException(sprintf('Category enrichment cannot sort on field "%s"', $field));++ case 'last_activity':+ $this->collection = $this->collection->sortBy(+ static fn (Category $category) => null === $category->meta['last_activity']+ ? '0000-00-00 00:00:00'+ : $category->meta['last_activity']->format('Y-m-d H:i:s'),+ SORT_REGULAR,+ 'desc' === $parameter[1]+ );++ break;+ }+ }+ }}diff --git a/app/Transformers/CategoryTransformer.php b/app/Transformers/CategoryTransformer.phpindex 7e0baff43c..bfeddb327d 100644--- a/app/Transformers/CategoryTransformer.php+++ b/app/Transformers/CategoryTransformer.php@@ -54,22 +54,24 @@ class CategoryTransformer extends AbstractTransformer'created_at' => $category->created_at->toAtomString(),'updated_at' => $category->updated_at->toAtomString(),'name' => $category->name,+ 'color' => $category->color,'notes' => $category->meta['notes'],+ 'last_activity' => $category->meta['last_activity'],// category never has currency settings.'object_has_currency_setting' => false,- 'primary_currency_id' => (string) $this->primaryCurrency->id,+ 'primary_currency_id' => (string)$this->primaryCurrency->id,'primary_currency_name' => $this->primaryCurrency->name,'primary_currency_code' => $this->primaryCurrency->code,'primary_currency_symbol' => $this->primaryCurrency->symbol,- 'primary_currency_decimal_places' => (int) $this->primaryCurrency->decimal_places,+ 'primary_currency_decimal_places' => (int)$this->primaryCurrency->decimal_places,'spent' => $this->beautify($category->meta['spent']),'pc_spent' => $this->beautify($category->meta['pc_spent']),'earned' => $this->beautify($category->meta['earned']),'pc_earned' => $this->beautify($category->meta['pc_earned']),'transferred' => $this->beautify($category->meta['transfers']),'pc_transferred' => $this->beautify($category->meta['pc_transfers']),- 'links' => [['rel' => 'self', 'uri' => '/categories/'.$category->id]],+ 'links' => [['rel' => 'self', 'uri' => '/categories/' . $category->id]],];}@@ -80,7 +82,7 @@ class CategoryTransformer extends AbstractTransformer}$return = [];foreach ($array as $data) {- $data['sum'] = Steam::bcround($data['sum'], (int) $data['currency_decimal_places']);+ $data['sum'] = Steam::bcround($data['sum'], (int)$data['currency_decimal_places']);$return[] = $data;}diff --git a/config/firefly.php b/config/firefly.phpindex 3270737d5a..e65aa329d0 100644--- a/config/firefly.php+++ b/config/firefly.php@@ -853,6 +853,9 @@ return ['name','account_number_and_iban',],+ 'Category' => [+ 'name'+ ],],'allowed_sort_parameters' => ['Account' => [@@ -879,9 +882,15 @@ return ['balance_difference','pc_balance_difference',],+ 'Category' => [+ 'id',+ 'name',+ 'last_activity'+ ],],'allowed_db_sort_parameters' => ['Account' => ['id', 'order', 'name', 'iban', 'active', 'account_type_id'],+ 'Category' => ['name'],],diff --git a/database/migrations/2026_10_09_062600_migrations_10_2026.php b/database/migrations/2026_10_09_062600_migrations_10_2026.phpnew file mode 100644index 0000000000..595338d77e--- /dev/null+++ b/database/migrations/2026_10_09_062600_migrations_10_2026.php@@ -0,0 +1,41 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ try {+ Schema::table('categories', static function (Blueprint $table): void {+ if (!Schema::hasColumn('categories', 'color')) {+ $table->string('color', 6)->nullable()->after('name');+ }+ });+ } catch (RuntimeException $e) {+ Log::error(sprintf('Could not add column: %s', $e->getMessage()));+ }+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ try {+ Schema::table('categories', static function (Blueprint $table): void {+ if (Schema::hasColumn('categories', 'color')) {+ $table->dropColumn('color');+ }+ });+ } catch (RuntimeException $e) {+ Log::error(sprintf('Could not drop column: %s', $e->getMessage()));+ }+ }+};diff --git a/resources/assets/v3/js/api/model/category/get.js b/resources/assets/v3/js/api/model/category/get.jsnew file mode 100644index 0000000000..56715a8518--- /dev/null+++ b/resources/assets/v3/js/api/model/category/get.js@@ -0,0 +1,32 @@+/*+ * list.js+ * Copyright (c) 2022 [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 { api } from "../../../boot/axios";+export default class Get {+ /**+ * @returns {Promise<AxiosResponse<any>>}+ */+ get(id) {+ return api.get(`/api/v1/categories/${id}`);+ }+ list(params) {+ return api.get("/api/v1/categories", { params: params });+ }+}diff --git a/resources/assets/v3/js/pages/accounts/index.js b/resources/assets/v3/js/pages/accounts/index.jsindex 716b18bcf7..bed2046e90 100644--- a/resources/assets/v3/js/pages/accounts/index.js+++ b/resources/assets/v3/js/pages/accounts/index.js@@ -22,14 +22,14 @@ import "../../boot/bootstrap.js";import sidebar from "../shared/sidebar.js";import dates from "../shared/dates.js";import Alpine from "@alpinejs/csp";-import { getVariable } from "../../store/get-variable.js";+import {getVariable} from "../../store/get-variable.js";import Put from "../../api/model/account/put.js";import Get from "../../api/model/account/get.js";import formatDate from "../../util/format-date.js";import formatMoney from "../../util/format-money.js";import i18next from "i18next";-import { addDrag } from "../shared/drag-and-droppable-rows.js";-import { sortableTable, storeFilterAndSort, updateHistory } from "../shared/sortable-tables.js";+import {addDrag} from "../shared/drag-and-droppable-rows.js";+import {sortableTable, storeFilterAndSort, updateHistory} from "../shared/sortable-tables.js";window.enableDates = true;@@ -72,6 +72,7 @@ let index = function () {init() {this.sortableTable = new sortableTable("main");// prepare some variables:+const address = window.location.href.split("?")[0].split("/");this.objectType = address[address.length - 1].substring(0, 15);this.i18next = i18next;@@ -125,9 +126,9 @@ let index = function () {this.sortableTable.sortDirection = this.sortDirection;this.updateHistory(this.page, this.sortColumn, this.sortDirection, this.filter);this.storeFilterAndSort(this.storageKey, this.sortColumn, this.sortDirection, this.filter);- this.downloadAccounts();+ this.downloadObjects();});- this.downloadAccounts();+ this.downloadObjects();// respond to drag and drop.getVariable("listPageSize").then((listPageSize) => {@@ -139,7 +140,7 @@ let index = function () {let item = e.detail[i];if (item.order !== item.currentOrder) {// PUT new order to system.- new Put().put({ order: item.order }, { id: item.id });+ new Put().put({order: item.order}, {id: item.id});// save new order as current order in the row.document@@ -184,13 +185,13 @@ let index = function () {}return account;},- downloadAccounts() {+ downloadObjects() {this.sortableTable.loadingNewSort = true;let sort ="asc" === this.sortableTable.sortDirection? this.sortableTable.sortColumn: "-" + this.sortableTable.sortColumn;- console.log("downloadAccounts:", { page: this.page, sort: sort });+ console.log("downloadObjects:", {page: this.page, sort: sort});let start = window.store.get("start");let end = window.store.get("end");this.convertToPrimary = window.store.get("convert_to_primary");@@ -206,6 +207,7 @@ let index = function () {end: end,}).then((response) => {+ const locale = window.store.get("locale");this.accounts = [];this.sums = {};this.debts = {};@@ -235,7 +237,8 @@ let index = function () {this.debts[pcc] += current.attributes.pc_debt_amount_float;this.differences[pcc] += current.attributes.pc_balance_difference_float;}- let lastActivity = this.formatDate(current.attributes.last_activity);+ let lastActivity = formatDate(current.attributes.last_activity, i18next.t("config.date_time_fns_short", {lng: locale}), locale);+let noLastActivity = false;if ("" === lastActivity) {lastActivity = i18next.t("firefly.never");@@ -310,16 +313,6 @@ let index = function () {}return iban.match(/.{1,4}/g).join(" ");},- formatDate(date) {- if (null === date) {- return "";- }- return formatDate(- new Date(date),- i18next.t("config.date_time_fns_short", { lng: window.store.get("locale") }),- window.store.get("locale"),- );- },};};diff --git a/resources/assets/v3/js/pages/categories/index.js b/resources/assets/v3/js/pages/categories/index.jsnew file mode 100644index 0000000000..b4656e28c4--- /dev/null+++ b/resources/assets/v3/js/pages/categories/index.js@@ -0,0 +1,187 @@+/*+ * index.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 "../../boot/bootstrap.js";+import sidebar from "../shared/sidebar.js";+import dates from "../shared/dates.js";+import Alpine from "@alpinejs/csp";+import formatMoney from "../../util/format-money.js";+import formatDate from "../../util/format-date.js";+import i18next from "i18next";+window.enableDates = false;+import { sortableTable, storeFilterAndSort, updateHistory } from "../shared/sortable-tables.js";+import Get from "../../api/model/category/get.js";+++let index = function () {+ return {+ categories: [],+ totalPages: 0,+ page: 1,+ i18next: null,+ anonymous: false,+ loadingPage: true,+ convertToPrimary: false,++ // functions+ formatMoney: formatMoney,+ formatDate: formatDate,++ // default settings for sorting+ filter: {},+ pageNavUrl: "./categories/",+ storageKey: "categories-index",+ defaultSortColumn: "name",+ defaultSortDirection: "asc",++ sortColumn: "name", // used in GET request.+ sortDirection: "asc", // used in GET request.++ // sort functions, imported+ updateHistory: updateHistory,+ storeFilterAndSort: storeFilterAndSort,+ sortableTable: null,++ init() {+ console.log('init');+ this.sortableTable = new sortableTable("main");+ this.i18next = i18next;+ this.anonymous = window.store.get("anonymous");++ // todo make function:+ // grab state from localStorage.+ let fromStore = window.store.get(this.storageKey);+ if (fromStore) {+ this.defaultSortColumn = fromStore.column;+ this.defaultSortDirection = fromStore.direction;+ this.filter = fromStore.filter;+ //console.log('Restore from store:', fromStore);+ }++ // todo make function+ // grab state from URL params.+ const params = new Proxy(new URLSearchParams(window.location.search), {+ get: (searchParams, prop) => searchParams.get(prop),+ });+ this.page = parseInt(params.page || "1");+ this.defaultSortColumn = params.column ?? this.defaultSortColumn;+ this.defaultSortDirection = params.direction ?? this.defaultSortDirection;+ this.sortColumn = this.defaultSortColumn;+ this.sortDirection = this.defaultSortDirection;+ console.log("Restore from params:", {+ page: this.page,+ column: this.defaultSortColumn,+ direction: this.defaultSortDirection,+ });++ this.sortableTable.sortColumn = this.defaultSortColumn;+ this.sortableTable.sortDirection = this.defaultSortDirection;+ this.sortableTable.storageKey = this.storageKey;+ this.sortableTable.page = this.page;++ this.sortableTable.init(this);++ // todo make function+ // watch for changes in the sortable table instructions.+ document.addEventListener("sortable-table-sort-change", (event) => {+ console.log("sortable-table-sort-change", event.detail);+ this.sortColumn = event.detail.sortColumn;+ this.sortDirection = event.detail.sortDirection;+ this.sortableTable.sortColumn = this.sortColumn;+ this.sortableTable.sortDirection = this.sortDirection;+ this.updateHistory(this.page, this.sortColumn, this.sortDirection, this.filter);+ this.storeFilterAndSort(this.storageKey, this.sortColumn, this.sortDirection, this.filter);+ this.downloadObjects();+ });+ this.downloadObjects();++ },+ downloadObjects() {+ this.sortableTable.loadingNewSort = true;+ let sort = "asc" === this.sortableTable.sortDirection ? this.sortableTable.sortColumn : "-" + this.sortableTable.sortColumn;+ this.convertToPrimary = window.store.get("convert_to_primary");+ let locale = window.store.get("locale");+ new Get()+ .list({+ active: this.active,+ sort: sort,+ page: this.page,+ filter: JSON.parse(JSON.stringify(this.filter)),+ })+ .then((response) => {+ this.categories = [];+ this.totalPages = parseInt(response.data.meta.pagination.total_pages);++ for (let i = 0; i < response.data.data.length; i++) {+ if (Object.hasOwn(response.data.data, i)) {+ let current = response.data.data[i];+ console.log(current);+ let lastActivity = i18next.t('firefly.never');+ let noLastActivity = true;+ if(null !== current.attributes.last_activity) {+ lastActivity = formatDate(current.attributes.last_activity, i18next.t("config.date_time_fns", { lng: locale }), locale);+ noLastActivity = false;+ }++ let category = {+ id: parseInt(current.id),+ name: current.attributes.name,+ active: current.attributes.active,+ last_activity: lastActivity,+ no_last_activity: noLastActivity,+ };+ this.categories.push(category);+ }+ }+ this.loadingPage = false;+ this.sortableTable.loadingNewSort = false;+ this.sortableTable.disableRefresh = false;+ if (0 === this.categories.length && false === this.isFiltering) {+ document.querySelectorAll(".data-holder").forEach((el) => {+ el.classList.add("d-none");+ });+ }+ });+ }+ }+}++const comps = {+ index,+ sidebar,+ dates,+};++function loadPage(comps) {+ Object.keys(comps).forEach((comp) => {+ let data = comps[comp]();+ Alpine.data(comp, () => data);+ });+ Alpine.start();+}++// wait for load until bootstrapped event is received.+document.addEventListener("firefly-iii-bootstrapped", () => {+ loadPage(comps);+});+// or is bootstrapped before event is triggered.+if (window.bootstrapped) {+ loadPage(comps);+}diff --git a/resources/assets/v3/js/pages/shared/sortable-tables.js b/resources/assets/v3/js/pages/shared/sortable-tables.jsindex 5e77453d74..4808171026 100644--- a/resources/assets/v3/js/pages/shared/sortable-tables.js+++ b/resources/assets/v3/js/pages/shared/sortable-tables.js@@ -136,7 +136,7 @@ export class sortableTable {// some sort of trigger to parent?// console.warn('Here be push to parent!');this.parent.updateHistory(page, this.sortColumn, this.sortDirection, this.parent.filter);- this.parent.downloadAccounts();+ this.parent.downloadObjects();e.preventDefault();queueMicrotask(() => {this.capturePageNavigation();diff --git a/resources/assets/v3/vite.config.js b/resources/assets/v3/vite.config.jsindex d0d9ae8115..4802d8c6d0 100644--- a/resources/assets/v3/vite.config.js+++ b/resources/assets/v3/vite.config.js@@ -60,7 +60,7 @@ export default defineConfig(({ command }) => {"js/pages/administrations/edit.js",// categories- // "js/pages/categories/index.js",+ "js/pages/categories/index.js",// budgetsdiff --git a/resources/views/categories/index.blade.php b/resources/views/categories/index.blade.phpindex f4182ce388..afe1ac618b 100644--- a/resources/views/categories/index.blade.php+++ b/resources/views/categories/index.blade.php@@ -1,5 +1,68 @@@extends('layout.v3.session')@section('content')+ <div class="row" x-data="index">+ <template x-if="true === loadingPage">+ <div class="col-lg-12 text-center">+ <div id="status-box" class="p-3 install-box-border">+ <div class="spinner-border spinner-border-sm" role="status">+ <span class="visually-hidden">{{ __('firefly.thinking') }}</span>+ </div>+ </div>+ </div>+ </template>+ <div class="col-lg-12 col-md-12 col-sm-12 data-holder">+ <div class="card" id="category-index">+ <x-elements.card-header-with-menu :cardTitle="trans('firefly.categories')"+ :route="route('categories.create') . '?_from=' . urlencode($FF3_FROM)"+ :linkTitle="__('firefly.create_new_category')"/>+ <div class="card-body p-0">+ <template x-if="totalPages > 1">+ <x-elements.alpine.page-navigation/>+ </template>+ <table data-sort-identifier="main" class="table table-valign-middle table-sm table-hover sortable">+ <thead>+ <tr>+ <th data-sort-column="name" data-filter-column="name" class="w-40"><span class="title">{{ trans('list.name') }}</span></th>+ <th data-sort-column="last_activity"><span class="title">{{ trans('list.last_activity') }}</span></th>+ </tr>+ </thead>+ <tbody>+ <template x-for="category in categories" :key="category.id">+ <tr>+ <td>+ <a :href="'./categories/show/' + category.id" :title="category.name"+ x-text="category.name"></a>+ </td>+ <td>+ <span x-text="category.last_activity"></span>+ </td>+ </tr>+ </template>+ </tbody>+ </table>++ <template x-if="totalPages > 1">+ <x-elements.alpine.page-navigation/>+ </template>++ <x-elements.card-footer-with-menu+ :route="route('categories.create') . '?_from=' . urlencode($FF3_FROM)"+ :linkTitle="__('firefly.create_new_category')"/>++ </div>+ </div>++ <template x-if="0 === categories.length && false === loadingPage && false === sortableTable.isFiltering">+ <x-empty-page :route="route('categories.create') . '?_from=' . urlencode($FF3_FROM)"+ type="categories" object-type=""/>+ </template>++ </div>+ </div>++++ {{--@if(0 === $categories->count() && 1 === $page)@php$shownDemo = true@@ -21,12 +84,12 @@</div></div>@endif- @endsection-+--}}+@endsection@section('styles')-<link href="v1/css/bootstrap-sortable.css?v={{ $FF_BUILD_TIME }}" type="text/css" rel="stylesheet" media="all" nonce="{{ $JS_NONCE }}">+@endsection@section('scripts')- @vite(['js/pages/generic.js'])+ @vite(['js/pages/categories/index.js'])@endsection