Commit Graph

388 Commits

Author SHA1 Message Date
Дмитрий 08d51eb6c8 feat: G1/SP2 реквизиты клиента + ИНН по DaData + гейт первого проекта
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 22:25:23 +03:00
Дмитрий 53fb7b7760 feat: G1/SP1 самозапись клиента с подтверждением почты 6-значным кодом
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 19:33:33 +03:00
Дмитрий f943871406 feat: G2-A дайджест новых сделок на почту - письмо-сводка раз в 30 минут вместо письма на каждую сделку
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 14:40:12 +03:00
Дмитрий a4a8ea31b9 refactor(security): единый источник security-заголовков — nginx
Убраны дубли HTTP-заголовков. nginx уже шлёт enforcing CSP, X-Frame-Options,
X-Content-Type-Options, Referrer-Policy, HSTS, Permissions-Policy, COOP, CORP
через add_header always. App-уровневый middleware SecurityHeaders дублировал
четыре из них и слал лишний CSP Report-Only; на проде add_header always плюс
PHP-заголовок давали дубль в ответе.

- удалён middleware SecurityHeaders и его регистрация в bootstrap/app.php
- SecurityHeadersTest переписан: фиксирует, что приложение эти заголовки не ставит

Прод-дедуп вступит в силу после деплоя. Verify локально 4 из 4 green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 09:31:47 +03:00
Дмитрий 23f81bdaf3 test: починка харнеса AdminBilling и AdminIncidents
AdminBillingIndexTest: teardown глушит session-триггеры на время очистки.
DELETE tenants каскадил в append-only tenant_operations_log, триггер
audit_block_mutation давал RAISE EXCEPTION. Плюс ensureRange гарантирует
месячные партиции balance_transactions за прошлые 2 месяца под SharesSupplierPdo.

AdminIncidentsIndexTest: добавлен трейт SharesSupplierPdo. Контроллер читает
через pgsql_supplier, тест писал через дефолтный pgsql под DatabaseTransactions,
cross-connection невидимость давала total=0.

Verify: оба класса 20 из 20 green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 09:05:06 +03:00
Дмитрий 8ad9e1d17f fix(test): routing-snapshot today+tomorrow в CsvWebhookRaceTest + PII на slack/papertrail/stderr
C: LeadRouter.activeSnapshotDate после 21:00 МСК = завтра; снимок только на сегодня не активен -> снимки на обе даты. A: PII-процессор на остальные лог-каналы, 6/6.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 21:37:41 +03:00
Дмитрий 7f5288726a feat(security): PII-scrubbing процессор логов — Medium go-live
Monolog PiiScrubbingProcessor (телефоны/email -> [PHONE]/[EMAIL]) + ScrubPii tap на single/daily в config/logging.php. Pest 6/6 GREEN. Sentry-scrubbing (OPEN-И-16) не реализуем: sentry-laravel не установлен — open-item.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 20:43:28 +03:00
Дмитрий b81a372e8f feat(security): webhook DNS-rebind пиннинг + аддитивный HMAC supplier-webhook — edge/P2 go-live
WebhookUrlGuard::safeDeliveryIp один резолв + CURLOPT_RESOLVE пиннинг в test(); supplier-webhook принимает HMAC X-Webhook-Signature как альтернативу URL-секрету + secretless-маршрут. Аддитивно, backward-compat. 6 новых тестов GREEN; 5 падений webhook-сюиты pre-existing (Phase-3 B-regex + CsvWebhookRaceTest), подтверждено baseline без моих файлов.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 20:21:11 +03:00
Дмитрий 518d71e81f feat(security): per-IP route-throttle на auth-эндпоинтах — P1 go-live
Именованные лимитеры auth-login/auth-2fa/auth-password (perMinute 20 by IP) в AppServiceProvider; throttle-middleware на login/forgot/reset/2fa-verify/recovery в web.php. Закрывает per-IP объёмный перебор. Pest tests/Feature/Auth 97/97 GREEN.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 19:56:23 +03:00
Дмитрий 380aedb04e feat(security): CSP Report-Only под Vue+Vuetify SPA — 2-я ZAP Medium go-live
Report-Only политика в middleware SecurityHeaders; Pest 6/6 GREEN.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 19:30:51 +03:00
Дмитрий d1976c9ccf feat(pdn): ретеншен ПДн удалённых лидов — анонимизация soft-deleted сделок — F-P1
152-ФЗ блокер B1/F-P1: телефоны и имена контактов soft-deleted сделок не
вычищались и хранились бессрочно. Добавлена плановая команда-ретеншен.

