Files
investbrain/app/Models/Transaction.php
T

213 lines
5.9 KiB
PHP
Raw Normal View History

2024-08-10 13:30:19 -05:00
<?php
namespace App\Models;
use App\Models\MarketData;
2024-08-24 22:19:40 -05:00
use Illuminate\Support\Arr;
2024-08-10 13:30:19 -05:00
use Illuminate\Database\Eloquent\Model;
2024-08-17 21:33:09 -05:00
use Illuminate\Database\Eloquent\Casts\Attribute;
2024-08-15 21:35:43 -05:00
use Illuminate\Database\Eloquent\Concerns\HasUuids;
2024-08-10 13:30:19 -05:00
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Transaction extends Model
{
use HasFactory;
2024-08-15 21:35:43 -05:00
use HasUuids;
2024-08-10 13:30:19 -05:00
protected $fillable = [
'symbol',
'date',
'transaction_type',
'quantity',
'cost_basis',
2024-08-17 21:33:09 -05:00
'sale_price'
2024-08-10 13:30:19 -05:00
];
protected $hidden = [];
protected $casts = [
'date' => 'datetime',
'split' => 'boolean',
];
protected static function boot()
{
parent::boot();
2024-08-15 21:35:43 -05:00
static::saving(function ($transaction) {
2024-08-10 13:30:19 -05:00
2024-08-15 21:35:43 -05:00
if ($transaction->transaction_type == 'SELL') {
2024-08-17 21:33:09 -05:00
$transaction->ensureCostBasisIsAddedToSale();
2024-08-15 21:35:43 -05:00
}
2024-08-10 13:30:19 -05:00
});
2024-08-15 21:35:43 -05:00
static::saved(function ($transaction) {
2024-08-17 21:33:09 -05:00
$transaction->syncHolding();
2024-08-21 20:42:32 -05:00
cache()->tags(['metrics', auth()->user()->id])->flush();
2024-08-15 21:35:43 -05:00
});
static::deleted(function ($transaction) {
2024-08-17 21:33:09 -05:00
$transaction->syncHolding();
2024-08-21 20:42:32 -05:00
cache()->tags(['metrics', auth()->user()->id])->flush();
2024-08-10 13:30:19 -05:00
});
}
2024-08-17 21:33:09 -05:00
/**
* Ensure transaction symbol is always upper case
*/
protected function symbol(): Attribute
2024-08-10 13:30:19 -05:00
{
2024-08-17 21:33:09 -05:00
return Attribute::make(
set: fn (string $value) => strtoupper($value)
);
2024-08-10 13:30:19 -05:00
}
/**
2024-08-17 21:33:09 -05:00
* Related market data for transaction
2024-08-10 13:30:19 -05:00
*
* @return void
*/
public function market_data()
{
return $this->hasOne(MarketData::class, 'symbol', 'symbol');
}
/**
2024-08-17 21:33:09 -05:00
* Related portfolio
2024-08-10 13:30:19 -05:00
*
* @return void
*/
public function portfolio()
{
return $this->belongsTo(Portfolio::class);
}
2024-08-28 15:19:20 -05:00
public function scopeWithMarketData($query)
{
$query->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')
->join('market_data', 'transactions.symbol', 'market_data.symbol');
}
2024-08-10 13:30:19 -05:00
public function scopePortfolio($query, $portfolio)
{
return $query->where('portfolio_id', $portfolio);
}
public function scopeSymbol($query, $symbol)
{
return $query->where('symbol', $symbol);
}
2024-08-28 22:06:47 -05:00
public function scopeMyTransactions()
{
return $this->whereHas('portfolio', function ($query) {
$query->whereHas('users', function ($query) {
$query->where('id', auth()->id());
});
});
}
2024-08-10 13:30:19 -05:00
public function refreshMarketData()
{
return MarketData::getMarketData($this->attributes['symbol']);
}
// public function syncDividendsToHolding()
// {
// return Dividend::syncHoldings(['symbol' => $this->attributes['symbol']]);
// }
2024-08-10 13:30:19 -05:00
// public function refreshDividends()
// {
// return Dividend::getDividendData($this->attributes['symbol']);
// }
2024-08-17 21:33:09 -05:00
/**
* Writes average cost basis to a sale transaction
*
* @return Transaction
*/
public function ensureCostBasisIsAddedToSale()
{
2024-08-27 21:17:54 -05:00
$average_cost_basis = Transaction::where([
2024-08-17 21:33:09 -05:00
'portfolio_id' => $this->portfolio_id,
2024-08-27 21:17:54 -05:00
'symbol' => $this->symbol,
'transaction_type' => 'BUY',
])->whereDate('date', '<=', $this->date)
->average('cost_basis');
2024-08-17 21:33:09 -05:00
2024-08-27 21:17:54 -05:00
$this->cost_basis = $average_cost_basis ?? 0;
2024-08-17 21:33:09 -05:00
return $this;
}
/**
* Syncs the holding related to this transaction
*
* @return void
*/
public function syncHolding() {
2024-08-24 22:19:40 -05:00
// sync previous symbol too
if (Arr::has($this->changes, 'symbol')) {
$temp = new Transaction;
$temp->symbol = $this->original['symbol'];
$temp->portfolio_id = $this->portfolio_id;
$temp->syncHolding();
}
2024-08-17 21:33:09 -05:00
// 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,
2024-08-21 20:42:32 -05:00
'realized_gain_dollars' => $query->realized_gains,
2024-08-17 21:33:09 -05:00
]);
$holding->save();
// load market data while we're here
$this->refreshMarketData();
2024-08-17 21:33:09 -05:00
// // sync dividends to holding
2024-08-17 21:33:09 -05:00
// $this->syncDividendsToHolding();
}
2024-08-10 13:30:19 -05:00
}