This commit is contained in:
hackerESQ
2024-08-17 21:33:09 -05:00
parent 5d3259b653
commit b84bc94da6
8 changed files with 215 additions and 164 deletions
+6 -6
View File
@@ -12,7 +12,7 @@ class Holding extends Model
use HasFactory; use HasFactory;
use HasUuids; use HasUuids;
protected $with = []; protected $with = ['market_data'];
/** /**
* The attributes that are mass assignable. * The attributes that are mass assignable.
@@ -42,7 +42,7 @@ class Holding extends Model
]; ];
/** /**
* get market data for holding * Market data for holding
* *
* @return void * @return void
*/ */
@@ -52,7 +52,7 @@ class Holding extends Model
} }
/** /**
* get related transactions for holding * Related transactions for holding
* *
* @return void * @return void
*/ */
@@ -62,7 +62,7 @@ class Holding extends Model
} }
/** /**
* get related dividends for holding * Related dividends for holding
* *
* @return void * @return void
*/ */
@@ -72,7 +72,7 @@ class Holding extends Model
} }
/** /**
* get related portfolio for holding * Related portfolio for holding
* *
* @return void * @return void
*/ */
@@ -82,7 +82,7 @@ class Holding extends Model
} }
/** /**
* get related splits for holding * Related splits for holding
* *
* @return void * @return void
*/ */
+2 -30
View File
@@ -11,58 +11,30 @@ class Portfolio extends Model
use HasFactory; use HasFactory;
use HasUuids; use HasUuids;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [ protected $fillable = [
'title', 'title',
'notes', 'notes',
'wishlist', 'wishlist',
]; ];
/**
*
* @return void
*/
protected static function boot() protected static function boot()
{ {
parent::boot(); parent::boot();
static::saved(function ($model) { static::saved(function ($model) {
self::syncUsers($model); self::syncUsers($model);
}); });
} }
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = []; protected $hidden = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [ protected $casts = [
'wishlist' => 'boolean' 'wishlist' => 'boolean'
]; ];
/**
* The relationships that should always be eagerly loaded.
*
* @var array
*/
protected $with = ['users', 'transactions']; protected $with = ['users', 'transactions'];
/**
* The attributes that should be appended.
*
* @var array
*/
protected $appends = ['owner_id']; protected $appends = ['owner_id'];
public function users() public function users()
@@ -77,7 +49,7 @@ class Portfolio extends Model
public function transactions() public function transactions()
{ {
return $this->hasMany(Transaction::class); return $this->hasMany(Transaction::class)->orderBy('created_at', 'DESC');
} }
public function daily_change() public function daily_change()
+83 -77
View File
@@ -4,6 +4,7 @@ namespace App\Models;
use App\Models\MarketData; use App\Models\MarketData;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -12,121 +13,57 @@ class Transaction extends Model
use HasFactory; use HasFactory;
use HasUuids; use HasUuids;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [ protected $fillable = [
'symbol', 'symbol',
'date', 'date',
'portfolio_id',
'transaction_type', 'transaction_type',
'quantity', 'quantity',
'cost_basis', 'cost_basis',
'sale_price', 'sale_price'
'split'
]; ];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = []; protected $hidden = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [ protected $casts = [
'date' => 'datetime', 'date' => 'datetime',
'first_date' => 'datetime',
'last_date' => 'datetime',
'split' => 'boolean', 'split' => 'boolean',
]; ];
/**
*
* @return void
*/
protected static function boot() protected static function boot()
{ {
parent::boot(); parent::boot();
static::saving(function ($transaction) { static::saving(function ($transaction) {
// if sale, move cost basis to sale price
if ($transaction->transaction_type == 'SELL') { if ($transaction->transaction_type == 'SELL') {
$transaction->cost_basis = $transaction->holding->average_cost_basis ?? $transaction->cost_basis; $transaction->ensureCostBasisIsAddedToSale();
} }
}); });
static::saved(function ($transaction) { static::saved(function ($transaction) {
// static::syncHolding($transaction); $transaction->syncHolding();
}); });
static::deleted(function ($transaction) { static::deleted(function ($transaction) {
// static::syncHolding($transaction); $transaction->syncHolding();
}); });
} }
public static function syncHolding($transaction) { /**
// get the holding for a symbol and portfolio (or create one) * Ensure transaction symbol is always upper case
$holding = Holding::firstOrNew([ */
'portfolio_id' => $transaction->portfolio_id, protected function symbol(): Attribute
'symbol' => $transaction->symbol
], [
'portfolio_id' => $transaction->portfolio_id,
'symbol' => $transaction->symbol,
'quantity' => $transaction->quantity,
'average_cost_basis' => $transaction->cost_basis,
'total_cost_basis' => $transaction->quantity * $transaction->cost_basis,
]);
// pull existing transaction data
$query = self::where([
'portfolio_id' => $transaction->portfolio_id,
'symbol' => $transaction->symbol,
])->selectRaw('SUM(CASE WHEN transaction_type = "BUY" THEN quantity ELSE 0 END) AS `qty_purchases`')
->selectRaw('SUM(CASE WHEN transaction_type = "SELL" THEN quantity ELSE 0 END) AS `qty_sales`')
->selectRaw('SUM(CASE WHEN transaction_type = "BUY" THEN (quantity * cost_basis) ELSE 0 END) AS `cost_basis`')
->selectRaw('SUM(CASE WHEN transaction_type = "SELL" THEN ((sale_price - cost_basis) * quantity) ELSE 0 END) AS `realized_gains`')
->first();
$total_quantity = $query->qty_purchases - $query->qty_sales;
$average_cost_basis = $query->qty_purchases > 0
? $query->cost_basis / $query->qty_purchases
: 0;
// update holding
$holding->fill([
'quantity' => $total_quantity,
'average_cost_basis' => $average_cost_basis,
'total_cost_basis' => $total_quantity * $average_cost_basis,
'realized_gain_loss_dollars' => $query->realized_gains,
]);
$holding->save();
// load market data while we're here
$transaction->refreshMarketData();
// sync dividends to holding
$transaction->syncDividendsToHolding();
}
public function setSymbolAttribute($value)
{ {
$this->attributes['symbol'] = strtoupper($value); return Attribute::make(
set: fn (string $value) => strtoupper($value)
);
} }
/** /**
* get market data for transaction * Related market data for transaction
* *
* @return void * @return void
*/ */
@@ -136,7 +73,7 @@ class Transaction extends Model
} }
/** /**
* get portfolio for transaction * Related portfolio
* *
* @return void * @return void
*/ */
@@ -176,4 +113,73 @@ class Transaction extends Model
{ {
return Dividend::getDividendData($this->attributes['symbol']); return Dividend::getDividendData($this->attributes['symbol']);
} }
/**
* Writes average cost basis to a sale transaction
*
* @return Transaction
*/
public function ensureCostBasisIsAddedToSale()
{
$holding = Holding::firstOrNew([
'portfolio_id' => $this->portfolio_id,
'symbol' => $this->symbol
],[
'average_cost_basis' => null
]);
$this->cost_basis = $holding->average_cost_basis ?? 0;
return $this;
}
/**
* Syncs the holding related to this transaction
*
* @return void
*/
public function syncHolding() {
// get the holding for a symbol and portfolio (or create one)
$holding = Holding::firstOrNew([
'portfolio_id' => $this->portfolio_id,
'symbol' => $this->symbol
], [
'portfolio_id' => $this->portfolio_id,
'symbol' => $this->symbol,
'quantity' => $this->quantity,
'average_cost_basis' => $this->cost_basis,
'total_cost_basis' => $this->quantity * $this->cost_basis,
]);
// pull existing transaction data
$query = self::where([
'portfolio_id' => $this->portfolio_id,
'symbol' => $this->symbol,
])->selectRaw('SUM(CASE WHEN transaction_type = "BUY" THEN quantity ELSE 0 END) AS `qty_purchases`')
->selectRaw('SUM(CASE WHEN transaction_type = "SELL" THEN quantity ELSE 0 END) AS `qty_sales`')
->selectRaw('SUM(CASE WHEN transaction_type = "BUY" THEN (quantity * cost_basis) ELSE 0 END) AS `cost_basis`')
->selectRaw('SUM(CASE WHEN transaction_type = "SELL" THEN ((sale_price - cost_basis) * quantity) ELSE 0 END) AS `realized_gains`')
->first();
$total_quantity = $query->qty_purchases - $query->qty_sales;
$average_cost_basis = $query->qty_purchases > 0
? $query->cost_basis / $query->qty_purchases
: 0;
// update holding
$holding->fill([
'quantity' => $total_quantity,
'average_cost_basis' => $average_cost_basis,
'total_cost_basis' => $total_quantity * $average_cost_basis,
'realized_gain_loss_dollars' => $query->realized_gains,
]);
$holding->save();
// load market data while we're here
// $this->refreshMarketData();
// sync dividends to holding
// $this->syncDividendsToHolding();
}
} }
@@ -0,0 +1,9 @@
<div role="status" class="flex w-full animate-pulse" wire:loading.delay>
<div class="h-2.5 bg-gray-200 rounded-full dark:bg-gray-700 w-48 mb-4"></div>
<div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[360px] mb-2.5"></div>
<div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 mb-2.5"></div>
<div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[330px] mb-2.5"></div>
<div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[300px] mb-2.5"></div>
<div class="h-2 bg-gray-200 rounded-full dark:bg-gray-700 max-w-[360px]"></div>
<span class="sr-only">Loading...</span>
</div>
@@ -0,0 +1,68 @@
<?php
use App\Models\Portfolio;
use App\Models\Transaction;
use Illuminate\Support\Collection;
use Livewire\Volt\Component;
new class extends Component {
// props
public Portfolio $portfolio;
public array $sortBy = ['column' => 'symbol', 'direction' => 'asc'];
public array $headers;
public function mount()
{
$this->headers = [
['key' => 'symbol', 'label' => __('Symbol'), 'class' => ''],
['key' => 'market_data_name', 'label' => __('Name'), 'sortable' => true],
['key' => 'quantity', 'label' => __('Quantity')],
['key' => 'average_cost_basis', 'label' => __('Average Cost Basis')],
['key' => 'total_cost_basis', 'label' => __('Total Cost Basis')],
['key' => 'market_data_market_value', 'label' => __('Market Value')],
['key' => 'total_market_value', 'label' => __('Total Market Value')],
['key' => 'market_gain_loss_dollars', 'label' => __('Market Gain/Loss')],
['key' => 'market_gain_loss_percent', 'label' => __('Market Gain/Loss')],
['key' => 'realized_gain_loss_dollars', 'label' => __('Realized Gain/Loss')],
['key' => 'dividends_earned', 'label' => __('Dividends Earned')],
['key' => 'market_data_fifty_two_week_low', 'label' => __('52 week low')],
['key' => 'market_data_fifty_two_week_high', 'label' => __('52 week high')],
['key' => 'num_transactions', 'label' => __('Number of Transactions')],
['key' => 'market_data_updated_at', 'label' => __('Market Data Age')],
];
}
public function holdings(): Collection
{
return $this->portfolio
->holdings()
->with(['transactions' => function ($query) {
$query->portfolio($this->portfolio->id);
}])
->withCount(['transactions as num_transactions' => function ($query) {
$query->portfolio($this->portfolio->id);
}])
->withAggregate('market_data', 'name')
->withAggregate('market_data', 'market_value')
->withAggregate('market_data', 'fifty_two_week_low')
->withAggregate('market_data', 'fifty_two_week_high')
->withAggregate('market_data', 'updated_at')
->selectRaw('(market_data.market_value * holdings.quantity) AS total_market_value')
->selectRaw('((market_data.market_value - holdings.average_cost_basis) * holdings.quantity) AS market_gain_loss_dollars')
->selectRaw('(((market_data.market_value - holdings.average_cost_basis) / holdings.average_cost_basis) * 100) AS market_gain_loss_percent')
->join('market_data', 'holdings.symbol', 'market_data.symbol')
->orderBy(...array_values($this->sortBy))
->where('quantity', '>', 0)
->get();
}
}; ?>
<div class="">
<x-table wire:loading.remove :headers="$headers" :rows="$this->holdings()" :sort-by="$sortBy" />
</div>
@@ -21,16 +21,16 @@ new class extends Component {
#[Rule('required|string|in:BUY,SELL')] #[Rule('required|string|in:BUY,SELL')]
public String $transaction_type; public String $transaction_type;
#[Rule('required|date')] #[Rule('required|date_format:Y-m-d')]
public String $date; public String $date;
#[Rule('required|numeric')] #[Rule('required|min:0|numeric')]
public Float $quantity; public Float $quantity;
#[Rule('exclude_if:transaction_type,SELL|numeric')] #[Rule('exclude_if:transaction_type,SELL|min:0|numeric')]
public ?Float $cost_basis; public ?Float $cost_basis;
#[Rule('exclude_if:transaction_type,BUY|numeric')] #[Rule('exclude_if:transaction_type,BUY|min:0|numeric')]
public ?Float $sale_price; public ?Float $sale_price;
public Bool $confirmingTransactionDeletion = false; public Bool $confirmingTransactionDeletion = false;
@@ -8,7 +8,6 @@ use Livewire\Volt\Component;
new class extends Component { new class extends Component {
// props // props
public ?Collection $transactions;
public Portfolio $portfolio; public Portfolio $portfolio;
public ?Transaction $editingTransaction; public ?Transaction $editingTransaction;
@@ -23,38 +22,39 @@ new class extends Component {
<div class=""> <div class="">
@foreach($transactions as $transaction) @foreach($portfolio->transactions->take(10) as $transaction)
<div x-data="{ loading: false, timeout: null }">
<x-list-item <x-list-item
no-separator no-separator
:item="$transaction" :item="$transaction"
class="cursor-pointer" class="cursor-pointer"
@click=" x-data="{ loading: false, timeout: null }"
timeout = setTimeout(() => { loading = true }, 200); @click="
$wire.showTransactionDialog('{{ $transaction->id }}').then(() => { timeout = setTimeout(() => { loading = true }, 200);
clearTimeout(timeout); $wire.showTransactionDialog('{{ $transaction->id }}').then(() => {
loading = false; clearTimeout(timeout);
}) loading = false;
" })
> "
<x-slot:value class="flex items-center"> >
<x-badge <x-slot:value class="flex items-center">
:value="$transaction->transaction_type" <x-badge
class="{{ $transaction->transaction_type == 'BUY' :value="$transaction->transaction_type"
? 'badge-success' class="{{ $transaction->transaction_type == 'BUY'
: 'badge-error' }} badge-sm mr-3" ? 'badge-success'
/> : 'badge-error' }} badge-sm mr-3"
{{ $transaction->date->format('M j, Y') }} />
{{ $transaction->symbol }} {{ $transaction->date->format('M j, Y') }}
({{ $transaction->quantity }} {{ $transaction->symbol }}
@ {{ $transaction->transaction_type == 'BUY' ({{ $transaction->quantity }}
? Number::currency($transaction->cost_basis) @ {{ $transaction->transaction_type == 'BUY'
: Number::currency($transaction->sale_price) }}) ? Number::currency($transaction->cost_basis)
: Number::currency($transaction->sale_price) }})
<x-loading x-show="loading" x-cloak class="text-gray-400 ml-2" />
</x-slot:value>
</x-list-item>
<x-loading x-show="loading" x-cloak class="text-gray-400 ml-2" />
</x-slot:value>
</x-list-item>
</div>
@endforeach @endforeach
<x-ib-modal <x-ib-modal
+11 -15
View File
@@ -84,6 +84,15 @@
<div class="mt-6 grid md:grid-cols-7 gap-5"> <div class="mt-6 grid md:grid-cols-7 gap-5">
<x-ib-card title="{{ __('Holdings') }}" class="md:col-span-4"> <x-ib-card title="{{ __('Holdings') }}" class="md:col-span-4">
@livewire('holdings-table', [
'portfolio' => $portfolio
])
</x-ib-card>
{{-- <x-ib-card title="{{ __('Top performers') }}" class="md:col-span-3">
@php @php
$users = App\Models\User::take(3)->get(); $users = App\Models\User::take(3)->get();
@@ -93,19 +102,7 @@
<x-list-item no-separator :item="$user" avatar="profile_photo_url" link="/docs/installation" /> <x-list-item no-separator :item="$user" avatar="profile_photo_url" link="/docs/installation" />
@endforeach @endforeach
</x-ib-card> </x-ib-card> --}}
<x-ib-card title="{{ __('Top performers') }}" class="md:col-span-3">
@php
$users = App\Models\User::take(3)->get();
@endphp
@foreach($users as $user)
<x-list-item no-separator :item="$user" avatar="profile_photo_url" link="/docs/installation" />
@endforeach
</x-ib-card>
{{-- <x-ib-card title="{{ __('Top headlines') }}" class="md:col-span-3"> {{-- <x-ib-card title="{{ __('Top headlines') }}" class="md:col-span-3">
@@ -119,10 +116,9 @@
</x-ib-card> --}} </x-ib-card> --}}
<x-ib-card title="{{ __('Recent activity') }}" class="md:col-span-4"> <x-ib-card title="{{ __('Recent activity') }}" class="md:col-span-3">
@livewire('transactions-list', [ @livewire('transactions-list', [
'transactions' => $portfolio->transactions,
'portfolio' => $portfolio 'portfolio' => $portfolio
]) ])