Code fixes.

This commit is contained in:
James Cole
2021-05-24 08:06:56 +02:00
parent 3b1b353b79
commit 2bff7750b4
45 changed files with 331 additions and 248 deletions

View File

@@ -46,6 +46,7 @@ abstract class Controller extends BaseController
protected const CONTENT_TYPE = 'application/vnd.api+json'; protected const CONTENT_TYPE = 'application/vnd.api+json';
protected ParameterBag $parameters; protected ParameterBag $parameters;
protected array $allowedSort;
/** /**
* Controller constructor. * Controller constructor.
@@ -53,7 +54,8 @@ abstract class Controller extends BaseController
public function __construct() public function __construct()
{ {
// get global parameters // get global parameters
$this->parameters = $this->getParameters(); $this->allowedSort = config('firefly.allowed_sort_parameters');
$this->parameters = $this->getParameters();
$this->middleware( $this->middleware(
function ($request, $next) { function ($request, $next) {
if (auth()->check()) { if (auth()->check()) {
@@ -106,10 +108,42 @@ abstract class Controller extends BaseController
} }
} }
return $bag; // sort fields:
$bag = $this->getSortParameters($bag);
return $bag;
} }
/**
* @param ParameterBag $bag
*
* @return ParameterBag
*/
private function getSortParameters(ParameterBag $bag): ParameterBag
{
$sortParameters = [];
$param = (string)request()->query->get('sort');
if ('' === $param) {
return $bag;
}
$parts = explode(',', $param);
foreach ($parts as $part) {
$part = trim($part);
$direction = 'asc';
if ('-' === $part[0]) {
$part = substr($part, 1);
$direction = 'desc';
}
if (in_array($part, $this->allowedSort, true)) {
$sortParameters[] = [$part, $direction];
}
}
$bag->set('sort', $sortParameters);
return $bag;
}
/** /**
* Method to help build URI's. * Method to help build URI's.
* *

View File

@@ -84,8 +84,12 @@ class ShowController extends Controller
// get list of accounts. Count it and split it. // get list of accounts. Count it and split it.
$this->repository->resetAccountOrder(); $this->repository->resetAccountOrder();
$collection = $this->repository->getAccountsByType($types); $collection = $this->repository->getAccountsByType($types, $this->parameters->get('sort') ?? []);
$count = $collection->count(); $count = $collection->count();
// continue sort:
$accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize);
// make paginator: // make paginator:

View File

@@ -76,8 +76,6 @@ class MoveTransactionsRequest extends FormRequest
} }
if ($originalCurrency->code !== $destinationCurrency->code) { if ($originalCurrency->code !== $destinationCurrency->code) {
$validator->errors()->add('title', (string)trans('validation.same_account_currency')); $validator->errors()->add('title', (string)trans('validation.same_account_currency'));
return;
} }
} }
} }

View File

@@ -135,8 +135,6 @@ class StoreRequest extends FormRequest
*/ */
public function rules(): array public function rules(): array
{ {
$today = Carbon::now()->addDay();
return [ return [
'type' => 'required|in:withdrawal,transfer,deposit', 'type' => 'required|in:withdrawal,transfer,deposit',
'title' => 'required|between:1,255|uniqueObjectForUser:recurrences,title', 'title' => 'required|between:1,255|uniqueObjectForUser:recurrences,title',

View File

@@ -53,15 +53,13 @@ class StoreRequest extends FormRequest
public function getAll(): array public function getAll(): array
{ {
Log::debug('get all data in TransactionStoreRequest'); Log::debug('get all data in TransactionStoreRequest');
$data = [ return [
'group_title' => $this->string('group_title'), 'group_title' => $this->string('group_title'),
'error_if_duplicate_hash' => $this->boolean('error_if_duplicate_hash'), 'error_if_duplicate_hash' => $this->boolean('error_if_duplicate_hash'),
'apply_rules' => $this->boolean('apply_rules', true), 'apply_rules' => $this->boolean('apply_rules', true),
'transactions' => $this->getTransactionData(), 'transactions' => $this->getTransactionData(),
]; ];
// TODO location // TODO location
return $data;
} }
/** /**

View File

@@ -366,7 +366,7 @@ class UpdateRequest extends FormRequest
$this->validateJournalIds($validator, $transactionGroup); $this->validateJournalIds($validator, $transactionGroup);
// all transaction types must be equal: // all transaction types must be equal:
$this->validateTransactionTypesForUpdate($validator, $transactionGroup); $this->validateTransactionTypesForUpdate($validator);
// validate source/destination is equal, depending on the transaction journal type. // validate source/destination is equal, depending on the transaction journal type.
$this->validateEqualAccountsForUpdate($validator, $transactionGroup); $this->validateEqualAccountsForUpdate($validator, $transactionGroup);

View File

@@ -54,10 +54,8 @@ class UpdateRequest extends FormRequest
'enabled' => ['enabled', 'boolean'], 'enabled' => ['enabled', 'boolean'],
]; ];
$return = $this->getAllData($fields); return $this->getAllData($fields);
// return $return;
return $return;
} }
/** /**

View File

@@ -56,7 +56,7 @@ class FixFrontpageAccounts extends Command
*/ */
public function handle(): int public function handle(): int
{ {
$start = microtime(true); $start = microtime(true);
$users = User::get(); $users = User::get();
/** @var User $user */ /** @var User $user */
@@ -88,16 +88,12 @@ class FixFrontpageAccounts extends Command
if (is_array($data)) { if (is_array($data)) {
/** @var string $accountId */ /** @var string $accountId */
foreach ($data as $accountId) { foreach ($data as $accountId) {
$accountId = (int)$accountId; $accountIdInt = (int)$accountId;
$account = $repository->findNull($accountId); $account = $repository->findNull($accountIdInt);
if (null !== $account) { if (null !== $account
if ( && in_array($account->accountType->type, [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE], true)
in_array($account->accountType->type, [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE], true) && true === $account->active) {
&& true === $account->active $fixed[] = $account->id;
) {
$fixed[] = $account->id;
continue;
}
} }
} }
} }

View File

@@ -227,16 +227,6 @@ class GroupCollector implements GroupCollectorInterface
*/ */
public function getGroups(): Collection public function getGroups(): Collection
{ {
$filterQuery = false;
// now filter the query according to the page and the limit (if necessary)
if ($filterQuery) {
if (null !== $this->limit && null !== $this->page) {
$offset = ($this->page - 1) * $this->limit;
$this->query->take($this->limit)->skip($offset);
}
}
/** @var Collection $result */ /** @var Collection $result */
$result = $this->query->get($this->fields); $result = $this->query->get($this->fields);
@@ -245,12 +235,10 @@ class GroupCollector implements GroupCollectorInterface
$this->total = $collection->count(); $this->total = $collection->count();
// now filter the array according to the page and the limit (if necessary) // now filter the array according to the page and the limit (if necessary)
if (!$filterQuery) { if (null !== $this->limit && null !== $this->page) {
if (null !== $this->limit && null !== $this->page) { $offset = ($this->page - 1) * $this->limit;
$offset = ($this->page - 1) * $this->limit;
return $collection->slice($offset, $this->limit); return $collection->slice($offset, $this->limit);
}
} }
return $collection; return $collection;

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -31,14 +32,14 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/** /**
* Class WebhookAttempt * Class WebhookAttempt
* *
* @property int $id * @property int $id
* @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at * @property \Illuminate\Support\Carbon|null $updated_at
* @property string|null $deleted_at * @property string|null $deleted_at
* @property int $webhook_message_id * @property int $webhook_message_id
* @property int $status_code * @property int $status_code
* @property string|null $logs * @property string|null $logs
* @property string|null $response * @property string|null $response
* @property-read \FireflyIII\Models\WebhookMessage $webhookMessage * @property-read \FireflyIII\Models\WebhookMessage $webhookMessage
* @method static \Illuminate\Database\Eloquent\Builder|WebhookAttempt newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|WebhookAttempt newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|WebhookAttempt newQuery() * @method static \Illuminate\Database\Eloquent\Builder|WebhookAttempt newQuery()
@@ -59,6 +60,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class WebhookAttempt extends Model class WebhookAttempt extends Model
{ {
use SoftDeletes; use SoftDeletes;
/** /**
* @codeCoverageIgnore * @codeCoverageIgnore
* @return BelongsTo * @return BelongsTo
@@ -84,10 +86,8 @@ class WebhookAttempt extends Model
$user = auth()->user(); $user = auth()->user();
/** @var WebhookAttempt $attempt */ /** @var WebhookAttempt $attempt */
$attempt = self::find($attemptId); $attempt = self::find($attemptId);
if (null !== $attempt) { if (null !== $attempt && $attempt->webhookMessage->webhook->user_id === $user->id) {
if($attempt->webhookMessage->webhook->user_id === $user->id) { return $attempt;
return $attempt;
}
} }
} }
throw new NotFoundHttpException; throw new NotFoundHttpException;

View File

@@ -22,6 +22,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace FireflyIII\Models; namespace FireflyIII\Models;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -31,18 +32,18 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/** /**
* FireflyIII\Models\WebhookMessage * FireflyIII\Models\WebhookMessage
* *
* @property int $id * @property int $id
* @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at * @property \Illuminate\Support\Carbon|null $updated_at
* @property string|null $deleted_at * @property string|null $deleted_at
* @property int $webhook_id * @property int $webhook_id
* @property bool $sent * @property bool $sent
* @property bool $errored * @property bool $errored
* @property int $attempts * @property int $attempts
* @property string $uuid * @property string $uuid
* @property array $message * @property array $message
* @property array|null $logs * @property array|null $logs
* @property-read \FireflyIII\Models\Webhook $webhook * @property-read \FireflyIII\Models\Webhook $webhook
* @method static \Illuminate\Database\Eloquent\Builder|WebhookMessage newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|WebhookMessage newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|WebhookMessage newQuery() * @method static \Illuminate\Database\Eloquent\Builder|WebhookMessage newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|WebhookMessage query() * @method static \Illuminate\Database\Eloquent\Builder|WebhookMessage query()
@@ -59,7 +60,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @method static \Illuminate\Database\Eloquent\Builder|WebhookMessage whereWebhookId($value) * @method static \Illuminate\Database\Eloquent\Builder|WebhookMessage whereWebhookId($value)
* @mixin \Eloquent * @mixin \Eloquent
* @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\WebhookAttempt[] $webhookAttempts * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\WebhookAttempt[] $webhookAttempts
* @property-read int|null $webhook_attempts_count * @property-read int|null $webhook_attempts_count
*/ */
class WebhookMessage extends Model class WebhookMessage extends Model
{ {
@@ -70,7 +71,7 @@ class WebhookMessage extends Model
'errored' => 'boolean', 'errored' => 'boolean',
'uuid' => 'string', 'uuid' => 'string',
'message' => 'json', 'message' => 'json',
'logs' => 'json', 'logs' => 'json',
]; ];
/** /**
@@ -89,10 +90,8 @@ class WebhookMessage extends Model
$user = auth()->user(); $user = auth()->user();
/** @var WebhookMessage $message */ /** @var WebhookMessage $message */
$message = self::find($messageId); $message = self::find($messageId);
if (null !== $message) { if (null !== $message && $message->webhook->user_id === $user->id) {
if($message->webhook->user_id === $user->id) { return $message;
return $message;
}
} }
} }
throw new NotFoundHttpException; throw new NotFoundHttpException;

View File

@@ -233,25 +233,35 @@ class AccountRepository implements AccountRepositoryInterface
} }
/** /**
* @param array $types * @param array $types
* @param array|null $sort
* *
* @return Collection * @return Collection
*/ */
public function getAccountsByType(array $types): Collection public function getAccountsByType(array $types, ?array $sort = []): Collection
{ {
$res = array_intersect([AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT], $types);
$query = $this->user->accounts(); $query = $this->user->accounts();
if (0 !== count($types)) { if (0 !== count($types)) {
$query->accountTypeIn($types); $query->accountTypeIn($types);
} }
$res = array_intersect([AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT], $types);
if (0 !== count($res)) { // add sort parameters. At this point they're filtered to allowed fields to sort by:
$query->orderBy('accounts.order', 'ASC'); if (count($sort) > 0) {
foreach ($sort as $param) {
$query->orderBy($param[0], $param[1]);
}
}
if (0 === count($sort)) {
if (0 !== count($res)) {
$query->orderBy('accounts.order', 'ASC');
}
$query->orderBy('accounts.active', 'DESC');
$query->orderBy('accounts.name', 'ASC');
} }
$query->orderBy('accounts.active', 'DESC');
$query->orderBy('accounts.name', 'ASC');
return $query->get(['accounts.*']); return $query->get(['accounts.*']);
} }
/** /**

View File

@@ -121,11 +121,12 @@ interface AccountRepositoryInterface
public function getAccountsById(array $accountIds): Collection; public function getAccountsById(array $accountIds): Collection;
/** /**
* @param array $types * @param array $types
* @param array|null $sort
* *
* @return Collection * @return Collection
*/ */
public function getAccountsByType(array $types): Collection; public function getAccountsByType(array $types, ?array $sort = []): Collection;
/** /**
* @param array $types * @param array $types

View File

@@ -88,7 +88,7 @@ class OperationsRepository implements OperationsRepositoryInterface
*/ */
public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null
): array { ): array {
$journals = $this->getTransactionsForSum($start, $end, $accounts, $expense, $currency, TransactionType::WITHDRAWAL); $journals = $this->getTransactionsForSum(TransactionType::WITHDRAWAL, $start, $end, $accounts, $expense, $currency);
return $this->groupByCurrency($journals, 'negative'); return $this->groupByCurrency($journals, 'negative');
@@ -100,7 +100,7 @@ class OperationsRepository implements OperationsRepositoryInterface
public function sumExpensesByDestination( public function sumExpensesByDestination(
Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null
): array { ): array {
$journals = $this->getTransactionsForSum($start, $end, $accounts, $expense, $currency, TransactionType::WITHDRAWAL); $journals = $this->getTransactionsForSum(TransactionType::WITHDRAWAL, $start, $end, $accounts, $expense, $currency);
return $this->groupByDirection($journals, 'destination', 'negative'); return $this->groupByDirection($journals, 'destination', 'negative');
} }
@@ -111,7 +111,7 @@ class OperationsRepository implements OperationsRepositoryInterface
public function sumExpensesBySource( public function sumExpensesBySource(
Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null
): array { ): array {
$journals = $this->getTransactionsForSum($start, $end, $accounts, $expense, $currency, TransactionType::WITHDRAWAL); $journals = $this->getTransactionsForSum(TransactionType::WITHDRAWAL, $start, $end, $accounts, $expense, $currency);
return $this->groupByDirection($journals, 'source', 'negative'); return $this->groupByDirection($journals, 'source', 'negative');
} }
@@ -121,7 +121,7 @@ class OperationsRepository implements OperationsRepositoryInterface
*/ */
public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null
): array { ): array {
$journals = $this->getTransactionsForSum($start, $end, $accounts, $revenue, $currency, TransactionType::DEPOSIT); $journals = $this->getTransactionsForSum(TransactionType::DEPOSIT, $start, $end, $accounts, $revenue, $currency);
return $this->groupByCurrency($journals, 'positive'); return $this->groupByCurrency($journals, 'positive');
} }
@@ -132,7 +132,7 @@ class OperationsRepository implements OperationsRepositoryInterface
public function sumIncomeByDestination( public function sumIncomeByDestination(
Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null
): array { ): array {
$journals = $this->getTransactionsForSum($start, $end, $accounts, $revenue, $currency, TransactionType::DEPOSIT); $journals = $this->getTransactionsForSum(TransactionType::DEPOSIT, $start, $end, $accounts, $revenue, $currency);
return $this->groupByDirection($journals, 'destination', 'positive'); return $this->groupByDirection($journals, 'destination', 'positive');
} }
@@ -143,7 +143,7 @@ class OperationsRepository implements OperationsRepositoryInterface
public function sumIncomeBySource( public function sumIncomeBySource(
Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null
): array { ): array {
$journals = $this->getTransactionsForSum($start, $end, $accounts, $revenue, $currency, TransactionType::DEPOSIT); $journals = $this->getTransactionsForSum(TransactionType::DEPOSIT, $start, $end, $accounts, $revenue, $currency);
return $this->groupByDirection($journals, 'source', 'positive'); return $this->groupByDirection($journals, 'source', 'positive');
} }
@@ -153,7 +153,7 @@ class OperationsRepository implements OperationsRepositoryInterface
*/ */
public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array
{ {
$journals = $this->getTransactionsForSum($start, $end, $accounts, null, $currency, TransactionType::TRANSFER); $journals = $this->getTransactionsForSum(TransactionType::TRANSFER, $start, $end, $accounts, null, $currency);
return $this->groupByEither($journals); return $this->groupByEither($journals);
} }
@@ -234,8 +234,8 @@ class OperationsRepository implements OperationsRepositoryInterface
* @return array * @return array
*/ */
private function getTransactionsForSum( private function getTransactionsForSum(
Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $opposing = null, ?TransactionCurrency $currency = null, string $type, Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $opposing = null, ?TransactionCurrency $currency = null
string $type
): array { ): array {
$start->startOfDay(); $start->startOfDay();
$end->endOfDay(); $end->endOfDay();
@@ -261,11 +261,9 @@ class OperationsRepository implements OperationsRepositoryInterface
$collector->setSourceAccounts($opposing); $collector->setSourceAccounts($opposing);
} }
} }
if(TransactionType::TRANSFER === $type) { // supports only accounts, not opposing.
// supports only accounts, not opposing. if (TransactionType::TRANSFER === $type && null !== $accounts) {
if(null !== $accounts) { $collector->setAccounts($accounts);
$collector->setAccounts($accounts);
}
} }
if (null !== $currency) { if (null !== $currency) {

View File

@@ -174,10 +174,8 @@ class AttachmentRepository implements AttachmentRepositoryInterface
$attachment->title = $data['title']; $attachment->title = $data['title'];
} }
if (array_key_exists('filename', $data)) { if (array_key_exists('filename', $data) && '' !== (string)$data['filename'] && $data['filename'] !== $attachment->filename) {
if ('' !== (string)$data['filename'] && $data['filename'] !== $attachment->filename) { $attachment->filename = $data['filename'];
$attachment->filename = $data['filename'];
}
} }
// update model (move attachment) // update model (move attachment)
// should be validated already: // should be validated already:

