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; }