a42ee07c42
Джобы Search/Study/Resolve делали AutopodborRun::findOrFail() ДО set_config app.current_tenant_id. На проде роль crm_app_user под FORCE RLS (на боевом кластере ни одна роль не BYPASSRLS) не видит строку без tenant-контекста → ModelNotFound, все три кнопки автоподбора падали. На dev маскировалось суперюзером postgres. Теперь tenantId передаётся в dispatch и контекст выставляется первым. 3 регресс-теста на порядок (set до чтения runs). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
135 lines
8.0 KiB
PHP
135 lines
8.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
use App\Jobs\Autopodbor\RunAutopodborStudyJob;
|
|
use App\Models\AutopodborCompetitor;
|
|
use App\Models\AutopodborRun;
|
|
use App\Models\AutopodborSource;
|
|
use App\Models\SystemSetting;
|
|
use App\Models\Tenant;
|
|
use App\Services\Autopodbor\Agent\CompetitorAgent;
|
|
use App\Services\Autopodbor\Agent\Dto\FindCompetitorsRequest;
|
|
use App\Services\Autopodbor\Agent\Dto\FindCompetitorsResult;
|
|
use App\Services\Autopodbor\Agent\Dto\ResolveByNameRequest;
|
|
use App\Services\Autopodbor\Agent\Dto\ResolveByNameResult;
|
|
use App\Services\Autopodbor\Agent\Dto\StudyCompetitorRequest;
|
|
use App\Services\Autopodbor\Agent\Dto\StudyCompetitorResult;
|
|
use App\Services\Autopodbor\Agent\FakeCompetitorAgent;
|
|
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Tests\Concerns\SharesSupplierPdo;
|
|
use Tests\Doubles\EmptyCompetitorAgent;
|
|
|
|
uses(DatabaseTransactions::class, SharesSupplierPdo::class);
|
|
|
|
it('успешное изучение: источники + конкурент изучен + списание', function () {
|
|
// Дефолтный агент теперь настоящий (ходит в сеть) — для детерминированного
|
|
// изучения пиним заглушку с захардкоженными демо-источниками.
|
|
app()->bind(CompetitorAgent::class, FakeCompetitorAgent::class);
|
|
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00']);
|
|
DB::statement('SET app.current_tenant_id = '.$tenant->id);
|
|
SystemSetting::updateOrCreate(['key' => 'autopodbor_price_study_rub'], ['value' => '900', 'type' => 'decimal']);
|
|
$searchRun = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'done', 'region_code' => 16, 'params' => []]);
|
|
$comp = AutopodborCompetitor::create(['tenant_id' => $tenant->id, 'search_run_id' => $searchRun->id, 'name' => 'Окна Комфорт', 'dedup_key' => 'site:okna-komfort-kzn.ru', 'site_url' => 'okna-komfort-kzn.ru']);
|
|
$run = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'study', 'status' => 'queued', 'region_code' => 16, 'competitor_id' => $comp->id, 'params' => []]);
|
|
|
|
app()->call([new RunAutopodborStudyJob($run->id), 'handle']);
|
|
|
|
expect($run->fresh()->status)->toBe('done')
|
|
->and($run->fresh()->price_rub_charged)->toBe('900.00')
|
|
->and($comp->fresh()->studied_at)->not->toBeNull()
|
|
->and($comp->fresh()->study_run_id)->toBe($run->id)
|
|
->and(AutopodborSource::where('competitor_id', $comp->id)->count())->toBeGreaterThan(0)
|
|
->and((string) $tenant->fresh()->balance_rub)->toBe('99100.00');
|
|
// источники нормализованы (телефоны 7xxxxxxxxxx)
|
|
$phone = AutopodborSource::where('competitor_id', $comp->id)->where('signal_type', 'call')->first();
|
|
if ($phone) {
|
|
expect($phone->identifier)->toMatch('/^7\d{10}$/')
|
|
->and(in_array($phone->phone_type, ['city', 'mobile', 'tollfree'], true))->toBeTrue(); // тип номера сохранён
|
|
}
|
|
});
|
|
|
|
it('пустой результат: status=empty, без списания', function () {
|
|
app()->bind(CompetitorAgent::class, EmptyCompetitorAgent::class);
|
|
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00']);
|
|
DB::statement('SET app.current_tenant_id = '.$tenant->id);
|
|
SystemSetting::updateOrCreate(['key' => 'autopodbor_price_study_rub'], ['value' => '900', 'type' => 'decimal']);
|
|
$searchRun = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'done', 'region_code' => 16, 'params' => []]);
|
|
$comp = AutopodborCompetitor::create(['tenant_id' => $tenant->id, 'search_run_id' => $searchRun->id, 'name' => 'Пусто', 'dedup_key' => 'site:empty.ru', 'site_url' => 'empty.ru']);
|
|
$run = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'study', 'status' => 'queued', 'region_code' => 16, 'competitor_id' => $comp->id, 'params' => []]);
|
|
|
|
app()->call([new RunAutopodborStudyJob($run->id), 'handle']);
|
|
|
|
expect($run->fresh()->status)->toBe('empty')
|
|
->and($run->fresh()->price_rub_charged)->toBeNull()
|
|
->and((string) $tenant->fresh()->balance_rub)->toBe('100000.00');
|
|
});
|
|
|
|
it('выставляет tenant-контекст ДО чтения прогона (иначе прод под RLS = ModelNotFound)', function () {
|
|
// Регресс прод-сбоя 07.07.2026: воркер шага 2 падал ModelNotFound, т.к. findOrFail
|
|
// выполнялся ДО set_config, а на боевом роль crm_app_user под FORCE RLS не видит строку
|
|
// без tenant-контекста (на dev маскировалось суперюзером postgres). Джоба обязана сперва
|
|
// представиться базе (tenantId из dispatch), и только потом читать прогон.
|
|
app()->bind(CompetitorAgent::class, EmptyCompetitorAgent::class);
|
|
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00']);
|
|
DB::statement('SET app.current_tenant_id = '.$tenant->id);
|
|
SystemSetting::updateOrCreate(['key' => 'autopodbor_price_study_rub'], ['value' => '900', 'type' => 'decimal']);
|
|
$searchRun = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'done', 'region_code' => 16, 'params' => []]);
|
|
$comp = AutopodborCompetitor::create(['tenant_id' => $tenant->id, 'search_run_id' => $searchRun->id, 'name' => 'X', 'dedup_key' => 'site:x.ru', 'site_url' => 'x.ru']);
|
|
$run = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'study', 'status' => 'queued', 'region_code' => 16, 'competitor_id' => $comp->id, 'params' => []]);
|
|
|
|
$order = [];
|
|
DB::listen(function ($q) use (&$order) {
|
|
if (str_contains($q->sql, 'app.current_tenant_id')) {
|
|
$order[] = 'set';
|
|
} elseif (preg_match('/from\s+"?autopodbor_runs"?/i', $q->sql)) {
|
|
$order[] = 'read_run';
|
|
}
|
|
});
|
|
|
|
app()->call([new RunAutopodborStudyJob($run->id, $tenant->id), 'handle']);
|
|
|
|
$firstSet = array_search('set', $order, true);
|
|
$firstRead = array_search('read_run', $order, true);
|
|
expect($firstSet)->not->toBeFalse('джоба ни разу не выставила app.current_tenant_id');
|
|
expect($firstRead)->not->toBeFalse('джоба не читала autopodbor_runs');
|
|
expect($firstSet)->toBeLessThan($firstRead);
|
|
});
|
|
|
|
it('джоба передаёт is_federal в StudyCompetitorRequest', function () {
|
|
$captured = null;
|
|
$spy = new class($captured) implements CompetitorAgent
|
|
{
|
|
public function __construct(public &$captured) {}
|
|
|
|
public function findCompetitors(FindCompetitorsRequest $r): FindCompetitorsResult
|
|
{
|
|
throw new LogicException('n/a');
|
|
}
|
|
|
|
public function resolveByName(ResolveByNameRequest $r): ResolveByNameResult
|
|
{
|
|
throw new LogicException('n/a');
|
|
}
|
|
|
|
public function studyCompetitor(StudyCompetitorRequest $r): StudyCompetitorResult
|
|
{
|
|
$this->captured = $r->competitor;
|
|
|
|
return new StudyCompetitorResult([]);
|
|
}
|
|
};
|
|
app()->instance(CompetitorAgent::class, $spy);
|
|
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00']);
|
|
DB::statement('SET app.current_tenant_id = '.$tenant->id);
|
|
SystemSetting::updateOrCreate(['key' => 'autopodbor_price_study_rub'], ['value' => '900', 'type' => 'decimal']);
|
|
$searchRun = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'done', 'region_code' => 29, 'params' => []]);
|
|
$comp = AutopodborCompetitor::create(['tenant_id' => $tenant->id, 'search_run_id' => $searchRun->id, 'name' => 'Банк ДОМ.РФ', 'dedup_key' => 'site:domrfbank.ru', 'site_url' => 'domrfbank.ru', 'is_federal' => true]);
|
|
$run = AutopodborRun::create(['tenant_id' => $tenant->id, 'kind' => 'study', 'status' => 'queued', 'region_code' => 29, 'competitor_id' => $comp->id, 'params' => []]);
|
|
|
|
app()->call([new RunAutopodborStudyJob($run->id), 'handle']);
|
|
|
|
expect($spy->captured['is_federal'])->toBeTrue();
|
|
});
|