2e0f5a4d29
Баг: при autopodbor_max_competitors=0 джоба делала array_slice($unique,0,0)=[] → сохраняла 0 конкурентов, НО всё равно списывала 50₽ (chargeForRun после обрезки, проверка empty стои́т ДО неё). Теперь $max>0?slice:все — 0 значит «сохранить всех». Плюс авто-повтор findCompetitors при пустом сборе (search_retry_on_empty, деф. 2): моргание 2ГИС/Яндекс/EXA не показывает клиенту «ничего не нашлось». Реально пустая ниша → empty без списания. 2 теста; ветка автоподбора 176/176. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
284 lines
14 KiB
PHP
284 lines
14 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
use App\Jobs\Autopodbor\RunAutopodborSearchJob;
|
|
use App\Mail\AutopodborReadyMail;
|
|
use App\Models\AutopodborCompetitor;
|
|
use App\Models\AutopodborRun;
|
|
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 Illuminate\Support\Facades\Mail;
|
|
use Tests\Concerns\SharesSupplierPdo;
|
|
use Tests\Doubles\EmptyCompetitorAgent;
|
|
|
|
uses(DatabaseTransactions::class, SharesSupplierPdo::class);
|
|
|
|
function runSearchJob(int $runId): void
|
|
{
|
|
// handle через контейнер (DI зависимостей)
|
|
app()->call([new RunAutopodborSearchJob($runId), 'handle']);
|
|
}
|
|
|
|
it('успешный подбор: сохраняет конкурентов, списывает, status=done', 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],
|
|
]);
|
|
|
|
runSearchJob($run->id);
|
|
|
|
expect($run->fresh()->status)->toBe('done')
|
|
->and($run->fresh()->price_rub_charged)->toBe('500.00')
|
|
->and(AutopodborCompetitor::where('search_run_id', $run->id)->count())->toBeGreaterThan(0)
|
|
->and((string) $tenant->fresh()->balance_rub)->toBe('99500.00');
|
|
});
|
|
|
|
it('сохраняет телефоны конкурента нормализованными (для клиентской склейки, НЕ в тихую)', 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' => '0', 'type' => 'decimal']);
|
|
SystemSetting::updateOrCreate(['key' => 'autopodbor_max_competitors'], ['value' => '15', 'type' => 'int']);
|
|
|
|
// Фейк-агент отдаёт конкурента с телефонами в разных форматах (как из карточек).
|
|
app()->bind(CompetitorAgent::class, fn () => new class implements CompetitorAgent
|
|
{
|
|
public function findCompetitors(FindCompetitorsRequest $r): FindCompetitorsResult
|
|
{
|
|
return new FindCompetitorsResult([
|
|
['name' => 'Ф', 'site_url' => 'f.ru', 'directory_urls' => [], 'phones' => ['8 (800) 111-22-33', '+78001112233']],
|
|
]);
|
|
}
|
|
|
|
public function studyCompetitor(StudyCompetitorRequest $r): StudyCompetitorResult
|
|
{
|
|
return new StudyCompetitorResult([]);
|
|
}
|
|
|
|
public function resolveByName(ResolveByNameRequest $r): ResolveByNameResult
|
|
{
|
|
return new ResolveByNameResult([]);
|
|
}
|
|
});
|
|
|
|
$run = AutopodborRun::create([
|
|
'tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'queued',
|
|
'region_code' => 16, 'params' => ['examples' => [], 'about_self' => [], 'include_federal' => false],
|
|
]);
|
|
|
|
runSearchJob($run->id);
|
|
|
|
$c = AutopodborCompetitor::where('search_run_id', $run->id)->where('name', 'Ф')->first();
|
|
expect($c)->not->toBeNull()
|
|
->and($c->phones)->toBe(['78001112233']); // два формата одного номера → один нормализованный
|
|
});
|
|
|
|
it('после готового подбора шлёт письмо «готово» на почту тенанта', function () {
|
|
Mail::fake();
|
|
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00', 'contact_email' => 'client@demo.local']);
|
|
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],
|
|
]);
|
|
|
|
runSearchJob($run->id);
|
|
|
|
expect($run->fresh()->status)->toBe('done');
|
|
Mail::assertSent(AutopodborReadyMail::class, fn ($m) => $m->hasTo('client@demo.local'));
|
|
});
|
|
|
|
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_search_rub'], ['value' => '500', 'type' => 'decimal']);
|
|
$run = AutopodborRun::create([
|
|
'tenant_id' => $tenant->id,
|
|
'kind' => 'search',
|
|
'status' => 'queued',
|
|
'region_code' => 16,
|
|
'params' => ['examples' => [], 'about_self' => [], 'include_federal' => false],
|
|
]);
|
|
|
|
runSearchJob($run->id);
|
|
|
|
expect($run->fresh()->status)->toBe('empty')
|
|
->and($run->fresh()->price_rub_charged)->toBeNull()
|
|
->and((string) $tenant->fresh()->balance_rub)->toBe('100000.00');
|
|
});
|
|
|
|
it('если почта падает с исключением — прогон всё равно завершается статусом done и конкуренты сохранены', function () {
|
|
// Имитируем недоступность SMTP: Mail::to() бросает исключение
|
|
Mail::shouldReceive('to')->andThrow(new RuntimeException('smtp down'));
|
|
|
|
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00', 'contact_email' => 'client@demo.local']);
|
|
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],
|
|
]);
|
|
|
|
// handle() НЕ должен бросать — ошибка почты поглощается внутри notifyReady()
|
|
expect(fn () => runSearchJob($run->id))->not->toThrow(Throwable::class);
|
|
|
|
expect($run->fresh()->status)->toBe('done')
|
|
->and(AutopodborCompetitor::where('search_run_id', $run->id)->count())->toBeGreaterThan(0);
|
|
});
|
|
|
|
it('если почта падает при пустом результате — прогон всё равно завершается статусом empty', function () {
|
|
Mail::shouldReceive('to')->andThrow(new RuntimeException('smtp down'));
|
|
|
|
app()->bind(CompetitorAgent::class, EmptyCompetitorAgent::class);
|
|
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00', 'contact_email' => 'client@demo.local']);
|
|
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' => 'queued',
|
|
'region_code' => 16, 'params' => ['examples' => [], 'about_self' => [], 'include_federal' => false],
|
|
]);
|
|
|
|
expect(fn () => runSearchJob($run->id))->not->toThrow(Throwable::class);
|
|
|
|
expect($run->fresh()->status)->toBe('empty');
|
|
});
|
|
|
|
it('повторный подбор не дублирует известных конкурентов и не списывает (сквозной дедуп)', 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' => '300', 'type' => 'decimal']);
|
|
SystemSetting::updateOrCreate(['key' => 'autopodbor_max_competitors'], ['value' => '15', 'type' => 'int']);
|
|
|
|
$mk = fn () => AutopodborRun::create([
|
|
'tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'queued',
|
|
'region_code' => 16, 'params' => ['examples' => ['okna.ru'], 'about_self' => [], 'include_federal' => true],
|
|
]);
|
|
|
|
$run1 = $mk();
|
|
runSearchJob($run1->id);
|
|
$afterFirst = AutopodborCompetitor::where('tenant_id', $tenant->id)->count();
|
|
expect($afterFirst)->toBeGreaterThan(0);
|
|
|
|
$run2 = $mk();
|
|
runSearchJob($run2->id);
|
|
|
|
// Заглушка отдаёт тот же набор → второй прогон не добавляет дублей и не списывает
|
|
expect(AutopodborCompetitor::where('tenant_id', $tenant->id)->count())->toBe($afterFirst)
|
|
->and($run2->fresh()->status)->toBe('empty')
|
|
->and($run2->fresh()->price_rub_charged)->toBeNull()
|
|
->and((string) $tenant->fresh()->balance_rub)->toBe('99700.00');
|
|
});
|
|
|
|
it('выставляет tenant-контекст ДО чтения прогона (иначе прод под RLS = ModelNotFound)', function () {
|
|
// Регресс прод-сбоя 07.07.2026 (шаг 1). См. пояснение в RunAutopodborStudyJobTest.
|
|
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_search_rub'], ['value' => '500', 'type' => 'decimal']);
|
|
$run = AutopodborRun::create([
|
|
'tenant_id' => $tenant->id,
|
|
'kind' => 'search',
|
|
'status' => 'queued',
|
|
'region_code' => 16,
|
|
'params' => ['examples' => ['okna.ru'], 'about_self' => [], 'include_federal' => false],
|
|
]);
|
|
|
|
$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 RunAutopodborSearchJob($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('лимит 0 («не режем») сохраняет всех найденных, не режет в ноль', function () {
|
|
// Регресс 07.07: при autopodbor_max_competitors=0 джоба делала array_slice($unique,0,0)=[] →
|
|
// сохраняла 0 конкурентов, но всё равно списывала. Теперь 0 = «сохранить всех».
|
|
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_max_competitors'], ['value' => '0', 'type' => 'int']);
|
|
SystemSetting::updateOrCreate(['key' => 'autopodbor_price_search_rub'], ['value' => '50', 'type' => 'decimal']);
|
|
$run = AutopodborRun::create([
|
|
'tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'queued', 'region_code' => 16,
|
|
'params' => ['examples' => ['okna.ru'], 'about_self' => [], 'include_federal' => false],
|
|
]);
|
|
|
|
app()->call([new RunAutopodborSearchJob($run->id, $tenant->id), 'handle']);
|
|
|
|
expect($run->fresh()->status)->toBe('done')
|
|
->and(AutopodborCompetitor::where('search_run_id', $run->id)->count())->toBeGreaterThan(0);
|
|
});
|
|
|
|
it('пустой сбор: авто-повтор попыток и БЕЗ списания', function () {
|
|
// Внешка моргнула → сбор пуст. Джоба повторяет поиск (search_retry_on_empty), и если всё
|
|
// равно пусто — статус empty без списания (за пустой результат денег не берём).
|
|
$agent = new class implements CompetitorAgent
|
|
{
|
|
public int $calls = 0;
|
|
|
|
public function findCompetitors(FindCompetitorsRequest $r): FindCompetitorsResult
|
|
{
|
|
$this->calls++;
|
|
|
|
return new FindCompetitorsResult([]);
|
|
}
|
|
|
|
public function resolveByName(ResolveByNameRequest $r): ResolveByNameResult
|
|
{
|
|
throw new LogicException('n/a');
|
|
}
|
|
|
|
public function studyCompetitor(StudyCompetitorRequest $r): StudyCompetitorResult
|
|
{
|
|
throw new LogicException('n/a');
|
|
}
|
|
};
|
|
app()->instance(CompetitorAgent::class, $agent);
|
|
config()->set('autopodbor.search_retry_on_empty', 2);
|
|
$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' => '50', 'type' => 'decimal']);
|
|
$run = AutopodborRun::create([
|
|
'tenant_id' => $tenant->id, 'kind' => 'search', 'status' => 'queued', 'region_code' => 16,
|
|
'params' => ['examples' => ['x'], 'about_self' => [], 'include_federal' => false],
|
|
]);
|
|
|
|
app()->call([new RunAutopodborSearchJob($run->id, $tenant->id), 'handle']);
|
|
|
|
expect($run->fresh()->status)->toBe('empty')
|
|
->and($agent->calls)->toBe(3) // 1 + 2 повтора
|
|
->and((string) $tenant->fresh()->balance_rub)->toBe('100000.00');
|
|
});
|