e8db184e99
LeadRouter SQL переписан на JOIN с project_routing_snapshots по active_slepok_date:
до 21:00 МСК = today, после 21:00 МСК = today+1. is_active / delivery_days_mask /
daily_limit / regions / signal_type / signal_identifier берутся из snapshot.
Из live projects — только delivered_today (счётчик остатка лимита). Из tenants —
balance_rub (live auto-pause при нулевом балансе).
Active snapshot date вычисляется в PHP (метод activeSnapshotDate()) и
передаётся в SQL как параметр — тестируемо через Carbon::setTestNow,
исключает дрейф между PHP- и DB-часами.
Fail-loud: Log::error('lead_router.no_snapshot_for_active_date', ...) если
по активной дате слепка вообще нет ни одной строки snapshot'а (cron не отработал).
Closes R-01, R-04, R-06, R-07, R-08, R-15.
Partial: R-02 (через шеринг), R-09 (race), R-10 (editable identifier) — закрываются Task 2.6+.
Plan: docs/superpowers/plans/2026-05-26-slepok-routing-protection.md §Task 2.5
Spec: docs/superpowers/specs/2026-05-26-slepok-routing-protection-design.md §4.2.3
Tests added:
- tests/Feature/LeadRouter/SnapshotRoutingTest.php (4 tests, all GREEN locally)
Tests patched (downstream — добавлен createRoutingSnapshotFromProject() helper):
- tests/Pest.php — global helper createRoutingSnapshotFromProject()
- tests/Feature/LeadRouter/BalanceFilterTest.php (2/2 GREEN)
- tests/Feature/Services/LeadRouterTest.php (10/10 GREEN)
- tests/Feature/Jobs/RouteSupplierLeadJobTest.php (14/14 GREEN)
- tests/Feature/Supplier/DirectPlatformTest.php (6/6 GREEN)
- tests/Feature/Supplier/RouteSupplierLeadJobBillingTest.php (3/3 GREEN)
- tests/Feature/Supplier/SupplierConnectionTest.php (5/5 GREEN)
- tests/Feature/Integration/SupplierLeadFlowTest.php (2/2 GREEN)
- tests/Feature/Pd/DealCreatePdLogTest.php (2/2 GREEN)
Each test file isolated regression: GREEN. Combined run 49/50 with 1 flake on
quirk #77 (Faker unique domainName + cross-connection pgsql/pgsql_supplier
DatabaseTransactions scope mismatch) — pre-existing, NOT regression от Task 2.5.
Patched via 7 parallel Sonnet subagents per Pravila §15.1; controller-verified
isolated + combined regression (latter caught 1 subagent over-application:
paused project in SupplierLeadFlowTest получил snapshot, что нарушило логику
теста — fixed inline, по semantic match with SnapshotBackfillCommand SQL
WHERE p.is_active = true).
130 lines
4.9 KiB
PHP
130 lines
4.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* 152-ФЗ: pd_processing_log 'created' записывается при создании сделки
|
|
* по двум живым путям — ручной API, поставщик (RouteSupplierLeadJob).
|
|
*/
|
|
|
|
use App\Jobs\RouteSupplierLeadJob;
|
|
use App\Models\Deal;
|
|
use App\Models\Project;
|
|
use App\Models\SupplierLead;
|
|
use App\Models\SupplierProject;
|
|
use App\Models\Tenant;
|
|
use App\Models\User;
|
|
use App\Services\Billing\LedgerService;
|
|
use App\Services\LeadDistributor;
|
|
use App\Services\LeadRouter;
|
|
use App\Services\NotificationService;
|
|
use App\Services\RegionTagResolver;
|
|
use App\Services\SupplierProjects\SupplierProjectResolver;
|
|
use Database\Seeders\PricingTierSeeder;
|
|
use Illuminate\Foundation\Testing\DatabaseTransactions;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Tests\Concerns\SharesSupplierPdo;
|
|
|
|
uses(DatabaseTransactions::class);
|
|
uses(SharesSupplierPdo::class);
|
|
|
|
beforeEach(function (): void {
|
|
$this->seed(PricingTierSeeder::class);
|
|
DB::statement("SELECT set_config('app.current_tenant_id', '0', true)");
|
|
});
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Path A: manual deal creation via DealController::store()
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
it('writes pd_processing_log created (manual) when deal created via API', function () {
|
|
$tenant = Tenant::factory()->create(['balance_leads' => 100]);
|
|
$user = User::factory()->for($tenant)->create();
|
|
$this->actingAs($user);
|
|
|
|
$before = DB::table('pd_processing_log')->where('purpose', 'lead_create_manual')->count();
|
|
|
|
$r = $this->postJson('/api/deals', [
|
|
'project_name' => 'Тест ПД',
|
|
'phone' => '+7 (999) 111-22-33',
|
|
]);
|
|
$r->assertStatus(201);
|
|
|
|
$dealId = $r->json('deal.id');
|
|
|
|
$rows = DB::table('pd_processing_log')
|
|
->where('action', 'created')
|
|
->where('purpose', 'lead_create_manual')
|
|
->where('subject_type', 'lead')
|
|
->where('subject_id', $dealId)
|
|
->where('tenant_id', $tenant->id)
|
|
->where('actor_tenant_user_id', $user->id)
|
|
->whereNull('actor_admin_user_id')
|
|
->count();
|
|
|
|
expect($rows)->toBe(1);
|
|
});
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Path B: supplier integration via RouteSupplierLeadJob
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
it('writes pd_processing_log created (supplier) when deal created via RouteSupplierLeadJob', function () {
|
|
$supplier = SupplierProject::factory()->create([
|
|
'platform' => 'B1',
|
|
'signal_type' => 'site',
|
|
'unique_key' => 'pd-test.ru',
|
|
]);
|
|
$tenant = Tenant::factory()->create(['balance_rub' => '100000.00']);
|
|
$project = Project::factory()->create([
|
|
'tenant_id' => $tenant->id,
|
|
'supplier_b1_project_id' => $supplier->id,
|
|
'signal_type' => 'site',
|
|
'signal_identifier' => 'pd-test.ru',
|
|
'is_active' => true,
|
|
'delivered_today' => 0,
|
|
'delivered_in_month' => 0,
|
|
]);
|
|
linkProjectToSupplier($project, $supplier);
|
|
createRoutingSnapshotFromProject($project, null, 'site', 'pd-test.ru');
|
|
|
|
$vid = 77741;
|
|
$lead = SupplierLead::factory()->create([
|
|
'supplier_project_id' => null,
|
|
'platform' => 'B1',
|
|
'vid' => $vid,
|
|
'phone' => '79992223344',
|
|
'raw_payload' => [
|
|
'vid' => $vid,
|
|
'project' => 'B1_pd-test.ru',
|
|
'phone' => '79992223344',
|
|
'time' => now()->getTimestamp(),
|
|
],
|
|
]);
|
|
|
|
(new RouteSupplierLeadJob($lead->id))->handle(
|
|
app(LeadRouter::class),
|
|
app(SupplierProjectResolver::class),
|
|
app(NotificationService::class),
|
|
app(LedgerService::class),
|
|
app(LeadDistributor::class),
|
|
app(RegionTagResolver::class),
|
|
);
|
|
|
|
DB::statement("SET LOCAL app.current_tenant_id = '{$tenant->id}'");
|
|
$deal = Deal::query()->where('tenant_id', $tenant->id)->where('source_crm_id', $vid)->first();
|
|
expect($deal)->not->toBeNull();
|
|
|
|
$rows = DB::table('pd_processing_log')
|
|
->where('action', 'created')
|
|
->where('purpose', 'lead_create_supplier')
|
|
->where('subject_type', 'lead')
|
|
->where('subject_id', $deal->id)
|
|
->where('tenant_id', $tenant->id)
|
|
->whereNull('actor_tenant_user_id')
|
|
->whereNull('actor_admin_user_id')
|
|
->count();
|
|
|
|
expect($rows)->toBe(1);
|
|
});
|