Optimise code.

This commit is contained in:
James Cole 2020-10-24 17:27:36 +02:00
parent b3f1737495
commit 3979e12043
No known key found for this signature in database
GPG Key ID: B5669F9493CDE38D
21 changed files with 199 additions and 187 deletions

View File

@ -86,7 +86,6 @@ class FixPiggies extends Command
$event->save(); $event->save();
$this->line(sprintf('Piggy bank #%d was referenced by an invalid event. This has been fixed.', $event->piggy_bank_id)); $this->line(sprintf('Piggy bank #%d was referenced by an invalid event. This has been fixed.', $event->piggy_bank_id));
$this->count++; $this->count++;
continue;
} }
} }
if (0 === $this->count) { if (0 === $this->count) {

View File

@ -33,11 +33,9 @@ class CronController
use CronRunner; use CronRunner;
/** /**
* @param string $token
*
* @return string * @return string
*/ */
public function cron(string $token): string public function cron(): string
{ {
$results = []; $results = [];
$results[] = $this->runRecurring(); $results[] = $this->runRecurring();

View File

@ -69,7 +69,7 @@ class ConvertController extends Controller
function ($request, $next) { function ($request, $next) {
$this->repository = app(JournalRepositoryInterface::class); $this->repository = app(JournalRepositoryInterface::class);
$this->accountRepository = app(AccountRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class);
app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('title', (string)trans('firefly.transactions'));
app('view')->share('mainTitleIcon', 'fa-exchange'); app('view')->share('mainTitleIcon', 'fa-exchange');
return $next($request); return $next($request);
@ -103,7 +103,7 @@ class ConvertController extends Controller
$groupTitle = $group->title ?? $first->description; $groupTitle = $group->title ?? $first->description;
$groupArray = $transformer->transformObject($group); $groupArray = $transformer->transformObject($group);
$subTitle = (string) trans('firefly.convert_to_' . $destinationType->type, ['description' => $groupTitle]); $subTitle = (string)trans('firefly.convert_to_' . $destinationType->type, ['description' => $groupTitle]);
$subTitleIcon = 'fa-exchange'; $subTitleIcon = 'fa-exchange';
// get a list of asset accounts and liabilities and stuff, in various combinations: // get a list of asset accounts and liabilities and stuff, in various combinations:
@ -119,7 +119,7 @@ class ConvertController extends Controller
if ($sourceType->type === $destinationType->type) { // cannot convert to its own type. if ($sourceType->type === $destinationType->type) { // cannot convert to its own type.
Log::debug('This is already a transaction of the expected type..'); Log::debug('This is already a transaction of the expected type..');
session()->flash('info', (string) trans('firefly.convert_is_already_type_' . $destinationType->type)); session()->flash('info', (string)trans('firefly.convert_is_already_type_' . $destinationType->type));
return redirect(route('transactions.show', [$group->id])); return redirect(route('transactions.show', [$group->id]));
} }
@ -174,9 +174,8 @@ class ConvertController extends Controller
// correct transfers: // correct transfers:
$group->refresh(); $group->refresh();
$this->correctTransfer($group);
session()->flash('success', (string) trans('firefly.converted_to_' . $destinationType->type)); session()->flash('success', (string)trans('firefly.converted_to_' . $destinationType->type));
event(new UpdatedTransactionGroup($group)); event(new UpdatedTransactionGroup($group));
return redirect(route('transactions.show', [$group->id])); return redirect(route('transactions.show', [$group->id]));
@ -203,10 +202,10 @@ class ConvertController extends Controller
$destinationName = $data['destination_name'][$journal->id] ?? null; $destinationName = $data['destination_name'][$journal->id] ?? null;
// double check its not an empty string. // double check its not an empty string.
$sourceId = '' === $sourceId || null === $sourceId ? null : (int) $sourceId; $sourceId = '' === $sourceId || null === $sourceId ? null : (int)$sourceId;
$sourceName = '' === $sourceName ? null : (string) $sourceName; $sourceName = '' === $sourceName ? null : (string)$sourceName;
$destinationId = '' === $destinationId || null === $destinationId ? null : (int) $destinationId; $destinationId = '' === $destinationId || null === $destinationId ? null : (int)$destinationId;
$destinationName = '' === $destinationName ? null : (string) $destinationName; $destinationName = '' === $destinationName ? null : (string)$destinationName;
$validSource = $validator->validateSource($sourceId, $sourceName, null); $validSource = $validator->validateSource($sourceId, $sourceName, null);
$validDestination = $validator->validateDestination($destinationId, $destinationName, null); $validDestination = $validator->validateDestination($destinationId, $destinationName, null);
@ -236,13 +235,6 @@ class ConvertController extends Controller
return $journal; return $journal;
} }
/**
* @param TransactionGroup $group
*/
private function correctTransfer(TransactionGroup $group): void
{
}
/** /**
* @return array * @return array
* @throws Exception * @throws Exception
@ -260,12 +252,12 @@ class ConvertController extends Controller
foreach ($accountList as $account) { foreach ($accountList as $account) {
$balance = app('steam')->balance($account, today()); $balance = app('steam')->balance($account, today());
$currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency; $currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = (string) $accountRepository->getMetaValue($account, 'account_role'); $role = (string)$accountRepository->getMetaValue($account, 'account_role');
if ('' === $role) { if ('' === $role) {
$role = 'no_account_type'; // @codeCoverageIgnore $role = 'no_account_type'; // @codeCoverageIgnore
} }
$key = (string) trans('firefly.opt_group_' . $role); $key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')'; $grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')';
} }
@ -290,7 +282,7 @@ class ConvertController extends Controller
$balance = app('steam')->balance($account, today()); $balance = app('steam')->balance($account, today());
$currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency; $currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = 'l_' . $account->accountType->type; $role = 'l_' . $account->accountType->type;
$key = (string) trans('firefly.opt_group_' . $role); $key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')'; $grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')';
} }
@ -312,7 +304,7 @@ class ConvertController extends Controller
// group accounts: // group accounts:
/** @var Account $account */ /** @var Account $account */
foreach ($accountList as $account) { foreach ($accountList as $account) {
$role = (string) $accountRepository->getMetaValue($account, 'account_role'); $role = (string)$accountRepository->getMetaValue($account, 'account_role');
$name = $account->name; $name = $account->name;
if ('' === $role) { if ('' === $role) {
$role = 'no_account_type'; // @codeCoverageIgnore $role = 'no_account_type'; // @codeCoverageIgnore
@ -332,7 +324,7 @@ class ConvertController extends Controller
$role = 'revenue_account'; // @codeCoverageIgnore $role = 'revenue_account'; // @codeCoverageIgnore
} }
$key = (string) trans('firefly.opt_group_' . $role); $key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $name; $grouped[$key][$account->id] = $name;
} }
@ -345,16 +337,17 @@ class ConvertController extends Controller
private function getValidWithdrawalDests(): array private function getValidWithdrawalDests(): array
{ {
// make repositories // make repositories
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $accountRepository */
$repository = app(AccountRepositoryInterface::class); $accountRepository = app(AccountRepositoryInterface::class);
$liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN]; $liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
$accountList = $repository $accountList = $accountRepository->getActiveAccountsByType(
->getActiveAccountsByType([AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]); [AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]
$grouped = []; );
$grouped = [];
// group accounts: // group accounts:
/** @var Account $account */ /** @var Account $account */
foreach ($accountList as $account) { foreach ($accountList as $account) {
$role = (string) $repository->getMetaValue($account, 'account_role'); $role = (string)$accountRepository->getMetaValue($account, 'account_role');
$name = $account->name; $name = $account->name;
if ('' === $role) { if ('' === $role) {
$role = 'no_account_type'; // @codeCoverageIgnore $role = 'no_account_type'; // @codeCoverageIgnore
@ -374,7 +367,7 @@ class ConvertController extends Controller
$role = 'expense_account'; // @codeCoverageIgnore $role = 'expense_account'; // @codeCoverageIgnore
} }
$key = (string) trans('firefly.opt_group_' . $role); $key = (string)trans('firefly.opt_group_' . $role);
$grouped[$key][$account->id] = $name; $grouped[$key][$account->id] = $name;
} }

View File

@ -41,8 +41,7 @@ class IndexController extends Controller
{ {
use PeriodOverview; use PeriodOverview;
/** @var JournalRepositoryInterface */ private JournalRepositoryInterface $repository;
private $repository;
/** /**
* IndexController constructor. * IndexController constructor.
@ -132,16 +131,12 @@ class IndexController extends Controller
*/ */
public function indexAll(Request $request, string $objectType) public function indexAll(Request $request, string $objectType)
{ {
/** @var JournalRepositoryInterface $repository */
$repository = app(JournalRepositoryInterface::class);
$subTitleIcon = config('firefly.transactionIconsByType.' . $objectType); $subTitleIcon = config('firefly.transactionIconsByType.' . $objectType);
$types = config('firefly.transactionTypesByType.' . $objectType); $types = config('firefly.transactionTypesByType.' . $objectType);
$page = (int) $request->get('page'); $page = (int) $request->get('page');
$pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $pageSize = (int) app('preferences')->get('listPageSize', 50)->data;
$path = route('transactions.index.all', [$objectType]); $path = route('transactions.index.all', [$objectType]);
$first = $repository->firstNull(); $first = $this->repository->firstNull();
$start = null === $first ? new Carbon : $first->date; $start = null === $first ? new Carbon : $first->date;
$last = $this->repository->getLast(); $last = $this->repository->getLast();
$end = $last ? $last->date : today(config('app.timezone')); $end = $last ? $last->date : today(config('app.timezone'));

View File

@ -47,8 +47,7 @@ use Log;
*/ */
class MassController extends Controller class MassController extends Controller
{ {
/** @var JournalRepositoryInterface Journals and transactions overview */ private JournalRepositoryInterface $repository;
private $repository;
/** /**
* MassController constructor. * MassController constructor.
@ -131,16 +130,16 @@ class MassController extends Controller
{ {
$subTitle = (string) trans('firefly.mass_edit_journals'); $subTitle = (string) trans('firefly.mass_edit_journals');
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $accountRepository */
$repository = app(AccountRepositoryInterface::class); $accountRepository = app(AccountRepositoryInterface::class);
// valid withdrawal sources: // valid withdrawal sources:
$array = array_keys(config(sprintf('firefly.source_dests.%s', TransactionType::WITHDRAWAL))); $array = array_keys(config(sprintf('firefly.source_dests.%s', TransactionType::WITHDRAWAL)));
$withdrawalSources = $repository->getAccountsByType($array); $withdrawalSources = $accountRepository->getAccountsByType($array);
// valid deposit destinations: // valid deposit destinations:
$array = config(sprintf('firefly.source_dests.%s.%s', TransactionType::DEPOSIT, AccountType::REVENUE)); $array = config(sprintf('firefly.source_dests.%s.%s', TransactionType::DEPOSIT, AccountType::REVENUE));
$depositDestinations = $repository->getAccountsByType($array); $depositDestinations = $accountRepository->getAccountsByType($array);
/** @var BudgetRepositoryInterface $budgetRepository */ /** @var BudgetRepositoryInterface $budgetRepository */
$budgetRepository = app(BudgetRepositoryInterface::class); $budgetRepository = app(BudgetRepositoryInterface::class);

View File

@ -331,8 +331,6 @@ class RecurrenceFormRequest extends FormRequest
$message = (string)trans('validation.generic_invalid_destination'); $message = (string)trans('validation.generic_invalid_destination');
$validator->errors()->add('destination_id', $message); $validator->errors()->add('destination_id', $message);
$validator->errors()->add('withdrawal_destination_id', $message); $validator->errors()->add('withdrawal_destination_id', $message);
return;
} }
} }
} }

View File

@ -212,7 +212,6 @@ class ReportFormRequest extends FormRequest
$tag = $repository->findNull((int)$tagTag); $tag = $repository->findNull((int)$tagTag);
if (null !== $tag) { if (null !== $tag) {
$collection->push($tag); $collection->push($tag);
continue;
} }
} }
} }

