Files
portal/app/tests/Feature/Autopodbor/CreateFromSourcesGateTest.php
T
Дмитрий f78ab4af3d feat(биллинг): баланс блокирует запуск проекта, а не создание — единый гейт
Создавать проекты можно всегда; баланс проверяется в момент ЗАПУСКА
(создать-и-запустить / запустить / возобновить одиночно и пачкой / автоподбор)
под замком на клиента (без гонок). Не хватает — проект остаётся на паузе с
меткой preflight_blocked_at, клиенту сообщение в рублях (сколько пополнить).
Групповой запуск «сколько влезло». Нет активного тарифа на дату → запуск
запрещён (fail-closed). Гейт реквизитов первого проекта добавлен и в автоподбор.

- LaunchBalanceGate — единый гейт вместо 3 копий preflight (ProjectController
  store/update, AutopodborController), под DB::transaction + lockForUpdate(Tenant).
- ProjectService::create($launch) + новый setActive(); bulk resume «сколько влезло».
- AutopodborProjectCreator: пачка в транзакции через общий ProjectService::create.
- Идемпотентность box/phone_type миграций автоподбора (Schema::hasColumn guard).
- Тест-инфра: afterRefreshingDatabase восстанавливает месячные партиции.

Тесты фичи 40/40 зелёные. Спека и план — docs/superpowers.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 11:07:22 +03:00

98 lines
2.9 KiB
PHP

<?php
declare(strict_types=1);
use App\Jobs\SyncSupplierProjectJob;
use App\Models\AutopodborCompetitor;
use App\Models\AutopodborRun;
use App\Models\AutopodborSource;
use App\Models\PricingTier;
use App\Models\Tenant;
use App\Services\Autopodbor\AutopodborProjectCreator;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Tests\Concerns\SharesSupplierPdo;
uses(DatabaseTransactions::class, SharesSupplierPdo::class);
beforeEach(function () {
PricingTier::create([
'tier_no' => 1,
'leads_in_tier' => null,
'price_per_lead_kopecks' => 10000,
'is_active' => true,
'effective_from' => now()->toDateString(),
]);
});
/**
* Создаёт tenant + run + competitor + 2 источника типа site.
*
* @return array{0: Tenant, 1: AutopodborSource, 2: AutopodborSource}
*/
function seedTwoAutopodborSources(Tenant $tenant): array
{
DB::statement('SET app.current_tenant_id = '.$tenant->id);
$run = AutopodborRun::create([
'tenant_id' => $tenant->id,
'kind' => 'search',
'status' => 'done',
'region_code' => 16,
'params' => [],
]);
$comp = AutopodborCompetitor::create([
'tenant_id' => $tenant->id,
'search_run_id' => $run->id,
'study_run_id' => $run->id,
'studied_at' => now(),
'name' => 'Тест-конкурент',
'box' => 'field',
'site_url' => 'rival1.ru',
'dedup_key' => 'site:rival1.ru',
]);
$s1 = AutopodborSource::create([
'tenant_id' => $tenant->id,
'competitor_id' => $comp->id,
'study_run_id' => $run->id,
'signal_type' => 'site',
'identifier' => 'rival1.ru',
'box' => 'field',
'dedup_key' => 'site:rival1.ru',
]);
$s2 = AutopodborSource::create([
'tenant_id' => $tenant->id,
'competitor_id' => $comp->id,
'study_run_id' => $run->id,
'signal_type' => 'site',
'identifier' => 'rival2.ru',
'box' => 'field',
'dedup_key' => 'site:rival2.ru',
]);
return [$tenant, $s1, $s2];
}
it('launch=true partial capacity → some launched, rest held, no premature sync', function () {
Queue::fake();
$t = Tenant::factory()->create(['balance_rub' => '600.00', 'delivered_in_month' => 0]); // 6 лидов ёмкость
[, $s1, $s2] = seedTwoAutopodborSources($t);
$projects = app(AutopodborProjectCreator::class)->createFromSources(
$t->id,
[$s1->id, $s2->id],
['regions' => [], 'daily_limit_target' => 5, 'delivery_days_mask' => 127],
launch: true,
);
$active = collect($projects)->filter(fn ($p) => $p->is_active);
expect($active)->toHaveCount(1); // 5 влезло, второй (5+5=10 > 6) → удержан
Queue::assertPushed(SyncSupplierProjectJob::class, 1); // только за запущенный
});