View File

@@ -505,14 +505,6 @@ class BillRepository implements BillRepositoryInterface
$currentStart = clone $nextExpectedMatch; $currentStart = clone $nextExpectedMatch;
} }
$simple = $set->each(
static function (Carbon $date) {
return $date->format('Y-m-d');
}
);
//Log::debug(sprintf('Found dates between %s and %s:', $start->format('Y-m-d'), $end->format('Y-m-d')), $simple->toArray());
return $set; return $set;
} }
@@ -657,12 +649,6 @@ class BillRepository implements BillRepositoryInterface
while ($start < $date) { while ($start < $date) {
$start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); $start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
} }
$end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
//Log::debug('nextDateMatch: Final start is ' . $start->format('Y-m-d'));
//Log::debug('nextDateMatch: Matching end is ' . $end->format('Y-m-d'));
$cache->store($start); $cache->store($start);
return $start; return $start;

View File

@@ -151,7 +151,7 @@ class TagRepository implements TagRepositoryInterface
$disk = Storage::disk('upload'); $disk = Storage::disk('upload');
return $set->each( return $set->each(
static function (Attachment $attachment, int $index) use ($disk) { static function (Attachment $attachment) use ($disk) {
/** @var Note $note */ /** @var Note $note */
$note = $attachment->notes()->first(); $note = $attachment->notes()->first();
// only used in v1 view of tags // only used in v1 view of tags

View File

@@ -116,7 +116,7 @@ class WebhookRepository implements WebhookRepositoryInterface
*/ */
public function store(array $data): Webhook public function store(array $data): Webhook
{ {
$secret = $random = Str::random(24); $secret = Str::random(24);
$fullData = [ $fullData = [
'user_id' => $this->user->id, 'user_id' => $this->user->id,
'active' => $data['active'] ?? false, 'active' => $data['active'] ?? false,
@@ -144,7 +144,7 @@ class WebhookRepository implements WebhookRepositoryInterface
$webhook->url = $data['url'] ?? $webhook->url; $webhook->url = $data['url'] ?? $webhook->url;
if (true === $data['secret']) { if (true === $data['secret']) {
$secret = $random = Str::random(24); $secret = Str::random(24);
$webhook->secret = $secret; $webhook->secret = $secret;
} }

View File

@@ -522,7 +522,7 @@ trait AccountServiceTrait
], ],
], ],
]; ];
Log::debug('Going for submission', $submission); Log::debug('Going for submission in createOBGroupV2', $submission);
/** @var TransactionGroupFactory $factory */ /** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class); $factory = app(TransactionGroupFactory::class);
@@ -595,7 +595,7 @@ trait AccountServiceTrait
], ],
], ],
]; ];
Log::debug('Going for submission', $submission); Log::debug('Going for submission in createCreditTransaction', $submission);
/** @var TransactionGroupFactory $factory */ /** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class); $factory = app(TransactionGroupFactory::class);
@@ -688,7 +688,7 @@ trait AccountServiceTrait
], ],
], ],
]; ];
Log::debug('Going for submission', $submission); Log::debug('Going for submission in createOBGroup', $submission);
/** @var TransactionGroupFactory $factory */ /** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class); $factory = app(TransactionGroupFactory::class);

View File

@@ -55,7 +55,6 @@ class CreditRecalculateService
*/ */
public function recalculate(): void public function recalculate(): void
{ {
Log::debug(sprintf('Now in %s', __METHOD__));
if (true !== config('firefly.feature_flags.handle_debts')) { if (true !== config('firefly.feature_flags.handle_debts')) {
Log::debug('handle_debts is disabled.'); Log::debug('handle_debts is disabled.');
@@ -83,7 +82,6 @@ class CreditRecalculateService
private function processWork(): void private function processWork(): void
{ {
$this->repository = app(AccountRepositoryInterface::class); $this->repository = app(AccountRepositoryInterface::class);
Log::debug(sprintf('Now in %s', __METHOD__));
foreach ($this->work as $account) { foreach ($this->work as $account) {
$this->processWorkAccount($account); $this->processWorkAccount($account);
} }
@@ -127,7 +125,6 @@ class CreditRecalculateService
*/ */
private function processGroup(): void private function processGroup(): void
{ {
Log::debug(sprintf('Now in %s', __METHOD__));
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($this->group->transactionJournals as $journal) { foreach ($this->group->transactionJournals as $journal) {
if (0 === count($this->work)) { if (0 === count($this->work)) {
@@ -149,7 +146,6 @@ class CreditRecalculateService
*/ */
private function findByJournal(TransactionJournal $journal): void private function findByJournal(TransactionJournal $journal): void
{ {
Log::debug(sprintf('Now in %s', __METHOD__));
$source = $this->getSourceAccount($journal); $source = $this->getSourceAccount($journal);
$destination = $this->getDestinationAccount($journal); $destination = $this->getDestinationAccount($journal);
@@ -190,12 +186,12 @@ class CreditRecalculateService
if (null === $transaction) { if (null === $transaction) {
throw new FireflyException(sprintf('Cannot find "%s"-transaction of journal #%d', $direction, $journal->id)); throw new FireflyException(sprintf('Cannot find "%s"-transaction of journal #%d', $direction, $journal->id));
} }
$account = $transaction->account; $foundAccount = $transaction->account;
if (null === $account) { if (null === $foundAccount) {
throw new FireflyException(sprintf('Cannot find "%s"-account of transaction #%d of journal #%d', $direction, $transaction->id, $journal->id)); throw new FireflyException(sprintf('Cannot find "%s"-account of transaction #%d of journal #%d', $direction, $transaction->id, $journal->id));
} }
return $account; return $foundAccount;
} }
/** /**
@@ -214,7 +210,6 @@ class CreditRecalculateService
*/ */
private function processAccount(): void private function processAccount(): void
{ {
Log::debug(sprintf('Now in %s', __METHOD__));
$valid = config('firefly.valid_liabilities'); $valid = config('firefly.valid_liabilities');
if (in_array($this->account->accountType->type, $valid)) { if (in_array($this->account->accountType->type, $valid)) {
Log::debug(sprintf('Account type is "%s", include it.', $this->account->accountType->type)); Log::debug(sprintf('Account type is "%s", include it.', $this->account->accountType->type));

View File

@@ -167,8 +167,6 @@ class CategoryUpdateService
} }
$dbNote->text = trim($note); $dbNote->text = trim($note);
$dbNote->save(); $dbNote->save();
return;
} }
} }

View File

@@ -98,9 +98,7 @@ class RemoteUserGuard implements Guard
*/ */
public function check(): bool public function check(): bool
{ {
$result = !is_null($this->user()); return !is_null($this->user());
return $result;
} }
/** /**

View File

@@ -75,6 +75,9 @@ class ExportDataGenerator
private Carbon $start; private Carbon $start;
private User $user; private User $user;
private const ADD_RECORD_ERR = 'Could not add record to set: %s';
private const EXPORT_ERR = 'Could not export to string: %s';
public function __construct() public function __construct()
{ {
$this->accounts = new Collection; $this->accounts = new Collection;
@@ -142,10 +145,10 @@ class ExportDataGenerator
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$repository->setUser($this->user); $repository->setUser($this->user);
$accounts = $repository->getAccountsByType([]); $allAccounts = $repository->getAccountsByType([]);
$records = []; $records = [];
/** @var Account $account */ /** @var Account $account */
foreach ($accounts as $account) { foreach ($allAccounts as $account) {
$currency = $repository->getAccountCurrency($account); $currency = $repository->getAccountCurrency($account);
$records[] = [ $records[] = [
$this->user->id, $this->user->id,
@@ -175,7 +178,7 @@ class ExportDataGenerator
try { try {
$csv->insertOne($header); $csv->insertOne($header);
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::ADD_RECORD_ERR, $e->getMessage()), 0, $e);
} }
//insert all the records //insert all the records
@@ -184,7 +187,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { } catch (Exception $e) {
throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
return $string; return $string;
@@ -229,7 +232,7 @@ class ExportDataGenerator
try { try {
$csv->insertOne($header); $csv->insertOne($header);
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::ADD_RECORD_ERR, $e->getMessage()), 0, $e);
} }
//insert all the records //insert all the records
@@ -238,7 +241,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { } catch (Exception $e) {
throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
return $string; return $string;
@@ -293,7 +296,7 @@ class ExportDataGenerator
try { try {
$csv->insertOne($header); $csv->insertOne($header);
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::ADD_RECORD_ERR, $e->getMessage()), 0, $e);
} }
//insert all the records //insert all the records
@@ -302,7 +305,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { } catch (Exception $e) {
throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
return $string; return $string;
@@ -342,7 +345,7 @@ class ExportDataGenerator
try { try {
$csv->insertOne($header); $csv->insertOne($header);
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::ADD_RECORD_ERR, $e->getMessage()), 0, $e);
} }
//insert all the records //insert all the records
@@ -351,7 +354,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { } catch (Exception $e) {
throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
return $string; return $string;
@@ -406,7 +409,7 @@ class ExportDataGenerator
try { try {
$csv->insertOne($header); $csv->insertOne($header);
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::ADD_RECORD_ERR, $e->getMessage()), 0, $e);
} }
//insert all the records //insert all the records
@@ -415,7 +418,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { } catch (Exception $e) {
throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
return $string; return $string;
@@ -504,7 +507,7 @@ class ExportDataGenerator
try { try {
$csv->insertOne($header); $csv->insertOne($header);
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::ADD_RECORD_ERR, $e->getMessage()), 0, $e);
} }
//insert all the records //insert all the records
@@ -513,7 +516,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { } catch (Exception $e) {
throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
return $string; return $string;
@@ -571,7 +574,7 @@ class ExportDataGenerator
try { try {
$csv->insertOne($header); $csv->insertOne($header);
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::ADD_RECORD_ERR, $e->getMessage()), 0, $e);
} }
//insert all the records //insert all the records
@@ -580,7 +583,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { } catch (Exception $e) {
throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
return $string; return $string;
@@ -621,7 +624,7 @@ class ExportDataGenerator
try { try {
$csv->insertOne($header); $csv->insertOne($header);
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::ADD_RECORD_ERR, $e->getMessage()), 0, $e);
} }
//insert all the records //insert all the records
@@ -630,7 +633,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { } catch (Exception $e) {
throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
return $string; return $string;
@@ -741,7 +744,7 @@ class ExportDataGenerator
try { try {
$csv->insertOne($header); $csv->insertOne($header);
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
throw new FireflyException(sprintf('Could not add record to set: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::ADD_RECORD_ERR, $e->getMessage()), 0, $e);
} }
//insert all the records //insert all the records
@@ -750,7 +753,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { } catch (Exception $e) {
throw new FireflyException(sprintf('Could not export to string: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
return $string; return $string;

View File

@@ -259,9 +259,9 @@ class OperatorQuerySearch implements SearchInterface
case Emoticon::class: case Emoticon::class:
case Emoji::class: case Emoji::class:
case Mention::class: case Mention::class:
$words = (string)$searchNode->getValue(); $allWords = (string)$searchNode->getValue();
Log::debug(sprintf('Add words "%s" to search string, because Node class is "%s"', $words, $class)); Log::debug(sprintf('Add words "%s" to search string, because Node class is "%s"', $allWords, $class));
$this->words[] = $words; $this->words[] = $allWords;
break; break;
case Field::class: case Field::class:
Log::debug(sprintf('Now handle Node class %s', $class)); Log::debug(sprintf('Now handle Node class %s', $class));
@@ -836,11 +836,11 @@ class OperatorQuerySearch implements SearchInterface
if ($parser->isDateRange($value)) { if ($parser->isDateRange($value)) {
return $parser->parseRange($value, $this->date); return $parser->parseRange($value, $this->date);
} }
$date = $parser->parseDate($value); $parsedDate = $parser->parseDate($value);
return [ return [
'start' => $date, 'start' => $parsedDate,
'end' => $date, 'end' => $parsedDate,
]; ];
} }

View File

@@ -293,11 +293,9 @@ class SearchRuleEngine implements RuleEngineInterface
$journalTrigger = false; $journalTrigger = false;
$dateTrigger = false; $dateTrigger = false;
foreach ($array as $triggerName => $values) { foreach ($array as $triggerName => $values) {
if ('journal_id' === $triggerName) { if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
if (is_array($values) && 1 === count($values)) { Log::debug('Found a journal_id trigger with 1 journal, true.');
Log::debug('Found a journal_id trigger with 1 journal, true.'); $journalTrigger = true;
$journalTrigger = true;
}
} }
if (in_array($triggerName, ['date_is', 'date', 'on', 'date_before', 'before', 'date_after', 'after'], 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.'); Log::debug('Found a date related trigger, set to true.');
@@ -320,11 +318,9 @@ class SearchRuleEngine implements RuleEngineInterface
Log::debug('Now in setDateFromJournalTrigger()'); Log::debug('Now in setDateFromJournalTrigger()');
$journalId = 0; $journalId = 0;
foreach ($array as $triggerName => $values) { foreach ($array as $triggerName => $values) {
if ('journal_id' === $triggerName) { if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) {
if (is_array($values) && 1 === count($values)) { $journalId = (int)trim(($values[0] ?? '"0"'), '"'); // follows format "123".
$journalId = (int)trim(($values[0] ?? '"0"'), '"'); // follows format "123". Log::debug(sprintf('Found journal ID #%d', $journalId));
Log::debug(sprintf('Found journal ID #%d', $journalId));
}
} }
} }
if (0 !== $journalId) { if (0 !== $journalId) {

View File

@@ -255,9 +255,7 @@ class BillTransformer extends AbstractTransformer
return $date->format('Y-m-d'); return $date->format('Y-m-d');
} }
); );
$array = $simple->toArray(); return $simple->toArray();
return $array;
} }
/** /**

View File

@@ -182,8 +182,6 @@ trait RecurrenceValidation
if ($reps > 0 && null !== $repeatUntil) { if ($reps > 0 && null !== $repeatUntil) {
$validator->errors()->add('nr_of_repetitions', trans('validation.require_repeat_until')); $validator->errors()->add('nr_of_repetitions', trans('validation.require_repeat_until'));
$validator->errors()->add('repeat_until', trans('validation.require_repeat_until')); $validator->errors()->add('repeat_until', trans('validation.require_repeat_until'));
return;
} }
} }

View File

@@ -331,9 +331,8 @@ trait TransactionValidation
* All types of splits must be equal. * All types of splits must be equal.
* *
* @param Validator $validator * @param Validator $validator
* @param TransactionGroup $transactionGroup
*/ */
public function validateTransactionTypesForUpdate(Validator $validator, TransactionGroup $transactionGroup): void public function validateTransactionTypesForUpdate(Validator $validator): void
{ {
Log::debug('Now in validateTransactionTypesForUpdate()'); Log::debug('Now in validateTransactionTypesForUpdate()');
$transactions = $this->getTransactionsArray($validator); $transactions = $this->getTransactionsArray($validator);

View File

@@ -36,8 +36,8 @@
<div class="card-header"> <div class="card-header">
</div> </div>
<div class="card-body p-0"> <div class="card-body p-0">
<b-table id="my-table" striped hover responsive="md" primary-key="id" <b-table id="my-table" striped hover responsive="md" primary-key="id" :no-local-sorting="true"
:items="accounts" :fields="fields" :items="itemsProvider" :fields="fields"
:per-page="perPage" :per-page="perPage"
sort-icon-left sort-icon-left
ref="table" ref="table"
@@ -46,7 +46,7 @@
:sort-by.sync="sortBy" :sort-by.sync="sortBy"
:sort-desc.sync="sortDesc" :sort-desc.sync="sortDesc"
> >
<template #cell(title)="data"> <template #cell(name)="data">
<a :class="false === data.item.active ? 'text-muted' : ''" :href="'./accounts/show/' + data.item.id" :title="data.value">{{ data.value }}</a> <a :class="false === data.item.active ? 'text-muted' : ''" :href="'./accounts/show/' + data.item.id" :title="data.value">{{ data.value }}</a>
</template> </template>
<template #cell(number)="data"> <template #cell(number)="data">
@@ -162,6 +162,10 @@
import {mapGetters} from "vuex"; import {mapGetters} from "vuex";
import Sortable from "sortablejs"; import Sortable from "sortablejs";
import format from "date-fns/format"; import format from "date-fns/format";
import {setup} from 'axios-cache-adapter'
// import {cacheAdapterEnhancer} from 'axios-extensions';
// pas wat teruggeven als die pagina ook gevraagd wordt, anders een empty array
// van X lang?
export default { export default {
name: "Index", name: "Index",
@@ -179,9 +183,10 @@ export default {
fields: [], fields: [],
currentPage: 1, currentPage: 1,
perPage: 5, perPage: 5,
total: 0, total: 1,
sortBy: 'order', sortBy: 'order',
sortDesc: false, sortDesc: false,
api: null,
sortableOptions: { sortableOptions: {
disabled: false, disabled: false,
chosenClass: 'is-selected', chosenClass: 'is-selected',
@@ -192,13 +197,13 @@ export default {
}, },
watch: { watch: {
storeReady: function () { storeReady: function () {
this.getAccountList(); //this.getAccountList();
}, },
start: function () { start: function () {
this.getAccountList(); //this.getAccountList();
}, },
end: function () { end: function () {
this.getAccountList(); //this.getAccountList();
}, },
orderMode: function (value) { orderMode: function (value) {
// update the table headers // update the table headers
@@ -229,14 +234,55 @@ export default {
let pathName = window.location.pathname; let pathName = window.location.pathname;
let parts = pathName.split('/'); let parts = pathName.split('/');
this.type = parts[parts.length - 1]; this.type = parts[parts.length - 1];
this.perPage = this.listPageSize ?? 51;
console.log('Per page: ' + this.perPage);
let params = new URLSearchParams(window.location.search); let params = new URLSearchParams(window.location.search);
this.currentPage = params.get('page') ? parseInt(params.get('page')) : 1; this.currentPage = params.get('page') ? parseInt(params.get('page')) : 1;
this.updateFieldList(); this.updateFieldList();
this.ready = true; this.ready = true;
// make object thing:
let token = document.head.querySelector('meta[name="csrf-token"]');
this.api = setup(
{
// `axios` options
//baseURL: './',
headers: {'X-CSRF-TOKEN': token.content, 'X-James': 'yes'},
// `axios-cache-adapter` options
cache: {
maxAge: 15 * 60 * 1000,
readHeaders: false,
exclude: {
query: false,
},
debug: true
}
});
}, },
methods: { methods: {
itemsProvider: function (ctx, callback) {
console.log('itemsProvider()');
console.log('ctx.currentPage = ' + ctx.currentPage);
console.log('this.currentPage = ' + this.currentPage);
if (ctx.currentPage === this.currentPage) {
let direction = this.sortDesc ? '-' : '+';
let url = 'api/v1/accounts?type=' + this.type + '&page=' + ctx.currentPage + '&sort=' + direction + this.sortBy;
this.api.get(url)
.then(async (response) => {
this.total = parseInt(response.data.meta.pagination.total);
let items = this.parseAccountsAndReturn(response.data.data);
items = this.filterAccountListAndReturn(items);
callback(items);
}
);
return null;
}
return [];
},
saveAccountSort: function (event) { saveAccountSort: function (event) {
let oldIndex = parseInt(event.oldIndex); let oldIndex = parseInt(event.oldIndex);
let newIndex = parseInt(event.newIndex); let newIndex = parseInt(event.newIndex);
@@ -277,7 +323,7 @@ export default {
updateFieldList: function () { updateFieldList: function () {
this.fields = []; this.fields = [];
this.fields = [{key: 'title', label: this.$t('list.name'), sortable: !this.orderMode}]; this.fields = [{key: 'name', label: this.$t('list.name'), sortable: !this.orderMode}];
if ('asset' === this.type) { if ('asset' === this.type) {
this.fields.push({key: 'role', label: this.$t('list.role'), sortable: !this.orderMode}); this.fields.push({key: 'role', label: this.$t('list.role'), sortable: !this.orderMode});
} }
@@ -305,7 +351,7 @@ export default {
this.perPage = this.listPageSize ?? 51; this.perPage = this.listPageSize ?? 51;
this.accounts = []; this.accounts = [];
this.allAccounts = []; this.allAccounts = [];
this.downloadAccountList(1); //this.downloadAccountList(1);
} }
if (this.indexReady && !this.loading && this.downloaded) { if (this.indexReady && !this.loading && this.downloaded) {
// console.log('Index ready, not loading and not downloaded.'); // console.log('Index ready, not loading and not downloaded.');
@@ -314,8 +360,13 @@ export default {
} }
}, },
downloadAccountList: function (page) { downloadAccountList: function (page) {
const http = axios.create({
baseURL: './',
headers: {'Cache-Control': 'no-cache'},
});
// console.log('downloadAccountList(' + page + ')'); // console.log('downloadAccountList(' + page + ')');
axios.get('./api/v1/accounts?type=' + this.type + '&page=' + page) http.get('./api/v1/accounts?type=' + this.type + '&page=' + page)
.then(response => { .then(response => {
let currentPage = parseInt(response.data.meta.pagination.current_page); let currentPage = parseInt(response.data.meta.pagination.current_page);
let totalPage = parseInt(response.data.meta.pagination.total_pages); let totalPage = parseInt(response.data.meta.pagination.total_pages);
@@ -333,6 +384,29 @@ export default {
} }
); );
}, },
filterAccountListAndReturn: function (allAccounts) {
console.log('filterAccountListAndReturn()');
let accounts = [];
for (let i in allAccounts) {
if (allAccounts.hasOwnProperty(i) && /^0$|^[1-9]\d*$/.test(i) && i <= 4294967294) {
// 1 = active only
// 2 = inactive only
// 3 = both
if (1 === this.activeFilter && false === allAccounts[i].active) {
// console.log('Skip account #' + this.allAccounts[i].id + ' because not active.');
continue;
}
if (2 === this.activeFilter && true === allAccounts[i].active) {
// console.log('Skip account #' + this.allAccounts[i].id + ' because active.');
continue;
}
// console.log('Include account #' + this.allAccounts[i].id + '.');
accounts.push(allAccounts[i]);
}
}
return accounts;
},
filterAccountList: function () { filterAccountList: function () {
// console.log('filterAccountList()'); // console.log('filterAccountList()');
this.accounts = []; this.accounts = [];
@@ -367,6 +441,49 @@ export default {
this.total = parseInt(data.pagination.total); this.total = parseInt(data.pagination.total);
//console.log('Total is now ' + this.total); //console.log('Total is now ' + this.total);
}, },
parseAccountsAndReturn: function (data) {
console.log('In parseAccountsAndReturn()');
let allAccounts = [];
for (let key in data) {
if (data.hasOwnProperty(key) && /^0$|^[1-9]\d*$/.test(key) && key <= 4294967294) {
let current = data[key];
let acct = {};
acct.id = parseInt(current.id);
acct.order = current.attributes.order;
acct.name = current.attributes.name;
acct.active = current.attributes.active;
acct.role = this.roleTranslate(current.attributes.account_role);
acct.account_number = current.attributes.account_number;
acct.current_balance = current.attributes.current_balance;
acct.currency_code = current.attributes.currency_code;
if ('liabilities' === this.type) {
acct.liability_type = this.$t('firefly.account_type_' + current.attributes.liability_type);
acct.liability_direction = this.$t('firefly.liability_direction_' + current.attributes.liability_direction + '_short');
acct.interest = current.attributes.interest;
acct.interest_period = this.$t('firefly.interest_calc_' + current.attributes.interest_period);
acct.amount_due = current.attributes.current_debt;
}
acct.balance_diff = 'loading';
acct.last_activity = 'loading';
if (null !== current.attributes.iban) {
acct.iban = current.attributes.iban.match(/.{1,4}/g).join(' ');
}
if (null === current.attributes.iban) {
acct.iban = null;
}
allAccounts.push(acct);
if ('asset' === this.type) {
// TODO
//this.getAccountBalanceDifference(this.allAccounts.length - 1, current);
//this.getAccountLastActivity(this.allAccounts.length - 1, current);
}
}
}
return allAccounts;
},
parseAccounts: function (data) { parseAccounts: function (data) {
// console.log('In parseAccounts()'); // console.log('In parseAccounts()');
for (let key in data) { for (let key in data) {
@@ -375,7 +492,7 @@ export default {
let acct = {}; let acct = {};
acct.id = parseInt(current.id); acct.id = parseInt(current.id);
acct.order = current.attributes.order; acct.order = current.attributes.order;
acct.title = current.attributes.name; acct.name = current.attributes.name;
acct.active = current.attributes.active; acct.active = current.attributes.active;
acct.role = this.roleTranslate(current.attributes.account_role); acct.role = this.roleTranslate(current.attributes.account_role);
acct.account_number = current.attributes.account_number; acct.account_number = current.attributes.account_number;

View File

@@ -65,8 +65,6 @@ export default {
liability_direction: function (value) { liability_direction: function (value) {
this.$emit('set-field', {field: 'liability_direction', value: value}); this.$emit('set-field', {field: 'liability_direction', value: value});
}, },
},
created() {
} }
} }
</script> </script>

View File

@@ -71,10 +71,7 @@
<script> <script>
export default { export default {
name: "Index", name: "Index"
created() {
}
} }
</script> </script>

View File

@@ -74,8 +74,9 @@ export default {
//let strokePointHighColors = []; //let strokePointHighColors = [];
for (let i = 0; i < colourSet.length; i++) { //for (let i = 0; i < colourSet.length; i++) {
fillColors.push("rgba(" + colourSet[i][0] + ", " + colourSet[i][1] + ", " + colourSet[i][2] + ", 0.5)"); for (let value of colourSet) {
fillColors.push("rgba(" + value[0] + ", " + value[1] + ", " + value[2] + ", 0.5)");
//strokePointHighColors.push("rgba(" + colourSet[i][0] + ", " + colourSet[i][1] + ", " + colourSet[i][2] + ", 0.9)"); //strokePointHighColors.push("rgba(" + colourSet[i][0] + ", " + colourSet[i][1] + ", " + colourSet[i][2] + ", 0.9)");
} }
this.newDataSet.labels = this.dataSet.labels; this.newDataSet.labels = this.dataSet.labels;
@@ -123,8 +124,9 @@ export default {
//let strokePointHighColors = []; //let strokePointHighColors = [];
for (let i = 0; i < colourSet.length; i++) { //for (let i = 0; i < colourSet.length; i++) {
fillColors.push("rgba(" + colourSet[i][0] + ", " + colourSet[i][1] + ", " + colourSet[i][2] + ", 0.5)"); for (let value of colourSet) {
fillColors.push("rgba(" + value[0] + ", " + value[1] + ", " + value[2] + ", 0.5)");
//strokePointHighColors.push("rgba(" + colourSet[i][0] + ", " + colourSet[i][1] + ", " + colourSet[i][2] + ", 0.9)"); //strokePointHighColors.push("rgba(" + colourSet[i][0] + ", " + colourSet[i][1] + ", " + colourSet[i][2] + ", 0.9)");
} }
this.newDataSet.labels = this.dataSet.labels; this.newDataSet.labels = this.dataSet.labels;

View File

@@ -327,7 +327,6 @@ export default {
let title = 'todo'; let title = 'todo';
let half = 1; let half = 1;
// its currently first half of year: // its currently first half of year:
if (today.getMonth() <= 5) { if (today.getMonth() <= 5) {
// previous year, last half: // previous year, last half:
@@ -398,7 +397,6 @@ export default {
end.setMonth(5); end.setMonth(5);
end.setDate(30); end.setDate(30);
end = endOfDay(end); end = endOfDay(end);
half = 1;
title = format(start, this.$t('config.half_year_fns', {half: half})); title = format(start, this.$t('config.half_year_fns', {half: half}));
this.periods.push( this.periods.push(
{ {
@@ -450,7 +448,6 @@ export default {
let today = new Date(this.range.start); let today = new Date(this.range.start);
let start; let start;
let end; let end;
let title;
// last year // last year
start = new Date(today); start = new Date(today);

View File

@@ -22,9 +22,6 @@
//import {Line, mixins} from 'vue-chartjs' //import {Line, mixins} from 'vue-chartjs'
import { Chart, LineController, LineElement, PointElement, LinearScale, Title } from 'chart.js'
const {reactiveProp} = mixins const {reactiveProp} = mixins
export default { export default {

View File

@@ -141,9 +141,9 @@ export default {
}); });
}, },
parseIncome(data) { parseIncome(data) {
for (let mainKey in data) { for (let i in data) {
if (data.hasOwnProperty(mainKey)) { if (data.hasOwnProperty(i)) {
mainKey = parseInt(mainKey); let mainKey = parseInt(i);
// contains currency info and entries. // contains currency info and entries.
let current = data[mainKey]; let current = data[mainKey];
current.pct = 0; current.pct = 0;

View File

@@ -25,8 +25,6 @@
<form @submit="submitTransaction" autocomplete="off"> <form @submit="submitTransaction" autocomplete="off">
<SplitPills :transactions="transactions"/> <SplitPills :transactions="transactions"/>
<div class="tab-content"> <div class="tab-content">
<!-- v-on:switch-accounts="switchAccounts($event)" -->
<!-- :allowed-opposing-types="allowedOpposingTypes" -->
<SplitForm <SplitForm
v-for="(transaction, index) in this.transactions" v-for="(transaction, index) in this.transactions"
v-bind:key="index" v-bind:key="index"
@@ -119,8 +117,6 @@ import SplitPills from "./SplitPills";
import TransactionGroupTitle from "./TransactionGroupTitle"; import TransactionGroupTitle from "./TransactionGroupTitle";
import SplitForm from "./SplitForm"; import SplitForm from "./SplitForm";
import {mapGetters, mapMutations} from "vuex"; import {mapGetters, mapMutations} from "vuex";
import {getDefaultErrors} from "../../shared/transactions";
export default { export default {
name: "Create", name: "Create",

View File

@@ -386,23 +386,23 @@ export default {
}, },
sourceAccount: function () { sourceAccount: function () {
//console.log('computed::sourceAccount(' + this.index + ')'); //console.log('computed::sourceAccount(' + this.index + ')');
let value = { return {
id: this.transaction.source_account_id, id: this.transaction.source_account_id,
name: this.transaction.source_account_name, name: this.transaction.source_account_name,
type: this.transaction.source_account_type, type: this.transaction.source_account_type,
}; };
//console.log(JSON.stringify(value)); //console.log(JSON.stringify(value));
return value; //return value;
}, },
destinationAccount: function () { destinationAccount: function () {
//console.log('computed::destinationAccount(' + this.index + ')'); //console.log('computed::destinationAccount(' + this.index + ')');
let value = { return {
id: this.transaction.destination_account_id, id: this.transaction.destination_account_id,
name: this.transaction.destination_account_name, name: this.transaction.destination_account_name,
type: this.transaction.destination_account_type, type: this.transaction.destination_account_type,
}; };
//console.log(JSON.stringify(value)); //console.log(JSON.stringify(value));
return value; //return value;
}, },
hasMetaFields: function () { hasMetaFields: function () {
let requiredFields = [ let requiredFields = [

View File

@@ -26,11 +26,6 @@
</span> </span>
<span v-if="'any' === this.transactionType" class="text-muted">&nbsp;</span> <span v-if="'any' === this.transactionType" class="text-muted">&nbsp;</span>
</div> </div>
<!--
<div class="btn-group d-flex">
<button class="btn btn-light" @click="switchAccounts">&harr;</button>
</div>
-->
</div> </div>
</template> </template>

View File

@@ -23,7 +23,6 @@
<div v-if="visible" class="text-xs d-none d-lg-block d-xl-block"> <div v-if="visible" class="text-xs d-none d-lg-block d-xl-block">
<span v-if="0 === this.index">{{ $t('firefly.' + this.direction + '_account') }}</span> <span v-if="0 === this.index">{{ $t('firefly.' + this.direction + '_account') }}</span>
<span v-if="this.index > 0" class="text-warning">{{ $t('firefly.first_split_overrules_' + this.direction) }}</span> <span v-if="this.index > 0" class="text-warning">{{ $t('firefly.first_split_overrules_' + this.direction) }}</span>
<!--<br><span>{{ selectedAccount }}</span>-->
</div> </div>
<div v-if="!visible" class="text-xs d-none d-lg-block d-xl-block"> <div v-if="!visible" class="text-xs d-none d-lg-block d-xl-block">
&nbsp; &nbsp;

View File

@@ -378,8 +378,6 @@ export default {
} }
tagList = []; tagList = [];
foreignAmount = null;
foreignCurrency = null;
// loop tags // loop tags
for (let tagKey in row.tags) { for (let tagKey in row.tags) {
if (row.tags.hasOwnProperty(tagKey) && /^0$|^[1-9]\d*$/.test(tagKey) && tagKey <= 4294967294) { if (row.tags.hasOwnProperty(tagKey) && /^0$|^[1-9]\d*$/.test(tagKey) && tagKey <= 4294967294) {

View File

@@ -56,9 +56,9 @@ export default {
error: Array error: Array
}, },
mounted: function () { mounted: function () {
window.addEventListener('paste', e => { // window.addEventListener('paste', e => {
this.$refs.input.files = e.clipboardData.files; // this.$refs.input.files = e.clipboardData.files;
}); // });
}, },
methods: { methods: {
clearAtt: function () { clearAtt: function () {

View File

@@ -165,8 +165,6 @@ class UpdateControllerTest extends TestCase
$fieldSet->addField(Field::createBasic('transactions/0/' . $value, 'uuid')); $fieldSet->addField(Field::createBasic('transactions/0/' . $value, 'uuid'));
$configuration->addOptionalFieldSet($value, $fieldSet); $configuration->addOptionalFieldSet($value, $fieldSet);
} }
$result = $configuration->generateAll(); return $configuration->generateAll();
return $result;
} }
} }

View File

@@ -113,7 +113,7 @@ class UpdateControllerTest extends TestCase
public function updateDataSet(): array public function updateDataSet(): array
{ {
$faker = Factory::create(); $faker = Factory::create();
$set = [ return [
'name' => [ 'name' => [
'id' => 'INR', 'id' => 'INR',
'fields' => [ 'fields' => [
@@ -157,7 +157,5 @@ class UpdateControllerTest extends TestCase
'extra_ignore' => [], 'extra_ignore' => [],
], ],
]; ];
return $set;
} }
} }

View File

@@ -21,10 +21,11 @@
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace Tests\Objects; namespace Tests\Objects;
use Faker\Factory; use Faker\Factory;
use RuntimeException; use UnexpectedValueException;
/** /**
* Class TestConfiguration * Class TestConfiguration
@@ -70,10 +71,10 @@ class TestConfiguration
{ {
$this->debugMsg('Now in generateAll()'); $this->debugMsg('Now in generateAll()');
// generate submissions // generate submissions
$array = $this->generateSubmissions(); $array = $this->generateSubmissions();
$parameters = $this->parameters; $allParameters = $this->parameters;
$ignored = $this->ignores; $ignored = $this->ignores;
$expected = $this->expected; $expectedValue = $this->expected;
$this->debugMsg(sprintf('Now validating %d ignored() values.', count($ignored))); $this->debugMsg(sprintf('Now validating %d ignored() values.', count($ignored)));
@@ -111,9 +112,9 @@ class TestConfiguration
foreach ($array as $index => $submission) { foreach ($array as $index => $submission) {
$final[] = [[ $final[] = [[
'submission' => $submission, 'submission' => $submission,
'expected' => $expected[$index] ?? $submission, 'expected' => $expectedValue[$index] ?? $submission,
'ignore' => $newIgnored[$index] ?? [], 'ignore' => $newIgnored[$index] ?? [],
'parameters' => $parameters[$index] ?? [], 'parameters' => $allParameters[$index] ?? [],
]]; ]];
} }
@@ -205,7 +206,7 @@ class TestConfiguration
$this->debugMsg(sprintf(' Set #%d will consist of:', $totalCount)); $this->debugMsg(sprintf(' Set #%d will consist of:', $totalCount));
// the custom set is born! // the custom set is born!
$custom = []; $custom = [];
$expected = []; $expectedValue = [];
foreach ($combinationSet as $combination) { foreach ($combinationSet as $combination) {
$this->debugMsg(sprintf(' %s', $combination)); $this->debugMsg(sprintf(' %s', $combination));
// here we start adding stuff to a copy of the standard submission. // here we start adding stuff to a copy of the standard submission.
@@ -217,7 +218,7 @@ class TestConfiguration
foreach ($customSet->fields as $field) { foreach ($customSet->fields as $field) {
$this->debugMsg(sprintf(' added field "%s" from custom set "%s"', $field->fieldTitle, $combination)); $this->debugMsg(sprintf(' added field "%s" from custom set "%s"', $field->fieldTitle, $combination));
$custom = $this->parseField($custom, $field); $custom = $this->parseField($custom, $field);
$expected = $this->parseExpected($expected, $field, $custom); $expectedValue = $this->parseExpected($expectedValue, $field, $custom);
// for each field, add the ignores to the current index (+1!) of // for each field, add the ignores to the current index (+1!) of
// ignores. // ignores.
$count = count($this->submission); $count = count($this->submission);
@@ -248,7 +249,7 @@ class TestConfiguration
$this->debugMsg(sprintf(' New set of ignore things (%d) is: %s', $count, json_encode($this->ignores[$count]))); $this->debugMsg(sprintf(' New set of ignore things (%d) is: %s', $count, json_encode($this->ignores[$count])));
} }
$this->expected[$count] = $expected; $this->expected[$count] = $expectedValue;
} }
$count = count($this->submission); $count = count($this->submission);
$this->parameters[$count] = $customSet->parameters ?? []; $this->parameters[$count] = $customSet->parameters ?? [];
@@ -341,12 +342,12 @@ class TestConfiguration
{ {
$ignore = []; $ignore = [];
$result = []; $result = [];
$expected = []; $expectedValue = [];
/** @var Field $field */ /** @var Field $field */
foreach ($set->fields as $field) { foreach ($set->fields as $field) {
// this is what we will submit: // this is what we will submit:
$result = $this->parseField($result, $field); $result = $this->parseField($result, $field);
$expected = $this->parseExpected($expected, $field, $result); $expectedValue = $this->parseExpected($expectedValue, $field, $result);
// this is what we will ignore: // this is what we will ignore:
$newIgnore = array_unique($ignore + $field->ignorableFields); $newIgnore = array_unique($ignore + $field->ignorableFields);
@@ -355,7 +356,7 @@ class TestConfiguration
} }
$this->ignores[] = array_values($ignore); $this->ignores[] = array_values($ignore);
$this->expected[] = $expected; $this->expected[] = $expectedValue;
$this->parameters[] = $set->parameters ?? []; $this->parameters[] = $set->parameters ?? [];
return $result; return $result;
@@ -388,7 +389,7 @@ class TestConfiguration
return $current; return $current;
} }
throw new RuntimeException(sprintf('Did not expect count %d from fieldTitle "%s".', $count, $field->fieldTitle)); throw new UnexpectedValueException(sprintf('Did not expect count %d from fieldTitle "%s".', $count, $field->fieldTitle));
} }
/** /**
@@ -401,7 +402,7 @@ class TestConfiguration
$faker = Factory::create(); $faker = Factory::create();
switch ($type) { switch ($type) {
default: default:
throw new RuntimeException(sprintf('Cannot handle field "%s"', $type)); throw new UnexpectedValueException(sprintf('Cannot handle field "%s"', $type));
case 'uuid': case 'uuid':
return $faker->uuid; return $faker->uuid;
case 'static-asset': case 'static-asset':
@@ -604,7 +605,7 @@ class TestConfiguration
return $expected; return $expected;
} }
throw new RuntimeException(sprintf('Did not expect count %d from fieldTitle "%s".', $count, $field->fieldTitle)); throw new UnexpectedValueException(sprintf('Did not expect count %d from fieldTitle "%s".', $count, $field->fieldTitle));
} }
/** /**

View File

@@ -193,7 +193,6 @@ trait TestHelpers
$url $url
); );
$this->assertEquals($response[$key], $original[$key], $message); $this->assertEquals($response[$key], $original[$key], $message);
continue;
} }
} }
} }