Catch query things.

This commit is contained in:
James Cole 2023-12-29 09:01:42 +01:00
parent e4d91aa337
commit 507e0fb54c
No known key found for this signature in database
GPG Key ID: B49A324B7EAD6D80
3 changed files with 180 additions and 162 deletions

View File

@ -62,7 +62,7 @@ class UpdateController extends Controller
if(false === config('firefly.allow_webhooks')) { if(false === config('firefly.allow_webhooks')) {
throw new NotFoundHttpException('Webhooks are not enabled.'); throw new NotFoundHttpException('Webhooks are not enabled.');
} }
$data = $request->getData(); $data = $request->getData();
$webhook = $this->repository->update($webhook, $data); $webhook = $this->repository->update($webhook, $data);
$manager = $this->getManager(); $manager = $this->getManager();

View File

@ -39,6 +39,9 @@ class ExchangeRateConverter
// use ConvertsExchangeRates; // use ConvertsExchangeRates;
private int $queryCount = 0; private int $queryCount = 0;
private array $prepared = []; private array $prepared = [];
private array $fallback = [];
private bool $isPrepared = false;
private bool $noPreparedRates = false;
/** /**
* @throws FireflyException * @throws FireflyException
@ -50,31 +53,31 @@ class ExchangeRateConverter
return bcmul($amount, $rate); return bcmul($amount, $rate);
} }
/**
* @throws FireflyException
*/
public function prepare(TransactionCurrency $from, TransactionCurrency $to, Carbon $start, Carbon $end): void public function prepare(TransactionCurrency $from, TransactionCurrency $to, Carbon $start, Carbon $end): void
{ {
$this->isPrepared = true;
$start->startOfDay(); $start->startOfDay();
$end->endOfDay(); $end->endOfDay();
Log::debug(sprintf('Preparing for %s to %s between %s and %s', $from->code, $to->code, $start->format('Y-m-d'), $end->format('Y-m-d'))); Log::debug(sprintf('Preparing for %s to %s between %s and %s', $from->code, $to->code, $start->format('Y-m-d'), $end->format('Y-m-d')));
$set = auth()->user() $set = auth()->user()
->currencyExchangeRates() ->currencyExchangeRates()
->where('from_currency_id', $from->id) ->where('from_currency_id', $from->id)
->where('to_currency_id', $to->id) ->where('to_currency_id', $to->id)
->where('date', '<=', $end->format('Y-m-d')) ->where('date', '<=', $end->format('Y-m-d'))
->where('date', '>=', $start->format('Y-m-d')) ->where('date', '>=', $start->format('Y-m-d'))
->orderBy('date', 'DESC')->get() ->orderBy('date', 'DESC')->get();
;
++$this->queryCount; ++$this->queryCount;
if (0 === $set->count()) { if (0 === $set->count()) {
Log::debug('No prepared rates found in this period.'); Log::debug('No prepared rates found in this period, use the fallback');
$this->fallback($from, $to, $start);
$this->noPreparedRates = true;
return; return;
} }
$fallback = $this->getRate($from, $to, $start);
/* // so there is a fallback just in case. Now loop the set of rates we DO have.
* Je moet een fallback rate hebben van voor de periode zodat je die altijd kan gebruiken.
* Dus de laatste met de meest recente datum voor je periode.
* Dan moet je gaan loopen per dag, en als er iets in $temp zit toevallig gebruik je die.
*/
$temp = []; $temp = [];
$count = 0; $count = 0;
foreach ($set as $rate) { foreach ($set as $rate) {
@ -91,7 +94,7 @@ class ExchangeRateConverter
while ($currentStart->lte($end)) { while ($currentStart->lte($end)) {
$currentDate = $currentStart->format('Y-m-d'); $currentDate = $currentStart->format('Y-m-d');
$this->prepared[$currentDate] ??= []; $this->prepared[$currentDate] ??= [];
$fallback = $temp[$currentDate][$from->id][$to->id] ?? $fallback; $fallback = $temp[$currentDate][$from->id][$to->id] ?? $this->fallback[$from->id][$to->id] ?? '0';
if (0 === count($this->prepared[$currentDate]) && 0 !== bccomp('0', $fallback)) { if (0 === count($this->prepared[$currentDate]) && 0 !== bccomp('0', $fallback)) {
// fill from temp or fallback or from temp (see before) // fill from temp or fallback or from temp (see before)
$this->prepared[$currentDate][$from->id][$to->id] = $fallback; $this->prepared[$currentDate][$from->id][$to->id] = $fallback;
@ -120,6 +123,10 @@ class ExchangeRateConverter
*/ */
private function getRate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): string private function getRate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): string
{ {
if($this->isPrepared && !$this->noPreparedRates) {
Log::debug(sprintf('Return fallback rate from #%d to #%d on %s.', $from, $to, $date));
return $this->fallback[$from->id][$to->id] ?? '0';
}
// first attempt: // first attempt:
$rate = $this->getFromDB($from->id, $to->id, $date->format('Y-m-d')); $rate = $this->getFromDB($from->id, $to->id, $date->format('Y-m-d'));
if (null !== $rate) { if (null !== $rate) {
@ -172,27 +179,28 @@ class ExchangeRateConverter
return $rate; return $rate;
} }
app('log')->debug(sprintf('Going to get rate #%d->#%d (%s) from DB.', $from, $to, $date));
/** @var null|CurrencyExchangeRate $result */ /** @var null|CurrencyExchangeRate $result */
$result = auth()->user() $result = auth()->user()
->currencyExchangeRates() ->currencyExchangeRates()
->where('from_currency_id', $from) ->where('from_currency_id', $from)
->where('to_currency_id', $to) ->where('to_currency_id', $to)
->where('date', '<=', $date) ->where('date', '<=', $date)
->orderBy('date', 'DESC') ->orderBy('date', 'DESC')
->first() ->first();
;
++$this->queryCount; ++$this->queryCount;
$rate = (string) $result?->rate; $rate = (string) $result?->rate;
if ('' === $rate) { if ('' === $rate) {
app('log')->debug(sprintf('Found no rate for #%d->#%d (%s) in the DB.', $from, $to, $date));
return null; return null;
} }
if (0 === bccomp('0', $rate)) { if (0 === bccomp('0', $rate)) {
app('log')->debug(sprintf('Found rate for #%d->#%d (%s) in the DB, but it\'s zero.', $from, $to, $date));
return null; return null;
} }
app('log')->debug(sprintf('Found rate for #%d->#%d (%s) in the DB: %s.', $from, $to, $date, $rate));
$cache->store($rate); $cache->store($rate);
// if the rate has not been cached during this particular run, save it // if the rate has not been cached during this particular run, save it
@ -263,4 +271,27 @@ class ExchangeRateConverter
return $euro->id; return $euro->id;
} }
/**
* If there are no exchange rate in the "prepare" array, future searches for any exchange rate
* will result in nothing: otherwise the preparation had been unnecessary. So, to fix this Firefly III
* will set two fallback currency exchange rates, A > B and B > A using the regular getCurrencyRate method.
*
* This method in turn will fall back on the default exchange rate (if present) or on "1" if necessary.
*
* @param TransactionCurrency $from
* @param TransactionCurrency $to
* @param Carbon $date
*
* @return void
* @throws FireflyException
*/
private function fallback(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): void
{
$fallback = $this->getRate($from, $to, $date);
$this->fallback[$from->id][$to->id] = $fallback;
$this->fallback[$to->id][$from->id] = bcdiv('1', $fallback);
Log::debug(sprintf('Fallback rate %s > %s = %s', $from->code, $to->code, $fallback));
Log::debug(sprintf('Fallback rate %s > %s = %s', $to->code, $from->code, bcdiv('1', $fallback)));
}
} }

View File

@ -46,21 +46,19 @@ class Steam
$currencyId = (int) $repository->getMetaValue($account, 'currency_id'); $currencyId = (int) $repository->getMetaValue($account, 'currency_id');
$transactions = $account->transactions() $transactions = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', $currencyId) ->where('transactions.transaction_currency_id', $currencyId)
->get(['transactions.amount'])->toArray() ->get(['transactions.amount'])->toArray();
;
$nativeBalance = $this->sumTransactions($transactions, 'amount'); $nativeBalance = $this->sumTransactions($transactions, 'amount');
// get all balances in foreign currency: // get all balances in foreign currency:
$transactions = $account->transactions() $transactions = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.foreign_currency_id', $currencyId) ->where('transactions.foreign_currency_id', $currencyId)
->where('transactions.transaction_currency_id', '!=', $currencyId) ->where('transactions.transaction_currency_id', '!=', $currencyId)
->get(['transactions.foreign_amount'])->toArray() ->get(['transactions.foreign_amount'])->toArray();
;
$foreignBalance = $this->sumTransactions($transactions, 'foreign_amount'); $foreignBalance = $this->sumTransactions($transactions, 'foreign_amount');
@ -118,24 +116,23 @@ class Steam
// query! // query!
$set = $account->transactions() $set = $account->transactions()
->leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00')) ->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00'))
->where('transaction_journals.date', '<=', $end->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $end->format('Y-m-d 23:59:59'))
->groupBy('transaction_journals.date') ->groupBy('transaction_journals.date')
->groupBy('transactions.transaction_currency_id') ->groupBy('transactions.transaction_currency_id')
->groupBy('transactions.foreign_currency_id') ->groupBy('transactions.foreign_currency_id')
->orderBy('transaction_journals.date', 'ASC') ->orderBy('transaction_journals.date', 'ASC')
->whereNull('transaction_journals.deleted_at') ->whereNull('transaction_journals.deleted_at')
->get( ->get(
[ // @phpstan-ignore-line [ // @phpstan-ignore-line
'transaction_journals.date', 'transaction_journals.date',
'transactions.transaction_currency_id', 'transactions.transaction_currency_id',
\DB::raw('SUM(transactions.amount) AS modified'), \DB::raw('SUM(transactions.amount) AS modified'),
'transactions.foreign_currency_id', 'transactions.foreign_currency_id',
\DB::raw('SUM(transactions.foreign_amount) AS modified_foreign'), \DB::raw('SUM(transactions.foreign_amount) AS modified_foreign'),
] ]
) );
;
$currentBalance = $startBalance; $currentBalance = $startBalance;
@ -189,20 +186,18 @@ class Steam
} }
// first part: get all balances in own currency: // first part: get all balances in own currency:
$transactions = $account->transactions() $transactions = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', $currency->id) ->where('transactions.transaction_currency_id', $currency->id)
->get(['transactions.amount'])->toArray() ->get(['transactions.amount'])->toArray();
;
$nativeBalance = $this->sumTransactions($transactions, 'amount'); $nativeBalance = $this->sumTransactions($transactions, 'amount');
// get all balances in foreign currency: // get all balances in foreign currency:
$transactions = $account->transactions() $transactions = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.foreign_currency_id', $currency->id) ->where('transactions.foreign_currency_id', $currency->id)
->where('transactions.transaction_currency_id', '!=', $currency->id) ->where('transactions.transaction_currency_id', '!=', $currency->id)
->get(['transactions.foreign_amount'])->toArray() ->get(['transactions.foreign_amount'])->toArray();
;
$foreignBalance = $this->sumTransactions($transactions, 'foreign_amount'); $foreignBalance = $this->sumTransactions($transactions, 'foreign_amount');
$balance = bcadd($nativeBalance, $foreignBalance); $balance = bcadd($nativeBalance, $foreignBalance);
$virtual = null === $account->virtual_balance ? '0' : $account->virtual_balance; $virtual = null === $account->virtual_balance ? '0' : $account->virtual_balance;
@ -229,7 +224,7 @@ class Steam
if ($cache->has()) { if ($cache->has()) {
return $cache->get(); return $cache->get();
} }
app('log')->debug(sprintf('balanceInRangeConverted for account #%d to %s', $account->id, $native->code)); Log::debug(sprintf('balanceInRangeConverted for account #%d to %s', $account->id, $native->code));
$start->subDay(); $start->subDay();
$end->addDay(); $end->addDay();
$balances = []; $balances = [];
@ -238,7 +233,7 @@ class Steam
$startBalance = $this->balanceConverted($account, $start, $native); // already converted to native amount $startBalance = $this->balanceConverted($account, $start, $native); // already converted to native amount
$balances[$formatted] = $startBalance; $balances[$formatted] = $startBalance;
app('log')->debug(sprintf('Start balance on %s is %s', $formatted, $startBalance)); Log::debug(sprintf('Start balance on %s is %s', $formatted, $startBalance));
Log::info(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); Log::info(sprintf('Created new ExchangeRateConverter in %s', __METHOD__));
$converter = new ExchangeRateConverter(); $converter = new ExchangeRateConverter();
@ -247,21 +242,20 @@ class Steam
// grab all transactions between start and end: // grab all transactions between start and end:
$set = $account->transactions() $set = $account->transactions()
->leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00')) ->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00'))
->where('transaction_journals.date', '<=', $end->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $end->format('Y-m-d 23:59:59'))
->orderBy('transaction_journals.date', 'ASC') ->orderBy('transaction_journals.date', 'ASC')
->whereNull('transaction_journals.deleted_at') ->whereNull('transaction_journals.deleted_at')
->get( ->get(
[ [
'transaction_journals.date', 'transaction_journals.date',
'transactions.transaction_currency_id', 'transactions.transaction_currency_id',
'transactions.amount', 'transactions.amount',
'transactions.foreign_currency_id', 'transactions.foreign_currency_id',
'transactions.foreign_amount', 'transactions.foreign_amount',
] ]
)->toArray() )->toArray();
;
// loop the set and convert if necessary: // loop the set and convert if necessary:
$currentBalance = $startBalance; $currentBalance = $startBalance;
@ -278,7 +272,7 @@ class Steam
// change the current balance, set it to today, continue the loop. // change the current balance, set it to today, continue the loop.
$currentBalance = bcadd($currentBalance, $transaction['amount']); $currentBalance = bcadd($currentBalance, $transaction['amount']);
$balances[$format] = $currentBalance; $balances[$format] = $currentBalance;
app('log')->debug(sprintf('%s: transaction in %s, new balance is %s.', $format, $native->code, $currentBalance)); Log::debug(sprintf('%s: transaction in %s, new balance is %s.', $format, $native->code, $currentBalance));
continue; continue;
} }
@ -286,7 +280,7 @@ class Steam
if ((int) $transaction['foreign_currency_id'] === $native->id) { if ((int) $transaction['foreign_currency_id'] === $native->id) {
$currentBalance = bcadd($currentBalance, $transaction['foreign_amount']); $currentBalance = bcadd($currentBalance, $transaction['foreign_amount']);
$balances[$format] = $currentBalance; $balances[$format] = $currentBalance;
app('log')->debug(sprintf('%s: transaction in %s (foreign), new balance is %s.', $format, $native->code, $currentBalance)); Log::debug(sprintf('%s: transaction in %s (foreign), new balance is %s.', $format, $native->code, $currentBalance));
continue; continue;
} }
@ -300,16 +294,16 @@ class Steam
$currentBalance = bcadd($currentBalance, $convertedAmount); $currentBalance = bcadd($currentBalance, $convertedAmount);
$balances[$format] = $currentBalance; $balances[$format] = $currentBalance;
app('log')->debug(sprintf( Log::debug(sprintf(
'%s: transaction in %s(!). Conversion rate is %s. %s %s = %s %s', '%s: transaction in %s(!). Conversion rate is %s. %s %s = %s %s',
$format, $format,
$currency->code, $currency->code,
$rate, $rate,
$currency->code, $currency->code,
$transaction['amount'], $transaction['amount'],
$native->code, $native->code,
$convertedAmount $convertedAmount
)); ));
} }
$cache->store($balances); $cache->store($balances);
@ -339,6 +333,7 @@ class Steam
*/ */
public function balanceConverted(Account $account, Carbon $date, TransactionCurrency $native): string public function balanceConverted(Account $account, Carbon $date, TransactionCurrency $native): string
{ {
Log::debug(sprintf('Now in balanceConverted (%s) for account #%d, converting to %s', $date->format('Y-m-d'), $account->id, $native->code));
$cache = new CacheProperties(); $cache = new CacheProperties();
$cache->addProperty($account->id); $cache->addProperty($account->id);
$cache->addProperty('balance'); $cache->addProperty('balance');
@ -347,7 +342,7 @@ class Steam
if ($cache->has()) { if ($cache->has()) {
Log::debug('Cached!'); Log::debug('Cached!');
return $cache->get(); //return $cache->get();
} }
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
@ -355,69 +350,62 @@ class Steam
$currency = $repository->getAccountCurrency($account); $currency = $repository->getAccountCurrency($account);
$currency = null === $currency ? app('amount')->getDefaultCurrencyByUserGroup($account->user->userGroup) : $currency; $currency = null === $currency ? app('amount')->getDefaultCurrencyByUserGroup($account->user->userGroup) : $currency;
if ($native->id === $currency->id) { if ($native->id === $currency->id) {
// Log::debug('No conversion necessary!'); Log::debug('No conversion necessary!');
return $this->balance($account, $date); return $this->balance($account, $date);
} }
app('log')->info(sprintf('Now in balanceConverted (%s) for account #%d, converting to %s', $date->format('Y-m-d'), $account->id, $native->code));
$new = []; $new = [];
$existing = []; $existing = [];
$new[] = $account->transactions() // 1 $new[] = $account->transactions() // 1
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', $currency->id) ->where('transactions.transaction_currency_id', $currency->id)
->whereNull('transactions.foreign_currency_id') ->whereNull('transactions.foreign_currency_id')
->get(['transaction_journals.date', 'transactions.amount'])->toArray() ->get(['transaction_journals.date', 'transactions.amount'])->toArray();
; Log::debug(sprintf('%d transaction(s) in set #1', count($new[0])));
app('log')->debug(sprintf('%d transaction(s) in set #1', count($new[0])));
$existing[] = $account->transactions() // 2 $existing[] = $account->transactions() // 2
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', $native->id) ->where('transactions.transaction_currency_id', $native->id)
->whereNull('transactions.foreign_currency_id') ->whereNull('transactions.foreign_currency_id')
->get(['transactions.amount'])->toArray() ->get(['transactions.amount'])->toArray();
; Log::debug(sprintf('%d transaction(s) in set #2', count($existing[0])));
app('log')->debug(sprintf('%d transaction(s) in set #2', count($existing[0])));
$new[] = $account->transactions() // 3 $new[] = $account->transactions() // 3
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', '!=', $currency->id) ->where('transactions.transaction_currency_id', '!=', $currency->id)
->where('transactions.transaction_currency_id', '!=', $native->id) ->where('transactions.transaction_currency_id', '!=', $native->id)
->whereNull('transactions.foreign_currency_id') ->whereNull('transactions.foreign_currency_id')
->get(['transaction_journals.date', 'transactions.amount'])->toArray() ->get(['transaction_journals.date', 'transactions.amount'])->toArray();
; Log::debug(sprintf('%d transactions in set #3', count($new[1])));
app('log')->debug(sprintf('%d transactions in set #3', count($new[1])));
$existing[] = $account->transactions() // 4 $existing[] = $account->transactions() // 4
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.foreign_currency_id', $native->id) ->where('transactions.foreign_currency_id', $native->id)
->whereNotNull('transactions.foreign_amount') ->whereNotNull('transactions.foreign_amount')
->get(['transactions.foreign_amount'])->toArray() ->get(['transactions.foreign_amount'])->toArray();
; Log::debug(sprintf('%d transactions in set #4', count($existing[1])));
app('log')->debug(sprintf('%d transactions in set #4', count($existing[1])));
$new[] = $account->transactions()// 5 $new[] = $account->transactions()// 5
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', $currency->id) ->where('transactions.transaction_currency_id', $currency->id)
->where('transactions.foreign_currency_id', '!=', $native->id) ->where('transactions.foreign_currency_id', '!=', $native->id)
->whereNotNull('transactions.foreign_amount') ->whereNotNull('transactions.foreign_amount')
->get(['transaction_journals.date', 'transactions.amount'])->toArray() ->get(['transaction_journals.date', 'transactions.amount'])->toArray();
; Log::debug(sprintf('%d transactions in set #5', count($new[2])));
app('log')->debug(sprintf('%d transactions in set #5', count($new[2])));
$new[] = $account->transactions()// 6 $new[] = $account->transactions()// 6
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->where('transactions.transaction_currency_id', '!=', $currency->id) ->where('transactions.transaction_currency_id', '!=', $currency->id)
->where('transactions.foreign_currency_id', '!=', $native->id) ->where('transactions.foreign_currency_id', '!=', $native->id)
->whereNotNull('transactions.foreign_amount') ->whereNotNull('transactions.foreign_amount')
->get(['transaction_journals.date', 'transactions.amount'])->toArray() ->get(['transaction_journals.date', 'transactions.amount'])->toArray();
; Log::debug(sprintf('%d transactions in set #6', count($new[3])));
app('log')->debug(sprintf('%d transactions in set #6', count($new[3])));
// process both sets of transactions. Of course, no need to convert set "existing". // process both sets of transactions. Of course, no need to convert set "existing".
$balance = $this->sumTransactions($existing[0], 'amount'); $balance = $this->sumTransactions($existing[0], 'amount');
$balance = bcadd($balance, $this->sumTransactions($existing[1], 'foreign_amount')); $balance = bcadd($balance, $this->sumTransactions($existing[1], 'foreign_amount'));
// app('log')->debug(sprintf('Balance from set #2 and #4 is %f', $balance)); Log::debug(sprintf('Balance from set #2 and #4 is %f', $balance));
// need to convert the others. All sets use the "amount" value as their base (that's easy) // need to convert the others. All sets use the "amount" value as their base (that's easy)
// but we need to convert each transaction separately because the date difference may // but we need to convert each transaction separately because the date difference may
@ -519,9 +507,9 @@ class Steam
$default = app('amount')->getDefaultCurrencyByUserGroup($account->user->userGroup); $default = app('amount')->getDefaultCurrencyByUserGroup($account->user->userGroup);
$result[$account->id] $result[$account->id]
= [ = [
'balance' => $this->balance($account, $date), 'balance' => $this->balance($account, $date),
'native_balance' => $this->balanceConverted($account, $date, $default), 'native_balance' => $this->balanceConverted($account, $date, $default),
]; ];
} }
$cache->store($result); $cache->store($result);
@ -568,10 +556,9 @@ class Steam
return $cache->get(); return $cache->get();
} }
$query = $account->transactions() $query = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59'))
->groupBy('transactions.transaction_currency_id') ->groupBy('transactions.transaction_currency_id');
;
$balances = $query->get(['transactions.transaction_currency_id', \DB::raw('SUM(transactions.amount) as sum_for_currency')]); // @phpstan-ignore-line $balances = $query->get(['transactions.transaction_currency_id', \DB::raw('SUM(transactions.amount) as sum_for_currency')]); // @phpstan-ignore-line
$return = []; $return = [];
@ -600,13 +587,13 @@ class Steam
$number = sprintf('%.12f', $number); $number = sprintf('%.12f', $number);
} }
// app('log')->debug(sprintf('Trying bcround("%s",%d)', $number, $precision)); // Log::debug(sprintf('Trying bcround("%s",%d)', $number, $precision));
if (str_contains($number, '.')) { if (str_contains($number, '.')) {
if ('-' !== $number[0]) { if ('-' !== $number[0]) {
return bcadd($number, '0.'.str_repeat('0', $precision).'5', $precision); return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision);
} }
return bcsub($number, '0.'.str_repeat('0', $precision).'5', $precision); return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision);
} }
return $number; return $number;
@ -688,9 +675,9 @@ class Steam
$list = []; $list = [];
$set = auth()->user()->transactions() $set = auth()->user()->transactions()
->whereIn('transactions.account_id', $accounts) ->whereIn('transactions.account_id', $accounts)
->groupBy(['transactions.account_id', 'transaction_journals.user_id']) ->groupBy(['transactions.account_id', 'transaction_journals.user_id'])
->get(['transactions.account_id', \DB::raw('MAX(transaction_journals.date) AS max_date')]) // @phpstan-ignore-line ->get(['transactions.account_id', \DB::raw('MAX(transaction_journals.date) AS max_date')]) // @phpstan-ignore-line
; ;
/** @var Transaction $entry */ /** @var Transaction $entry */
@ -760,7 +747,7 @@ class Steam
*/ */
public function getSafePreviousUrl(): string public function getSafePreviousUrl(): string
{ {
// app('log')->debug(sprintf('getSafePreviousUrl: "%s"', session()->previousUrl())); // Log::debug(sprintf('getSafePreviousUrl: "%s"', session()->previousUrl()));
return session()->previousUrl() ?? route('index'); return session()->previousUrl() ?? route('index');
} }
@ -769,7 +756,7 @@ class Steam
*/ */
public function getSafeUrl(string $unknownUrl, string $safeUrl): string public function getSafeUrl(string $unknownUrl, string $safeUrl): string
{ {
// app('log')->debug(sprintf('getSafeUrl(%s, %s)', $unknownUrl, $safeUrl)); // Log::debug(sprintf('getSafeUrl(%s, %s)', $unknownUrl, $safeUrl));
$returnUrl = $safeUrl; $returnUrl = $safeUrl;
$unknownHost = parse_url($unknownUrl, PHP_URL_HOST); $unknownHost = parse_url($unknownUrl, PHP_URL_HOST);
$safeHost = parse_url($safeUrl, PHP_URL_HOST); $safeHost = parse_url($safeUrl, PHP_URL_HOST);
@ -878,8 +865,8 @@ class Steam
$amount = bcmul($amount, '-1'); $amount = bcmul($amount, '-1');
} }
} catch (\ValueError $e) { } catch (\ValueError $e) {
app('log')->error(sprintf('ValueError in Steam::positive("%s"): %s', $amount, $e->getMessage())); Log::error(sprintf('ValueError in Steam::positive("%s"): %s', $amount, $e->getMessage()));
app('log')->error($e->getTraceAsString()); Log::error($e->getTraceAsString());
return '0'; return '0';
} }