View File

@ -27,12 +27,10 @@ namespace FireflyIII\Jobs;
use Carbon\Carbon; use Carbon\Carbon;
use FireflyIII\Events\RequestedReportOnJournals; use FireflyIII\Events\RequestedReportOnJournals;
use FireflyIII\Events\StoredTransactionGroup; use FireflyIII\Events\StoredTransactionGroup;
use FireflyIII\Factory\PiggyBankEventFactory;
use FireflyIII\Models\Recurrence; use FireflyIII\Models\Recurrence;
use FireflyIII\Models\RecurrenceRepetition; use FireflyIII\Models\RecurrenceRepetition;
use FireflyIII\Models\RecurrenceTransaction; use FireflyIII\Models\RecurrenceTransaction;
use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface;
@ -52,22 +50,14 @@ class CreateRecurringTransactions implements ShouldQueue
{ {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/** @var int Transaction groups created */ public int $created;
public int $created; public int $executed;
/** @var int Number of recurrences actually fired */ public int $submitted;
public int $executed; private Carbon $date;
/** @var int Number of recurrences submitted */ private bool $force;
public int $submitted; private TransactionGroupRepositoryInterface $groupRepository;
/** @var Carbon The current date */ private JournalRepositoryInterface $journalRepository;
private Carbon $date; private RecurringRepositoryInterface $repository;
/** @var bool Force the transaction to be created no matter what. */
private bool $force;
/** @var TransactionGroupRepositoryInterface */
private $groupRepository;
/** @var JournalRepositoryInterface Journal repository */
private $journalRepository;
/** @var RecurringRepositoryInterface Recurring transactions repository. */
private $repository;
/** /**
* Create a new job instance. * Create a new job instance.
@ -121,9 +111,9 @@ class CreateRecurringTransactions implements ShouldQueue
app('preferences')->setForUser($recurrence->user, 'lastActivity', microtime()); app('preferences')->setForUser($recurrence->user, 'lastActivity', microtime());
Log::debug(sprintf('Now at recurrence #%d', $recurrence->id)); Log::debug(sprintf('Now at recurrence #%d', $recurrence->id));
$created = $this->handleRepetitions($recurrence); $createdReps = $this->handleRepetitions($recurrence);
Log::debug(sprintf('Done with recurrence #%d', $recurrence->id)); Log::debug(sprintf('Done with recurrence #%d', $recurrence->id));
$result[$recurrence->user_id] = $result[$recurrence->user_id]->merge($created); $result[$recurrence->user_id] = $result[$recurrence->user_id]->merge($createdReps);
$this->executed++; $this->executed++;
} }
@ -218,11 +208,11 @@ class CreateRecurringTransactions implements ShouldQueue
$return = []; $return = [];
/** @var RecurrenceTransaction $transaction */ /** @var RecurrenceTransaction $transaction */
foreach ($transactions as $index => $transaction) { foreach ($transactions as $index => $transaction) {
$single = [ $single = [
'type' => strtolower($recurrence->transactionType->type), 'type' => strtolower($recurrence->transactionType->type),
'date' => $date, 'date' => $date,
'user' => $recurrence->user_id, 'user' => $recurrence->user_id,
'currency_id' => (int) $transaction->transaction_currency_id, 'currency_id' => (int)$transaction->transaction_currency_id,
'currency_code' => null, 'currency_code' => null,
'description' => $recurrence->recurrenceTransactions()->first()->description, 'description' => $recurrence->recurrenceTransactions()->first()->description,
'amount' => $transaction->amount, 'amount' => $transaction->amount,
@ -239,16 +229,16 @@ class CreateRecurringTransactions implements ShouldQueue
'foreign_amount' => $transaction->foreign_amount, 'foreign_amount' => $transaction->foreign_amount,
'reconciled' => false, 'reconciled' => false,
'identifier' => $index, 'identifier' => $index,
'recurrence_id' => (int) $recurrence->id, 'recurrence_id' => (int)$recurrence->id,
'order' => $index, 'order' => $index,
'notes' => (string) trans('firefly.created_from_recurrence', ['id' => $recurrence->id, 'title' => $recurrence->title]), 'notes' => (string)trans('firefly.created_from_recurrence', ['id' => $recurrence->id, 'title' => $recurrence->title]),
'tags' => $this->repository->getTags($transaction), 'tags' => $this->repository->getTags($transaction),
'piggy_bank_id' => $this->repository->getPiggyBank($transaction), 'piggy_bank_id' => $this->repository->getPiggyBank($transaction),
'piggy_bank_name' => null, 'piggy_bank_name' => null,
'bill_id' => null, 'bill_id' => null,
'bill_name' => null, 'bill_name' => null,
'recurrence_total' => $total, 'recurrence_total' => $total,
'recurrence_count' => $count, 'recurrence_count' => $count,
]; ];
$return[] = $single; $return[] = $single;
} }

View File

@ -57,9 +57,9 @@ class NewIPAddressWarningMail extends Mailable
// time // time
$this->time = now()->formatLocalized((string)trans('config.date_time')); $this->time = now()->formatLocalized((string)trans('config.date_time'));
$this->host = ''; $this->host = '';
$host = gethostbyaddr($this->ipAddress); $hostName = gethostbyaddr($this->ipAddress);
if($host !== $this->ipAddress) { if($hostName !== $this->ipAddress) {
$this->host = $host; $this->host = $hostName;
} }
return $this->view('emails.new-ip-html')->text('emails.new-ip-text') return $this->view('emails.new-ip-html')->text('emails.new-ip-text')

View File

@ -44,17 +44,7 @@ class BillUpdateService
{ {
use BillServiceTrait, CreatesObjectGroups; use BillServiceTrait, CreatesObjectGroups;
protected $user; protected User $user;
/**
* Constructor.
*/
public function __construct()
{
if ('testing' === config('app.env')) {
Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this)));
}
}
/** /**
* @param Bill $bill * @param Bill $bill
@ -223,7 +213,6 @@ class BillUpdateService
Log::debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); Log::debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue));
$trigger->trigger_value = $newValue; $trigger->trigger_value = $newValue;
$trigger->save(); $trigger->save();
continue;
} }
} }
} }
@ -248,18 +237,14 @@ class BillUpdateService
private function updateOrder(Bill $bill, int $oldOrder, int $newOrder): void private function updateOrder(Bill $bill, int $oldOrder, int $newOrder): void
{ {
if ($newOrder > $oldOrder) { if ($newOrder > $oldOrder) {
/** @var User $user */ $this->user->bills()->where('order', '<=', $newOrder)->where('order', '>', $oldOrder)
$user = $this->user;
$user->bills()->where('order', '<=', $newOrder)->where('order', '>', $oldOrder)
->where('bills.id', '!=', $bill->id) ->where('bills.id', '!=', $bill->id)
->update(['order' => DB::raw('bills.order-1')]); ->update(['order' => DB::raw('bills.order-1')]);
$bill->order = $newOrder; $bill->order = $newOrder;
$bill->save(); $bill->save();
} }
if ($newOrder < $oldOrder) { if ($newOrder < $oldOrder) {
/** @var User $user */ $this->user->bills()->where('order', '>=', $newOrder)->where('order', '<', $oldOrder)
$user = $this->user;
$user->bills()->where('order', '>=', $newOrder)->where('order', '<', $oldOrder)
->where('bills.id', '!=', $bill->id) ->where('bills.id', '!=', $bill->id)
->update(['order' => DB::raw('bills.order+1')]); ->update(['order' => DB::raw('bills.order+1')]);
$bill->order = $newOrder; $bill->order = $newOrder;

View File

@ -54,32 +54,17 @@ class JournalUpdateService
{ {
use JournalServiceTrait; use JournalServiceTrait;
/** @var BillRepositoryInterface */ private BillRepositoryInterface $billRepository;
private $billRepository; private CurrencyRepositoryInterface $currencyRepository;
/** @var CurrencyRepositoryInterface */ private array $data;
private $currencyRepository; private Account $destinationAccount;
/** @var array The data to update the journal with. */ private Transaction $destinationTransaction;
private $data; private array $metaDate;
/** @var Account The destination account. */ private array $metaString;
private $destinationAccount; private Account $sourceAccount;
/** @var Transaction */ private Transaction $sourceTransaction;
private $destinationTransaction; private TransactionGroup $transactionGroup;
/** @var array All meta values that are dates. */ private TransactionJournal $transactionJournal;
private $metaDate;
/** @var array All meta values that are strings. */
private $metaString;
/** @var Account Source account of the journal */
private $sourceAccount;
/** @var Transaction Source transaction of the journal. */
private $sourceTransaction;
/** @var TransactionGroup The parent group. */
private $transactionGroup;
/** @var TransactionJournal The journal to update. */
private $transactionJournal;
/** @var Account If new account info is submitted, this array will hold the valid destination. */
private $validDestination;
/** @var Account If new account info is submitted, this array will hold the valid source. */
private $validSource;
/** /**
* JournalUpdateService constructor. * JournalUpdateService constructor.
@ -253,7 +238,7 @@ class JournalUpdateService
} }
$destInfo = [ $destInfo = [
'id' => (int) ($this->data['destination_id'] ?? null), 'id' => (int)($this->data['destination_id'] ?? null),
'name' => $this->data['destination_name'] ?? null, 'name' => $this->data['destination_name'] ?? null,
'iban' => $this->data['destination_iban'] ?? null, 'iban' => $this->data['destination_iban'] ?? null,
'number' => $this->data['destination_number'] ?? null, 'number' => $this->data['destination_number'] ?? null,
@ -287,7 +272,7 @@ class JournalUpdateService
} }
$sourceInfo = [ $sourceInfo = [
'id' => (int) ($this->data['source_id'] ?? null), 'id' => (int)($this->data['source_id'] ?? null),
'name' => $this->data['source_name'] ?? null, 'name' => $this->data['source_name'] ?? null,
'iban' => $this->data['source_iban'] ?? null, 'iban' => $this->data['source_iban'] ?? null,
'number' => $this->data['source_number'] ?? null, 'number' => $this->data['source_number'] ?? null,
@ -479,8 +464,8 @@ class JournalUpdateService
) )
&& TransactionType::WITHDRAWAL === $type && TransactionType::WITHDRAWAL === $type
) { ) {
$billId = (int) ($this->data['bill_id'] ?? 0); $billId = (int)($this->data['bill_id'] ?? 0);
$billName = (string) ($this->data['bill_name'] ?? ''); $billName = (string)($this->data['bill_name'] ?? '');
$bill = $this->billRepository->findBill($billId, $billName); $bill = $this->billRepository->findBill($billId, $billName);
$this->transactionJournal->bill_id = null === $bill ? null : $bill->id; $this->transactionJournal->bill_id = null === $bill ? null : $bill->id;
Log::debug('Updated bill ID'); Log::debug('Updated bill ID');
@ -551,15 +536,15 @@ class JournalUpdateService
*/ */
private function updateField(string $fieldName): void private function updateField(string $fieldName): void
{ {
if (array_key_exists($fieldName, $this->data) && '' !== (string) $this->data[$fieldName]) { if (array_key_exists($fieldName, $this->data) && '' !== (string)$this->data[$fieldName]) {
$value = $this->data[$fieldName]; $value = $this->data[$fieldName];
if ('date' === $fieldName) { if ('date' === $fieldName) {
if($value instanceof Carbon) { if ($value instanceof Carbon) {
// update timezone. // update timezone.
$value->setTimezone(config('app.timezone')); $value->setTimezone(config('app.timezone'));
} }
if(!($value instanceof Carbon)) { if (!($value instanceof Carbon)) {
$value = new Carbon($value); $value = new Carbon($value);
} }
// do some parsing. // do some parsing.
@ -667,7 +652,7 @@ class JournalUpdateService
foreach ($this->metaDate as $field) { foreach ($this->metaDate as $field) {
if ($this->hasFields([$field])) { if ($this->hasFields([$field])) {
try { try {
$value = '' === (string) $this->data[$field] ? null : new Carbon($this->data[$field]); $value = '' === (string)$this->data[$field] ? null : new Carbon($this->data[$field]);
} catch (Exception $e) { } catch (Exception $e) {
Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage())); Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage()));
@ -713,7 +698,7 @@ class JournalUpdateService
{ {
// update notes. // update notes.
if ($this->hasFields(['notes'])) { if ($this->hasFields(['notes'])) {
$notes = '' === (string) $this->data['notes'] ? null : $this->data['notes']; $notes = '' === (string)$this->data['notes'] ? null : $this->data['notes'];
$this->storeNotes($this->transactionJournal, $notes); $this->storeNotes($this->transactionJournal, $notes);
} }
} }

View File

@ -106,8 +106,6 @@ class OAuthKeys
} }
if (!self::keysInDatabase() && self::hasKeyFiles()) { if (!self::keysInDatabase() && self::hasKeyFiles()) {
self::storeKeysInDB(); self::storeKeysInDB();
return;
} }
} }

View File

@ -75,7 +75,7 @@ class AccountTransformer extends AbstractTransformer
[$currencyId, $currencyCode, $currencySymbol, $decimalPlaces] = $this->getCurrency($account); [$currencyId, $currencyCode, $currencySymbol, $decimalPlaces] = $this->getCurrency($account);
[$creditCardType, $monthlyPaymentDate] = $this->getCCInfo($account, $accountRole, $accountType); [$creditCardType, $monthlyPaymentDate] = $this->getCCInfo($account, $accountRole, $accountType);
[$openingBalance, $openingBalanceDate] = $this->getOpeningBalance($account, $accountType, $decimalPlaces); [$openingBalance, $openingBalanceDate] = $this->getOpeningBalance($account, $accountType);
[$interest, $interestPeriod] = $this->getInterest($account, $accountType); [$interest, $interestPeriod] = $this->getInterest($account, $accountType);
$openingBalance = number_format((float) $openingBalance, $decimalPlaces, '.', ''); $openingBalance = number_format((float) $openingBalance, $decimalPlaces, '.', '');
@ -235,7 +235,7 @@ class AccountTransformer extends AbstractTransformer
* *
* TODO refactor call to getOpeningBalanceAmount / Date because its extra queries. * TODO refactor call to getOpeningBalanceAmount / Date because its extra queries.
*/ */
private function getOpeningBalance(Account $account, string $accountType, int $decimalPlaces): array private function getOpeningBalance(Account $account, string $accountType): array
{ {
$openingBalance = null; $openingBalance = null;
$openingBalanceDate = null; $openingBalanceDate = null;

View File

@ -29,26 +29,19 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\User; use FireflyIII\User;
/** /**
* I have no idea what made me do this. I'll reverse it some day.
*
* Trait AccountValidatorProperties * Trait AccountValidatorProperties
*/ */
trait AccountValidatorProperties trait AccountValidatorProperties
{ {
/** @var bool */ public bool $createMode;
public $createMode; public string $destError;
/** @var string */ public Account $destination;
public $destError; public Account $source;
/** @var Account */ public string $sourceError;
public $destination; private AccountRepositoryInterface $accountRepository;
/** @var Account */ private array $combinations;
public $source; private string $transactionType;
/** @var string */ private User $user;
public $sourceError;
/** @var AccountRepositoryInterface */
private $accountRepository;
/** @var array */
private $combinations;
/** @var string */
private $transactionType;
/** @var User */
private $user;
} }

View File

@ -96,8 +96,6 @@ trait TransactionValidation
if (false === $validDestination) { if (false === $validDestination) {
$validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError); $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError);
$validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError); $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError);
return;
} }
} }
@ -257,8 +255,6 @@ trait TransactionValidation
$unique = array_unique($types); $unique = array_unique($types);
if (count($unique) > 1) { if (count($unique) > 1) {
$validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal')); $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal'));
return;
} }
} }

