fix: calculate proper cost basis

This commit is contained in:
hackerESQ
2025-07-21 20:28:39 -05:00
parent 81af737204
commit 8e0d792d26
+8 -2
View File
@@ -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;
}