Команда pd:scrub-soft-deleted-deals анонимизирует phone/contact_name/phones
сделок с deleted_at старше N дней; N из system_settings
pd_scrub_soft_deleted_deals_days, по умолчанию no-op — юр.срок не зашит в код.
Значения затирания идентичны PdErasureService. Cross-tenant через
pgsql_supplier BYPASSRLS, идемпотентно, summary-запись в pd_processing_log
системным актором. Планировщик ежедневно 03:30 МСК с heartbeat.

Схема v8.41: partial index deals_deleted_at_index ON deals deleted_at WHERE
deleted_at IS NOT NULL для дешёвой выборки; счётчик индексов 120 на 121.

F-T2 проверен: /api/admin за middleware saas-admin fail-closed 503 — кодовой
правки не требует.

TDD: 4 Pest ScrubSoftDeletedDealsCommandTest GREEN. Escape-per-write — печать
церемонии не опечатывала план.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:24:48 +03:00
Дмитрий 84936929eb feat(security): middleware безопасных HTTP-заголовков — закрытие ZAP Medium anti-clickjacking
X-Frame-Options SAMEORIGIN + X-Content-Type-Options nosniff + Referrer-Policy на все web-ответы (go-live аудит 17.06). CSP вынесен отдельно (SPA Vue+Vuetify). TDD-тест на публичном /.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:12:32 +03:00
Дмитрий 1cb3b56f70 fix(dashboard): верхняя строка дашборда — настоящие числа вместо заглушки — F5
Accessibility (Pa11y live) / a11y (push) Has been cancelled
SAST — Semgrep / Semgrep SAST scan (push) Has been cancelled
Строка-приветствие показывала захардкоженную рыбу: +3 новых лида с утра,
сегодня 11 / вчера 38, средняя стоимость 2 248 руб. Числа ни к чему не были
привязаны — остаток прототипа Sprint 4.

Бэкенд: DashboardController.summary отдаёт avg_lead_cost_rub — среднее
фактически списанных rub-сумм за окно периода: AVG price_per_lead_kopecks
WHERE charge_source rub делить на 100; null если в окне нет rub-списаний.
Тот же источник, что карточка сделки F2.

Фронт: DashboardPageHead принимает пропы сегодня/вчера/средняя; сегодня и
вчера берутся из activity.points последняя точка сегодня; средняя из
avg_lead_cost_rub, прочерк при null. Размытое +3 с утра убрано.

