b3f5158e48
Ускорение шага 1: CategoryScraper грузит страницы категории 2ГИС не по одной, а пачками поперёк рубрик через BatchPageFetcher. На остывшем xfetch 2ГИС упал с ~23 мин до ~5 мин и собрал 139 фирм вместо 12. Общий лимит одновременных xfetch снижен 4→3 (безопаснее под оконный rate-limit сервиса). Таймауты ИИ/EXA подняты с запасом (латентность моделей плавает, сбор асинхронный, клиент ждёт): sonar 120→300с, отсев агрегаторов 90→240с, общий AITUNNEL 30→120с, EXA 30→90с. Джоба: один прогон без авто-ретраев (tries 3→1, чтобы таймаут не перезапускал платный движок трижды) и общий таймаут 900→1800с. Фиксы, найденные на живом прогоне: - Письмо «готово» больше не роняет прогон при недоступной почте (тесты на сбой SMTP при status done/empty). - Яндекс-загрузчик берёт путь к node из config (autopodbor.node_bin, дефолт node) — из-под PHP node теперь находится; на живом прогоне Яндекс дал 78 фирм вместо 0. По TDD. Бэкенд автоподбора 262/262, Pint чисто. Живой прогон end-to-end: ~8 мин, 14 новых конкурентов, списание 300 ₽ корректно. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
146 lines
7.3 KiB
PHP
146 lines
7.3 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 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 () {
|
|
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');
|
|
});
|