Update Dividend.php (#176)

* Adds a second join condition requiring holdings.symbol = dividends.symbol. 
Without this, the join only matches on portfolio_id, which could incorrectly associate dividends with holdings of a different symbol within the same portfolio.

* Add test

---------

Co-authored-by: hackerESQ <corey@coreyvarma.com>
This commit is contained in:
Carlos E. Barboza
2026-03-15 17:00:29 -05:00
committed by GitHub
parent 401b0eef91
commit 6bc174a87b
2 changed files with 26 additions and 5 deletions
+8 -5
View File
@@ -146,16 +146,19 @@ class Dividend extends Model
'dividends.symbol',
'dividends.dividend_amount',
])->selectRaw("
(COALESCE(SUM(CASE WHEN transactions.transaction_type = 'BUY'
AND date(transactions.date) <= date(dividends.date)
(COALESCE(SUM(CASE WHEN transactions.transaction_type = 'BUY'
AND date(transactions.date) <= date(dividends.date)
THEN transactions.quantity ELSE 0 END), 0)
- COALESCE(SUM(CASE WHEN transactions.transaction_type = 'SELL'
AND date(transactions.date) <= date(dividends.date)
- COALESCE(SUM(CASE WHEN transactions.transaction_type = 'SELL'
AND date(transactions.date) <= date(dividends.date)
THEN transactions.quantity ELSE 0 END), 0))
* dividends.dividend_amount
AS total_received
")->join('transactions', 'transactions.symbol', '=', 'dividends.symbol')
->join('holdings', 'transactions.portfolio_id', '=', 'holdings.portfolio_id')
->join('holdings', function ($join) {
$join->on('transactions.portfolio_id', '=', 'holdings.portfolio_id')
->on('holdings.symbol', '=', 'dividends.symbol');
})
->where('dividends.symbol', $symbol)
->groupBy('holdings.portfolio_id', 'dividends.date', 'dividends.symbol', 'dividends.dividend_amount', 'dividends.dividend_amount_base');
+18
View File
@@ -89,4 +89,22 @@ class DividendsTest extends TestCase
$this->assertEquals(4.95, $holdingOne->dividends_earned);
$this->assertEquals(8, $holdingTwo->dividends_earned);
}
public function test_dividend_earnings_not_shared_in_same_portfolio_with_multiple_symbols(): void
{
$this->actingAs($user = User::factory()->create());
$portfolio = Portfolio::factory()->create();
Transaction::factory()->buy()->yearsAgo()->portfolio($portfolio->id)->symbol('ACME')->create();
Transaction::factory()->buy()->yearsAgo()->portfolio($portfolio->id)->symbol('GOOG')->create();
Dividend::refreshDividendData('ACME');
$acmeHolding = Holding::query()->portfolio($portfolio->id)->symbol('ACME')->first();
$googHolding = Holding::query()->portfolio($portfolio->id)->symbol('GOOG')->first();
$this->assertEquals(4.95, $acmeHolding->dividends_earned);
$this->assertEquals(0, $googHolding->dividends_earned);
}
}