f78ab4af3d
Создавать проекты можно всегда; баланс проверяется в момент ЗАПУСКА (создать-и-запустить / запустить / возобновить одиночно и пачкой / автоподбор) под замком на клиента (без гонок). Не хватает — проект остаётся на паузе с меткой 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>
154 lines
6.2 KiB
PHP
154 lines
6.2 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
use App\Jobs\SyncSupplierProjectJob;
|
||
use App\Models\PricingTier;
|
||
use App\Models\Project;
|
||
use App\Models\Tenant;
|
||
use App\Models\User;
|
||
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Support\Facades\Queue;
|
||
use Tests\Concerns\SharesSupplierPdo;
|
||
|
||
uses(DatabaseTransactions::class);
|
||
uses(SharesSupplierPdo::class);
|
||
|
||
beforeEach(function () {
|
||
Queue::fake();
|
||
DB::statement("SELECT set_config('app.current_tenant_id', '0', true)");
|
||
PricingTier::query()->create([
|
||
'tier_no' => 1,
|
||
'leads_in_tier' => null,
|
||
'price_per_lead_kopecks' => 5000, // 50₽/лид — capacity = balance/50
|
||
'is_active' => true,
|
||
'effective_from' => now(),
|
||
]);
|
||
});
|
||
|
||
it('creates project held (not launched) when it would overload balance', function () {
|
||
// 1000₽ / 50₽ = 20 лидов capacity; запрашиваем daily_limit_target=30 → дефицит 10.
|
||
// Новое поведение: проект создаётся (201), но удерживается с preflight_blocked_at.
|
||
$tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '1000.00']);
|
||
$user = User::factory()->create(['tenant_id' => $tenant->id]);
|
||
|
||
$response = $this->actingAs($user)->postJson('/api/projects', [
|
||
'name' => 'Перегрузка',
|
||
'signal_type' => 'site',
|
||
'signal_identifier' => 'overload.ru',
|
||
'daily_limit_target' => 30,
|
||
'regions' => [],
|
||
'delivery_days_mask' => 127,
|
||
]);
|
||
|
||
$response->assertCreated();
|
||
$response->assertJsonPath('launch.launched', 0);
|
||
$response->assertJsonPath('launch.deferred', 1);
|
||
$response->assertJsonPath('launch.balance.deficit_leads', 10);
|
||
$response->assertJsonPath('launch.balance.current_capacity_leads', 20);
|
||
$response->assertJsonPath('launch.balance.would_be_required_leads', 30);
|
||
|
||
$p = Project::where('signal_identifier', 'overload.ru')->first();
|
||
expect($p)->not->toBeNull();
|
||
expect($p->preflight_blocked_at)->not->toBeNull();
|
||
expect((bool) $p->is_active)->toBeFalse();
|
||
|
||
Queue::assertNotPushed(SyncSupplierProjectJob::class);
|
||
});
|
||
|
||
it('creates blocked project when force_save_blocked=true', function () {
|
||
$tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '1000.00']);
|
||
$user = User::factory()->create(['tenant_id' => $tenant->id]);
|
||
|
||
$response = $this->actingAs($user)->postJson('/api/projects', [
|
||
'name' => 'Заблокированный',
|
||
'signal_type' => 'site',
|
||
'signal_identifier' => 'force-blocked.ru',
|
||
'daily_limit_target' => 30,
|
||
'regions' => [],
|
||
'delivery_days_mask' => 127,
|
||
'force_save_blocked' => true,
|
||
]);
|
||
|
||
$response->assertCreated();
|
||
$project = Project::where('signal_identifier', 'force-blocked.ru')->first();
|
||
expect($project)->not->toBeNull();
|
||
expect($project->preflight_blocked_at)->not->toBeNull();
|
||
});
|
||
|
||
it('creates normally when within balance', function () {
|
||
// 2000₽ / 50₽ = 40 лидов capacity; daily_limit_target=30 — passes.
|
||
$tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '2000.00']);
|
||
$user = User::factory()->create(['tenant_id' => $tenant->id]);
|
||
|
||
$response = $this->actingAs($user)->postJson('/api/projects', [
|
||
'name' => 'Норма',
|
||
'signal_type' => 'site',
|
||
'signal_identifier' => 'ok-balance.ru',
|
||
'daily_limit_target' => 30,
|
||
'regions' => [],
|
||
'delivery_days_mask' => 127,
|
||
]);
|
||
|
||
$response->assertCreated();
|
||
$project = Project::where('signal_identifier', 'ok-balance.ru')->first();
|
||
expect($project->preflight_blocked_at)->toBeNull();
|
||
});
|
||
|
||
it('does not order blocked project at supplier on create', function () {
|
||
// Баланс не тянет лимит → клиент продавил force_save_blocked → проект помечен
|
||
// preflight_blocked_at. Такой проект НЕ должен уезжать заказом к поставщику
|
||
// (зеркалит фильтр sweep-джоба ->whereNull('preflight_blocked_at')).
|
||
$tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '1000.00']);
|
||
$user = User::factory()->create(['tenant_id' => $tenant->id]);
|
||
|
||
$this->actingAs($user)->postJson('/api/projects', [
|
||
'name' => 'Блок-без-заказа',
|
||
'signal_type' => 'site',
|
||
'signal_identifier' => 'blocked-no-order.ru',
|
||
'daily_limit_target' => 30,
|
||
'regions' => [],
|
||
'delivery_days_mask' => 127,
|
||
'force_save_blocked' => true,
|
||
])->assertCreated();
|
||
|
||
Queue::assertNotPushed(SyncSupplierProjectJob::class);
|
||
});
|
||
|
||
it('orders unblocked project at supplier on create', function () {
|
||
// Баланс тянет лимит → проект не заблокирован → заказ к поставщику уходит.
|
||
$tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '2000.00']);
|
||
$user = User::factory()->create(['tenant_id' => $tenant->id]);
|
||
|
||
$this->actingAs($user)->postJson('/api/projects', [
|
||
'name' => 'Норма-с-заказом',
|
||
'signal_type' => 'site',
|
||
'signal_identifier' => 'ok-order.ru',
|
||
'daily_limit_target' => 30,
|
||
'regions' => [],
|
||
'delivery_days_mask' => 127,
|
||
])->assertCreated();
|
||
|
||
Queue::assertPushed(SyncSupplierProjectJob::class);
|
||
});
|
||
|
||
it('returns 409 on update when increased limit overloads balance', function () {
|
||
// существующий проект на 15 лидов, всё ок (capacity 20).
|
||
$tenant = Tenant::factory()->withRequisites()->create(['balance_rub' => '1000.00']);
|
||
$user = User::factory()->create(['tenant_id' => $tenant->id]);
|
||
$project = Project::factory()->for($tenant)->create([
|
||
'is_active' => true,
|
||
'daily_limit_target' => 15,
|
||
]);
|
||
|
||
// UPDATE до 30 → suma 30 > capacity 20 → 409.
|
||
$response = $this->actingAs($user)->patchJson("/api/projects/{$project->id}", [
|
||
'daily_limit_target' => 30,
|
||
]);
|
||
|
||
$response->assertStatus(409);
|
||
$response->assertJsonPath('error', 'balance_insufficient');
|
||
expect($project->fresh()->daily_limit_target)->toBe(15); // не изменилось
|
||
});
|