diff --git a/app/Models/Dividend.php b/app/Models/Dividend.php index ebf6d40..b53b7d9 100644 --- a/app/Models/Dividend.php +++ b/app/Models/Dividend.php @@ -27,7 +27,7 @@ class Dividend extends Model protected $casts = [ 'date' => 'datetime', - 'last_date' => 'datetime', + 'last_dividend_update' => 'datetime', ]; public function marketData() { @@ -55,22 +55,22 @@ class Dividend extends Model { $dividends_meta = self::where(['symbol' => $symbol]) ->selectRaw('COUNT(symbol) as total_dividends') - ->selectRaw('MAX(date) as last_date') + ->selectRaw('MAX(created_at) as last_dividend_update') ->get() ->first(); // assume we need to populate ALL dividend data - $start_date = new \DateTime('@0'); + $start_date = new Carbon('@0'); $end_date = now(); // nope, refresh forward looking only if ( $dividends_meta->total_dividends ) { - - $start_date = $dividends_meta->last_date->addHours(24); + + $start_date = $dividends_meta->last_dividend_update->addHours(24); } - + // skip refresh if there's already recent data - if ($start_date >= $end_date) { + if ($start_date->greaterThan($end_date)) { return; } diff --git a/tests/DividendsTest.php b/tests/DividendsTest.php index d264e3e..7478869 100644 --- a/tests/DividendsTest.php +++ b/tests/DividendsTest.php @@ -61,4 +61,26 @@ class DividendsTest extends TestCase $this->assertCount(3, $transactions); $this->assertEqualsWithDelta(4.95, $dividendsReinvested * $market_data->market_value, 0.01); } + + /** + */ + public function test_do_not_duplicate_recent_dividends(): void + { + $this->actingAs($user = User::factory()->create()); + + $portfolio = Portfolio::factory()->create(); + Transaction::factory()->buy()->yearsAgo()->portfolio($portfolio->id)->symbol('ACME')->create(); + + $holding = Holding::query()->portfolio($portfolio->id)->symbol('ACME')->first(); + + Dividend::create([ + 'symbol' => 'ACME', + 'date' => now()->subDay(2), + 'dividend_amount' => .01 + ]); + + Dividend::refreshDividendData('ACME'); + + $this->assertCount(1, $holding->dividends); + } }