Files
portal/app/tests/Feature/Project/ToggleActiveGateTest.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

59 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
use App\Models\PricingTier;
use App\Models\Project;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\Concerns\SharesSupplierPdo;
uses(DatabaseTransactions::class);
uses(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(),
]);
});
it('refuses resume via API when balance insufficient (409)', function () {
$t = Tenant::factory()->create(['balance_rub' => '100.00', 'delivered_in_month' => 0]);
$u = User::factory()->for($t)->create();
$p = Project::factory()->for($t)->create(['is_active' => false, 'daily_limit_target' => 5, 'paused_at' => now(), 'preflight_blocked_at' => null]);
$resp = $this->actingAs($u)->patchJson("/api/projects/{$p->id}/toggle-active", ['is_active' => true]);
$resp->assertStatus(409);
$resp->assertJsonPath('error', 'balance_insufficient');
expect($p->fresh()->is_active)->toBeFalse();
});
it('resumes via API when balance sufficient (200 with data)', function () {
$t = Tenant::factory()->create(['balance_rub' => '1000.00', 'delivered_in_month' => 0]);
$u = User::factory()->for($t)->create();
$p = Project::factory()->for($t)->create(['is_active' => false, 'daily_limit_target' => 5, 'paused_at' => now(), 'preflight_blocked_at' => null]);
$resp = $this->actingAs($u)->patchJson("/api/projects/{$p->id}/toggle-active", ['is_active' => true]);
$resp->assertOk();
$resp->assertJsonStructure(['data']);
expect($p->fresh()->is_active)->toBeTrue();
});
it('pauses via API without balance check (200)', function () {
$t = Tenant::factory()->create(['balance_rub' => '0.00', 'delivered_in_month' => 0]);
$u = User::factory()->for($t)->create();
$p = Project::factory()->for($t)->create(['is_active' => true, 'daily_limit_target' => 5]);
$resp = $this->actingAs($u)->patchJson("/api/projects/{$p->id}/toggle-active", ['is_active' => false]);
$resp->assertOk();
expect($p->fresh()->is_active)->toBeFalse();
});