Better index for accounts.

This commit is contained in:
James Cole
2024-03-06 19:54:09 +01:00
parent fd2edf3b23
commit 930a08ec90
8 changed files with 161 additions and 235 deletions

View File

@@ -24,9 +24,11 @@ declare(strict_types=1);
namespace FireflyIII\Api\V2\Controllers\Model\Account;
use FireflyIII\Api\V2\Controllers\Controller;
use FireflyIII\Api\V2\Request\Model\Account\IndexRequest;
use FireflyIII\Api\V2\Request\Model\Transaction\InfiniteListRequest;
use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface;
use FireflyIII\Transformers\V2\AccountTransformer;
use FireflyIII\Transformers\V2\BillTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
@@ -56,6 +58,27 @@ class IndexController extends Controller
);
}
/**
* TODO see autocomplete/accountcontroller for list.
*/
public function index(IndexRequest $request): JsonResponse
{
$this->repository->resetAccountOrder();
$types = $request->getAccountTypes();
$accounts = $this->repository->getAccountsByType($types);
$pageSize = $this->parameters->get('limit');
$count = $accounts->count();
$accounts = $accounts->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
$paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page'));
$transformer = new AccountTransformer();
$transformer->setParameters($this->parameters); // give params to transformer
return response()
->json($this->jsonApiList('accounts', $paginator, $transformer))
->header('Content-Type', self::CONTENT_TYPE)
;
}
public function infiniteList(InfiniteListRequest $request): JsonResponse
{
$this->repository->resetAccountOrder();

View File

@@ -0,0 +1,68 @@
<?php
/*
* IndexRequest.php
* Copyright (c) 2024 james@firefly-iii.org.
*
* 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\V2\Request\Model\Account;
use Carbon\Carbon;
use FireflyIII\Support\Http\Api\AccountFilter;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
use Illuminate\Foundation\Http\FormRequest;
/**
* Class IndexRequest
*
* Lots of code stolen from the SingleDateRequest.
*/
class IndexRequest extends FormRequest
{
use ChecksLogin;
use ConvertsDataTypes;
use AccountFilter;
/**
* Get all data from the request.
*/
public function getDate(): Carbon
{
return $this->getCarbonDate('date');
}
public function getAccountTypes(): array
{
$type = (string)$this->get('type', 'default');
return $this->mapAccountTypes($type);
}
/**
* The rules that the incoming request must be matched against.
*/
public function rules(): array
{
return [
'date' => 'date|after:1900-01-01|before:2099-12-31',
];
}
}

View File

@@ -26,19 +26,20 @@ export default class Get {
/**
*
* @param identifier
* @param date
* @param params
* @returns {Promise<AxiosResponse<any>>}
*/
list(identifier, date) {
let params = {date: format(date, 'y-MM-dd').slice(0, 10)};
if (!date) {
return api.get('/api/v2/accounts/' + identifier);
}
show(identifier, params) {
return api.get('/api/v2/accounts/' + identifier, {params: params});
}
infiniteList(params) {
return api.get('/api/v2/infinite/accounts', {params: params});
/**
*
* @param params
* @returns {Promise<AxiosResponse<any>>}
*/
index(params) {
return api.get('/api/v2/accounts', {params: params});
}
/**

View File

@@ -23,129 +23,16 @@ import dates from "../shared/dates.js";
import i18next from "i18next";
import {format} from "date-fns";
import formatMoney from "../../util/format-money.js";
import Put from "../../api/v2/model/transaction/put.js";
import {createGrid, ModuleRegistry} from "@ag-grid-community/core";
import '@ag-grid-community/styles/ag-grid.css';
import '@ag-grid-community/styles/ag-theme-alpine.css';
import '../../css/grid-ff3-theme.css';
import AmountEditor from "../../support/ag-grid/AmountEditor.js";
import AccountDataSource from "../../support/ag-grid/AccountDataSource.js";
import {InfiniteRowModelModule} from '@ag-grid-community/infinite-row-model';
import DateTimeEditor from "../../support/ag-grid/DateTimeEditor.js";
const ds = new AccountDataSource();
import Get from "../../api/v2/model/account/get.js";
// set type from URL
const urlParts = window.location.href.split('/');
const type = urlParts[urlParts.length - 1];
ds.setType(type);
document.addEventListener('cellEditRequest', () => {
console.log('Loaded through event listener.');
//loadPage();
});
let rowImmutableStore = [];
let dataTable;
const editableFields = ['description', 'amount', 'date'];
const onCellEditRequestMethod = (event) => {
console.log('onCellEditRequestMethod');
const data = event.data;
const field = event.colDef.field;
let newValue = event.newValue;
if (!editableFields.includes(field)) {
console.log('Field ' + field + ' is not editable.');
return;
}
// this needs to be better
if ('amount' === field) {
newValue = event.newValue.amount;
console.log('New value is now' + newValue);
}
console.log('New value for field "' + field + '" in transaction journal #' + data.transaction_journal_id + ' of group #' + data.id + ' is "' + newValue + '"');
data[field] = newValue;
let rowNode = dataTable.getRowNode(String(event.rowIndex));
rowNode.updateData(data);
// then push update to Firefly III over API:
let submission = {
transactions: [
{
transaction_journal_id: data.transaction_journal_id,
}
]
};
submission.transactions[0][field] = newValue;
// let putter = new Put();
// putter.put(submission, {id: data.id});
};
document.addEventListener('cellValueChanged', () => {
console.log('I just realized a cell value has changed.');
});
document.addEventListener('onCellValueChanged', () => {
console.log('I just realized a cell value has changed.');
});
let doOnCellValueChanged = function (e) {
console.log('I just realized a cell value has changed.');
};
const gridOptions = {
rowModelType: 'infinite',
datasource: ds,
onCellEditRequest: onCellEditRequestMethod,
readOnlyEdit: true,
cacheOverflowSize: 1,
cacheBlockSize: 20,
// Row Data: The data to be displayed.
// rowData: [
// { description: "Tesla", model: "Model Y", price: 64950, electric: true },
// { description: "Ford", model: "F-Series", price: 33850, electric: false },
// { description: "Toyota", model: "Corolla", price: 29600, electric: false },
// ],
// Column Definitions: Defines & controls grid columns.
columnDefs: [
{
field: "icon",
editable: false,
headerName: '',
sortable: false,
width: 40,
cellRenderer: function (params) {
if (params.getValue()) {
return '<a href="./transactions/show/' + parseInt(params.value.id) + '"><em class="' + params.value.classes + '"></em></a>';
}
return '';
}
},
{
field: "name",
cellDataType: 'text',
editable: true,
cellRenderer: function (params) {
if (params.getValue()) {
return '<a href="./accounts/show/' + parseInt(params.data.id) + '">'+params.getValue() +'</a>';
}
return '';
}
}
]
};
ModuleRegistry.registerModules([InfiniteRowModelModule]);
let index = function () {
return {
// notifications
@@ -158,31 +45,45 @@ let index = function () {
show: false, text: '',
}
},
totalPages: 1,
page: 1,
// available columns:
}, totalPages: 1, page: 1, // available columns:
tableColumns: {
name: {
enabled: true
},
},
table: null,
accounts: [],
formatMoney(amount, currencyCode) {
return formatMoney(amount, currencyCode);
},
format(date) {
return format(date, i18next.t('config.date_time_fns'));
},
init() {
this.notifications.wait.show = true;
this.notifications.wait.text = i18next.t('firefly.wait_loading_data')
this.loadAccounts();
},
// Your Javascript code to create the grid
dataTable = createGrid(document.querySelector('#grid'), gridOptions);
loadAccounts() {
// one page only.
(new Get()).index({type: type, page: this.page}).then(response => {
for (let i = 0; i < response.data.data.length; i++) {
if (response.data.data.hasOwnProperty(i)) {
let current = response.data.data[i];
let account = {
id: parseInt(current.id),
name: current.attributes.name,
};
this.accounts.push(account);
}
}
this.notifications.wait.show = false;
});
},
}
}

View File

@@ -191,7 +191,7 @@ export default () => ({
if (account.hasOwnProperty(i)) {
let accountId = account[i];
// grab account info for box:
(new Get).get(accountId, new Date(window.store.get('end'))).then((response) => {
(new Get).show(accountId, new Date(window.store.get('end'))).then((response) => {
let parent = response.data.data;
// get groups for account:

View File

@@ -1,90 +0,0 @@
/*
* TransactionDataSource.js
* Copyright (c) 2024 james@firefly-iii.org.
*
* 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/v2/model/account/get.js";
export default class AccountDataSource {
constructor() {
this.type = 'all';
this.rowCount = null;
this.sortModel = null;
}
rowCount() {
console.log('The row count is: ', this.rowCount);
return this.rowCount;
}
getRows(params) {
console.log('The sort model used is: ', params.sortModel);
let sorting = [];
for (let i in params.sortModel) {
if (params.sortModel.hasOwnProperty(i)) {
let sort = params.sortModel[i];
sorting.push({column: sort.colId, direction: sort.sort});
}
}
let getter = new Get();
getter.infiniteList({
start_row: params.startRow,
end_row: params.endRow,
type: this.type,
sorting: sorting
}).then(response => {
this.parseAccounts(response.data.data, params.successCallback);
// set meta data
this.rowCount = response.data.meta.pagination.total;
console.log('The row count is: ', this.rowCount);
}).catch(error => {
// todo this is auto generated
//this.notifications.wait.show = false;
//this.notifications.error.show = true;
//this.notifications.error.text = error.response.data.message;
console.log(error);
});
}
parseAccounts(data, callback) {
let accounts = [];
// no parse, just save
for (let i in data) {
if (data.hasOwnProperty(i)) {
let current = data[i];
let entry = {};
entry.id = current.id;
entry.name = current.attributes.name;
accounts.push(entry);
}
}
console.log('accounts length = ', accounts.length);
callback(accounts, false);
return accounts;
}
setType(type) {
this.type = type;
}
}

View File

@@ -49,16 +49,50 @@
<div class="card-header">
<div class="row">
<div class="col">
<h3 class="card-title">Accounts</h3>
<h3 class="card-title">Accounts (ungrouped)</h3>
</div>
<div class="col text-end">
</div>
</div>
</div>
<div class="card-body p-0">
<div id="grid" class="ag-theme-alpine-auto-dark ag-theme-firefly-iii" style="height: 500px;">
<table class="table">
<thead>
<tr>
<td>&nbsp;</td>
<td>Active?</td>
<td>Name</td>
<td>Type</td>
<td>Account number</td>
<td>Current balance</td>
<td>Last activity</td>
<td>Balance difference</td>
<td>&nbsp;</td>
</tr>
</thead>
<tbody>
<template x-for="(account, index) in accounts" :key="index">
<tr>
<td>&nbsp;</td>
<td>
&nbsp;
</td>
<td>
<a :href="'./accounts/show/' + account.id">
<span x-text="account.name"></span>
</a>
</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>&nbsp;</td>
</tr>
</template>
</tbody>
</div>
</table>
</div>
</div>

View File

@@ -104,6 +104,7 @@ Route::group(
'as' => 'api.v2.accounts.',
],
static function (): void {
Route::get('', ['uses' => 'IndexController@index', 'as' => 'show']);
Route::get('{account}', ['uses' => 'ShowController@show', 'as' => 'show']);
}
);
@@ -172,18 +173,6 @@ Route::group(
}
);
// infinite accounts list:
Route::group(
[
'namespace' => 'FireflyIII\Api\V2\Controllers\Model\Account',
'prefix' => 'v2/infinite/accounts',
'as' => 'api.v2.infinite.accounts.',
],
static function (): void {
Route::get('', ['uses' => 'IndexController@infiniteList', 'as' => 'list']);
}
);
// V2 API route for budgets and budget limits:
Route::group(
[