Files
portal/app/tests/Feature/Autopodbor/AutopodborJobIdempotencyTest.php
T
2026-06-28 16:17:44 +03:00

47 lines
2.9 KiB
PHP

<?php
declare(strict_types=1);
use App\Models\Tenant;
use App\Models\SystemSetting;
use App\Models\AutopodborRun;
use App\Models\AutopodborCompetitor;
use App\Models\BalanceTransaction;
use App\Jobs\Autopodbor\RunAutopodborSearchJob;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
uses(DatabaseTransactions::class, \Tests\Concerns\SharesSupplierPdo::class);
it('повторный запуск SearchJob не плодит конкурентов и не списывает дважды', function () {
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00']);
DB::statement("SET app.current_tenant_id = ".$tenant->id);
SystemSetting::updateOrCreate(['key' => 'autopodbor_price_search_rub'], ['value' => '500', 'type' => 'decimal']);
SystemSetting::updateOrCreate(['key' => 'autopodbor_max_competitors'], ['value' => '15', 'type' => 'int']);
$run = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'queued', 'region_code' => 16, 'params' => ['examples' => ['okna.ru'], 'about_self' => [], 'include_federal' => true]]);
// первый прогон
app()->call([new RunAutopodborSearchJob($run->id), 'handle']);
$countAfter1 = AutopodborCompetitor::where('search_run_id', $run->id)->count();
$balAfter1 = (string) $tenant->fresh()->balance_rub;
$txAfter1 = BalanceTransaction::where('related_type', AutopodborRun::class)->where('related_id', $run->id)->count();
// имитируем ретрай: сбросим статус в running (как если бы краш был до status=done), competitors уже есть, charge уже сделан
$run->update(['status' => 'running']);
app()->call([new RunAutopodborSearchJob($run->id), 'handle']);
expect(AutopodborCompetitor::where('search_run_id', $run->id)->count())->toBe($countAfter1) // нет дублей
->and((string) $tenant->fresh()->balance_rub)->toBe($balAfter1) // нет второго списания
->and(BalanceTransaction::where('related_type', AutopodborRun::class)->where('related_id', $run->id)->count())->toBe($txAfter1); // одна проводка
expect($run->fresh()->status)->toBe('done');
});
it('done-прогон при повторном dispatch сразу выходит (top-guard)', function () {
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00']);
DB::statement("SET app.current_tenant_id = ".$tenant->id);
SystemSetting::updateOrCreate(['key' => 'autopodbor_price_search_rub'], ['value' => '500', 'type' => 'decimal']);
$run = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'done', 'region_code' => 16, 'params' => ['examples' => [], 'about_self' => [], 'include_federal' => false]]);
app()->call([new RunAutopodborSearchJob($run->id), 'handle']);
expect(AutopodborCompetitor::where('search_run_id', $run->id)->count())->toBe(0); // ничего не делал
});