TDD: 2 Pest DashboardSummaryTest 10/10 + 4 vitest DashboardPageHead;
полная фронт-сюита 959 passed / 3 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 16:02:04 +03:00
Дмитрий 2a6b476d6d fix(billing): единый источник runway — дашборд = биллинг (F3)
Дашборд считал «хватит на дни» от legacy balance_leads (≈0 для рублёвых тенантов)
и расходился с биллингом. Введён общий RunwayCalculator; оба контроллера считают
runway от affordable leads (рубли→лиды по тарифу, BalanceToLeadsConverter). Фронт
DashboardView больше не режет число дней до 7 сегментов полосы. TDD: 4 Pest нового
сервиса + обновлён DashboardSummary + 1 vitest.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 14:07:22 +03:00
Дмитрий 4d8a1af099 feat(deals): карточка показывает реальную стоимость лида — F2
Backend: GET /api/deals/{id} отдаёт cost_kopecks — снимок rub-списания из
lead_charges по deal_id, либо null для prepaid/не списано. Frontend: ApiDeal.cost_kopecks
→ MockDeal.costKopecks → карточка DealDetailBody показывает formatCost(costKopecks/100)
либо прочерк вместо вводящего в заблуждение 0 рублей. TDD: 3 Pest + 4 vitest.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 13:30:46 +03:00
Дмитрий 9fe5b5f229 imitation phase1 merge
# Conflicts:
#	app/app/Console/Commands/PhoneRangesImportCommand.php
#	app/app/Jobs/RouteSupplierLeadJob.php
#	app/app/Services/LeadRegionResolver.php
#	app/database/migrations/2026_05_31_100000_create_phone_ranges_and_resolution_log.php
#	app/tests/Feature/Console/PhoneRangesImportCommandTest.php
#	app/tests/Feature/Jobs/RouteSupplierLeadJobTest.php
#	app/tests/Feature/PartitionsCreateMonthsTest.php
#	cspell-words.txt
#	docs/observer/STATUS.md
#	tools/enforce-powershell-gate.test.mjs
#	tools/enforce-router-gate.mjs
#	tools/enforce-router-gate.test.mjs
#	tools/enforce-tdd-gate.test.mjs
#	tools/enforce-tdd-real-test-verifier.mjs
#	tools/enforce-tdd-real-test-verifier.test.mjs
#	tools/enforce-verify-record.test.mjs
#	tools/mcp-tool-classifier.test.mjs
#	tools/shell-content-rules.test.mjs
2026-06-17 08:03:35 +03:00
Дмитрий f94552d452 WIP чекпойнт: lead-region/supplier бэкенд + фронт-редизайн + Pint + тесты
92 файла одной пачкой. Исключены чужие зоны: CLAUDE.md, .claude/settings.json, docs/observer/.pii-counters.json.
gitleaks staged: no leaks found. Не верифицировано тестами - сохранение труда в историю.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 05:17:12 +03:00
Дмитрий 8e7a7803c1 fix: 152-FZ erasure - surgical scrub of deals.phones JSONB plus email no-op, F-P1b
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 11:54:45 +03:00
Дмитрий c4cb766d25 feat: merge lead-region cascade to main — deals-city + rossvyaz normalize, prod-parity verified
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 07:28:33 +03:00
Дмитрий c975e16a14 feat: merge lead-region cascade to main — deals-city + rossvyaz normalize, prod-parity verified
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 07:17:38 +03:00
Дмитрий 669e161017 feat(imitation): imitation:seed command to populate local portal
Self-contained app-namespace artisan command (NEVER on production) that funds local imitation clients on a shared B2 supplier, disables DaData (region from tag), rebuilds the routing snapshot, then injects synthetic leads through the real RouteSupplierLeadJob so deals/charges/notifications appear for hands-on UI review. The lead payload encodes the supplier unique_key as a domain so RouteSupplierLeadJob re-resolves the real supplier (parseProjectField then resolveOrStub). Test asserts exit 0 + new deals.
2026-06-04 05:09:29 +03:00
Дмитрий 61de9ae9a8 test(imitation): topologies + money + intake checks 2026-06-04 04:58:20 +03:00
Дмитрий 49ea46ab0e test(imitation): X1 step-3 substitution + X3 source breakdown 2026-06-04 04:45:37 +03:00
Дмитрий d5e966eebc test(imitation): scenarios G5/G6 special leads + dedup 2026-06-04 04:38:12 +03:00
Дмитрий a00c2da479 test(imitation): scenario G3 orphan lead 2026-06-04 04:29:35 +03:00
Дмитрий 5720458f7b test(imitation): scenarios E1/E2/F freezes + limit 2026-06-04 04:25:00 +03:00
Дмитрий 19a425e20f test(imitation): scenario D delivery days 2026-06-04 04:19:30 +03:00
Дмитрий 27bc60be47 test(imitation): scenarios B/C region cascade 2026-06-04 04:14:57 +03:00
Дмитрий f55c224d6a test(imitation): scenario A weighted lottery + distribution stats 2026-06-03 20:21:22 +03:00
Дмитрий 2969f3720f test(imitation): region resolution cascade coverage 2026-06-03 20:08:49 +03:00
Дмитрий 22f6178b2b fix(migrations): clean migrate:fresh resilience (partition parent guard + delta idempotency)
Restores a working migrate:fresh without the reverted blanket catch-all. (1) MonthlyPartitionManager::ensureMonth skips a partitioned table whose parent does not exist yet (targeted pg_class relkind='p' guard) instead of crashing — the initial schema-load runs partitions:create-months before later delta-migrations create their own partitioned tables. (2) migration 0001 runs with $withinTransaction=false so the schema.sql DDL is committed before partitions:create-months opens its second pgsql_supplier connection. (3) re-applies the clean idempotency guards on add_balance_freeze (DROP POLICY IF EXISTS) and add_paused_at (column/index existence checks) since schema.sql already contains those objects. migrate:fresh now rebuilds liderra_testing cleanly; MonthlyPartitionManagerTest 15/15 incl. new resilience guard test.
2026-06-03 20:01:55 +03:00
Дмитрий 544e9e589c feat(imitation): test clients + single-project matrix seeder 2026-06-03 19:37:49 +03:00
Дмитрий 40629276d9 feat(imitation): snapshot forge + condition levers 2026-06-03 19:09:12 +03:00
Дмитрий f8d89e81d1 revert(imitation): drop out-of-scope migration edits from 7c5ca7f6 + dead webhook_log test
Reverts 7c5ca7f6 production-migration edits (load_initial_schema withinTransaction=false + try/catch, idempotency guards) and coupled migrate:fresh guard tests to baseline; imitation suite uses DatabaseTransactions on a pre-migrated DB so the reverted migrate:fresh resilience is not needed for Phase 1. Also drops the orphaned ensureMonth webhook_log test (webhook_log removed from PARTITIONED_TABLES in 2026_05_24_140000_drop_legacy_webhook_artefacts).
2026-06-03 18:58:13 +03:00
Дмитрий 7c5ca7f688 chore(imitation): Task 0.5 — test env, reference-seed base, migrate:fresh resilience 2026-06-03 16:49:23 +03:00
Дмитрий e03da647c0 docs(imitation): plan — execution status + corrections (namespace, subject codes, Task 0.5 env provision) 2026-06-03 16:25:52 +03:00
Дмитрий a54b0346e9 feat(imitation): deterministic fake DaData phone client 2026-06-03 15:35:46 +03:00
Дмитрий e213f9b01c feat(deals): backfill command for «Город» on existing deals
deals:backfill-region-city fills deals.city from the lead resolved_subject_code (deals -> supplier_lead_deliveries -> supplier_leads) for deals where city is still empty, idempotently and across all tenants (BYPASSRLS). --dry-run reports the count without writing. Whitelisted in artisan-run.yml (dry-run read-only; real run requires confirm_apply). TDD: +4 tests GREEN.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 13:38:10 +03:00
Дмитрий 1609faee8c feat(deals): fill «Город» (deals.city) with resolved region name
The UI «Город» column binds to deals.city but nothing ever populated it — the region was only stored as a numeric code on supplier_leads + the resolution log. RouteSupplierLeadJob now writes the resolved subject name (RussianRegions::CODE_TO_NAME) into deals.city on deal creation (the lead's real region, even if subject_code is substituted on routing step 3), and updates it in the CSV-merge branch when the webhook resolution outranks the tag. New deals now display the region. TDD: +2 tests in RouteSupplierLeadJobTest; 24 job tests GREEN.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 13:16:31 +03:00
Дмитрий 893a142812 feat(region): phone-region:smoke staging command 2026-06-01 07:21:15 +03:00
Дмитрий dae2085ea0 feat(region): RouteSupplierLeadJob — resolve region + persist + fail-safe log + step-3 substitution + CSV-merge 2026-06-01 07:21:08 +03:00
Дмитрий 8be1db34b8 feat(region): LeadRouter cascade routing (exact→all-RF→fallback) + weighted pick variant В + routing_step 2026-06-01 07:19:54 +03:00
Дмитрий 4bb94257cf feat(region): LeadRegionResolver orchestrator (full qc cascade) 2026-06-01 07:19:37 +03:00
Дмитрий b91b6d5008 feat(region): DaData layer (region map, config, enum, client, budget guard) 2026-06-01 07:19:29 +03:00
Дмитрий b822042a66 feat(region): phone-ranges:import command (parse/map/dry-run/idempotency) 2026-06-01 07:18:23 +03:00
Дмитрий b25aa025e4 feat(region): RossvyazPrefixLookup + RossvyazRecord DTO 2026-06-01 07:18:17 +03:00
Дмитрий ec21971888 feat(region): schema migration + MonthlyPartitionManager registration 2026-06-01 07:12:08 +03:00
Дмитрий 720697ae43 style(audit): pint auto-fix на shared config + rebuild rewrite
Task 6 Step 4 плана 2026-05-29-audit-rebuild-per-tenant-fix.md.
Pint auto-fix purely cosmetic (unary_operator_spaces, phpdoc_align,
ordered_imports, fully_qualified_strict_types, no_blank_lines_after_phpdoc).
Никаких semantic-изменений.

Larastan analyse --level=max на 3 файла: 0 errors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:41 +03:00
Дмитрий 307a65e786 test(audit): drop pre-rebuild sanity-check в multi-tenant test
Test env (`SharesSupplierPdo` trait + postgres superuser) обходит RLS, поэтому
trigger `audit_chain_hash()` в тестах пишет global chain, не per-tenant. Это
расхождение с prod (где RLS активен и trigger пишет per-tenant) валидно — но
делает pre-rebuild sanity-check невыполнимым assumption'ом.

Multi-tenant test теперь проверяет только self-consistency post-rebuild:
rebuild должен produce chain matching своему partition_clause.

Pre-Task-4 (global LAG): post-rebuild verify с PARTITION BY tenant_id → mismatch
→ RED (текущее состояние).

Post-Task-4 (per-tenant LAG): post-rebuild verify с PARTITION BY tenant_id →
match → GREEN.

Prod RLS-aware trigger semantics валидируется live `audit:verify-chains`, не в
этом тесте.

Ref: docs/superpowers/plans/2026-05-29-audit-rebuild-per-tenant-fix.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:39 +03:00
Дмитрий 88cdd34e98 test(audit): failing tests для per-tenant rebuild (ADR-018, RED phase)
Task 3 плана 2026-05-29-audit-rebuild-per-tenant-fix.md.
3 новых сценария в AuditRebuildChainTest.php:

1. multi-tenant — 2 tenants, 4 rows interleaved, rebuild from firstId →
   chain должна остаться intact per-tenant. RED: fails на pre-rebuild
   sanity-check (preMismatches=1) — в test env trigger пишет НЕ per-tenant
   chain (SharesSupplierPdo trait → BYPASSRLS). Task 4 имплементер должен
   разобрать: либо trigger в test env починить (RLS-aware), либо тест
   адаптировать к фактической семантике pgsql_supplier.

2. BYPASSRLS auth_log — INSERT direct через pgsql_supplier, partition_clause=''
   (global chain within partition). Сейчас PASS случайно (single global LAG
   совпадает с tенущим rebuild semantics).

3. single-row partition — 1 tenant, 1 row, rebuild → должна работать.
   Сейчас PASS случайно.

+ new const AUTH_LOG_ROW_EXPR mirror'ит AuditChainConfig::TABLES['auth_log'].

Регрессия narrow: 7 tests / 6 passed / 1 failed (RED expected).

Ref: docs/adr/ADR-018-audit-chain-per-tenant-semantics.md
     docs/superpowers/plans/2026-05-29-audit-rebuild-per-tenant-fix.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:39 +03:00