diff --git a/app/Http/Requests/Concerns/ValidatesAccountDetailRules.php b/app/Http/Requests/Concerns/ValidatesAccountDetailRules.php index ff753b30..cc0325d2 100644 --- a/app/Http/Requests/Concerns/ValidatesAccountDetailRules.php +++ b/app/Http/Requests/Concerns/ValidatesAccountDetailRules.php @@ -24,7 +24,10 @@ trait ValidatesAccountDetailRules ], 'address' => ['nullable', 'string', 'max:500'], 'purchase_price' => ['nullable', 'integer', 'min:0'], - 'purchase_date' => ['nullable', 'date', 'before_or_equal:today'], + // Floor the date: a mistyped/ancient year would make the historical + // balance generator build a multi-century monthly series and OOM the + // queue worker (PHP-LARAVEL-49). 1900 rejects typos, not real assets. + 'purchase_date' => ['nullable', 'date', 'after_or_equal:1900-01-01', 'before_or_equal:today'], 'area_value' => ['nullable', 'numeric', 'min:0', 'max:99999999.99'], 'area_unit' => ['nullable', 'string', Rule::in(['sqm', 'sqft', 'acres', 'hectares'])], 'linked_loan_account_id' => [ @@ -52,7 +55,9 @@ trait ValidatesAccountDetailRules return [ 'annual_interest_rate' => ['nullable', 'numeric', 'min:0', 'max:100'], 'loan_term_months' => ['nullable', 'integer', 'min:1', 'max:600'], - 'loan_start_date' => ['nullable', 'date'], + // Floor the date for the same reason as purchase_date above: an + // ancient loan start date OOMs the balance generator (PHP-LARAVEL-49). + 'loan_start_date' => ['nullable', 'date', 'after_or_equal:1900-01-01'], 'original_amount' => ['nullable', 'integer', 'min:0'], ]; } diff --git a/app/Services/LoanBalanceGeneratorService.php b/app/Services/LoanBalanceGeneratorService.php index 8e67119d..9713dd83 100644 --- a/app/Services/LoanBalanceGeneratorService.php +++ b/app/Services/LoanBalanceGeneratorService.php @@ -9,6 +9,15 @@ use Illuminate\Support\Str; class LoanBalanceGeneratorService { + /** + * Upsert historical balances in batches of this size. An old loan start + * date (which has no lower bound in validation) can produce a very long + * monthly series; building and upserting it all at once exhausts the queue + * worker's memory in Arr::map/flatten (PHP-LARAVEL-49). Batching bounds + * peak memory. + */ + private const UPSERT_CHUNK_SIZE = 500; + /** * Generate historical monthly balances from a loan's start date to today * using linear interpolation between the original amount owed and the @@ -73,6 +82,25 @@ class LoanBalanceGeneratorService 'created_at' => $now, 'updated_at' => $now, ]; + + if (count($rows) >= self::UPSERT_CHUNK_SIZE) { + $this->upsertBalances($rows); + $rows = []; + } + } + + $this->upsertBalances($rows); + } + + /** + * Upsert a batch of balance rows, keyed by (account_id, balance_date). + * + * @param list> $rows + */ + private function upsertBalances(array $rows): void + { + if ($rows === []) { + return; } AccountBalance::upsert($rows, ['account_id', 'balance_date'], ['balance', 'updated_at']); diff --git a/app/Services/RealEstateBalanceGeneratorService.php b/app/Services/RealEstateBalanceGeneratorService.php index dbf3a8df..d203cdc4 100644 --- a/app/Services/RealEstateBalanceGeneratorService.php +++ b/app/Services/RealEstateBalanceGeneratorService.php @@ -9,6 +9,14 @@ use Illuminate\Support\Str; class RealEstateBalanceGeneratorService { + /** + * Upsert historical balances in batches of this size. An old purchase date + * (which has no lower bound in validation) can produce a very long monthly + * series; building and upserting it all at once exhausts the queue worker's + * memory in Arr::map/flatten (PHP-LARAVEL-49). Batching bounds peak memory. + */ + private const UPSERT_CHUNK_SIZE = 500; + /** * Generate historical monthly balances from purchase date to today * using linear interpolation between purchase price and current value. @@ -73,6 +81,25 @@ class RealEstateBalanceGeneratorService 'created_at' => $now, 'updated_at' => $now, ]; + + if (count($rows) >= self::UPSERT_CHUNK_SIZE) { + $this->upsertBalances($rows); + $rows = []; + } + } + + $this->upsertBalances($rows); + } + + /** + * Upsert a batch of balance rows, keyed by (account_id, balance_date). + * + * @param list> $rows + */ + private function upsertBalances(array $rows): void + { + if ($rows === []) { + return; } AccountBalance::upsert($rows, ['account_id', 'balance_date'], ['balance', 'updated_at']); diff --git a/tests/Feature/RealEstateTest.php b/tests/Feature/RealEstateTest.php index 963ad0ac..65bc3f94 100644 --- a/tests/Feature/RealEstateTest.php +++ b/tests/Feature/RealEstateTest.php @@ -63,6 +63,26 @@ it('can create a real estate account with property details', function () { ]); }); +it('rejects a purchase date before the 1900 floor', function () { + actingAs($this->user); + + // A pre-1900 (typically mistyped) date would make the historical balance + // generator build a multi-century monthly series and OOM the queue worker + // (PHP-LARAVEL-49). It must be rejected at validation. + $data = [ + 'name' => 'My Apartment', + 'currency_code' => 'EUR', + 'type' => AccountType::RealEstate->value, + 'property_type' => PropertyType::Residential->value, + 'purchase_price' => 25000000, + 'purchase_date' => '1899-12-31', + ]; + + $response = $this->post(route('accounts.store'), $data); + + $response->assertSessionHasErrors(['purchase_date']); +}); + it('can create a real estate account with only required fields', function () { actingAs($this->user); diff --git a/tests/Feature/Services/LoanBalanceGeneratorServiceTest.php b/tests/Feature/Services/LoanBalanceGeneratorServiceTest.php index c76b5c98..b43bf5eb 100644 --- a/tests/Feature/Services/LoanBalanceGeneratorServiceTest.php +++ b/tests/Feature/Services/LoanBalanceGeneratorServiceTest.php @@ -10,6 +10,37 @@ beforeEach(function () { $this->service = app(LoanBalanceGeneratorService::class); }); +it('generates a long series across multiple upsert batches without gaps or duplicates', function () { + $this->travelTo(Carbon::parse('2026-06-15')); + + $account = Account::factory()->loan()->create([ + 'user_id' => $this->user->id, + ]); + + // ~46 years of monthly points is well over the internal upsert batch size, + // so this drives the chunked build/upsert path that stops the queue worker + // from exhausting memory on an ancient loan start date (PHP-LARAVEL-49). + $this->service->generateHistoricalBalances( + $account, + originalAmount: 15000000, + startDate: Carbon::parse('1980-01-15'), + currentBalance: 3000000, + ); + + $balances = $account->balances()->orderBy('balance_date')->get(); + $dates = $balances->pluck('balance_date')->map->toDateString(); + + // Enough points to span more than one batch... + expect($balances->count())->toBeGreaterThan(500); + // ...and the batch boundaries must not drop or duplicate any date. + expect($dates->unique()->count())->toBe($balances->count()); + // Endpoints stay anchored across the batched writes. + expect($dates->first())->toBe('1980-01-15'); + expect($balances->first()->balance)->toBe(15000000); + expect($dates->last())->toBe('2026-06-15'); + expect($balances->last()->balance)->toBe(3000000); +}); + it('generates linearly interpolated balances from start date to today', function () { $this->travelTo(Carbon::parse('2026-03-15')); diff --git a/tests/Feature/Services/RealEstateBalanceGeneratorServiceTest.php b/tests/Feature/Services/RealEstateBalanceGeneratorServiceTest.php index 3195ee02..f1845fea 100644 --- a/tests/Feature/Services/RealEstateBalanceGeneratorServiceTest.php +++ b/tests/Feature/Services/RealEstateBalanceGeneratorServiceTest.php @@ -10,6 +10,37 @@ beforeEach(function () { $this->service = app(RealEstateBalanceGeneratorService::class); }); +it('generates a long series across multiple upsert batches without gaps or duplicates', function () { + $this->travelTo(Carbon::parse('2026-06-15')); + + $account = Account::factory()->realEstate()->create([ + 'user_id' => $this->user->id, + ]); + + // ~46 years of monthly points is well over the internal upsert batch size, + // so this drives the chunked build/upsert path that stops the queue worker + // from exhausting memory on an ancient purchase date (PHP-LARAVEL-49). + $this->service->generateHistoricalBalances( + $account, + purchasePrice: 10000000, + purchaseDate: Carbon::parse('1980-01-15'), + currentValue: 16000000, + ); + + $balances = $account->balances()->orderBy('balance_date')->get(); + $dates = $balances->pluck('balance_date')->map->toDateString(); + + // Enough points to span more than one batch... + expect($balances->count())->toBeGreaterThan(500); + // ...and the batch boundaries must not drop or duplicate any date. + expect($dates->unique()->count())->toBe($balances->count()); + // Endpoints stay anchored across the batched writes. + expect($dates->first())->toBe('1980-01-15'); + expect($balances->first()->balance)->toBe(10000000); + expect($dates->last())->toBe('2026-06-15'); + expect($balances->last()->balance)->toBe(16000000); +}); + it('generates linearly interpolated balances from purchase date to today', function () { $this->travelTo(Carbon::parse('2026-03-15'));