View File

@ -64,11 +64,11 @@ function colorizeData(data) {
var newData = {}; var newData = {};
newData.datasets = []; newData.datasets = [];
for (var i = 0; i < data.count; i++) { for (var loop = 0; loop < data.count; loop++) {
newData.labels = data.labels; newData.labels = data.labels;
var dataset = data.datasets[i]; var dataset = data.datasets[loop];
dataset.fill = false; dataset.fill = false;
dataset.backgroundColor = dataset.borderColor = fillColors[i]; dataset.backgroundColor = dataset.borderColor = fillColors[loop];
newData.datasets.push(dataset); newData.datasets.push(dataset);
} }
return newData; return newData;

View File

@ -22,7 +22,97 @@ var count = 0;
$(document).ready(function () { $(document).ready(function () {
updateListButtons(); updateListButtons();
addSort();
}); });
var fixHelper = function (e, tr) {
"use strict";
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function (index) {
// Set helper cell sizes to match the original sizes
$(this).width($originals.eq(index).width());
});
return $helper;
};
/**
*
*/
function addSort() {
if (typeof $(".table-sortable>tbody").sortable !== "undefined") {
$('.table-sortable>tbody').sortable(
{
items: "tr:not(.unsortable)",
handle: '.object-handle',
stop: sortStop,
start: function (event, ui) {
// Build a placeholder cell that spans all the cells in the row
var cellCount = 0;
$('td, th', ui.helper).each(function () {
// For each TD or TH try and get it's colspan attribute, and add that or 1 to the total
var colspan = 1;
var colspanAttr = $(this).attr('colspan');
if (colspanAttr > 1) {
colspan = colspanAttr;
}
cellCount += colspan;
});
// Add the placeholder UI - note that this is the item's content, so TD rather than TR
ui.placeholder.html('<td colspan="' + cellCount + '">&nbsp;</td>');
}
}
);
}
}
/**
*
* @param event
* @param ui
* @returns {boolean|undefined}
*/
function sortStop(event, ui) {
"use strict";
var current = $(ui.item);
var thisDate = current.data('date');
var originalBG = current.css('backgroundColor');
if (current.prev().data('date') !== thisDate && current.next().data('date') !== thisDate) {
// animate something with color:
current.animate({backgroundColor: "#d9534f"}, 200, function () {
$(this).animate({backgroundColor: originalBG}, 200);
return undefined;
});
return false;
}
//return false;
// do update
var list = $('tr[data-date="' + thisDate + '"]');
var submit = [];
$.each(list, function (i, v) {
var row = $(v);
var id = row.data('id');
submit.push(id);
});
// do extra animation when done?
$.post('transactions/reorder', {items: submit, date: thisDate, _token: token});
current.animate({backgroundColor: "#5cb85c"}, 200, function () {
$(this).animate({backgroundColor: originalBG}, 200);
return undefined;
});
return undefined;
}
/**
*
*/
function updateListButtons() { function updateListButtons() {
// top button to select all / deselect all: // top button to select all / deselect all:
$('input[name="select-all"]').change(function () { $('input[name="select-all"]').change(function () {
@ -91,8 +181,6 @@ function getCheckboxes() {
} }
function countChecked() { function countChecked() {
count = $('.mass-select:checked').length; count = $('.mass-select:checked').length;
} }

View File

@ -59,7 +59,7 @@ function testRuleTriggers(e) {
var modal = $("#testTriggerModal"); var modal = $("#testTriggerModal");
// respond to modal: // respond to modal:
modal.on('hide.bs.modal', function (e) { modal.on('hide.bs.modal', function () {
disableRuleSpinners(); disableRuleSpinners();
}); });
@ -98,28 +98,28 @@ function sortStop(event, ui) {
// resort / move rule // resort / move rule
$.each($('.group-rules'), function(i,v) { $.each($('.group-rules'), function(i,v) {
$.each($('tr.single-rule', $(v)), function (i, v) { $.each($('tr.single-rule', $(v)), function (counter, value) {
var holder = $(v); var holder = $(value);
var position = parseInt(holder.data('position')); var position = parseInt(holder.data('position'));
var ruleGroupId = holder.data('group-id'); var ruleGroupId = holder.data('group-id');
var ruleId = holder.data('id'); var ruleId = holder.data('id');
var originalOrder = parseInt(holder.data('order')); var originalOrder = parseInt(holder.data('order'));
var newOrder; var newOrder;
if (position === i) { if (position === counter) {
// not changed, position is what it should be. // not changed, position is what it should be.
return; return;
} }
if (position < i) { if (position < counter) {
// position is less. // position is less.
console.log('Rule #' + ruleId + ' moved down from position ' + originalOrder + ' to ' + (i + 1)); console.log('Rule #' + ruleId + ' moved down from position ' + originalOrder + ' to ' + (counter + 1));
} }
if (position > i) { if (position > counter) {
console.log('Rule #' + ruleId + ' moved up from position ' + originalOrder + ' to ' + (i + 1)); console.log('Rule #' + ruleId + ' moved up from position ' + originalOrder + ' to ' + (counter + 1));
} }
// update position: // update position:
holder.data('position', i); holder.data('position', counter);
newOrder = i+1; newOrder = counter + 1;
$.post('rules/move-rule/' + ruleId + '/' + ruleGroupId, {order: newOrder, _token: token}); $.post('rules/move-rule/' + ruleId + '/' + ruleGroupId, {order: newOrder, _token: token});
}); });

View File

@ -806,7 +806,7 @@ export default {
// console.log('Uploading attachment #' + key); // console.log('Uploading attachment #' + key);
const uploadUri = './api/v1/attachments/' + response.data.data.id + '/upload'; const uploadUri = './api/v1/attachments/' + response.data.data.id + '/upload';
axios.post(uploadUri, fileData[key].content) axios.post(uploadUri, fileData[key].content)
.then(response => { .then(secondResponse => {
// console.log('Uploaded attachment #' + key); // console.log('Uploaded attachment #' + key);
uploads++; uploads++;
if (uploads === count) { if (uploads === count) {

View File

@ -171,13 +171,13 @@
{% block scripts %} {% block scripts %}
<script type="text/javascript" nonce="{{ JS_NONCE }}"> <script type="text/javascript" nonce="{{ JS_NONCE }}">
var doPlaceMarker = false;
// location stuff // location stuff
{% if location %} {% if location %}
var latitude = {{ location.latitude|default("52.3167") }}; var latitude = {{ location.latitude|default("52.3167") }};
var longitude = {{ location.longitude|default("5.5500") }}; var longitude = {{ location.longitude|default("5.5500") }};
var zoomLevel = {{ location.zoom_level|default("6") }}; var zoomLevel = {{ location.zoom_level|default("6") }};
var doPlaceMarker = true; doPlaceMarker = true;
// token for Mapbox: // token for Mapbox:
var mapboxToken = "{{ config('firefly.mapbox_api_key') }}"; var mapboxToken = "{{ config('firefly.mapbox_api_key') }}";
{% endif %} {% endif %}

View File

@ -1,8 +1,4 @@
<!-- <table class="table table-condensed table-hover table-responsive table-sortable">
TODO: reconcile
TODO: hide and show columns
-->
<table class="table table-condensed table-hover table-responsive">
<thead> <thead>
<tr> <tr>
{% if showCategory or showBudget %} {% if showCategory or showBudget %}
@ -53,7 +49,7 @@ TODO: hide and show columns
<tbody> <tbody>
{% for group in groups %} {% for group in groups %}
{% if group.count > 1 %} {% if group.count > 1 %}
<tr style="border-top:1px #aaa solid;"> <tr style="border-top:1px #aaa solid;" class="unsortable">
<td colspan="2" style="border-top:1px #aaa solid;"> <td colspan="2" style="border-top:1px #aaa solid;">
<small><strong> <small><strong>
<a href="{{ route('transactions.show', [group.id]) }}" <a href="{{ route('transactions.show', [group.id]) }}"
@ -102,25 +98,25 @@ TODO: hide and show columns
{% if group.transactions|length == loop.index and group.count > 1 %} {% if group.transactions|length == loop.index and group.count > 1 %}
{% set style="border-bottom:1px #aaa solid;" %} {% set style="border-bottom:1px #aaa solid;" %}
{% endif %} {% endif %}
<tr data-date="{{ transaction.date.format('Y-m-d') }}"> <tr data-date="{{ transaction.date.format('Y-m-d') }}" data-count="{{ group.count }}" data-id="{{ group.id }}">
<td style=" {{ style|raw }}" class="hidden-xs"> <td style=" {{ style|raw }}" class="hidden-xs">
{% if transaction.transaction_type_type == 'Withdrawal' %} {% if transaction.transaction_type_type == 'Withdrawal' %}
<i class="fa fa-long-arrow-left fa-fw" title="{{ trans('firefly.Withdrawal') }}"></i> <i class="object-handle fa fa-long-arrow-left fa-fw" title="{{ trans('firefly.Withdrawal') }}"></i>
{% endif %} {% endif %}
{% if transaction.transaction_type_type == 'Deposit' %} {% if transaction.transaction_type_type == 'Deposit' %}
<i class="fa fa-long-arrow-right fa-fw" title="{{ trans('firefly.Deposit') }}"></i> <i class="object-handle fa fa-long-arrow-right fa-fw" title="{{ trans('firefly.Deposit') }}"></i>
{% endif %} {% endif %}
{% if transaction.transaction_type_type == 'Transfer' %} {% if transaction.transaction_type_type == 'Transfer' %}
<i class="fa fa-exchange fa-fw" title="{{ trans('firefly.Transfer') }}"></i> <i class="object-handle fa fa-exchange fa-fw" title="{{ trans('firefly.Transfer') }}"></i>
{% endif %} {% endif %}
{% if transaction.transaction_type_type == 'Reconciliation' %} {% if transaction.transaction_type_type == 'Reconciliation' %}
<i class="fa-fw fa fa-calculator" title="{{ trans('firefly.reconciliation_transaction') }}"></i> <i class="object-handle fa-fw fa fa-calculator" title="{{ trans('firefly.reconciliation_transaction') }}"></i>
{% endif %} {% endif %}
{% if transaction.transaction_type_type == 'Opening balance' %} {% if transaction.transaction_type_type == 'Opening balance' %}
<i class="fa-fw fa fa-star-o" title="{{ trans('firefly.Opening balance') }}"></i> <i class="object-handle fa-fw fa fa-star-o" title="{{ trans('firefly.Opening balance') }}"></i>
{% endif %} {% endif %}
</td> </td>