Replace native with primary where possible

This commit is contained in:
Sander Dorigo
2025-08-01 12:31:01 +02:00
parent 65dcad6898
commit 6278662014
59 changed files with 430 additions and 430 deletions

View File

@@ -103,7 +103,7 @@ class Amount
{
$convertToPrimary = $this->convertToPrimary();
$currency = $this->getPrimaryCurrency();
$field = $convertToPrimary && $currency->id !== $journal['currency_id'] ? 'native_amount' : 'amount';
$field = $convertToPrimary && $currency->id !== $journal['currency_id'] ? 'pc_amount' : 'amount';
$amount = $journal[$field] ?? '0';
// Log::debug(sprintf('Field is %s, amount is %s', $field, $amount));
// fallback, the transaction has a foreign amount in $currency.
@@ -118,10 +118,10 @@ class Amount
public function convertToPrimary(?User $user = null): bool
{
if (!$user instanceof User) {
return true === Preferences::get('convert_to_native', false)->data && true === config('cer.enabled');
return true === Preferences::get('convert_to_primary', false)->data && true === config('cer.enabled');
}
return true === Preferences::getForUser($user, 'convert_to_native', false)->data && true === config('cer.enabled');
return true === Preferences::getForUser($user, 'convert_to_primary', false)->data && true === config('cer.enabled');
}
public function getPrimaryCurrency(): TransactionCurrency
@@ -171,7 +171,7 @@ class Amount
{
$convertToPrimary = $this->convertToPrimary();
$currency = $this->getPrimaryCurrency();
$field = $convertToPrimary && $currency->id !== $journal->transaction_currency_id ? 'native_amount' : 'amount';
$field = $convertToPrimary && $currency->id !== $journal->transaction_currency_id ? 'pc_amount' : 'amount';
/** @var null|Transaction $sourceTransaction */
$sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();

View File

@@ -39,7 +39,7 @@ use Illuminate\Support\Facades\Log;
*/
class FrontpageChartGenerator
{
public bool $convertToNative = false;
public bool $convertToPrimary = false;
public TransactionCurrency $default;
protected OperationsRepositoryInterface $opsRepository;
private readonly BudgetLimitRepositoryInterface $blRepository;
@@ -149,12 +149,12 @@ class FrontpageChartGenerator
*/
private function processLimit(array $data, Budget $budget, BudgetLimit $limit): array
{
$useNative = $this->convertToNative && $this->default->id !== $limit->transaction_currency_id;
$usePrimary = $this->convertToPrimary && $this->default->id !== $limit->transaction_currency_id;
$currency = $limit->transactionCurrency;
if ($useNative) {
Log::debug(sprintf('Processing limit #%d with (native) %s %s', $limit->id, $this->default->code, $limit->native_amount));
if ($usePrimary) {
Log::debug(sprintf('Processing limit #%d with (primary currency) %s %s', $limit->id, $this->default->code, $limit->native_amount));
}
if (!$useNative) {
if (!$usePrimary) {
Log::debug(sprintf('Processing limit #%d with %s %s', $limit->id, $limit->transactionCurrency->code, $limit->amount));
}
@@ -164,12 +164,12 @@ class FrontpageChartGenerator
/** @var array $entry */
foreach ($spent as $entry) {
// only spent the entry where the entry's currency matches the budget limit's currency
// or when useNative is true.
if ($entry['currency_id'] === $limit->transaction_currency_id || $useNative) {
// or when usePrimary is true.
if ($entry['currency_id'] === $limit->transaction_currency_id || $usePrimary) {
Log::debug(sprintf('Process spent row (%s)', $entry['currency_code']));
$data = $this->processRow($data, $budget, $limit, $entry);
}
if (!($entry['currency_id'] === $limit->transaction_currency_id || $useNative)) {
if (!($entry['currency_id'] === $limit->transaction_currency_id || $usePrimary)) {
Log::debug(sprintf('Skipping spent row (%s).', $entry['currency_code']));
}
}
@@ -196,10 +196,10 @@ class FrontpageChartGenerator
$limit->end_date->isoFormat($this->monthAndDayFormat)
);
}
$useNative = $this->convertToNative && $this->default->id !== $limit->transaction_currency_id;
$usePrimary = $this->convertToPrimary && $this->default->id !== $limit->transaction_currency_id;
$amount = $limit->amount;
Log::debug(sprintf('Amount is "%s".', $amount));
if ($useNative && $limit->transaction_currency_id !== $this->default->id) {
if ($usePrimary && $limit->transaction_currency_id !== $this->default->id) {
$amount = $limit->native_amount;
Log::debug(sprintf('Amount is now "%s".', $amount));
}

View File

@@ -43,7 +43,7 @@ class FrontpageChartGenerator
{
use AugumentData;
public bool $convertToNative = false;
public bool $convertToPrimary = false;
public TransactionCurrency $defaultCurrency;
private AccountRepositoryInterface $accountRepos;
private array $currencies;

View File

@@ -36,7 +36,7 @@ use Illuminate\Support\Collection;
*/
class WholePeriodChartGenerator
{
public bool $convertToNative;
public bool $convertToPrimary;
public function generate(Category $category, Carbon $start, Carbon $end): array
{

View File

@@ -43,8 +43,8 @@ class ChartData
if (array_key_exists('currency_id', $data)) {
$data['currency_id'] = (string) $data['currency_id'];
}
if (array_key_exists('native_currency_id', $data)) {
$data['native_currency_id'] = (string) $data['native_currency_id'];
if (array_key_exists('primary_currency_id', $data)) {
$data['primary_currency_id'] = (string) $data['primary_currency_id'];
}
$required = ['start', 'date', 'end', 'entries'];
foreach ($required as $field) {

View File

@@ -734,11 +734,11 @@ class ExportDataGenerator
{
Log::debug('Will now export transactions.');
// TODO better place for keys?
$header = ['user_id', 'group_id', 'journal_id', 'created_at', 'updated_at', 'group_title', 'type', 'currency_code', 'amount', 'foreign_currency_code', 'foreign_amount', 'native_currency_code', 'native_amount', 'native_foreign_amount', 'description', 'date', 'source_name', 'source_iban', 'source_type', 'destination_name', 'destination_iban', 'destination_type', 'reconciled', 'category', 'budget', 'bill', 'tags', 'notes'];
$header = ['user_id', 'group_id', 'journal_id', 'created_at', 'updated_at', 'group_title', 'type', 'currency_code', 'amount', 'foreign_currency_code', 'foreign_amount', 'primary_currency_code', 'pc_amount', 'pc_foreign_amount', 'description', 'date', 'source_name', 'source_iban', 'source_type', 'destination_name', 'destination_iban', 'destination_type', 'reconciled', 'category', 'budget', 'bill', 'tags', 'notes'];
$metaFields = config('firefly.journal_meta_fields');
$header = array_merge($header, $metaFields);
$default = Amount::getPrimaryCurrency();
$primary = Amount::getPrimaryCurrency();
$collector = app(GroupCollectorInterface::class);
$collector->setUser($this->user);
@@ -760,28 +760,28 @@ class ExportDataGenerator
$metaData = $repository->getMetaFields($journal['transaction_journal_id'], $metaFields);
$amount = Steam::bcround(Steam::negative($journal['amount']), $journal['currency_decimal_places']);
$foreignAmount = null === $journal['foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['foreign_amount']), $journal['foreign_currency_decimal_places']);
$nativeAmount = null === $journal['native_amount'] ? null : Steam::bcround(Steam::negative($journal['native_amount']), $default->decimal_places);
$nativeForeignAmount = null === $journal['native_foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['native_foreign_amount']), $default->decimal_places);
$pcAmount = null === $journal['pc_amount'] ? null : Steam::bcround(Steam::negative($journal['pc_amount']), $primary->decimal_places);
$pcForeignAmount = null === $journal['pc_foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['pc_foreign_amount']), $primary->decimal_places);
if (TransactionTypeEnum::WITHDRAWAL->value !== $journal['transaction_type_type']) {
$amount = Steam::bcround(Steam::positive($journal['amount']), $journal['currency_decimal_places']);
$foreignAmount = null === $journal['foreign_amount'] ? null : Steam::bcround(Steam::positive($journal['foreign_amount']), $journal['foreign_currency_decimal_places']);
$nativeAmount = null === $journal['native_amount'] ? null : Steam::bcround(Steam::positive($journal['native_amount']), $default->decimal_places);
$nativeForeignAmount = null === $journal['native_foreign_amount'] ? null : Steam::bcround(Steam::positive($journal['native_foreign_amount']), $default->decimal_places);
$pcAmount = null === $journal['pc_amount'] ? null : Steam::bcround(Steam::positive($journal['pc_amount']), $primary->decimal_places);
$pcForeignAmount = null === $journal['pc_foreign_amount'] ? null : Steam::bcround(Steam::positive($journal['pc_foreign_amount']), $primary->decimal_places);
}
// opening balance depends on source account type.
if (TransactionTypeEnum::OPENING_BALANCE->value === $journal['transaction_type_type'] && AccountTypeEnum::ASSET->value === $journal['source_account_type']) {
$amount = Steam::bcround(Steam::negative($journal['amount']), $journal['currency_decimal_places']);
$foreignAmount = null === $journal['foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['foreign_amount']), $journal['foreign_currency_decimal_places']);
$nativeAmount = null === $journal['native_amount'] ? null : Steam::bcround(Steam::negative($journal['native_amount']), $default->decimal_places);
$nativeForeignAmount = null === $journal['native_foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['native_foreign_amount']), $default->decimal_places);
$pcAmount = null === $journal['pc_amount'] ? null : Steam::bcround(Steam::negative($journal['pc_amount']), $primary->decimal_places);
$pcForeignAmount = null === $journal['pc_foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['pc_foreign_amount']), $primary->decimal_places);
}
$records[] = [
$journal['user_id'], $journal['transaction_group_id'], $journal['transaction_journal_id'], $journal['created_at']->toAtomString(), $journal['updated_at']->toAtomString(), $journal['transaction_group_title'], $journal['transaction_type_type'],
// amounts and currencies
$journal['currency_code'], $amount, $journal['foreign_currency_code'], $foreignAmount, $default->code, $nativeAmount, $nativeForeignAmount,
$journal['currency_code'], $amount, $journal['foreign_currency_code'], $foreignAmount, $primary->code, $pcAmount, $pcForeignAmount,
// more fields
$journal['description'], $journal['date']->toAtomString(), $journal['source_account_name'], $journal['source_account_iban'], $journal['source_account_type'], $journal['destination_account_name'], $journal['destination_account_iban'], $journal['destination_account_type'], $journal['reconciled'], $journal['category_name'], $journal['budget_name'], $journal['bill_name'],

View File

@@ -41,7 +41,7 @@ class AccountBalanceGrouped
private readonly ExchangeRateConverter $converter;
private array $currencies = [];
private array $data = [];
private TransactionCurrency $default;
private TransactionCurrency $primary;
private Carbon $end;
private array $journals = [];
private string $preferredRange;
@@ -70,16 +70,16 @@ class AccountBalanceGrouped
'currency_symbol' => $currency['currency_symbol'],
'currency_code' => $currency['currency_code'],
'currency_decimal_places' => $currency['currency_decimal_places'],
'native_currency_id' => (string) $currency['native_currency_id'],
'native_currency_symbol' => $currency['native_currency_symbol'],
'native_currency_code' => $currency['native_currency_code'],
'native_currency_decimal_places' => $currency['native_currency_decimal_places'],
'primary_currency_id' => (string) $currency['primary_currency_id'],
'primary_currency_symbol' => $currency['primary_currency_symbol'],
'primary_currency_code' => $currency['primary_currency_code'],
'primary_currency_decimal_places' => $currency['primary_currency_decimal_places'],
'date' => $this->start->toAtomString(),
'start' => $this->start->toAtomString(),
'end' => $this->end->toAtomString(),
'period' => $this->preferredRange,
'entries' => [],
'native_entries' => [],
'primary_entries' => [],
];
$expense = [
'label' => 'spent',
@@ -87,16 +87,16 @@ class AccountBalanceGrouped
'currency_symbol' => $currency['currency_symbol'],
'currency_code' => $currency['currency_code'],
'currency_decimal_places' => $currency['currency_decimal_places'],
'native_currency_id' => (string) $currency['native_currency_id'],
'native_currency_symbol' => $currency['native_currency_symbol'],
'native_currency_code' => $currency['native_currency_code'],
'native_currency_decimal_places' => $currency['native_currency_decimal_places'],
'primary_currency_id' => (string) $currency['primary_currency_id'],
'primary_currency_symbol' => $currency['primary_currency_symbol'],
'primary_currency_code' => $currency['primary_currency_code'],
'primary_currency_decimal_places' => $currency['primary_currency_decimal_places'],
'date' => $this->start->toAtomString(),
'start' => $this->start->toAtomString(),
'end' => $this->end->toAtomString(),
'period' => $this->preferredRange,
'entries' => [],
'native_entries' => [],
'pc_entries' => [],
];
// loop all possible periods between $start and $end, and add them to the correct dataset.
$currentStart = clone $this->start;
@@ -108,8 +108,8 @@ class AccountBalanceGrouped
$expense['entries'][$label] = app('steam')->bcround($currency[$key]['spent'] ?? '0', $currency['currency_decimal_places']);
// converted entries
$income['native_entries'][$label] = app('steam')->bcround($currency[$key]['native_earned'] ?? '0', $currency['native_currency_decimal_places']);
$expense['native_entries'][$label] = app('steam')->bcround($currency[$key]['native_spent'] ?? '0', $currency['native_currency_decimal_places']);
$income['pc_entries'][$label] = app('steam')->bcround($currency[$key]['pc_earned'] ?? '0', $currency['primary_currency_decimal_places']);
$expense['pc_entries'][$label] = app('steam')->bcround($currency[$key]['pc_spent'] ?? '0', $currency['primary_currency_decimal_places']);
// next loop
$currentStart = app('navigation')->addPeriod($currentStart, $this->preferredRange, 0);
@@ -159,8 +159,8 @@ class AccountBalanceGrouped
$rate = $this->getRate($currency, $journal['date']);
$amountConverted = bcmul((string) $amount, $rate);
// perhaps transaction already has the foreign amount in the native currency.
if ((int) $journal['foreign_currency_id'] === $this->default->id) {
// perhaps transaction already has the foreign amount in the primary currency.
if ((int) $journal['foreign_currency_id'] === $this->primary->id) {
$amountConverted = $journal['foreign_amount'] ?? '0';
$amountConverted = 'earned' === $key ? app('steam')->positive($amountConverted) : app('steam')->negative($amountConverted);
}
@@ -169,7 +169,7 @@ class AccountBalanceGrouped
$this->data[$currencyId][$period][$key] = bcadd((string) $this->data[$currencyId][$period][$key], (string) $amount);
// add converted entry
$convertedKey = sprintf('native_%s', $key);
$convertedKey = sprintf('pc_%s', $key);
$this->data[$currencyId][$period][$convertedKey] = bcadd((string) $this->data[$currencyId][$period][$convertedKey], (string) $amountConverted);
}
@@ -192,11 +192,11 @@ class AccountBalanceGrouped
'currency_code' => $journal['currency_code'],
'currency_name' => $journal['currency_name'],
'currency_decimal_places' => $journal['currency_decimal_places'],
// native currency info (could be the same)
'native_currency_id' => (string) $this->default->id,
'native_currency_code' => $this->default->code,
'native_currency_symbol' => $this->default->symbol,
'native_currency_decimal_places' => $this->default->decimal_places,
// primary currency info (could be the same)
'primary_currency_id' => (string) $this->primary->id,
'primary_currency_code' => $this->primary->code,
'primary_currency_symbol' => $this->primary->symbol,
'primary_currency_decimal_places' => $this->primary->decimal_places,
];
}
@@ -208,8 +208,8 @@ class AccountBalanceGrouped
'period' => $period,
'spent' => '0',
'earned' => '0',
'native_spent' => '0',
'native_earned' => '0',
'pc_spent' => '0',
'pc_earned' => '0',
];
}
@@ -238,7 +238,7 @@ class AccountBalanceGrouped
private function getRate(TransactionCurrency $currency, Carbon $date): string
{
try {
$rate = $this->converter->getCurrencyRate($currency, $this->default, $date);
$rate = $this->converter->getCurrencyRate($currency, $this->primary, $date);
} catch (FireflyException $e) {
app('log')->error($e->getMessage());
$rate = '1';
@@ -252,22 +252,22 @@ class AccountBalanceGrouped
$this->accountIds = $accounts->pluck('id')->toArray();
}
public function setDefault(TransactionCurrency $default): void
public function setPrimary(TransactionCurrency $primary): void
{
$this->default = $default;
$defaultCurrencyId = $default->id;
$this->currencies = [$default->id => $default]; // currency cache
$this->data[$defaultCurrencyId] = [
'currency_id' => (string) $defaultCurrencyId,
'currency_symbol' => $default->symbol,
'currency_code' => $default->code,
'currency_name' => $default->name,
'currency_decimal_places' => $default->decimal_places,
'native_currency_id' => (string) $defaultCurrencyId,
'native_currency_symbol' => $default->symbol,
'native_currency_code' => $default->code,
'native_currency_name' => $default->name,
'native_currency_decimal_places' => $default->decimal_places,
$this->primary = $primary;
$primaryCurrencyId = $primary->id;
$this->currencies = [$primary->id => $primary]; // currency cache
$this->data[$primaryCurrencyId] = [
'currency_id' => (string) $primaryCurrencyId,
'currency_symbol' => $primary->symbol,
'currency_code' => $primary->code,
'currency_name' => $primary->name,
'currency_decimal_places' => $primary->decimal_places,
'primary_currency_id' => (string) $primaryCurrencyId,
'primary_currency_symbol' => $primary->symbol,
'primary_currency_code' => $primary->code,
'primary_currency_name' => $primary->name,
'primary_currency_decimal_places' => $primary->decimal_places,
];
}

View File

@@ -50,8 +50,8 @@ trait CleansChartData
if (array_key_exists('currency_id', $array)) {
$array['currency_id'] = (string) $array['currency_id'];
}
if (array_key_exists('native_currency_id', $array)) {
$array['native_currency_id'] = (string) $array['native_currency_id'];
if (array_key_exists('primary_currency_id', $array)) {
$array['primary_currency_id'] = (string) $array['primary_currency_id'];
}
if (!array_key_exists('start', $array)) {
throw new FireflyException(sprintf('Data-set "%s" is missing the "start"-variable.', $index));

View File

@@ -57,8 +57,8 @@ class SummaryBalanceGrouped
};
$return[] = [
'key' => sprintf('%s-in-native', $title),
'value' => $this->amounts[$key]['native'] ?? '0',
'key' => sprintf('%s-in-pc', $title),
'value' => $this->amounts[$key]['primary'] ?? '0',
'currency_id' => (string) $this->default->id,
'currency_code' => $this->default->code,
'currency_symbol' => $this->default->symbol,
@@ -68,8 +68,8 @@ class SummaryBalanceGrouped
// loop 3: format amounts:
$currencyIds = array_keys($this->amounts[self::SUM] ?? []);
foreach ($currencyIds as $currencyId) {
if ('native' === $currencyId) {
// skip native entries.
if ('primary' === $currencyId) {
// skip primary entries.
continue;
}
$currencyId = (int) $currencyId;
@@ -112,23 +112,23 @@ class SummaryBalanceGrouped
$amount = bcmul((string) $journal['amount'], $multiplier);
$currency = $this->currencies[$currencyId] ?? TransactionCurrency::find($currencyId);
$this->currencies[$currencyId] = $currency;
$nativeAmount = $converter->convert($currency, $this->default, $journal['date'], $amount);
$pcAmount = $converter->convert($currency, $this->default, $journal['date'], $amount);
if ((int) $journal['foreign_currency_id'] === $this->default->id) {
// use foreign amount instead
$nativeAmount = $journal['foreign_amount'];
$pcAmount = $journal['foreign_amount'];
}
// prep the arrays
$this->amounts[$key] ??= [];
$this->amounts[$key][$currencyId] ??= '0';
$this->amounts[$key]['native'] ??= '0';
$this->amounts[$key]['primary'] ??= '0';
$this->amounts[self::SUM][$currencyId] ??= '0';
$this->amounts[self::SUM]['native'] ??= '0';
$this->amounts[self::SUM]['primary'] ??= '0';
// add values:
$this->amounts[$key][$currencyId] = bcadd((string) $this->amounts[$key][$currencyId], $amount);
$this->amounts[self::SUM][$currencyId] = bcadd((string) $this->amounts[self::SUM][$currencyId], $amount);
$this->amounts[$key]['native'] = bcadd((string) $this->amounts[$key]['native'], (string) $nativeAmount);
$this->amounts[self::SUM]['native'] = bcadd((string) $this->amounts[self::SUM]['native'], (string) $nativeAmount);
$this->amounts[$key]['primary'] = bcadd((string) $this->amounts[$key]['primary'], (string) $pcAmount);
$this->amounts[self::SUM]['primary'] = bcadd((string) $this->amounts[self::SUM]['primary'], (string) $pcAmount);
}
$converter->summarize();
}

View File

@@ -182,7 +182,7 @@ trait AugumentData
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($budget->id);
$cache->addProperty($this->convertToNative);
$cache->addProperty($this->convertToPrimary);
$cache->addProperty('get-limits');
if ($cache->has()) {
@@ -193,14 +193,14 @@ trait AugumentData
$budgetCollection = new Collection([$budget]);
// merge sets based on a key, in case of convert to native
// merge sets based on a key, in case of convert to primary currency
$limits = new Collection();
/** @var BudgetLimit $entry */
foreach ($set as $entry) {
Log::debug(sprintf('Now at budget limit #%d', $entry->id));
$currency = $entry->transactionCurrency;
if ($this->convertToNative) {
if ($this->convertToPrimary) {
// the sumExpenses method already handles this.
$currency = $this->defaultCurrency;
}
@@ -213,10 +213,10 @@ trait AugumentData
$currentEnd = clone $currentStart;
$currentEnd->addMonth();
}
// native amount.
$expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency, $this->convertToNative);
// primary currency amount.
$expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency, $this->convertToPrimary);
$spent = $expenses[$currency->id]['sum'] ?? '0';
$entry->native_spent = $spent;
$entry->pc_spent = $spent;
// normal amount:
$expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency, false);

View File

@@ -38,7 +38,7 @@ trait BasicDataSupport
*/
protected function isInArray(array $array, int $entryId)
{
$key = $this->convertToNative ? 'native_balance' : 'balance';
$key = $this->convertToPrimary ? 'pc_balance' : 'balance';
return $array[$entryId][$key] ?? '0';
}

View File

@@ -48,13 +48,13 @@ trait ChartGeneration
protected function accountBalanceChart(Collection $accounts, Carbon $start, Carbon $end): array // chart helper method.
{
// chart properties for cache:
$convertToNative = Amount::convertToPrimary();
$convertToPrimary = Amount::convertToPrimary();
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty('chart.account.account-balance-chart');
$cache->addProperty($accounts);
$cache->addProperty($convertToNative);
$cache->addProperty($convertToPrimary);
if ($cache->has()) {
return $cache->get();
}
@@ -76,9 +76,9 @@ trait ChartGeneration
foreach ($accounts as $account) {
Log::debug(sprintf('Now at account #%d ("%s)', $account->id, $account->name));
$currency = $accountRepos->getAccountCurrency($account) ?? $default;
$useNative = $convertToNative && $default->id !== $currency->id;
$field = $convertToNative ? 'native_balance' : 'balance';
$currency = $useNative ? $default : $currency;
$usePrimary = $convertToPrimary && $default->id !== $currency->id;
$field = $convertToPrimary ? 'pc_balance' : 'balance';
$currency = $usePrimary ? $default : $currency;
Log::debug(sprintf('Will use field %s', $field));
$currentSet = [
'label' => $account->name,
@@ -87,7 +87,7 @@ trait ChartGeneration
];
$currentStart = clone $start;
$range = Steam::finalAccountBalanceInRange($account, clone $start, clone $end, $this->convertToNative);
$range = Steam::finalAccountBalanceInRange($account, clone $start, clone $end, $this->convertToPrimary);
$previous = array_values($range)[0];
Log::debug(sprintf('Start balance for account #%d ("%s) is', $account->id, $account->name), $previous);
while ($currentStart <= $end) {

View File

@@ -194,15 +194,15 @@ trait PeriodOverview
$foreignCurrencyId = $journal['foreign_currency_id'];
$amount = $journal['amount'] ?? '0';
if ($this->convertToNative && $currencyId !== $this->defaultCurrency->id && $foreignCurrencyId !== $this->defaultCurrency->id) {
$amount = $journal['native_amount'] ?? '0';
$currencyId = $this->defaultCurrency->id;
$currencyCode = $this->defaultCurrency->code;
$currencyName = $this->defaultCurrency->name;
$currencySymbol = $this->defaultCurrency->symbol;
$currencyDecimalPlaces = $this->defaultCurrency->decimal_places;
if ($this->convertToPrimary && $currencyId !== $this->primaryCurrency->id && $foreignCurrencyId !== $this->primaryCurrency->id) {
$amount = $journal['pc_amount'] ?? '0';
$currencyId = $this->primaryCurrency->id;
$currencyCode = $this->primaryCurrency->code;
$currencyName = $this->primaryCurrency->name;
$currencySymbol = $this->primaryCurrency->symbol;
$currencyDecimalPlaces = $this->primaryCurrency->decimal_places;
}
if ($this->convertToNative && $currencyId !== $this->defaultCurrency->id && $foreignCurrencyId === $this->defaultCurrency->id) {
if ($this->convertToPrimary && $currencyId !== $this->primaryCurrency->id && $foreignCurrencyId === $this->primaryCurrency->id) {
$currencyId = (int) $foreignCurrencyId;
$currencyCode = $journal['foreign_currency_code'];
$currencyName = $journal['foreign_currency_name'];
@@ -334,7 +334,7 @@ trait PeriodOverview
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($this->convertToNative);
$cache->addProperty($this->convertToPrimary);
$cache->addProperty('no-budget-period-entries');
if ($cache->has()) {

View File

@@ -55,7 +55,7 @@ class AccountEnrichment implements EnrichmentInterface
private array $currencies;
private array $locations;
private array $meta;
private TransactionCurrency $native;
private TransactionCurrency $primaryCurrency;
private array $notes;
private array $openingBalances;
private User $user;
@@ -150,7 +150,7 @@ class AccountEnrichment implements EnrichmentInterface
foreach ($currencies as $currency) {
$this->currencies[(int) $currency->id] = $currency;
}
$this->currencies[0] = $this->native;
$this->currencies[0] = $this->primaryCurrency;
foreach ($this->currencies as $id => $currency) {
if (true === $currency) {
throw new FireflyException(sprintf('Currency #%d not found.', $id));
@@ -278,9 +278,9 @@ class AccountEnrichment implements EnrichmentInterface
});
}
public function setNative(TransactionCurrency $native): void
public function setPrimaryCurrency(TransactionCurrency $primary): void
{
$this->native = $native;
$this->primaryCurrency = $primary;
}
private function collectLastActivities(): void

View File

@@ -26,7 +26,7 @@ class SubscriptionEnrichment implements EnrichmentInterface
private User $user;
private UserGroup $userGroup;
private Collection $collection;
private bool $convertToNative = false;
private bool $convertToPrimary = false;
private ?Carbon $start = null;
private ?Carbon $end = null;
private array $subscriptionIds = [];
@@ -35,7 +35,7 @@ class SubscriptionEnrichment implements EnrichmentInterface
private array $paidDates = [];
private array $notes = [];
private array $payDates = [];
private TransactionCurrency $nativeCurrency;
private TransactionCurrency $primaryCurrency;
private BillDateCalculator $calculator;
public function enrich(Collection $collection): Collection
@@ -88,15 +88,15 @@ class SubscriptionEnrichment implements EnrichmentInterface
$meta['notes'] = $notes[$item->id];
}
// Convert amounts to native currency if needed
if ($this->convertToNative && $item->currency_id !== $this->nativeCurrency->id) {
Log::debug('Convert to native currency');
// Convert amounts to primary currency if needed
if ($this->convertToPrimary && $item->currency_id !== $this->primaryCurrency->id) {
Log::debug('Convert to primary currency');
$converter = new ExchangeRateConverter();
$amounts = [
'amount_min' => Steam::bcround($converter->convert($item->transactionCurrency, $this->nativeCurrency, today(), $item->amount_min), $this->nativeCurrency->decimal_places),
'amount_max' => Steam::bcround($converter->convert($item->transactionCurrency, $this->nativeCurrency, today(), $item->amount_max), $this->nativeCurrency->decimal_places),
'amount_min' => Steam::bcround($converter->convert($item->transactionCurrency, $this->primaryCurrency, today(), $item->amount_min), $this->primaryCurrency->decimal_places),
'amount_max' => Steam::bcround($converter->convert($item->transactionCurrency, $this->primaryCurrency, today(), $item->amount_max), $this->primaryCurrency->decimal_places),
];
$amounts['average'] = Steam::bcround(bcdiv(bcadd($amounts['amount_min'], $amounts['amount_max']), '2'), $this->nativeCurrency->decimal_places);
$amounts['average'] = Steam::bcround(bcdiv(bcadd($amounts['amount_min'], $amounts['amount_max']), '2'), $this->primaryCurrency->decimal_places);
}
$item->amounts = $amounts;
$item->meta = $meta;
@@ -140,14 +140,14 @@ class SubscriptionEnrichment implements EnrichmentInterface
$this->userGroup = $userGroup;
}
public function setConvertToNative(bool $convertToNative): void
public function setConvertToPrimary(bool $convertToPrimary): void
{
$this->convertToNative = $convertToNative;
$this->convertToPrimary = $convertToPrimary;
}
public function setNative(TransactionCurrency $nativeCurrency): void
public function setPrimaryCurrency(TransactionCurrency $primaryCurrency): void
{
$this->nativeCurrency = $nativeCurrency;
$this->primaryCurrency = $primaryCurrency;
}
private function collectSubscriptionIds(): void
@@ -267,11 +267,11 @@ class SubscriptionEnrichment implements EnrichmentInterface
$array['foreign_currency_decimal_places'] = $entry->foreign_currency_decimal_places;
$array['foreign_amount'] = Steam::bcround($entry->foreign_amount, $entry->foreign_currency_decimal_places);
}
if($this->convertToNative) {
$array['amount'] = $converter->convert($entry->transactionCurrency, $this->nativeCurrency, $entry->date, $entry->amount);
$array['currency_id'] = $this->nativeCurrency->id;
$array['currency_code'] = $this->nativeCurrency->code;
$array['currency_decimal_places'] = $this->nativeCurrency->decimal_places;
if($this->convertToPrimary) {
$array['amount'] = $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->date, $entry->amount);
$array['currency_id'] = $this->primaryCurrency->id;
$array['currency_code'] = $this->primaryCurrency->code;
$array['currency_decimal_places'] = $this->primaryCurrency->decimal_places;
}

View File

@@ -31,7 +31,7 @@ use Illuminate\Support\Facades\Log;
class TransactionSummarizer
{
private bool $convertToNative = false;
private bool $convertToPrimary = false;
private TransactionCurrency $default;
private User $user;
@@ -46,7 +46,7 @@ class TransactionSummarizer
{
$this->user = $user;
$this->default = Amount::getPrimaryCurrencyByUserGroup($user->userGroup);
$this->convertToNative = Amount::convertToPrimary($user);
$this->convertToPrimary = Amount::convertToPrimary($user);
}
public function groupByCurrencyId(array $journals, string $method = 'negative', bool $includeForeign = true): array
@@ -70,14 +70,14 @@ class TransactionSummarizer
$foreignCurrencyCode = null;
$foreignCurrencyDecimalPlaces = null;
if ($this->convertToNative) {
// Log::debug('convertToNative is true.');
// if convert to native, use the native amount yes or no?
$useNative = $this->default->id !== (int) $journal['currency_id'];
if ($this->convertToPrimary) {
// Log::debug('convertToPrimary is true.');
// if convert to primary currency, use the primary currency amount yes or no?
$usePrimary = $this->default->id !== (int) $journal['currency_id'];
$useForeign = $this->default->id === (int) $journal['foreign_currency_id'];
if ($useNative) {
// Log::debug(sprintf('Journal #%d switches to native amount (original is %s)', $journal['transaction_journal_id'], $journal['currency_code']));
$field = 'native_amount';
if ($usePrimary) {
// Log::debug(sprintf('Journal #%d switches to primary currency amount (original is %s)', $journal['transaction_journal_id'], $journal['currency_code']));
$field = 'pc_amount';
$currencyId = $this->default->id;
$currencyName = $this->default->name;
$currencySymbol = $this->default->symbol;
@@ -94,8 +94,8 @@ class TransactionSummarizer
$currencyDecimalPlaces = $journal['foreign_currency_decimal_places'];
}
}
if (!$this->convertToNative) {
// Log::debug('convertToNative is false.');
if (!$this->convertToPrimary) {
// Log::debug('convertToPrimary is false.');
// use foreign amount?
$foreignCurrencyId = (int) $journal['foreign_currency_id'];
if (0 !== $foreignCurrencyId) {
@@ -159,8 +159,8 @@ class TransactionSummarizer
$array = [];
$idKey = sprintf('%s_account_id', $direction);
$nameKey = sprintf('%s_account_name', $direction);
$convertToNative = Amount::convertToPrimary($this->user);
$default = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
$convertToPrimary = Amount::convertToPrimary($this->user);
$primary = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup);
Log::debug(sprintf('groupByDirection(array, %s, %s).', $direction, $method));
@@ -171,18 +171,18 @@ class TransactionSummarizer
$currencySymbol = $journal['currency_symbol'];
$currencyCode = $journal['currency_code'];
$currencyDecimalPlaces = $journal['currency_decimal_places'];
$field = $convertToNative && $currencyId !== $default->id ? 'native_amount' : 'amount';
$field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount';
// perhaps use default currency instead?
if ($convertToNative && $journal['currency_id'] !== $default->id) {
$currencyId = $default->id;
$currencyName = $default->name;
$currencySymbol = $default->symbol;
$currencyCode = $default->code;
$currencyDecimalPlaces = $default->decimal_places;
if ($convertToPrimary && $journal['currency_id'] !== $primary->id) {
$currencyId = $primary->id;
$currencyName = $primary->name;
$currencySymbol = $primary->symbol;
$currencyCode = $primary->code;
$currencyDecimalPlaces = $primary->decimal_places;
}
// use foreign amount when the foreign currency IS the default currency.
if ($convertToNative && $journal['currency_id'] !== $default->id && $default->id === $journal['foreign_currency_id']) {
if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) {
$field = 'foreign_amount';
}
$key = sprintf('%s-%s', $journal[$idKey], $currencyId);
@@ -202,9 +202,9 @@ class TransactionSummarizer
$array[$key]['sum'] = bcadd($array[$key]['sum'], (string) app('steam')->{$method}((string) ($journal[$field] ?? '0'))); // @phpstan-ignore-line
Log::debug(sprintf('Field for transaction #%d is "%s" (%s). Sum: %s', $journal['transaction_group_id'], $currencyCode, $field, $array[$key]['sum']));
// also do foreign amount, but only when convertToNative is false (otherwise we have it already)
// or when convertToNative is true and the foreign currency is ALSO not the default currency.
if ((!$convertToNative || $journal['foreign_currency_id'] !== $default->id) && 0 !== (int) $journal['foreign_currency_id']) {
// also do foreign amount, but only when convertToPrimary is false (otherwise we have it already)
// or when convertToPrimary is true and the foreign currency is ALSO not the default currency.
if ((!$convertToPrimary || $journal['foreign_currency_id'] !== $primary->id) && 0 !== (int) $journal['foreign_currency_id']) {
Log::debug(sprintf('Use foreign amount from transaction #%d: %s %s. Sum: %s', $journal['transaction_group_id'], $currencyCode, $journal['foreign_amount'], $array[$key]['sum']));
$key = sprintf('%s-%s', $journal[$idKey], $journal['foreign_currency_id']);
$array[$key] ??= [
@@ -224,9 +224,9 @@ class TransactionSummarizer
return $array;
}
public function setConvertToNative(bool $convertToNative): void
public function setConvertToPrimary(bool $convertToPrimary): void
{
Log::debug(sprintf('Overrule convertToNative to become %s', var_export($convertToNative, true)));
$this->convertToNative = $convertToNative;
Log::debug(sprintf('Overrule convertToPrimary to become %s', var_export($convertToPrimary, true)));
$this->convertToPrimary = $convertToPrimary;
}
}

View File

@@ -73,19 +73,19 @@ class Steam
return $number;
}
public function filterAccountBalances(array $total, Account $account, bool $convertToNative, ?TransactionCurrency $currency = null): array
public function filterAccountBalances(array $total, Account $account, bool $convertToPrimary, ?TransactionCurrency $currency = null): array
{
Log::debug(sprintf('filterAccountBalances(#%d)', $account->id));
$return = [];
foreach ($total as $key => $value) {
$return[$key] = $this->filterAccountBalance($value, $account, $convertToNative, $currency);
$return[$key] = $this->filterAccountBalance($value, $account, $convertToPrimary, $currency);
}
Log::debug(sprintf('end of filterAccountBalances(#%d)', $account->id));
return $return;
}
public function filterAccountBalance(array $set, Account $account, bool $convertToNative, ?TransactionCurrency $currency = null): array
public function filterAccountBalance(array $set, Account $account, bool $convertToPrimary, ?TransactionCurrency $currency = null): array
{
Log::debug(sprintf('filterAccountBalance(#%d)', $account->id), $set);
if (0 === count($set)) {
@@ -93,14 +93,14 @@ class Steam
return [];
}
$defaultCurrency = Amount::getPrimaryCurrency();
if ($convertToNative) {
if ($defaultCurrency->id === $currency?->id) {
Log::debug(sprintf('Unset [%s] for account #%d (no longer unset "native_balance")', $defaultCurrency->code, $account->id));
unset($set[$defaultCurrency->code]);
$primaryCurrency = Amount::getPrimaryCurrency();
if ($convertToPrimary) {
if ($primaryCurrency->id === $currency?->id) {
Log::debug(sprintf('Unset [%s] for account #%d (no longer unset "pc_balance")', $primaryCurrency->code, $account->id));
unset($set[$primaryCurrency->code]);
}
// todo rethink this logic.
if ($currency instanceof TransactionCurrency && $defaultCurrency->id !== $currency->id) {
if ($currency instanceof TransactionCurrency && $primaryCurrency->id !== $currency->id) {
Log::debug(sprintf('Unset balance for account #%d', $account->id));
unset($set['balance']);
}
@@ -111,22 +111,22 @@ class Steam
}
}
if (!$convertToNative) {
if (!$convertToPrimary) {
if (!$currency instanceof TransactionCurrency) {
Log::debug(sprintf('Unset native_balance and make defaultCurrency balance the balance for account #%d', $account->id));
$set['balance'] = $set[$defaultCurrency->code] ?? '0';
unset($set[$defaultCurrency->code]);
Log::debug(sprintf('Unset pc_balance and make defaultCurrency balance the balance for account #%d', $account->id));
$set['balance'] = $set[$primaryCurrency->code] ?? '0';
unset($set[$primaryCurrency->code]);
}
if ($currency instanceof TransactionCurrency) {
Log::debug(sprintf('Unset [%s] + [%s] balance for account #%d', $defaultCurrency->code, $currency->code, $account->id));
unset($set[$defaultCurrency->code], $set[$currency->code]);
Log::debug(sprintf('Unset [%s] + [%s] balance for account #%d', $primaryCurrency->code, $currency->code, $account->id));
unset($set[$primaryCurrency->code], $set[$currency->code]);
}
}
// put specific value first in array.
if (array_key_exists('native_balance', $set)) {
$set = ['native_balance' => $set['native_balance']] + $set;
if (array_key_exists('pc_balance', $set)) {
$set = ['pc_balance' => $set['pc_balance']] + $set;
}
if (array_key_exists('balance', $set)) {
$set = ['balance' => $set['balance']] + $set;
@@ -195,7 +195,7 @@ class Steam
return str_replace($search, '', $string);
}
public function finalAccountBalanceInRange(Account $account, Carbon $start, Carbon $end, bool $convertToNative): array
public function finalAccountBalanceInRange(Account $account, Carbon $start, Carbon $end, bool $convertToPrimary): array
{
// expand period.
$start->startOfDay();
@@ -207,7 +207,7 @@ class Steam
$cache->addProperty($account->id);
$cache->addProperty('final-balance-in-range');
$cache->addProperty($start);
$cache->addProperty($convertToNative);
$cache->addProperty($convertToPrimary);
$cache->addProperty($end);
if ($cache->has()) {
return $cache->get();
@@ -224,10 +224,10 @@ class Steam
$request->subDay()->endOfDay();
Log::debug(sprintf('finalAccountBalanceInRange: Call finalAccountBalance with date/time "%s"', $request->toIso8601String()));
$startBalance = $this->finalAccountBalance($account, $request);
$nativeCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup);
$primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup);
$accountCurrency = $this->getAccountCurrency($account);
$hasCurrency = $accountCurrency instanceof TransactionCurrency;
$currency = $accountCurrency ?? $nativeCurrency;
$currency = $accountCurrency ?? $primaryCurrency;
Log::debug(sprintf('Currency is %s', $currency->code));
@@ -237,12 +237,12 @@ class Steam
$startBalance[$accountCurrency->code] ??= '0';
}
if (!$hasCurrency) {
Log::debug(sprintf('Also set start balance in %s', $nativeCurrency->code));
$startBalance[$nativeCurrency->code] ??= '0';
Log::debug(sprintf('Also set start balance in %s', $primaryCurrency->code));
$startBalance[$primaryCurrency->code] ??= '0';
}
$currencies = [
$currency->id => $currency,
$nativeCurrency->id => $nativeCurrency,
$primaryCurrency->id => $primaryCurrency,
];
$balances[$formatted] = $startBalance;
@@ -294,15 +294,15 @@ class Steam
$currentBalance[$entryCurrency->code] ??= '0';
$currentBalance[$entryCurrency->code] = bcadd($sumOfDay, (string) $currentBalance[$entryCurrency->code]);
// if not requested to convert to native, add the amount to "balance", do nothing else.
if (!$convertToNative) {
// if not requested to convert to primary currency, add the amount to "balance", do nothing else.
if (!$convertToPrimary) {
$currentBalance['balance'] = bcadd((string) $currentBalance['balance'], $sumOfDay);
}
// if convert to native add the converted amount to "native_balance".
// if there is a request to convert, convert to "native_balance" and use "balance" for whichever amount is in the native currency.
if ($convertToNative) {
$nativeSumOfDay = $converter->convert($entryCurrency, $nativeCurrency, $carbon, $sumOfDay);
$currentBalance['native_balance'] = bcadd((string) ($currentBalance['native_balance'] ?? '0'), $nativeSumOfDay);
// if convert to primary currency add the converted amount to "pc_balance".
// if there is a request to convert, convert to "pc_balance" and use "balance" for whichever amount is in the primary currency.
if ($convertToPrimary) {
$pcSumOfDay = $converter->convert($entryCurrency, $primaryCurrency, $carbon, $sumOfDay);
$currentBalance['pc_balance'] = bcadd((string) ($currentBalance['pc_balance'] ?? '0'), $pcSumOfDay);
// if it's the same currency as the entry, also add to balance (see other code).
if ($currency->id === $entryCurrency->id) {
$currentBalance['balance'] = bcadd((string) $currentBalance['balance'], $sumOfDay);
@@ -323,15 +323,15 @@ class Steam
*
* Returns the balance of an account at exact moment given. Array with at least one value.
* Always returns:
* "balance": balance in the account's currency OR user's native currency if the account has no currency
* "balance": balance in the account's currency OR user's primary currency if the account has no currency
* "EUR": balance in EUR (or whatever currencies the account has balance in)
*
* If the user has $convertToNative:
* "balance": balance in the account's currency OR user's native currency if the account has no currency
* --> "native_balance": balance in the user's native balance, with all amounts converted to native.
* If the user has $convertToPrimary:
* "balance": balance in the account's currency OR user's primary currency if the account has no currency
* --> "pc_balance": balance in the user's primary currency, with all amounts converted to the primary currency.
* "EUR": balance in EUR (or whatever currencies the account has balance in)
*/
public function finalAccountBalance(Account $account, Carbon $date, ?TransactionCurrency $native = null, ?bool $convertToNative = null): array
public function finalAccountBalance(Account $account, Carbon $date, ?TransactionCurrency $primary = null, ?bool $convertToPrimary = null): array
{
$cache = new CacheProperties();
@@ -343,11 +343,11 @@ class Steam
return $cache->get();
}
// Log::debug(sprintf('finalAccountBalance(#%d, %s)', $account->id, $date->format('Y-m-d H:i:s')));
if (null === $convertToNative) {
$convertToNative = Amount::convertToPrimary($account->user);
if (null === $convertToPrimary) {
$convertToPrimary = Amount::convertToPrimary($account->user);
}
if (!$native instanceof TransactionCurrency) {
$native = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup);
if (!$primary instanceof TransactionCurrency) {
$primary = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup);
}
// account balance thing.
$currencyPresent = isset($account->meta) && array_key_exists('currency', $account->meta) && null !== $account->meta['currency'];
@@ -359,9 +359,9 @@ class Steam
$accountCurrency = $this->getAccountCurrency($account);
}
$hasCurrency = null !== $accountCurrency;
$currency = $hasCurrency ? $accountCurrency : $native;
$currency = $hasCurrency ? $accountCurrency : $primary;
$return = [
'native_balance' => '0',
'pc_balance' => '0',
'balance' => '0', // this key is overwritten right away, but I must remember it is always created.
];
// balance(s) in all currencies.
@@ -373,32 +373,32 @@ class Steam
;
$others = $this->groupAndSumTransactions($array, 'code', 'amount');
// Log::debug('All balances are (joined)', $others);
// if there is no request to convert, take this as "balance" and "native_balance".
// if there is no request to convert, take this as "balance" and "pc_balance".
$return['balance'] = $others[$currency->code] ?? '0';
if (!$convertToNative) {
unset($return['native_balance']);
// Log::debug(sprintf('Set balance to %s, unset native_balance', $return['balance']));
if (!$convertToPrimary) {
unset($return['pc_balance']);
// Log::debug(sprintf('Set balance to %s, unset pc_balance', $return['balance']));
}
// if there is a request to convert, convert to "native_balance" and use "balance" for whichever amount is in the native currency.
if ($convertToNative) {
$return['native_balance'] = $this->convertAllBalances($others, $native, $date); // todo sum all and convert.
// Log::debug(sprintf('Set native_balance to %s', $return['native_balance']));
// if there is a request to convert, convert to "pc_balance" and use "balance" for whichever amount is in the primary currency.
if ($convertToPrimary) {
$return['primary_balance'] = $this->convertAllBalances($others, $primary, $date); // todo sum all and convert.
// Log::debug(sprintf('Set pc_balance to %s', $return['pc_balance']));
}
// either way, the balance is always combined with the virtual balance:
$virtualBalance = (string) ('' === (string) $account->virtual_balance ? '0' : $account->virtual_balance);
if ($convertToNative) {
// the native balance is combined with a converted virtual_balance:
if ($convertToPrimary) {
// the primary currency balance is combined with a converted virtual_balance:
$converter = new ExchangeRateConverter();
$nativeVirtualBalance = $converter->convert($currency, $native, $date, $virtualBalance);
$return['native_balance'] = bcadd($nativeVirtualBalance, $return['native_balance']);
// Log::debug(sprintf('Native virtual balance makes the native total %s', $return['native_balance']));
$pcVirtualBalance = $converter->convert($currency, $primary, $date, $virtualBalance);
$return['pc_balance'] = bcadd($pcVirtualBalance, $return['pc_balance']);
// Log::debug(sprintf('Primary virtual balance makes the primary total %s', $return['pc_balance']));
}
if (!$convertToNative) {
// if not, also increase the balance + native balance for consistency.
if (!$convertToPrimary) {
// if not, also increase the balance + primary balance for consistency.
$return['balance'] = bcadd($return['balance'], $virtualBalance);
// Log::debug(sprintf('Virtual balance makes the (native) total %s', $return['balance']));
// Log::debug(sprintf('Virtual balance makes the (primary currency) total %s', $return['balance']));
}
$final = array_merge($return, $others);
// Log::debug('Final balance is', $final);
@@ -436,7 +436,7 @@ class Steam
return $return;
}
private function convertAllBalances(array $others, TransactionCurrency $native, Carbon $date): string
private function convertAllBalances(array $others, TransactionCurrency $primary, Carbon $date): string
{
$total = '0';
$converter = new ExchangeRateConverter();
@@ -445,8 +445,8 @@ class Steam
if (null === $currency) {
continue;
}
$current = $converter->convert($currency, $native, $date, $amount);
Log::debug(sprintf('Convert %s %s to %s %s', $currency->code, $amount, $native->code, $current));
$current = $converter->convert($currency, $primary, $date, $amount);
Log::debug(sprintf('Convert %s %s to %s %s', $currency->code, $amount, $primary->code, $current));
$total = bcadd($current, $total);
}

View File

@@ -156,7 +156,7 @@ class AmountFormat extends AbstractExtension
/** @var null|TransactionCurrency $currency */
$currency = TransactionCurrency::whereCode($code)->first();
if (null === $currency) {
Log::error(sprintf('Could not find currency with code "%s". Fallback to native currency.', $code));
Log::error(sprintf('Could not find currency with code "%s". Fallback to primary currency.', $code));
$currency = Amount::getPrimaryCurrency();
Log::error(sprintf('Fallback currency is "%s".', $currency->code));
}

View File

@@ -75,30 +75,30 @@ class General extends AbstractExtension
Log::debug(sprintf('twig balance: Call finalAccountBalance with date/time "%s"', $date->toIso8601String()));
$info = Steam::finalAccountBalance($account, $date);
$currency = Steam::getAccountCurrency($account);
$default = Amount::getPrimaryCurrency();
$convertToNative = Amount::convertToPrimary();
$useNative = $convertToNative && $default->id !== $currency->id;
$currency ??= $default;
$primary = Amount::getPrimaryCurrency();
$convertToPrimary = Amount::convertToPrimary();
$usePrimary = $convertToPrimary && $primary->id !== $currency->id;
$currency ??= $primary;
$strings = [];
foreach ($info as $key => $balance) {
if ('balance' === $key) {
// balance in account currency.
if (!$useNative) {
if (!$usePrimary) {
$strings[] = app('amount')->formatAnything($currency, $balance, false);
}
continue;
}
if ('native_balance' === $key) {
// balance in native currency.
if ($useNative) {
$strings[] = app('amount')->formatAnything($default, $balance, false);
if ('pc_balance' === $key) {
// balance in primary currency.
if ($usePrimary) {
$strings[] = app('amount')->formatAnything($primary, $balance, false);
}
continue;
}
// for multi currency accounts.
if ($useNative && $key !== $default->code) {
if ($usePrimary && $key !== $primary->code) {
$strings[] = app('amount')->formatAnything(TransactionCurrency::where('code', $key)->first(), $balance, false);
}
}