Feat: Adds multi currency support (#88)

This commit is contained in:
hackerESQ
2025-04-09 19:25:15 -05:00
committed by GitHub
parent 6d6f968f42
commit eae345f243
100 changed files with 17735 additions and 35761 deletions
@@ -0,0 +1,246 @@
<?php
use App\Models\Currency;
use App\Models\MarketData;
use App\Models\Portfolio;
use App\Models\Transaction;
use App\Rules\QuantityValidationRule;
use App\Rules\SymbolValidationRule;
use App\Traits\WithTrimStrings;
use Illuminate\Support\Collection;
use Livewire\Volt\Component;
use Mary\Traits\Toast;
new class extends Component
{
use Toast;
use WithTrimStrings;
// props
public ?Portfolio $portfolio;
public ?Transaction $transaction;
public ?string $portfolio_id;
public string $symbol;
public string $transaction_type;
public string $date;
public float $quantity;
public ?float $cost_basis;
public ?float $sale_price;
public bool $confirmingTransactionDeletion = false;
public Collection $currencies;
public string $currency;
// methods
public function rules()
{
return [
'symbol' => ['required', 'string', new SymbolValidationRule],
'transaction_type' => 'required|string|in:BUY,SELL',
'portfolio_id' => 'required|exists:portfolios,id',
'date' => ['required', 'date_format:Y-m-d', 'before_or_equal:'.now()->toDateString()],
'quantity' => [
'required',
'numeric',
'gt:0',
new QuantityValidationRule($this->portfolio, $this->symbol, $this->transaction_type, $this->date),
],
'currency' => ['required', 'exists:currencies,currency'],
'cost_basis' => 'exclude_if:transaction_type,SELL|min:0|numeric',
'sale_price' => 'exclude_if:transaction_type,BUY|min:0|numeric',
];
}
public function mount()
{
$this->currencies = Currency::list();
$this->currency = auth()->user()->getCurrency();
if (isset($this->transaction)) {
$this->currency = $this->transaction->market_data->currency;
$this->symbol = $this->transaction->symbol;
$this->transaction_type = $this->transaction->transaction_type;
$this->portfolio_id = $this->transaction->portfolio_id;
$this->date = $this->transaction->date->toDateString();
$this->quantity = $this->transaction->quantity;
$this->cost_basis = $this->transaction->cost_basis;
$this->sale_price = $this->transaction->sale_price;
} else {
if (isset($this->symbol)) {
$this->currency = MarketData::getMarketData($this->symbol)?->currency;
}
$this->transaction_type = 'BUY';
$this->portfolio_id = isset($this->portfolio) ? $this->portfolio->id : '';
$this->date = now()->toDateString();
}
}
public function update()
{
$this->authorize('fullAccess', $this->portfolio);
$this->transaction->update($this->validate());
$this->transaction->save();
$this->success(__('Transaction updated'));
$this->dispatch('toggle-manage-transaction');
$this->dispatch('transaction-updated');
}
public function save()
{
if (! isset($this->portfolio)) {
$this->portfolio = Portfolio::find($this->portfolio_id);
}
$this->authorize('fullAccess', $this->portfolio);
$validated = $this->validate();
$transaction = $this->portfolio->transactions()->create($validated);
$transaction->save();
$this->dispatch('transaction-saved');
$this->success(__('Transaction created'), redirectTo: route('holding.show', ['portfolio' => $this->portfolio->id, 'symbol' => $transaction->symbol]));
}
public function delete()
{
$this->authorize('fullAccess', $this->portfolio);
$this->transaction->delete();
$this->success(__('Transaction deleted'), redirectTo: route('holding.show', ['portfolio' => $this->portfolio->id, 'symbol' => $this->symbol]));
}
}; ?>
<div class="" x-data="{ transaction_type: @entangle('transaction_type') }">
<x-ib-form wire:submit="{{ $transaction ? 'update' : 'save' }}" class="">
@if(empty($portfolio))
<x-select
label="{{ __('Portfolio') }}"
wire:model="portfolio_id"
required
:options="auth()->user()->portfolios()->fullAccess()->get()"
option-label="title"
placeholder="Select a portfolio"
/>
@endif
<x-input label="{{ __('Symbol') }}" wire:model="symbol" required />
<x-select label="{{ __('Transaction Type') }}" :options="[
['id' => 'BUY', 'name' => 'Buy'],
['id' => 'SELL', 'name' => 'Sell']
]" wire:model.live="transaction_type" />
<x-datetime label="{{ __('Transaction Date') }}" wire:model="date" required />
<x-input label="{{ __('Quantity') }}" type="number" step="any" wire:model="quantity" required />
@if($transaction_type == 'SELL')
<x-input
label="{{ __('Sale Price') }}"
wire:model.number="sale_price"
required
type="number"
step="any"
>
<x-slot:prepend>
<x-select
class="rounded-e-none border-e-0 bg-base-200"
icon="o-banknotes"
:options="$currencies"
option-value="currency"
option-label="currency"
wire:model="currency"
id="currency"
/>
</x-slot:prepend>
</x-input>
@else
<x-input
label="{{ __('Cost Basis') }}"
wire:model.number="cost_basis"
required
type="number"
step="any"
>
<x-slot:prepend>
<x-select
class="rounded-e-none border-e-0 bg-base-200"
icon="o-banknotes"
:options="$currencies"
option-value="currency"
option-label="currency"
wire:model="currency"
id="currency"
/>
</x-slot:prepend>
</x-input>
@endif
<x-slot:actions>
@if ($transaction)
<x-button
wire:click="$toggle('confirmingTransactionDeletion')"
wire:loading.attr="disabled"
class="btn text-error"
title="{{ __('Delete Transaction') }}"
label="{{ __('Delete Transaction') }}"
/>
@endif
<x-button
label="{{ $transaction ? __('Update') : __('Create') }}"
type="submit"
icon="o-paper-airplane"
class="btn-primary"
spinner="{{ $transaction ? 'update' : 'save' }}"
/>
</x-slot:actions>
</x-ib-form>
<x-confirmation-modal wire:model.live="confirmingTransactionDeletion">
<x-slot name="title">
{{ __('Delete Transaction') }}
</x-slot>
<x-slot name="content">
{{ __('Are you sure you want to delete this transaction?') }}
</x-slot>
<x-slot name="footer">
<x-button class="btn-outline" wire:click="$toggle('confirmingTransactionDeletion')" wire:loading.attr="disabled">
{{ __('Cancel') }}
</x-secondary-button>
<x-button class="ms-3 btn-error text-white" wire:click="delete" wire:loading.attr="disabled">
{{ __('Delete Transaction') }}
</x-button>
</x-slot>
</x-confirmation-modal>
</div>
@@ -0,0 +1,154 @@
<?php
use App\Models\Portfolio;
use App\Models\Transaction;
use Illuminate\Support\Collection;
use Livewire\Volt\Component;
use Mary\Traits\Toast;
new class extends Component
{
use Toast;
// props
public Collection $transactions;
public ?Portfolio $portfolio;
public ?Transaction $editingTransaction;
public bool $shouldGoToHolding = true;
public bool $showPortfolio = false;
public bool $paginate = true;
public int $perPage = 5;
public int $offset = 0;
protected $listeners = [
'transaction-updated' => '$refresh',
'transaction-saved' => '$refresh',
];
// methods
public function showTransactionDialog($transactionId)
{
if (! auth()->user()->can('fullAccess', $this->portfolio)) {
$this->error(__('You do not have permission to manage transactions for this portfolio'));
return;
}
$this->editingTransaction = Transaction::findOrFail($transactionId);
$this->dispatch('toggle-manage-transaction');
}
public function goToHolding($holding)
{
return $this->redirect(route('holding.show', ['portfolio' => $holding['portfolio_id'], 'symbol' => $holding['symbol']]));
}
public function updateOffset($amount = 0)
{
$this->offset = $this->offset + $amount;
}
}; ?>
<div class="">
@foreach($transactions->sortByDesc('date')->slice($offset)->take($perPage) as $transaction)
<x-list-item
no-separator
:item="$transaction"
class="cursor-pointer"
x-data="{ loading: false, timeout: null }"
:key="$transaction->id"
@click="
if ($wire.shouldGoToHolding) {
$wire.goToHolding({{ $transaction }})
return;
}
timeout = setTimeout(() => { loading = true }, 200);
$wire.showTransactionDialog('{{ $transaction->id }}').then(() => {
clearTimeout(timeout);
loading = false;
})
"
>
<x-slot:value class="flex items-center">
<x-badge
:value="$transaction->split
? 'SPLIT'
: ($transaction->reinvested_dividend
? 'REINVEST'
: $transaction->transaction_type)"
class="{{ $transaction->transaction_type == 'BUY'
? 'badge-success'
: 'badge-error' }} badge-sm mr-3"
/>
{{ $transaction->symbol }}
({{ $transaction->quantity }}
@ {{ Number::currency(
$transaction->transaction_type == 'BUY'
? $transaction->cost_basis
: $transaction->sale_price,
$transaction->market_data->currency
) }})
<x-loading x-show="loading" x-cloak class="text-gray-400 ml-2" />
</x-slot:value>
<x-slot:sub-value>
@if($showPortfolio)
<span title="{{ __('Portfolio') }}">{{ $transaction->portfolio->title }} </span>
&middot;
@endif
<span title="{{ __('Transaction Date') }}">{{ $transaction->date->format('F j, Y') }} </span>
</x-slot:sub-value>
</x-list-item>
@endforeach
@if ($paginate && count($transactions) > $perPage)
<div class="flex justify-between">
<span>
@if($offset > 0)
<x-button
class="btn btn-sm btn-ghost text-secondary"
wire:click="updateOffset(-{{ $perPage }})"
>
{!! __('pagination.previous') !!}
</x-button>
@endif
</span>
<span>
@if(count($transactions) - $offset > $offset)
<x-button
class="btn btn-sm btn-ghost text-secondary"
wire:click="updateOffset({{ $perPage }})"
>
{!! __('pagination.next') !!}
</x-button>
@endif
</span>
</div>
@endif
<x-ib-alpine-modal
key="manage-transaction"
title="{{ __('Manage Transaction') }}"
>
@livewire('manage-transaction-form', [
'portfolio' => $portfolio,
'transaction' => $editingTransaction,
], key($editingTransaction?->id.rand()))
</x-ib-alpine-modal>
</div>
@@ -0,0 +1,124 @@
<?php
use App\Models\Transaction;
use App\Models\User;
use Livewire\Volt\Component;
use Livewire\WithPagination;
use App\Models\Currency;
new class extends Component
{
use WithPagination;
// props
public User $user;
public ?Transaction $editingTransaction;
protected $listeners = [
'transaction-updated' => '$refresh',
'transaction-saved' => '$refresh',
];
public array $sortBy = ['column' => 'date', 'direction' => 'desc'];
public array $headers;
// methods
public function goToHolding($holding)
{
return $this->redirect(route('holding.show', ['portfolio' => $holding['portfolio_id'], 'symbol' => $holding['symbol']]));
}
public function mount()
{
$this->headers = [
['key' => 'date', 'label' => __('Date'), 'sortable' => true],
['key' => 'portfolio_title', 'label' => __('Portfolio')],
['key' => 'symbol', 'label' => __('Symbol'), 'class' => ''],
['key' => 'market_data_name', 'label' => __('Name')],
['key' => 'transaction_type', 'label' => __('Type')],
['key' => 'split', 'label' => __('Split')],
['key' => 'quantity', 'label' => __('Quantity')],
['key' => 'cost_basis', 'label' => __('Cost Basis')],
['key' => 'gain_dollars', 'label' => __('Gain/Loss')],
];
}
public function transactions()
{
return auth()
->user()
->transactions()
->orderBy(...array_values($this->sortBy))
->paginate(10);
}
}; ?>
<div class="">
<x-table
:headers="$headers"
:rows="$this->transactions()"
x-data="{ loadingId: null, timeout: null }"
@row-click="
timeout = setTimeout(() => { loadingId = $event.detail.id }, 200);
$wire.goToHolding($event.detail).then(() => {
clearTimeout(timeout);
loadingId = null;
})
"
:sort-by="$sortBy"
with-pagination
>
@scope('cell_symbol', $row)
<span class="flex">
{{ $row->symbol }}
<x-loading x-show="loadingId === '{{ $row->id }}'" x-cloak class="text-gray-400 ml-2" />
</span>
@endscope
@scope('cell_date', $row)
{{ $row->date->format('M d, Y') }}
@endscope
@scope('cell_split', $row)
{{ $row->split ? __('Yes') : '' }}
@endscope
@scope('cell_transaction_type', $row)
<x-badge
:value="$row->split
? 'SPLIT'
: ($row->reinvested_dividend
? 'REINVEST'
: $row->transaction_type)"
class="{{ $row->transaction_type == 'BUY'
? 'badge-success'
: 'badge-error' }} badge-sm mr-3"
/>
@endscope
@scope('cell_cost_basis', $row)
{{ Number::currency($row->cost_basis ?? 0, $row->market_data->currency) }}
@endscope
@scope('cell_total_cost_basis', $row)
{{ Number::currency($row->total_cost_basis ?? 0, $row->market_data->currency) }}
@endscope
@scope('cell_gain_dollars', $row)
{{ Number::currency($row->gain_dollars ?? 0, $row->market_data->currency) }}
@endscope
@scope('cell_market_data_market_value', $row)
{{ Number::currency($row->market_data_market_value ?? 0, $row->market_data->currency) }}
@endscope
@scope('cell_total_market_value', $row)
{{ Number::currency($row->total_market_value ?? 0, $row->market_data->currency) }}
@endscope
</x-table>
<x-ib-alpine-modal
key="manage-transaction"
title="Manage Transaction"
>
@livewire('manage-transaction-form', [
'transaction' => $editingTransaction,
], key($editingTransaction->id ?? 'new'))
</x-ib-alpine-modal>
</div>