From 8e0d792d26e2b4c296a3c703d97f570bfd4d5019 Mon Sep 17 00:00:00 2001 From: hackerESQ Date: Mon, 21 Jul 2025 20:28:39 -0500 Subject: [PATCH] fix: calculate proper cost basis --- app/Actions/EnsureCostBasisAddedToSale.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/Actions/EnsureCostBasisAddedToSale.php b/app/Actions/EnsureCostBasisAddedToSale.php index b0efbe2..8908654 100644 --- a/app/Actions/EnsureCostBasisAddedToSale.php +++ b/app/Actions/EnsureCostBasisAddedToSale.php @@ -14,12 +14,18 @@ class EnsureCostBasisAddedToSale // cost basis is required for sales to calculate realized gains if ($model->transaction_type == 'SELL') { - $average_cost_basis = Transaction::where([ + $cost_basis = Transaction::where([ 'portfolio_id' => $model->portfolio_id, 'symbol' => $model->symbol, 'transaction_type' => 'BUY', ])->whereDate('date', '<=', $model->date) - ->average('cost_basis'); + ->selectRaw('SUM(transactions.cost_basis * transactions.quantity) as total_cost_basis') + ->selectRaw('SUM(transactions.quantity) as total_quantity') + ->first(); + + $average_cost_basis = empty($cost_basis->total_quantity) + ? 0 + : $cost_basis->total_cost_basis / $cost_basis->total_quantity; $model->cost_basis = $average_cost_basis ?? 0; }