Files
investbrain/tests/TransactionsTest.php
T

71 lines
1.9 KiB
PHP
Raw Normal View History

2024-09-06 19:39:04 -05:00
<?php
namespace Tests;
2024-09-06 21:59:58 -05:00
use App\Models\Holding;
2024-09-06 19:39:04 -05:00
use App\Models\Portfolio;
use App\Models\Transaction;
2025-01-28 17:14:49 -06:00
use App\Models\User;
2024-09-06 19:39:04 -05:00
use Illuminate\Foundation\Testing\RefreshDatabase;
class TransactionsTest extends TestCase
{
use RefreshDatabase;
2024-09-06 21:59:58 -05:00
2024-09-06 19:39:04 -05:00
public function test_can_create_a_transaction(): void
{
2024-09-06 21:59:58 -05:00
$this->actingAs($user = User::factory()->create());
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
$transaction = Transaction::factory()->create();
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
$this->assertNotNull($transaction);
}
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
public function test_sales_calculate_cost_basis(): void
{
$this->actingAs($user = User::factory()->create());
2024-09-06 19:39:04 -05:00
Transaction::factory(5)->buy()->lastYear()->symbol('AAPL')->create();
2024-09-06 19:39:04 -05:00
$transaction = Transaction::factory()->sell()->lastMonth()->symbol('AAPL')->create();
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
$this->assertNotNull($transaction->cost_basis);
}
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
public function test_purchases_dont_have_sale_price(): void
{
$this->actingAs($user = User::factory()->create());
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
$transaction = Transaction::factory()->buy()->create();
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
$this->assertNull($transaction->sale_price);
}
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
public function test_transaction_synced_to_holding(): void
{
$this->actingAs($user = User::factory()->create());
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
$portfolio = Portfolio::factory()->create();
2024-09-06 19:39:04 -05:00
Transaction::factory(5)->buy()->lastYear()->portfolio($portfolio->id)->symbol('AAPL')->create();
$transaction = Transaction::factory()->sell()->lastMonth()->portfolio($portfolio->id)->symbol('AAPL')->create();
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
$this->assertDatabaseHas('holdings', [
'portfolio_id' => $portfolio->id,
'symbol' => 'AAPL',
2025-01-28 17:14:49 -06:00
'quantity' => 4,
2024-09-06 21:59:58 -05:00
]);
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
$holding = Holding::where([
'portfolio_id' => $portfolio->id,
2025-01-28 17:14:49 -06:00
'symbol' => 'AAPL',
2024-09-06 21:59:58 -05:00
])->first();
2024-09-06 19:39:04 -05:00
2024-09-06 21:59:58 -05:00
$this->assertEqualsWithDelta(
2025-01-28 17:14:49 -06:00
$holding->realized_gain_dollars,
$transaction->sale_price - $transaction->cost_basis,
2024-09-06 21:59:58 -05:00
0.01
);
}
}